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