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