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