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