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