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