radv: remove unnecessary RADV_DEBUG=nobatchchain option
[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 = pdevice->rad_info.chip_class >= GFX8,
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 = pdevice->rad_info.chip_class >= GFX7;
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 = pdevice->rad_info.chip_class >= GFX8 ? sample_counts : VK_SAMPLE_COUNT_1_BIT,
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 (i == 0) {
3903 si_cs_emit_cache_flush(cs,
3904 queue->device->physical_device->rad_info.chip_class,
3905 NULL, 0,
3906 queue->queue_family_index == RING_COMPUTE &&
3907 queue->device->physical_device->rad_info.chip_class >= GFX7,
3908 (queue->queue_family_index == RADV_QUEUE_COMPUTE ? RADV_CMD_FLAG_CS_PARTIAL_FLUSH : (RADV_CMD_FLAG_CS_PARTIAL_FLUSH | RADV_CMD_FLAG_PS_PARTIAL_FLUSH)) |
3909 RADV_CMD_FLAG_INV_ICACHE |
3910 RADV_CMD_FLAG_INV_SCACHE |
3911 RADV_CMD_FLAG_INV_VCACHE |
3912 RADV_CMD_FLAG_INV_L2 |
3913 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3914 } else if (i == 1) {
3915 si_cs_emit_cache_flush(cs,
3916 queue->device->physical_device->rad_info.chip_class,
3917 NULL, 0,
3918 queue->queue_family_index == RING_COMPUTE &&
3919 queue->device->physical_device->rad_info.chip_class >= GFX7,
3920 RADV_CMD_FLAG_INV_ICACHE |
3921 RADV_CMD_FLAG_INV_SCACHE |
3922 RADV_CMD_FLAG_INV_VCACHE |
3923 RADV_CMD_FLAG_INV_L2 |
3924 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3925 }
3926
3927 if (!queue->device->ws->cs_finalize(cs))
3928 goto fail;
3929 }
3930
3931 if (queue->initial_full_flush_preamble_cs)
3932 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
3933
3934 if (queue->initial_preamble_cs)
3935 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
3936
3937 if (queue->continue_preamble_cs)
3938 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
3939
3940 queue->initial_full_flush_preamble_cs = dest_cs[0];
3941 queue->initial_preamble_cs = dest_cs[1];
3942 queue->continue_preamble_cs = dest_cs[2];
3943
3944 if (scratch_bo != queue->scratch_bo) {
3945 if (queue->scratch_bo)
3946 queue->device->ws->buffer_destroy(queue->scratch_bo);
3947 queue->scratch_bo = scratch_bo;
3948 }
3949 queue->scratch_size_per_wave = scratch_size_per_wave;
3950 queue->scratch_waves = scratch_waves;
3951
3952 if (compute_scratch_bo != queue->compute_scratch_bo) {
3953 if (queue->compute_scratch_bo)
3954 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
3955 queue->compute_scratch_bo = compute_scratch_bo;
3956 }
3957 queue->compute_scratch_size_per_wave = compute_scratch_size_per_wave;
3958 queue->compute_scratch_waves = compute_scratch_waves;
3959
3960 if (esgs_ring_bo != queue->esgs_ring_bo) {
3961 if (queue->esgs_ring_bo)
3962 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
3963 queue->esgs_ring_bo = esgs_ring_bo;
3964 queue->esgs_ring_size = esgs_ring_size;
3965 }
3966
3967 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
3968 if (queue->gsvs_ring_bo)
3969 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
3970 queue->gsvs_ring_bo = gsvs_ring_bo;
3971 queue->gsvs_ring_size = gsvs_ring_size;
3972 }
3973
3974 if (tess_rings_bo != queue->tess_rings_bo) {
3975 queue->tess_rings_bo = tess_rings_bo;
3976 queue->has_tess_rings = true;
3977 }
3978
3979 if (gds_bo != queue->gds_bo) {
3980 queue->gds_bo = gds_bo;
3981 queue->has_gds = true;
3982 }
3983
3984 if (gds_oa_bo != queue->gds_oa_bo) {
3985 queue->gds_oa_bo = gds_oa_bo;
3986 queue->has_gds_oa = true;
3987 }
3988
3989 if (descriptor_bo != queue->descriptor_bo) {
3990 if (queue->descriptor_bo)
3991 queue->device->ws->buffer_destroy(queue->descriptor_bo);
3992
3993 queue->descriptor_bo = descriptor_bo;
3994 }
3995
3996 if (add_sample_positions)
3997 queue->has_sample_positions = true;
3998
3999 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
4000 *initial_preamble_cs = queue->initial_preamble_cs;
4001 *continue_preamble_cs = queue->continue_preamble_cs;
4002 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
4003 *continue_preamble_cs = NULL;
4004 return VK_SUCCESS;
4005 fail:
4006 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
4007 if (dest_cs[i])
4008 queue->device->ws->cs_destroy(dest_cs[i]);
4009 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
4010 queue->device->ws->buffer_destroy(descriptor_bo);
4011 if (scratch_bo && scratch_bo != queue->scratch_bo)
4012 queue->device->ws->buffer_destroy(scratch_bo);
4013 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
4014 queue->device->ws->buffer_destroy(compute_scratch_bo);
4015 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
4016 queue->device->ws->buffer_destroy(esgs_ring_bo);
4017 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
4018 queue->device->ws->buffer_destroy(gsvs_ring_bo);
4019 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
4020 queue->device->ws->buffer_destroy(tess_rings_bo);
4021 if (gds_bo && gds_bo != queue->gds_bo)
4022 queue->device->ws->buffer_destroy(gds_bo);
4023 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
4024 queue->device->ws->buffer_destroy(gds_oa_bo);
4025
4026 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4027 }
4028
4029 static VkResult radv_alloc_sem_counts(struct radv_device *device,
4030 struct radv_winsys_sem_counts *counts,
4031 int num_sems,
4032 struct radv_semaphore_part **sems,
4033 const uint64_t *timeline_values,
4034 VkFence _fence,
4035 bool is_signal)
4036 {
4037 int syncobj_idx = 0, sem_idx = 0;
4038
4039 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
4040 return VK_SUCCESS;
4041
4042 for (uint32_t i = 0; i < num_sems; i++) {
4043 switch(sems[i]->kind) {
4044 case RADV_SEMAPHORE_SYNCOBJ:
4045 counts->syncobj_count++;
4046 break;
4047 case RADV_SEMAPHORE_WINSYS:
4048 counts->sem_count++;
4049 break;
4050 case RADV_SEMAPHORE_NONE:
4051 break;
4052 case RADV_SEMAPHORE_TIMELINE:
4053 counts->syncobj_count++;
4054 break;
4055 }
4056 }
4057
4058 if (_fence != VK_NULL_HANDLE) {
4059 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4060 if (fence->temp_syncobj || fence->syncobj)
4061 counts->syncobj_count++;
4062 }
4063
4064 if (counts->syncobj_count) {
4065 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
4066 if (!counts->syncobj)
4067 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4068 }
4069
4070 if (counts->sem_count) {
4071 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
4072 if (!counts->sem) {
4073 free(counts->syncobj);
4074 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4075 }
4076 }
4077
4078 for (uint32_t i = 0; i < num_sems; i++) {
4079 switch(sems[i]->kind) {
4080 case RADV_SEMAPHORE_NONE:
4081 unreachable("Empty semaphore");
4082 break;
4083 case RADV_SEMAPHORE_SYNCOBJ:
4084 counts->syncobj[syncobj_idx++] = sems[i]->syncobj;
4085 break;
4086 case RADV_SEMAPHORE_WINSYS:
4087 counts->sem[sem_idx++] = sems[i]->ws_sem;
4088 break;
4089 case RADV_SEMAPHORE_TIMELINE: {
4090 pthread_mutex_lock(&sems[i]->timeline.mutex);
4091 struct radv_timeline_point *point = NULL;
4092 if (is_signal) {
4093 point = radv_timeline_add_point_locked(device, &sems[i]->timeline, timeline_values[i]);
4094 } else {
4095 point = radv_timeline_find_point_at_least_locked(device, &sems[i]->timeline, timeline_values[i]);
4096 }
4097
4098 pthread_mutex_unlock(&sems[i]->timeline.mutex);
4099
4100 if (point) {
4101 counts->syncobj[syncobj_idx++] = point->syncobj;
4102 } else {
4103 /* Explicitly remove the semaphore so we might not find
4104 * a point later post-submit. */
4105 sems[i] = NULL;
4106 }
4107 break;
4108 }
4109 }
4110 }
4111
4112 if (_fence != VK_NULL_HANDLE) {
4113 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4114 if (fence->temp_syncobj)
4115 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
4116 else if (fence->syncobj)
4117 counts->syncobj[syncobj_idx++] = fence->syncobj;
4118 }
4119
4120 assert(syncobj_idx <= counts->syncobj_count);
4121 counts->syncobj_count = syncobj_idx;
4122
4123 return VK_SUCCESS;
4124 }
4125
4126 static void
4127 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
4128 {
4129 free(sem_info->wait.syncobj);
4130 free(sem_info->wait.sem);
4131 free(sem_info->signal.syncobj);
4132 free(sem_info->signal.sem);
4133 }
4134
4135
4136 static void radv_free_temp_syncobjs(struct radv_device *device,
4137 int num_sems,
4138 struct radv_semaphore_part *sems)
4139 {
4140 for (uint32_t i = 0; i < num_sems; i++) {
4141 radv_destroy_semaphore_part(device, sems + i);
4142 }
4143 }
4144
4145 static VkResult
4146 radv_alloc_sem_info(struct radv_device *device,
4147 struct radv_winsys_sem_info *sem_info,
4148 int num_wait_sems,
4149 struct radv_semaphore_part **wait_sems,
4150 const uint64_t *wait_values,
4151 int num_signal_sems,
4152 struct radv_semaphore_part **signal_sems,
4153 const uint64_t *signal_values,
4154 VkFence fence)
4155 {
4156 VkResult ret;
4157 memset(sem_info, 0, sizeof(*sem_info));
4158
4159 ret = radv_alloc_sem_counts(device, &sem_info->wait, num_wait_sems, wait_sems, wait_values, VK_NULL_HANDLE, false);
4160 if (ret)
4161 return ret;
4162 ret = radv_alloc_sem_counts(device, &sem_info->signal, num_signal_sems, signal_sems, signal_values, fence, true);
4163 if (ret)
4164 radv_free_sem_info(sem_info);
4165
4166 /* caller can override these */
4167 sem_info->cs_emit_wait = true;
4168 sem_info->cs_emit_signal = true;
4169 return ret;
4170 }
4171
4172 static void
4173 radv_finalize_timelines(struct radv_device *device,
4174 uint32_t num_wait_sems,
4175 struct radv_semaphore_part **wait_sems,
4176 const uint64_t *wait_values,
4177 uint32_t num_signal_sems,
4178 struct radv_semaphore_part **signal_sems,
4179 const uint64_t *signal_values,
4180 struct list_head *processing_list)
4181 {
4182 for (uint32_t i = 0; i < num_wait_sems; ++i) {
4183 if (wait_sems[i] && wait_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4184 pthread_mutex_lock(&wait_sems[i]->timeline.mutex);
4185 struct radv_timeline_point *point =
4186 radv_timeline_find_point_at_least_locked(device, &wait_sems[i]->timeline, wait_values[i]);
4187 point->wait_count -= 2;
4188 pthread_mutex_unlock(&wait_sems[i]->timeline.mutex);
4189 }
4190 }
4191 for (uint32_t i = 0; i < num_signal_sems; ++i) {
4192 if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4193 pthread_mutex_lock(&signal_sems[i]->timeline.mutex);
4194 struct radv_timeline_point *point =
4195 radv_timeline_find_point_at_least_locked(device, &signal_sems[i]->timeline, signal_values[i]);
4196 signal_sems[i]->timeline.highest_submitted =
4197 MAX2(signal_sems[i]->timeline.highest_submitted, point->value);
4198 point->wait_count -= 2;
4199 radv_timeline_trigger_waiters_locked(&signal_sems[i]->timeline, processing_list);
4200 pthread_mutex_unlock(&signal_sems[i]->timeline.mutex);
4201 }
4202 }
4203 }
4204
4205 static void
4206 radv_sparse_buffer_bind_memory(struct radv_device *device,
4207 const VkSparseBufferMemoryBindInfo *bind)
4208 {
4209 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
4210
4211 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4212 struct radv_device_memory *mem = NULL;
4213
4214 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4215 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4216
4217 device->ws->buffer_virtual_bind(buffer->bo,
4218 bind->pBinds[i].resourceOffset,
4219 bind->pBinds[i].size,
4220 mem ? mem->bo : NULL,
4221 bind->pBinds[i].memoryOffset);
4222 }
4223 }
4224
4225 static void
4226 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
4227 const VkSparseImageOpaqueMemoryBindInfo *bind)
4228 {
4229 RADV_FROM_HANDLE(radv_image, image, bind->image);
4230
4231 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4232 struct radv_device_memory *mem = NULL;
4233
4234 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4235 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4236
4237 device->ws->buffer_virtual_bind(image->bo,
4238 bind->pBinds[i].resourceOffset,
4239 bind->pBinds[i].size,
4240 mem ? mem->bo : NULL,
4241 bind->pBinds[i].memoryOffset);
4242 }
4243 }
4244
4245 static VkResult
4246 radv_get_preambles(struct radv_queue *queue,
4247 const VkCommandBuffer *cmd_buffers,
4248 uint32_t cmd_buffer_count,
4249 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
4250 struct radeon_cmdbuf **initial_preamble_cs,
4251 struct radeon_cmdbuf **continue_preamble_cs)
4252 {
4253 uint32_t scratch_size_per_wave = 0, waves_wanted = 0;
4254 uint32_t compute_scratch_size_per_wave = 0, compute_waves_wanted = 0;
4255 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
4256 bool tess_rings_needed = false;
4257 bool gds_needed = false;
4258 bool gds_oa_needed = false;
4259 bool sample_positions_needed = false;
4260
4261 for (uint32_t j = 0; j < cmd_buffer_count; j++) {
4262 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
4263 cmd_buffers[j]);
4264
4265 scratch_size_per_wave = MAX2(scratch_size_per_wave, cmd_buffer->scratch_size_per_wave_needed);
4266 waves_wanted = MAX2(waves_wanted, cmd_buffer->scratch_waves_wanted);
4267 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave,
4268 cmd_buffer->compute_scratch_size_per_wave_needed);
4269 compute_waves_wanted = MAX2(compute_waves_wanted,
4270 cmd_buffer->compute_scratch_waves_wanted);
4271 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
4272 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
4273 tess_rings_needed |= cmd_buffer->tess_rings_needed;
4274 gds_needed |= cmd_buffer->gds_needed;
4275 gds_oa_needed |= cmd_buffer->gds_oa_needed;
4276 sample_positions_needed |= cmd_buffer->sample_positions_needed;
4277 }
4278
4279 return radv_get_preamble_cs(queue, scratch_size_per_wave, waves_wanted,
4280 compute_scratch_size_per_wave, compute_waves_wanted,
4281 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
4282 gds_needed, gds_oa_needed, sample_positions_needed,
4283 initial_full_flush_preamble_cs,
4284 initial_preamble_cs, continue_preamble_cs);
4285 }
4286
4287 struct radv_deferred_queue_submission {
4288 struct radv_queue *queue;
4289 VkCommandBuffer *cmd_buffers;
4290 uint32_t cmd_buffer_count;
4291
4292 /* Sparse bindings that happen on a queue. */
4293 VkSparseBufferMemoryBindInfo *buffer_binds;
4294 uint32_t buffer_bind_count;
4295 VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4296 uint32_t image_opaque_bind_count;
4297
4298 bool flush_caches;
4299 VkShaderStageFlags wait_dst_stage_mask;
4300 struct radv_semaphore_part **wait_semaphores;
4301 uint32_t wait_semaphore_count;
4302 struct radv_semaphore_part **signal_semaphores;
4303 uint32_t signal_semaphore_count;
4304 VkFence fence;
4305
4306 uint64_t *wait_values;
4307 uint64_t *signal_values;
4308
4309 struct radv_semaphore_part *temporary_semaphore_parts;
4310 uint32_t temporary_semaphore_part_count;
4311
4312 struct list_head queue_pending_list;
4313 uint32_t submission_wait_count;
4314 struct radv_timeline_waiter *wait_nodes;
4315
4316 struct list_head processing_list;
4317 };
4318
4319 struct radv_queue_submission {
4320 const VkCommandBuffer *cmd_buffers;
4321 uint32_t cmd_buffer_count;
4322
4323 /* Sparse bindings that happen on a queue. */
4324 const VkSparseBufferMemoryBindInfo *buffer_binds;
4325 uint32_t buffer_bind_count;
4326 const VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4327 uint32_t image_opaque_bind_count;
4328
4329 bool flush_caches;
4330 VkPipelineStageFlags wait_dst_stage_mask;
4331 const VkSemaphore *wait_semaphores;
4332 uint32_t wait_semaphore_count;
4333 const VkSemaphore *signal_semaphores;
4334 uint32_t signal_semaphore_count;
4335 VkFence fence;
4336
4337 const uint64_t *wait_values;
4338 uint32_t wait_value_count;
4339 const uint64_t *signal_values;
4340 uint32_t signal_value_count;
4341 };
4342
4343 static VkResult
4344 radv_create_deferred_submission(struct radv_queue *queue,
4345 const struct radv_queue_submission *submission,
4346 struct radv_deferred_queue_submission **out)
4347 {
4348 struct radv_deferred_queue_submission *deferred = NULL;
4349 size_t size = sizeof(struct radv_deferred_queue_submission);
4350
4351 uint32_t temporary_count = 0;
4352 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4353 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4354 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE)
4355 ++temporary_count;
4356 }
4357
4358 size += submission->cmd_buffer_count * sizeof(VkCommandBuffer);
4359 size += submission->buffer_bind_count * sizeof(VkSparseBufferMemoryBindInfo);
4360 size += submission->image_opaque_bind_count * sizeof(VkSparseImageOpaqueMemoryBindInfo);
4361 size += submission->wait_semaphore_count * sizeof(struct radv_semaphore_part *);
4362 size += temporary_count * sizeof(struct radv_semaphore_part);
4363 size += submission->signal_semaphore_count * sizeof(struct radv_semaphore_part *);
4364 size += submission->wait_value_count * sizeof(uint64_t);
4365 size += submission->signal_value_count * sizeof(uint64_t);
4366 size += submission->wait_semaphore_count * sizeof(struct radv_timeline_waiter);
4367
4368 deferred = calloc(1, size);
4369 if (!deferred)
4370 return VK_ERROR_OUT_OF_HOST_MEMORY;
4371
4372 deferred->queue = queue;
4373
4374 deferred->cmd_buffers = (void*)(deferred + 1);
4375 deferred->cmd_buffer_count = submission->cmd_buffer_count;
4376 memcpy(deferred->cmd_buffers, submission->cmd_buffers,
4377 submission->cmd_buffer_count * sizeof(*deferred->cmd_buffers));
4378
4379 deferred->buffer_binds = (void*)(deferred->cmd_buffers + submission->cmd_buffer_count);
4380 deferred->buffer_bind_count = submission->buffer_bind_count;
4381 memcpy(deferred->buffer_binds, submission->buffer_binds,
4382 submission->buffer_bind_count * sizeof(*deferred->buffer_binds));
4383
4384 deferred->image_opaque_binds = (void*)(deferred->buffer_binds + submission->buffer_bind_count);
4385 deferred->image_opaque_bind_count = submission->image_opaque_bind_count;
4386 memcpy(deferred->image_opaque_binds, submission->image_opaque_binds,
4387 submission->image_opaque_bind_count * sizeof(*deferred->image_opaque_binds));
4388
4389 deferred->flush_caches = submission->flush_caches;
4390 deferred->wait_dst_stage_mask = submission->wait_dst_stage_mask;
4391
4392 deferred->wait_semaphores = (void*)(deferred->image_opaque_binds + deferred->image_opaque_bind_count);
4393 deferred->wait_semaphore_count = submission->wait_semaphore_count;
4394
4395 deferred->signal_semaphores = (void*)(deferred->wait_semaphores + deferred->wait_semaphore_count);
4396 deferred->signal_semaphore_count = submission->signal_semaphore_count;
4397
4398 deferred->fence = submission->fence;
4399
4400 deferred->temporary_semaphore_parts = (void*)(deferred->signal_semaphores + deferred->signal_semaphore_count);
4401 deferred->temporary_semaphore_part_count = temporary_count;
4402
4403 uint32_t temporary_idx = 0;
4404 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4405 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4406 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4407 deferred->wait_semaphores[i] = &deferred->temporary_semaphore_parts[temporary_idx];
4408 deferred->temporary_semaphore_parts[temporary_idx] = semaphore->temporary;
4409 semaphore->temporary.kind = RADV_SEMAPHORE_NONE;
4410 ++temporary_idx;
4411 } else
4412 deferred->wait_semaphores[i] = &semaphore->permanent;
4413 }
4414
4415 for (uint32_t i = 0; i < submission->signal_semaphore_count; ++i) {
4416 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->signal_semaphores[i]);
4417 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4418 deferred->signal_semaphores[i] = &semaphore->temporary;
4419 } else {
4420 deferred->signal_semaphores[i] = &semaphore->permanent;
4421 }
4422 }
4423
4424 deferred->wait_values = (void*)(deferred->temporary_semaphore_parts + temporary_count);
4425 memcpy(deferred->wait_values, submission->wait_values, submission->wait_value_count * sizeof(uint64_t));
4426 deferred->signal_values = deferred->wait_values + submission->wait_value_count;
4427 memcpy(deferred->signal_values, submission->signal_values, submission->signal_value_count * sizeof(uint64_t));
4428
4429 deferred->wait_nodes = (void*)(deferred->signal_values + submission->signal_value_count);
4430 /* This is worst-case. radv_queue_enqueue_submission will fill in further, but this
4431 * ensure the submission is not accidentally triggered early when adding wait timelines. */
4432 deferred->submission_wait_count = 1 + submission->wait_semaphore_count;
4433
4434 *out = deferred;
4435 return VK_SUCCESS;
4436 }
4437
4438 static void
4439 radv_queue_enqueue_submission(struct radv_deferred_queue_submission *submission,
4440 struct list_head *processing_list)
4441 {
4442 uint32_t wait_cnt = 0;
4443 struct radv_timeline_waiter *waiter = submission->wait_nodes;
4444 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4445 if (submission->wait_semaphores[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4446 pthread_mutex_lock(&submission->wait_semaphores[i]->timeline.mutex);
4447 if (submission->wait_semaphores[i]->timeline.highest_submitted < submission->wait_values[i]) {
4448 ++wait_cnt;
4449 waiter->value = submission->wait_values[i];
4450 waiter->submission = submission;
4451 list_addtail(&waiter->list, &submission->wait_semaphores[i]->timeline.waiters);
4452 ++waiter;
4453 }
4454 pthread_mutex_unlock(&submission->wait_semaphores[i]->timeline.mutex);
4455 }
4456 }
4457
4458 pthread_mutex_lock(&submission->queue->pending_mutex);
4459
4460 bool is_first = list_is_empty(&submission->queue->pending_submissions);
4461 list_addtail(&submission->queue_pending_list, &submission->queue->pending_submissions);
4462
4463 pthread_mutex_unlock(&submission->queue->pending_mutex);
4464
4465 /* If there is already a submission in the queue, that will decrement the counter by 1 when
4466 * submitted, but if the queue was empty, we decrement ourselves as there is no previous
4467 * submission. */
4468 uint32_t decrement = submission->wait_semaphore_count - wait_cnt + (is_first ? 1 : 0);
4469 if (__atomic_sub_fetch(&submission->submission_wait_count, decrement, __ATOMIC_ACQ_REL) == 0) {
4470 list_addtail(&submission->processing_list, processing_list);
4471 }
4472 }
4473
4474 static void
4475 radv_queue_submission_update_queue(struct radv_deferred_queue_submission *submission,
4476 struct list_head *processing_list)
4477 {
4478 pthread_mutex_lock(&submission->queue->pending_mutex);
4479 list_del(&submission->queue_pending_list);
4480
4481 /* trigger the next submission in the queue. */
4482 if (!list_is_empty(&submission->queue->pending_submissions)) {
4483 struct radv_deferred_queue_submission *next_submission =
4484 list_first_entry(&submission->queue->pending_submissions,
4485 struct radv_deferred_queue_submission,
4486 queue_pending_list);
4487 if (p_atomic_dec_zero(&next_submission->submission_wait_count)) {
4488 list_addtail(&next_submission->processing_list, processing_list);
4489 }
4490 }
4491 pthread_mutex_unlock(&submission->queue->pending_mutex);
4492
4493 pthread_cond_broadcast(&submission->queue->device->timeline_cond);
4494 }
4495
4496 static VkResult
4497 radv_queue_submit_deferred(struct radv_deferred_queue_submission *submission,
4498 struct list_head *processing_list)
4499 {
4500 RADV_FROM_HANDLE(radv_fence, fence, submission->fence);
4501 struct radv_queue *queue = submission->queue;
4502 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4503 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
4504 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
4505 bool do_flush = submission->flush_caches || submission->wait_dst_stage_mask;
4506 bool can_patch = true;
4507 uint32_t advance;
4508 struct radv_winsys_sem_info sem_info;
4509 VkResult result;
4510 int ret;
4511 struct radeon_cmdbuf *initial_preamble_cs = NULL;
4512 struct radeon_cmdbuf *initial_flush_preamble_cs = NULL;
4513 struct radeon_cmdbuf *continue_preamble_cs = NULL;
4514
4515 result = radv_get_preambles(queue, submission->cmd_buffers,
4516 submission->cmd_buffer_count,
4517 &initial_preamble_cs,
4518 &initial_flush_preamble_cs,
4519 &continue_preamble_cs);
4520 if (result != VK_SUCCESS)
4521 goto fail;
4522
4523 result = radv_alloc_sem_info(queue->device,
4524 &sem_info,
4525 submission->wait_semaphore_count,
4526 submission->wait_semaphores,
4527 submission->wait_values,
4528 submission->signal_semaphore_count,
4529 submission->signal_semaphores,
4530 submission->signal_values,
4531 submission->fence);
4532 if (result != VK_SUCCESS)
4533 goto fail;
4534
4535 for (uint32_t i = 0; i < submission->buffer_bind_count; ++i) {
4536 radv_sparse_buffer_bind_memory(queue->device,
4537 submission->buffer_binds + i);
4538 }
4539
4540 for (uint32_t i = 0; i < submission->image_opaque_bind_count; ++i) {
4541 radv_sparse_image_opaque_bind_memory(queue->device,
4542 submission->image_opaque_binds + i);
4543 }
4544
4545 if (!submission->cmd_buffer_count) {
4546 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
4547 &queue->device->empty_cs[queue->queue_family_index],
4548 1, NULL, NULL,
4549 &sem_info, NULL,
4550 false, base_fence);
4551 if (ret) {
4552 radv_loge("failed to submit CS\n");
4553 abort();
4554 }
4555
4556 goto success;
4557 } else {
4558 struct radeon_cmdbuf **cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
4559 (submission->cmd_buffer_count));
4560
4561 for (uint32_t j = 0; j < submission->cmd_buffer_count; j++) {
4562 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, submission->cmd_buffers[j]);
4563 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4564
4565 cs_array[j] = cmd_buffer->cs;
4566 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
4567 can_patch = false;
4568
4569 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
4570 }
4571
4572 for (uint32_t j = 0; j < submission->cmd_buffer_count; j += advance) {
4573 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
4574 const struct radv_winsys_bo_list *bo_list = NULL;
4575
4576 advance = MIN2(max_cs_submission,
4577 submission->cmd_buffer_count - j);
4578
4579 if (queue->device->trace_bo)
4580 *queue->device->trace_id_ptr = 0;
4581
4582 sem_info.cs_emit_wait = j == 0;
4583 sem_info.cs_emit_signal = j + advance == submission->cmd_buffer_count;
4584
4585 if (unlikely(queue->device->use_global_bo_list)) {
4586 pthread_mutex_lock(&queue->device->bo_list.mutex);
4587 bo_list = &queue->device->bo_list.list;
4588 }
4589
4590 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
4591 advance, initial_preamble, continue_preamble_cs,
4592 &sem_info, bo_list,
4593 can_patch, base_fence);
4594
4595 if (unlikely(queue->device->use_global_bo_list))
4596 pthread_mutex_unlock(&queue->device->bo_list.mutex);
4597
4598 if (ret) {
4599 radv_loge("failed to submit CS\n");
4600 abort();
4601 }
4602 if (queue->device->trace_bo) {
4603 radv_check_gpu_hangs(queue, cs_array[j]);
4604 }
4605 }
4606
4607 free(cs_array);
4608 }
4609
4610 success:
4611 radv_free_temp_syncobjs(queue->device,
4612 submission->temporary_semaphore_part_count,
4613 submission->temporary_semaphore_parts);
4614 radv_finalize_timelines(queue->device,
4615 submission->wait_semaphore_count,
4616 submission->wait_semaphores,
4617 submission->wait_values,
4618 submission->signal_semaphore_count,
4619 submission->signal_semaphores,
4620 submission->signal_values,
4621 processing_list);
4622 /* Has to happen after timeline finalization to make sure the
4623 * condition variable is only triggered when timelines and queue have
4624 * been updated. */
4625 radv_queue_submission_update_queue(submission, processing_list);
4626 radv_free_sem_info(&sem_info);
4627 free(submission);
4628 return VK_SUCCESS;
4629
4630 fail:
4631 radv_free_temp_syncobjs(queue->device,
4632 submission->temporary_semaphore_part_count,
4633 submission->temporary_semaphore_parts);
4634 free(submission);
4635 return VK_ERROR_DEVICE_LOST;
4636 }
4637
4638 static VkResult
4639 radv_process_submissions(struct list_head *processing_list)
4640 {
4641 while(!list_is_empty(processing_list)) {
4642 struct radv_deferred_queue_submission *submission =
4643 list_first_entry(processing_list, struct radv_deferred_queue_submission, processing_list);
4644 list_del(&submission->processing_list);
4645
4646 VkResult result = radv_queue_submit_deferred(submission, processing_list);
4647 if (result != VK_SUCCESS)
4648 return result;
4649 }
4650 return VK_SUCCESS;
4651 }
4652
4653 static VkResult radv_queue_submit(struct radv_queue *queue,
4654 const struct radv_queue_submission *submission)
4655 {
4656 struct radv_deferred_queue_submission *deferred = NULL;
4657
4658 VkResult result = radv_create_deferred_submission(queue, submission, &deferred);
4659 if (result != VK_SUCCESS)
4660 return result;
4661
4662 struct list_head processing_list;
4663 list_inithead(&processing_list);
4664
4665 radv_queue_enqueue_submission(deferred, &processing_list);
4666 return radv_process_submissions(&processing_list);
4667 }
4668
4669 /* Signals fence as soon as all the work currently put on queue is done. */
4670 static VkResult radv_signal_fence(struct radv_queue *queue,
4671 VkFence fence)
4672 {
4673 return radv_queue_submit(queue, &(struct radv_queue_submission) {
4674 .fence = fence
4675 });
4676 }
4677
4678 static bool radv_submit_has_effects(const VkSubmitInfo *info)
4679 {
4680 return info->commandBufferCount ||
4681 info->waitSemaphoreCount ||
4682 info->signalSemaphoreCount;
4683 }
4684
4685 VkResult radv_QueueSubmit(
4686 VkQueue _queue,
4687 uint32_t submitCount,
4688 const VkSubmitInfo* pSubmits,
4689 VkFence fence)
4690 {
4691 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4692 VkResult result;
4693 uint32_t fence_idx = 0;
4694 bool flushed_caches = false;
4695
4696 if (fence != VK_NULL_HANDLE) {
4697 for (uint32_t i = 0; i < submitCount; ++i)
4698 if (radv_submit_has_effects(pSubmits + i))
4699 fence_idx = i;
4700 } else
4701 fence_idx = UINT32_MAX;
4702
4703 for (uint32_t i = 0; i < submitCount; i++) {
4704 if (!radv_submit_has_effects(pSubmits + i) && fence_idx != i)
4705 continue;
4706
4707 VkPipelineStageFlags wait_dst_stage_mask = 0;
4708 for (unsigned j = 0; j < pSubmits[i].waitSemaphoreCount; ++j) {
4709 wait_dst_stage_mask |= pSubmits[i].pWaitDstStageMask[j];
4710 }
4711
4712 const VkTimelineSemaphoreSubmitInfo *timeline_info =
4713 vk_find_struct_const(pSubmits[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
4714
4715 result = radv_queue_submit(queue, &(struct radv_queue_submission) {
4716 .cmd_buffers = pSubmits[i].pCommandBuffers,
4717 .cmd_buffer_count = pSubmits[i].commandBufferCount,
4718 .wait_dst_stage_mask = wait_dst_stage_mask,
4719 .flush_caches = !flushed_caches,
4720 .wait_semaphores = pSubmits[i].pWaitSemaphores,
4721 .wait_semaphore_count = pSubmits[i].waitSemaphoreCount,
4722 .signal_semaphores = pSubmits[i].pSignalSemaphores,
4723 .signal_semaphore_count = pSubmits[i].signalSemaphoreCount,
4724 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
4725 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
4726 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
4727 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
4728 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
4729 });
4730 if (result != VK_SUCCESS)
4731 return result;
4732
4733 flushed_caches = true;
4734 }
4735
4736 if (fence != VK_NULL_HANDLE && !submitCount) {
4737 result = radv_signal_fence(queue, fence);
4738 if (result != VK_SUCCESS)
4739 return result;
4740 }
4741
4742 return VK_SUCCESS;
4743 }
4744
4745 VkResult radv_QueueWaitIdle(
4746 VkQueue _queue)
4747 {
4748 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4749
4750 pthread_mutex_lock(&queue->pending_mutex);
4751 while (!list_is_empty(&queue->pending_submissions)) {
4752 pthread_cond_wait(&queue->device->timeline_cond, &queue->pending_mutex);
4753 }
4754 pthread_mutex_unlock(&queue->pending_mutex);
4755
4756 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
4757 radv_queue_family_to_ring(queue->queue_family_index),
4758 queue->queue_idx);
4759 return VK_SUCCESS;
4760 }
4761
4762 VkResult radv_DeviceWaitIdle(
4763 VkDevice _device)
4764 {
4765 RADV_FROM_HANDLE(radv_device, device, _device);
4766
4767 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
4768 for (unsigned q = 0; q < device->queue_count[i]; q++) {
4769 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
4770 }
4771 }
4772 return VK_SUCCESS;
4773 }
4774
4775 VkResult radv_EnumerateInstanceExtensionProperties(
4776 const char* pLayerName,
4777 uint32_t* pPropertyCount,
4778 VkExtensionProperties* pProperties)
4779 {
4780 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
4781
4782 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
4783 if (radv_supported_instance_extensions.extensions[i]) {
4784 vk_outarray_append(&out, prop) {
4785 *prop = radv_instance_extensions[i];
4786 }
4787 }
4788 }
4789
4790 return vk_outarray_status(&out);
4791 }
4792
4793 VkResult radv_EnumerateDeviceExtensionProperties(
4794 VkPhysicalDevice physicalDevice,
4795 const char* pLayerName,
4796 uint32_t* pPropertyCount,
4797 VkExtensionProperties* pProperties)
4798 {
4799 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
4800 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
4801
4802 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
4803 if (device->supported_extensions.extensions[i]) {
4804 vk_outarray_append(&out, prop) {
4805 *prop = radv_device_extensions[i];
4806 }
4807 }
4808 }
4809
4810 return vk_outarray_status(&out);
4811 }
4812
4813 PFN_vkVoidFunction radv_GetInstanceProcAddr(
4814 VkInstance _instance,
4815 const char* pName)
4816 {
4817 RADV_FROM_HANDLE(radv_instance, instance, _instance);
4818 bool unchecked = instance ? instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS : false;
4819
4820 if (unchecked) {
4821 return radv_lookup_entrypoint_unchecked(pName);
4822 } else {
4823 return radv_lookup_entrypoint_checked(pName,
4824 instance ? instance->apiVersion : 0,
4825 instance ? &instance->enabled_extensions : NULL,
4826 NULL);
4827 }
4828 }
4829
4830 /* The loader wants us to expose a second GetInstanceProcAddr function
4831 * to work around certain LD_PRELOAD issues seen in apps.
4832 */
4833 PUBLIC
4834 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
4835 VkInstance instance,
4836 const char* pName);
4837
4838 PUBLIC
4839 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
4840 VkInstance instance,
4841 const char* pName)
4842 {
4843 return radv_GetInstanceProcAddr(instance, pName);
4844 }
4845
4846 PUBLIC
4847 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
4848 VkInstance _instance,
4849 const char* pName);
4850
4851 PUBLIC
4852 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
4853 VkInstance _instance,
4854 const char* pName)
4855 {
4856 RADV_FROM_HANDLE(radv_instance, instance, _instance);
4857
4858 return radv_lookup_physical_device_entrypoint_checked(pName,
4859 instance ? instance->apiVersion : 0,
4860 instance ? &instance->enabled_extensions : NULL);
4861 }
4862
4863 PFN_vkVoidFunction radv_GetDeviceProcAddr(
4864 VkDevice _device,
4865 const char* pName)
4866 {
4867 RADV_FROM_HANDLE(radv_device, device, _device);
4868 bool unchecked = device ? device->instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS : false;
4869
4870 if (unchecked) {
4871 return radv_lookup_entrypoint_unchecked(pName);
4872 } else {
4873 return radv_lookup_entrypoint_checked(pName,
4874 device->instance->apiVersion,
4875 &device->instance->enabled_extensions,
4876 &device->enabled_extensions);
4877 }
4878 }
4879
4880 bool radv_get_memory_fd(struct radv_device *device,
4881 struct radv_device_memory *memory,
4882 int *pFD)
4883 {
4884 struct radeon_bo_metadata metadata;
4885
4886 if (memory->image) {
4887 if (memory->image->tiling != VK_IMAGE_TILING_LINEAR)
4888 radv_init_metadata(device, memory->image, &metadata);
4889 device->ws->buffer_set_metadata(memory->bo, &metadata);
4890 }
4891
4892 return device->ws->buffer_get_fd(device->ws, memory->bo,
4893 pFD);
4894 }
4895
4896
4897 static void radv_free_memory(struct radv_device *device,
4898 const VkAllocationCallbacks* pAllocator,
4899 struct radv_device_memory *mem)
4900 {
4901 if (mem == NULL)
4902 return;
4903
4904 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
4905 if (mem->android_hardware_buffer)
4906 AHardwareBuffer_release(mem->android_hardware_buffer);
4907 #endif
4908
4909 if (mem->bo) {
4910 radv_bo_list_remove(device, mem->bo);
4911 device->ws->buffer_destroy(mem->bo);
4912 mem->bo = NULL;
4913 }
4914
4915 vk_free2(&device->alloc, pAllocator, mem);
4916 }
4917
4918 static VkResult radv_alloc_memory(struct radv_device *device,
4919 const VkMemoryAllocateInfo* pAllocateInfo,
4920 const VkAllocationCallbacks* pAllocator,
4921 VkDeviceMemory* pMem)
4922 {
4923 struct radv_device_memory *mem;
4924 VkResult result;
4925 enum radeon_bo_domain domain;
4926 uint32_t flags = 0;
4927 enum radv_mem_type mem_type_index = device->physical_device->mem_type_indices[pAllocateInfo->memoryTypeIndex];
4928
4929 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
4930
4931 const VkImportMemoryFdInfoKHR *import_info =
4932 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
4933 const VkMemoryDedicatedAllocateInfo *dedicate_info =
4934 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
4935 const VkExportMemoryAllocateInfo *export_info =
4936 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
4937 const struct VkImportAndroidHardwareBufferInfoANDROID *ahb_import_info =
4938 vk_find_struct_const(pAllocateInfo->pNext,
4939 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
4940 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
4941 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
4942
4943 const struct wsi_memory_allocate_info *wsi_info =
4944 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
4945
4946 if (pAllocateInfo->allocationSize == 0 && !ahb_import_info &&
4947 !(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
4948 /* Apparently, this is allowed */
4949 *pMem = VK_NULL_HANDLE;
4950 return VK_SUCCESS;
4951 }
4952
4953 mem = vk_zalloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
4954 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4955 if (mem == NULL)
4956 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4957
4958 if (wsi_info && wsi_info->implicit_sync)
4959 flags |= RADEON_FLAG_IMPLICIT_SYNC;
4960
4961 if (dedicate_info) {
4962 mem->image = radv_image_from_handle(dedicate_info->image);
4963 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
4964 } else {
4965 mem->image = NULL;
4966 mem->buffer = NULL;
4967 }
4968
4969 float priority_float = 0.5;
4970 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
4971 vk_find_struct_const(pAllocateInfo->pNext,
4972 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
4973 if (priority_ext)
4974 priority_float = priority_ext->priority;
4975
4976 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
4977 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
4978
4979 mem->user_ptr = NULL;
4980 mem->bo = NULL;
4981
4982 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
4983 mem->android_hardware_buffer = NULL;
4984 #endif
4985
4986 if (ahb_import_info) {
4987 result = radv_import_ahb_memory(device, mem, priority, ahb_import_info);
4988 if (result != VK_SUCCESS)
4989 goto fail;
4990 } else if(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
4991 result = radv_create_ahb_memory(device, mem, priority, pAllocateInfo);
4992 if (result != VK_SUCCESS)
4993 goto fail;
4994 } else if (import_info) {
4995 assert(import_info->handleType ==
4996 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
4997 import_info->handleType ==
4998 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
4999 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
5000 priority, NULL);
5001 if (!mem->bo) {
5002 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5003 goto fail;
5004 } else {
5005 close(import_info->fd);
5006 }
5007 } else if (host_ptr_info) {
5008 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
5009 assert(radv_is_mem_type_gtt_cached(mem_type_index));
5010 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
5011 pAllocateInfo->allocationSize,
5012 priority);
5013 if (!mem->bo) {
5014 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5015 goto fail;
5016 } else {
5017 mem->user_ptr = host_ptr_info->pHostPointer;
5018 }
5019 } else {
5020 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
5021 if (radv_is_mem_type_gtt_wc(mem_type_index) ||
5022 radv_is_mem_type_gtt_cached(mem_type_index))
5023 domain = RADEON_DOMAIN_GTT;
5024 else
5025 domain = RADEON_DOMAIN_VRAM;
5026
5027 if (radv_is_mem_type_vram(mem_type_index))
5028 flags |= RADEON_FLAG_NO_CPU_ACCESS;
5029 else
5030 flags |= RADEON_FLAG_CPU_ACCESS;
5031
5032 if (radv_is_mem_type_gtt_wc(mem_type_index))
5033 flags |= RADEON_FLAG_GTT_WC;
5034
5035 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
5036 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
5037 if (device->use_global_bo_list) {
5038 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
5039 }
5040 }
5041
5042 if (radv_is_mem_type_uncached(mem_type_index)) {
5043 assert(device->physical_device->rad_info.has_l2_uncached);
5044 flags |= RADEON_FLAG_VA_UNCACHED;
5045 }
5046
5047 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
5048 domain, flags, priority);
5049
5050 if (!mem->bo) {
5051 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5052 goto fail;
5053 }
5054 mem->type_index = mem_type_index;
5055 }
5056
5057 result = radv_bo_list_add(device, mem->bo);
5058 if (result != VK_SUCCESS)
5059 goto fail;
5060
5061 *pMem = radv_device_memory_to_handle(mem);
5062
5063 return VK_SUCCESS;
5064
5065 fail:
5066 radv_free_memory(device, pAllocator,mem);
5067
5068 return result;
5069 }
5070
5071 VkResult radv_AllocateMemory(
5072 VkDevice _device,
5073 const VkMemoryAllocateInfo* pAllocateInfo,
5074 const VkAllocationCallbacks* pAllocator,
5075 VkDeviceMemory* pMem)
5076 {
5077 RADV_FROM_HANDLE(radv_device, device, _device);
5078 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
5079 }
5080
5081 void radv_FreeMemory(
5082 VkDevice _device,
5083 VkDeviceMemory _mem,
5084 const VkAllocationCallbacks* pAllocator)
5085 {
5086 RADV_FROM_HANDLE(radv_device, device, _device);
5087 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
5088
5089 radv_free_memory(device, pAllocator, mem);
5090 }
5091
5092 VkResult radv_MapMemory(
5093 VkDevice _device,
5094 VkDeviceMemory _memory,
5095 VkDeviceSize offset,
5096 VkDeviceSize size,
5097 VkMemoryMapFlags flags,
5098 void** ppData)
5099 {
5100 RADV_FROM_HANDLE(radv_device, device, _device);
5101 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5102
5103 if (mem == NULL) {
5104 *ppData = NULL;
5105 return VK_SUCCESS;
5106 }
5107
5108 if (mem->user_ptr)
5109 *ppData = mem->user_ptr;
5110 else
5111 *ppData = device->ws->buffer_map(mem->bo);
5112
5113 if (*ppData) {
5114 *ppData += offset;
5115 return VK_SUCCESS;
5116 }
5117
5118 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
5119 }
5120
5121 void radv_UnmapMemory(
5122 VkDevice _device,
5123 VkDeviceMemory _memory)
5124 {
5125 RADV_FROM_HANDLE(radv_device, device, _device);
5126 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5127
5128 if (mem == NULL)
5129 return;
5130
5131 if (mem->user_ptr == NULL)
5132 device->ws->buffer_unmap(mem->bo);
5133 }
5134
5135 VkResult radv_FlushMappedMemoryRanges(
5136 VkDevice _device,
5137 uint32_t memoryRangeCount,
5138 const VkMappedMemoryRange* pMemoryRanges)
5139 {
5140 return VK_SUCCESS;
5141 }
5142
5143 VkResult radv_InvalidateMappedMemoryRanges(
5144 VkDevice _device,
5145 uint32_t memoryRangeCount,
5146 const VkMappedMemoryRange* pMemoryRanges)
5147 {
5148 return VK_SUCCESS;
5149 }
5150
5151 void radv_GetBufferMemoryRequirements(
5152 VkDevice _device,
5153 VkBuffer _buffer,
5154 VkMemoryRequirements* pMemoryRequirements)
5155 {
5156 RADV_FROM_HANDLE(radv_device, device, _device);
5157 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
5158
5159 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5160
5161 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
5162 pMemoryRequirements->alignment = 4096;
5163 else
5164 pMemoryRequirements->alignment = 16;
5165
5166 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
5167 }
5168
5169 void radv_GetBufferMemoryRequirements2(
5170 VkDevice device,
5171 const VkBufferMemoryRequirementsInfo2 *pInfo,
5172 VkMemoryRequirements2 *pMemoryRequirements)
5173 {
5174 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
5175 &pMemoryRequirements->memoryRequirements);
5176 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5177 switch (ext->sType) {
5178 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5179 VkMemoryDedicatedRequirements *req =
5180 (VkMemoryDedicatedRequirements *) ext;
5181 req->requiresDedicatedAllocation = false;
5182 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5183 break;
5184 }
5185 default:
5186 break;
5187 }
5188 }
5189 }
5190
5191 void radv_GetImageMemoryRequirements(
5192 VkDevice _device,
5193 VkImage _image,
5194 VkMemoryRequirements* pMemoryRequirements)
5195 {
5196 RADV_FROM_HANDLE(radv_device, device, _device);
5197 RADV_FROM_HANDLE(radv_image, image, _image);
5198
5199 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5200
5201 pMemoryRequirements->size = image->size;
5202 pMemoryRequirements->alignment = image->alignment;
5203 }
5204
5205 void radv_GetImageMemoryRequirements2(
5206 VkDevice device,
5207 const VkImageMemoryRequirementsInfo2 *pInfo,
5208 VkMemoryRequirements2 *pMemoryRequirements)
5209 {
5210 radv_GetImageMemoryRequirements(device, pInfo->image,
5211 &pMemoryRequirements->memoryRequirements);
5212
5213 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
5214
5215 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5216 switch (ext->sType) {
5217 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5218 VkMemoryDedicatedRequirements *req =
5219 (VkMemoryDedicatedRequirements *) ext;
5220 req->requiresDedicatedAllocation = image->shareable &&
5221 image->tiling != VK_IMAGE_TILING_LINEAR;
5222 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5223 break;
5224 }
5225 default:
5226 break;
5227 }
5228 }
5229 }
5230
5231 void radv_GetImageSparseMemoryRequirements(
5232 VkDevice device,
5233 VkImage image,
5234 uint32_t* pSparseMemoryRequirementCount,
5235 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
5236 {
5237 stub();
5238 }
5239
5240 void radv_GetImageSparseMemoryRequirements2(
5241 VkDevice device,
5242 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
5243 uint32_t* pSparseMemoryRequirementCount,
5244 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
5245 {
5246 stub();
5247 }
5248
5249 void radv_GetDeviceMemoryCommitment(
5250 VkDevice device,
5251 VkDeviceMemory memory,
5252 VkDeviceSize* pCommittedMemoryInBytes)
5253 {
5254 *pCommittedMemoryInBytes = 0;
5255 }
5256
5257 VkResult radv_BindBufferMemory2(VkDevice device,
5258 uint32_t bindInfoCount,
5259 const VkBindBufferMemoryInfo *pBindInfos)
5260 {
5261 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5262 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5263 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
5264
5265 if (mem) {
5266 buffer->bo = mem->bo;
5267 buffer->offset = pBindInfos[i].memoryOffset;
5268 } else {
5269 buffer->bo = NULL;
5270 }
5271 }
5272 return VK_SUCCESS;
5273 }
5274
5275 VkResult radv_BindBufferMemory(
5276 VkDevice device,
5277 VkBuffer buffer,
5278 VkDeviceMemory memory,
5279 VkDeviceSize memoryOffset)
5280 {
5281 const VkBindBufferMemoryInfo info = {
5282 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5283 .buffer = buffer,
5284 .memory = memory,
5285 .memoryOffset = memoryOffset
5286 };
5287
5288 return radv_BindBufferMemory2(device, 1, &info);
5289 }
5290
5291 VkResult radv_BindImageMemory2(VkDevice device,
5292 uint32_t bindInfoCount,
5293 const VkBindImageMemoryInfo *pBindInfos)
5294 {
5295 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5296 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5297 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
5298
5299 if (mem) {
5300 image->bo = mem->bo;
5301 image->offset = pBindInfos[i].memoryOffset;
5302 } else {
5303 image->bo = NULL;
5304 image->offset = 0;
5305 }
5306 }
5307 return VK_SUCCESS;
5308 }
5309
5310
5311 VkResult radv_BindImageMemory(
5312 VkDevice device,
5313 VkImage image,
5314 VkDeviceMemory memory,
5315 VkDeviceSize memoryOffset)
5316 {
5317 const VkBindImageMemoryInfo info = {
5318 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5319 .image = image,
5320 .memory = memory,
5321 .memoryOffset = memoryOffset
5322 };
5323
5324 return radv_BindImageMemory2(device, 1, &info);
5325 }
5326
5327 static bool radv_sparse_bind_has_effects(const VkBindSparseInfo *info)
5328 {
5329 return info->bufferBindCount ||
5330 info->imageOpaqueBindCount ||
5331 info->imageBindCount ||
5332 info->waitSemaphoreCount ||
5333 info->signalSemaphoreCount;
5334 }
5335
5336 VkResult radv_QueueBindSparse(
5337 VkQueue _queue,
5338 uint32_t bindInfoCount,
5339 const VkBindSparseInfo* pBindInfo,
5340 VkFence fence)
5341 {
5342 RADV_FROM_HANDLE(radv_queue, queue, _queue);
5343 VkResult result;
5344 uint32_t fence_idx = 0;
5345
5346 if (fence != VK_NULL_HANDLE) {
5347 for (uint32_t i = 0; i < bindInfoCount; ++i)
5348 if (radv_sparse_bind_has_effects(pBindInfo + i))
5349 fence_idx = i;
5350 } else
5351 fence_idx = UINT32_MAX;
5352
5353 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5354 if (i != fence_idx && !radv_sparse_bind_has_effects(pBindInfo + i))
5355 continue;
5356
5357 const VkTimelineSemaphoreSubmitInfo *timeline_info =
5358 vk_find_struct_const(pBindInfo[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
5359
5360 VkResult result = radv_queue_submit(queue, &(struct radv_queue_submission) {
5361 .buffer_binds = pBindInfo[i].pBufferBinds,
5362 .buffer_bind_count = pBindInfo[i].bufferBindCount,
5363 .image_opaque_binds = pBindInfo[i].pImageOpaqueBinds,
5364 .image_opaque_bind_count = pBindInfo[i].imageOpaqueBindCount,
5365 .wait_semaphores = pBindInfo[i].pWaitSemaphores,
5366 .wait_semaphore_count = pBindInfo[i].waitSemaphoreCount,
5367 .signal_semaphores = pBindInfo[i].pSignalSemaphores,
5368 .signal_semaphore_count = pBindInfo[i].signalSemaphoreCount,
5369 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
5370 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
5371 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
5372 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
5373 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
5374 });
5375
5376 if (result != VK_SUCCESS)
5377 return result;
5378 }
5379
5380 if (fence != VK_NULL_HANDLE && !bindInfoCount) {
5381 result = radv_signal_fence(queue, fence);
5382 if (result != VK_SUCCESS)
5383 return result;
5384 }
5385
5386 return VK_SUCCESS;
5387 }
5388
5389 VkResult radv_CreateFence(
5390 VkDevice _device,
5391 const VkFenceCreateInfo* pCreateInfo,
5392 const VkAllocationCallbacks* pAllocator,
5393 VkFence* pFence)
5394 {
5395 RADV_FROM_HANDLE(radv_device, device, _device);
5396 const VkExportFenceCreateInfo *export =
5397 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
5398 VkExternalFenceHandleTypeFlags handleTypes =
5399 export ? export->handleTypes : 0;
5400
5401 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
5402 sizeof(*fence), 8,
5403 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5404
5405 if (!fence)
5406 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5407
5408 fence->fence_wsi = NULL;
5409 fence->temp_syncobj = 0;
5410 if (device->always_use_syncobj || handleTypes) {
5411 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
5412 if (ret) {
5413 vk_free2(&device->alloc, pAllocator, fence);
5414 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5415 }
5416 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
5417 device->ws->signal_syncobj(device->ws, fence->syncobj);
5418 }
5419 fence->fence = NULL;
5420 } else {
5421 fence->fence = device->ws->create_fence();
5422 if (!fence->fence) {
5423 vk_free2(&device->alloc, pAllocator, fence);
5424 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5425 }
5426 fence->syncobj = 0;
5427 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
5428 device->ws->signal_fence(fence->fence);
5429 }
5430
5431 *pFence = radv_fence_to_handle(fence);
5432
5433 return VK_SUCCESS;
5434 }
5435
5436 void radv_DestroyFence(
5437 VkDevice _device,
5438 VkFence _fence,
5439 const VkAllocationCallbacks* pAllocator)
5440 {
5441 RADV_FROM_HANDLE(radv_device, device, _device);
5442 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5443
5444 if (!fence)
5445 return;
5446
5447 if (fence->temp_syncobj)
5448 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5449 if (fence->syncobj)
5450 device->ws->destroy_syncobj(device->ws, fence->syncobj);
5451 if (fence->fence)
5452 device->ws->destroy_fence(fence->fence);
5453 if (fence->fence_wsi)
5454 fence->fence_wsi->destroy(fence->fence_wsi);
5455 vk_free2(&device->alloc, pAllocator, fence);
5456 }
5457
5458
5459 uint64_t radv_get_current_time(void)
5460 {
5461 struct timespec tv;
5462 clock_gettime(CLOCK_MONOTONIC, &tv);
5463 return tv.tv_nsec + tv.tv_sec*1000000000ull;
5464 }
5465
5466 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
5467 {
5468 uint64_t current_time = radv_get_current_time();
5469
5470 timeout = MIN2(UINT64_MAX - current_time, timeout);
5471
5472 return current_time + timeout;
5473 }
5474
5475
5476 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
5477 uint32_t fenceCount, const VkFence *pFences)
5478 {
5479 for (uint32_t i = 0; i < fenceCount; ++i) {
5480 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5481 if (fence->fence == NULL || fence->syncobj ||
5482 fence->temp_syncobj || fence->fence_wsi ||
5483 (!device->ws->is_fence_waitable(fence->fence)))
5484 return false;
5485 }
5486 return true;
5487 }
5488
5489 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
5490 {
5491 for (uint32_t i = 0; i < fenceCount; ++i) {
5492 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5493 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
5494 return false;
5495 }
5496 return true;
5497 }
5498
5499 VkResult radv_WaitForFences(
5500 VkDevice _device,
5501 uint32_t fenceCount,
5502 const VkFence* pFences,
5503 VkBool32 waitAll,
5504 uint64_t timeout)
5505 {
5506 RADV_FROM_HANDLE(radv_device, device, _device);
5507 timeout = radv_get_absolute_timeout(timeout);
5508
5509 if (device->always_use_syncobj &&
5510 radv_all_fences_syncobj(fenceCount, pFences))
5511 {
5512 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
5513 if (!handles)
5514 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5515
5516 for (uint32_t i = 0; i < fenceCount; ++i) {
5517 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5518 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
5519 }
5520
5521 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
5522
5523 free(handles);
5524 return success ? VK_SUCCESS : VK_TIMEOUT;
5525 }
5526
5527 if (!waitAll && fenceCount > 1) {
5528 /* Not doing this by default for waitAll, due to needing to allocate twice. */
5529 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
5530 uint32_t wait_count = 0;
5531 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
5532 if (!fences)
5533 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5534
5535 for (uint32_t i = 0; i < fenceCount; ++i) {
5536 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5537
5538 if (device->ws->fence_wait(device->ws, fence->fence, false, 0)) {
5539 free(fences);
5540 return VK_SUCCESS;
5541 }
5542
5543 fences[wait_count++] = fence->fence;
5544 }
5545
5546 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
5547 waitAll, timeout - radv_get_current_time());
5548
5549 free(fences);
5550 return success ? VK_SUCCESS : VK_TIMEOUT;
5551 }
5552
5553 while(radv_get_current_time() <= timeout) {
5554 for (uint32_t i = 0; i < fenceCount; ++i) {
5555 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
5556 return VK_SUCCESS;
5557 }
5558 }
5559 return VK_TIMEOUT;
5560 }
5561
5562 for (uint32_t i = 0; i < fenceCount; ++i) {
5563 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5564 bool expired = false;
5565
5566 if (fence->temp_syncobj) {
5567 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
5568 return VK_TIMEOUT;
5569 continue;
5570 }
5571
5572 if (fence->syncobj) {
5573 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
5574 return VK_TIMEOUT;
5575 continue;
5576 }
5577
5578 if (fence->fence) {
5579 if (!device->ws->is_fence_waitable(fence->fence)) {
5580 while(!device->ws->is_fence_waitable(fence->fence) &&
5581 radv_get_current_time() <= timeout)
5582 /* Do nothing */;
5583 }
5584
5585 expired = device->ws->fence_wait(device->ws,
5586 fence->fence,
5587 true, timeout);
5588 if (!expired)
5589 return VK_TIMEOUT;
5590 }
5591
5592 if (fence->fence_wsi) {
5593 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
5594 if (result != VK_SUCCESS)
5595 return result;
5596 }
5597 }
5598
5599 return VK_SUCCESS;
5600 }
5601
5602 VkResult radv_ResetFences(VkDevice _device,
5603 uint32_t fenceCount,
5604 const VkFence *pFences)
5605 {
5606 RADV_FROM_HANDLE(radv_device, device, _device);
5607
5608 for (unsigned i = 0; i < fenceCount; ++i) {
5609 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5610 if (fence->fence)
5611 device->ws->reset_fence(fence->fence);
5612
5613 /* Per spec, we first restore the permanent payload, and then reset, so
5614 * having a temp syncobj should not skip resetting the permanent syncobj. */
5615 if (fence->temp_syncobj) {
5616 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5617 fence->temp_syncobj = 0;
5618 }
5619
5620 if (fence->syncobj) {
5621 device->ws->reset_syncobj(device->ws, fence->syncobj);
5622 }
5623 }
5624
5625 return VK_SUCCESS;
5626 }
5627
5628 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
5629 {
5630 RADV_FROM_HANDLE(radv_device, device, _device);
5631 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5632
5633 if (fence->temp_syncobj) {
5634 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
5635 return success ? VK_SUCCESS : VK_NOT_READY;
5636 }
5637
5638 if (fence->syncobj) {
5639 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
5640 return success ? VK_SUCCESS : VK_NOT_READY;
5641 }
5642
5643 if (fence->fence) {
5644 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
5645 return VK_NOT_READY;
5646 }
5647 if (fence->fence_wsi) {
5648 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
5649
5650 if (result != VK_SUCCESS) {
5651 if (result == VK_TIMEOUT)
5652 return VK_NOT_READY;
5653 return result;
5654 }
5655 }
5656 return VK_SUCCESS;
5657 }
5658
5659
5660 // Queue semaphore functions
5661
5662 static void
5663 radv_create_timeline(struct radv_timeline *timeline, uint64_t value)
5664 {
5665 timeline->highest_signaled = value;
5666 timeline->highest_submitted = value;
5667 list_inithead(&timeline->points);
5668 list_inithead(&timeline->free_points);
5669 list_inithead(&timeline->waiters);
5670 pthread_mutex_init(&timeline->mutex, NULL);
5671 }
5672
5673 static void
5674 radv_destroy_timeline(struct radv_device *device,
5675 struct radv_timeline *timeline)
5676 {
5677 list_for_each_entry_safe(struct radv_timeline_point, point,
5678 &timeline->free_points, list) {
5679 list_del(&point->list);
5680 device->ws->destroy_syncobj(device->ws, point->syncobj);
5681 free(point);
5682 }
5683 list_for_each_entry_safe(struct radv_timeline_point, point,
5684 &timeline->points, list) {
5685 list_del(&point->list);
5686 device->ws->destroy_syncobj(device->ws, point->syncobj);
5687 free(point);
5688 }
5689 pthread_mutex_destroy(&timeline->mutex);
5690 }
5691
5692 static void
5693 radv_timeline_gc_locked(struct radv_device *device,
5694 struct radv_timeline *timeline)
5695 {
5696 list_for_each_entry_safe(struct radv_timeline_point, point,
5697 &timeline->points, list) {
5698 if (point->wait_count || point->value > timeline->highest_submitted)
5699 return;
5700
5701 if (device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, 0)) {
5702 timeline->highest_signaled = point->value;
5703 list_del(&point->list);
5704 list_add(&point->list, &timeline->free_points);
5705 }
5706 }
5707 }
5708
5709 static struct radv_timeline_point *
5710 radv_timeline_find_point_at_least_locked(struct radv_device *device,
5711 struct radv_timeline *timeline,
5712 uint64_t p)
5713 {
5714 radv_timeline_gc_locked(device, timeline);
5715
5716 if (p <= timeline->highest_signaled)
5717 return NULL;
5718
5719 list_for_each_entry(struct radv_timeline_point, point,
5720 &timeline->points, list) {
5721 if (point->value >= p) {
5722 ++point->wait_count;
5723 return point;
5724 }
5725 }
5726 return NULL;
5727 }
5728
5729 static struct radv_timeline_point *
5730 radv_timeline_add_point_locked(struct radv_device *device,
5731 struct radv_timeline *timeline,
5732 uint64_t p)
5733 {
5734 radv_timeline_gc_locked(device, timeline);
5735
5736 struct radv_timeline_point *ret = NULL;
5737 struct radv_timeline_point *prev = NULL;
5738
5739 if (p <= timeline->highest_signaled)
5740 return NULL;
5741
5742 list_for_each_entry(struct radv_timeline_point, point,
5743 &timeline->points, list) {
5744 if (point->value == p) {
5745 return NULL;
5746 }
5747
5748 if (point->value < p)
5749 prev = point;
5750 }
5751
5752 if (list_is_empty(&timeline->free_points)) {
5753 ret = malloc(sizeof(struct radv_timeline_point));
5754 device->ws->create_syncobj(device->ws, &ret->syncobj);
5755 } else {
5756 ret = list_first_entry(&timeline->free_points, struct radv_timeline_point, list);
5757 list_del(&ret->list);
5758
5759 device->ws->reset_syncobj(device->ws, ret->syncobj);
5760 }
5761
5762 ret->value = p;
5763 ret->wait_count = 1;
5764
5765 if (prev) {
5766 list_add(&ret->list, &prev->list);
5767 } else {
5768 list_addtail(&ret->list, &timeline->points);
5769 }
5770 return ret;
5771 }
5772
5773
5774 static VkResult
5775 radv_timeline_wait_locked(struct radv_device *device,
5776 struct radv_timeline *timeline,
5777 uint64_t value,
5778 uint64_t abs_timeout)
5779 {
5780 while(timeline->highest_submitted < value) {
5781 struct timespec abstime;
5782 timespec_from_nsec(&abstime, abs_timeout);
5783
5784 pthread_cond_timedwait(&device->timeline_cond, &timeline->mutex, &abstime);
5785
5786 if (radv_get_current_time() >= abs_timeout && timeline->highest_submitted < value)
5787 return VK_TIMEOUT;
5788 }
5789
5790 struct radv_timeline_point *point = radv_timeline_find_point_at_least_locked(device, timeline, value);
5791 if (!point)
5792 return VK_SUCCESS;
5793
5794 pthread_mutex_unlock(&timeline->mutex);
5795
5796 bool success = device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, abs_timeout);
5797
5798 pthread_mutex_lock(&timeline->mutex);
5799 point->wait_count--;
5800 return success ? VK_SUCCESS : VK_TIMEOUT;
5801 }
5802
5803 static void
5804 radv_timeline_trigger_waiters_locked(struct radv_timeline *timeline,
5805 struct list_head *processing_list)
5806 {
5807 list_for_each_entry_safe(struct radv_timeline_waiter, waiter,
5808 &timeline->waiters, list) {
5809 if (waiter->value > timeline->highest_submitted)
5810 continue;
5811
5812 if (p_atomic_dec_zero(&waiter->submission->submission_wait_count)) {
5813 list_addtail(&waiter->submission->processing_list, processing_list);
5814 }
5815 list_del(&waiter->list);
5816 }
5817 }
5818
5819 static
5820 void radv_destroy_semaphore_part(struct radv_device *device,
5821 struct radv_semaphore_part *part)
5822 {
5823 switch(part->kind) {
5824 case RADV_SEMAPHORE_NONE:
5825 break;
5826 case RADV_SEMAPHORE_WINSYS:
5827 device->ws->destroy_sem(part->ws_sem);
5828 break;
5829 case RADV_SEMAPHORE_TIMELINE:
5830 radv_destroy_timeline(device, &part->timeline);
5831 break;
5832 case RADV_SEMAPHORE_SYNCOBJ:
5833 device->ws->destroy_syncobj(device->ws, part->syncobj);
5834 break;
5835 }
5836 part->kind = RADV_SEMAPHORE_NONE;
5837 }
5838
5839 static VkSemaphoreTypeKHR
5840 radv_get_semaphore_type(const void *pNext, uint64_t *initial_value)
5841 {
5842 const VkSemaphoreTypeCreateInfo *type_info =
5843 vk_find_struct_const(pNext, SEMAPHORE_TYPE_CREATE_INFO);
5844
5845 if (!type_info)
5846 return VK_SEMAPHORE_TYPE_BINARY;
5847
5848 if (initial_value)
5849 *initial_value = type_info->initialValue;
5850 return type_info->semaphoreType;
5851 }
5852
5853 VkResult radv_CreateSemaphore(
5854 VkDevice _device,
5855 const VkSemaphoreCreateInfo* pCreateInfo,
5856 const VkAllocationCallbacks* pAllocator,
5857 VkSemaphore* pSemaphore)
5858 {
5859 RADV_FROM_HANDLE(radv_device, device, _device);
5860 const VkExportSemaphoreCreateInfo *export =
5861 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
5862 VkExternalSemaphoreHandleTypeFlags handleTypes =
5863 export ? export->handleTypes : 0;
5864 uint64_t initial_value = 0;
5865 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pCreateInfo->pNext, &initial_value);
5866
5867 struct radv_semaphore *sem = vk_alloc2(&device->alloc, pAllocator,
5868 sizeof(*sem), 8,
5869 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5870 if (!sem)
5871 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5872
5873 sem->temporary.kind = RADV_SEMAPHORE_NONE;
5874 sem->permanent.kind = RADV_SEMAPHORE_NONE;
5875
5876 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
5877 radv_create_timeline(&sem->permanent.timeline, initial_value);
5878 sem->permanent.kind = RADV_SEMAPHORE_TIMELINE;
5879 } else if (device->always_use_syncobj || handleTypes) {
5880 assert (device->physical_device->rad_info.has_syncobj);
5881 int ret = device->ws->create_syncobj(device->ws, &sem->permanent.syncobj);
5882 if (ret) {
5883 vk_free2(&device->alloc, pAllocator, sem);
5884 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5885 }
5886 sem->permanent.kind = RADV_SEMAPHORE_SYNCOBJ;
5887 } else {
5888 sem->permanent.ws_sem = device->ws->create_sem(device->ws);
5889 if (!sem->permanent.ws_sem) {
5890 vk_free2(&device->alloc, pAllocator, sem);
5891 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5892 }
5893 sem->permanent.kind = RADV_SEMAPHORE_WINSYS;
5894 }
5895
5896 *pSemaphore = radv_semaphore_to_handle(sem);
5897 return VK_SUCCESS;
5898 }
5899
5900 void radv_DestroySemaphore(
5901 VkDevice _device,
5902 VkSemaphore _semaphore,
5903 const VkAllocationCallbacks* pAllocator)
5904 {
5905 RADV_FROM_HANDLE(radv_device, device, _device);
5906 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
5907 if (!_semaphore)
5908 return;
5909
5910 radv_destroy_semaphore_part(device, &sem->temporary);
5911 radv_destroy_semaphore_part(device, &sem->permanent);
5912 vk_free2(&device->alloc, pAllocator, sem);
5913 }
5914
5915 VkResult
5916 radv_GetSemaphoreCounterValue(VkDevice _device,
5917 VkSemaphore _semaphore,
5918 uint64_t* pValue)
5919 {
5920 RADV_FROM_HANDLE(radv_device, device, _device);
5921 RADV_FROM_HANDLE(radv_semaphore, semaphore, _semaphore);
5922
5923 struct radv_semaphore_part *part =
5924 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
5925
5926 switch (part->kind) {
5927 case RADV_SEMAPHORE_TIMELINE: {
5928 pthread_mutex_lock(&part->timeline.mutex);
5929 radv_timeline_gc_locked(device, &part->timeline);
5930 *pValue = part->timeline.highest_signaled;
5931 pthread_mutex_unlock(&part->timeline.mutex);
5932 return VK_SUCCESS;
5933 }
5934 case RADV_SEMAPHORE_NONE:
5935 case RADV_SEMAPHORE_SYNCOBJ:
5936 case RADV_SEMAPHORE_WINSYS:
5937 unreachable("Invalid semaphore type");
5938 }
5939 unreachable("Unhandled semaphore type");
5940 }
5941
5942
5943 static VkResult
5944 radv_wait_timelines(struct radv_device *device,
5945 const VkSemaphoreWaitInfo* pWaitInfo,
5946 uint64_t abs_timeout)
5947 {
5948 if ((pWaitInfo->flags & VK_SEMAPHORE_WAIT_ANY_BIT_KHR) && pWaitInfo->semaphoreCount > 1) {
5949 for (;;) {
5950 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
5951 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
5952 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
5953 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], 0);
5954 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
5955
5956 if (result == VK_SUCCESS)
5957 return VK_SUCCESS;
5958 }
5959 if (radv_get_current_time() > abs_timeout)
5960 return VK_TIMEOUT;
5961 }
5962 }
5963
5964 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
5965 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
5966 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
5967 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], abs_timeout);
5968 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
5969
5970 if (result != VK_SUCCESS)
5971 return result;
5972 }
5973 return VK_SUCCESS;
5974 }
5975 VkResult
5976 radv_WaitSemaphores(VkDevice _device,
5977 const VkSemaphoreWaitInfo* pWaitInfo,
5978 uint64_t timeout)
5979 {
5980 RADV_FROM_HANDLE(radv_device, device, _device);
5981 uint64_t abs_timeout = radv_get_absolute_timeout(timeout);
5982 return radv_wait_timelines(device, pWaitInfo, abs_timeout);
5983 }
5984
5985 VkResult
5986 radv_SignalSemaphore(VkDevice _device,
5987 const VkSemaphoreSignalInfo* pSignalInfo)
5988 {
5989 RADV_FROM_HANDLE(radv_device, device, _device);
5990 RADV_FROM_HANDLE(radv_semaphore, semaphore, pSignalInfo->semaphore);
5991
5992 struct radv_semaphore_part *part =
5993 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
5994
5995 switch(part->kind) {
5996 case RADV_SEMAPHORE_TIMELINE: {
5997 pthread_mutex_lock(&part->timeline.mutex);
5998 radv_timeline_gc_locked(device, &part->timeline);
5999 part->timeline.highest_submitted = MAX2(part->timeline.highest_submitted, pSignalInfo->value);
6000 part->timeline.highest_signaled = MAX2(part->timeline.highest_signaled, pSignalInfo->value);
6001
6002 struct list_head processing_list;
6003 list_inithead(&processing_list);
6004 radv_timeline_trigger_waiters_locked(&part->timeline, &processing_list);
6005 pthread_mutex_unlock(&part->timeline.mutex);
6006
6007 return radv_process_submissions(&processing_list);
6008 }
6009 case RADV_SEMAPHORE_NONE:
6010 case RADV_SEMAPHORE_SYNCOBJ:
6011 case RADV_SEMAPHORE_WINSYS:
6012 unreachable("Invalid semaphore type");
6013 }
6014 return VK_SUCCESS;
6015 }
6016
6017
6018
6019 VkResult radv_CreateEvent(
6020 VkDevice _device,
6021 const VkEventCreateInfo* pCreateInfo,
6022 const VkAllocationCallbacks* pAllocator,
6023 VkEvent* pEvent)
6024 {
6025 RADV_FROM_HANDLE(radv_device, device, _device);
6026 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
6027 sizeof(*event), 8,
6028 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6029
6030 if (!event)
6031 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6032
6033 event->bo = device->ws->buffer_create(device->ws, 8, 8,
6034 RADEON_DOMAIN_GTT,
6035 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
6036 RADV_BO_PRIORITY_FENCE);
6037 if (!event->bo) {
6038 vk_free2(&device->alloc, pAllocator, event);
6039 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6040 }
6041
6042 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
6043
6044 *pEvent = radv_event_to_handle(event);
6045
6046 return VK_SUCCESS;
6047 }
6048
6049 void radv_DestroyEvent(
6050 VkDevice _device,
6051 VkEvent _event,
6052 const VkAllocationCallbacks* pAllocator)
6053 {
6054 RADV_FROM_HANDLE(radv_device, device, _device);
6055 RADV_FROM_HANDLE(radv_event, event, _event);
6056
6057 if (!event)
6058 return;
6059 device->ws->buffer_destroy(event->bo);
6060 vk_free2(&device->alloc, pAllocator, event);
6061 }
6062
6063 VkResult radv_GetEventStatus(
6064 VkDevice _device,
6065 VkEvent _event)
6066 {
6067 RADV_FROM_HANDLE(radv_event, event, _event);
6068
6069 if (*event->map == 1)
6070 return VK_EVENT_SET;
6071 return VK_EVENT_RESET;
6072 }
6073
6074 VkResult radv_SetEvent(
6075 VkDevice _device,
6076 VkEvent _event)
6077 {
6078 RADV_FROM_HANDLE(radv_event, event, _event);
6079 *event->map = 1;
6080
6081 return VK_SUCCESS;
6082 }
6083
6084 VkResult radv_ResetEvent(
6085 VkDevice _device,
6086 VkEvent _event)
6087 {
6088 RADV_FROM_HANDLE(radv_event, event, _event);
6089 *event->map = 0;
6090
6091 return VK_SUCCESS;
6092 }
6093
6094 VkResult radv_CreateBuffer(
6095 VkDevice _device,
6096 const VkBufferCreateInfo* pCreateInfo,
6097 const VkAllocationCallbacks* pAllocator,
6098 VkBuffer* pBuffer)
6099 {
6100 RADV_FROM_HANDLE(radv_device, device, _device);
6101 struct radv_buffer *buffer;
6102
6103 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
6104
6105 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
6106 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6107 if (buffer == NULL)
6108 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6109
6110 buffer->size = pCreateInfo->size;
6111 buffer->usage = pCreateInfo->usage;
6112 buffer->bo = NULL;
6113 buffer->offset = 0;
6114 buffer->flags = pCreateInfo->flags;
6115
6116 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
6117 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
6118
6119 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
6120 buffer->bo = device->ws->buffer_create(device->ws,
6121 align64(buffer->size, 4096),
6122 4096, 0, RADEON_FLAG_VIRTUAL,
6123 RADV_BO_PRIORITY_VIRTUAL);
6124 if (!buffer->bo) {
6125 vk_free2(&device->alloc, pAllocator, buffer);
6126 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6127 }
6128 }
6129
6130 *pBuffer = radv_buffer_to_handle(buffer);
6131
6132 return VK_SUCCESS;
6133 }
6134
6135 void radv_DestroyBuffer(
6136 VkDevice _device,
6137 VkBuffer _buffer,
6138 const VkAllocationCallbacks* pAllocator)
6139 {
6140 RADV_FROM_HANDLE(radv_device, device, _device);
6141 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
6142
6143 if (!buffer)
6144 return;
6145
6146 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
6147 device->ws->buffer_destroy(buffer->bo);
6148
6149 vk_free2(&device->alloc, pAllocator, buffer);
6150 }
6151
6152 VkDeviceAddress radv_GetBufferDeviceAddress(
6153 VkDevice device,
6154 const VkBufferDeviceAddressInfo* pInfo)
6155 {
6156 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
6157 return radv_buffer_get_va(buffer->bo) + buffer->offset;
6158 }
6159
6160
6161 uint64_t radv_GetBufferOpaqueCaptureAddress(VkDevice device,
6162 const VkBufferDeviceAddressInfo* pInfo)
6163 {
6164 return 0;
6165 }
6166
6167 uint64_t radv_GetDeviceMemoryOpaqueCaptureAddress(VkDevice device,
6168 const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo)
6169 {
6170 return 0;
6171 }
6172
6173 static inline unsigned
6174 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
6175 {
6176 if (stencil)
6177 return plane->surface.u.legacy.stencil_tiling_index[level];
6178 else
6179 return plane->surface.u.legacy.tiling_index[level];
6180 }
6181
6182 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
6183 {
6184 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
6185 }
6186
6187 static uint32_t
6188 radv_init_dcc_control_reg(struct radv_device *device,
6189 struct radv_image_view *iview)
6190 {
6191 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
6192 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
6193 unsigned max_compressed_block_size;
6194 unsigned independent_128b_blocks;
6195 unsigned independent_64b_blocks;
6196
6197 if (!radv_dcc_enabled(iview->image, iview->base_mip))
6198 return 0;
6199
6200 if (!device->physical_device->rad_info.has_dedicated_vram) {
6201 /* amdvlk: [min-compressed-block-size] should be set to 32 for
6202 * dGPU and 64 for APU because all of our APUs to date use
6203 * DIMMs which have a request granularity size of 64B while all
6204 * other chips have a 32B request size.
6205 */
6206 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
6207 }
6208
6209 if (device->physical_device->rad_info.chip_class >= GFX10) {
6210 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6211 independent_64b_blocks = 0;
6212 independent_128b_blocks = 1;
6213 } else {
6214 independent_128b_blocks = 0;
6215
6216 if (iview->image->info.samples > 1) {
6217 if (iview->image->planes[0].surface.bpe == 1)
6218 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6219 else if (iview->image->planes[0].surface.bpe == 2)
6220 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6221 }
6222
6223 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
6224 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
6225 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
6226 /* If this DCC image is potentially going to be used in texture
6227 * fetches, we need some special settings.
6228 */
6229 independent_64b_blocks = 1;
6230 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6231 } else {
6232 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
6233 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
6234 * big as possible for better compression state.
6235 */
6236 independent_64b_blocks = 0;
6237 max_compressed_block_size = max_uncompressed_block_size;
6238 }
6239 }
6240
6241 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
6242 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
6243 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
6244 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
6245 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
6246 }
6247
6248 void
6249 radv_initialise_color_surface(struct radv_device *device,
6250 struct radv_color_buffer_info *cb,
6251 struct radv_image_view *iview)
6252 {
6253 const struct vk_format_description *desc;
6254 unsigned ntype, format, swap, endian;
6255 unsigned blend_clamp = 0, blend_bypass = 0;
6256 uint64_t va;
6257 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
6258 const struct radeon_surf *surf = &plane->surface;
6259
6260 desc = vk_format_description(iview->vk_format);
6261
6262 memset(cb, 0, sizeof(*cb));
6263
6264 /* Intensity is implemented as Red, so treat it that way. */
6265 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
6266
6267 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
6268
6269 cb->cb_color_base = va >> 8;
6270
6271 if (device->physical_device->rad_info.chip_class >= GFX9) {
6272 struct gfx9_surf_meta_flags meta;
6273 if (iview->image->dcc_offset)
6274 meta = surf->u.gfx9.dcc;
6275 else
6276 meta = surf->u.gfx9.cmask;
6277
6278 if (device->physical_device->rad_info.chip_class >= GFX10) {
6279 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6280 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6281 S_028EE0_CMASK_PIPE_ALIGNED(surf->u.gfx9.cmask.pipe_aligned) |
6282 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
6283 } else {
6284 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6285 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6286 S_028C74_RB_ALIGNED(meta.rb_aligned) |
6287 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
6288 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
6289 }
6290
6291 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
6292 cb->cb_color_base |= surf->tile_swizzle;
6293 } else {
6294 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
6295 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
6296
6297 cb->cb_color_base += level_info->offset >> 8;
6298 if (level_info->mode == RADEON_SURF_MODE_2D)
6299 cb->cb_color_base |= surf->tile_swizzle;
6300
6301 pitch_tile_max = level_info->nblk_x / 8 - 1;
6302 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
6303 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
6304
6305 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
6306 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
6307 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
6308
6309 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
6310
6311 if (radv_image_has_fmask(iview->image)) {
6312 if (device->physical_device->rad_info.chip_class >= GFX7)
6313 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
6314 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
6315 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
6316 } else {
6317 /* This must be set for fast clear to work without FMASK. */
6318 if (device->physical_device->rad_info.chip_class >= GFX7)
6319 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
6320 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
6321 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
6322 }
6323 }
6324
6325 /* CMASK variables */
6326 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6327 va += iview->image->cmask_offset;
6328 cb->cb_color_cmask = va >> 8;
6329
6330 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6331 va += iview->image->dcc_offset;
6332
6333 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
6334 device->physical_device->rad_info.chip_class <= GFX8)
6335 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
6336
6337 unsigned dcc_tile_swizzle = surf->tile_swizzle;
6338 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
6339
6340 cb->cb_dcc_base = va >> 8;
6341 cb->cb_dcc_base |= dcc_tile_swizzle;
6342
6343 /* GFX10 field has the same base shift as the GFX6 field. */
6344 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6345 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
6346 S_028C6C_SLICE_MAX_GFX10(max_slice);
6347
6348 if (iview->image->info.samples > 1) {
6349 unsigned log_samples = util_logbase2(iview->image->info.samples);
6350
6351 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
6352 S_028C74_NUM_FRAGMENTS(log_samples);
6353 }
6354
6355 if (radv_image_has_fmask(iview->image)) {
6356 va = radv_buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask_offset;
6357 cb->cb_color_fmask = va >> 8;
6358 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
6359 } else {
6360 cb->cb_color_fmask = cb->cb_color_base;
6361 }
6362
6363 ntype = radv_translate_color_numformat(iview->vk_format,
6364 desc,
6365 vk_format_get_first_non_void_channel(iview->vk_format));
6366 format = radv_translate_colorformat(iview->vk_format);
6367 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
6368 radv_finishme("Illegal color\n");
6369 swap = radv_translate_colorswap(iview->vk_format, false);
6370 endian = radv_colorformat_endian_swap(format);
6371
6372 /* blend clamp should be set for all NORM/SRGB types */
6373 if (ntype == V_028C70_NUMBER_UNORM ||
6374 ntype == V_028C70_NUMBER_SNORM ||
6375 ntype == V_028C70_NUMBER_SRGB)
6376 blend_clamp = 1;
6377
6378 /* set blend bypass according to docs if SINT/UINT or
6379 8/24 COLOR variants */
6380 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
6381 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
6382 format == V_028C70_COLOR_X24_8_32_FLOAT) {
6383 blend_clamp = 0;
6384 blend_bypass = 1;
6385 }
6386 #if 0
6387 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
6388 (format == V_028C70_COLOR_8 ||
6389 format == V_028C70_COLOR_8_8 ||
6390 format == V_028C70_COLOR_8_8_8_8))
6391 ->color_is_int8 = true;
6392 #endif
6393 cb->cb_color_info = S_028C70_FORMAT(format) |
6394 S_028C70_COMP_SWAP(swap) |
6395 S_028C70_BLEND_CLAMP(blend_clamp) |
6396 S_028C70_BLEND_BYPASS(blend_bypass) |
6397 S_028C70_SIMPLE_FLOAT(1) |
6398 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
6399 ntype != V_028C70_NUMBER_SNORM &&
6400 ntype != V_028C70_NUMBER_SRGB &&
6401 format != V_028C70_COLOR_8_24 &&
6402 format != V_028C70_COLOR_24_8) |
6403 S_028C70_NUMBER_TYPE(ntype) |
6404 S_028C70_ENDIAN(endian);
6405 if (radv_image_has_fmask(iview->image)) {
6406 cb->cb_color_info |= S_028C70_COMPRESSION(1);
6407 if (device->physical_device->rad_info.chip_class == GFX6) {
6408 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
6409 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
6410 }
6411
6412 if (radv_image_is_tc_compat_cmask(iview->image)) {
6413 /* Allow the texture block to read FMASK directly
6414 * without decompressing it. This bit must be cleared
6415 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
6416 * otherwise the operation doesn't happen.
6417 */
6418 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
6419
6420 /* Set CMASK into a tiling format that allows the
6421 * texture block to read it.
6422 */
6423 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
6424 }
6425 }
6426
6427 if (radv_image_has_cmask(iview->image) &&
6428 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
6429 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
6430
6431 if (radv_dcc_enabled(iview->image, iview->base_mip))
6432 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
6433
6434 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
6435
6436 /* This must be set for fast clear to work without FMASK. */
6437 if (!radv_image_has_fmask(iview->image) &&
6438 device->physical_device->rad_info.chip_class == GFX6) {
6439 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
6440 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
6441 }
6442
6443 if (device->physical_device->rad_info.chip_class >= GFX9) {
6444 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
6445
6446 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
6447 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
6448 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
6449 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
6450
6451 if (device->physical_device->rad_info.chip_class >= GFX10) {
6452 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
6453
6454 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
6455 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
6456 S_028EE0_RESOURCE_LEVEL(1);
6457 } else {
6458 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
6459 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
6460 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
6461 }
6462
6463 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
6464 S_028C68_MIP0_HEIGHT(height - 1) |
6465 S_028C68_MAX_MIP(iview->image->info.levels - 1);
6466 }
6467 }
6468
6469 static unsigned
6470 radv_calc_decompress_on_z_planes(struct radv_device *device,
6471 struct radv_image_view *iview)
6472 {
6473 unsigned max_zplanes = 0;
6474
6475 assert(radv_image_is_tc_compat_htile(iview->image));
6476
6477 if (device->physical_device->rad_info.chip_class >= GFX9) {
6478 /* Default value for 32-bit depth surfaces. */
6479 max_zplanes = 4;
6480
6481 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
6482 iview->image->info.samples > 1)
6483 max_zplanes = 2;
6484
6485 max_zplanes = max_zplanes + 1;
6486 } else {
6487 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
6488 /* Do not enable Z plane compression for 16-bit depth
6489 * surfaces because isn't supported on GFX8. Only
6490 * 32-bit depth surfaces are supported by the hardware.
6491 * This allows to maintain shader compatibility and to
6492 * reduce the number of depth decompressions.
6493 */
6494 max_zplanes = 1;
6495 } else {
6496 if (iview->image->info.samples <= 1)
6497 max_zplanes = 5;
6498 else if (iview->image->info.samples <= 4)
6499 max_zplanes = 3;
6500 else
6501 max_zplanes = 2;
6502 }
6503 }
6504
6505 return max_zplanes;
6506 }
6507
6508 void
6509 radv_initialise_ds_surface(struct radv_device *device,
6510 struct radv_ds_buffer_info *ds,
6511 struct radv_image_view *iview)
6512 {
6513 unsigned level = iview->base_mip;
6514 unsigned format, stencil_format;
6515 uint64_t va, s_offs, z_offs;
6516 bool stencil_only = false;
6517 const struct radv_image_plane *plane = &iview->image->planes[0];
6518 const struct radeon_surf *surf = &plane->surface;
6519
6520 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
6521
6522 memset(ds, 0, sizeof(*ds));
6523 switch (iview->image->vk_format) {
6524 case VK_FORMAT_D24_UNORM_S8_UINT:
6525 case VK_FORMAT_X8_D24_UNORM_PACK32:
6526 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
6527 ds->offset_scale = 2.0f;
6528 break;
6529 case VK_FORMAT_D16_UNORM:
6530 case VK_FORMAT_D16_UNORM_S8_UINT:
6531 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
6532 ds->offset_scale = 4.0f;
6533 break;
6534 case VK_FORMAT_D32_SFLOAT:
6535 case VK_FORMAT_D32_SFLOAT_S8_UINT:
6536 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
6537 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
6538 ds->offset_scale = 1.0f;
6539 break;
6540 case VK_FORMAT_S8_UINT:
6541 stencil_only = true;
6542 break;
6543 default:
6544 break;
6545 }
6546
6547 format = radv_translate_dbformat(iview->image->vk_format);
6548 stencil_format = surf->has_stencil ?
6549 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
6550
6551 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6552 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
6553 S_028008_SLICE_MAX(max_slice);
6554 if (device->physical_device->rad_info.chip_class >= GFX10) {
6555 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
6556 S_028008_SLICE_MAX_HI(max_slice >> 11);
6557 }
6558
6559 ds->db_htile_data_base = 0;
6560 ds->db_htile_surface = 0;
6561
6562 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6563 s_offs = z_offs = va;
6564
6565 if (device->physical_device->rad_info.chip_class >= GFX9) {
6566 assert(surf->u.gfx9.surf_offset == 0);
6567 s_offs += surf->u.gfx9.stencil_offset;
6568
6569 ds->db_z_info = S_028038_FORMAT(format) |
6570 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
6571 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6572 S_028038_MAXMIP(iview->image->info.levels - 1) |
6573 S_028038_ZRANGE_PRECISION(1);
6574 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
6575 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
6576
6577 if (device->physical_device->rad_info.chip_class == GFX9) {
6578 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
6579 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
6580 }
6581
6582 ds->db_depth_view |= S_028008_MIPID(level);
6583 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
6584 S_02801C_Y_MAX(iview->image->info.height - 1);
6585
6586 if (radv_htile_enabled(iview->image, level)) {
6587 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
6588
6589 if (radv_image_is_tc_compat_htile(iview->image)) {
6590 unsigned max_zplanes =
6591 radv_calc_decompress_on_z_planes(device, iview);
6592
6593 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6594
6595 if (device->physical_device->rad_info.chip_class >= GFX10) {
6596 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
6597 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
6598 } else {
6599 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
6600 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
6601 }
6602 }
6603
6604 if (!surf->has_stencil)
6605 /* Use all of the htile_buffer for depth if there's no stencil. */
6606 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
6607 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6608 iview->image->htile_offset;
6609 ds->db_htile_data_base = va >> 8;
6610 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
6611 S_028ABC_PIPE_ALIGNED(surf->u.gfx9.htile.pipe_aligned);
6612
6613 if (device->physical_device->rad_info.chip_class == GFX9) {
6614 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(surf->u.gfx9.htile.rb_aligned);
6615 }
6616 }
6617 } else {
6618 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
6619
6620 if (stencil_only)
6621 level_info = &surf->u.legacy.stencil_level[level];
6622
6623 z_offs += surf->u.legacy.level[level].offset;
6624 s_offs += surf->u.legacy.stencil_level[level].offset;
6625
6626 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
6627 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
6628 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
6629
6630 if (iview->image->info.samples > 1)
6631 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
6632
6633 if (device->physical_device->rad_info.chip_class >= GFX7) {
6634 struct radeon_info *info = &device->physical_device->rad_info;
6635 unsigned tiling_index = surf->u.legacy.tiling_index[level];
6636 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
6637 unsigned macro_index = surf->u.legacy.macro_tile_index;
6638 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
6639 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
6640 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
6641
6642 if (stencil_only)
6643 tile_mode = stencil_tile_mode;
6644
6645 ds->db_depth_info |=
6646 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
6647 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
6648 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
6649 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
6650 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
6651 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
6652 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
6653 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
6654 } else {
6655 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
6656 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
6657 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
6658 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
6659 if (stencil_only)
6660 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
6661 }
6662
6663 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
6664 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
6665 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
6666
6667 if (radv_htile_enabled(iview->image, level)) {
6668 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
6669
6670 if (!surf->has_stencil &&
6671 !radv_image_is_tc_compat_htile(iview->image))
6672 /* Use all of the htile_buffer for depth if there's no stencil. */
6673 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
6674
6675 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6676 iview->image->htile_offset;
6677 ds->db_htile_data_base = va >> 8;
6678 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
6679
6680 if (radv_image_is_tc_compat_htile(iview->image)) {
6681 unsigned max_zplanes =
6682 radv_calc_decompress_on_z_planes(device, iview);
6683
6684 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
6685 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6686 }
6687 }
6688 }
6689
6690 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
6691 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
6692 }
6693
6694 VkResult radv_CreateFramebuffer(
6695 VkDevice _device,
6696 const VkFramebufferCreateInfo* pCreateInfo,
6697 const VkAllocationCallbacks* pAllocator,
6698 VkFramebuffer* pFramebuffer)
6699 {
6700 RADV_FROM_HANDLE(radv_device, device, _device);
6701 struct radv_framebuffer *framebuffer;
6702 const VkFramebufferAttachmentsCreateInfo *imageless_create_info =
6703 vk_find_struct_const(pCreateInfo->pNext,
6704 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO);
6705
6706 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
6707
6708 size_t size = sizeof(*framebuffer);
6709 if (!imageless_create_info)
6710 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
6711 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
6712 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6713 if (framebuffer == NULL)
6714 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6715
6716 framebuffer->attachment_count = pCreateInfo->attachmentCount;
6717 framebuffer->width = pCreateInfo->width;
6718 framebuffer->height = pCreateInfo->height;
6719 framebuffer->layers = pCreateInfo->layers;
6720 if (imageless_create_info) {
6721 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
6722 const VkFramebufferAttachmentImageInfo *attachment =
6723 imageless_create_info->pAttachmentImageInfos + i;
6724 framebuffer->width = MIN2(framebuffer->width, attachment->width);
6725 framebuffer->height = MIN2(framebuffer->height, attachment->height);
6726 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
6727 }
6728 } else {
6729 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
6730 VkImageView _iview = pCreateInfo->pAttachments[i];
6731 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
6732 framebuffer->attachments[i] = iview;
6733 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
6734 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
6735 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
6736 }
6737 }
6738
6739 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
6740 return VK_SUCCESS;
6741 }
6742
6743 void radv_DestroyFramebuffer(
6744 VkDevice _device,
6745 VkFramebuffer _fb,
6746 const VkAllocationCallbacks* pAllocator)
6747 {
6748 RADV_FROM_HANDLE(radv_device, device, _device);
6749 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
6750
6751 if (!fb)
6752 return;
6753 vk_free2(&device->alloc, pAllocator, fb);
6754 }
6755
6756 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
6757 {
6758 switch (address_mode) {
6759 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
6760 return V_008F30_SQ_TEX_WRAP;
6761 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
6762 return V_008F30_SQ_TEX_MIRROR;
6763 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
6764 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
6765 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
6766 return V_008F30_SQ_TEX_CLAMP_BORDER;
6767 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
6768 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
6769 default:
6770 unreachable("illegal tex wrap mode");
6771 break;
6772 }
6773 }
6774
6775 static unsigned
6776 radv_tex_compare(VkCompareOp op)
6777 {
6778 switch (op) {
6779 case VK_COMPARE_OP_NEVER:
6780 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
6781 case VK_COMPARE_OP_LESS:
6782 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
6783 case VK_COMPARE_OP_EQUAL:
6784 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
6785 case VK_COMPARE_OP_LESS_OR_EQUAL:
6786 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
6787 case VK_COMPARE_OP_GREATER:
6788 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
6789 case VK_COMPARE_OP_NOT_EQUAL:
6790 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
6791 case VK_COMPARE_OP_GREATER_OR_EQUAL:
6792 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
6793 case VK_COMPARE_OP_ALWAYS:
6794 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
6795 default:
6796 unreachable("illegal compare mode");
6797 break;
6798 }
6799 }
6800
6801 static unsigned
6802 radv_tex_filter(VkFilter filter, unsigned max_ansio)
6803 {
6804 switch (filter) {
6805 case VK_FILTER_NEAREST:
6806 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
6807 V_008F38_SQ_TEX_XY_FILTER_POINT);
6808 case VK_FILTER_LINEAR:
6809 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
6810 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
6811 case VK_FILTER_CUBIC_IMG:
6812 default:
6813 fprintf(stderr, "illegal texture filter");
6814 return 0;
6815 }
6816 }
6817
6818 static unsigned
6819 radv_tex_mipfilter(VkSamplerMipmapMode mode)
6820 {
6821 switch (mode) {
6822 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
6823 return V_008F38_SQ_TEX_Z_FILTER_POINT;
6824 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
6825 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
6826 default:
6827 return V_008F38_SQ_TEX_Z_FILTER_NONE;
6828 }
6829 }
6830
6831 static unsigned
6832 radv_tex_bordercolor(VkBorderColor bcolor)
6833 {
6834 switch (bcolor) {
6835 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
6836 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
6837 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
6838 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
6839 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
6840 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
6841 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
6842 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
6843 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
6844 default:
6845 break;
6846 }
6847 return 0;
6848 }
6849
6850 static unsigned
6851 radv_tex_aniso_filter(unsigned filter)
6852 {
6853 if (filter < 2)
6854 return 0;
6855 if (filter < 4)
6856 return 1;
6857 if (filter < 8)
6858 return 2;
6859 if (filter < 16)
6860 return 3;
6861 return 4;
6862 }
6863
6864 static unsigned
6865 radv_tex_filter_mode(VkSamplerReductionMode mode)
6866 {
6867 switch (mode) {
6868 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
6869 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
6870 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
6871 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
6872 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
6873 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
6874 default:
6875 break;
6876 }
6877 return 0;
6878 }
6879
6880 static uint32_t
6881 radv_get_max_anisotropy(struct radv_device *device,
6882 const VkSamplerCreateInfo *pCreateInfo)
6883 {
6884 if (device->force_aniso >= 0)
6885 return device->force_aniso;
6886
6887 if (pCreateInfo->anisotropyEnable &&
6888 pCreateInfo->maxAnisotropy > 1.0f)
6889 return (uint32_t)pCreateInfo->maxAnisotropy;
6890
6891 return 0;
6892 }
6893
6894 static void
6895 radv_init_sampler(struct radv_device *device,
6896 struct radv_sampler *sampler,
6897 const VkSamplerCreateInfo *pCreateInfo)
6898 {
6899 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
6900 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
6901 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
6902 device->physical_device->rad_info.chip_class == GFX9;
6903 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
6904 unsigned depth_compare_func = V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
6905
6906 const struct VkSamplerReductionModeCreateInfo *sampler_reduction =
6907 vk_find_struct_const(pCreateInfo->pNext,
6908 SAMPLER_REDUCTION_MODE_CREATE_INFO);
6909 if (sampler_reduction)
6910 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
6911
6912 if (pCreateInfo->compareEnable)
6913 depth_compare_func = radv_tex_compare(pCreateInfo->compareOp);
6914
6915 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
6916 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
6917 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
6918 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
6919 S_008F30_DEPTH_COMPARE_FUNC(depth_compare_func) |
6920 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
6921 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
6922 S_008F30_ANISO_BIAS(max_aniso_ratio) |
6923 S_008F30_DISABLE_CUBE_WRAP(0) |
6924 S_008F30_COMPAT_MODE(compat_mode) |
6925 S_008F30_FILTER_MODE(filter_mode));
6926 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
6927 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
6928 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
6929 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
6930 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
6931 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
6932 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
6933 S_008F38_MIP_POINT_PRECLAMP(0));
6934 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
6935 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
6936
6937 if (device->physical_device->rad_info.chip_class >= GFX10) {
6938 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
6939 } else {
6940 sampler->state[2] |=
6941 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
6942 S_008F38_FILTER_PREC_FIX(1) |
6943 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
6944 }
6945 }
6946
6947 VkResult radv_CreateSampler(
6948 VkDevice _device,
6949 const VkSamplerCreateInfo* pCreateInfo,
6950 const VkAllocationCallbacks* pAllocator,
6951 VkSampler* pSampler)
6952 {
6953 RADV_FROM_HANDLE(radv_device, device, _device);
6954 struct radv_sampler *sampler;
6955
6956 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
6957 vk_find_struct_const(pCreateInfo->pNext,
6958 SAMPLER_YCBCR_CONVERSION_INFO);
6959
6960 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
6961
6962 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
6963 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6964 if (!sampler)
6965 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6966
6967 radv_init_sampler(device, sampler, pCreateInfo);
6968
6969 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
6970 *pSampler = radv_sampler_to_handle(sampler);
6971
6972 return VK_SUCCESS;
6973 }
6974
6975 void radv_DestroySampler(
6976 VkDevice _device,
6977 VkSampler _sampler,
6978 const VkAllocationCallbacks* pAllocator)
6979 {
6980 RADV_FROM_HANDLE(radv_device, device, _device);
6981 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
6982
6983 if (!sampler)
6984 return;
6985 vk_free2(&device->alloc, pAllocator, sampler);
6986 }
6987
6988 /* vk_icd.h does not declare this function, so we declare it here to
6989 * suppress Wmissing-prototypes.
6990 */
6991 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
6992 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
6993
6994 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
6995 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
6996 {
6997 /* For the full details on loader interface versioning, see
6998 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
6999 * What follows is a condensed summary, to help you navigate the large and
7000 * confusing official doc.
7001 *
7002 * - Loader interface v0 is incompatible with later versions. We don't
7003 * support it.
7004 *
7005 * - In loader interface v1:
7006 * - The first ICD entrypoint called by the loader is
7007 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
7008 * entrypoint.
7009 * - The ICD must statically expose no other Vulkan symbol unless it is
7010 * linked with -Bsymbolic.
7011 * - Each dispatchable Vulkan handle created by the ICD must be
7012 * a pointer to a struct whose first member is VK_LOADER_DATA. The
7013 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
7014 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
7015 * vkDestroySurfaceKHR(). The ICD must be capable of working with
7016 * such loader-managed surfaces.
7017 *
7018 * - Loader interface v2 differs from v1 in:
7019 * - The first ICD entrypoint called by the loader is
7020 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
7021 * statically expose this entrypoint.
7022 *
7023 * - Loader interface v3 differs from v2 in:
7024 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
7025 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
7026 * because the loader no longer does so.
7027 */
7028 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
7029 return VK_SUCCESS;
7030 }
7031
7032 VkResult radv_GetMemoryFdKHR(VkDevice _device,
7033 const VkMemoryGetFdInfoKHR *pGetFdInfo,
7034 int *pFD)
7035 {
7036 RADV_FROM_HANDLE(radv_device, device, _device);
7037 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
7038
7039 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
7040
7041 /* At the moment, we support only the below handle types. */
7042 assert(pGetFdInfo->handleType ==
7043 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
7044 pGetFdInfo->handleType ==
7045 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
7046
7047 bool ret = radv_get_memory_fd(device, memory, pFD);
7048 if (ret == false)
7049 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
7050 return VK_SUCCESS;
7051 }
7052
7053 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
7054 VkExternalMemoryHandleTypeFlagBits handleType,
7055 int fd,
7056 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
7057 {
7058 RADV_FROM_HANDLE(radv_device, device, _device);
7059
7060 switch (handleType) {
7061 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
7062 pMemoryFdProperties->memoryTypeBits = (1 << RADV_MEM_TYPE_COUNT) - 1;
7063 return VK_SUCCESS;
7064
7065 default:
7066 /* The valid usage section for this function says:
7067 *
7068 * "handleType must not be one of the handle types defined as
7069 * opaque."
7070 *
7071 * So opaque handle types fall into the default "unsupported" case.
7072 */
7073 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7074 }
7075 }
7076
7077 static VkResult radv_import_opaque_fd(struct radv_device *device,
7078 int fd,
7079 uint32_t *syncobj)
7080 {
7081 uint32_t syncobj_handle = 0;
7082 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
7083 if (ret != 0)
7084 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7085
7086 if (*syncobj)
7087 device->ws->destroy_syncobj(device->ws, *syncobj);
7088
7089 *syncobj = syncobj_handle;
7090 close(fd);
7091
7092 return VK_SUCCESS;
7093 }
7094
7095 static VkResult radv_import_sync_fd(struct radv_device *device,
7096 int fd,
7097 uint32_t *syncobj)
7098 {
7099 /* If we create a syncobj we do it locally so that if we have an error, we don't
7100 * leave a syncobj in an undetermined state in the fence. */
7101 uint32_t syncobj_handle = *syncobj;
7102 if (!syncobj_handle) {
7103 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
7104 if (ret) {
7105 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7106 }
7107 }
7108
7109 if (fd == -1) {
7110 device->ws->signal_syncobj(device->ws, syncobj_handle);
7111 } else {
7112 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
7113 if (ret != 0)
7114 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7115 }
7116
7117 *syncobj = syncobj_handle;
7118 if (fd != -1)
7119 close(fd);
7120
7121 return VK_SUCCESS;
7122 }
7123
7124 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
7125 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
7126 {
7127 RADV_FROM_HANDLE(radv_device, device, _device);
7128 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
7129 VkResult result;
7130 struct radv_semaphore_part *dst = NULL;
7131
7132 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
7133 dst = &sem->temporary;
7134 } else {
7135 dst = &sem->permanent;
7136 }
7137
7138 uint32_t syncobj = dst->kind == RADV_SEMAPHORE_SYNCOBJ ? dst->syncobj : 0;
7139
7140 switch(pImportSemaphoreFdInfo->handleType) {
7141 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7142 result = radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7143 break;
7144 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7145 result = radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7146 break;
7147 default:
7148 unreachable("Unhandled semaphore handle type");
7149 }
7150
7151 if (result == VK_SUCCESS) {
7152 dst->syncobj = syncobj;
7153 dst->kind = RADV_SEMAPHORE_SYNCOBJ;
7154 }
7155
7156 return result;
7157 }
7158
7159 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
7160 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
7161 int *pFd)
7162 {
7163 RADV_FROM_HANDLE(radv_device, device, _device);
7164 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
7165 int ret;
7166 uint32_t syncobj_handle;
7167
7168 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7169 assert(sem->temporary.kind == RADV_SEMAPHORE_SYNCOBJ);
7170 syncobj_handle = sem->temporary.syncobj;
7171 } else {
7172 assert(sem->permanent.kind == RADV_SEMAPHORE_SYNCOBJ);
7173 syncobj_handle = sem->permanent.syncobj;
7174 }
7175
7176 switch(pGetFdInfo->handleType) {
7177 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7178 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7179 break;
7180 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7181 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7182 if (!ret) {
7183 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7184 radv_destroy_semaphore_part(device, &sem->temporary);
7185 } else {
7186 device->ws->reset_syncobj(device->ws, syncobj_handle);
7187 }
7188 }
7189 break;
7190 default:
7191 unreachable("Unhandled semaphore handle type");
7192 }
7193
7194 if (ret)
7195 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7196 return VK_SUCCESS;
7197 }
7198
7199 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
7200 VkPhysicalDevice physicalDevice,
7201 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
7202 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
7203 {
7204 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7205 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pExternalSemaphoreInfo->pNext, NULL);
7206
7207 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
7208 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7209 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7210 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7211
7212 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
7213 } else if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7214 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7215 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
7216 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7217 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7218 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7219 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7220 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
7221 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7222 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7223 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7224 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7225 } else {
7226 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7227 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7228 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7229 }
7230 }
7231
7232 VkResult radv_ImportFenceFdKHR(VkDevice _device,
7233 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
7234 {
7235 RADV_FROM_HANDLE(radv_device, device, _device);
7236 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
7237 uint32_t *syncobj_dst = NULL;
7238
7239
7240 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
7241 syncobj_dst = &fence->temp_syncobj;
7242 } else {
7243 syncobj_dst = &fence->syncobj;
7244 }
7245
7246 switch(pImportFenceFdInfo->handleType) {
7247 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7248 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7249 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7250 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7251 default:
7252 unreachable("Unhandled fence handle type");
7253 }
7254 }
7255
7256 VkResult radv_GetFenceFdKHR(VkDevice _device,
7257 const VkFenceGetFdInfoKHR *pGetFdInfo,
7258 int *pFd)
7259 {
7260 RADV_FROM_HANDLE(radv_device, device, _device);
7261 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
7262 int ret;
7263 uint32_t syncobj_handle;
7264
7265 if (fence->temp_syncobj)
7266 syncobj_handle = fence->temp_syncobj;
7267 else
7268 syncobj_handle = fence->syncobj;
7269
7270 switch(pGetFdInfo->handleType) {
7271 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7272 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7273 break;
7274 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7275 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7276 if (!ret) {
7277 if (fence->temp_syncobj) {
7278 close (fence->temp_syncobj);
7279 fence->temp_syncobj = 0;
7280 } else {
7281 device->ws->reset_syncobj(device->ws, syncobj_handle);
7282 }
7283 }
7284 break;
7285 default:
7286 unreachable("Unhandled fence handle type");
7287 }
7288
7289 if (ret)
7290 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7291 return VK_SUCCESS;
7292 }
7293
7294 void radv_GetPhysicalDeviceExternalFenceProperties(
7295 VkPhysicalDevice physicalDevice,
7296 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
7297 VkExternalFenceProperties *pExternalFenceProperties)
7298 {
7299 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7300
7301 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7302 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7303 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
7304 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7305 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7306 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
7307 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7308 } else {
7309 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
7310 pExternalFenceProperties->compatibleHandleTypes = 0;
7311 pExternalFenceProperties->externalFenceFeatures = 0;
7312 }
7313 }
7314
7315 VkResult
7316 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
7317 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
7318 const VkAllocationCallbacks* pAllocator,
7319 VkDebugReportCallbackEXT* pCallback)
7320 {
7321 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7322 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
7323 pCreateInfo, pAllocator, &instance->alloc,
7324 pCallback);
7325 }
7326
7327 void
7328 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
7329 VkDebugReportCallbackEXT _callback,
7330 const VkAllocationCallbacks* pAllocator)
7331 {
7332 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7333 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
7334 _callback, pAllocator, &instance->alloc);
7335 }
7336
7337 void
7338 radv_DebugReportMessageEXT(VkInstance _instance,
7339 VkDebugReportFlagsEXT flags,
7340 VkDebugReportObjectTypeEXT objectType,
7341 uint64_t object,
7342 size_t location,
7343 int32_t messageCode,
7344 const char* pLayerPrefix,
7345 const char* pMessage)
7346 {
7347 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7348 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
7349 object, location, messageCode, pLayerPrefix, pMessage);
7350 }
7351
7352 void
7353 radv_GetDeviceGroupPeerMemoryFeatures(
7354 VkDevice device,
7355 uint32_t heapIndex,
7356 uint32_t localDeviceIndex,
7357 uint32_t remoteDeviceIndex,
7358 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
7359 {
7360 assert(localDeviceIndex == remoteDeviceIndex);
7361
7362 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
7363 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
7364 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
7365 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
7366 }
7367
7368 static const VkTimeDomainEXT radv_time_domains[] = {
7369 VK_TIME_DOMAIN_DEVICE_EXT,
7370 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
7371 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
7372 };
7373
7374 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
7375 VkPhysicalDevice physicalDevice,
7376 uint32_t *pTimeDomainCount,
7377 VkTimeDomainEXT *pTimeDomains)
7378 {
7379 int d;
7380 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
7381
7382 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
7383 vk_outarray_append(&out, i) {
7384 *i = radv_time_domains[d];
7385 }
7386 }
7387
7388 return vk_outarray_status(&out);
7389 }
7390
7391 static uint64_t
7392 radv_clock_gettime(clockid_t clock_id)
7393 {
7394 struct timespec current;
7395 int ret;
7396
7397 ret = clock_gettime(clock_id, &current);
7398 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
7399 ret = clock_gettime(CLOCK_MONOTONIC, &current);
7400 if (ret < 0)
7401 return 0;
7402
7403 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
7404 }
7405
7406 VkResult radv_GetCalibratedTimestampsEXT(
7407 VkDevice _device,
7408 uint32_t timestampCount,
7409 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
7410 uint64_t *pTimestamps,
7411 uint64_t *pMaxDeviation)
7412 {
7413 RADV_FROM_HANDLE(radv_device, device, _device);
7414 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
7415 int d;
7416 uint64_t begin, end;
7417 uint64_t max_clock_period = 0;
7418
7419 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7420
7421 for (d = 0; d < timestampCount; d++) {
7422 switch (pTimestampInfos[d].timeDomain) {
7423 case VK_TIME_DOMAIN_DEVICE_EXT:
7424 pTimestamps[d] = device->ws->query_value(device->ws,
7425 RADEON_TIMESTAMP);
7426 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
7427 max_clock_period = MAX2(max_clock_period, device_period);
7428 break;
7429 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
7430 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
7431 max_clock_period = MAX2(max_clock_period, 1);
7432 break;
7433
7434 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
7435 pTimestamps[d] = begin;
7436 break;
7437 default:
7438 pTimestamps[d] = 0;
7439 break;
7440 }
7441 }
7442
7443 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7444
7445 /*
7446 * The maximum deviation is the sum of the interval over which we
7447 * perform the sampling and the maximum period of any sampled
7448 * clock. That's because the maximum skew between any two sampled
7449 * clock edges is when the sampled clock with the largest period is
7450 * sampled at the end of that period but right at the beginning of the
7451 * sampling interval and some other clock is sampled right at the
7452 * begining of its sampling period and right at the end of the
7453 * sampling interval. Let's assume the GPU has the longest clock
7454 * period and that the application is sampling GPU and monotonic:
7455 *
7456 * s e
7457 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
7458 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7459 *
7460 * g
7461 * 0 1 2 3
7462 * GPU -----_____-----_____-----_____-----_____
7463 *
7464 * m
7465 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
7466 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7467 *
7468 * Interval <----------------->
7469 * Deviation <-------------------------->
7470 *
7471 * s = read(raw) 2
7472 * g = read(GPU) 1
7473 * m = read(monotonic) 2
7474 * e = read(raw) b
7475 *
7476 * We round the sample interval up by one tick to cover sampling error
7477 * in the interval clock
7478 */
7479
7480 uint64_t sample_interval = end - begin + 1;
7481
7482 *pMaxDeviation = sample_interval + max_clock_period;
7483
7484 return VK_SUCCESS;
7485 }
7486
7487 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
7488 VkPhysicalDevice physicalDevice,
7489 VkSampleCountFlagBits samples,
7490 VkMultisamplePropertiesEXT* pMultisampleProperties)
7491 {
7492 if (samples & (VK_SAMPLE_COUNT_2_BIT |
7493 VK_SAMPLE_COUNT_4_BIT |
7494 VK_SAMPLE_COUNT_8_BIT)) {
7495 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
7496 } else {
7497 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
7498 }
7499 }