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