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