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