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