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