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