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