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