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