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