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