radv: add the custom border color BO to the list of buffers
[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 (queue->device->border_color_data.bo)
3595 radv_cs_add_buffer(queue->device->ws, cs,
3596 queue->device->border_color_data.bo);
3597
3598 if (i == 0) {
3599 si_cs_emit_cache_flush(cs,
3600 queue->device->physical_device->rad_info.chip_class,
3601 NULL, 0,
3602 queue->queue_family_index == RING_COMPUTE &&
3603 queue->device->physical_device->rad_info.chip_class >= GFX7,
3604 (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)) |
3605 RADV_CMD_FLAG_INV_ICACHE |
3606 RADV_CMD_FLAG_INV_SCACHE |
3607 RADV_CMD_FLAG_INV_VCACHE |
3608 RADV_CMD_FLAG_INV_L2 |
3609 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3610 } else if (i == 1) {
3611 si_cs_emit_cache_flush(cs,
3612 queue->device->physical_device->rad_info.chip_class,
3613 NULL, 0,
3614 queue->queue_family_index == RING_COMPUTE &&
3615 queue->device->physical_device->rad_info.chip_class >= GFX7,
3616 RADV_CMD_FLAG_INV_ICACHE |
3617 RADV_CMD_FLAG_INV_SCACHE |
3618 RADV_CMD_FLAG_INV_VCACHE |
3619 RADV_CMD_FLAG_INV_L2 |
3620 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3621 }
3622
3623 if (queue->device->ws->cs_finalize(cs) != VK_SUCCESS)
3624 goto fail;
3625 }
3626
3627 if (queue->initial_full_flush_preamble_cs)
3628 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
3629
3630 if (queue->initial_preamble_cs)
3631 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
3632
3633 if (queue->continue_preamble_cs)
3634 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
3635
3636 queue->initial_full_flush_preamble_cs = dest_cs[0];
3637 queue->initial_preamble_cs = dest_cs[1];
3638 queue->continue_preamble_cs = dest_cs[2];
3639
3640 if (scratch_bo != queue->scratch_bo) {
3641 if (queue->scratch_bo)
3642 queue->device->ws->buffer_destroy(queue->scratch_bo);
3643 queue->scratch_bo = scratch_bo;
3644 }
3645 queue->scratch_size_per_wave = scratch_size_per_wave;
3646 queue->scratch_waves = scratch_waves;
3647
3648 if (compute_scratch_bo != queue->compute_scratch_bo) {
3649 if (queue->compute_scratch_bo)
3650 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
3651 queue->compute_scratch_bo = compute_scratch_bo;
3652 }
3653 queue->compute_scratch_size_per_wave = compute_scratch_size_per_wave;
3654 queue->compute_scratch_waves = compute_scratch_waves;
3655
3656 if (esgs_ring_bo != queue->esgs_ring_bo) {
3657 if (queue->esgs_ring_bo)
3658 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
3659 queue->esgs_ring_bo = esgs_ring_bo;
3660 queue->esgs_ring_size = esgs_ring_size;
3661 }
3662
3663 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
3664 if (queue->gsvs_ring_bo)
3665 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
3666 queue->gsvs_ring_bo = gsvs_ring_bo;
3667 queue->gsvs_ring_size = gsvs_ring_size;
3668 }
3669
3670 if (tess_rings_bo != queue->tess_rings_bo) {
3671 queue->tess_rings_bo = tess_rings_bo;
3672 queue->has_tess_rings = true;
3673 }
3674
3675 if (gds_bo != queue->gds_bo) {
3676 queue->gds_bo = gds_bo;
3677 queue->has_gds = true;
3678 }
3679
3680 if (gds_oa_bo != queue->gds_oa_bo) {
3681 queue->gds_oa_bo = gds_oa_bo;
3682 queue->has_gds_oa = true;
3683 }
3684
3685 if (descriptor_bo != queue->descriptor_bo) {
3686 if (queue->descriptor_bo)
3687 queue->device->ws->buffer_destroy(queue->descriptor_bo);
3688
3689 queue->descriptor_bo = descriptor_bo;
3690 }
3691
3692 if (add_sample_positions)
3693 queue->has_sample_positions = true;
3694
3695 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3696 *initial_preamble_cs = queue->initial_preamble_cs;
3697 *continue_preamble_cs = queue->continue_preamble_cs;
3698 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
3699 *continue_preamble_cs = NULL;
3700 return VK_SUCCESS;
3701 fail:
3702 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
3703 if (dest_cs[i])
3704 queue->device->ws->cs_destroy(dest_cs[i]);
3705 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
3706 queue->device->ws->buffer_destroy(descriptor_bo);
3707 if (scratch_bo && scratch_bo != queue->scratch_bo)
3708 queue->device->ws->buffer_destroy(scratch_bo);
3709 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
3710 queue->device->ws->buffer_destroy(compute_scratch_bo);
3711 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
3712 queue->device->ws->buffer_destroy(esgs_ring_bo);
3713 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
3714 queue->device->ws->buffer_destroy(gsvs_ring_bo);
3715 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
3716 queue->device->ws->buffer_destroy(tess_rings_bo);
3717 if (gds_bo && gds_bo != queue->gds_bo)
3718 queue->device->ws->buffer_destroy(gds_bo);
3719 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
3720 queue->device->ws->buffer_destroy(gds_oa_bo);
3721
3722 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3723 }
3724
3725 static VkResult radv_alloc_sem_counts(struct radv_device *device,
3726 struct radv_winsys_sem_counts *counts,
3727 int num_sems,
3728 struct radv_semaphore_part **sems,
3729 const uint64_t *timeline_values,
3730 VkFence _fence,
3731 bool is_signal)
3732 {
3733 int syncobj_idx = 0, sem_idx = 0;
3734
3735 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
3736 return VK_SUCCESS;
3737
3738 for (uint32_t i = 0; i < num_sems; i++) {
3739 switch(sems[i]->kind) {
3740 case RADV_SEMAPHORE_SYNCOBJ:
3741 counts->syncobj_count++;
3742 break;
3743 case RADV_SEMAPHORE_WINSYS:
3744 counts->sem_count++;
3745 break;
3746 case RADV_SEMAPHORE_NONE:
3747 break;
3748 case RADV_SEMAPHORE_TIMELINE:
3749 counts->syncobj_count++;
3750 break;
3751 }
3752 }
3753
3754 if (_fence != VK_NULL_HANDLE) {
3755 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3756 if (fence->temp_syncobj || fence->syncobj)
3757 counts->syncobj_count++;
3758 }
3759
3760 if (counts->syncobj_count) {
3761 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
3762 if (!counts->syncobj)
3763 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3764 }
3765
3766 if (counts->sem_count) {
3767 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
3768 if (!counts->sem) {
3769 free(counts->syncobj);
3770 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3771 }
3772 }
3773
3774 for (uint32_t i = 0; i < num_sems; i++) {
3775 switch(sems[i]->kind) {
3776 case RADV_SEMAPHORE_NONE:
3777 unreachable("Empty semaphore");
3778 break;
3779 case RADV_SEMAPHORE_SYNCOBJ:
3780 counts->syncobj[syncobj_idx++] = sems[i]->syncobj;
3781 break;
3782 case RADV_SEMAPHORE_WINSYS:
3783 counts->sem[sem_idx++] = sems[i]->ws_sem;
3784 break;
3785 case RADV_SEMAPHORE_TIMELINE: {
3786 pthread_mutex_lock(&sems[i]->timeline.mutex);
3787 struct radv_timeline_point *point = NULL;
3788 if (is_signal) {
3789 point = radv_timeline_add_point_locked(device, &sems[i]->timeline, timeline_values[i]);
3790 } else {
3791 point = radv_timeline_find_point_at_least_locked(device, &sems[i]->timeline, timeline_values[i]);
3792 }
3793
3794 pthread_mutex_unlock(&sems[i]->timeline.mutex);
3795
3796 if (point) {
3797 counts->syncobj[syncobj_idx++] = point->syncobj;
3798 } else {
3799 /* Explicitly remove the semaphore so we might not find
3800 * a point later post-submit. */
3801 sems[i] = NULL;
3802 }
3803 break;
3804 }
3805 }
3806 }
3807
3808 if (_fence != VK_NULL_HANDLE) {
3809 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3810 if (fence->temp_syncobj)
3811 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
3812 else if (fence->syncobj)
3813 counts->syncobj[syncobj_idx++] = fence->syncobj;
3814 }
3815
3816 assert(syncobj_idx <= counts->syncobj_count);
3817 counts->syncobj_count = syncobj_idx;
3818
3819 return VK_SUCCESS;
3820 }
3821
3822 static void
3823 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
3824 {
3825 free(sem_info->wait.syncobj);
3826 free(sem_info->wait.sem);
3827 free(sem_info->signal.syncobj);
3828 free(sem_info->signal.sem);
3829 }
3830
3831
3832 static void radv_free_temp_syncobjs(struct radv_device *device,
3833 int num_sems,
3834 struct radv_semaphore_part *sems)
3835 {
3836 for (uint32_t i = 0; i < num_sems; i++) {
3837 radv_destroy_semaphore_part(device, sems + i);
3838 }
3839 }
3840
3841 static VkResult
3842 radv_alloc_sem_info(struct radv_device *device,
3843 struct radv_winsys_sem_info *sem_info,
3844 int num_wait_sems,
3845 struct radv_semaphore_part **wait_sems,
3846 const uint64_t *wait_values,
3847 int num_signal_sems,
3848 struct radv_semaphore_part **signal_sems,
3849 const uint64_t *signal_values,
3850 VkFence fence)
3851 {
3852 VkResult ret;
3853 memset(sem_info, 0, sizeof(*sem_info));
3854
3855 ret = radv_alloc_sem_counts(device, &sem_info->wait, num_wait_sems, wait_sems, wait_values, VK_NULL_HANDLE, false);
3856 if (ret)
3857 return ret;
3858 ret = radv_alloc_sem_counts(device, &sem_info->signal, num_signal_sems, signal_sems, signal_values, fence, true);
3859 if (ret)
3860 radv_free_sem_info(sem_info);
3861
3862 /* caller can override these */
3863 sem_info->cs_emit_wait = true;
3864 sem_info->cs_emit_signal = true;
3865 return ret;
3866 }
3867
3868 static void
3869 radv_finalize_timelines(struct radv_device *device,
3870 uint32_t num_wait_sems,
3871 struct radv_semaphore_part **wait_sems,
3872 const uint64_t *wait_values,
3873 uint32_t num_signal_sems,
3874 struct radv_semaphore_part **signal_sems,
3875 const uint64_t *signal_values,
3876 struct list_head *processing_list)
3877 {
3878 for (uint32_t i = 0; i < num_wait_sems; ++i) {
3879 if (wait_sems[i] && wait_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
3880 pthread_mutex_lock(&wait_sems[i]->timeline.mutex);
3881 struct radv_timeline_point *point =
3882 radv_timeline_find_point_at_least_locked(device, &wait_sems[i]->timeline, wait_values[i]);
3883 point->wait_count -= 2;
3884 pthread_mutex_unlock(&wait_sems[i]->timeline.mutex);
3885 }
3886 }
3887 for (uint32_t i = 0; i < num_signal_sems; ++i) {
3888 if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
3889 pthread_mutex_lock(&signal_sems[i]->timeline.mutex);
3890 struct radv_timeline_point *point =
3891 radv_timeline_find_point_at_least_locked(device, &signal_sems[i]->timeline, signal_values[i]);
3892 signal_sems[i]->timeline.highest_submitted =
3893 MAX2(signal_sems[i]->timeline.highest_submitted, point->value);
3894 point->wait_count -= 2;
3895 radv_timeline_trigger_waiters_locked(&signal_sems[i]->timeline, processing_list);
3896 pthread_mutex_unlock(&signal_sems[i]->timeline.mutex);
3897 }
3898 }
3899 }
3900
3901 static void
3902 radv_sparse_buffer_bind_memory(struct radv_device *device,
3903 const VkSparseBufferMemoryBindInfo *bind)
3904 {
3905 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
3906
3907 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3908 struct radv_device_memory *mem = NULL;
3909
3910 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3911 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3912
3913 device->ws->buffer_virtual_bind(buffer->bo,
3914 bind->pBinds[i].resourceOffset,
3915 bind->pBinds[i].size,
3916 mem ? mem->bo : NULL,
3917 bind->pBinds[i].memoryOffset);
3918 }
3919 }
3920
3921 static void
3922 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
3923 const VkSparseImageOpaqueMemoryBindInfo *bind)
3924 {
3925 RADV_FROM_HANDLE(radv_image, image, bind->image);
3926
3927 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3928 struct radv_device_memory *mem = NULL;
3929
3930 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3931 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3932
3933 device->ws->buffer_virtual_bind(image->bo,
3934 bind->pBinds[i].resourceOffset,
3935 bind->pBinds[i].size,
3936 mem ? mem->bo : NULL,
3937 bind->pBinds[i].memoryOffset);
3938 }
3939 }
3940
3941 static VkResult
3942 radv_get_preambles(struct radv_queue *queue,
3943 const VkCommandBuffer *cmd_buffers,
3944 uint32_t cmd_buffer_count,
3945 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
3946 struct radeon_cmdbuf **initial_preamble_cs,
3947 struct radeon_cmdbuf **continue_preamble_cs)
3948 {
3949 uint32_t scratch_size_per_wave = 0, waves_wanted = 0;
3950 uint32_t compute_scratch_size_per_wave = 0, compute_waves_wanted = 0;
3951 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
3952 bool tess_rings_needed = false;
3953 bool gds_needed = false;
3954 bool gds_oa_needed = false;
3955 bool sample_positions_needed = false;
3956
3957 for (uint32_t j = 0; j < cmd_buffer_count; j++) {
3958 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
3959 cmd_buffers[j]);
3960
3961 scratch_size_per_wave = MAX2(scratch_size_per_wave, cmd_buffer->scratch_size_per_wave_needed);
3962 waves_wanted = MAX2(waves_wanted, cmd_buffer->scratch_waves_wanted);
3963 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave,
3964 cmd_buffer->compute_scratch_size_per_wave_needed);
3965 compute_waves_wanted = MAX2(compute_waves_wanted,
3966 cmd_buffer->compute_scratch_waves_wanted);
3967 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
3968 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
3969 tess_rings_needed |= cmd_buffer->tess_rings_needed;
3970 gds_needed |= cmd_buffer->gds_needed;
3971 gds_oa_needed |= cmd_buffer->gds_oa_needed;
3972 sample_positions_needed |= cmd_buffer->sample_positions_needed;
3973 }
3974
3975 return radv_get_preamble_cs(queue, scratch_size_per_wave, waves_wanted,
3976 compute_scratch_size_per_wave, compute_waves_wanted,
3977 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
3978 gds_needed, gds_oa_needed, sample_positions_needed,
3979 initial_full_flush_preamble_cs,
3980 initial_preamble_cs, continue_preamble_cs);
3981 }
3982
3983 struct radv_deferred_queue_submission {
3984 struct radv_queue *queue;
3985 VkCommandBuffer *cmd_buffers;
3986 uint32_t cmd_buffer_count;
3987
3988 /* Sparse bindings that happen on a queue. */
3989 VkSparseBufferMemoryBindInfo *buffer_binds;
3990 uint32_t buffer_bind_count;
3991 VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
3992 uint32_t image_opaque_bind_count;
3993
3994 bool flush_caches;
3995 VkShaderStageFlags wait_dst_stage_mask;
3996 struct radv_semaphore_part **wait_semaphores;
3997 uint32_t wait_semaphore_count;
3998 struct radv_semaphore_part **signal_semaphores;
3999 uint32_t signal_semaphore_count;
4000 VkFence fence;
4001
4002 uint64_t *wait_values;
4003 uint64_t *signal_values;
4004
4005 struct radv_semaphore_part *temporary_semaphore_parts;
4006 uint32_t temporary_semaphore_part_count;
4007
4008 struct list_head queue_pending_list;
4009 uint32_t submission_wait_count;
4010 struct radv_timeline_waiter *wait_nodes;
4011
4012 struct list_head processing_list;
4013 };
4014
4015 struct radv_queue_submission {
4016 const VkCommandBuffer *cmd_buffers;
4017 uint32_t cmd_buffer_count;
4018
4019 /* Sparse bindings that happen on a queue. */
4020 const VkSparseBufferMemoryBindInfo *buffer_binds;
4021 uint32_t buffer_bind_count;
4022 const VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4023 uint32_t image_opaque_bind_count;
4024
4025 bool flush_caches;
4026 VkPipelineStageFlags wait_dst_stage_mask;
4027 const VkSemaphore *wait_semaphores;
4028 uint32_t wait_semaphore_count;
4029 const VkSemaphore *signal_semaphores;
4030 uint32_t signal_semaphore_count;
4031 VkFence fence;
4032
4033 const uint64_t *wait_values;
4034 uint32_t wait_value_count;
4035 const uint64_t *signal_values;
4036 uint32_t signal_value_count;
4037 };
4038
4039 static VkResult
4040 radv_create_deferred_submission(struct radv_queue *queue,
4041 const struct radv_queue_submission *submission,
4042 struct radv_deferred_queue_submission **out)
4043 {
4044 struct radv_deferred_queue_submission *deferred = NULL;
4045 size_t size = sizeof(struct radv_deferred_queue_submission);
4046
4047 uint32_t temporary_count = 0;
4048 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4049 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4050 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE)
4051 ++temporary_count;
4052 }
4053
4054 size += submission->cmd_buffer_count * sizeof(VkCommandBuffer);
4055 size += submission->buffer_bind_count * sizeof(VkSparseBufferMemoryBindInfo);
4056 size += submission->image_opaque_bind_count * sizeof(VkSparseImageOpaqueMemoryBindInfo);
4057 size += submission->wait_semaphore_count * sizeof(struct radv_semaphore_part *);
4058 size += temporary_count * sizeof(struct radv_semaphore_part);
4059 size += submission->signal_semaphore_count * sizeof(struct radv_semaphore_part *);
4060 size += submission->wait_value_count * sizeof(uint64_t);
4061 size += submission->signal_value_count * sizeof(uint64_t);
4062 size += submission->wait_semaphore_count * sizeof(struct radv_timeline_waiter);
4063
4064 deferred = calloc(1, size);
4065 if (!deferred)
4066 return VK_ERROR_OUT_OF_HOST_MEMORY;
4067
4068 deferred->queue = queue;
4069
4070 deferred->cmd_buffers = (void*)(deferred + 1);
4071 deferred->cmd_buffer_count = submission->cmd_buffer_count;
4072 memcpy(deferred->cmd_buffers, submission->cmd_buffers,
4073 submission->cmd_buffer_count * sizeof(*deferred->cmd_buffers));
4074
4075 deferred->buffer_binds = (void*)(deferred->cmd_buffers + submission->cmd_buffer_count);
4076 deferred->buffer_bind_count = submission->buffer_bind_count;
4077 memcpy(deferred->buffer_binds, submission->buffer_binds,
4078 submission->buffer_bind_count * sizeof(*deferred->buffer_binds));
4079
4080 deferred->image_opaque_binds = (void*)(deferred->buffer_binds + submission->buffer_bind_count);
4081 deferred->image_opaque_bind_count = submission->image_opaque_bind_count;
4082 memcpy(deferred->image_opaque_binds, submission->image_opaque_binds,
4083 submission->image_opaque_bind_count * sizeof(*deferred->image_opaque_binds));
4084
4085 deferred->flush_caches = submission->flush_caches;
4086 deferred->wait_dst_stage_mask = submission->wait_dst_stage_mask;
4087
4088 deferred->wait_semaphores = (void*)(deferred->image_opaque_binds + deferred->image_opaque_bind_count);
4089 deferred->wait_semaphore_count = submission->wait_semaphore_count;
4090
4091 deferred->signal_semaphores = (void*)(deferred->wait_semaphores + deferred->wait_semaphore_count);
4092 deferred->signal_semaphore_count = submission->signal_semaphore_count;
4093
4094 deferred->fence = submission->fence;
4095
4096 deferred->temporary_semaphore_parts = (void*)(deferred->signal_semaphores + deferred->signal_semaphore_count);
4097 deferred->temporary_semaphore_part_count = temporary_count;
4098
4099 uint32_t temporary_idx = 0;
4100 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4101 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4102 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4103 deferred->wait_semaphores[i] = &deferred->temporary_semaphore_parts[temporary_idx];
4104 deferred->temporary_semaphore_parts[temporary_idx] = semaphore->temporary;
4105 semaphore->temporary.kind = RADV_SEMAPHORE_NONE;
4106 ++temporary_idx;
4107 } else
4108 deferred->wait_semaphores[i] = &semaphore->permanent;
4109 }
4110
4111 for (uint32_t i = 0; i < submission->signal_semaphore_count; ++i) {
4112 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->signal_semaphores[i]);
4113 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4114 deferred->signal_semaphores[i] = &semaphore->temporary;
4115 } else {
4116 deferred->signal_semaphores[i] = &semaphore->permanent;
4117 }
4118 }
4119
4120 deferred->wait_values = (void*)(deferred->temporary_semaphore_parts + temporary_count);
4121 memcpy(deferred->wait_values, submission->wait_values, submission->wait_value_count * sizeof(uint64_t));
4122 deferred->signal_values = deferred->wait_values + submission->wait_value_count;
4123 memcpy(deferred->signal_values, submission->signal_values, submission->signal_value_count * sizeof(uint64_t));
4124
4125 deferred->wait_nodes = (void*)(deferred->signal_values + submission->signal_value_count);
4126 /* This is worst-case. radv_queue_enqueue_submission will fill in further, but this
4127 * ensure the submission is not accidentally triggered early when adding wait timelines. */
4128 deferred->submission_wait_count = 1 + submission->wait_semaphore_count;
4129
4130 *out = deferred;
4131 return VK_SUCCESS;
4132 }
4133
4134 static void
4135 radv_queue_enqueue_submission(struct radv_deferred_queue_submission *submission,
4136 struct list_head *processing_list)
4137 {
4138 uint32_t wait_cnt = 0;
4139 struct radv_timeline_waiter *waiter = submission->wait_nodes;
4140 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4141 if (submission->wait_semaphores[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4142 pthread_mutex_lock(&submission->wait_semaphores[i]->timeline.mutex);
4143 if (submission->wait_semaphores[i]->timeline.highest_submitted < submission->wait_values[i]) {
4144 ++wait_cnt;
4145 waiter->value = submission->wait_values[i];
4146 waiter->submission = submission;
4147 list_addtail(&waiter->list, &submission->wait_semaphores[i]->timeline.waiters);
4148 ++waiter;
4149 }
4150 pthread_mutex_unlock(&submission->wait_semaphores[i]->timeline.mutex);
4151 }
4152 }
4153
4154 pthread_mutex_lock(&submission->queue->pending_mutex);
4155
4156 bool is_first = list_is_empty(&submission->queue->pending_submissions);
4157 list_addtail(&submission->queue_pending_list, &submission->queue->pending_submissions);
4158
4159 pthread_mutex_unlock(&submission->queue->pending_mutex);
4160
4161 /* If there is already a submission in the queue, that will decrement the counter by 1 when
4162 * submitted, but if the queue was empty, we decrement ourselves as there is no previous
4163 * submission. */
4164 uint32_t decrement = submission->wait_semaphore_count - wait_cnt + (is_first ? 1 : 0);
4165 if (__atomic_sub_fetch(&submission->submission_wait_count, decrement, __ATOMIC_ACQ_REL) == 0) {
4166 list_addtail(&submission->processing_list, processing_list);
4167 }
4168 }
4169
4170 static void
4171 radv_queue_submission_update_queue(struct radv_deferred_queue_submission *submission,
4172 struct list_head *processing_list)
4173 {
4174 pthread_mutex_lock(&submission->queue->pending_mutex);
4175 list_del(&submission->queue_pending_list);
4176
4177 /* trigger the next submission in the queue. */
4178 if (!list_is_empty(&submission->queue->pending_submissions)) {
4179 struct radv_deferred_queue_submission *next_submission =
4180 list_first_entry(&submission->queue->pending_submissions,
4181 struct radv_deferred_queue_submission,
4182 queue_pending_list);
4183 if (p_atomic_dec_zero(&next_submission->submission_wait_count)) {
4184 list_addtail(&next_submission->processing_list, processing_list);
4185 }
4186 }
4187 pthread_mutex_unlock(&submission->queue->pending_mutex);
4188
4189 pthread_cond_broadcast(&submission->queue->device->timeline_cond);
4190 }
4191
4192 static VkResult
4193 radv_queue_submit_deferred(struct radv_deferred_queue_submission *submission,
4194 struct list_head *processing_list)
4195 {
4196 RADV_FROM_HANDLE(radv_fence, fence, submission->fence);
4197 struct radv_queue *queue = submission->queue;
4198 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4199 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
4200 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
4201 bool do_flush = submission->flush_caches || submission->wait_dst_stage_mask;
4202 bool can_patch = true;
4203 uint32_t advance;
4204 struct radv_winsys_sem_info sem_info;
4205 VkResult result;
4206 int ret;
4207 struct radeon_cmdbuf *initial_preamble_cs = NULL;
4208 struct radeon_cmdbuf *initial_flush_preamble_cs = NULL;
4209 struct radeon_cmdbuf *continue_preamble_cs = NULL;
4210
4211 result = radv_get_preambles(queue, submission->cmd_buffers,
4212 submission->cmd_buffer_count,
4213 &initial_preamble_cs,
4214 &initial_flush_preamble_cs,
4215 &continue_preamble_cs);
4216 if (result != VK_SUCCESS)
4217 goto fail;
4218
4219 result = radv_alloc_sem_info(queue->device,
4220 &sem_info,
4221 submission->wait_semaphore_count,
4222 submission->wait_semaphores,
4223 submission->wait_values,
4224 submission->signal_semaphore_count,
4225 submission->signal_semaphores,
4226 submission->signal_values,
4227 submission->fence);
4228 if (result != VK_SUCCESS)
4229 goto fail;
4230
4231 for (uint32_t i = 0; i < submission->buffer_bind_count; ++i) {
4232 radv_sparse_buffer_bind_memory(queue->device,
4233 submission->buffer_binds + i);
4234 }
4235
4236 for (uint32_t i = 0; i < submission->image_opaque_bind_count; ++i) {
4237 radv_sparse_image_opaque_bind_memory(queue->device,
4238 submission->image_opaque_binds + i);
4239 }
4240
4241 if (!submission->cmd_buffer_count) {
4242 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
4243 &queue->device->empty_cs[queue->queue_family_index],
4244 1, NULL, NULL,
4245 &sem_info, NULL,
4246 false, base_fence);
4247 if (ret) {
4248 radv_loge("failed to submit CS\n");
4249 abort();
4250 }
4251
4252 goto success;
4253 } else {
4254 struct radeon_cmdbuf **cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
4255 (submission->cmd_buffer_count));
4256
4257 for (uint32_t j = 0; j < submission->cmd_buffer_count; j++) {
4258 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, submission->cmd_buffers[j]);
4259 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4260
4261 cs_array[j] = cmd_buffer->cs;
4262 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
4263 can_patch = false;
4264
4265 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
4266 }
4267
4268 for (uint32_t j = 0; j < submission->cmd_buffer_count; j += advance) {
4269 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
4270 const struct radv_winsys_bo_list *bo_list = NULL;
4271
4272 advance = MIN2(max_cs_submission,
4273 submission->cmd_buffer_count - j);
4274
4275 if (queue->device->trace_bo)
4276 *queue->device->trace_id_ptr = 0;
4277
4278 sem_info.cs_emit_wait = j == 0;
4279 sem_info.cs_emit_signal = j + advance == submission->cmd_buffer_count;
4280
4281 if (unlikely(queue->device->use_global_bo_list)) {
4282 pthread_mutex_lock(&queue->device->bo_list.mutex);
4283 bo_list = &queue->device->bo_list.list;
4284 }
4285
4286 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
4287 advance, initial_preamble, continue_preamble_cs,
4288 &sem_info, bo_list,
4289 can_patch, base_fence);
4290
4291 if (unlikely(queue->device->use_global_bo_list))
4292 pthread_mutex_unlock(&queue->device->bo_list.mutex);
4293
4294 if (ret) {
4295 radv_loge("failed to submit CS\n");
4296 abort();
4297 }
4298 if (queue->device->trace_bo) {
4299 radv_check_gpu_hangs(queue, cs_array[j]);
4300 }
4301 }
4302
4303 free(cs_array);
4304 }
4305
4306 success:
4307 radv_free_temp_syncobjs(queue->device,
4308 submission->temporary_semaphore_part_count,
4309 submission->temporary_semaphore_parts);
4310 radv_finalize_timelines(queue->device,
4311 submission->wait_semaphore_count,
4312 submission->wait_semaphores,
4313 submission->wait_values,
4314 submission->signal_semaphore_count,
4315 submission->signal_semaphores,
4316 submission->signal_values,
4317 processing_list);
4318 /* Has to happen after timeline finalization to make sure the
4319 * condition variable is only triggered when timelines and queue have
4320 * been updated. */
4321 radv_queue_submission_update_queue(submission, processing_list);
4322 radv_free_sem_info(&sem_info);
4323 free(submission);
4324 return VK_SUCCESS;
4325
4326 fail:
4327 radv_free_temp_syncobjs(queue->device,
4328 submission->temporary_semaphore_part_count,
4329 submission->temporary_semaphore_parts);
4330 free(submission);
4331 return VK_ERROR_DEVICE_LOST;
4332 }
4333
4334 static VkResult
4335 radv_process_submissions(struct list_head *processing_list)
4336 {
4337 while(!list_is_empty(processing_list)) {
4338 struct radv_deferred_queue_submission *submission =
4339 list_first_entry(processing_list, struct radv_deferred_queue_submission, processing_list);
4340 list_del(&submission->processing_list);
4341
4342 VkResult result = radv_queue_submit_deferred(submission, processing_list);
4343 if (result != VK_SUCCESS)
4344 return result;
4345 }
4346 return VK_SUCCESS;
4347 }
4348
4349 static VkResult radv_queue_submit(struct radv_queue *queue,
4350 const struct radv_queue_submission *submission)
4351 {
4352 struct radv_deferred_queue_submission *deferred = NULL;
4353
4354 VkResult result = radv_create_deferred_submission(queue, submission, &deferred);
4355 if (result != VK_SUCCESS)
4356 return result;
4357
4358 struct list_head processing_list;
4359 list_inithead(&processing_list);
4360
4361 radv_queue_enqueue_submission(deferred, &processing_list);
4362 return radv_process_submissions(&processing_list);
4363 }
4364
4365 bool
4366 radv_queue_internal_submit(struct radv_queue *queue, struct radeon_cmdbuf *cs)
4367 {
4368 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4369 struct radv_winsys_sem_info sem_info;
4370 VkResult result;
4371 int ret;
4372
4373 result = radv_alloc_sem_info(queue->device, &sem_info, 0, NULL, 0, 0,
4374 0, NULL, VK_NULL_HANDLE);
4375 if (result != VK_SUCCESS)
4376 return false;
4377
4378 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, &cs, 1, NULL,
4379 NULL, &sem_info, NULL, false, NULL);
4380 radv_free_sem_info(&sem_info);
4381 return !ret;
4382 }
4383
4384 /* Signals fence as soon as all the work currently put on queue is done. */
4385 static VkResult radv_signal_fence(struct radv_queue *queue,
4386 VkFence fence)
4387 {
4388 return radv_queue_submit(queue, &(struct radv_queue_submission) {
4389 .fence = fence
4390 });
4391 }
4392
4393 static bool radv_submit_has_effects(const VkSubmitInfo *info)
4394 {
4395 return info->commandBufferCount ||
4396 info->waitSemaphoreCount ||
4397 info->signalSemaphoreCount;
4398 }
4399
4400 VkResult radv_QueueSubmit(
4401 VkQueue _queue,
4402 uint32_t submitCount,
4403 const VkSubmitInfo* pSubmits,
4404 VkFence fence)
4405 {
4406 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4407 VkResult result;
4408 uint32_t fence_idx = 0;
4409 bool flushed_caches = false;
4410
4411 if (fence != VK_NULL_HANDLE) {
4412 for (uint32_t i = 0; i < submitCount; ++i)
4413 if (radv_submit_has_effects(pSubmits + i))
4414 fence_idx = i;
4415 } else
4416 fence_idx = UINT32_MAX;
4417
4418 for (uint32_t i = 0; i < submitCount; i++) {
4419 if (!radv_submit_has_effects(pSubmits + i) && fence_idx != i)
4420 continue;
4421
4422 VkPipelineStageFlags wait_dst_stage_mask = 0;
4423 for (unsigned j = 0; j < pSubmits[i].waitSemaphoreCount; ++j) {
4424 wait_dst_stage_mask |= pSubmits[i].pWaitDstStageMask[j];
4425 }
4426
4427 const VkTimelineSemaphoreSubmitInfo *timeline_info =
4428 vk_find_struct_const(pSubmits[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
4429
4430 result = radv_queue_submit(queue, &(struct radv_queue_submission) {
4431 .cmd_buffers = pSubmits[i].pCommandBuffers,
4432 .cmd_buffer_count = pSubmits[i].commandBufferCount,
4433 .wait_dst_stage_mask = wait_dst_stage_mask,
4434 .flush_caches = !flushed_caches,
4435 .wait_semaphores = pSubmits[i].pWaitSemaphores,
4436 .wait_semaphore_count = pSubmits[i].waitSemaphoreCount,
4437 .signal_semaphores = pSubmits[i].pSignalSemaphores,
4438 .signal_semaphore_count = pSubmits[i].signalSemaphoreCount,
4439 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
4440 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
4441 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
4442 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
4443 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
4444 });
4445 if (result != VK_SUCCESS)
4446 return result;
4447
4448 flushed_caches = true;
4449 }
4450
4451 if (fence != VK_NULL_HANDLE && !submitCount) {
4452 result = radv_signal_fence(queue, fence);
4453 if (result != VK_SUCCESS)
4454 return result;
4455 }
4456
4457 return VK_SUCCESS;
4458 }
4459
4460 VkResult radv_QueueWaitIdle(
4461 VkQueue _queue)
4462 {
4463 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4464
4465 pthread_mutex_lock(&queue->pending_mutex);
4466 while (!list_is_empty(&queue->pending_submissions)) {
4467 pthread_cond_wait(&queue->device->timeline_cond, &queue->pending_mutex);
4468 }
4469 pthread_mutex_unlock(&queue->pending_mutex);
4470
4471 if (!queue->device->ws->ctx_wait_idle(queue->hw_ctx,
4472 radv_queue_family_to_ring(queue->queue_family_index),
4473 queue->queue_idx))
4474 return VK_ERROR_DEVICE_LOST;
4475
4476 return VK_SUCCESS;
4477 }
4478
4479 VkResult radv_DeviceWaitIdle(
4480 VkDevice _device)
4481 {
4482 RADV_FROM_HANDLE(radv_device, device, _device);
4483
4484 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
4485 for (unsigned q = 0; q < device->queue_count[i]; q++) {
4486 VkResult result =
4487 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
4488
4489 if (result != VK_SUCCESS)
4490 return result;
4491 }
4492 }
4493 return VK_SUCCESS;
4494 }
4495
4496 VkResult radv_EnumerateInstanceExtensionProperties(
4497 const char* pLayerName,
4498 uint32_t* pPropertyCount,
4499 VkExtensionProperties* pProperties)
4500 {
4501 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
4502
4503 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
4504 if (radv_instance_extensions_supported.extensions[i]) {
4505 vk_outarray_append(&out, prop) {
4506 *prop = radv_instance_extensions[i];
4507 }
4508 }
4509 }
4510
4511 return vk_outarray_status(&out);
4512 }
4513
4514 VkResult radv_EnumerateDeviceExtensionProperties(
4515 VkPhysicalDevice physicalDevice,
4516 const char* pLayerName,
4517 uint32_t* pPropertyCount,
4518 VkExtensionProperties* pProperties)
4519 {
4520 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
4521 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
4522
4523 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
4524 if (device->supported_extensions.extensions[i]) {
4525 vk_outarray_append(&out, prop) {
4526 *prop = radv_device_extensions[i];
4527 }
4528 }
4529 }
4530
4531 return vk_outarray_status(&out);
4532 }
4533
4534 PFN_vkVoidFunction radv_GetInstanceProcAddr(
4535 VkInstance _instance,
4536 const char* pName)
4537 {
4538 RADV_FROM_HANDLE(radv_instance, instance, _instance);
4539
4540 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
4541 * when we have to return valid function pointers, NULL, or it's left
4542 * undefined. See the table for exact details.
4543 */
4544 if (pName == NULL)
4545 return NULL;
4546
4547 #define LOOKUP_RADV_ENTRYPOINT(entrypoint) \
4548 if (strcmp(pName, "vk" #entrypoint) == 0) \
4549 return (PFN_vkVoidFunction)radv_##entrypoint
4550
4551 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
4552 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceLayerProperties);
4553 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceVersion);
4554 LOOKUP_RADV_ENTRYPOINT(CreateInstance);
4555
4556 /* GetInstanceProcAddr() can also be called with a NULL instance.
4557 * See https://gitlab.khronos.org/vulkan/vulkan/issues/2057
4558 */
4559 LOOKUP_RADV_ENTRYPOINT(GetInstanceProcAddr);
4560
4561 #undef LOOKUP_RADV_ENTRYPOINT
4562
4563 if (instance == NULL)
4564 return NULL;
4565
4566 int idx = radv_get_instance_entrypoint_index(pName);
4567 if (idx >= 0)
4568 return instance->dispatch.entrypoints[idx];
4569
4570 idx = radv_get_physical_device_entrypoint_index(pName);
4571 if (idx >= 0)
4572 return instance->physical_device_dispatch.entrypoints[idx];
4573
4574 idx = radv_get_device_entrypoint_index(pName);
4575 if (idx >= 0)
4576 return instance->device_dispatch.entrypoints[idx];
4577
4578 return NULL;
4579 }
4580
4581 /* The loader wants us to expose a second GetInstanceProcAddr function
4582 * to work around certain LD_PRELOAD issues seen in apps.
4583 */
4584 PUBLIC
4585 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
4586 VkInstance instance,
4587 const char* pName);
4588
4589 PUBLIC
4590 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
4591 VkInstance instance,
4592 const char* pName)
4593 {
4594 return radv_GetInstanceProcAddr(instance, pName);
4595 }
4596
4597 PUBLIC
4598 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
4599 VkInstance _instance,
4600 const char* pName);
4601
4602 PUBLIC
4603 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
4604 VkInstance _instance,
4605 const char* pName)
4606 {
4607 RADV_FROM_HANDLE(radv_instance, instance, _instance);
4608
4609 if (!pName || !instance)
4610 return NULL;
4611
4612 int idx = radv_get_physical_device_entrypoint_index(pName);
4613 if (idx < 0)
4614 return NULL;
4615
4616 return instance->physical_device_dispatch.entrypoints[idx];
4617 }
4618
4619 PFN_vkVoidFunction radv_GetDeviceProcAddr(
4620 VkDevice _device,
4621 const char* pName)
4622 {
4623 RADV_FROM_HANDLE(radv_device, device, _device);
4624
4625 if (!device || !pName)
4626 return NULL;
4627
4628 int idx = radv_get_device_entrypoint_index(pName);
4629 if (idx < 0)
4630 return NULL;
4631
4632 return device->dispatch.entrypoints[idx];
4633 }
4634
4635 bool radv_get_memory_fd(struct radv_device *device,
4636 struct radv_device_memory *memory,
4637 int *pFD)
4638 {
4639 struct radeon_bo_metadata metadata;
4640
4641 if (memory->image) {
4642 if (memory->image->tiling != VK_IMAGE_TILING_LINEAR)
4643 radv_init_metadata(device, memory->image, &metadata);
4644 device->ws->buffer_set_metadata(memory->bo, &metadata);
4645 }
4646
4647 return device->ws->buffer_get_fd(device->ws, memory->bo,
4648 pFD);
4649 }
4650
4651
4652 static void radv_free_memory(struct radv_device *device,
4653 const VkAllocationCallbacks* pAllocator,
4654 struct radv_device_memory *mem)
4655 {
4656 if (mem == NULL)
4657 return;
4658
4659 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
4660 if (mem->android_hardware_buffer)
4661 AHardwareBuffer_release(mem->android_hardware_buffer);
4662 #endif
4663
4664 if (mem->bo) {
4665 if (device->overallocation_disallowed) {
4666 mtx_lock(&device->overallocation_mutex);
4667 device->allocated_memory_size[mem->heap_index] -= mem->alloc_size;
4668 mtx_unlock(&device->overallocation_mutex);
4669 }
4670
4671 radv_bo_list_remove(device, mem->bo);
4672 device->ws->buffer_destroy(mem->bo);
4673 mem->bo = NULL;
4674 }
4675
4676 vk_object_base_finish(&mem->base);
4677 vk_free2(&device->vk.alloc, pAllocator, mem);
4678 }
4679
4680 static VkResult radv_alloc_memory(struct radv_device *device,
4681 const VkMemoryAllocateInfo* pAllocateInfo,
4682 const VkAllocationCallbacks* pAllocator,
4683 VkDeviceMemory* pMem)
4684 {
4685 struct radv_device_memory *mem;
4686 VkResult result;
4687 enum radeon_bo_domain domain;
4688 uint32_t flags = 0;
4689
4690 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
4691
4692 const VkImportMemoryFdInfoKHR *import_info =
4693 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
4694 const VkMemoryDedicatedAllocateInfo *dedicate_info =
4695 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
4696 const VkExportMemoryAllocateInfo *export_info =
4697 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
4698 const struct VkImportAndroidHardwareBufferInfoANDROID *ahb_import_info =
4699 vk_find_struct_const(pAllocateInfo->pNext,
4700 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
4701 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
4702 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
4703
4704 const struct wsi_memory_allocate_info *wsi_info =
4705 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
4706
4707 if (pAllocateInfo->allocationSize == 0 && !ahb_import_info &&
4708 !(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
4709 /* Apparently, this is allowed */
4710 *pMem = VK_NULL_HANDLE;
4711 return VK_SUCCESS;
4712 }
4713
4714 mem = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*mem), 8,
4715 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4716 if (mem == NULL)
4717 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4718
4719 vk_object_base_init(&device->vk, &mem->base,
4720 VK_OBJECT_TYPE_DEVICE_MEMORY);
4721
4722 if (wsi_info && wsi_info->implicit_sync)
4723 flags |= RADEON_FLAG_IMPLICIT_SYNC;
4724
4725 if (dedicate_info) {
4726 mem->image = radv_image_from_handle(dedicate_info->image);
4727 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
4728 } else {
4729 mem->image = NULL;
4730 mem->buffer = NULL;
4731 }
4732
4733 float priority_float = 0.5;
4734 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
4735 vk_find_struct_const(pAllocateInfo->pNext,
4736 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
4737 if (priority_ext)
4738 priority_float = priority_ext->priority;
4739
4740 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
4741 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
4742
4743 mem->user_ptr = NULL;
4744 mem->bo = NULL;
4745
4746 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
4747 mem->android_hardware_buffer = NULL;
4748 #endif
4749
4750 if (ahb_import_info) {
4751 result = radv_import_ahb_memory(device, mem, priority, ahb_import_info);
4752 if (result != VK_SUCCESS)
4753 goto fail;
4754 } else if(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
4755 result = radv_create_ahb_memory(device, mem, priority, pAllocateInfo);
4756 if (result != VK_SUCCESS)
4757 goto fail;
4758 } else if (import_info) {
4759 assert(import_info->handleType ==
4760 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
4761 import_info->handleType ==
4762 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
4763 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
4764 priority, NULL);
4765 if (!mem->bo) {
4766 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
4767 goto fail;
4768 } else {
4769 close(import_info->fd);
4770 }
4771 } else if (host_ptr_info) {
4772 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
4773 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
4774 pAllocateInfo->allocationSize,
4775 priority);
4776 if (!mem->bo) {
4777 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
4778 goto fail;
4779 } else {
4780 mem->user_ptr = host_ptr_info->pHostPointer;
4781 }
4782 } else {
4783 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
4784 uint32_t heap_index;
4785
4786 heap_index = device->physical_device->memory_properties.memoryTypes[pAllocateInfo->memoryTypeIndex].heapIndex;
4787 domain = device->physical_device->memory_domains[pAllocateInfo->memoryTypeIndex];
4788 flags |= device->physical_device->memory_flags[pAllocateInfo->memoryTypeIndex];
4789
4790 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
4791 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
4792 if (device->use_global_bo_list) {
4793 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
4794 }
4795 }
4796
4797 if (device->overallocation_disallowed) {
4798 uint64_t total_size =
4799 device->physical_device->memory_properties.memoryHeaps[heap_index].size;
4800
4801 mtx_lock(&device->overallocation_mutex);
4802 if (device->allocated_memory_size[heap_index] + alloc_size > total_size) {
4803 mtx_unlock(&device->overallocation_mutex);
4804 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
4805 goto fail;
4806 }
4807 device->allocated_memory_size[heap_index] += alloc_size;
4808 mtx_unlock(&device->overallocation_mutex);
4809 }
4810
4811 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
4812 domain, flags, priority);
4813
4814 if (!mem->bo) {
4815 if (device->overallocation_disallowed) {
4816 mtx_lock(&device->overallocation_mutex);
4817 device->allocated_memory_size[heap_index] -= alloc_size;
4818 mtx_unlock(&device->overallocation_mutex);
4819 }
4820 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
4821 goto fail;
4822 }
4823
4824 mem->heap_index = heap_index;
4825 mem->alloc_size = alloc_size;
4826 }
4827
4828 if (!wsi_info) {
4829 result = radv_bo_list_add(device, mem->bo);
4830 if (result != VK_SUCCESS)
4831 goto fail;
4832 }
4833
4834 *pMem = radv_device_memory_to_handle(mem);
4835
4836 return VK_SUCCESS;
4837
4838 fail:
4839 radv_free_memory(device, pAllocator,mem);
4840
4841 return result;
4842 }
4843
4844 VkResult radv_AllocateMemory(
4845 VkDevice _device,
4846 const VkMemoryAllocateInfo* pAllocateInfo,
4847 const VkAllocationCallbacks* pAllocator,
4848 VkDeviceMemory* pMem)
4849 {
4850 RADV_FROM_HANDLE(radv_device, device, _device);
4851 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
4852 }
4853
4854 void radv_FreeMemory(
4855 VkDevice _device,
4856 VkDeviceMemory _mem,
4857 const VkAllocationCallbacks* pAllocator)
4858 {
4859 RADV_FROM_HANDLE(radv_device, device, _device);
4860 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
4861
4862 radv_free_memory(device, pAllocator, mem);
4863 }
4864
4865 VkResult radv_MapMemory(
4866 VkDevice _device,
4867 VkDeviceMemory _memory,
4868 VkDeviceSize offset,
4869 VkDeviceSize size,
4870 VkMemoryMapFlags flags,
4871 void** ppData)
4872 {
4873 RADV_FROM_HANDLE(radv_device, device, _device);
4874 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
4875
4876 if (mem == NULL) {
4877 *ppData = NULL;
4878 return VK_SUCCESS;
4879 }
4880
4881 if (mem->user_ptr)
4882 *ppData = mem->user_ptr;
4883 else
4884 *ppData = device->ws->buffer_map(mem->bo);
4885
4886 if (*ppData) {
4887 *ppData += offset;
4888 return VK_SUCCESS;
4889 }
4890
4891 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
4892 }
4893
4894 void radv_UnmapMemory(
4895 VkDevice _device,
4896 VkDeviceMemory _memory)
4897 {
4898 RADV_FROM_HANDLE(radv_device, device, _device);
4899 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
4900
4901 if (mem == NULL)
4902 return;
4903
4904 if (mem->user_ptr == NULL)
4905 device->ws->buffer_unmap(mem->bo);
4906 }
4907
4908 VkResult radv_FlushMappedMemoryRanges(
4909 VkDevice _device,
4910 uint32_t memoryRangeCount,
4911 const VkMappedMemoryRange* pMemoryRanges)
4912 {
4913 return VK_SUCCESS;
4914 }
4915
4916 VkResult radv_InvalidateMappedMemoryRanges(
4917 VkDevice _device,
4918 uint32_t memoryRangeCount,
4919 const VkMappedMemoryRange* pMemoryRanges)
4920 {
4921 return VK_SUCCESS;
4922 }
4923
4924 void radv_GetBufferMemoryRequirements(
4925 VkDevice _device,
4926 VkBuffer _buffer,
4927 VkMemoryRequirements* pMemoryRequirements)
4928 {
4929 RADV_FROM_HANDLE(radv_device, device, _device);
4930 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
4931
4932 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
4933
4934 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
4935 pMemoryRequirements->alignment = 4096;
4936 else
4937 pMemoryRequirements->alignment = 16;
4938
4939 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
4940 }
4941
4942 void radv_GetBufferMemoryRequirements2(
4943 VkDevice device,
4944 const VkBufferMemoryRequirementsInfo2 *pInfo,
4945 VkMemoryRequirements2 *pMemoryRequirements)
4946 {
4947 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
4948 &pMemoryRequirements->memoryRequirements);
4949 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
4950 switch (ext->sType) {
4951 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4952 VkMemoryDedicatedRequirements *req =
4953 (VkMemoryDedicatedRequirements *) ext;
4954 req->requiresDedicatedAllocation = false;
4955 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
4956 break;
4957 }
4958 default:
4959 break;
4960 }
4961 }
4962 }
4963
4964 void radv_GetImageMemoryRequirements(
4965 VkDevice _device,
4966 VkImage _image,
4967 VkMemoryRequirements* pMemoryRequirements)
4968 {
4969 RADV_FROM_HANDLE(radv_device, device, _device);
4970 RADV_FROM_HANDLE(radv_image, image, _image);
4971
4972 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
4973
4974 pMemoryRequirements->size = image->size;
4975 pMemoryRequirements->alignment = image->alignment;
4976 }
4977
4978 void radv_GetImageMemoryRequirements2(
4979 VkDevice device,
4980 const VkImageMemoryRequirementsInfo2 *pInfo,
4981 VkMemoryRequirements2 *pMemoryRequirements)
4982 {
4983 radv_GetImageMemoryRequirements(device, pInfo->image,
4984 &pMemoryRequirements->memoryRequirements);
4985
4986 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
4987
4988 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
4989 switch (ext->sType) {
4990 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4991 VkMemoryDedicatedRequirements *req =
4992 (VkMemoryDedicatedRequirements *) ext;
4993 req->requiresDedicatedAllocation = image->shareable &&
4994 image->tiling != VK_IMAGE_TILING_LINEAR;
4995 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
4996 break;
4997 }
4998 default:
4999 break;
5000 }
5001 }
5002 }
5003
5004 void radv_GetImageSparseMemoryRequirements(
5005 VkDevice device,
5006 VkImage image,
5007 uint32_t* pSparseMemoryRequirementCount,
5008 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
5009 {
5010 stub();
5011 }
5012
5013 void radv_GetImageSparseMemoryRequirements2(
5014 VkDevice device,
5015 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
5016 uint32_t* pSparseMemoryRequirementCount,
5017 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
5018 {
5019 stub();
5020 }
5021
5022 void radv_GetDeviceMemoryCommitment(
5023 VkDevice device,
5024 VkDeviceMemory memory,
5025 VkDeviceSize* pCommittedMemoryInBytes)
5026 {
5027 *pCommittedMemoryInBytes = 0;
5028 }
5029
5030 VkResult radv_BindBufferMemory2(VkDevice device,
5031 uint32_t bindInfoCount,
5032 const VkBindBufferMemoryInfo *pBindInfos)
5033 {
5034 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5035 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5036 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
5037
5038 if (mem) {
5039 buffer->bo = mem->bo;
5040 buffer->offset = pBindInfos[i].memoryOffset;
5041 } else {
5042 buffer->bo = NULL;
5043 }
5044 }
5045 return VK_SUCCESS;
5046 }
5047
5048 VkResult radv_BindBufferMemory(
5049 VkDevice device,
5050 VkBuffer buffer,
5051 VkDeviceMemory memory,
5052 VkDeviceSize memoryOffset)
5053 {
5054 const VkBindBufferMemoryInfo info = {
5055 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5056 .buffer = buffer,
5057 .memory = memory,
5058 .memoryOffset = memoryOffset
5059 };
5060
5061 return radv_BindBufferMemory2(device, 1, &info);
5062 }
5063
5064 VkResult radv_BindImageMemory2(VkDevice device,
5065 uint32_t bindInfoCount,
5066 const VkBindImageMemoryInfo *pBindInfos)
5067 {
5068 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5069 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5070 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
5071
5072 if (mem) {
5073 image->bo = mem->bo;
5074 image->offset = pBindInfos[i].memoryOffset;
5075 } else {
5076 image->bo = NULL;
5077 image->offset = 0;
5078 }
5079 }
5080 return VK_SUCCESS;
5081 }
5082
5083
5084 VkResult radv_BindImageMemory(
5085 VkDevice device,
5086 VkImage image,
5087 VkDeviceMemory memory,
5088 VkDeviceSize memoryOffset)
5089 {
5090 const VkBindImageMemoryInfo info = {
5091 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5092 .image = image,
5093 .memory = memory,
5094 .memoryOffset = memoryOffset
5095 };
5096
5097 return radv_BindImageMemory2(device, 1, &info);
5098 }
5099
5100 static bool radv_sparse_bind_has_effects(const VkBindSparseInfo *info)
5101 {
5102 return info->bufferBindCount ||
5103 info->imageOpaqueBindCount ||
5104 info->imageBindCount ||
5105 info->waitSemaphoreCount ||
5106 info->signalSemaphoreCount;
5107 }
5108
5109 VkResult radv_QueueBindSparse(
5110 VkQueue _queue,
5111 uint32_t bindInfoCount,
5112 const VkBindSparseInfo* pBindInfo,
5113 VkFence fence)
5114 {
5115 RADV_FROM_HANDLE(radv_queue, queue, _queue);
5116 VkResult result;
5117 uint32_t fence_idx = 0;
5118
5119 if (fence != VK_NULL_HANDLE) {
5120 for (uint32_t i = 0; i < bindInfoCount; ++i)
5121 if (radv_sparse_bind_has_effects(pBindInfo + i))
5122 fence_idx = i;
5123 } else
5124 fence_idx = UINT32_MAX;
5125
5126 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5127 if (i != fence_idx && !radv_sparse_bind_has_effects(pBindInfo + i))
5128 continue;
5129
5130 const VkTimelineSemaphoreSubmitInfo *timeline_info =
5131 vk_find_struct_const(pBindInfo[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
5132
5133 VkResult result = radv_queue_submit(queue, &(struct radv_queue_submission) {
5134 .buffer_binds = pBindInfo[i].pBufferBinds,
5135 .buffer_bind_count = pBindInfo[i].bufferBindCount,
5136 .image_opaque_binds = pBindInfo[i].pImageOpaqueBinds,
5137 .image_opaque_bind_count = pBindInfo[i].imageOpaqueBindCount,
5138 .wait_semaphores = pBindInfo[i].pWaitSemaphores,
5139 .wait_semaphore_count = pBindInfo[i].waitSemaphoreCount,
5140 .signal_semaphores = pBindInfo[i].pSignalSemaphores,
5141 .signal_semaphore_count = pBindInfo[i].signalSemaphoreCount,
5142 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
5143 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
5144 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
5145 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
5146 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
5147 });
5148
5149 if (result != VK_SUCCESS)
5150 return result;
5151 }
5152
5153 if (fence != VK_NULL_HANDLE && !bindInfoCount) {
5154 result = radv_signal_fence(queue, fence);
5155 if (result != VK_SUCCESS)
5156 return result;
5157 }
5158
5159 return VK_SUCCESS;
5160 }
5161
5162 VkResult radv_CreateFence(
5163 VkDevice _device,
5164 const VkFenceCreateInfo* pCreateInfo,
5165 const VkAllocationCallbacks* pAllocator,
5166 VkFence* pFence)
5167 {
5168 RADV_FROM_HANDLE(radv_device, device, _device);
5169 const VkExportFenceCreateInfo *export =
5170 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
5171 VkExternalFenceHandleTypeFlags handleTypes =
5172 export ? export->handleTypes : 0;
5173
5174 struct radv_fence *fence = vk_alloc2(&device->vk.alloc, pAllocator,
5175 sizeof(*fence), 8,
5176 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5177
5178 if (!fence)
5179 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5180
5181 vk_object_base_init(&device->vk, &fence->base, VK_OBJECT_TYPE_FENCE);
5182
5183 fence->fence_wsi = NULL;
5184 fence->temp_syncobj = 0;
5185 if (device->always_use_syncobj || handleTypes) {
5186 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
5187 if (ret) {
5188 vk_free2(&device->vk.alloc, pAllocator, fence);
5189 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5190 }
5191 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
5192 device->ws->signal_syncobj(device->ws, fence->syncobj);
5193 }
5194 fence->fence = NULL;
5195 } else {
5196 fence->fence = device->ws->create_fence();
5197 if (!fence->fence) {
5198 vk_free2(&device->vk.alloc, pAllocator, fence);
5199 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5200 }
5201 fence->syncobj = 0;
5202 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
5203 device->ws->signal_fence(fence->fence);
5204 }
5205
5206 *pFence = radv_fence_to_handle(fence);
5207
5208 return VK_SUCCESS;
5209 }
5210
5211 void radv_DestroyFence(
5212 VkDevice _device,
5213 VkFence _fence,
5214 const VkAllocationCallbacks* pAllocator)
5215 {
5216 RADV_FROM_HANDLE(radv_device, device, _device);
5217 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5218
5219 if (!fence)
5220 return;
5221
5222 if (fence->temp_syncobj)
5223 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5224 if (fence->syncobj)
5225 device->ws->destroy_syncobj(device->ws, fence->syncobj);
5226 if (fence->fence)
5227 device->ws->destroy_fence(fence->fence);
5228 if (fence->fence_wsi)
5229 fence->fence_wsi->destroy(fence->fence_wsi);
5230
5231 vk_object_base_finish(&fence->base);
5232 vk_free2(&device->vk.alloc, pAllocator, fence);
5233 }
5234
5235
5236 uint64_t radv_get_current_time(void)
5237 {
5238 struct timespec tv;
5239 clock_gettime(CLOCK_MONOTONIC, &tv);
5240 return tv.tv_nsec + tv.tv_sec*1000000000ull;
5241 }
5242
5243 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
5244 {
5245 uint64_t current_time = radv_get_current_time();
5246
5247 timeout = MIN2(UINT64_MAX - current_time, timeout);
5248
5249 return current_time + timeout;
5250 }
5251
5252
5253 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
5254 uint32_t fenceCount, const VkFence *pFences)
5255 {
5256 for (uint32_t i = 0; i < fenceCount; ++i) {
5257 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5258 if (fence->fence == NULL || fence->syncobj ||
5259 fence->temp_syncobj || fence->fence_wsi ||
5260 (!device->ws->is_fence_waitable(fence->fence)))
5261 return false;
5262 }
5263 return true;
5264 }
5265
5266 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
5267 {
5268 for (uint32_t i = 0; i < fenceCount; ++i) {
5269 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5270 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
5271 return false;
5272 }
5273 return true;
5274 }
5275
5276 VkResult radv_WaitForFences(
5277 VkDevice _device,
5278 uint32_t fenceCount,
5279 const VkFence* pFences,
5280 VkBool32 waitAll,
5281 uint64_t timeout)
5282 {
5283 RADV_FROM_HANDLE(radv_device, device, _device);
5284 timeout = radv_get_absolute_timeout(timeout);
5285
5286 if (device->always_use_syncobj &&
5287 radv_all_fences_syncobj(fenceCount, pFences))
5288 {
5289 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
5290 if (!handles)
5291 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5292
5293 for (uint32_t i = 0; i < fenceCount; ++i) {
5294 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5295 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
5296 }
5297
5298 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
5299
5300 free(handles);
5301 return success ? VK_SUCCESS : VK_TIMEOUT;
5302 }
5303
5304 if (!waitAll && fenceCount > 1) {
5305 /* Not doing this by default for waitAll, due to needing to allocate twice. */
5306 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
5307 uint32_t wait_count = 0;
5308 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
5309 if (!fences)
5310 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5311
5312 for (uint32_t i = 0; i < fenceCount; ++i) {
5313 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5314
5315 if (device->ws->fence_wait(device->ws, fence->fence, false, 0)) {
5316 free(fences);
5317 return VK_SUCCESS;
5318 }
5319
5320 fences[wait_count++] = fence->fence;
5321 }
5322
5323 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
5324 waitAll, timeout - radv_get_current_time());
5325
5326 free(fences);
5327 return success ? VK_SUCCESS : VK_TIMEOUT;
5328 }
5329
5330 while(radv_get_current_time() <= timeout) {
5331 for (uint32_t i = 0; i < fenceCount; ++i) {
5332 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
5333 return VK_SUCCESS;
5334 }
5335 }
5336 return VK_TIMEOUT;
5337 }
5338
5339 for (uint32_t i = 0; i < fenceCount; ++i) {
5340 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5341 bool expired = false;
5342
5343 if (fence->temp_syncobj) {
5344 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
5345 return VK_TIMEOUT;
5346 continue;
5347 }
5348
5349 if (fence->syncobj) {
5350 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
5351 return VK_TIMEOUT;
5352 continue;
5353 }
5354
5355 if (fence->fence) {
5356 if (!device->ws->is_fence_waitable(fence->fence)) {
5357 while(!device->ws->is_fence_waitable(fence->fence) &&
5358 radv_get_current_time() <= timeout)
5359 /* Do nothing */;
5360 }
5361
5362 expired = device->ws->fence_wait(device->ws,
5363 fence->fence,
5364 true, timeout);
5365 if (!expired)
5366 return VK_TIMEOUT;
5367 }
5368
5369 if (fence->fence_wsi) {
5370 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
5371 if (result != VK_SUCCESS)
5372 return result;
5373 }
5374 }
5375
5376 return VK_SUCCESS;
5377 }
5378
5379 VkResult radv_ResetFences(VkDevice _device,
5380 uint32_t fenceCount,
5381 const VkFence *pFences)
5382 {
5383 RADV_FROM_HANDLE(radv_device, device, _device);
5384
5385 for (unsigned i = 0; i < fenceCount; ++i) {
5386 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5387 if (fence->fence)
5388 device->ws->reset_fence(fence->fence);
5389
5390 /* Per spec, we first restore the permanent payload, and then reset, so
5391 * having a temp syncobj should not skip resetting the permanent syncobj. */
5392 if (fence->temp_syncobj) {
5393 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5394 fence->temp_syncobj = 0;
5395 }
5396
5397 if (fence->syncobj) {
5398 device->ws->reset_syncobj(device->ws, fence->syncobj);
5399 }
5400 }
5401
5402 return VK_SUCCESS;
5403 }
5404
5405 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
5406 {
5407 RADV_FROM_HANDLE(radv_device, device, _device);
5408 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5409
5410 if (fence->temp_syncobj) {
5411 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
5412 return success ? VK_SUCCESS : VK_NOT_READY;
5413 }
5414
5415 if (fence->syncobj) {
5416 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
5417 return success ? VK_SUCCESS : VK_NOT_READY;
5418 }
5419
5420 if (fence->fence) {
5421 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
5422 return VK_NOT_READY;
5423 }
5424 if (fence->fence_wsi) {
5425 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
5426
5427 if (result != VK_SUCCESS) {
5428 if (result == VK_TIMEOUT)
5429 return VK_NOT_READY;
5430 return result;
5431 }
5432 }
5433 return VK_SUCCESS;
5434 }
5435
5436
5437 // Queue semaphore functions
5438
5439 static void
5440 radv_create_timeline(struct radv_timeline *timeline, uint64_t value)
5441 {
5442 timeline->highest_signaled = value;
5443 timeline->highest_submitted = value;
5444 list_inithead(&timeline->points);
5445 list_inithead(&timeline->free_points);
5446 list_inithead(&timeline->waiters);
5447 pthread_mutex_init(&timeline->mutex, NULL);
5448 }
5449
5450 static void
5451 radv_destroy_timeline(struct radv_device *device,
5452 struct radv_timeline *timeline)
5453 {
5454 list_for_each_entry_safe(struct radv_timeline_point, point,
5455 &timeline->free_points, list) {
5456 list_del(&point->list);
5457 device->ws->destroy_syncobj(device->ws, point->syncobj);
5458 free(point);
5459 }
5460 list_for_each_entry_safe(struct radv_timeline_point, point,
5461 &timeline->points, list) {
5462 list_del(&point->list);
5463 device->ws->destroy_syncobj(device->ws, point->syncobj);
5464 free(point);
5465 }
5466 pthread_mutex_destroy(&timeline->mutex);
5467 }
5468
5469 static void
5470 radv_timeline_gc_locked(struct radv_device *device,
5471 struct radv_timeline *timeline)
5472 {
5473 list_for_each_entry_safe(struct radv_timeline_point, point,
5474 &timeline->points, list) {
5475 if (point->wait_count || point->value > timeline->highest_submitted)
5476 return;
5477
5478 if (device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, 0)) {
5479 timeline->highest_signaled = point->value;
5480 list_del(&point->list);
5481 list_add(&point->list, &timeline->free_points);
5482 }
5483 }
5484 }
5485
5486 static struct radv_timeline_point *
5487 radv_timeline_find_point_at_least_locked(struct radv_device *device,
5488 struct radv_timeline *timeline,
5489 uint64_t p)
5490 {
5491 radv_timeline_gc_locked(device, timeline);
5492
5493 if (p <= timeline->highest_signaled)
5494 return NULL;
5495
5496 list_for_each_entry(struct radv_timeline_point, point,
5497 &timeline->points, list) {
5498 if (point->value >= p) {
5499 ++point->wait_count;
5500 return point;
5501 }
5502 }
5503 return NULL;
5504 }
5505
5506 static struct radv_timeline_point *
5507 radv_timeline_add_point_locked(struct radv_device *device,
5508 struct radv_timeline *timeline,
5509 uint64_t p)
5510 {
5511 radv_timeline_gc_locked(device, timeline);
5512
5513 struct radv_timeline_point *ret = NULL;
5514 struct radv_timeline_point *prev = NULL;
5515
5516 if (p <= timeline->highest_signaled)
5517 return NULL;
5518
5519 list_for_each_entry(struct radv_timeline_point, point,
5520 &timeline->points, list) {
5521 if (point->value == p) {
5522 return NULL;
5523 }
5524
5525 if (point->value < p)
5526 prev = point;
5527 }
5528
5529 if (list_is_empty(&timeline->free_points)) {
5530 ret = malloc(sizeof(struct radv_timeline_point));
5531 device->ws->create_syncobj(device->ws, &ret->syncobj);
5532 } else {
5533 ret = list_first_entry(&timeline->free_points, struct radv_timeline_point, list);
5534 list_del(&ret->list);
5535
5536 device->ws->reset_syncobj(device->ws, ret->syncobj);
5537 }
5538
5539 ret->value = p;
5540 ret->wait_count = 1;
5541
5542 if (prev) {
5543 list_add(&ret->list, &prev->list);
5544 } else {
5545 list_addtail(&ret->list, &timeline->points);
5546 }
5547 return ret;
5548 }
5549
5550
5551 static VkResult
5552 radv_timeline_wait_locked(struct radv_device *device,
5553 struct radv_timeline *timeline,
5554 uint64_t value,
5555 uint64_t abs_timeout)
5556 {
5557 while(timeline->highest_submitted < value) {
5558 struct timespec abstime;
5559 timespec_from_nsec(&abstime, abs_timeout);
5560
5561 pthread_cond_timedwait(&device->timeline_cond, &timeline->mutex, &abstime);
5562
5563 if (radv_get_current_time() >= abs_timeout && timeline->highest_submitted < value)
5564 return VK_TIMEOUT;
5565 }
5566
5567 struct radv_timeline_point *point = radv_timeline_find_point_at_least_locked(device, timeline, value);
5568 if (!point)
5569 return VK_SUCCESS;
5570
5571 pthread_mutex_unlock(&timeline->mutex);
5572
5573 bool success = device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, abs_timeout);
5574
5575 pthread_mutex_lock(&timeline->mutex);
5576 point->wait_count--;
5577 return success ? VK_SUCCESS : VK_TIMEOUT;
5578 }
5579
5580 static void
5581 radv_timeline_trigger_waiters_locked(struct radv_timeline *timeline,
5582 struct list_head *processing_list)
5583 {
5584 list_for_each_entry_safe(struct radv_timeline_waiter, waiter,
5585 &timeline->waiters, list) {
5586 if (waiter->value > timeline->highest_submitted)
5587 continue;
5588
5589 if (p_atomic_dec_zero(&waiter->submission->submission_wait_count)) {
5590 list_addtail(&waiter->submission->processing_list, processing_list);
5591 }
5592 list_del(&waiter->list);
5593 }
5594 }
5595
5596 static
5597 void radv_destroy_semaphore_part(struct radv_device *device,
5598 struct radv_semaphore_part *part)
5599 {
5600 switch(part->kind) {
5601 case RADV_SEMAPHORE_NONE:
5602 break;
5603 case RADV_SEMAPHORE_WINSYS:
5604 device->ws->destroy_sem(part->ws_sem);
5605 break;
5606 case RADV_SEMAPHORE_TIMELINE:
5607 radv_destroy_timeline(device, &part->timeline);
5608 break;
5609 case RADV_SEMAPHORE_SYNCOBJ:
5610 device->ws->destroy_syncobj(device->ws, part->syncobj);
5611 break;
5612 }
5613 part->kind = RADV_SEMAPHORE_NONE;
5614 }
5615
5616 static VkSemaphoreTypeKHR
5617 radv_get_semaphore_type(const void *pNext, uint64_t *initial_value)
5618 {
5619 const VkSemaphoreTypeCreateInfo *type_info =
5620 vk_find_struct_const(pNext, SEMAPHORE_TYPE_CREATE_INFO);
5621
5622 if (!type_info)
5623 return VK_SEMAPHORE_TYPE_BINARY;
5624
5625 if (initial_value)
5626 *initial_value = type_info->initialValue;
5627 return type_info->semaphoreType;
5628 }
5629
5630 VkResult radv_CreateSemaphore(
5631 VkDevice _device,
5632 const VkSemaphoreCreateInfo* pCreateInfo,
5633 const VkAllocationCallbacks* pAllocator,
5634 VkSemaphore* pSemaphore)
5635 {
5636 RADV_FROM_HANDLE(radv_device, device, _device);
5637 const VkExportSemaphoreCreateInfo *export =
5638 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
5639 VkExternalSemaphoreHandleTypeFlags handleTypes =
5640 export ? export->handleTypes : 0;
5641 uint64_t initial_value = 0;
5642 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pCreateInfo->pNext, &initial_value);
5643
5644 struct radv_semaphore *sem = vk_alloc2(&device->vk.alloc, pAllocator,
5645 sizeof(*sem), 8,
5646 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5647 if (!sem)
5648 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5649
5650 vk_object_base_init(&device->vk, &sem->base,
5651 VK_OBJECT_TYPE_SEMAPHORE);
5652
5653 sem->temporary.kind = RADV_SEMAPHORE_NONE;
5654 sem->permanent.kind = RADV_SEMAPHORE_NONE;
5655
5656 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
5657 radv_create_timeline(&sem->permanent.timeline, initial_value);
5658 sem->permanent.kind = RADV_SEMAPHORE_TIMELINE;
5659 } else if (device->always_use_syncobj || handleTypes) {
5660 assert (device->physical_device->rad_info.has_syncobj);
5661 int ret = device->ws->create_syncobj(device->ws, &sem->permanent.syncobj);
5662 if (ret) {
5663 vk_free2(&device->vk.alloc, pAllocator, sem);
5664 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5665 }
5666 sem->permanent.kind = RADV_SEMAPHORE_SYNCOBJ;
5667 } else {
5668 sem->permanent.ws_sem = device->ws->create_sem(device->ws);
5669 if (!sem->permanent.ws_sem) {
5670 vk_free2(&device->vk.alloc, pAllocator, sem);
5671 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5672 }
5673 sem->permanent.kind = RADV_SEMAPHORE_WINSYS;
5674 }
5675
5676 *pSemaphore = radv_semaphore_to_handle(sem);
5677 return VK_SUCCESS;
5678 }
5679
5680 void radv_DestroySemaphore(
5681 VkDevice _device,
5682 VkSemaphore _semaphore,
5683 const VkAllocationCallbacks* pAllocator)
5684 {
5685 RADV_FROM_HANDLE(radv_device, device, _device);
5686 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
5687 if (!_semaphore)
5688 return;
5689
5690 radv_destroy_semaphore_part(device, &sem->temporary);
5691 radv_destroy_semaphore_part(device, &sem->permanent);
5692 vk_object_base_finish(&sem->base);
5693 vk_free2(&device->vk.alloc, pAllocator, sem);
5694 }
5695
5696 VkResult
5697 radv_GetSemaphoreCounterValue(VkDevice _device,
5698 VkSemaphore _semaphore,
5699 uint64_t* pValue)
5700 {
5701 RADV_FROM_HANDLE(radv_device, device, _device);
5702 RADV_FROM_HANDLE(radv_semaphore, semaphore, _semaphore);
5703
5704 struct radv_semaphore_part *part =
5705 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
5706
5707 switch (part->kind) {
5708 case RADV_SEMAPHORE_TIMELINE: {
5709 pthread_mutex_lock(&part->timeline.mutex);
5710 radv_timeline_gc_locked(device, &part->timeline);
5711 *pValue = part->timeline.highest_signaled;
5712 pthread_mutex_unlock(&part->timeline.mutex);
5713 return VK_SUCCESS;
5714 }
5715 case RADV_SEMAPHORE_NONE:
5716 case RADV_SEMAPHORE_SYNCOBJ:
5717 case RADV_SEMAPHORE_WINSYS:
5718 unreachable("Invalid semaphore type");
5719 }
5720 unreachable("Unhandled semaphore type");
5721 }
5722
5723
5724 static VkResult
5725 radv_wait_timelines(struct radv_device *device,
5726 const VkSemaphoreWaitInfo* pWaitInfo,
5727 uint64_t abs_timeout)
5728 {
5729 if ((pWaitInfo->flags & VK_SEMAPHORE_WAIT_ANY_BIT_KHR) && pWaitInfo->semaphoreCount > 1) {
5730 for (;;) {
5731 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
5732 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
5733 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
5734 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], 0);
5735 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
5736
5737 if (result == VK_SUCCESS)
5738 return VK_SUCCESS;
5739 }
5740 if (radv_get_current_time() > abs_timeout)
5741 return VK_TIMEOUT;
5742 }
5743 }
5744
5745 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
5746 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
5747 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
5748 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], abs_timeout);
5749 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
5750
5751 if (result != VK_SUCCESS)
5752 return result;
5753 }
5754 return VK_SUCCESS;
5755 }
5756 VkResult
5757 radv_WaitSemaphores(VkDevice _device,
5758 const VkSemaphoreWaitInfo* pWaitInfo,
5759 uint64_t timeout)
5760 {
5761 RADV_FROM_HANDLE(radv_device, device, _device);
5762 uint64_t abs_timeout = radv_get_absolute_timeout(timeout);
5763 return radv_wait_timelines(device, pWaitInfo, abs_timeout);
5764 }
5765
5766 VkResult
5767 radv_SignalSemaphore(VkDevice _device,
5768 const VkSemaphoreSignalInfo* pSignalInfo)
5769 {
5770 RADV_FROM_HANDLE(radv_device, device, _device);
5771 RADV_FROM_HANDLE(radv_semaphore, semaphore, pSignalInfo->semaphore);
5772
5773 struct radv_semaphore_part *part =
5774 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
5775
5776 switch(part->kind) {
5777 case RADV_SEMAPHORE_TIMELINE: {
5778 pthread_mutex_lock(&part->timeline.mutex);
5779 radv_timeline_gc_locked(device, &part->timeline);
5780 part->timeline.highest_submitted = MAX2(part->timeline.highest_submitted, pSignalInfo->value);
5781 part->timeline.highest_signaled = MAX2(part->timeline.highest_signaled, pSignalInfo->value);
5782
5783 struct list_head processing_list;
5784 list_inithead(&processing_list);
5785 radv_timeline_trigger_waiters_locked(&part->timeline, &processing_list);
5786 pthread_mutex_unlock(&part->timeline.mutex);
5787
5788 return radv_process_submissions(&processing_list);
5789 }
5790 case RADV_SEMAPHORE_NONE:
5791 case RADV_SEMAPHORE_SYNCOBJ:
5792 case RADV_SEMAPHORE_WINSYS:
5793 unreachable("Invalid semaphore type");
5794 }
5795 return VK_SUCCESS;
5796 }
5797
5798 static void radv_destroy_event(struct radv_device *device,
5799 const VkAllocationCallbacks* pAllocator,
5800 struct radv_event *event)
5801 {
5802 device->ws->buffer_destroy(event->bo);
5803 vk_object_base_finish(&event->base);
5804 vk_free2(&device->vk.alloc, pAllocator, event);
5805 }
5806
5807 VkResult radv_CreateEvent(
5808 VkDevice _device,
5809 const VkEventCreateInfo* pCreateInfo,
5810 const VkAllocationCallbacks* pAllocator,
5811 VkEvent* pEvent)
5812 {
5813 RADV_FROM_HANDLE(radv_device, device, _device);
5814 struct radv_event *event = vk_alloc2(&device->vk.alloc, pAllocator,
5815 sizeof(*event), 8,
5816 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5817
5818 if (!event)
5819 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5820
5821 vk_object_base_init(&device->vk, &event->base, VK_OBJECT_TYPE_EVENT);
5822
5823 event->bo = device->ws->buffer_create(device->ws, 8, 8,
5824 RADEON_DOMAIN_GTT,
5825 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
5826 RADV_BO_PRIORITY_FENCE);
5827 if (!event->bo) {
5828 vk_free2(&device->vk.alloc, pAllocator, event);
5829 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
5830 }
5831
5832 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
5833 if (!event->map) {
5834 radv_destroy_event(device, pAllocator, event);
5835 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
5836 }
5837
5838 *pEvent = radv_event_to_handle(event);
5839
5840 return VK_SUCCESS;
5841 }
5842
5843 void radv_DestroyEvent(
5844 VkDevice _device,
5845 VkEvent _event,
5846 const VkAllocationCallbacks* pAllocator)
5847 {
5848 RADV_FROM_HANDLE(radv_device, device, _device);
5849 RADV_FROM_HANDLE(radv_event, event, _event);
5850
5851 if (!event)
5852 return;
5853
5854 radv_destroy_event(device, pAllocator, event);
5855 }
5856
5857 VkResult radv_GetEventStatus(
5858 VkDevice _device,
5859 VkEvent _event)
5860 {
5861 RADV_FROM_HANDLE(radv_event, event, _event);
5862
5863 if (*event->map == 1)
5864 return VK_EVENT_SET;
5865 return VK_EVENT_RESET;
5866 }
5867
5868 VkResult radv_SetEvent(
5869 VkDevice _device,
5870 VkEvent _event)
5871 {
5872 RADV_FROM_HANDLE(radv_event, event, _event);
5873 *event->map = 1;
5874
5875 return VK_SUCCESS;
5876 }
5877
5878 VkResult radv_ResetEvent(
5879 VkDevice _device,
5880 VkEvent _event)
5881 {
5882 RADV_FROM_HANDLE(radv_event, event, _event);
5883 *event->map = 0;
5884
5885 return VK_SUCCESS;
5886 }
5887
5888 VkResult radv_CreateBuffer(
5889 VkDevice _device,
5890 const VkBufferCreateInfo* pCreateInfo,
5891 const VkAllocationCallbacks* pAllocator,
5892 VkBuffer* pBuffer)
5893 {
5894 RADV_FROM_HANDLE(radv_device, device, _device);
5895 struct radv_buffer *buffer;
5896
5897 if (pCreateInfo->size > RADV_MAX_MEMORY_ALLOCATION_SIZE)
5898 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
5899
5900 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
5901
5902 buffer = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*buffer), 8,
5903 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5904 if (buffer == NULL)
5905 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5906
5907 vk_object_base_init(&device->vk, &buffer->base, VK_OBJECT_TYPE_BUFFER);
5908
5909 buffer->size = pCreateInfo->size;
5910 buffer->usage = pCreateInfo->usage;
5911 buffer->bo = NULL;
5912 buffer->offset = 0;
5913 buffer->flags = pCreateInfo->flags;
5914
5915 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
5916 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
5917
5918 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
5919 buffer->bo = device->ws->buffer_create(device->ws,
5920 align64(buffer->size, 4096),
5921 4096, 0, RADEON_FLAG_VIRTUAL,
5922 RADV_BO_PRIORITY_VIRTUAL);
5923 if (!buffer->bo) {
5924 vk_free2(&device->vk.alloc, pAllocator, buffer);
5925 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
5926 }
5927 }
5928
5929 *pBuffer = radv_buffer_to_handle(buffer);
5930
5931 return VK_SUCCESS;
5932 }
5933
5934 void radv_DestroyBuffer(
5935 VkDevice _device,
5936 VkBuffer _buffer,
5937 const VkAllocationCallbacks* pAllocator)
5938 {
5939 RADV_FROM_HANDLE(radv_device, device, _device);
5940 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
5941
5942 if (!buffer)
5943 return;
5944
5945 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
5946 device->ws->buffer_destroy(buffer->bo);
5947
5948 vk_object_base_finish(&buffer->base);
5949 vk_free2(&device->vk.alloc, pAllocator, buffer);
5950 }
5951
5952 VkDeviceAddress radv_GetBufferDeviceAddress(
5953 VkDevice device,
5954 const VkBufferDeviceAddressInfo* pInfo)
5955 {
5956 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
5957 return radv_buffer_get_va(buffer->bo) + buffer->offset;
5958 }
5959
5960
5961 uint64_t radv_GetBufferOpaqueCaptureAddress(VkDevice device,
5962 const VkBufferDeviceAddressInfo* pInfo)
5963 {
5964 return 0;
5965 }
5966
5967 uint64_t radv_GetDeviceMemoryOpaqueCaptureAddress(VkDevice device,
5968 const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo)
5969 {
5970 return 0;
5971 }
5972
5973 static inline unsigned
5974 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
5975 {
5976 if (stencil)
5977 return plane->surface.u.legacy.stencil_tiling_index[level];
5978 else
5979 return plane->surface.u.legacy.tiling_index[level];
5980 }
5981
5982 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
5983 {
5984 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
5985 }
5986
5987 static uint32_t
5988 radv_init_dcc_control_reg(struct radv_device *device,
5989 struct radv_image_view *iview)
5990 {
5991 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
5992 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
5993 unsigned max_compressed_block_size;
5994 unsigned independent_128b_blocks;
5995 unsigned independent_64b_blocks;
5996
5997 if (!radv_dcc_enabled(iview->image, iview->base_mip))
5998 return 0;
5999
6000 if (!device->physical_device->rad_info.has_dedicated_vram) {
6001 /* amdvlk: [min-compressed-block-size] should be set to 32 for
6002 * dGPU and 64 for APU because all of our APUs to date use
6003 * DIMMs which have a request granularity size of 64B while all
6004 * other chips have a 32B request size.
6005 */
6006 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
6007 }
6008
6009 if (device->physical_device->rad_info.chip_class >= GFX10) {
6010 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6011 independent_64b_blocks = 0;
6012 independent_128b_blocks = 1;
6013 } else {
6014 independent_128b_blocks = 0;
6015
6016 if (iview->image->info.samples > 1) {
6017 if (iview->image->planes[0].surface.bpe == 1)
6018 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6019 else if (iview->image->planes[0].surface.bpe == 2)
6020 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6021 }
6022
6023 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
6024 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
6025 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
6026 /* If this DCC image is potentially going to be used in texture
6027 * fetches, we need some special settings.
6028 */
6029 independent_64b_blocks = 1;
6030 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6031 } else {
6032 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
6033 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
6034 * big as possible for better compression state.
6035 */
6036 independent_64b_blocks = 0;
6037 max_compressed_block_size = max_uncompressed_block_size;
6038 }
6039 }
6040
6041 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
6042 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
6043 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
6044 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
6045 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
6046 }
6047
6048 void
6049 radv_initialise_color_surface(struct radv_device *device,
6050 struct radv_color_buffer_info *cb,
6051 struct radv_image_view *iview)
6052 {
6053 const struct vk_format_description *desc;
6054 unsigned ntype, format, swap, endian;
6055 unsigned blend_clamp = 0, blend_bypass = 0;
6056 uint64_t va;
6057 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
6058 const struct radeon_surf *surf = &plane->surface;
6059
6060 desc = vk_format_description(iview->vk_format);
6061
6062 memset(cb, 0, sizeof(*cb));
6063
6064 /* Intensity is implemented as Red, so treat it that way. */
6065 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
6066
6067 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
6068
6069 cb->cb_color_base = va >> 8;
6070
6071 if (device->physical_device->rad_info.chip_class >= GFX9) {
6072 if (device->physical_device->rad_info.chip_class >= GFX10) {
6073 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6074 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6075 S_028EE0_CMASK_PIPE_ALIGNED(1) |
6076 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
6077 } else {
6078 struct gfx9_surf_meta_flags meta = {
6079 .rb_aligned = 1,
6080 .pipe_aligned = 1,
6081 };
6082
6083 if (surf->dcc_offset)
6084 meta = surf->u.gfx9.dcc;
6085
6086 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6087 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6088 S_028C74_RB_ALIGNED(meta.rb_aligned) |
6089 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
6090 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
6091 }
6092
6093 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
6094 cb->cb_color_base |= surf->tile_swizzle;
6095 } else {
6096 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
6097 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
6098
6099 cb->cb_color_base += level_info->offset >> 8;
6100 if (level_info->mode == RADEON_SURF_MODE_2D)
6101 cb->cb_color_base |= surf->tile_swizzle;
6102
6103 pitch_tile_max = level_info->nblk_x / 8 - 1;
6104 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
6105 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
6106
6107 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
6108 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
6109 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
6110
6111 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
6112
6113 if (radv_image_has_fmask(iview->image)) {
6114 if (device->physical_device->rad_info.chip_class >= GFX7)
6115 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
6116 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
6117 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
6118 } else {
6119 /* This must be set for fast clear to work without FMASK. */
6120 if (device->physical_device->rad_info.chip_class >= GFX7)
6121 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
6122 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
6123 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
6124 }
6125 }
6126
6127 /* CMASK variables */
6128 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6129 va += surf->cmask_offset;
6130 cb->cb_color_cmask = va >> 8;
6131
6132 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6133 va += surf->dcc_offset;
6134
6135 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
6136 device->physical_device->rad_info.chip_class <= GFX8)
6137 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
6138
6139 unsigned dcc_tile_swizzle = surf->tile_swizzle;
6140 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
6141
6142 cb->cb_dcc_base = va >> 8;
6143 cb->cb_dcc_base |= dcc_tile_swizzle;
6144
6145 /* GFX10 field has the same base shift as the GFX6 field. */
6146 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6147 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
6148 S_028C6C_SLICE_MAX_GFX10(max_slice);
6149
6150 if (iview->image->info.samples > 1) {
6151 unsigned log_samples = util_logbase2(iview->image->info.samples);
6152
6153 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
6154 S_028C74_NUM_FRAGMENTS(log_samples);
6155 }
6156
6157 if (radv_image_has_fmask(iview->image)) {
6158 va = radv_buffer_get_va(iview->bo) + iview->image->offset + surf->fmask_offset;
6159 cb->cb_color_fmask = va >> 8;
6160 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
6161 } else {
6162 cb->cb_color_fmask = cb->cb_color_base;
6163 }
6164
6165 ntype = radv_translate_color_numformat(iview->vk_format,
6166 desc,
6167 vk_format_get_first_non_void_channel(iview->vk_format));
6168 format = radv_translate_colorformat(iview->vk_format);
6169 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
6170 radv_finishme("Illegal color\n");
6171 swap = radv_translate_colorswap(iview->vk_format, false);
6172 endian = radv_colorformat_endian_swap(format);
6173
6174 /* blend clamp should be set for all NORM/SRGB types */
6175 if (ntype == V_028C70_NUMBER_UNORM ||
6176 ntype == V_028C70_NUMBER_SNORM ||
6177 ntype == V_028C70_NUMBER_SRGB)
6178 blend_clamp = 1;
6179
6180 /* set blend bypass according to docs if SINT/UINT or
6181 8/24 COLOR variants */
6182 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
6183 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
6184 format == V_028C70_COLOR_X24_8_32_FLOAT) {
6185 blend_clamp = 0;
6186 blend_bypass = 1;
6187 }
6188 #if 0
6189 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
6190 (format == V_028C70_COLOR_8 ||
6191 format == V_028C70_COLOR_8_8 ||
6192 format == V_028C70_COLOR_8_8_8_8))
6193 ->color_is_int8 = true;
6194 #endif
6195 cb->cb_color_info = S_028C70_FORMAT(format) |
6196 S_028C70_COMP_SWAP(swap) |
6197 S_028C70_BLEND_CLAMP(blend_clamp) |
6198 S_028C70_BLEND_BYPASS(blend_bypass) |
6199 S_028C70_SIMPLE_FLOAT(1) |
6200 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
6201 ntype != V_028C70_NUMBER_SNORM &&
6202 ntype != V_028C70_NUMBER_SRGB &&
6203 format != V_028C70_COLOR_8_24 &&
6204 format != V_028C70_COLOR_24_8) |
6205 S_028C70_NUMBER_TYPE(ntype) |
6206 S_028C70_ENDIAN(endian);
6207 if (radv_image_has_fmask(iview->image)) {
6208 cb->cb_color_info |= S_028C70_COMPRESSION(1);
6209 if (device->physical_device->rad_info.chip_class == GFX6) {
6210 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
6211 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
6212 }
6213
6214 if (radv_image_is_tc_compat_cmask(iview->image)) {
6215 /* Allow the texture block to read FMASK directly
6216 * without decompressing it. This bit must be cleared
6217 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
6218 * otherwise the operation doesn't happen.
6219 */
6220 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
6221
6222 /* Set CMASK into a tiling format that allows the
6223 * texture block to read it.
6224 */
6225 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
6226 }
6227 }
6228
6229 if (radv_image_has_cmask(iview->image) &&
6230 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
6231 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
6232
6233 if (radv_dcc_enabled(iview->image, iview->base_mip))
6234 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
6235
6236 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
6237
6238 /* This must be set for fast clear to work without FMASK. */
6239 if (!radv_image_has_fmask(iview->image) &&
6240 device->physical_device->rad_info.chip_class == GFX6) {
6241 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
6242 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
6243 }
6244
6245 if (device->physical_device->rad_info.chip_class >= GFX9) {
6246 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
6247
6248 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
6249 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
6250 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
6251 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
6252
6253 if (device->physical_device->rad_info.chip_class >= GFX10) {
6254 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
6255
6256 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
6257 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
6258 S_028EE0_RESOURCE_LEVEL(1);
6259 } else {
6260 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
6261 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
6262 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
6263 }
6264
6265 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
6266 S_028C68_MIP0_HEIGHT(height - 1) |
6267 S_028C68_MAX_MIP(iview->image->info.levels - 1);
6268 }
6269 }
6270
6271 static unsigned
6272 radv_calc_decompress_on_z_planes(struct radv_device *device,
6273 struct radv_image_view *iview)
6274 {
6275 unsigned max_zplanes = 0;
6276
6277 assert(radv_image_is_tc_compat_htile(iview->image));
6278
6279 if (device->physical_device->rad_info.chip_class >= GFX9) {
6280 /* Default value for 32-bit depth surfaces. */
6281 max_zplanes = 4;
6282
6283 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
6284 iview->image->info.samples > 1)
6285 max_zplanes = 2;
6286
6287 max_zplanes = max_zplanes + 1;
6288 } else {
6289 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
6290 /* Do not enable Z plane compression for 16-bit depth
6291 * surfaces because isn't supported on GFX8. Only
6292 * 32-bit depth surfaces are supported by the hardware.
6293 * This allows to maintain shader compatibility and to
6294 * reduce the number of depth decompressions.
6295 */
6296 max_zplanes = 1;
6297 } else {
6298 if (iview->image->info.samples <= 1)
6299 max_zplanes = 5;
6300 else if (iview->image->info.samples <= 4)
6301 max_zplanes = 3;
6302 else
6303 max_zplanes = 2;
6304 }
6305 }
6306
6307 return max_zplanes;
6308 }
6309
6310 void
6311 radv_initialise_ds_surface(struct radv_device *device,
6312 struct radv_ds_buffer_info *ds,
6313 struct radv_image_view *iview)
6314 {
6315 unsigned level = iview->base_mip;
6316 unsigned format, stencil_format;
6317 uint64_t va, s_offs, z_offs;
6318 bool stencil_only = false;
6319 const struct radv_image_plane *plane = &iview->image->planes[0];
6320 const struct radeon_surf *surf = &plane->surface;
6321
6322 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
6323
6324 memset(ds, 0, sizeof(*ds));
6325 switch (iview->image->vk_format) {
6326 case VK_FORMAT_D24_UNORM_S8_UINT:
6327 case VK_FORMAT_X8_D24_UNORM_PACK32:
6328 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
6329 ds->offset_scale = 2.0f;
6330 break;
6331 case VK_FORMAT_D16_UNORM:
6332 case VK_FORMAT_D16_UNORM_S8_UINT:
6333 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
6334 ds->offset_scale = 4.0f;
6335 break;
6336 case VK_FORMAT_D32_SFLOAT:
6337 case VK_FORMAT_D32_SFLOAT_S8_UINT:
6338 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
6339 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
6340 ds->offset_scale = 1.0f;
6341 break;
6342 case VK_FORMAT_S8_UINT:
6343 stencil_only = true;
6344 break;
6345 default:
6346 break;
6347 }
6348
6349 format = radv_translate_dbformat(iview->image->vk_format);
6350 stencil_format = surf->has_stencil ?
6351 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
6352
6353 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6354 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
6355 S_028008_SLICE_MAX(max_slice);
6356 if (device->physical_device->rad_info.chip_class >= GFX10) {
6357 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
6358 S_028008_SLICE_MAX_HI(max_slice >> 11);
6359 }
6360
6361 ds->db_htile_data_base = 0;
6362 ds->db_htile_surface = 0;
6363
6364 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6365 s_offs = z_offs = va;
6366
6367 if (device->physical_device->rad_info.chip_class >= GFX9) {
6368 assert(surf->u.gfx9.surf_offset == 0);
6369 s_offs += surf->u.gfx9.stencil_offset;
6370
6371 ds->db_z_info = S_028038_FORMAT(format) |
6372 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
6373 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6374 S_028038_MAXMIP(iview->image->info.levels - 1) |
6375 S_028038_ZRANGE_PRECISION(1);
6376 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
6377 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
6378
6379 if (device->physical_device->rad_info.chip_class == GFX9) {
6380 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
6381 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
6382 }
6383
6384 ds->db_depth_view |= S_028008_MIPID(level);
6385 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
6386 S_02801C_Y_MAX(iview->image->info.height - 1);
6387
6388 if (radv_htile_enabled(iview->image, level)) {
6389 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
6390
6391 if (radv_image_is_tc_compat_htile(iview->image)) {
6392 unsigned max_zplanes =
6393 radv_calc_decompress_on_z_planes(device, iview);
6394
6395 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6396
6397 if (device->physical_device->rad_info.chip_class >= GFX10) {
6398 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
6399 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
6400 } else {
6401 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
6402 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
6403 }
6404 }
6405
6406 if (!surf->has_stencil)
6407 /* Use all of the htile_buffer for depth if there's no stencil. */
6408 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
6409 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6410 surf->htile_offset;
6411 ds->db_htile_data_base = va >> 8;
6412 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
6413 S_028ABC_PIPE_ALIGNED(1);
6414
6415 if (device->physical_device->rad_info.chip_class == GFX9) {
6416 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(1);
6417 }
6418 }
6419 } else {
6420 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
6421
6422 if (stencil_only)
6423 level_info = &surf->u.legacy.stencil_level[level];
6424
6425 z_offs += surf->u.legacy.level[level].offset;
6426 s_offs += surf->u.legacy.stencil_level[level].offset;
6427
6428 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
6429 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
6430 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
6431
6432 if (iview->image->info.samples > 1)
6433 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
6434
6435 if (device->physical_device->rad_info.chip_class >= GFX7) {
6436 struct radeon_info *info = &device->physical_device->rad_info;
6437 unsigned tiling_index = surf->u.legacy.tiling_index[level];
6438 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
6439 unsigned macro_index = surf->u.legacy.macro_tile_index;
6440 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
6441 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
6442 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
6443
6444 if (stencil_only)
6445 tile_mode = stencil_tile_mode;
6446
6447 ds->db_depth_info |=
6448 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
6449 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
6450 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
6451 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
6452 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
6453 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
6454 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
6455 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
6456 } else {
6457 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
6458 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
6459 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
6460 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
6461 if (stencil_only)
6462 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
6463 }
6464
6465 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
6466 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
6467 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
6468
6469 if (radv_htile_enabled(iview->image, level)) {
6470 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
6471
6472 if (!surf->has_stencil &&
6473 !radv_image_is_tc_compat_htile(iview->image))
6474 /* Use all of the htile_buffer for depth if there's no stencil. */
6475 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
6476
6477 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6478 surf->htile_offset;
6479 ds->db_htile_data_base = va >> 8;
6480 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
6481
6482 if (radv_image_is_tc_compat_htile(iview->image)) {
6483 unsigned max_zplanes =
6484 radv_calc_decompress_on_z_planes(device, iview);
6485
6486 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
6487 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6488 }
6489 }
6490 }
6491
6492 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
6493 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
6494 }
6495
6496 VkResult radv_CreateFramebuffer(
6497 VkDevice _device,
6498 const VkFramebufferCreateInfo* pCreateInfo,
6499 const VkAllocationCallbacks* pAllocator,
6500 VkFramebuffer* pFramebuffer)
6501 {
6502 RADV_FROM_HANDLE(radv_device, device, _device);
6503 struct radv_framebuffer *framebuffer;
6504 const VkFramebufferAttachmentsCreateInfo *imageless_create_info =
6505 vk_find_struct_const(pCreateInfo->pNext,
6506 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO);
6507
6508 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
6509
6510 size_t size = sizeof(*framebuffer);
6511 if (!imageless_create_info)
6512 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
6513 framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
6514 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6515 if (framebuffer == NULL)
6516 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6517
6518 vk_object_base_init(&device->vk, &framebuffer->base,
6519 VK_OBJECT_TYPE_FRAMEBUFFER);
6520
6521 framebuffer->attachment_count = pCreateInfo->attachmentCount;
6522 framebuffer->width = pCreateInfo->width;
6523 framebuffer->height = pCreateInfo->height;
6524 framebuffer->layers = pCreateInfo->layers;
6525 if (imageless_create_info) {
6526 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
6527 const VkFramebufferAttachmentImageInfo *attachment =
6528 imageless_create_info->pAttachmentImageInfos + i;
6529 framebuffer->width = MIN2(framebuffer->width, attachment->width);
6530 framebuffer->height = MIN2(framebuffer->height, attachment->height);
6531 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
6532 }
6533 } else {
6534 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
6535 VkImageView _iview = pCreateInfo->pAttachments[i];
6536 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
6537 framebuffer->attachments[i] = iview;
6538 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
6539 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
6540 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
6541 }
6542 }
6543
6544 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
6545 return VK_SUCCESS;
6546 }
6547
6548 void radv_DestroyFramebuffer(
6549 VkDevice _device,
6550 VkFramebuffer _fb,
6551 const VkAllocationCallbacks* pAllocator)
6552 {
6553 RADV_FROM_HANDLE(radv_device, device, _device);
6554 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
6555
6556 if (!fb)
6557 return;
6558 vk_object_base_finish(&fb->base);
6559 vk_free2(&device->vk.alloc, pAllocator, fb);
6560 }
6561
6562 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
6563 {
6564 switch (address_mode) {
6565 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
6566 return V_008F30_SQ_TEX_WRAP;
6567 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
6568 return V_008F30_SQ_TEX_MIRROR;
6569 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
6570 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
6571 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
6572 return V_008F30_SQ_TEX_CLAMP_BORDER;
6573 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
6574 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
6575 default:
6576 unreachable("illegal tex wrap mode");
6577 break;
6578 }
6579 }
6580
6581 static unsigned
6582 radv_tex_compare(VkCompareOp op)
6583 {
6584 switch (op) {
6585 case VK_COMPARE_OP_NEVER:
6586 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
6587 case VK_COMPARE_OP_LESS:
6588 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
6589 case VK_COMPARE_OP_EQUAL:
6590 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
6591 case VK_COMPARE_OP_LESS_OR_EQUAL:
6592 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
6593 case VK_COMPARE_OP_GREATER:
6594 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
6595 case VK_COMPARE_OP_NOT_EQUAL:
6596 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
6597 case VK_COMPARE_OP_GREATER_OR_EQUAL:
6598 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
6599 case VK_COMPARE_OP_ALWAYS:
6600 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
6601 default:
6602 unreachable("illegal compare mode");
6603 break;
6604 }
6605 }
6606
6607 static unsigned
6608 radv_tex_filter(VkFilter filter, unsigned max_ansio)
6609 {
6610 switch (filter) {
6611 case VK_FILTER_NEAREST:
6612 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
6613 V_008F38_SQ_TEX_XY_FILTER_POINT);
6614 case VK_FILTER_LINEAR:
6615 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
6616 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
6617 case VK_FILTER_CUBIC_IMG:
6618 default:
6619 fprintf(stderr, "illegal texture filter");
6620 return 0;
6621 }
6622 }
6623
6624 static unsigned
6625 radv_tex_mipfilter(VkSamplerMipmapMode mode)
6626 {
6627 switch (mode) {
6628 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
6629 return V_008F38_SQ_TEX_Z_FILTER_POINT;
6630 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
6631 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
6632 default:
6633 return V_008F38_SQ_TEX_Z_FILTER_NONE;
6634 }
6635 }
6636
6637 static unsigned
6638 radv_tex_bordercolor(VkBorderColor bcolor)
6639 {
6640 switch (bcolor) {
6641 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
6642 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
6643 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
6644 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
6645 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
6646 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
6647 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
6648 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
6649 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
6650 case VK_BORDER_COLOR_FLOAT_CUSTOM_EXT:
6651 case VK_BORDER_COLOR_INT_CUSTOM_EXT:
6652 return V_008F3C_SQ_TEX_BORDER_COLOR_REGISTER;
6653 default:
6654 break;
6655 }
6656 return 0;
6657 }
6658
6659 static unsigned
6660 radv_tex_aniso_filter(unsigned filter)
6661 {
6662 if (filter < 2)
6663 return 0;
6664 if (filter < 4)
6665 return 1;
6666 if (filter < 8)
6667 return 2;
6668 if (filter < 16)
6669 return 3;
6670 return 4;
6671 }
6672
6673 static unsigned
6674 radv_tex_filter_mode(VkSamplerReductionMode mode)
6675 {
6676 switch (mode) {
6677 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
6678 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
6679 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
6680 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
6681 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
6682 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
6683 default:
6684 break;
6685 }
6686 return 0;
6687 }
6688
6689 static uint32_t
6690 radv_get_max_anisotropy(struct radv_device *device,
6691 const VkSamplerCreateInfo *pCreateInfo)
6692 {
6693 if (device->force_aniso >= 0)
6694 return device->force_aniso;
6695
6696 if (pCreateInfo->anisotropyEnable &&
6697 pCreateInfo->maxAnisotropy > 1.0f)
6698 return (uint32_t)pCreateInfo->maxAnisotropy;
6699
6700 return 0;
6701 }
6702
6703 static inline int S_FIXED(float value, unsigned frac_bits)
6704 {
6705 return value * (1 << frac_bits);
6706 }
6707
6708 static uint32_t radv_register_border_color(struct radv_device *device,
6709 VkClearColorValue value)
6710 {
6711 uint32_t slot;
6712
6713 pthread_mutex_lock(&device->border_color_data.mutex);
6714
6715 for (slot = 0; slot < RADV_BORDER_COLOR_COUNT; slot++) {
6716 if (!device->border_color_data.used[slot]) {
6717 /* Copy to the GPU wrt endian-ness. */
6718 util_memcpy_cpu_to_le32(&device->border_color_data.colors_gpu_ptr[slot],
6719 &value,
6720 sizeof(VkClearColorValue));
6721
6722 device->border_color_data.used[slot] = true;
6723 break;
6724 }
6725 }
6726
6727 pthread_mutex_unlock(&device->border_color_data.mutex);
6728
6729 return slot;
6730 }
6731
6732 static void radv_unregister_border_color(struct radv_device *device,
6733 uint32_t slot)
6734 {
6735 pthread_mutex_lock(&device->border_color_data.mutex);
6736
6737 device->border_color_data.used[slot] = false;
6738
6739 pthread_mutex_unlock(&device->border_color_data.mutex);
6740 }
6741
6742 static void
6743 radv_init_sampler(struct radv_device *device,
6744 struct radv_sampler *sampler,
6745 const VkSamplerCreateInfo *pCreateInfo)
6746 {
6747 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
6748 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
6749 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
6750 device->physical_device->rad_info.chip_class == GFX9;
6751 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
6752 unsigned depth_compare_func = V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
6753 bool trunc_coord = pCreateInfo->minFilter == VK_FILTER_NEAREST && pCreateInfo->magFilter == VK_FILTER_NEAREST;
6754 bool uses_border_color = pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
6755 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
6756 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
6757 VkBorderColor border_color = uses_border_color ? pCreateInfo->borderColor : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
6758 uint32_t border_color_ptr;
6759
6760 const struct VkSamplerReductionModeCreateInfo *sampler_reduction =
6761 vk_find_struct_const(pCreateInfo->pNext,
6762 SAMPLER_REDUCTION_MODE_CREATE_INFO);
6763 if (sampler_reduction)
6764 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
6765
6766 if (pCreateInfo->compareEnable)
6767 depth_compare_func = radv_tex_compare(pCreateInfo->compareOp);
6768
6769 sampler->border_color_slot = RADV_BORDER_COLOR_COUNT;
6770
6771 if (border_color == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT || border_color == VK_BORDER_COLOR_INT_CUSTOM_EXT) {
6772 const VkSamplerCustomBorderColorCreateInfoEXT *custom_border_color =
6773 vk_find_struct_const(pCreateInfo->pNext,
6774 SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT);
6775
6776 assert(custom_border_color);
6777
6778 sampler->border_color_slot =
6779 radv_register_border_color(device, custom_border_color->customBorderColor);
6780
6781 /* Did we fail to find a slot? */
6782 if (sampler->border_color_slot == RADV_BORDER_COLOR_COUNT) {
6783 fprintf(stderr, "WARNING: no free border color slots, defaulting to TRANS_BLACK.\n");
6784 border_color = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
6785 }
6786 }
6787
6788 /* If we don't have a custom color, set the ptr to 0 */
6789 border_color_ptr = sampler->border_color_slot != RADV_BORDER_COLOR_COUNT
6790 ? sampler->border_color_slot
6791 : 0;
6792
6793 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
6794 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
6795 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
6796 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
6797 S_008F30_DEPTH_COMPARE_FUNC(depth_compare_func) |
6798 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
6799 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
6800 S_008F30_ANISO_BIAS(max_aniso_ratio) |
6801 S_008F30_DISABLE_CUBE_WRAP(0) |
6802 S_008F30_COMPAT_MODE(compat_mode) |
6803 S_008F30_FILTER_MODE(filter_mode) |
6804 S_008F30_TRUNC_COORD(trunc_coord));
6805 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
6806 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
6807 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
6808 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
6809 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
6810 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
6811 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
6812 S_008F38_MIP_POINT_PRECLAMP(0));
6813 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(border_color_ptr) |
6814 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(border_color)));
6815
6816 if (device->physical_device->rad_info.chip_class >= GFX10) {
6817 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
6818 } else {
6819 sampler->state[2] |=
6820 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
6821 S_008F38_FILTER_PREC_FIX(1) |
6822 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
6823 }
6824 }
6825
6826 VkResult radv_CreateSampler(
6827 VkDevice _device,
6828 const VkSamplerCreateInfo* pCreateInfo,
6829 const VkAllocationCallbacks* pAllocator,
6830 VkSampler* pSampler)
6831 {
6832 RADV_FROM_HANDLE(radv_device, device, _device);
6833 struct radv_sampler *sampler;
6834
6835 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
6836 vk_find_struct_const(pCreateInfo->pNext,
6837 SAMPLER_YCBCR_CONVERSION_INFO);
6838
6839 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
6840
6841 sampler = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*sampler), 8,
6842 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6843 if (!sampler)
6844 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6845
6846 vk_object_base_init(&device->vk, &sampler->base,
6847 VK_OBJECT_TYPE_SAMPLER);
6848
6849 radv_init_sampler(device, sampler, pCreateInfo);
6850
6851 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
6852 *pSampler = radv_sampler_to_handle(sampler);
6853
6854 return VK_SUCCESS;
6855 }
6856
6857 void radv_DestroySampler(
6858 VkDevice _device,
6859 VkSampler _sampler,
6860 const VkAllocationCallbacks* pAllocator)
6861 {
6862 RADV_FROM_HANDLE(radv_device, device, _device);
6863 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
6864
6865 if (!sampler)
6866 return;
6867
6868 if (sampler->border_color_slot != RADV_BORDER_COLOR_COUNT)
6869 radv_unregister_border_color(device, sampler->border_color_slot);
6870
6871 vk_object_base_finish(&sampler->base);
6872 vk_free2(&device->vk.alloc, pAllocator, sampler);
6873 }
6874
6875 /* vk_icd.h does not declare this function, so we declare it here to
6876 * suppress Wmissing-prototypes.
6877 */
6878 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
6879 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
6880
6881 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
6882 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
6883 {
6884 /* For the full details on loader interface versioning, see
6885 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
6886 * What follows is a condensed summary, to help you navigate the large and
6887 * confusing official doc.
6888 *
6889 * - Loader interface v0 is incompatible with later versions. We don't
6890 * support it.
6891 *
6892 * - In loader interface v1:
6893 * - The first ICD entrypoint called by the loader is
6894 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
6895 * entrypoint.
6896 * - The ICD must statically expose no other Vulkan symbol unless it is
6897 * linked with -Bsymbolic.
6898 * - Each dispatchable Vulkan handle created by the ICD must be
6899 * a pointer to a struct whose first member is VK_LOADER_DATA. The
6900 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
6901 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
6902 * vkDestroySurfaceKHR(). The ICD must be capable of working with
6903 * such loader-managed surfaces.
6904 *
6905 * - Loader interface v2 differs from v1 in:
6906 * - The first ICD entrypoint called by the loader is
6907 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
6908 * statically expose this entrypoint.
6909 *
6910 * - Loader interface v3 differs from v2 in:
6911 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
6912 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
6913 * because the loader no longer does so.
6914 */
6915 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
6916 return VK_SUCCESS;
6917 }
6918
6919 VkResult radv_GetMemoryFdKHR(VkDevice _device,
6920 const VkMemoryGetFdInfoKHR *pGetFdInfo,
6921 int *pFD)
6922 {
6923 RADV_FROM_HANDLE(radv_device, device, _device);
6924 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
6925
6926 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
6927
6928 /* At the moment, we support only the below handle types. */
6929 assert(pGetFdInfo->handleType ==
6930 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
6931 pGetFdInfo->handleType ==
6932 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
6933
6934 bool ret = radv_get_memory_fd(device, memory, pFD);
6935 if (ret == false)
6936 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6937 return VK_SUCCESS;
6938 }
6939
6940 static uint32_t radv_compute_valid_memory_types_attempt(struct radv_physical_device *dev,
6941 enum radeon_bo_domain domains,
6942 enum radeon_bo_flag flags,
6943 enum radeon_bo_flag ignore_flags)
6944 {
6945 /* Don't count GTT/CPU as relevant:
6946 *
6947 * - We're not fully consistent between the two.
6948 * - Sometimes VRAM gets VRAM|GTT.
6949 */
6950 const enum radeon_bo_domain relevant_domains = RADEON_DOMAIN_VRAM |
6951 RADEON_DOMAIN_GDS |
6952 RADEON_DOMAIN_OA;
6953 uint32_t bits = 0;
6954 for (unsigned i = 0; i < dev->memory_properties.memoryTypeCount; ++i) {
6955 if ((domains & relevant_domains) != (dev->memory_domains[i] & relevant_domains))
6956 continue;
6957
6958 if ((flags & ~ignore_flags) != (dev->memory_flags[i] & ~ignore_flags))
6959 continue;
6960
6961 bits |= 1u << i;
6962 }
6963
6964 return bits;
6965 }
6966
6967 static uint32_t radv_compute_valid_memory_types(struct radv_physical_device *dev,
6968 enum radeon_bo_domain domains,
6969 enum radeon_bo_flag flags)
6970 {
6971 enum radeon_bo_flag ignore_flags = ~(RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_GTT_WC);
6972 uint32_t bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
6973
6974 if (!bits) {
6975 ignore_flags |= RADEON_FLAG_NO_CPU_ACCESS;
6976 bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
6977 }
6978
6979 return bits;
6980 }
6981 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
6982 VkExternalMemoryHandleTypeFlagBits handleType,
6983 int fd,
6984 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
6985 {
6986 RADV_FROM_HANDLE(radv_device, device, _device);
6987
6988 switch (handleType) {
6989 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT: {
6990 enum radeon_bo_domain domains;
6991 enum radeon_bo_flag flags;
6992 if (!device->ws->buffer_get_flags_from_fd(device->ws, fd, &domains, &flags))
6993 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
6994
6995 pMemoryFdProperties->memoryTypeBits = radv_compute_valid_memory_types(device->physical_device, domains, flags);
6996 return VK_SUCCESS;
6997 }
6998 default:
6999 /* The valid usage section for this function says:
7000 *
7001 * "handleType must not be one of the handle types defined as
7002 * opaque."
7003 *
7004 * So opaque handle types fall into the default "unsupported" case.
7005 */
7006 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7007 }
7008 }
7009
7010 static VkResult radv_import_opaque_fd(struct radv_device *device,
7011 int fd,
7012 uint32_t *syncobj)
7013 {
7014 uint32_t syncobj_handle = 0;
7015 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
7016 if (ret != 0)
7017 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7018
7019 if (*syncobj)
7020 device->ws->destroy_syncobj(device->ws, *syncobj);
7021
7022 *syncobj = syncobj_handle;
7023 close(fd);
7024
7025 return VK_SUCCESS;
7026 }
7027
7028 static VkResult radv_import_sync_fd(struct radv_device *device,
7029 int fd,
7030 uint32_t *syncobj)
7031 {
7032 /* If we create a syncobj we do it locally so that if we have an error, we don't
7033 * leave a syncobj in an undetermined state in the fence. */
7034 uint32_t syncobj_handle = *syncobj;
7035 if (!syncobj_handle) {
7036 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
7037 if (ret) {
7038 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7039 }
7040 }
7041
7042 if (fd == -1) {
7043 device->ws->signal_syncobj(device->ws, syncobj_handle);
7044 } else {
7045 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
7046 if (ret != 0)
7047 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7048 }
7049
7050 *syncobj = syncobj_handle;
7051 if (fd != -1)
7052 close(fd);
7053
7054 return VK_SUCCESS;
7055 }
7056
7057 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
7058 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
7059 {
7060 RADV_FROM_HANDLE(radv_device, device, _device);
7061 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
7062 VkResult result;
7063 struct radv_semaphore_part *dst = NULL;
7064
7065 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
7066 dst = &sem->temporary;
7067 } else {
7068 dst = &sem->permanent;
7069 }
7070
7071 uint32_t syncobj = dst->kind == RADV_SEMAPHORE_SYNCOBJ ? dst->syncobj : 0;
7072
7073 switch(pImportSemaphoreFdInfo->handleType) {
7074 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7075 result = radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7076 break;
7077 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7078 result = radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7079 break;
7080 default:
7081 unreachable("Unhandled semaphore handle type");
7082 }
7083
7084 if (result == VK_SUCCESS) {
7085 dst->syncobj = syncobj;
7086 dst->kind = RADV_SEMAPHORE_SYNCOBJ;
7087 }
7088
7089 return result;
7090 }
7091
7092 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
7093 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
7094 int *pFd)
7095 {
7096 RADV_FROM_HANDLE(radv_device, device, _device);
7097 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
7098 int ret;
7099 uint32_t syncobj_handle;
7100
7101 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7102 assert(sem->temporary.kind == RADV_SEMAPHORE_SYNCOBJ);
7103 syncobj_handle = sem->temporary.syncobj;
7104 } else {
7105 assert(sem->permanent.kind == RADV_SEMAPHORE_SYNCOBJ);
7106 syncobj_handle = sem->permanent.syncobj;
7107 }
7108
7109 switch(pGetFdInfo->handleType) {
7110 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7111 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7112 break;
7113 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7114 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7115 if (!ret) {
7116 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7117 radv_destroy_semaphore_part(device, &sem->temporary);
7118 } else {
7119 device->ws->reset_syncobj(device->ws, syncobj_handle);
7120 }
7121 }
7122 break;
7123 default:
7124 unreachable("Unhandled semaphore handle type");
7125 }
7126
7127 if (ret)
7128 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7129 return VK_SUCCESS;
7130 }
7131
7132 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
7133 VkPhysicalDevice physicalDevice,
7134 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
7135 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
7136 {
7137 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7138 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pExternalSemaphoreInfo->pNext, NULL);
7139
7140 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
7141 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7142 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7143 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7144
7145 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
7146 } else if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7147 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7148 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
7149 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7150 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7151 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7152 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7153 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
7154 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7155 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7156 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7157 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7158 } else {
7159 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7160 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7161 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7162 }
7163 }
7164
7165 VkResult radv_ImportFenceFdKHR(VkDevice _device,
7166 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
7167 {
7168 RADV_FROM_HANDLE(radv_device, device, _device);
7169 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
7170 uint32_t *syncobj_dst = NULL;
7171
7172
7173 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
7174 syncobj_dst = &fence->temp_syncobj;
7175 } else {
7176 syncobj_dst = &fence->syncobj;
7177 }
7178
7179 switch(pImportFenceFdInfo->handleType) {
7180 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7181 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7182 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7183 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7184 default:
7185 unreachable("Unhandled fence handle type");
7186 }
7187 }
7188
7189 VkResult radv_GetFenceFdKHR(VkDevice _device,
7190 const VkFenceGetFdInfoKHR *pGetFdInfo,
7191 int *pFd)
7192 {
7193 RADV_FROM_HANDLE(radv_device, device, _device);
7194 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
7195 int ret;
7196 uint32_t syncobj_handle;
7197
7198 if (fence->temp_syncobj)
7199 syncobj_handle = fence->temp_syncobj;
7200 else
7201 syncobj_handle = fence->syncobj;
7202
7203 switch(pGetFdInfo->handleType) {
7204 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7205 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7206 break;
7207 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7208 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7209 if (!ret) {
7210 if (fence->temp_syncobj) {
7211 close (fence->temp_syncobj);
7212 fence->temp_syncobj = 0;
7213 } else {
7214 device->ws->reset_syncobj(device->ws, syncobj_handle);
7215 }
7216 }
7217 break;
7218 default:
7219 unreachable("Unhandled fence handle type");
7220 }
7221
7222 if (ret)
7223 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7224 return VK_SUCCESS;
7225 }
7226
7227 void radv_GetPhysicalDeviceExternalFenceProperties(
7228 VkPhysicalDevice physicalDevice,
7229 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
7230 VkExternalFenceProperties *pExternalFenceProperties)
7231 {
7232 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7233
7234 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7235 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7236 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
7237 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7238 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7239 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
7240 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7241 } else {
7242 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
7243 pExternalFenceProperties->compatibleHandleTypes = 0;
7244 pExternalFenceProperties->externalFenceFeatures = 0;
7245 }
7246 }
7247
7248 VkResult
7249 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
7250 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
7251 const VkAllocationCallbacks* pAllocator,
7252 VkDebugReportCallbackEXT* pCallback)
7253 {
7254 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7255 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
7256 pCreateInfo, pAllocator, &instance->alloc,
7257 pCallback);
7258 }
7259
7260 void
7261 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
7262 VkDebugReportCallbackEXT _callback,
7263 const VkAllocationCallbacks* pAllocator)
7264 {
7265 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7266 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
7267 _callback, pAllocator, &instance->alloc);
7268 }
7269
7270 void
7271 radv_DebugReportMessageEXT(VkInstance _instance,
7272 VkDebugReportFlagsEXT flags,
7273 VkDebugReportObjectTypeEXT objectType,
7274 uint64_t object,
7275 size_t location,
7276 int32_t messageCode,
7277 const char* pLayerPrefix,
7278 const char* pMessage)
7279 {
7280 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7281 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
7282 object, location, messageCode, pLayerPrefix, pMessage);
7283 }
7284
7285 void
7286 radv_GetDeviceGroupPeerMemoryFeatures(
7287 VkDevice device,
7288 uint32_t heapIndex,
7289 uint32_t localDeviceIndex,
7290 uint32_t remoteDeviceIndex,
7291 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
7292 {
7293 assert(localDeviceIndex == remoteDeviceIndex);
7294
7295 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
7296 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
7297 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
7298 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
7299 }
7300
7301 static const VkTimeDomainEXT radv_time_domains[] = {
7302 VK_TIME_DOMAIN_DEVICE_EXT,
7303 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
7304 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
7305 };
7306
7307 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
7308 VkPhysicalDevice physicalDevice,
7309 uint32_t *pTimeDomainCount,
7310 VkTimeDomainEXT *pTimeDomains)
7311 {
7312 int d;
7313 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
7314
7315 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
7316 vk_outarray_append(&out, i) {
7317 *i = radv_time_domains[d];
7318 }
7319 }
7320
7321 return vk_outarray_status(&out);
7322 }
7323
7324 static uint64_t
7325 radv_clock_gettime(clockid_t clock_id)
7326 {
7327 struct timespec current;
7328 int ret;
7329
7330 ret = clock_gettime(clock_id, &current);
7331 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
7332 ret = clock_gettime(CLOCK_MONOTONIC, &current);
7333 if (ret < 0)
7334 return 0;
7335
7336 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
7337 }
7338
7339 VkResult radv_GetCalibratedTimestampsEXT(
7340 VkDevice _device,
7341 uint32_t timestampCount,
7342 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
7343 uint64_t *pTimestamps,
7344 uint64_t *pMaxDeviation)
7345 {
7346 RADV_FROM_HANDLE(radv_device, device, _device);
7347 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
7348 int d;
7349 uint64_t begin, end;
7350 uint64_t max_clock_period = 0;
7351
7352 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7353
7354 for (d = 0; d < timestampCount; d++) {
7355 switch (pTimestampInfos[d].timeDomain) {
7356 case VK_TIME_DOMAIN_DEVICE_EXT:
7357 pTimestamps[d] = device->ws->query_value(device->ws,
7358 RADEON_TIMESTAMP);
7359 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
7360 max_clock_period = MAX2(max_clock_period, device_period);
7361 break;
7362 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
7363 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
7364 max_clock_period = MAX2(max_clock_period, 1);
7365 break;
7366
7367 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
7368 pTimestamps[d] = begin;
7369 break;
7370 default:
7371 pTimestamps[d] = 0;
7372 break;
7373 }
7374 }
7375
7376 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7377
7378 /*
7379 * The maximum deviation is the sum of the interval over which we
7380 * perform the sampling and the maximum period of any sampled
7381 * clock. That's because the maximum skew between any two sampled
7382 * clock edges is when the sampled clock with the largest period is
7383 * sampled at the end of that period but right at the beginning of the
7384 * sampling interval and some other clock is sampled right at the
7385 * begining of its sampling period and right at the end of the
7386 * sampling interval. Let's assume the GPU has the longest clock
7387 * period and that the application is sampling GPU and monotonic:
7388 *
7389 * s e
7390 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
7391 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7392 *
7393 * g
7394 * 0 1 2 3
7395 * GPU -----_____-----_____-----_____-----_____
7396 *
7397 * m
7398 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
7399 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7400 *
7401 * Interval <----------------->
7402 * Deviation <-------------------------->
7403 *
7404 * s = read(raw) 2
7405 * g = read(GPU) 1
7406 * m = read(monotonic) 2
7407 * e = read(raw) b
7408 *
7409 * We round the sample interval up by one tick to cover sampling error
7410 * in the interval clock
7411 */
7412
7413 uint64_t sample_interval = end - begin + 1;
7414
7415 *pMaxDeviation = sample_interval + max_clock_period;
7416
7417 return VK_SUCCESS;
7418 }
7419
7420 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
7421 VkPhysicalDevice physicalDevice,
7422 VkSampleCountFlagBits samples,
7423 VkMultisamplePropertiesEXT* pMultisampleProperties)
7424 {
7425 if (samples & (VK_SAMPLE_COUNT_2_BIT |
7426 VK_SAMPLE_COUNT_4_BIT |
7427 VK_SAMPLE_COUNT_8_BIT)) {
7428 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
7429 } else {
7430 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
7431 }
7432 }
7433
7434 VkResult radv_CreatePrivateDataSlotEXT(
7435 VkDevice _device,
7436 const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
7437 const VkAllocationCallbacks* pAllocator,
7438 VkPrivateDataSlotEXT* pPrivateDataSlot)
7439 {
7440 RADV_FROM_HANDLE(radv_device, device, _device);
7441 return vk_private_data_slot_create(&device->vk, pCreateInfo, pAllocator,
7442 pPrivateDataSlot);
7443 }
7444
7445 void radv_DestroyPrivateDataSlotEXT(
7446 VkDevice _device,
7447 VkPrivateDataSlotEXT privateDataSlot,
7448 const VkAllocationCallbacks* pAllocator)
7449 {
7450 RADV_FROM_HANDLE(radv_device, device, _device);
7451 vk_private_data_slot_destroy(&device->vk, privateDataSlot, pAllocator);
7452 }
7453
7454 VkResult radv_SetPrivateDataEXT(
7455 VkDevice _device,
7456 VkObjectType objectType,
7457 uint64_t objectHandle,
7458 VkPrivateDataSlotEXT privateDataSlot,
7459 uint64_t data)
7460 {
7461 RADV_FROM_HANDLE(radv_device, device, _device);
7462 return vk_object_base_set_private_data(&device->vk, objectType,
7463 objectHandle, privateDataSlot,
7464 data);
7465 }
7466
7467 void radv_GetPrivateDataEXT(
7468 VkDevice _device,
7469 VkObjectType objectType,
7470 uint64_t objectHandle,
7471 VkPrivateDataSlotEXT privateDataSlot,
7472 uint64_t* pData)
7473 {
7474 RADV_FROM_HANDLE(radv_device, device, _device);
7475 vk_object_base_get_private_data(&device->vk, objectType, objectHandle,
7476 privateDataSlot, pData);
7477 }