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