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