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