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