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