b57fbcf8ae94d7228044c1b36713166bf462aaa4
[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 && (LLVM_VERSION_MAJOR >= 9 || pdevice->use_aco);
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 && (LLVM_VERSION_MAJOR >= 9 || pdevice->use_aco);
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
2672 /* Not fully to spec but if we're doing sandboxed compilations already this doesn't matter. */
2673 flags &= ~VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT;
2674
2675 radv_create_shaders(pipeline, device, NULL, &key, pStages, flags, NULL, stage_feedbacks);
2676
2677 /* free memory allocated above */
2678 for (uint32_t set = 0; set < layout.num_sets; set++)
2679 free(layout.set[set].layout);
2680
2681 for (uint32_t i = 0; i < MESA_SHADER_STAGES; i++) {
2682 if (!pStages[i])
2683 continue;
2684
2685 free((void *) pStages[i]->pName);
2686 free(radv_shader_module_from_handle(pStages[i]->module));
2687 if (pStages[i]->pSpecializationInfo) {
2688 free((void *) pStages[i]->pSpecializationInfo->pData);
2689 free((void *) pStages[i]->pSpecializationInfo->pMapEntries);
2690 free((void *) pStages[i]->pSpecializationInfo);
2691 }
2692 free((void *) pStages[i]);
2693 }
2694
2695 vk_free(&device->vk.alloc, pipeline);
2696
2697 sc_type = RADV_SC_TYPE_COMPILE_PIPELINE_FINISHED;
2698 write(fd_secure_output, &sc_type, sizeof(sc_type));
2699
2700 } else if (sc_type == RADV_SC_TYPE_DESTROY_DEVICE) {
2701 goto secure_compile_exit;
2702 }
2703 }
2704
2705 secure_compile_exit:
2706 close(fd_secure_input);
2707 close(fd_secure_output);
2708 close(fd_idle_device_output);
2709 _exit(0);
2710 }
2711
2712 static enum radv_secure_compile_type fork_secure_compile_device(struct radv_device *device, unsigned process)
2713 {
2714 int fd_secure_input[2];
2715 int fd_secure_output[2];
2716
2717 /* create pipe descriptors (used to communicate between processes) */
2718 if (pipe(fd_secure_input) == -1 || pipe(fd_secure_output) == -1)
2719 return RADV_SC_TYPE_INIT_FAILURE;
2720
2721
2722 int sc_pid;
2723 if ((sc_pid = fork()) == 0) {
2724 device->sc_state->secure_compile_thread_counter = process;
2725 run_secure_compile_device(device, process, fd_secure_output[1]);
2726 } else {
2727 if (sc_pid == -1)
2728 return RADV_SC_TYPE_INIT_FAILURE;
2729
2730 /* Read the init result returned from the secure process */
2731 enum radv_secure_compile_type sc_type;
2732 bool sc_read = radv_sc_read(fd_secure_output[0], &sc_type, sizeof(sc_type), true);
2733
2734 if (sc_type == RADV_SC_TYPE_INIT_FAILURE || !sc_read) {
2735 close(fd_secure_input[0]);
2736 close(fd_secure_input[1]);
2737 close(fd_secure_output[1]);
2738 close(fd_secure_output[0]);
2739 int status;
2740 waitpid(sc_pid, &status, 0);
2741
2742 return RADV_SC_TYPE_INIT_FAILURE;
2743 } else {
2744 assert(sc_type == RADV_SC_TYPE_INIT_SUCCESS);
2745 write(device->sc_state->secure_compile_processes[process].fd_secure_output, &sc_type, sizeof(sc_type));
2746
2747 close(fd_secure_input[0]);
2748 close(fd_secure_input[1]);
2749 close(fd_secure_output[1]);
2750 close(fd_secure_output[0]);
2751
2752 int status;
2753 waitpid(sc_pid, &status, 0);
2754 }
2755 }
2756
2757 return RADV_SC_TYPE_INIT_SUCCESS;
2758 }
2759
2760 /* Run a bare bones fork of a device that was forked right after its creation.
2761 * This device will have low overhead when it is forked again before each
2762 * pipeline compilation. This device sits idle and its only job is to fork
2763 * itself.
2764 */
2765 static void run_secure_compile_idle_device(struct radv_device *device, unsigned process,
2766 int fd_secure_input, int fd_secure_output)
2767 {
2768 enum radv_secure_compile_type sc_type = RADV_SC_TYPE_INIT_SUCCESS;
2769 device->sc_state->secure_compile_processes[process].fd_secure_input = fd_secure_input;
2770 device->sc_state->secure_compile_processes[process].fd_secure_output = fd_secure_output;
2771
2772 write(fd_secure_output, &sc_type, sizeof(sc_type));
2773
2774 while (true) {
2775 radv_sc_read(fd_secure_input, &sc_type, sizeof(sc_type), false);
2776
2777 if (sc_type == RADV_SC_TYPE_FORK_DEVICE) {
2778 sc_type = fork_secure_compile_device(device, process);
2779
2780 if (sc_type == RADV_SC_TYPE_INIT_FAILURE)
2781 goto secure_compile_exit;
2782
2783 } else if (sc_type == RADV_SC_TYPE_DESTROY_DEVICE) {
2784 goto secure_compile_exit;
2785 }
2786 }
2787
2788 secure_compile_exit:
2789 close(fd_secure_input);
2790 close(fd_secure_output);
2791 _exit(0);
2792 }
2793
2794 static void destroy_secure_compile_device(struct radv_device *device, unsigned process)
2795 {
2796 int fd_secure_input = device->sc_state->secure_compile_processes[process].fd_secure_input;
2797
2798 enum radv_secure_compile_type sc_type = RADV_SC_TYPE_DESTROY_DEVICE;
2799 write(fd_secure_input, &sc_type, sizeof(sc_type));
2800
2801 close(device->sc_state->secure_compile_processes[process].fd_secure_input);
2802 close(device->sc_state->secure_compile_processes[process].fd_secure_output);
2803
2804 int status;
2805 waitpid(device->sc_state->secure_compile_processes[process].sc_pid, &status, 0);
2806 }
2807
2808 static VkResult fork_secure_compile_idle_device(struct radv_device *device)
2809 {
2810 device->sc_state = vk_zalloc(&device->vk.alloc,
2811 sizeof(struct radv_secure_compile_state),
2812 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2813
2814 mtx_init(&device->sc_state->secure_compile_mutex, mtx_plain);
2815
2816 pid_t upid = getpid();
2817 time_t seconds = time(NULL);
2818
2819 char *uid;
2820 if (asprintf(&uid, "%ld_%ld", (long) upid, (long) seconds) == -1)
2821 return VK_ERROR_INITIALIZATION_FAILED;
2822
2823 device->sc_state->uid = uid;
2824
2825 uint8_t sc_threads = device->instance->num_sc_threads;
2826 int fd_secure_input[MAX_SC_PROCS][2];
2827 int fd_secure_output[MAX_SC_PROCS][2];
2828
2829 /* create pipe descriptors (used to communicate between processes) */
2830 for (unsigned i = 0; i < sc_threads; i++) {
2831 if (pipe(fd_secure_input[i]) == -1 ||
2832 pipe(fd_secure_output[i]) == -1) {
2833 return VK_ERROR_INITIALIZATION_FAILED;
2834 }
2835 }
2836
2837 device->sc_state->secure_compile_processes = vk_zalloc(&device->vk.alloc,
2838 sizeof(struct radv_secure_compile_process) * sc_threads, 8,
2839 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2840
2841 for (unsigned process = 0; process < sc_threads; process++) {
2842 if ((device->sc_state->secure_compile_processes[process].sc_pid = fork()) == 0) {
2843 device->sc_state->secure_compile_thread_counter = process;
2844 run_secure_compile_idle_device(device, process, fd_secure_input[process][0], fd_secure_output[process][1]);
2845 } else {
2846 if (device->sc_state->secure_compile_processes[process].sc_pid == -1)
2847 return VK_ERROR_INITIALIZATION_FAILED;
2848
2849 /* Read the init result returned from the secure process */
2850 enum radv_secure_compile_type sc_type;
2851 bool sc_read = radv_sc_read(fd_secure_output[process][0], &sc_type, sizeof(sc_type), true);
2852
2853 bool fifo_result;
2854 if (sc_read && sc_type == RADV_SC_TYPE_INIT_SUCCESS) {
2855 fifo_result = secure_compile_open_fifo_fds(device->sc_state,
2856 &device->sc_state->secure_compile_processes[process].fd_server,
2857 &device->sc_state->secure_compile_processes[process].fd_client,
2858 process, true);
2859
2860 device->sc_state->secure_compile_processes[process].fd_secure_input = fd_secure_input[process][1];
2861 device->sc_state->secure_compile_processes[process].fd_secure_output = fd_secure_output[process][0];
2862 }
2863
2864 if (sc_type == RADV_SC_TYPE_INIT_FAILURE || !sc_read || !fifo_result) {
2865 close(fd_secure_input[process][0]);
2866 close(fd_secure_input[process][1]);
2867 close(fd_secure_output[process][1]);
2868 close(fd_secure_output[process][0]);
2869 int status;
2870 waitpid(device->sc_state->secure_compile_processes[process].sc_pid, &status, 0);
2871
2872 /* Destroy any forks that were created sucessfully */
2873 for (unsigned i = 0; i < process; i++) {
2874 destroy_secure_compile_device(device, i);
2875 }
2876
2877 return VK_ERROR_INITIALIZATION_FAILED;
2878 }
2879 }
2880 }
2881 return VK_SUCCESS;
2882 }
2883
2884 static void
2885 radv_device_init_dispatch(struct radv_device *device)
2886 {
2887 const struct radv_instance *instance = device->physical_device->instance;
2888 const struct radv_device_dispatch_table *dispatch_table_layer = NULL;
2889 bool unchecked = instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS;
2890 int radv_thread_trace = radv_get_int_debug_option("RADV_THREAD_TRACE", -1);
2891
2892 if (radv_thread_trace >= 0) {
2893 /* Use device entrypoints from the SQTT layer if enabled. */
2894 dispatch_table_layer = &sqtt_device_dispatch_table;
2895 }
2896
2897 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
2898 /* Vulkan requires that entrypoints for extensions which have not been
2899 * enabled must not be advertised.
2900 */
2901 if (!unchecked &&
2902 !radv_device_entrypoint_is_enabled(i, instance->apiVersion,
2903 &instance->enabled_extensions,
2904 &device->enabled_extensions)) {
2905 device->dispatch.entrypoints[i] = NULL;
2906 } else if (dispatch_table_layer &&
2907 dispatch_table_layer->entrypoints[i]) {
2908 device->dispatch.entrypoints[i] =
2909 dispatch_table_layer->entrypoints[i];
2910 } else {
2911 device->dispatch.entrypoints[i] =
2912 radv_device_dispatch_table.entrypoints[i];
2913 }
2914 }
2915 }
2916
2917 static VkResult
2918 radv_create_pthread_cond(pthread_cond_t *cond)
2919 {
2920 pthread_condattr_t condattr;
2921 if (pthread_condattr_init(&condattr)) {
2922 return VK_ERROR_INITIALIZATION_FAILED;
2923 }
2924
2925 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
2926 pthread_condattr_destroy(&condattr);
2927 return VK_ERROR_INITIALIZATION_FAILED;
2928 }
2929 if (pthread_cond_init(cond, &condattr)) {
2930 pthread_condattr_destroy(&condattr);
2931 return VK_ERROR_INITIALIZATION_FAILED;
2932 }
2933 pthread_condattr_destroy(&condattr);
2934 return VK_SUCCESS;
2935 }
2936
2937 static VkResult
2938 check_physical_device_features(VkPhysicalDevice physicalDevice,
2939 const VkPhysicalDeviceFeatures *features)
2940 {
2941 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2942 VkPhysicalDeviceFeatures supported_features;
2943 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2944 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2945 VkBool32 *enabled_feature = (VkBool32 *)features;
2946 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2947 for (uint32_t i = 0; i < num_features; i++) {
2948 if (enabled_feature[i] && !supported_feature[i])
2949 return vk_error(physical_device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
2950 }
2951
2952 return VK_SUCCESS;
2953 }
2954
2955 static VkResult radv_device_init_border_color(struct radv_device *device)
2956 {
2957 device->border_color_data.bo =
2958 device->ws->buffer_create(device->ws,
2959 RADV_BORDER_COLOR_BUFFER_SIZE,
2960 4096,
2961 RADEON_DOMAIN_VRAM,
2962 RADEON_FLAG_CPU_ACCESS |
2963 RADEON_FLAG_READ_ONLY |
2964 RADEON_FLAG_NO_INTERPROCESS_SHARING,
2965 RADV_BO_PRIORITY_SHADER);
2966
2967 if (device->border_color_data.bo == NULL)
2968 return vk_error(device->physical_device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2969
2970 device->border_color_data.colors_gpu_ptr =
2971 device->ws->buffer_map(device->border_color_data.bo);
2972 pthread_mutex_init(&device->border_color_data.mutex, NULL);
2973
2974 return VK_SUCCESS;
2975 }
2976
2977 static void radv_device_finish_border_color(struct radv_device *device)
2978 {
2979 if (device->border_color_data.bo) {
2980 device->ws->buffer_destroy(device->border_color_data.bo);
2981
2982 pthread_mutex_destroy(&device->border_color_data.mutex);
2983 }
2984 }
2985
2986 VkResult radv_CreateDevice(
2987 VkPhysicalDevice physicalDevice,
2988 const VkDeviceCreateInfo* pCreateInfo,
2989 const VkAllocationCallbacks* pAllocator,
2990 VkDevice* pDevice)
2991 {
2992 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2993 VkResult result;
2994 struct radv_device *device;
2995
2996 bool keep_shader_info = false;
2997 bool robust_buffer_access = false;
2998 bool overallocation_disallowed = false;
2999 bool custom_border_colors = false;
3000
3001 /* Check enabled features */
3002 if (pCreateInfo->pEnabledFeatures) {
3003 result = check_physical_device_features(physicalDevice,
3004 pCreateInfo->pEnabledFeatures);
3005 if (result != VK_SUCCESS)
3006 return result;
3007
3008 if (pCreateInfo->pEnabledFeatures->robustBufferAccess)
3009 robust_buffer_access = true;
3010 }
3011
3012 vk_foreach_struct_const(ext, pCreateInfo->pNext) {
3013 switch (ext->sType) {
3014 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
3015 const VkPhysicalDeviceFeatures2 *features = (const void *)ext;
3016 result = check_physical_device_features(physicalDevice,
3017 &features->features);
3018 if (result != VK_SUCCESS)
3019 return result;
3020
3021 if (features->features.robustBufferAccess)
3022 robust_buffer_access = true;
3023 break;
3024 }
3025 case VK_STRUCTURE_TYPE_DEVICE_MEMORY_OVERALLOCATION_CREATE_INFO_AMD: {
3026 const VkDeviceMemoryOverallocationCreateInfoAMD *overallocation = (const void *)ext;
3027 if (overallocation->overallocationBehavior == VK_MEMORY_OVERALLOCATION_BEHAVIOR_DISALLOWED_AMD)
3028 overallocation_disallowed = true;
3029 break;
3030 }
3031 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT: {
3032 const VkPhysicalDeviceCustomBorderColorFeaturesEXT *border_color_features = (const void *)ext;
3033 custom_border_colors = border_color_features->customBorderColors;
3034 break;
3035 }
3036 default:
3037 break;
3038 }
3039 }
3040
3041 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
3042 sizeof(*device), 8,
3043 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
3044 if (!device)
3045 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3046
3047 vk_device_init(&device->vk, pCreateInfo,
3048 &physical_device->instance->alloc, pAllocator);
3049
3050 device->instance = physical_device->instance;
3051 device->physical_device = physical_device;
3052
3053 device->ws = physical_device->ws;
3054
3055 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
3056 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
3057 int index = radv_get_device_extension_index(ext_name);
3058 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
3059 vk_free(&device->vk.alloc, device);
3060 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
3061 }
3062
3063 device->enabled_extensions.extensions[index] = true;
3064 }
3065
3066 radv_device_init_dispatch(device);
3067
3068 keep_shader_info = device->enabled_extensions.AMD_shader_info;
3069
3070 /* With update after bind we can't attach bo's to the command buffer
3071 * from the descriptor set anymore, so we have to use a global BO list.
3072 */
3073 device->use_global_bo_list =
3074 (device->instance->perftest_flags & RADV_PERFTEST_BO_LIST) ||
3075 device->enabled_extensions.EXT_descriptor_indexing ||
3076 device->enabled_extensions.EXT_buffer_device_address ||
3077 device->enabled_extensions.KHR_buffer_device_address;
3078
3079 device->robust_buffer_access = robust_buffer_access;
3080
3081 mtx_init(&device->shader_slab_mutex, mtx_plain);
3082 list_inithead(&device->shader_slabs);
3083
3084 device->overallocation_disallowed = overallocation_disallowed;
3085 mtx_init(&device->overallocation_mutex, mtx_plain);
3086
3087 radv_bo_list_init(&device->bo_list);
3088
3089 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
3090 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
3091 uint32_t qfi = queue_create->queueFamilyIndex;
3092 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
3093 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
3094
3095 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
3096
3097 device->queues[qfi] = vk_alloc(&device->vk.alloc,
3098 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
3099 if (!device->queues[qfi]) {
3100 result = VK_ERROR_OUT_OF_HOST_MEMORY;
3101 goto fail;
3102 }
3103
3104 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
3105
3106 device->queue_count[qfi] = queue_create->queueCount;
3107
3108 for (unsigned q = 0; q < queue_create->queueCount; q++) {
3109 result = radv_queue_init(device, &device->queues[qfi][q],
3110 qfi, q, queue_create->flags,
3111 global_priority);
3112 if (result != VK_SUCCESS)
3113 goto fail;
3114 }
3115 }
3116
3117 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
3118 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
3119
3120 /* Disable DFSM by default. As of 2019-09-15 Talos on Low is still 3% slower on Raven. */
3121 device->dfsm_allowed = device->pbb_allowed &&
3122 (device->instance->perftest_flags & RADV_PERFTEST_DFSM);
3123
3124 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
3125
3126 /* The maximum number of scratch waves. Scratch space isn't divided
3127 * evenly between CUs. The number is only a function of the number of CUs.
3128 * We can decrease the constant to decrease the scratch buffer size.
3129 *
3130 * sctx->scratch_waves must be >= the maximum possible size of
3131 * 1 threadgroup, so that the hw doesn't hang from being unable
3132 * to start any.
3133 *
3134 * The recommended value is 4 per CU at most. Higher numbers don't
3135 * bring much benefit, but they still occupy chip resources (think
3136 * async compute). I've seen ~2% performance difference between 4 and 32.
3137 */
3138 uint32_t max_threads_per_block = 2048;
3139 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
3140 max_threads_per_block / 64);
3141
3142 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1);
3143
3144 if (device->physical_device->rad_info.chip_class >= GFX7) {
3145 /* If the KMD allows it (there is a KMD hw register for it),
3146 * allow launching waves out-of-order.
3147 */
3148 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
3149 }
3150
3151 radv_device_init_gs_info(device);
3152
3153 device->tess_offchip_block_dw_size =
3154 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
3155
3156 if (getenv("RADV_TRACE_FILE")) {
3157 const char *filename = getenv("RADV_TRACE_FILE");
3158
3159 keep_shader_info = true;
3160
3161 if (!radv_init_trace(device))
3162 goto fail;
3163
3164 fprintf(stderr, "*****************************************************************************\n");
3165 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
3166 fprintf(stderr, "*****************************************************************************\n");
3167
3168 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
3169 radv_dump_enabled_options(device, stderr);
3170 }
3171
3172 int radv_thread_trace = radv_get_int_debug_option("RADV_THREAD_TRACE", -1);
3173 if (radv_thread_trace >= 0) {
3174 fprintf(stderr, "*************************************************\n");
3175 fprintf(stderr, "* WARNING: Thread trace support is experimental *\n");
3176 fprintf(stderr, "*************************************************\n");
3177
3178 if (device->physical_device->rad_info.chip_class < GFX8) {
3179 fprintf(stderr, "GPU hardware not supported: refer to "
3180 "the RGP documentation for the list of "
3181 "supported GPUs!\n");
3182 abort();
3183 }
3184
3185 /* Default buffer size set to 1MB per SE. */
3186 device->thread_trace_buffer_size =
3187 radv_get_int_debug_option("RADV_THREAD_TRACE_BUFFER_SIZE", 1024 * 1024);
3188 device->thread_trace_start_frame = radv_thread_trace;
3189
3190 if (!radv_thread_trace_init(device))
3191 goto fail;
3192 }
3193
3194 /* Temporarily disable secure compile while we create meta shaders, etc */
3195 uint8_t sc_threads = device->instance->num_sc_threads;
3196 if (sc_threads)
3197 device->instance->num_sc_threads = 0;
3198
3199 device->keep_shader_info = keep_shader_info;
3200 result = radv_device_init_meta(device);
3201 if (result != VK_SUCCESS)
3202 goto fail;
3203
3204 radv_device_init_msaa(device);
3205
3206 /* If the border color extension is enabled, let's create the buffer we need. */
3207 if (custom_border_colors) {
3208 result = radv_device_init_border_color(device);
3209 if (result != VK_SUCCESS)
3210 goto fail;
3211 }
3212
3213 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
3214 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
3215 switch (family) {
3216 case RADV_QUEUE_GENERAL:
3217 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
3218 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_LOAD_ENABLE(1));
3219 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_SHADOW_ENABLE(1));
3220 break;
3221 case RADV_QUEUE_COMPUTE:
3222 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
3223 radeon_emit(device->empty_cs[family], 0);
3224 break;
3225 }
3226 device->ws->cs_finalize(device->empty_cs[family]);
3227 }
3228
3229 if (device->physical_device->rad_info.chip_class >= GFX7)
3230 cik_create_gfx_config(device);
3231
3232 VkPipelineCacheCreateInfo ci;
3233 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
3234 ci.pNext = NULL;
3235 ci.flags = 0;
3236 ci.pInitialData = NULL;
3237 ci.initialDataSize = 0;
3238 VkPipelineCache pc;
3239 result = radv_CreatePipelineCache(radv_device_to_handle(device),
3240 &ci, NULL, &pc);
3241 if (result != VK_SUCCESS)
3242 goto fail_meta;
3243
3244 device->mem_cache = radv_pipeline_cache_from_handle(pc);
3245
3246 result = radv_create_pthread_cond(&device->timeline_cond);
3247 if (result != VK_SUCCESS)
3248 goto fail_mem_cache;
3249
3250 device->force_aniso =
3251 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
3252 if (device->force_aniso >= 0) {
3253 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
3254 1 << util_logbase2(device->force_aniso));
3255 }
3256
3257 /* Fork device for secure compile as required */
3258 device->instance->num_sc_threads = sc_threads;
3259 if (radv_device_use_secure_compile(device->instance)) {
3260
3261 result = fork_secure_compile_idle_device(device);
3262 if (result != VK_SUCCESS)
3263 goto fail_meta;
3264 }
3265
3266 *pDevice = radv_device_to_handle(device);
3267 return VK_SUCCESS;
3268
3269 fail_mem_cache:
3270 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
3271 fail_meta:
3272 radv_device_finish_meta(device);
3273 fail:
3274 radv_bo_list_finish(&device->bo_list);
3275
3276 radv_thread_trace_finish(device);
3277
3278 if (device->trace_bo)
3279 device->ws->buffer_destroy(device->trace_bo);
3280
3281 if (device->gfx_init)
3282 device->ws->buffer_destroy(device->gfx_init);
3283
3284 radv_device_finish_border_color(device);
3285
3286 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
3287 for (unsigned q = 0; q < device->queue_count[i]; q++)
3288 radv_queue_finish(&device->queues[i][q]);
3289 if (device->queue_count[i])
3290 vk_free(&device->vk.alloc, device->queues[i]);
3291 }
3292
3293 vk_free(&device->vk.alloc, device);
3294 return result;
3295 }
3296
3297 void radv_DestroyDevice(
3298 VkDevice _device,
3299 const VkAllocationCallbacks* pAllocator)
3300 {
3301 RADV_FROM_HANDLE(radv_device, device, _device);
3302
3303 if (!device)
3304 return;
3305
3306 if (device->trace_bo)
3307 device->ws->buffer_destroy(device->trace_bo);
3308
3309 if (device->gfx_init)
3310 device->ws->buffer_destroy(device->gfx_init);
3311
3312 radv_device_finish_border_color(device);
3313
3314 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
3315 for (unsigned q = 0; q < device->queue_count[i]; q++)
3316 radv_queue_finish(&device->queues[i][q]);
3317 if (device->queue_count[i])
3318 vk_free(&device->vk.alloc, device->queues[i]);
3319 if (device->empty_cs[i])
3320 device->ws->cs_destroy(device->empty_cs[i]);
3321 }
3322 radv_device_finish_meta(device);
3323
3324 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
3325 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
3326
3327 radv_destroy_shader_slabs(device);
3328
3329 pthread_cond_destroy(&device->timeline_cond);
3330 radv_bo_list_finish(&device->bo_list);
3331
3332 radv_thread_trace_finish(device);
3333
3334 if (radv_device_use_secure_compile(device->instance)) {
3335 for (unsigned i = 0; i < device->instance->num_sc_threads; i++ ) {
3336 destroy_secure_compile_device(device, i);
3337 }
3338 }
3339
3340 if (device->sc_state) {
3341 free(device->sc_state->uid);
3342 vk_free(&device->vk.alloc, device->sc_state->secure_compile_processes);
3343 }
3344 vk_free(&device->vk.alloc, device->sc_state);
3345 vk_free(&device->vk.alloc, device);
3346 }
3347
3348 VkResult radv_EnumerateInstanceLayerProperties(
3349 uint32_t* pPropertyCount,
3350 VkLayerProperties* pProperties)
3351 {
3352 if (pProperties == NULL) {
3353 *pPropertyCount = 0;
3354 return VK_SUCCESS;
3355 }
3356
3357 /* None supported at this time */
3358 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
3359 }
3360
3361 VkResult radv_EnumerateDeviceLayerProperties(
3362 VkPhysicalDevice physicalDevice,
3363 uint32_t* pPropertyCount,
3364 VkLayerProperties* pProperties)
3365 {
3366 if (pProperties == NULL) {
3367 *pPropertyCount = 0;
3368 return VK_SUCCESS;
3369 }
3370
3371 /* None supported at this time */
3372 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
3373 }
3374
3375 void radv_GetDeviceQueue2(
3376 VkDevice _device,
3377 const VkDeviceQueueInfo2* pQueueInfo,
3378 VkQueue* pQueue)
3379 {
3380 RADV_FROM_HANDLE(radv_device, device, _device);
3381 struct radv_queue *queue;
3382
3383 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
3384 if (pQueueInfo->flags != queue->flags) {
3385 /* From the Vulkan 1.1.70 spec:
3386 *
3387 * "The queue returned by vkGetDeviceQueue2 must have the same
3388 * flags value from this structure as that used at device
3389 * creation time in a VkDeviceQueueCreateInfo instance. If no
3390 * matching flags were specified at device creation time then
3391 * pQueue will return VK_NULL_HANDLE."
3392 */
3393 *pQueue = VK_NULL_HANDLE;
3394 return;
3395 }
3396
3397 *pQueue = radv_queue_to_handle(queue);
3398 }
3399
3400 void radv_GetDeviceQueue(
3401 VkDevice _device,
3402 uint32_t queueFamilyIndex,
3403 uint32_t queueIndex,
3404 VkQueue* pQueue)
3405 {
3406 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
3407 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
3408 .queueFamilyIndex = queueFamilyIndex,
3409 .queueIndex = queueIndex
3410 };
3411
3412 radv_GetDeviceQueue2(_device, &info, pQueue);
3413 }
3414
3415 static void
3416 fill_geom_tess_rings(struct radv_queue *queue,
3417 uint32_t *map,
3418 bool add_sample_positions,
3419 uint32_t esgs_ring_size,
3420 struct radeon_winsys_bo *esgs_ring_bo,
3421 uint32_t gsvs_ring_size,
3422 struct radeon_winsys_bo *gsvs_ring_bo,
3423 uint32_t tess_factor_ring_size,
3424 uint32_t tess_offchip_ring_offset,
3425 uint32_t tess_offchip_ring_size,
3426 struct radeon_winsys_bo *tess_rings_bo)
3427 {
3428 uint32_t *desc = &map[4];
3429
3430 if (esgs_ring_bo) {
3431 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
3432
3433 /* stride 0, num records - size, add tid, swizzle, elsize4,
3434 index stride 64 */
3435 desc[0] = esgs_va;
3436 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
3437 S_008F04_SWIZZLE_ENABLE(true);
3438 desc[2] = esgs_ring_size;
3439 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3440 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3441 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3442 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
3443 S_008F0C_INDEX_STRIDE(3) |
3444 S_008F0C_ADD_TID_ENABLE(1);
3445
3446 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3447 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3448 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3449 S_008F0C_RESOURCE_LEVEL(1);
3450 } else {
3451 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3452 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
3453 S_008F0C_ELEMENT_SIZE(1);
3454 }
3455
3456 /* GS entry for ES->GS ring */
3457 /* stride 0, num records - size, elsize0,
3458 index stride 0 */
3459 desc[4] = esgs_va;
3460 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32);
3461 desc[6] = esgs_ring_size;
3462 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3463 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3464 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3465 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3466
3467 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3468 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3469 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3470 S_008F0C_RESOURCE_LEVEL(1);
3471 } else {
3472 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3473 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3474 }
3475 }
3476
3477 desc += 8;
3478
3479 if (gsvs_ring_bo) {
3480 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
3481
3482 /* VS entry for GS->VS ring */
3483 /* stride 0, num records - size, elsize0,
3484 index stride 0 */
3485 desc[0] = gsvs_va;
3486 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32);
3487 desc[2] = gsvs_ring_size;
3488 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3489 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3490 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3491 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3492
3493 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3494 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3495 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3496 S_008F0C_RESOURCE_LEVEL(1);
3497 } else {
3498 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3499 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3500 }
3501
3502 /* stride gsvs_itemsize, num records 64
3503 elsize 4, index stride 16 */
3504 /* shader will patch stride and desc[2] */
3505 desc[4] = gsvs_va;
3506 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32) |
3507 S_008F04_SWIZZLE_ENABLE(1);
3508 desc[6] = 0;
3509 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3510 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3511 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3512 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
3513 S_008F0C_INDEX_STRIDE(1) |
3514 S_008F0C_ADD_TID_ENABLE(true);
3515
3516 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3517 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3518 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_DISABLED) |
3519 S_008F0C_RESOURCE_LEVEL(1);
3520 } else {
3521 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3522 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
3523 S_008F0C_ELEMENT_SIZE(1);
3524 }
3525
3526 }
3527
3528 desc += 8;
3529
3530 if (tess_rings_bo) {
3531 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
3532 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
3533
3534 desc[0] = tess_va;
3535 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32);
3536 desc[2] = tess_factor_ring_size;
3537 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3538 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3539 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3540 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3541
3542 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3543 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3544 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
3545 S_008F0C_RESOURCE_LEVEL(1);
3546 } else {
3547 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3548 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3549 }
3550
3551 desc[4] = tess_offchip_va;
3552 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32);
3553 desc[6] = tess_offchip_ring_size;
3554 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
3555 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
3556 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
3557 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
3558
3559 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3560 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
3561 S_008F0C_OOB_SELECT(V_008F0C_OOB_SELECT_RAW) |
3562 S_008F0C_RESOURCE_LEVEL(1);
3563 } else {
3564 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
3565 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
3566 }
3567 }
3568
3569 desc += 8;
3570
3571 if (add_sample_positions) {
3572 /* add sample positions after all rings */
3573 memcpy(desc, queue->device->sample_locations_1x, 8);
3574 desc += 2;
3575 memcpy(desc, queue->device->sample_locations_2x, 16);
3576 desc += 4;
3577 memcpy(desc, queue->device->sample_locations_4x, 32);
3578 desc += 8;
3579 memcpy(desc, queue->device->sample_locations_8x, 64);
3580 }
3581 }
3582
3583 static unsigned
3584 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
3585 {
3586 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= GFX7 &&
3587 device->physical_device->rad_info.family != CHIP_CARRIZO &&
3588 device->physical_device->rad_info.family != CHIP_STONEY;
3589 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
3590 unsigned max_offchip_buffers;
3591 unsigned offchip_granularity;
3592 unsigned hs_offchip_param;
3593
3594 /*
3595 * Per RadeonSI:
3596 * This must be one less than the maximum number due to a hw limitation.
3597 * Various hardware bugs need thGFX7
3598 *
3599 * Per AMDVLK:
3600 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
3601 * Gfx7 should limit max_offchip_buffers to 508
3602 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
3603 *
3604 * Follow AMDVLK here.
3605 */
3606 if (device->physical_device->rad_info.chip_class >= GFX10) {
3607 max_offchip_buffers_per_se = 256;
3608 } else if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
3609 device->physical_device->rad_info.chip_class == GFX7 ||
3610 device->physical_device->rad_info.chip_class == GFX6)
3611 --max_offchip_buffers_per_se;
3612
3613 max_offchip_buffers = max_offchip_buffers_per_se *
3614 device->physical_device->rad_info.max_se;
3615
3616 /* Hawaii has a bug with offchip buffers > 256 that can be worked
3617 * around by setting 4K granularity.
3618 */
3619 if (device->tess_offchip_block_dw_size == 4096) {
3620 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
3621 offchip_granularity = V_03093C_X_4K_DWORDS;
3622 } else {
3623 assert(device->tess_offchip_block_dw_size == 8192);
3624 offchip_granularity = V_03093C_X_8K_DWORDS;
3625 }
3626
3627 switch (device->physical_device->rad_info.chip_class) {
3628 case GFX6:
3629 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
3630 break;
3631 case GFX7:
3632 case GFX8:
3633 case GFX9:
3634 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
3635 break;
3636 case GFX10:
3637 break;
3638 default:
3639 break;
3640 }
3641
3642 *max_offchip_buffers_p = max_offchip_buffers;
3643 if (device->physical_device->rad_info.chip_class >= GFX7) {
3644 if (device->physical_device->rad_info.chip_class >= GFX8)
3645 --max_offchip_buffers;
3646 hs_offchip_param =
3647 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
3648 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
3649 } else {
3650 hs_offchip_param =
3651 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
3652 }
3653 return hs_offchip_param;
3654 }
3655
3656 static void
3657 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3658 struct radeon_winsys_bo *esgs_ring_bo,
3659 uint32_t esgs_ring_size,
3660 struct radeon_winsys_bo *gsvs_ring_bo,
3661 uint32_t gsvs_ring_size)
3662 {
3663 if (!esgs_ring_bo && !gsvs_ring_bo)
3664 return;
3665
3666 if (esgs_ring_bo)
3667 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
3668
3669 if (gsvs_ring_bo)
3670 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
3671
3672 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
3673 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
3674 radeon_emit(cs, esgs_ring_size >> 8);
3675 radeon_emit(cs, gsvs_ring_size >> 8);
3676 } else {
3677 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
3678 radeon_emit(cs, esgs_ring_size >> 8);
3679 radeon_emit(cs, gsvs_ring_size >> 8);
3680 }
3681 }
3682
3683 static void
3684 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3685 unsigned hs_offchip_param, unsigned tf_ring_size,
3686 struct radeon_winsys_bo *tess_rings_bo)
3687 {
3688 uint64_t tf_va;
3689
3690 if (!tess_rings_bo)
3691 return;
3692
3693 tf_va = radv_buffer_get_va(tess_rings_bo);
3694
3695 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
3696
3697 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
3698 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
3699 S_030938_SIZE(tf_ring_size / 4));
3700 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
3701 tf_va >> 8);
3702
3703 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3704 radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
3705 S_030984_BASE_HI(tf_va >> 40));
3706 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3707 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
3708 S_030944_BASE_HI(tf_va >> 40));
3709 }
3710 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
3711 hs_offchip_param);
3712 } else {
3713 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
3714 S_008988_SIZE(tf_ring_size / 4));
3715 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
3716 tf_va >> 8);
3717 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
3718 hs_offchip_param);
3719 }
3720 }
3721
3722 static void
3723 radv_emit_graphics_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3724 uint32_t size_per_wave, uint32_t waves,
3725 struct radeon_winsys_bo *scratch_bo)
3726 {
3727 if (queue->queue_family_index != RADV_QUEUE_GENERAL)
3728 return;
3729
3730 if (!scratch_bo)
3731 return;
3732
3733 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
3734
3735 radeon_set_context_reg(cs, R_0286E8_SPI_TMPRING_SIZE,
3736 S_0286E8_WAVES(waves) |
3737 S_0286E8_WAVESIZE(round_up_u32(size_per_wave, 1024)));
3738 }
3739
3740 static void
3741 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3742 uint32_t size_per_wave, uint32_t waves,
3743 struct radeon_winsys_bo *compute_scratch_bo)
3744 {
3745 uint64_t scratch_va;
3746
3747 if (!compute_scratch_bo)
3748 return;
3749
3750 scratch_va = radv_buffer_get_va(compute_scratch_bo);
3751
3752 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
3753
3754 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
3755 radeon_emit(cs, scratch_va);
3756 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3757 S_008F04_SWIZZLE_ENABLE(1));
3758
3759 radeon_set_sh_reg(cs, R_00B860_COMPUTE_TMPRING_SIZE,
3760 S_00B860_WAVES(waves) |
3761 S_00B860_WAVESIZE(round_up_u32(size_per_wave, 1024)));
3762 }
3763
3764 static void
3765 radv_emit_global_shader_pointers(struct radv_queue *queue,
3766 struct radeon_cmdbuf *cs,
3767 struct radeon_winsys_bo *descriptor_bo)
3768 {
3769 uint64_t va;
3770
3771 if (!descriptor_bo)
3772 return;
3773
3774 va = radv_buffer_get_va(descriptor_bo);
3775
3776 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
3777
3778 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3779 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3780 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3781 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3782 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3783
3784 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3785 radv_emit_shader_pointer(queue->device, cs, regs[i],
3786 va, true);
3787 }
3788 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3789 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3790 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3791 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3792 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3793
3794 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3795 radv_emit_shader_pointer(queue->device, cs, regs[i],
3796 va, true);
3797 }
3798 } else {
3799 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3800 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3801 R_00B230_SPI_SHADER_USER_DATA_GS_0,
3802 R_00B330_SPI_SHADER_USER_DATA_ES_0,
3803 R_00B430_SPI_SHADER_USER_DATA_HS_0,
3804 R_00B530_SPI_SHADER_USER_DATA_LS_0};
3805
3806 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3807 radv_emit_shader_pointer(queue->device, cs, regs[i],
3808 va, true);
3809 }
3810 }
3811 }
3812
3813 static void
3814 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3815 {
3816 struct radv_device *device = queue->device;
3817
3818 if (device->gfx_init) {
3819 uint64_t va = radv_buffer_get_va(device->gfx_init);
3820
3821 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
3822 radeon_emit(cs, va);
3823 radeon_emit(cs, va >> 32);
3824 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
3825
3826 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
3827 } else {
3828 si_emit_graphics(device, cs);
3829 }
3830 }
3831
3832 static void
3833 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3834 {
3835 struct radv_physical_device *physical_device = queue->device->physical_device;
3836 si_emit_compute(physical_device, cs);
3837 }
3838
3839 static VkResult
3840 radv_get_preamble_cs(struct radv_queue *queue,
3841 uint32_t scratch_size_per_wave,
3842 uint32_t scratch_waves,
3843 uint32_t compute_scratch_size_per_wave,
3844 uint32_t compute_scratch_waves,
3845 uint32_t esgs_ring_size,
3846 uint32_t gsvs_ring_size,
3847 bool needs_tess_rings,
3848 bool needs_gds,
3849 bool needs_gds_oa,
3850 bool needs_sample_positions,
3851 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
3852 struct radeon_cmdbuf **initial_preamble_cs,
3853 struct radeon_cmdbuf **continue_preamble_cs)
3854 {
3855 struct radeon_winsys_bo *scratch_bo = NULL;
3856 struct radeon_winsys_bo *descriptor_bo = NULL;
3857 struct radeon_winsys_bo *compute_scratch_bo = NULL;
3858 struct radeon_winsys_bo *esgs_ring_bo = NULL;
3859 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
3860 struct radeon_winsys_bo *tess_rings_bo = NULL;
3861 struct radeon_winsys_bo *gds_bo = NULL;
3862 struct radeon_winsys_bo *gds_oa_bo = NULL;
3863 struct radeon_cmdbuf *dest_cs[3] = {0};
3864 bool add_tess_rings = false, add_gds = false, add_gds_oa = false, add_sample_positions = false;
3865 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
3866 unsigned max_offchip_buffers;
3867 unsigned hs_offchip_param = 0;
3868 unsigned tess_offchip_ring_offset;
3869 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
3870 if (!queue->has_tess_rings) {
3871 if (needs_tess_rings)
3872 add_tess_rings = true;
3873 }
3874 if (!queue->has_gds) {
3875 if (needs_gds)
3876 add_gds = true;
3877 }
3878 if (!queue->has_gds_oa) {
3879 if (needs_gds_oa)
3880 add_gds_oa = true;
3881 }
3882 if (!queue->has_sample_positions) {
3883 if (needs_sample_positions)
3884 add_sample_positions = true;
3885 }
3886 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
3887 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
3888 &max_offchip_buffers);
3889 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
3890 tess_offchip_ring_size = max_offchip_buffers *
3891 queue->device->tess_offchip_block_dw_size * 4;
3892
3893 scratch_size_per_wave = MAX2(scratch_size_per_wave, queue->scratch_size_per_wave);
3894 if (scratch_size_per_wave)
3895 scratch_waves = MIN2(scratch_waves, UINT32_MAX / scratch_size_per_wave);
3896 else
3897 scratch_waves = 0;
3898
3899 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave, queue->compute_scratch_size_per_wave);
3900 if (compute_scratch_size_per_wave)
3901 compute_scratch_waves = MIN2(compute_scratch_waves, UINT32_MAX / compute_scratch_size_per_wave);
3902 else
3903 compute_scratch_waves = 0;
3904
3905 if (scratch_size_per_wave <= queue->scratch_size_per_wave &&
3906 scratch_waves <= queue->scratch_waves &&
3907 compute_scratch_size_per_wave <= queue->compute_scratch_size_per_wave &&
3908 compute_scratch_waves <= queue->compute_scratch_waves &&
3909 esgs_ring_size <= queue->esgs_ring_size &&
3910 gsvs_ring_size <= queue->gsvs_ring_size &&
3911 !add_tess_rings && !add_gds && !add_gds_oa && !add_sample_positions &&
3912 queue->initial_preamble_cs) {
3913 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3914 *initial_preamble_cs = queue->initial_preamble_cs;
3915 *continue_preamble_cs = queue->continue_preamble_cs;
3916 if (!scratch_size_per_wave && !compute_scratch_size_per_wave &&
3917 !esgs_ring_size && !gsvs_ring_size && !needs_tess_rings &&
3918 !needs_gds && !needs_gds_oa && !needs_sample_positions)
3919 *continue_preamble_cs = NULL;
3920 return VK_SUCCESS;
3921 }
3922
3923 uint32_t scratch_size = scratch_size_per_wave * scratch_waves;
3924 uint32_t queue_scratch_size = queue->scratch_size_per_wave * queue->scratch_waves;
3925 if (scratch_size > queue_scratch_size) {
3926 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3927 scratch_size,
3928 4096,
3929 RADEON_DOMAIN_VRAM,
3930 ring_bo_flags,
3931 RADV_BO_PRIORITY_SCRATCH);
3932 if (!scratch_bo)
3933 goto fail;
3934 } else
3935 scratch_bo = queue->scratch_bo;
3936
3937 uint32_t compute_scratch_size = compute_scratch_size_per_wave * compute_scratch_waves;
3938 uint32_t compute_queue_scratch_size = queue->compute_scratch_size_per_wave * queue->compute_scratch_waves;
3939 if (compute_scratch_size > compute_queue_scratch_size) {
3940 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3941 compute_scratch_size,
3942 4096,
3943 RADEON_DOMAIN_VRAM,
3944 ring_bo_flags,
3945 RADV_BO_PRIORITY_SCRATCH);
3946 if (!compute_scratch_bo)
3947 goto fail;
3948
3949 } else
3950 compute_scratch_bo = queue->compute_scratch_bo;
3951
3952 if (esgs_ring_size > queue->esgs_ring_size) {
3953 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3954 esgs_ring_size,
3955 4096,
3956 RADEON_DOMAIN_VRAM,
3957 ring_bo_flags,
3958 RADV_BO_PRIORITY_SCRATCH);
3959 if (!esgs_ring_bo)
3960 goto fail;
3961 } else {
3962 esgs_ring_bo = queue->esgs_ring_bo;
3963 esgs_ring_size = queue->esgs_ring_size;
3964 }
3965
3966 if (gsvs_ring_size > queue->gsvs_ring_size) {
3967 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3968 gsvs_ring_size,
3969 4096,
3970 RADEON_DOMAIN_VRAM,
3971 ring_bo_flags,
3972 RADV_BO_PRIORITY_SCRATCH);
3973 if (!gsvs_ring_bo)
3974 goto fail;
3975 } else {
3976 gsvs_ring_bo = queue->gsvs_ring_bo;
3977 gsvs_ring_size = queue->gsvs_ring_size;
3978 }
3979
3980 if (add_tess_rings) {
3981 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
3982 tess_offchip_ring_offset + tess_offchip_ring_size,
3983 256,
3984 RADEON_DOMAIN_VRAM,
3985 ring_bo_flags,
3986 RADV_BO_PRIORITY_SCRATCH);
3987 if (!tess_rings_bo)
3988 goto fail;
3989 } else {
3990 tess_rings_bo = queue->tess_rings_bo;
3991 }
3992
3993 if (add_gds) {
3994 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
3995
3996 /* 4 streamout GDS counters.
3997 * We need 256B (64 dw) of GDS, otherwise streamout hangs.
3998 */
3999 gds_bo = queue->device->ws->buffer_create(queue->device->ws,
4000 256, 4,
4001 RADEON_DOMAIN_GDS,
4002 ring_bo_flags,
4003 RADV_BO_PRIORITY_SCRATCH);
4004 if (!gds_bo)
4005 goto fail;
4006 } else {
4007 gds_bo = queue->gds_bo;
4008 }
4009
4010 if (add_gds_oa) {
4011 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
4012
4013 gds_oa_bo = queue->device->ws->buffer_create(queue->device->ws,
4014 4, 1,
4015 RADEON_DOMAIN_OA,
4016 ring_bo_flags,
4017 RADV_BO_PRIORITY_SCRATCH);
4018 if (!gds_oa_bo)
4019 goto fail;
4020 } else {
4021 gds_oa_bo = queue->gds_oa_bo;
4022 }
4023
4024 if (scratch_bo != queue->scratch_bo ||
4025 esgs_ring_bo != queue->esgs_ring_bo ||
4026 gsvs_ring_bo != queue->gsvs_ring_bo ||
4027 tess_rings_bo != queue->tess_rings_bo ||
4028 add_sample_positions) {
4029 uint32_t size = 0;
4030 if (gsvs_ring_bo || esgs_ring_bo ||
4031 tess_rings_bo || add_sample_positions) {
4032 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
4033 if (add_sample_positions)
4034 size += 128; /* 64+32+16+8 = 120 bytes */
4035 }
4036 else if (scratch_bo)
4037 size = 8; /* 2 dword */
4038
4039 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
4040 size,
4041 4096,
4042 RADEON_DOMAIN_VRAM,
4043 RADEON_FLAG_CPU_ACCESS |
4044 RADEON_FLAG_NO_INTERPROCESS_SHARING |
4045 RADEON_FLAG_READ_ONLY,
4046 RADV_BO_PRIORITY_DESCRIPTOR);
4047 if (!descriptor_bo)
4048 goto fail;
4049 } else
4050 descriptor_bo = queue->descriptor_bo;
4051
4052 if (descriptor_bo != queue->descriptor_bo) {
4053 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
4054
4055 if (scratch_bo) {
4056 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
4057 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
4058 S_008F04_SWIZZLE_ENABLE(1);
4059 map[0] = scratch_va;
4060 map[1] = rsrc1;
4061 }
4062
4063 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
4064 fill_geom_tess_rings(queue, map, add_sample_positions,
4065 esgs_ring_size, esgs_ring_bo,
4066 gsvs_ring_size, gsvs_ring_bo,
4067 tess_factor_ring_size,
4068 tess_offchip_ring_offset,
4069 tess_offchip_ring_size,
4070 tess_rings_bo);
4071
4072 queue->device->ws->buffer_unmap(descriptor_bo);
4073 }
4074
4075 for(int i = 0; i < 3; ++i) {
4076 struct radeon_cmdbuf *cs = NULL;
4077 cs = queue->device->ws->cs_create(queue->device->ws,
4078 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
4079 if (!cs)
4080 goto fail;
4081
4082 dest_cs[i] = cs;
4083
4084 if (scratch_bo)
4085 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
4086
4087 /* Emit initial configuration. */
4088 switch (queue->queue_family_index) {
4089 case RADV_QUEUE_GENERAL:
4090 radv_init_graphics_state(cs, queue);
4091 break;
4092 case RADV_QUEUE_COMPUTE:
4093 radv_init_compute_state(cs, queue);
4094 break;
4095 case RADV_QUEUE_TRANSFER:
4096 break;
4097 }
4098
4099 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
4100 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
4101 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
4102
4103 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
4104 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
4105 }
4106
4107 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
4108 gsvs_ring_bo, gsvs_ring_size);
4109 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
4110 tess_factor_ring_size, tess_rings_bo);
4111 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
4112 radv_emit_compute_scratch(queue, cs, compute_scratch_size_per_wave,
4113 compute_scratch_waves, compute_scratch_bo);
4114 radv_emit_graphics_scratch(queue, cs, scratch_size_per_wave,
4115 scratch_waves, scratch_bo);
4116
4117 if (gds_bo)
4118 radv_cs_add_buffer(queue->device->ws, cs, gds_bo);
4119 if (gds_oa_bo)
4120 radv_cs_add_buffer(queue->device->ws, cs, gds_oa_bo);
4121
4122 if (queue->device->trace_bo)
4123 radv_cs_add_buffer(queue->device->ws, cs, queue->device->trace_bo);
4124
4125 if (i == 0) {
4126 si_cs_emit_cache_flush(cs,
4127 queue->device->physical_device->rad_info.chip_class,
4128 NULL, 0,
4129 queue->queue_family_index == RING_COMPUTE &&
4130 queue->device->physical_device->rad_info.chip_class >= GFX7,
4131 (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)) |
4132 RADV_CMD_FLAG_INV_ICACHE |
4133 RADV_CMD_FLAG_INV_SCACHE |
4134 RADV_CMD_FLAG_INV_VCACHE |
4135 RADV_CMD_FLAG_INV_L2 |
4136 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
4137 } else if (i == 1) {
4138 si_cs_emit_cache_flush(cs,
4139 queue->device->physical_device->rad_info.chip_class,
4140 NULL, 0,
4141 queue->queue_family_index == RING_COMPUTE &&
4142 queue->device->physical_device->rad_info.chip_class >= GFX7,
4143 RADV_CMD_FLAG_INV_ICACHE |
4144 RADV_CMD_FLAG_INV_SCACHE |
4145 RADV_CMD_FLAG_INV_VCACHE |
4146 RADV_CMD_FLAG_INV_L2 |
4147 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
4148 }
4149
4150 if (!queue->device->ws->cs_finalize(cs))
4151 goto fail;
4152 }
4153
4154 if (queue->initial_full_flush_preamble_cs)
4155 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
4156
4157 if (queue->initial_preamble_cs)
4158 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
4159
4160 if (queue->continue_preamble_cs)
4161 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
4162
4163 queue->initial_full_flush_preamble_cs = dest_cs[0];
4164 queue->initial_preamble_cs = dest_cs[1];
4165 queue->continue_preamble_cs = dest_cs[2];
4166
4167 if (scratch_bo != queue->scratch_bo) {
4168 if (queue->scratch_bo)
4169 queue->device->ws->buffer_destroy(queue->scratch_bo);
4170 queue->scratch_bo = scratch_bo;
4171 }
4172 queue->scratch_size_per_wave = scratch_size_per_wave;
4173 queue->scratch_waves = scratch_waves;
4174
4175 if (compute_scratch_bo != queue->compute_scratch_bo) {
4176 if (queue->compute_scratch_bo)
4177 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
4178 queue->compute_scratch_bo = compute_scratch_bo;
4179 }
4180 queue->compute_scratch_size_per_wave = compute_scratch_size_per_wave;
4181 queue->compute_scratch_waves = compute_scratch_waves;
4182
4183 if (esgs_ring_bo != queue->esgs_ring_bo) {
4184 if (queue->esgs_ring_bo)
4185 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
4186 queue->esgs_ring_bo = esgs_ring_bo;
4187 queue->esgs_ring_size = esgs_ring_size;
4188 }
4189
4190 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
4191 if (queue->gsvs_ring_bo)
4192 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
4193 queue->gsvs_ring_bo = gsvs_ring_bo;
4194 queue->gsvs_ring_size = gsvs_ring_size;
4195 }
4196
4197 if (tess_rings_bo != queue->tess_rings_bo) {
4198 queue->tess_rings_bo = tess_rings_bo;
4199 queue->has_tess_rings = true;
4200 }
4201
4202 if (gds_bo != queue->gds_bo) {
4203 queue->gds_bo = gds_bo;
4204 queue->has_gds = true;
4205 }
4206
4207 if (gds_oa_bo != queue->gds_oa_bo) {
4208 queue->gds_oa_bo = gds_oa_bo;
4209 queue->has_gds_oa = true;
4210 }
4211
4212 if (descriptor_bo != queue->descriptor_bo) {
4213 if (queue->descriptor_bo)
4214 queue->device->ws->buffer_destroy(queue->descriptor_bo);
4215
4216 queue->descriptor_bo = descriptor_bo;
4217 }
4218
4219 if (add_sample_positions)
4220 queue->has_sample_positions = true;
4221
4222 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
4223 *initial_preamble_cs = queue->initial_preamble_cs;
4224 *continue_preamble_cs = queue->continue_preamble_cs;
4225 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
4226 *continue_preamble_cs = NULL;
4227 return VK_SUCCESS;
4228 fail:
4229 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
4230 if (dest_cs[i])
4231 queue->device->ws->cs_destroy(dest_cs[i]);
4232 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
4233 queue->device->ws->buffer_destroy(descriptor_bo);
4234 if (scratch_bo && scratch_bo != queue->scratch_bo)
4235 queue->device->ws->buffer_destroy(scratch_bo);
4236 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
4237 queue->device->ws->buffer_destroy(compute_scratch_bo);
4238 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
4239 queue->device->ws->buffer_destroy(esgs_ring_bo);
4240 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
4241 queue->device->ws->buffer_destroy(gsvs_ring_bo);
4242 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
4243 queue->device->ws->buffer_destroy(tess_rings_bo);
4244 if (gds_bo && gds_bo != queue->gds_bo)
4245 queue->device->ws->buffer_destroy(gds_bo);
4246 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
4247 queue->device->ws->buffer_destroy(gds_oa_bo);
4248
4249 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4250 }
4251
4252 static VkResult radv_alloc_sem_counts(struct radv_device *device,
4253 struct radv_winsys_sem_counts *counts,
4254 int num_sems,
4255 struct radv_semaphore_part **sems,
4256 const uint64_t *timeline_values,
4257 VkFence _fence,
4258 bool is_signal)
4259 {
4260 int syncobj_idx = 0, sem_idx = 0;
4261
4262 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
4263 return VK_SUCCESS;
4264
4265 for (uint32_t i = 0; i < num_sems; i++) {
4266 switch(sems[i]->kind) {
4267 case RADV_SEMAPHORE_SYNCOBJ:
4268 counts->syncobj_count++;
4269 break;
4270 case RADV_SEMAPHORE_WINSYS:
4271 counts->sem_count++;
4272 break;
4273 case RADV_SEMAPHORE_NONE:
4274 break;
4275 case RADV_SEMAPHORE_TIMELINE:
4276 counts->syncobj_count++;
4277 break;
4278 }
4279 }
4280
4281 if (_fence != VK_NULL_HANDLE) {
4282 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4283 if (fence->temp_syncobj || fence->syncobj)
4284 counts->syncobj_count++;
4285 }
4286
4287 if (counts->syncobj_count) {
4288 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
4289 if (!counts->syncobj)
4290 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4291 }
4292
4293 if (counts->sem_count) {
4294 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
4295 if (!counts->sem) {
4296 free(counts->syncobj);
4297 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4298 }
4299 }
4300
4301 for (uint32_t i = 0; i < num_sems; i++) {
4302 switch(sems[i]->kind) {
4303 case RADV_SEMAPHORE_NONE:
4304 unreachable("Empty semaphore");
4305 break;
4306 case RADV_SEMAPHORE_SYNCOBJ:
4307 counts->syncobj[syncobj_idx++] = sems[i]->syncobj;
4308 break;
4309 case RADV_SEMAPHORE_WINSYS:
4310 counts->sem[sem_idx++] = sems[i]->ws_sem;
4311 break;
4312 case RADV_SEMAPHORE_TIMELINE: {
4313 pthread_mutex_lock(&sems[i]->timeline.mutex);
4314 struct radv_timeline_point *point = NULL;
4315 if (is_signal) {
4316 point = radv_timeline_add_point_locked(device, &sems[i]->timeline, timeline_values[i]);
4317 } else {
4318 point = radv_timeline_find_point_at_least_locked(device, &sems[i]->timeline, timeline_values[i]);
4319 }
4320
4321 pthread_mutex_unlock(&sems[i]->timeline.mutex);
4322
4323 if (point) {
4324 counts->syncobj[syncobj_idx++] = point->syncobj;
4325 } else {
4326 /* Explicitly remove the semaphore so we might not find
4327 * a point later post-submit. */
4328 sems[i] = NULL;
4329 }
4330 break;
4331 }
4332 }
4333 }
4334
4335 if (_fence != VK_NULL_HANDLE) {
4336 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4337 if (fence->temp_syncobj)
4338 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
4339 else if (fence->syncobj)
4340 counts->syncobj[syncobj_idx++] = fence->syncobj;
4341 }
4342
4343 assert(syncobj_idx <= counts->syncobj_count);
4344 counts->syncobj_count = syncobj_idx;
4345
4346 return VK_SUCCESS;
4347 }
4348
4349 static void
4350 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
4351 {
4352 free(sem_info->wait.syncobj);
4353 free(sem_info->wait.sem);
4354 free(sem_info->signal.syncobj);
4355 free(sem_info->signal.sem);
4356 }
4357
4358
4359 static void radv_free_temp_syncobjs(struct radv_device *device,
4360 int num_sems,
4361 struct radv_semaphore_part *sems)
4362 {
4363 for (uint32_t i = 0; i < num_sems; i++) {
4364 radv_destroy_semaphore_part(device, sems + i);
4365 }
4366 }
4367
4368 static VkResult
4369 radv_alloc_sem_info(struct radv_device *device,
4370 struct radv_winsys_sem_info *sem_info,
4371 int num_wait_sems,
4372 struct radv_semaphore_part **wait_sems,
4373 const uint64_t *wait_values,
4374 int num_signal_sems,
4375 struct radv_semaphore_part **signal_sems,
4376 const uint64_t *signal_values,
4377 VkFence fence)
4378 {
4379 VkResult ret;
4380 memset(sem_info, 0, sizeof(*sem_info));
4381
4382 ret = radv_alloc_sem_counts(device, &sem_info->wait, num_wait_sems, wait_sems, wait_values, VK_NULL_HANDLE, false);
4383 if (ret)
4384 return ret;
4385 ret = radv_alloc_sem_counts(device, &sem_info->signal, num_signal_sems, signal_sems, signal_values, fence, true);
4386 if (ret)
4387 radv_free_sem_info(sem_info);
4388
4389 /* caller can override these */
4390 sem_info->cs_emit_wait = true;
4391 sem_info->cs_emit_signal = true;
4392 return ret;
4393 }
4394
4395 static void
4396 radv_finalize_timelines(struct radv_device *device,
4397 uint32_t num_wait_sems,
4398 struct radv_semaphore_part **wait_sems,
4399 const uint64_t *wait_values,
4400 uint32_t num_signal_sems,
4401 struct radv_semaphore_part **signal_sems,
4402 const uint64_t *signal_values,
4403 struct list_head *processing_list)
4404 {
4405 for (uint32_t i = 0; i < num_wait_sems; ++i) {
4406 if (wait_sems[i] && wait_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4407 pthread_mutex_lock(&wait_sems[i]->timeline.mutex);
4408 struct radv_timeline_point *point =
4409 radv_timeline_find_point_at_least_locked(device, &wait_sems[i]->timeline, wait_values[i]);
4410 point->wait_count -= 2;
4411 pthread_mutex_unlock(&wait_sems[i]->timeline.mutex);
4412 }
4413 }
4414 for (uint32_t i = 0; i < num_signal_sems; ++i) {
4415 if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4416 pthread_mutex_lock(&signal_sems[i]->timeline.mutex);
4417 struct radv_timeline_point *point =
4418 radv_timeline_find_point_at_least_locked(device, &signal_sems[i]->timeline, signal_values[i]);
4419 signal_sems[i]->timeline.highest_submitted =
4420 MAX2(signal_sems[i]->timeline.highest_submitted, point->value);
4421 point->wait_count -= 2;
4422 radv_timeline_trigger_waiters_locked(&signal_sems[i]->timeline, processing_list);
4423 pthread_mutex_unlock(&signal_sems[i]->timeline.mutex);
4424 }
4425 }
4426 }
4427
4428 static void
4429 radv_sparse_buffer_bind_memory(struct radv_device *device,
4430 const VkSparseBufferMemoryBindInfo *bind)
4431 {
4432 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
4433
4434 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4435 struct radv_device_memory *mem = NULL;
4436
4437 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4438 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4439
4440 device->ws->buffer_virtual_bind(buffer->bo,
4441 bind->pBinds[i].resourceOffset,
4442 bind->pBinds[i].size,
4443 mem ? mem->bo : NULL,
4444 bind->pBinds[i].memoryOffset);
4445 }
4446 }
4447
4448 static void
4449 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
4450 const VkSparseImageOpaqueMemoryBindInfo *bind)
4451 {
4452 RADV_FROM_HANDLE(radv_image, image, bind->image);
4453
4454 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4455 struct radv_device_memory *mem = NULL;
4456
4457 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4458 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4459
4460 device->ws->buffer_virtual_bind(image->bo,
4461 bind->pBinds[i].resourceOffset,
4462 bind->pBinds[i].size,
4463 mem ? mem->bo : NULL,
4464 bind->pBinds[i].memoryOffset);
4465 }
4466 }
4467
4468 static VkResult
4469 radv_get_preambles(struct radv_queue *queue,
4470 const VkCommandBuffer *cmd_buffers,
4471 uint32_t cmd_buffer_count,
4472 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
4473 struct radeon_cmdbuf **initial_preamble_cs,
4474 struct radeon_cmdbuf **continue_preamble_cs)
4475 {
4476 uint32_t scratch_size_per_wave = 0, waves_wanted = 0;
4477 uint32_t compute_scratch_size_per_wave = 0, compute_waves_wanted = 0;
4478 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
4479 bool tess_rings_needed = false;
4480 bool gds_needed = false;
4481 bool gds_oa_needed = false;
4482 bool sample_positions_needed = false;
4483
4484 for (uint32_t j = 0; j < cmd_buffer_count; j++) {
4485 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
4486 cmd_buffers[j]);
4487
4488 scratch_size_per_wave = MAX2(scratch_size_per_wave, cmd_buffer->scratch_size_per_wave_needed);
4489 waves_wanted = MAX2(waves_wanted, cmd_buffer->scratch_waves_wanted);
4490 compute_scratch_size_per_wave = MAX2(compute_scratch_size_per_wave,
4491 cmd_buffer->compute_scratch_size_per_wave_needed);
4492 compute_waves_wanted = MAX2(compute_waves_wanted,
4493 cmd_buffer->compute_scratch_waves_wanted);
4494 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
4495 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
4496 tess_rings_needed |= cmd_buffer->tess_rings_needed;
4497 gds_needed |= cmd_buffer->gds_needed;
4498 gds_oa_needed |= cmd_buffer->gds_oa_needed;
4499 sample_positions_needed |= cmd_buffer->sample_positions_needed;
4500 }
4501
4502 return radv_get_preamble_cs(queue, scratch_size_per_wave, waves_wanted,
4503 compute_scratch_size_per_wave, compute_waves_wanted,
4504 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
4505 gds_needed, gds_oa_needed, sample_positions_needed,
4506 initial_full_flush_preamble_cs,
4507 initial_preamble_cs, continue_preamble_cs);
4508 }
4509
4510 struct radv_deferred_queue_submission {
4511 struct radv_queue *queue;
4512 VkCommandBuffer *cmd_buffers;
4513 uint32_t cmd_buffer_count;
4514
4515 /* Sparse bindings that happen on a queue. */
4516 VkSparseBufferMemoryBindInfo *buffer_binds;
4517 uint32_t buffer_bind_count;
4518 VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4519 uint32_t image_opaque_bind_count;
4520
4521 bool flush_caches;
4522 VkShaderStageFlags wait_dst_stage_mask;
4523 struct radv_semaphore_part **wait_semaphores;
4524 uint32_t wait_semaphore_count;
4525 struct radv_semaphore_part **signal_semaphores;
4526 uint32_t signal_semaphore_count;
4527 VkFence fence;
4528
4529 uint64_t *wait_values;
4530 uint64_t *signal_values;
4531
4532 struct radv_semaphore_part *temporary_semaphore_parts;
4533 uint32_t temporary_semaphore_part_count;
4534
4535 struct list_head queue_pending_list;
4536 uint32_t submission_wait_count;
4537 struct radv_timeline_waiter *wait_nodes;
4538
4539 struct list_head processing_list;
4540 };
4541
4542 struct radv_queue_submission {
4543 const VkCommandBuffer *cmd_buffers;
4544 uint32_t cmd_buffer_count;
4545
4546 /* Sparse bindings that happen on a queue. */
4547 const VkSparseBufferMemoryBindInfo *buffer_binds;
4548 uint32_t buffer_bind_count;
4549 const VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
4550 uint32_t image_opaque_bind_count;
4551
4552 bool flush_caches;
4553 VkPipelineStageFlags wait_dst_stage_mask;
4554 const VkSemaphore *wait_semaphores;
4555 uint32_t wait_semaphore_count;
4556 const VkSemaphore *signal_semaphores;
4557 uint32_t signal_semaphore_count;
4558 VkFence fence;
4559
4560 const uint64_t *wait_values;
4561 uint32_t wait_value_count;
4562 const uint64_t *signal_values;
4563 uint32_t signal_value_count;
4564 };
4565
4566 static VkResult
4567 radv_create_deferred_submission(struct radv_queue *queue,
4568 const struct radv_queue_submission *submission,
4569 struct radv_deferred_queue_submission **out)
4570 {
4571 struct radv_deferred_queue_submission *deferred = NULL;
4572 size_t size = sizeof(struct radv_deferred_queue_submission);
4573
4574 uint32_t temporary_count = 0;
4575 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4576 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4577 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE)
4578 ++temporary_count;
4579 }
4580
4581 size += submission->cmd_buffer_count * sizeof(VkCommandBuffer);
4582 size += submission->buffer_bind_count * sizeof(VkSparseBufferMemoryBindInfo);
4583 size += submission->image_opaque_bind_count * sizeof(VkSparseImageOpaqueMemoryBindInfo);
4584 size += submission->wait_semaphore_count * sizeof(struct radv_semaphore_part *);
4585 size += temporary_count * sizeof(struct radv_semaphore_part);
4586 size += submission->signal_semaphore_count * sizeof(struct radv_semaphore_part *);
4587 size += submission->wait_value_count * sizeof(uint64_t);
4588 size += submission->signal_value_count * sizeof(uint64_t);
4589 size += submission->wait_semaphore_count * sizeof(struct radv_timeline_waiter);
4590
4591 deferred = calloc(1, size);
4592 if (!deferred)
4593 return VK_ERROR_OUT_OF_HOST_MEMORY;
4594
4595 deferred->queue = queue;
4596
4597 deferred->cmd_buffers = (void*)(deferred + 1);
4598 deferred->cmd_buffer_count = submission->cmd_buffer_count;
4599 memcpy(deferred->cmd_buffers, submission->cmd_buffers,
4600 submission->cmd_buffer_count * sizeof(*deferred->cmd_buffers));
4601
4602 deferred->buffer_binds = (void*)(deferred->cmd_buffers + submission->cmd_buffer_count);
4603 deferred->buffer_bind_count = submission->buffer_bind_count;
4604 memcpy(deferred->buffer_binds, submission->buffer_binds,
4605 submission->buffer_bind_count * sizeof(*deferred->buffer_binds));
4606
4607 deferred->image_opaque_binds = (void*)(deferred->buffer_binds + submission->buffer_bind_count);
4608 deferred->image_opaque_bind_count = submission->image_opaque_bind_count;
4609 memcpy(deferred->image_opaque_binds, submission->image_opaque_binds,
4610 submission->image_opaque_bind_count * sizeof(*deferred->image_opaque_binds));
4611
4612 deferred->flush_caches = submission->flush_caches;
4613 deferred->wait_dst_stage_mask = submission->wait_dst_stage_mask;
4614
4615 deferred->wait_semaphores = (void*)(deferred->image_opaque_binds + deferred->image_opaque_bind_count);
4616 deferred->wait_semaphore_count = submission->wait_semaphore_count;
4617
4618 deferred->signal_semaphores = (void*)(deferred->wait_semaphores + deferred->wait_semaphore_count);
4619 deferred->signal_semaphore_count = submission->signal_semaphore_count;
4620
4621 deferred->fence = submission->fence;
4622
4623 deferred->temporary_semaphore_parts = (void*)(deferred->signal_semaphores + deferred->signal_semaphore_count);
4624 deferred->temporary_semaphore_part_count = temporary_count;
4625
4626 uint32_t temporary_idx = 0;
4627 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4628 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
4629 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4630 deferred->wait_semaphores[i] = &deferred->temporary_semaphore_parts[temporary_idx];
4631 deferred->temporary_semaphore_parts[temporary_idx] = semaphore->temporary;
4632 semaphore->temporary.kind = RADV_SEMAPHORE_NONE;
4633 ++temporary_idx;
4634 } else
4635 deferred->wait_semaphores[i] = &semaphore->permanent;
4636 }
4637
4638 for (uint32_t i = 0; i < submission->signal_semaphore_count; ++i) {
4639 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->signal_semaphores[i]);
4640 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE) {
4641 deferred->signal_semaphores[i] = &semaphore->temporary;
4642 } else {
4643 deferred->signal_semaphores[i] = &semaphore->permanent;
4644 }
4645 }
4646
4647 deferred->wait_values = (void*)(deferred->temporary_semaphore_parts + temporary_count);
4648 memcpy(deferred->wait_values, submission->wait_values, submission->wait_value_count * sizeof(uint64_t));
4649 deferred->signal_values = deferred->wait_values + submission->wait_value_count;
4650 memcpy(deferred->signal_values, submission->signal_values, submission->signal_value_count * sizeof(uint64_t));
4651
4652 deferred->wait_nodes = (void*)(deferred->signal_values + submission->signal_value_count);
4653 /* This is worst-case. radv_queue_enqueue_submission will fill in further, but this
4654 * ensure the submission is not accidentally triggered early when adding wait timelines. */
4655 deferred->submission_wait_count = 1 + submission->wait_semaphore_count;
4656
4657 *out = deferred;
4658 return VK_SUCCESS;
4659 }
4660
4661 static void
4662 radv_queue_enqueue_submission(struct radv_deferred_queue_submission *submission,
4663 struct list_head *processing_list)
4664 {
4665 uint32_t wait_cnt = 0;
4666 struct radv_timeline_waiter *waiter = submission->wait_nodes;
4667 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
4668 if (submission->wait_semaphores[i]->kind == RADV_SEMAPHORE_TIMELINE) {
4669 pthread_mutex_lock(&submission->wait_semaphores[i]->timeline.mutex);
4670 if (submission->wait_semaphores[i]->timeline.highest_submitted < submission->wait_values[i]) {
4671 ++wait_cnt;
4672 waiter->value = submission->wait_values[i];
4673 waiter->submission = submission;
4674 list_addtail(&waiter->list, &submission->wait_semaphores[i]->timeline.waiters);
4675 ++waiter;
4676 }
4677 pthread_mutex_unlock(&submission->wait_semaphores[i]->timeline.mutex);
4678 }
4679 }
4680
4681 pthread_mutex_lock(&submission->queue->pending_mutex);
4682
4683 bool is_first = list_is_empty(&submission->queue->pending_submissions);
4684 list_addtail(&submission->queue_pending_list, &submission->queue->pending_submissions);
4685
4686 pthread_mutex_unlock(&submission->queue->pending_mutex);
4687
4688 /* If there is already a submission in the queue, that will decrement the counter by 1 when
4689 * submitted, but if the queue was empty, we decrement ourselves as there is no previous
4690 * submission. */
4691 uint32_t decrement = submission->wait_semaphore_count - wait_cnt + (is_first ? 1 : 0);
4692 if (__atomic_sub_fetch(&submission->submission_wait_count, decrement, __ATOMIC_ACQ_REL) == 0) {
4693 list_addtail(&submission->processing_list, processing_list);
4694 }
4695 }
4696
4697 static void
4698 radv_queue_submission_update_queue(struct radv_deferred_queue_submission *submission,
4699 struct list_head *processing_list)
4700 {
4701 pthread_mutex_lock(&submission->queue->pending_mutex);
4702 list_del(&submission->queue_pending_list);
4703
4704 /* trigger the next submission in the queue. */
4705 if (!list_is_empty(&submission->queue->pending_submissions)) {
4706 struct radv_deferred_queue_submission *next_submission =
4707 list_first_entry(&submission->queue->pending_submissions,
4708 struct radv_deferred_queue_submission,
4709 queue_pending_list);
4710 if (p_atomic_dec_zero(&next_submission->submission_wait_count)) {
4711 list_addtail(&next_submission->processing_list, processing_list);
4712 }
4713 }
4714 pthread_mutex_unlock(&submission->queue->pending_mutex);
4715
4716 pthread_cond_broadcast(&submission->queue->device->timeline_cond);
4717 }
4718
4719 static VkResult
4720 radv_queue_submit_deferred(struct radv_deferred_queue_submission *submission,
4721 struct list_head *processing_list)
4722 {
4723 RADV_FROM_HANDLE(radv_fence, fence, submission->fence);
4724 struct radv_queue *queue = submission->queue;
4725 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4726 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
4727 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
4728 bool do_flush = submission->flush_caches || submission->wait_dst_stage_mask;
4729 bool can_patch = true;
4730 uint32_t advance;
4731 struct radv_winsys_sem_info sem_info;
4732 VkResult result;
4733 int ret;
4734 struct radeon_cmdbuf *initial_preamble_cs = NULL;
4735 struct radeon_cmdbuf *initial_flush_preamble_cs = NULL;
4736 struct radeon_cmdbuf *continue_preamble_cs = NULL;
4737
4738 result = radv_get_preambles(queue, submission->cmd_buffers,
4739 submission->cmd_buffer_count,
4740 &initial_preamble_cs,
4741 &initial_flush_preamble_cs,
4742 &continue_preamble_cs);
4743 if (result != VK_SUCCESS)
4744 goto fail;
4745
4746 result = radv_alloc_sem_info(queue->device,
4747 &sem_info,
4748 submission->wait_semaphore_count,
4749 submission->wait_semaphores,
4750 submission->wait_values,
4751 submission->signal_semaphore_count,
4752 submission->signal_semaphores,
4753 submission->signal_values,
4754 submission->fence);
4755 if (result != VK_SUCCESS)
4756 goto fail;
4757
4758 for (uint32_t i = 0; i < submission->buffer_bind_count; ++i) {
4759 radv_sparse_buffer_bind_memory(queue->device,
4760 submission->buffer_binds + i);
4761 }
4762
4763 for (uint32_t i = 0; i < submission->image_opaque_bind_count; ++i) {
4764 radv_sparse_image_opaque_bind_memory(queue->device,
4765 submission->image_opaque_binds + i);
4766 }
4767
4768 if (!submission->cmd_buffer_count) {
4769 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
4770 &queue->device->empty_cs[queue->queue_family_index],
4771 1, NULL, NULL,
4772 &sem_info, NULL,
4773 false, base_fence);
4774 if (ret) {
4775 radv_loge("failed to submit CS\n");
4776 abort();
4777 }
4778
4779 goto success;
4780 } else {
4781 struct radeon_cmdbuf **cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
4782 (submission->cmd_buffer_count));
4783
4784 for (uint32_t j = 0; j < submission->cmd_buffer_count; j++) {
4785 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer, submission->cmd_buffers[j]);
4786 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4787
4788 cs_array[j] = cmd_buffer->cs;
4789 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
4790 can_patch = false;
4791
4792 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
4793 }
4794
4795 for (uint32_t j = 0; j < submission->cmd_buffer_count; j += advance) {
4796 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
4797 const struct radv_winsys_bo_list *bo_list = NULL;
4798
4799 advance = MIN2(max_cs_submission,
4800 submission->cmd_buffer_count - j);
4801
4802 if (queue->device->trace_bo)
4803 *queue->device->trace_id_ptr = 0;
4804
4805 sem_info.cs_emit_wait = j == 0;
4806 sem_info.cs_emit_signal = j + advance == submission->cmd_buffer_count;
4807
4808 if (unlikely(queue->device->use_global_bo_list)) {
4809 pthread_mutex_lock(&queue->device->bo_list.mutex);
4810 bo_list = &queue->device->bo_list.list;
4811 }
4812
4813 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
4814 advance, initial_preamble, continue_preamble_cs,
4815 &sem_info, bo_list,
4816 can_patch, base_fence);
4817
4818 if (unlikely(queue->device->use_global_bo_list))
4819 pthread_mutex_unlock(&queue->device->bo_list.mutex);
4820
4821 if (ret) {
4822 radv_loge("failed to submit CS\n");
4823 abort();
4824 }
4825 if (queue->device->trace_bo) {
4826 radv_check_gpu_hangs(queue, cs_array[j]);
4827 }
4828 }
4829
4830 free(cs_array);
4831 }
4832
4833 success:
4834 radv_free_temp_syncobjs(queue->device,
4835 submission->temporary_semaphore_part_count,
4836 submission->temporary_semaphore_parts);
4837 radv_finalize_timelines(queue->device,
4838 submission->wait_semaphore_count,
4839 submission->wait_semaphores,
4840 submission->wait_values,
4841 submission->signal_semaphore_count,
4842 submission->signal_semaphores,
4843 submission->signal_values,
4844 processing_list);
4845 /* Has to happen after timeline finalization to make sure the
4846 * condition variable is only triggered when timelines and queue have
4847 * been updated. */
4848 radv_queue_submission_update_queue(submission, processing_list);
4849 radv_free_sem_info(&sem_info);
4850 free(submission);
4851 return VK_SUCCESS;
4852
4853 fail:
4854 radv_free_temp_syncobjs(queue->device,
4855 submission->temporary_semaphore_part_count,
4856 submission->temporary_semaphore_parts);
4857 free(submission);
4858 return VK_ERROR_DEVICE_LOST;
4859 }
4860
4861 static VkResult
4862 radv_process_submissions(struct list_head *processing_list)
4863 {
4864 while(!list_is_empty(processing_list)) {
4865 struct radv_deferred_queue_submission *submission =
4866 list_first_entry(processing_list, struct radv_deferred_queue_submission, processing_list);
4867 list_del(&submission->processing_list);
4868
4869 VkResult result = radv_queue_submit_deferred(submission, processing_list);
4870 if (result != VK_SUCCESS)
4871 return result;
4872 }
4873 return VK_SUCCESS;
4874 }
4875
4876 static VkResult radv_queue_submit(struct radv_queue *queue,
4877 const struct radv_queue_submission *submission)
4878 {
4879 struct radv_deferred_queue_submission *deferred = NULL;
4880
4881 VkResult result = radv_create_deferred_submission(queue, submission, &deferred);
4882 if (result != VK_SUCCESS)
4883 return result;
4884
4885 struct list_head processing_list;
4886 list_inithead(&processing_list);
4887
4888 radv_queue_enqueue_submission(deferred, &processing_list);
4889 return radv_process_submissions(&processing_list);
4890 }
4891
4892 bool
4893 radv_queue_internal_submit(struct radv_queue *queue, struct radeon_cmdbuf *cs)
4894 {
4895 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
4896 struct radv_winsys_sem_info sem_info;
4897 VkResult result;
4898 int ret;
4899
4900 result = radv_alloc_sem_info(queue->device, &sem_info, 0, NULL, 0, 0,
4901 0, NULL, VK_NULL_HANDLE);
4902 if (result != VK_SUCCESS)
4903 return false;
4904
4905 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, &cs, 1, NULL,
4906 NULL, &sem_info, NULL, false, NULL);
4907 radv_free_sem_info(&sem_info);
4908 return !ret;
4909 }
4910
4911 /* Signals fence as soon as all the work currently put on queue is done. */
4912 static VkResult radv_signal_fence(struct radv_queue *queue,
4913 VkFence fence)
4914 {
4915 return radv_queue_submit(queue, &(struct radv_queue_submission) {
4916 .fence = fence
4917 });
4918 }
4919
4920 static bool radv_submit_has_effects(const VkSubmitInfo *info)
4921 {
4922 return info->commandBufferCount ||
4923 info->waitSemaphoreCount ||
4924 info->signalSemaphoreCount;
4925 }
4926
4927 VkResult radv_QueueSubmit(
4928 VkQueue _queue,
4929 uint32_t submitCount,
4930 const VkSubmitInfo* pSubmits,
4931 VkFence fence)
4932 {
4933 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4934 VkResult result;
4935 uint32_t fence_idx = 0;
4936 bool flushed_caches = false;
4937
4938 if (fence != VK_NULL_HANDLE) {
4939 for (uint32_t i = 0; i < submitCount; ++i)
4940 if (radv_submit_has_effects(pSubmits + i))
4941 fence_idx = i;
4942 } else
4943 fence_idx = UINT32_MAX;
4944
4945 for (uint32_t i = 0; i < submitCount; i++) {
4946 if (!radv_submit_has_effects(pSubmits + i) && fence_idx != i)
4947 continue;
4948
4949 VkPipelineStageFlags wait_dst_stage_mask = 0;
4950 for (unsigned j = 0; j < pSubmits[i].waitSemaphoreCount; ++j) {
4951 wait_dst_stage_mask |= pSubmits[i].pWaitDstStageMask[j];
4952 }
4953
4954 const VkTimelineSemaphoreSubmitInfo *timeline_info =
4955 vk_find_struct_const(pSubmits[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
4956
4957 result = radv_queue_submit(queue, &(struct radv_queue_submission) {
4958 .cmd_buffers = pSubmits[i].pCommandBuffers,
4959 .cmd_buffer_count = pSubmits[i].commandBufferCount,
4960 .wait_dst_stage_mask = wait_dst_stage_mask,
4961 .flush_caches = !flushed_caches,
4962 .wait_semaphores = pSubmits[i].pWaitSemaphores,
4963 .wait_semaphore_count = pSubmits[i].waitSemaphoreCount,
4964 .signal_semaphores = pSubmits[i].pSignalSemaphores,
4965 .signal_semaphore_count = pSubmits[i].signalSemaphoreCount,
4966 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
4967 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
4968 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
4969 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
4970 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
4971 });
4972 if (result != VK_SUCCESS)
4973 return result;
4974
4975 flushed_caches = true;
4976 }
4977
4978 if (fence != VK_NULL_HANDLE && !submitCount) {
4979 result = radv_signal_fence(queue, fence);
4980 if (result != VK_SUCCESS)
4981 return result;
4982 }
4983
4984 return VK_SUCCESS;
4985 }
4986
4987 VkResult radv_QueueWaitIdle(
4988 VkQueue _queue)
4989 {
4990 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4991
4992 pthread_mutex_lock(&queue->pending_mutex);
4993 while (!list_is_empty(&queue->pending_submissions)) {
4994 pthread_cond_wait(&queue->device->timeline_cond, &queue->pending_mutex);
4995 }
4996 pthread_mutex_unlock(&queue->pending_mutex);
4997
4998 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
4999 radv_queue_family_to_ring(queue->queue_family_index),
5000 queue->queue_idx);
5001 return VK_SUCCESS;
5002 }
5003
5004 VkResult radv_DeviceWaitIdle(
5005 VkDevice _device)
5006 {
5007 RADV_FROM_HANDLE(radv_device, device, _device);
5008
5009 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
5010 for (unsigned q = 0; q < device->queue_count[i]; q++) {
5011 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
5012 }
5013 }
5014 return VK_SUCCESS;
5015 }
5016
5017 VkResult radv_EnumerateInstanceExtensionProperties(
5018 const char* pLayerName,
5019 uint32_t* pPropertyCount,
5020 VkExtensionProperties* pProperties)
5021 {
5022 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
5023
5024 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
5025 if (radv_instance_extensions_supported.extensions[i]) {
5026 vk_outarray_append(&out, prop) {
5027 *prop = radv_instance_extensions[i];
5028 }
5029 }
5030 }
5031
5032 return vk_outarray_status(&out);
5033 }
5034
5035 VkResult radv_EnumerateDeviceExtensionProperties(
5036 VkPhysicalDevice physicalDevice,
5037 const char* pLayerName,
5038 uint32_t* pPropertyCount,
5039 VkExtensionProperties* pProperties)
5040 {
5041 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
5042 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
5043
5044 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
5045 if (device->supported_extensions.extensions[i]) {
5046 vk_outarray_append(&out, prop) {
5047 *prop = radv_device_extensions[i];
5048 }
5049 }
5050 }
5051
5052 return vk_outarray_status(&out);
5053 }
5054
5055 PFN_vkVoidFunction radv_GetInstanceProcAddr(
5056 VkInstance _instance,
5057 const char* pName)
5058 {
5059 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5060
5061 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
5062 * when we have to return valid function pointers, NULL, or it's left
5063 * undefined. See the table for exact details.
5064 */
5065 if (pName == NULL)
5066 return NULL;
5067
5068 #define LOOKUP_RADV_ENTRYPOINT(entrypoint) \
5069 if (strcmp(pName, "vk" #entrypoint) == 0) \
5070 return (PFN_vkVoidFunction)radv_##entrypoint
5071
5072 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
5073 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceLayerProperties);
5074 LOOKUP_RADV_ENTRYPOINT(EnumerateInstanceVersion);
5075 LOOKUP_RADV_ENTRYPOINT(CreateInstance);
5076
5077 /* GetInstanceProcAddr() can also be called with a NULL instance.
5078 * See https://gitlab.khronos.org/vulkan/vulkan/issues/2057
5079 */
5080 LOOKUP_RADV_ENTRYPOINT(GetInstanceProcAddr);
5081
5082 #undef LOOKUP_RADV_ENTRYPOINT
5083
5084 if (instance == NULL)
5085 return NULL;
5086
5087 int idx = radv_get_instance_entrypoint_index(pName);
5088 if (idx >= 0)
5089 return instance->dispatch.entrypoints[idx];
5090
5091 idx = radv_get_physical_device_entrypoint_index(pName);
5092 if (idx >= 0)
5093 return instance->physical_device_dispatch.entrypoints[idx];
5094
5095 idx = radv_get_device_entrypoint_index(pName);
5096 if (idx >= 0)
5097 return instance->device_dispatch.entrypoints[idx];
5098
5099 return NULL;
5100 }
5101
5102 /* The loader wants us to expose a second GetInstanceProcAddr function
5103 * to work around certain LD_PRELOAD issues seen in apps.
5104 */
5105 PUBLIC
5106 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
5107 VkInstance instance,
5108 const char* pName);
5109
5110 PUBLIC
5111 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
5112 VkInstance instance,
5113 const char* pName)
5114 {
5115 return radv_GetInstanceProcAddr(instance, pName);
5116 }
5117
5118 PUBLIC
5119 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
5120 VkInstance _instance,
5121 const char* pName);
5122
5123 PUBLIC
5124 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
5125 VkInstance _instance,
5126 const char* pName)
5127 {
5128 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5129
5130 if (!pName || !instance)
5131 return NULL;
5132
5133 int idx = radv_get_physical_device_entrypoint_index(pName);
5134 if (idx < 0)
5135 return NULL;
5136
5137 return instance->physical_device_dispatch.entrypoints[idx];
5138 }
5139
5140 PFN_vkVoidFunction radv_GetDeviceProcAddr(
5141 VkDevice _device,
5142 const char* pName)
5143 {
5144 RADV_FROM_HANDLE(radv_device, device, _device);
5145
5146 if (!device || !pName)
5147 return NULL;
5148
5149 int idx = radv_get_device_entrypoint_index(pName);
5150 if (idx < 0)
5151 return NULL;
5152
5153 return device->dispatch.entrypoints[idx];
5154 }
5155
5156 bool radv_get_memory_fd(struct radv_device *device,
5157 struct radv_device_memory *memory,
5158 int *pFD)
5159 {
5160 struct radeon_bo_metadata metadata;
5161
5162 if (memory->image) {
5163 if (memory->image->tiling != VK_IMAGE_TILING_LINEAR)
5164 radv_init_metadata(device, memory->image, &metadata);
5165 device->ws->buffer_set_metadata(memory->bo, &metadata);
5166 }
5167
5168 return device->ws->buffer_get_fd(device->ws, memory->bo,
5169 pFD);
5170 }
5171
5172
5173 static void radv_free_memory(struct radv_device *device,
5174 const VkAllocationCallbacks* pAllocator,
5175 struct radv_device_memory *mem)
5176 {
5177 if (mem == NULL)
5178 return;
5179
5180 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
5181 if (mem->android_hardware_buffer)
5182 AHardwareBuffer_release(mem->android_hardware_buffer);
5183 #endif
5184
5185 if (mem->bo) {
5186 if (device->overallocation_disallowed) {
5187 mtx_lock(&device->overallocation_mutex);
5188 device->allocated_memory_size[mem->heap_index] -= mem->alloc_size;
5189 mtx_unlock(&device->overallocation_mutex);
5190 }
5191
5192 radv_bo_list_remove(device, mem->bo);
5193 device->ws->buffer_destroy(mem->bo);
5194 mem->bo = NULL;
5195 }
5196
5197 vk_object_base_finish(&mem->base);
5198 vk_free2(&device->vk.alloc, pAllocator, mem);
5199 }
5200
5201 static VkResult radv_alloc_memory(struct radv_device *device,
5202 const VkMemoryAllocateInfo* pAllocateInfo,
5203 const VkAllocationCallbacks* pAllocator,
5204 VkDeviceMemory* pMem)
5205 {
5206 struct radv_device_memory *mem;
5207 VkResult result;
5208 enum radeon_bo_domain domain;
5209 uint32_t flags = 0;
5210
5211 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
5212
5213 const VkImportMemoryFdInfoKHR *import_info =
5214 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
5215 const VkMemoryDedicatedAllocateInfo *dedicate_info =
5216 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
5217 const VkExportMemoryAllocateInfo *export_info =
5218 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
5219 const struct VkImportAndroidHardwareBufferInfoANDROID *ahb_import_info =
5220 vk_find_struct_const(pAllocateInfo->pNext,
5221 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
5222 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
5223 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
5224
5225 const struct wsi_memory_allocate_info *wsi_info =
5226 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
5227
5228 if (pAllocateInfo->allocationSize == 0 && !ahb_import_info &&
5229 !(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
5230 /* Apparently, this is allowed */
5231 *pMem = VK_NULL_HANDLE;
5232 return VK_SUCCESS;
5233 }
5234
5235 mem = vk_zalloc2(&device->vk.alloc, pAllocator, sizeof(*mem), 8,
5236 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5237 if (mem == NULL)
5238 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5239
5240 vk_object_base_init(&device->vk, &mem->base,
5241 VK_OBJECT_TYPE_DEVICE_MEMORY);
5242
5243 if (wsi_info && wsi_info->implicit_sync)
5244 flags |= RADEON_FLAG_IMPLICIT_SYNC;
5245
5246 if (dedicate_info) {
5247 mem->image = radv_image_from_handle(dedicate_info->image);
5248 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
5249 } else {
5250 mem->image = NULL;
5251 mem->buffer = NULL;
5252 }
5253
5254 float priority_float = 0.5;
5255 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
5256 vk_find_struct_const(pAllocateInfo->pNext,
5257 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
5258 if (priority_ext)
5259 priority_float = priority_ext->priority;
5260
5261 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
5262 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
5263
5264 mem->user_ptr = NULL;
5265 mem->bo = NULL;
5266
5267 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
5268 mem->android_hardware_buffer = NULL;
5269 #endif
5270
5271 if (ahb_import_info) {
5272 result = radv_import_ahb_memory(device, mem, priority, ahb_import_info);
5273 if (result != VK_SUCCESS)
5274 goto fail;
5275 } else if(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
5276 result = radv_create_ahb_memory(device, mem, priority, pAllocateInfo);
5277 if (result != VK_SUCCESS)
5278 goto fail;
5279 } else if (import_info) {
5280 assert(import_info->handleType ==
5281 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
5282 import_info->handleType ==
5283 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
5284 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
5285 priority, NULL);
5286 if (!mem->bo) {
5287 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5288 goto fail;
5289 } else {
5290 close(import_info->fd);
5291 }
5292 } else if (host_ptr_info) {
5293 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
5294 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
5295 pAllocateInfo->allocationSize,
5296 priority);
5297 if (!mem->bo) {
5298 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
5299 goto fail;
5300 } else {
5301 mem->user_ptr = host_ptr_info->pHostPointer;
5302 }
5303 } else {
5304 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
5305 uint32_t heap_index;
5306
5307 heap_index = device->physical_device->memory_properties.memoryTypes[pAllocateInfo->memoryTypeIndex].heapIndex;
5308 domain = device->physical_device->memory_domains[pAllocateInfo->memoryTypeIndex];
5309 flags |= device->physical_device->memory_flags[pAllocateInfo->memoryTypeIndex];
5310
5311 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
5312 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
5313 if (device->use_global_bo_list) {
5314 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
5315 }
5316 }
5317
5318 if (device->overallocation_disallowed) {
5319 uint64_t total_size =
5320 device->physical_device->memory_properties.memoryHeaps[heap_index].size;
5321
5322 mtx_lock(&device->overallocation_mutex);
5323 if (device->allocated_memory_size[heap_index] + alloc_size > total_size) {
5324 mtx_unlock(&device->overallocation_mutex);
5325 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5326 goto fail;
5327 }
5328 device->allocated_memory_size[heap_index] += alloc_size;
5329 mtx_unlock(&device->overallocation_mutex);
5330 }
5331
5332 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
5333 domain, flags, priority);
5334
5335 if (!mem->bo) {
5336 if (device->overallocation_disallowed) {
5337 mtx_lock(&device->overallocation_mutex);
5338 device->allocated_memory_size[heap_index] -= alloc_size;
5339 mtx_unlock(&device->overallocation_mutex);
5340 }
5341 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
5342 goto fail;
5343 }
5344
5345 mem->heap_index = heap_index;
5346 mem->alloc_size = alloc_size;
5347 }
5348
5349 if (!wsi_info) {
5350 result = radv_bo_list_add(device, mem->bo);
5351 if (result != VK_SUCCESS)
5352 goto fail;
5353 }
5354
5355 *pMem = radv_device_memory_to_handle(mem);
5356
5357 return VK_SUCCESS;
5358
5359 fail:
5360 radv_free_memory(device, pAllocator,mem);
5361
5362 return result;
5363 }
5364
5365 VkResult radv_AllocateMemory(
5366 VkDevice _device,
5367 const VkMemoryAllocateInfo* pAllocateInfo,
5368 const VkAllocationCallbacks* pAllocator,
5369 VkDeviceMemory* pMem)
5370 {
5371 RADV_FROM_HANDLE(radv_device, device, _device);
5372 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
5373 }
5374
5375 void radv_FreeMemory(
5376 VkDevice _device,
5377 VkDeviceMemory _mem,
5378 const VkAllocationCallbacks* pAllocator)
5379 {
5380 RADV_FROM_HANDLE(radv_device, device, _device);
5381 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
5382
5383 radv_free_memory(device, pAllocator, mem);
5384 }
5385
5386 VkResult radv_MapMemory(
5387 VkDevice _device,
5388 VkDeviceMemory _memory,
5389 VkDeviceSize offset,
5390 VkDeviceSize size,
5391 VkMemoryMapFlags flags,
5392 void** ppData)
5393 {
5394 RADV_FROM_HANDLE(radv_device, device, _device);
5395 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5396
5397 if (mem == NULL) {
5398 *ppData = NULL;
5399 return VK_SUCCESS;
5400 }
5401
5402 if (mem->user_ptr)
5403 *ppData = mem->user_ptr;
5404 else
5405 *ppData = device->ws->buffer_map(mem->bo);
5406
5407 if (*ppData) {
5408 *ppData += offset;
5409 return VK_SUCCESS;
5410 }
5411
5412 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
5413 }
5414
5415 void radv_UnmapMemory(
5416 VkDevice _device,
5417 VkDeviceMemory _memory)
5418 {
5419 RADV_FROM_HANDLE(radv_device, device, _device);
5420 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
5421
5422 if (mem == NULL)
5423 return;
5424
5425 if (mem->user_ptr == NULL)
5426 device->ws->buffer_unmap(mem->bo);
5427 }
5428
5429 VkResult radv_FlushMappedMemoryRanges(
5430 VkDevice _device,
5431 uint32_t memoryRangeCount,
5432 const VkMappedMemoryRange* pMemoryRanges)
5433 {
5434 return VK_SUCCESS;
5435 }
5436
5437 VkResult radv_InvalidateMappedMemoryRanges(
5438 VkDevice _device,
5439 uint32_t memoryRangeCount,
5440 const VkMappedMemoryRange* pMemoryRanges)
5441 {
5442 return VK_SUCCESS;
5443 }
5444
5445 void radv_GetBufferMemoryRequirements(
5446 VkDevice _device,
5447 VkBuffer _buffer,
5448 VkMemoryRequirements* pMemoryRequirements)
5449 {
5450 RADV_FROM_HANDLE(radv_device, device, _device);
5451 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
5452
5453 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5454
5455 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
5456 pMemoryRequirements->alignment = 4096;
5457 else
5458 pMemoryRequirements->alignment = 16;
5459
5460 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
5461 }
5462
5463 void radv_GetBufferMemoryRequirements2(
5464 VkDevice device,
5465 const VkBufferMemoryRequirementsInfo2 *pInfo,
5466 VkMemoryRequirements2 *pMemoryRequirements)
5467 {
5468 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
5469 &pMemoryRequirements->memoryRequirements);
5470 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5471 switch (ext->sType) {
5472 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5473 VkMemoryDedicatedRequirements *req =
5474 (VkMemoryDedicatedRequirements *) ext;
5475 req->requiresDedicatedAllocation = false;
5476 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5477 break;
5478 }
5479 default:
5480 break;
5481 }
5482 }
5483 }
5484
5485 void radv_GetImageMemoryRequirements(
5486 VkDevice _device,
5487 VkImage _image,
5488 VkMemoryRequirements* pMemoryRequirements)
5489 {
5490 RADV_FROM_HANDLE(radv_device, device, _device);
5491 RADV_FROM_HANDLE(radv_image, image, _image);
5492
5493 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
5494
5495 pMemoryRequirements->size = image->size;
5496 pMemoryRequirements->alignment = image->alignment;
5497 }
5498
5499 void radv_GetImageMemoryRequirements2(
5500 VkDevice device,
5501 const VkImageMemoryRequirementsInfo2 *pInfo,
5502 VkMemoryRequirements2 *pMemoryRequirements)
5503 {
5504 radv_GetImageMemoryRequirements(device, pInfo->image,
5505 &pMemoryRequirements->memoryRequirements);
5506
5507 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
5508
5509 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
5510 switch (ext->sType) {
5511 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
5512 VkMemoryDedicatedRequirements *req =
5513 (VkMemoryDedicatedRequirements *) ext;
5514 req->requiresDedicatedAllocation = image->shareable &&
5515 image->tiling != VK_IMAGE_TILING_LINEAR;
5516 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
5517 break;
5518 }
5519 default:
5520 break;
5521 }
5522 }
5523 }
5524
5525 void radv_GetImageSparseMemoryRequirements(
5526 VkDevice device,
5527 VkImage image,
5528 uint32_t* pSparseMemoryRequirementCount,
5529 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
5530 {
5531 stub();
5532 }
5533
5534 void radv_GetImageSparseMemoryRequirements2(
5535 VkDevice device,
5536 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
5537 uint32_t* pSparseMemoryRequirementCount,
5538 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
5539 {
5540 stub();
5541 }
5542
5543 void radv_GetDeviceMemoryCommitment(
5544 VkDevice device,
5545 VkDeviceMemory memory,
5546 VkDeviceSize* pCommittedMemoryInBytes)
5547 {
5548 *pCommittedMemoryInBytes = 0;
5549 }
5550
5551 VkResult radv_BindBufferMemory2(VkDevice device,
5552 uint32_t bindInfoCount,
5553 const VkBindBufferMemoryInfo *pBindInfos)
5554 {
5555 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5556 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5557 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
5558
5559 if (mem) {
5560 buffer->bo = mem->bo;
5561 buffer->offset = pBindInfos[i].memoryOffset;
5562 } else {
5563 buffer->bo = NULL;
5564 }
5565 }
5566 return VK_SUCCESS;
5567 }
5568
5569 VkResult radv_BindBufferMemory(
5570 VkDevice device,
5571 VkBuffer buffer,
5572 VkDeviceMemory memory,
5573 VkDeviceSize memoryOffset)
5574 {
5575 const VkBindBufferMemoryInfo info = {
5576 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5577 .buffer = buffer,
5578 .memory = memory,
5579 .memoryOffset = memoryOffset
5580 };
5581
5582 return radv_BindBufferMemory2(device, 1, &info);
5583 }
5584
5585 VkResult radv_BindImageMemory2(VkDevice device,
5586 uint32_t bindInfoCount,
5587 const VkBindImageMemoryInfo *pBindInfos)
5588 {
5589 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5590 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
5591 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
5592
5593 if (mem) {
5594 image->bo = mem->bo;
5595 image->offset = pBindInfos[i].memoryOffset;
5596 } else {
5597 image->bo = NULL;
5598 image->offset = 0;
5599 }
5600 }
5601 return VK_SUCCESS;
5602 }
5603
5604
5605 VkResult radv_BindImageMemory(
5606 VkDevice device,
5607 VkImage image,
5608 VkDeviceMemory memory,
5609 VkDeviceSize memoryOffset)
5610 {
5611 const VkBindImageMemoryInfo info = {
5612 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
5613 .image = image,
5614 .memory = memory,
5615 .memoryOffset = memoryOffset
5616 };
5617
5618 return radv_BindImageMemory2(device, 1, &info);
5619 }
5620
5621 static bool radv_sparse_bind_has_effects(const VkBindSparseInfo *info)
5622 {
5623 return info->bufferBindCount ||
5624 info->imageOpaqueBindCount ||
5625 info->imageBindCount ||
5626 info->waitSemaphoreCount ||
5627 info->signalSemaphoreCount;
5628 }
5629
5630 VkResult radv_QueueBindSparse(
5631 VkQueue _queue,
5632 uint32_t bindInfoCount,
5633 const VkBindSparseInfo* pBindInfo,
5634 VkFence fence)
5635 {
5636 RADV_FROM_HANDLE(radv_queue, queue, _queue);
5637 VkResult result;
5638 uint32_t fence_idx = 0;
5639
5640 if (fence != VK_NULL_HANDLE) {
5641 for (uint32_t i = 0; i < bindInfoCount; ++i)
5642 if (radv_sparse_bind_has_effects(pBindInfo + i))
5643 fence_idx = i;
5644 } else
5645 fence_idx = UINT32_MAX;
5646
5647 for (uint32_t i = 0; i < bindInfoCount; ++i) {
5648 if (i != fence_idx && !radv_sparse_bind_has_effects(pBindInfo + i))
5649 continue;
5650
5651 const VkTimelineSemaphoreSubmitInfo *timeline_info =
5652 vk_find_struct_const(pBindInfo[i].pNext, TIMELINE_SEMAPHORE_SUBMIT_INFO);
5653
5654 VkResult result = radv_queue_submit(queue, &(struct radv_queue_submission) {
5655 .buffer_binds = pBindInfo[i].pBufferBinds,
5656 .buffer_bind_count = pBindInfo[i].bufferBindCount,
5657 .image_opaque_binds = pBindInfo[i].pImageOpaqueBinds,
5658 .image_opaque_bind_count = pBindInfo[i].imageOpaqueBindCount,
5659 .wait_semaphores = pBindInfo[i].pWaitSemaphores,
5660 .wait_semaphore_count = pBindInfo[i].waitSemaphoreCount,
5661 .signal_semaphores = pBindInfo[i].pSignalSemaphores,
5662 .signal_semaphore_count = pBindInfo[i].signalSemaphoreCount,
5663 .fence = i == fence_idx ? fence : VK_NULL_HANDLE,
5664 .wait_values = timeline_info ? timeline_info->pWaitSemaphoreValues : NULL,
5665 .wait_value_count = timeline_info && timeline_info->pWaitSemaphoreValues ? timeline_info->waitSemaphoreValueCount : 0,
5666 .signal_values = timeline_info ? timeline_info->pSignalSemaphoreValues : NULL,
5667 .signal_value_count = timeline_info && timeline_info->pSignalSemaphoreValues ? timeline_info->signalSemaphoreValueCount : 0,
5668 });
5669
5670 if (result != VK_SUCCESS)
5671 return result;
5672 }
5673
5674 if (fence != VK_NULL_HANDLE && !bindInfoCount) {
5675 result = radv_signal_fence(queue, fence);
5676 if (result != VK_SUCCESS)
5677 return result;
5678 }
5679
5680 return VK_SUCCESS;
5681 }
5682
5683 VkResult radv_CreateFence(
5684 VkDevice _device,
5685 const VkFenceCreateInfo* pCreateInfo,
5686 const VkAllocationCallbacks* pAllocator,
5687 VkFence* pFence)
5688 {
5689 RADV_FROM_HANDLE(radv_device, device, _device);
5690 const VkExportFenceCreateInfo *export =
5691 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
5692 VkExternalFenceHandleTypeFlags handleTypes =
5693 export ? export->handleTypes : 0;
5694
5695 struct radv_fence *fence = vk_alloc2(&device->vk.alloc, pAllocator,
5696 sizeof(*fence), 8,
5697 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5698
5699 if (!fence)
5700 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5701
5702 vk_object_base_init(&device->vk, &fence->base, VK_OBJECT_TYPE_FENCE);
5703
5704 fence->fence_wsi = NULL;
5705 fence->temp_syncobj = 0;
5706 if (device->always_use_syncobj || handleTypes) {
5707 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
5708 if (ret) {
5709 vk_free2(&device->vk.alloc, pAllocator, fence);
5710 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5711 }
5712 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
5713 device->ws->signal_syncobj(device->ws, fence->syncobj);
5714 }
5715 fence->fence = NULL;
5716 } else {
5717 fence->fence = device->ws->create_fence();
5718 if (!fence->fence) {
5719 vk_free2(&device->vk.alloc, pAllocator, fence);
5720 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5721 }
5722 fence->syncobj = 0;
5723 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
5724 device->ws->signal_fence(fence->fence);
5725 }
5726
5727 *pFence = radv_fence_to_handle(fence);
5728
5729 return VK_SUCCESS;
5730 }
5731
5732 void radv_DestroyFence(
5733 VkDevice _device,
5734 VkFence _fence,
5735 const VkAllocationCallbacks* pAllocator)
5736 {
5737 RADV_FROM_HANDLE(radv_device, device, _device);
5738 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5739
5740 if (!fence)
5741 return;
5742
5743 if (fence->temp_syncobj)
5744 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5745 if (fence->syncobj)
5746 device->ws->destroy_syncobj(device->ws, fence->syncobj);
5747 if (fence->fence)
5748 device->ws->destroy_fence(fence->fence);
5749 if (fence->fence_wsi)
5750 fence->fence_wsi->destroy(fence->fence_wsi);
5751
5752 vk_object_base_finish(&fence->base);
5753 vk_free2(&device->vk.alloc, pAllocator, fence);
5754 }
5755
5756
5757 uint64_t radv_get_current_time(void)
5758 {
5759 struct timespec tv;
5760 clock_gettime(CLOCK_MONOTONIC, &tv);
5761 return tv.tv_nsec + tv.tv_sec*1000000000ull;
5762 }
5763
5764 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
5765 {
5766 uint64_t current_time = radv_get_current_time();
5767
5768 timeout = MIN2(UINT64_MAX - current_time, timeout);
5769
5770 return current_time + timeout;
5771 }
5772
5773
5774 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
5775 uint32_t fenceCount, const VkFence *pFences)
5776 {
5777 for (uint32_t i = 0; i < fenceCount; ++i) {
5778 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5779 if (fence->fence == NULL || fence->syncobj ||
5780 fence->temp_syncobj || fence->fence_wsi ||
5781 (!device->ws->is_fence_waitable(fence->fence)))
5782 return false;
5783 }
5784 return true;
5785 }
5786
5787 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
5788 {
5789 for (uint32_t i = 0; i < fenceCount; ++i) {
5790 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5791 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
5792 return false;
5793 }
5794 return true;
5795 }
5796
5797 VkResult radv_WaitForFences(
5798 VkDevice _device,
5799 uint32_t fenceCount,
5800 const VkFence* pFences,
5801 VkBool32 waitAll,
5802 uint64_t timeout)
5803 {
5804 RADV_FROM_HANDLE(radv_device, device, _device);
5805 timeout = radv_get_absolute_timeout(timeout);
5806
5807 if (device->always_use_syncobj &&
5808 radv_all_fences_syncobj(fenceCount, pFences))
5809 {
5810 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
5811 if (!handles)
5812 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5813
5814 for (uint32_t i = 0; i < fenceCount; ++i) {
5815 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5816 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
5817 }
5818
5819 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
5820
5821 free(handles);
5822 return success ? VK_SUCCESS : VK_TIMEOUT;
5823 }
5824
5825 if (!waitAll && fenceCount > 1) {
5826 /* Not doing this by default for waitAll, due to needing to allocate twice. */
5827 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
5828 uint32_t wait_count = 0;
5829 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
5830 if (!fences)
5831 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5832
5833 for (uint32_t i = 0; i < fenceCount; ++i) {
5834 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5835
5836 if (device->ws->fence_wait(device->ws, fence->fence, false, 0)) {
5837 free(fences);
5838 return VK_SUCCESS;
5839 }
5840
5841 fences[wait_count++] = fence->fence;
5842 }
5843
5844 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
5845 waitAll, timeout - radv_get_current_time());
5846
5847 free(fences);
5848 return success ? VK_SUCCESS : VK_TIMEOUT;
5849 }
5850
5851 while(radv_get_current_time() <= timeout) {
5852 for (uint32_t i = 0; i < fenceCount; ++i) {
5853 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
5854 return VK_SUCCESS;
5855 }
5856 }
5857 return VK_TIMEOUT;
5858 }
5859
5860 for (uint32_t i = 0; i < fenceCount; ++i) {
5861 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5862 bool expired = false;
5863
5864 if (fence->temp_syncobj) {
5865 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
5866 return VK_TIMEOUT;
5867 continue;
5868 }
5869
5870 if (fence->syncobj) {
5871 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
5872 return VK_TIMEOUT;
5873 continue;
5874 }
5875
5876 if (fence->fence) {
5877 if (!device->ws->is_fence_waitable(fence->fence)) {
5878 while(!device->ws->is_fence_waitable(fence->fence) &&
5879 radv_get_current_time() <= timeout)
5880 /* Do nothing */;
5881 }
5882
5883 expired = device->ws->fence_wait(device->ws,
5884 fence->fence,
5885 true, timeout);
5886 if (!expired)
5887 return VK_TIMEOUT;
5888 }
5889
5890 if (fence->fence_wsi) {
5891 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
5892 if (result != VK_SUCCESS)
5893 return result;
5894 }
5895 }
5896
5897 return VK_SUCCESS;
5898 }
5899
5900 VkResult radv_ResetFences(VkDevice _device,
5901 uint32_t fenceCount,
5902 const VkFence *pFences)
5903 {
5904 RADV_FROM_HANDLE(radv_device, device, _device);
5905
5906 for (unsigned i = 0; i < fenceCount; ++i) {
5907 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
5908 if (fence->fence)
5909 device->ws->reset_fence(fence->fence);
5910
5911 /* Per spec, we first restore the permanent payload, and then reset, so
5912 * having a temp syncobj should not skip resetting the permanent syncobj. */
5913 if (fence->temp_syncobj) {
5914 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
5915 fence->temp_syncobj = 0;
5916 }
5917
5918 if (fence->syncobj) {
5919 device->ws->reset_syncobj(device->ws, fence->syncobj);
5920 }
5921 }
5922
5923 return VK_SUCCESS;
5924 }
5925
5926 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
5927 {
5928 RADV_FROM_HANDLE(radv_device, device, _device);
5929 RADV_FROM_HANDLE(radv_fence, fence, _fence);
5930
5931 if (fence->temp_syncobj) {
5932 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
5933 return success ? VK_SUCCESS : VK_NOT_READY;
5934 }
5935
5936 if (fence->syncobj) {
5937 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
5938 return success ? VK_SUCCESS : VK_NOT_READY;
5939 }
5940
5941 if (fence->fence) {
5942 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
5943 return VK_NOT_READY;
5944 }
5945 if (fence->fence_wsi) {
5946 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
5947
5948 if (result != VK_SUCCESS) {
5949 if (result == VK_TIMEOUT)
5950 return VK_NOT_READY;
5951 return result;
5952 }
5953 }
5954 return VK_SUCCESS;
5955 }
5956
5957
5958 // Queue semaphore functions
5959
5960 static void
5961 radv_create_timeline(struct radv_timeline *timeline, uint64_t value)
5962 {
5963 timeline->highest_signaled = value;
5964 timeline->highest_submitted = value;
5965 list_inithead(&timeline->points);
5966 list_inithead(&timeline->free_points);
5967 list_inithead(&timeline->waiters);
5968 pthread_mutex_init(&timeline->mutex, NULL);
5969 }
5970
5971 static void
5972 radv_destroy_timeline(struct radv_device *device,
5973 struct radv_timeline *timeline)
5974 {
5975 list_for_each_entry_safe(struct radv_timeline_point, point,
5976 &timeline->free_points, list) {
5977 list_del(&point->list);
5978 device->ws->destroy_syncobj(device->ws, point->syncobj);
5979 free(point);
5980 }
5981 list_for_each_entry_safe(struct radv_timeline_point, point,
5982 &timeline->points, list) {
5983 list_del(&point->list);
5984 device->ws->destroy_syncobj(device->ws, point->syncobj);
5985 free(point);
5986 }
5987 pthread_mutex_destroy(&timeline->mutex);
5988 }
5989
5990 static void
5991 radv_timeline_gc_locked(struct radv_device *device,
5992 struct radv_timeline *timeline)
5993 {
5994 list_for_each_entry_safe(struct radv_timeline_point, point,
5995 &timeline->points, list) {
5996 if (point->wait_count || point->value > timeline->highest_submitted)
5997 return;
5998
5999 if (device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, 0)) {
6000 timeline->highest_signaled = point->value;
6001 list_del(&point->list);
6002 list_add(&point->list, &timeline->free_points);
6003 }
6004 }
6005 }
6006
6007 static struct radv_timeline_point *
6008 radv_timeline_find_point_at_least_locked(struct radv_device *device,
6009 struct radv_timeline *timeline,
6010 uint64_t p)
6011 {
6012 radv_timeline_gc_locked(device, timeline);
6013
6014 if (p <= timeline->highest_signaled)
6015 return NULL;
6016
6017 list_for_each_entry(struct radv_timeline_point, point,
6018 &timeline->points, list) {
6019 if (point->value >= p) {
6020 ++point->wait_count;
6021 return point;
6022 }
6023 }
6024 return NULL;
6025 }
6026
6027 static struct radv_timeline_point *
6028 radv_timeline_add_point_locked(struct radv_device *device,
6029 struct radv_timeline *timeline,
6030 uint64_t p)
6031 {
6032 radv_timeline_gc_locked(device, timeline);
6033
6034 struct radv_timeline_point *ret = NULL;
6035 struct radv_timeline_point *prev = NULL;
6036
6037 if (p <= timeline->highest_signaled)
6038 return NULL;
6039
6040 list_for_each_entry(struct radv_timeline_point, point,
6041 &timeline->points, list) {
6042 if (point->value == p) {
6043 return NULL;
6044 }
6045
6046 if (point->value < p)
6047 prev = point;
6048 }
6049
6050 if (list_is_empty(&timeline->free_points)) {
6051 ret = malloc(sizeof(struct radv_timeline_point));
6052 device->ws->create_syncobj(device->ws, &ret->syncobj);
6053 } else {
6054 ret = list_first_entry(&timeline->free_points, struct radv_timeline_point, list);
6055 list_del(&ret->list);
6056
6057 device->ws->reset_syncobj(device->ws, ret->syncobj);
6058 }
6059
6060 ret->value = p;
6061 ret->wait_count = 1;
6062
6063 if (prev) {
6064 list_add(&ret->list, &prev->list);
6065 } else {
6066 list_addtail(&ret->list, &timeline->points);
6067 }
6068 return ret;
6069 }
6070
6071
6072 static VkResult
6073 radv_timeline_wait_locked(struct radv_device *device,
6074 struct radv_timeline *timeline,
6075 uint64_t value,
6076 uint64_t abs_timeout)
6077 {
6078 while(timeline->highest_submitted < value) {
6079 struct timespec abstime;
6080 timespec_from_nsec(&abstime, abs_timeout);
6081
6082 pthread_cond_timedwait(&device->timeline_cond, &timeline->mutex, &abstime);
6083
6084 if (radv_get_current_time() >= abs_timeout && timeline->highest_submitted < value)
6085 return VK_TIMEOUT;
6086 }
6087
6088 struct radv_timeline_point *point = radv_timeline_find_point_at_least_locked(device, timeline, value);
6089 if (!point)
6090 return VK_SUCCESS;
6091
6092 pthread_mutex_unlock(&timeline->mutex);
6093
6094 bool success = device->ws->wait_syncobj(device->ws, &point->syncobj, 1, true, abs_timeout);
6095
6096 pthread_mutex_lock(&timeline->mutex);
6097 point->wait_count--;
6098 return success ? VK_SUCCESS : VK_TIMEOUT;
6099 }
6100
6101 static void
6102 radv_timeline_trigger_waiters_locked(struct radv_timeline *timeline,
6103 struct list_head *processing_list)
6104 {
6105 list_for_each_entry_safe(struct radv_timeline_waiter, waiter,
6106 &timeline->waiters, list) {
6107 if (waiter->value > timeline->highest_submitted)
6108 continue;
6109
6110 if (p_atomic_dec_zero(&waiter->submission->submission_wait_count)) {
6111 list_addtail(&waiter->submission->processing_list, processing_list);
6112 }
6113 list_del(&waiter->list);
6114 }
6115 }
6116
6117 static
6118 void radv_destroy_semaphore_part(struct radv_device *device,
6119 struct radv_semaphore_part *part)
6120 {
6121 switch(part->kind) {
6122 case RADV_SEMAPHORE_NONE:
6123 break;
6124 case RADV_SEMAPHORE_WINSYS:
6125 device->ws->destroy_sem(part->ws_sem);
6126 break;
6127 case RADV_SEMAPHORE_TIMELINE:
6128 radv_destroy_timeline(device, &part->timeline);
6129 break;
6130 case RADV_SEMAPHORE_SYNCOBJ:
6131 device->ws->destroy_syncobj(device->ws, part->syncobj);
6132 break;
6133 }
6134 part->kind = RADV_SEMAPHORE_NONE;
6135 }
6136
6137 static VkSemaphoreTypeKHR
6138 radv_get_semaphore_type(const void *pNext, uint64_t *initial_value)
6139 {
6140 const VkSemaphoreTypeCreateInfo *type_info =
6141 vk_find_struct_const(pNext, SEMAPHORE_TYPE_CREATE_INFO);
6142
6143 if (!type_info)
6144 return VK_SEMAPHORE_TYPE_BINARY;
6145
6146 if (initial_value)
6147 *initial_value = type_info->initialValue;
6148 return type_info->semaphoreType;
6149 }
6150
6151 VkResult radv_CreateSemaphore(
6152 VkDevice _device,
6153 const VkSemaphoreCreateInfo* pCreateInfo,
6154 const VkAllocationCallbacks* pAllocator,
6155 VkSemaphore* pSemaphore)
6156 {
6157 RADV_FROM_HANDLE(radv_device, device, _device);
6158 const VkExportSemaphoreCreateInfo *export =
6159 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
6160 VkExternalSemaphoreHandleTypeFlags handleTypes =
6161 export ? export->handleTypes : 0;
6162 uint64_t initial_value = 0;
6163 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pCreateInfo->pNext, &initial_value);
6164
6165 struct radv_semaphore *sem = vk_alloc2(&device->vk.alloc, pAllocator,
6166 sizeof(*sem), 8,
6167 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6168 if (!sem)
6169 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6170
6171 vk_object_base_init(&device->vk, &sem->base,
6172 VK_OBJECT_TYPE_SEMAPHORE);
6173
6174 sem->temporary.kind = RADV_SEMAPHORE_NONE;
6175 sem->permanent.kind = RADV_SEMAPHORE_NONE;
6176
6177 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
6178 radv_create_timeline(&sem->permanent.timeline, initial_value);
6179 sem->permanent.kind = RADV_SEMAPHORE_TIMELINE;
6180 } else if (device->always_use_syncobj || handleTypes) {
6181 assert (device->physical_device->rad_info.has_syncobj);
6182 int ret = device->ws->create_syncobj(device->ws, &sem->permanent.syncobj);
6183 if (ret) {
6184 vk_free2(&device->vk.alloc, pAllocator, sem);
6185 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6186 }
6187 sem->permanent.kind = RADV_SEMAPHORE_SYNCOBJ;
6188 } else {
6189 sem->permanent.ws_sem = device->ws->create_sem(device->ws);
6190 if (!sem->permanent.ws_sem) {
6191 vk_free2(&device->vk.alloc, pAllocator, sem);
6192 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6193 }
6194 sem->permanent.kind = RADV_SEMAPHORE_WINSYS;
6195 }
6196
6197 *pSemaphore = radv_semaphore_to_handle(sem);
6198 return VK_SUCCESS;
6199 }
6200
6201 void radv_DestroySemaphore(
6202 VkDevice _device,
6203 VkSemaphore _semaphore,
6204 const VkAllocationCallbacks* pAllocator)
6205 {
6206 RADV_FROM_HANDLE(radv_device, device, _device);
6207 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
6208 if (!_semaphore)
6209 return;
6210
6211 radv_destroy_semaphore_part(device, &sem->temporary);
6212 radv_destroy_semaphore_part(device, &sem->permanent);
6213 vk_object_base_finish(&sem->base);
6214 vk_free2(&device->vk.alloc, pAllocator, sem);
6215 }
6216
6217 VkResult
6218 radv_GetSemaphoreCounterValue(VkDevice _device,
6219 VkSemaphore _semaphore,
6220 uint64_t* pValue)
6221 {
6222 RADV_FROM_HANDLE(radv_device, device, _device);
6223 RADV_FROM_HANDLE(radv_semaphore, semaphore, _semaphore);
6224
6225 struct radv_semaphore_part *part =
6226 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
6227
6228 switch (part->kind) {
6229 case RADV_SEMAPHORE_TIMELINE: {
6230 pthread_mutex_lock(&part->timeline.mutex);
6231 radv_timeline_gc_locked(device, &part->timeline);
6232 *pValue = part->timeline.highest_signaled;
6233 pthread_mutex_unlock(&part->timeline.mutex);
6234 return VK_SUCCESS;
6235 }
6236 case RADV_SEMAPHORE_NONE:
6237 case RADV_SEMAPHORE_SYNCOBJ:
6238 case RADV_SEMAPHORE_WINSYS:
6239 unreachable("Invalid semaphore type");
6240 }
6241 unreachable("Unhandled semaphore type");
6242 }
6243
6244
6245 static VkResult
6246 radv_wait_timelines(struct radv_device *device,
6247 const VkSemaphoreWaitInfo* pWaitInfo,
6248 uint64_t abs_timeout)
6249 {
6250 if ((pWaitInfo->flags & VK_SEMAPHORE_WAIT_ANY_BIT_KHR) && pWaitInfo->semaphoreCount > 1) {
6251 for (;;) {
6252 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6253 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6254 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
6255 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], 0);
6256 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
6257
6258 if (result == VK_SUCCESS)
6259 return VK_SUCCESS;
6260 }
6261 if (radv_get_current_time() > abs_timeout)
6262 return VK_TIMEOUT;
6263 }
6264 }
6265
6266 for(uint32_t i = 0; i < pWaitInfo->semaphoreCount; ++i) {
6267 RADV_FROM_HANDLE(radv_semaphore, semaphore, pWaitInfo->pSemaphores[i]);
6268 pthread_mutex_lock(&semaphore->permanent.timeline.mutex);
6269 VkResult result = radv_timeline_wait_locked(device, &semaphore->permanent.timeline, pWaitInfo->pValues[i], abs_timeout);
6270 pthread_mutex_unlock(&semaphore->permanent.timeline.mutex);
6271
6272 if (result != VK_SUCCESS)
6273 return result;
6274 }
6275 return VK_SUCCESS;
6276 }
6277 VkResult
6278 radv_WaitSemaphores(VkDevice _device,
6279 const VkSemaphoreWaitInfo* pWaitInfo,
6280 uint64_t timeout)
6281 {
6282 RADV_FROM_HANDLE(radv_device, device, _device);
6283 uint64_t abs_timeout = radv_get_absolute_timeout(timeout);
6284 return radv_wait_timelines(device, pWaitInfo, abs_timeout);
6285 }
6286
6287 VkResult
6288 radv_SignalSemaphore(VkDevice _device,
6289 const VkSemaphoreSignalInfo* pSignalInfo)
6290 {
6291 RADV_FROM_HANDLE(radv_device, device, _device);
6292 RADV_FROM_HANDLE(radv_semaphore, semaphore, pSignalInfo->semaphore);
6293
6294 struct radv_semaphore_part *part =
6295 semaphore->temporary.kind != RADV_SEMAPHORE_NONE ? &semaphore->temporary : &semaphore->permanent;
6296
6297 switch(part->kind) {
6298 case RADV_SEMAPHORE_TIMELINE: {
6299 pthread_mutex_lock(&part->timeline.mutex);
6300 radv_timeline_gc_locked(device, &part->timeline);
6301 part->timeline.highest_submitted = MAX2(part->timeline.highest_submitted, pSignalInfo->value);
6302 part->timeline.highest_signaled = MAX2(part->timeline.highest_signaled, pSignalInfo->value);
6303
6304 struct list_head processing_list;
6305 list_inithead(&processing_list);
6306 radv_timeline_trigger_waiters_locked(&part->timeline, &processing_list);
6307 pthread_mutex_unlock(&part->timeline.mutex);
6308
6309 return radv_process_submissions(&processing_list);
6310 }
6311 case RADV_SEMAPHORE_NONE:
6312 case RADV_SEMAPHORE_SYNCOBJ:
6313 case RADV_SEMAPHORE_WINSYS:
6314 unreachable("Invalid semaphore type");
6315 }
6316 return VK_SUCCESS;
6317 }
6318
6319
6320
6321 VkResult radv_CreateEvent(
6322 VkDevice _device,
6323 const VkEventCreateInfo* pCreateInfo,
6324 const VkAllocationCallbacks* pAllocator,
6325 VkEvent* pEvent)
6326 {
6327 RADV_FROM_HANDLE(radv_device, device, _device);
6328 struct radv_event *event = vk_alloc2(&device->vk.alloc, pAllocator,
6329 sizeof(*event), 8,
6330 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6331
6332 if (!event)
6333 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6334
6335 vk_object_base_init(&device->vk, &event->base, VK_OBJECT_TYPE_EVENT);
6336
6337 event->bo = device->ws->buffer_create(device->ws, 8, 8,
6338 RADEON_DOMAIN_GTT,
6339 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
6340 RADV_BO_PRIORITY_FENCE);
6341 if (!event->bo) {
6342 vk_free2(&device->vk.alloc, pAllocator, event);
6343 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6344 }
6345
6346 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
6347
6348 *pEvent = radv_event_to_handle(event);
6349
6350 return VK_SUCCESS;
6351 }
6352
6353 void radv_DestroyEvent(
6354 VkDevice _device,
6355 VkEvent _event,
6356 const VkAllocationCallbacks* pAllocator)
6357 {
6358 RADV_FROM_HANDLE(radv_device, device, _device);
6359 RADV_FROM_HANDLE(radv_event, event, _event);
6360
6361 if (!event)
6362 return;
6363 device->ws->buffer_destroy(event->bo);
6364 vk_object_base_finish(&event->base);
6365 vk_free2(&device->vk.alloc, pAllocator, event);
6366 }
6367
6368 VkResult radv_GetEventStatus(
6369 VkDevice _device,
6370 VkEvent _event)
6371 {
6372 RADV_FROM_HANDLE(radv_event, event, _event);
6373
6374 if (*event->map == 1)
6375 return VK_EVENT_SET;
6376 return VK_EVENT_RESET;
6377 }
6378
6379 VkResult radv_SetEvent(
6380 VkDevice _device,
6381 VkEvent _event)
6382 {
6383 RADV_FROM_HANDLE(radv_event, event, _event);
6384 *event->map = 1;
6385
6386 return VK_SUCCESS;
6387 }
6388
6389 VkResult radv_ResetEvent(
6390 VkDevice _device,
6391 VkEvent _event)
6392 {
6393 RADV_FROM_HANDLE(radv_event, event, _event);
6394 *event->map = 0;
6395
6396 return VK_SUCCESS;
6397 }
6398
6399 VkResult radv_CreateBuffer(
6400 VkDevice _device,
6401 const VkBufferCreateInfo* pCreateInfo,
6402 const VkAllocationCallbacks* pAllocator,
6403 VkBuffer* pBuffer)
6404 {
6405 RADV_FROM_HANDLE(radv_device, device, _device);
6406 struct radv_buffer *buffer;
6407
6408 if (pCreateInfo->size > RADV_MAX_MEMORY_ALLOCATION_SIZE)
6409 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
6410
6411 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
6412
6413 buffer = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*buffer), 8,
6414 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
6415 if (buffer == NULL)
6416 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
6417
6418 vk_object_base_init(&device->vk, &buffer->base, VK_OBJECT_TYPE_BUFFER);
6419
6420 buffer->size = pCreateInfo->size;
6421 buffer->usage = pCreateInfo->usage;
6422 buffer->bo = NULL;
6423 buffer->offset = 0;
6424 buffer->flags = pCreateInfo->flags;
6425
6426 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
6427 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
6428
6429 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
6430 buffer->bo = device->ws->buffer_create(device->ws,
6431 align64(buffer->size, 4096),
6432 4096, 0, RADEON_FLAG_VIRTUAL,
6433 RADV_BO_PRIORITY_VIRTUAL);
6434 if (!buffer->bo) {
6435 vk_free2(&device->vk.alloc, pAllocator, buffer);
6436 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
6437 }
6438 }
6439
6440 *pBuffer = radv_buffer_to_handle(buffer);
6441
6442 return VK_SUCCESS;
6443 }
6444
6445 void radv_DestroyBuffer(
6446 VkDevice _device,
6447 VkBuffer _buffer,
6448 const VkAllocationCallbacks* pAllocator)
6449 {
6450 RADV_FROM_HANDLE(radv_device, device, _device);
6451 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
6452
6453 if (!buffer)
6454 return;
6455
6456 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
6457 device->ws->buffer_destroy(buffer->bo);
6458
6459 vk_object_base_finish(&buffer->base);
6460 vk_free2(&device->vk.alloc, pAllocator, buffer);
6461 }
6462
6463 VkDeviceAddress radv_GetBufferDeviceAddress(
6464 VkDevice device,
6465 const VkBufferDeviceAddressInfo* pInfo)
6466 {
6467 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
6468 return radv_buffer_get_va(buffer->bo) + buffer->offset;
6469 }
6470
6471
6472 uint64_t radv_GetBufferOpaqueCaptureAddress(VkDevice device,
6473 const VkBufferDeviceAddressInfo* pInfo)
6474 {
6475 return 0;
6476 }
6477
6478 uint64_t radv_GetDeviceMemoryOpaqueCaptureAddress(VkDevice device,
6479 const VkDeviceMemoryOpaqueCaptureAddressInfo* pInfo)
6480 {
6481 return 0;
6482 }
6483
6484 static inline unsigned
6485 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
6486 {
6487 if (stencil)
6488 return plane->surface.u.legacy.stencil_tiling_index[level];
6489 else
6490 return plane->surface.u.legacy.tiling_index[level];
6491 }
6492
6493 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
6494 {
6495 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
6496 }
6497
6498 static uint32_t
6499 radv_init_dcc_control_reg(struct radv_device *device,
6500 struct radv_image_view *iview)
6501 {
6502 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
6503 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
6504 unsigned max_compressed_block_size;
6505 unsigned independent_128b_blocks;
6506 unsigned independent_64b_blocks;
6507
6508 if (!radv_dcc_enabled(iview->image, iview->base_mip))
6509 return 0;
6510
6511 if (!device->physical_device->rad_info.has_dedicated_vram) {
6512 /* amdvlk: [min-compressed-block-size] should be set to 32 for
6513 * dGPU and 64 for APU because all of our APUs to date use
6514 * DIMMs which have a request granularity size of 64B while all
6515 * other chips have a 32B request size.
6516 */
6517 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
6518 }
6519
6520 if (device->physical_device->rad_info.chip_class >= GFX10) {
6521 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6522 independent_64b_blocks = 0;
6523 independent_128b_blocks = 1;
6524 } else {
6525 independent_128b_blocks = 0;
6526
6527 if (iview->image->info.samples > 1) {
6528 if (iview->image->planes[0].surface.bpe == 1)
6529 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6530 else if (iview->image->planes[0].surface.bpe == 2)
6531 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
6532 }
6533
6534 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
6535 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
6536 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
6537 /* If this DCC image is potentially going to be used in texture
6538 * fetches, we need some special settings.
6539 */
6540 independent_64b_blocks = 1;
6541 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
6542 } else {
6543 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
6544 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
6545 * big as possible for better compression state.
6546 */
6547 independent_64b_blocks = 0;
6548 max_compressed_block_size = max_uncompressed_block_size;
6549 }
6550 }
6551
6552 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
6553 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
6554 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
6555 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
6556 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
6557 }
6558
6559 void
6560 radv_initialise_color_surface(struct radv_device *device,
6561 struct radv_color_buffer_info *cb,
6562 struct radv_image_view *iview)
6563 {
6564 const struct vk_format_description *desc;
6565 unsigned ntype, format, swap, endian;
6566 unsigned blend_clamp = 0, blend_bypass = 0;
6567 uint64_t va;
6568 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
6569 const struct radeon_surf *surf = &plane->surface;
6570
6571 desc = vk_format_description(iview->vk_format);
6572
6573 memset(cb, 0, sizeof(*cb));
6574
6575 /* Intensity is implemented as Red, so treat it that way. */
6576 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
6577
6578 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
6579
6580 cb->cb_color_base = va >> 8;
6581
6582 if (device->physical_device->rad_info.chip_class >= GFX9) {
6583 if (device->physical_device->rad_info.chip_class >= GFX10) {
6584 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6585 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6586 S_028EE0_CMASK_PIPE_ALIGNED(1) |
6587 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
6588 } else {
6589 struct gfx9_surf_meta_flags meta = {
6590 .rb_aligned = 1,
6591 .pipe_aligned = 1,
6592 };
6593
6594 if (iview->image->dcc_offset)
6595 meta = surf->u.gfx9.dcc;
6596
6597 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6598 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
6599 S_028C74_RB_ALIGNED(meta.rb_aligned) |
6600 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
6601 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
6602 }
6603
6604 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
6605 cb->cb_color_base |= surf->tile_swizzle;
6606 } else {
6607 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
6608 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
6609
6610 cb->cb_color_base += level_info->offset >> 8;
6611 if (level_info->mode == RADEON_SURF_MODE_2D)
6612 cb->cb_color_base |= surf->tile_swizzle;
6613
6614 pitch_tile_max = level_info->nblk_x / 8 - 1;
6615 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
6616 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
6617
6618 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
6619 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
6620 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
6621
6622 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
6623
6624 if (radv_image_has_fmask(iview->image)) {
6625 if (device->physical_device->rad_info.chip_class >= GFX7)
6626 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
6627 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
6628 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
6629 } else {
6630 /* This must be set for fast clear to work without FMASK. */
6631 if (device->physical_device->rad_info.chip_class >= GFX7)
6632 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
6633 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
6634 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
6635 }
6636 }
6637
6638 /* CMASK variables */
6639 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6640 va += iview->image->cmask_offset;
6641 cb->cb_color_cmask = va >> 8;
6642
6643 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6644 va += iview->image->dcc_offset;
6645
6646 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
6647 device->physical_device->rad_info.chip_class <= GFX8)
6648 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
6649
6650 unsigned dcc_tile_swizzle = surf->tile_swizzle;
6651 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
6652
6653 cb->cb_dcc_base = va >> 8;
6654 cb->cb_dcc_base |= dcc_tile_swizzle;
6655
6656 /* GFX10 field has the same base shift as the GFX6 field. */
6657 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6658 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
6659 S_028C6C_SLICE_MAX_GFX10(max_slice);
6660
6661 if (iview->image->info.samples > 1) {
6662 unsigned log_samples = util_logbase2(iview->image->info.samples);
6663
6664 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
6665 S_028C74_NUM_FRAGMENTS(log_samples);
6666 }
6667
6668 if (radv_image_has_fmask(iview->image)) {
6669 va = radv_buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask_offset;
6670 cb->cb_color_fmask = va >> 8;
6671 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
6672 } else {
6673 cb->cb_color_fmask = cb->cb_color_base;
6674 }
6675
6676 ntype = radv_translate_color_numformat(iview->vk_format,
6677 desc,
6678 vk_format_get_first_non_void_channel(iview->vk_format));
6679 format = radv_translate_colorformat(iview->vk_format);
6680 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
6681 radv_finishme("Illegal color\n");
6682 swap = radv_translate_colorswap(iview->vk_format, false);
6683 endian = radv_colorformat_endian_swap(format);
6684
6685 /* blend clamp should be set for all NORM/SRGB types */
6686 if (ntype == V_028C70_NUMBER_UNORM ||
6687 ntype == V_028C70_NUMBER_SNORM ||
6688 ntype == V_028C70_NUMBER_SRGB)
6689 blend_clamp = 1;
6690
6691 /* set blend bypass according to docs if SINT/UINT or
6692 8/24 COLOR variants */
6693 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
6694 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
6695 format == V_028C70_COLOR_X24_8_32_FLOAT) {
6696 blend_clamp = 0;
6697 blend_bypass = 1;
6698 }
6699 #if 0
6700 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
6701 (format == V_028C70_COLOR_8 ||
6702 format == V_028C70_COLOR_8_8 ||
6703 format == V_028C70_COLOR_8_8_8_8))
6704 ->color_is_int8 = true;
6705 #endif
6706 cb->cb_color_info = S_028C70_FORMAT(format) |
6707 S_028C70_COMP_SWAP(swap) |
6708 S_028C70_BLEND_CLAMP(blend_clamp) |
6709 S_028C70_BLEND_BYPASS(blend_bypass) |
6710 S_028C70_SIMPLE_FLOAT(1) |
6711 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
6712 ntype != V_028C70_NUMBER_SNORM &&
6713 ntype != V_028C70_NUMBER_SRGB &&
6714 format != V_028C70_COLOR_8_24 &&
6715 format != V_028C70_COLOR_24_8) |
6716 S_028C70_NUMBER_TYPE(ntype) |
6717 S_028C70_ENDIAN(endian);
6718 if (radv_image_has_fmask(iview->image)) {
6719 cb->cb_color_info |= S_028C70_COMPRESSION(1);
6720 if (device->physical_device->rad_info.chip_class == GFX6) {
6721 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
6722 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
6723 }
6724
6725 if (radv_image_is_tc_compat_cmask(iview->image)) {
6726 /* Allow the texture block to read FMASK directly
6727 * without decompressing it. This bit must be cleared
6728 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
6729 * otherwise the operation doesn't happen.
6730 */
6731 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
6732
6733 /* Set CMASK into a tiling format that allows the
6734 * texture block to read it.
6735 */
6736 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
6737 }
6738 }
6739
6740 if (radv_image_has_cmask(iview->image) &&
6741 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
6742 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
6743
6744 if (radv_dcc_enabled(iview->image, iview->base_mip))
6745 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
6746
6747 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
6748
6749 /* This must be set for fast clear to work without FMASK. */
6750 if (!radv_image_has_fmask(iview->image) &&
6751 device->physical_device->rad_info.chip_class == GFX6) {
6752 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
6753 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
6754 }
6755
6756 if (device->physical_device->rad_info.chip_class >= GFX9) {
6757 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
6758
6759 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
6760 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
6761 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
6762 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
6763
6764 if (device->physical_device->rad_info.chip_class >= GFX10) {
6765 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
6766
6767 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
6768 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
6769 S_028EE0_RESOURCE_LEVEL(1);
6770 } else {
6771 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
6772 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
6773 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
6774 }
6775
6776 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
6777 S_028C68_MIP0_HEIGHT(height - 1) |
6778 S_028C68_MAX_MIP(iview->image->info.levels - 1);
6779 }
6780 }
6781
6782 static unsigned
6783 radv_calc_decompress_on_z_planes(struct radv_device *device,
6784 struct radv_image_view *iview)
6785 {
6786 unsigned max_zplanes = 0;
6787
6788 assert(radv_image_is_tc_compat_htile(iview->image));
6789
6790 if (device->physical_device->rad_info.chip_class >= GFX9) {
6791 /* Default value for 32-bit depth surfaces. */
6792 max_zplanes = 4;
6793
6794 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
6795 iview->image->info.samples > 1)
6796 max_zplanes = 2;
6797
6798 max_zplanes = max_zplanes + 1;
6799 } else {
6800 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
6801 /* Do not enable Z plane compression for 16-bit depth
6802 * surfaces because isn't supported on GFX8. Only
6803 * 32-bit depth surfaces are supported by the hardware.
6804 * This allows to maintain shader compatibility and to
6805 * reduce the number of depth decompressions.
6806 */
6807 max_zplanes = 1;
6808 } else {
6809 if (iview->image->info.samples <= 1)
6810 max_zplanes = 5;
6811 else if (iview->image->info.samples <= 4)
6812 max_zplanes = 3;
6813 else
6814 max_zplanes = 2;
6815 }
6816 }
6817
6818 return max_zplanes;
6819 }
6820
6821 void
6822 radv_initialise_ds_surface(struct radv_device *device,
6823 struct radv_ds_buffer_info *ds,
6824 struct radv_image_view *iview)
6825 {
6826 unsigned level = iview->base_mip;
6827 unsigned format, stencil_format;
6828 uint64_t va, s_offs, z_offs;
6829 bool stencil_only = false;
6830 const struct radv_image_plane *plane = &iview->image->planes[0];
6831 const struct radeon_surf *surf = &plane->surface;
6832
6833 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
6834
6835 memset(ds, 0, sizeof(*ds));
6836 switch (iview->image->vk_format) {
6837 case VK_FORMAT_D24_UNORM_S8_UINT:
6838 case VK_FORMAT_X8_D24_UNORM_PACK32:
6839 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
6840 ds->offset_scale = 2.0f;
6841 break;
6842 case VK_FORMAT_D16_UNORM:
6843 case VK_FORMAT_D16_UNORM_S8_UINT:
6844 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
6845 ds->offset_scale = 4.0f;
6846 break;
6847 case VK_FORMAT_D32_SFLOAT:
6848 case VK_FORMAT_D32_SFLOAT_S8_UINT:
6849 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
6850 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
6851 ds->offset_scale = 1.0f;
6852 break;
6853 case VK_FORMAT_S8_UINT:
6854 stencil_only = true;
6855 break;
6856 default:
6857 break;
6858 }
6859
6860 format = radv_translate_dbformat(iview->image->vk_format);
6861 stencil_format = surf->has_stencil ?
6862 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
6863
6864 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
6865 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
6866 S_028008_SLICE_MAX(max_slice);
6867 if (device->physical_device->rad_info.chip_class >= GFX10) {
6868 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
6869 S_028008_SLICE_MAX_HI(max_slice >> 11);
6870 }
6871
6872 ds->db_htile_data_base = 0;
6873 ds->db_htile_surface = 0;
6874
6875 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
6876 s_offs = z_offs = va;
6877
6878 if (device->physical_device->rad_info.chip_class >= GFX9) {
6879 assert(surf->u.gfx9.surf_offset == 0);
6880 s_offs += surf->u.gfx9.stencil_offset;
6881
6882 ds->db_z_info = S_028038_FORMAT(format) |
6883 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
6884 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
6885 S_028038_MAXMIP(iview->image->info.levels - 1) |
6886 S_028038_ZRANGE_PRECISION(1);
6887 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
6888 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
6889
6890 if (device->physical_device->rad_info.chip_class == GFX9) {
6891 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
6892 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
6893 }
6894
6895 ds->db_depth_view |= S_028008_MIPID(level);
6896 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
6897 S_02801C_Y_MAX(iview->image->info.height - 1);
6898
6899 if (radv_htile_enabled(iview->image, level)) {
6900 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
6901
6902 if (radv_image_is_tc_compat_htile(iview->image)) {
6903 unsigned max_zplanes =
6904 radv_calc_decompress_on_z_planes(device, iview);
6905
6906 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6907
6908 if (device->physical_device->rad_info.chip_class >= GFX10) {
6909 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
6910 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
6911 } else {
6912 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
6913 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
6914 }
6915 }
6916
6917 if (!surf->has_stencil)
6918 /* Use all of the htile_buffer for depth if there's no stencil. */
6919 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
6920 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6921 iview->image->htile_offset;
6922 ds->db_htile_data_base = va >> 8;
6923 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
6924 S_028ABC_PIPE_ALIGNED(1);
6925
6926 if (device->physical_device->rad_info.chip_class == GFX9) {
6927 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(1);
6928 }
6929 }
6930 } else {
6931 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
6932
6933 if (stencil_only)
6934 level_info = &surf->u.legacy.stencil_level[level];
6935
6936 z_offs += surf->u.legacy.level[level].offset;
6937 s_offs += surf->u.legacy.stencil_level[level].offset;
6938
6939 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
6940 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
6941 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
6942
6943 if (iview->image->info.samples > 1)
6944 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
6945
6946 if (device->physical_device->rad_info.chip_class >= GFX7) {
6947 struct radeon_info *info = &device->physical_device->rad_info;
6948 unsigned tiling_index = surf->u.legacy.tiling_index[level];
6949 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
6950 unsigned macro_index = surf->u.legacy.macro_tile_index;
6951 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
6952 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
6953 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
6954
6955 if (stencil_only)
6956 tile_mode = stencil_tile_mode;
6957
6958 ds->db_depth_info |=
6959 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
6960 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
6961 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
6962 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
6963 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
6964 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
6965 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
6966 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
6967 } else {
6968 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
6969 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
6970 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
6971 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
6972 if (stencil_only)
6973 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
6974 }
6975
6976 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
6977 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
6978 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
6979
6980 if (radv_htile_enabled(iview->image, level)) {
6981 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
6982
6983 if (!surf->has_stencil &&
6984 !radv_image_is_tc_compat_htile(iview->image))
6985 /* Use all of the htile_buffer for depth if there's no stencil. */
6986 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
6987
6988 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
6989 iview->image->htile_offset;
6990 ds->db_htile_data_base = va >> 8;
6991 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
6992
6993 if (radv_image_is_tc_compat_htile(iview->image)) {
6994 unsigned max_zplanes =
6995 radv_calc_decompress_on_z_planes(device, iview);
6996
6997 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
6998 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
6999 }
7000 }
7001 }
7002
7003 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
7004 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
7005 }
7006
7007 VkResult radv_CreateFramebuffer(
7008 VkDevice _device,
7009 const VkFramebufferCreateInfo* pCreateInfo,
7010 const VkAllocationCallbacks* pAllocator,
7011 VkFramebuffer* pFramebuffer)
7012 {
7013 RADV_FROM_HANDLE(radv_device, device, _device);
7014 struct radv_framebuffer *framebuffer;
7015 const VkFramebufferAttachmentsCreateInfo *imageless_create_info =
7016 vk_find_struct_const(pCreateInfo->pNext,
7017 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO);
7018
7019 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
7020
7021 size_t size = sizeof(*framebuffer);
7022 if (!imageless_create_info)
7023 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
7024 framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
7025 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
7026 if (framebuffer == NULL)
7027 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7028
7029 vk_object_base_init(&device->vk, &framebuffer->base,
7030 VK_OBJECT_TYPE_FRAMEBUFFER);
7031
7032 framebuffer->attachment_count = pCreateInfo->attachmentCount;
7033 framebuffer->width = pCreateInfo->width;
7034 framebuffer->height = pCreateInfo->height;
7035 framebuffer->layers = pCreateInfo->layers;
7036 if (imageless_create_info) {
7037 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
7038 const VkFramebufferAttachmentImageInfo *attachment =
7039 imageless_create_info->pAttachmentImageInfos + i;
7040 framebuffer->width = MIN2(framebuffer->width, attachment->width);
7041 framebuffer->height = MIN2(framebuffer->height, attachment->height);
7042 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
7043 }
7044 } else {
7045 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
7046 VkImageView _iview = pCreateInfo->pAttachments[i];
7047 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
7048 framebuffer->attachments[i] = iview;
7049 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
7050 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
7051 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
7052 }
7053 }
7054
7055 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
7056 return VK_SUCCESS;
7057 }
7058
7059 void radv_DestroyFramebuffer(
7060 VkDevice _device,
7061 VkFramebuffer _fb,
7062 const VkAllocationCallbacks* pAllocator)
7063 {
7064 RADV_FROM_HANDLE(radv_device, device, _device);
7065 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
7066
7067 if (!fb)
7068 return;
7069 vk_object_base_finish(&fb->base);
7070 vk_free2(&device->vk.alloc, pAllocator, fb);
7071 }
7072
7073 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
7074 {
7075 switch (address_mode) {
7076 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
7077 return V_008F30_SQ_TEX_WRAP;
7078 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
7079 return V_008F30_SQ_TEX_MIRROR;
7080 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
7081 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
7082 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
7083 return V_008F30_SQ_TEX_CLAMP_BORDER;
7084 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
7085 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
7086 default:
7087 unreachable("illegal tex wrap mode");
7088 break;
7089 }
7090 }
7091
7092 static unsigned
7093 radv_tex_compare(VkCompareOp op)
7094 {
7095 switch (op) {
7096 case VK_COMPARE_OP_NEVER:
7097 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
7098 case VK_COMPARE_OP_LESS:
7099 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
7100 case VK_COMPARE_OP_EQUAL:
7101 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
7102 case VK_COMPARE_OP_LESS_OR_EQUAL:
7103 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
7104 case VK_COMPARE_OP_GREATER:
7105 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
7106 case VK_COMPARE_OP_NOT_EQUAL:
7107 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
7108 case VK_COMPARE_OP_GREATER_OR_EQUAL:
7109 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
7110 case VK_COMPARE_OP_ALWAYS:
7111 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
7112 default:
7113 unreachable("illegal compare mode");
7114 break;
7115 }
7116 }
7117
7118 static unsigned
7119 radv_tex_filter(VkFilter filter, unsigned max_ansio)
7120 {
7121 switch (filter) {
7122 case VK_FILTER_NEAREST:
7123 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
7124 V_008F38_SQ_TEX_XY_FILTER_POINT);
7125 case VK_FILTER_LINEAR:
7126 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
7127 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
7128 case VK_FILTER_CUBIC_IMG:
7129 default:
7130 fprintf(stderr, "illegal texture filter");
7131 return 0;
7132 }
7133 }
7134
7135 static unsigned
7136 radv_tex_mipfilter(VkSamplerMipmapMode mode)
7137 {
7138 switch (mode) {
7139 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
7140 return V_008F38_SQ_TEX_Z_FILTER_POINT;
7141 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
7142 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
7143 default:
7144 return V_008F38_SQ_TEX_Z_FILTER_NONE;
7145 }
7146 }
7147
7148 static unsigned
7149 radv_tex_bordercolor(VkBorderColor bcolor)
7150 {
7151 switch (bcolor) {
7152 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
7153 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
7154 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
7155 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
7156 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
7157 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
7158 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
7159 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
7160 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
7161 case VK_BORDER_COLOR_FLOAT_CUSTOM_EXT:
7162 case VK_BORDER_COLOR_INT_CUSTOM_EXT:
7163 return V_008F3C_SQ_TEX_BORDER_COLOR_REGISTER;
7164 default:
7165 break;
7166 }
7167 return 0;
7168 }
7169
7170 static unsigned
7171 radv_tex_aniso_filter(unsigned filter)
7172 {
7173 if (filter < 2)
7174 return 0;
7175 if (filter < 4)
7176 return 1;
7177 if (filter < 8)
7178 return 2;
7179 if (filter < 16)
7180 return 3;
7181 return 4;
7182 }
7183
7184 static unsigned
7185 radv_tex_filter_mode(VkSamplerReductionMode mode)
7186 {
7187 switch (mode) {
7188 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
7189 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
7190 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
7191 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
7192 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
7193 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
7194 default:
7195 break;
7196 }
7197 return 0;
7198 }
7199
7200 static uint32_t
7201 radv_get_max_anisotropy(struct radv_device *device,
7202 const VkSamplerCreateInfo *pCreateInfo)
7203 {
7204 if (device->force_aniso >= 0)
7205 return device->force_aniso;
7206
7207 if (pCreateInfo->anisotropyEnable &&
7208 pCreateInfo->maxAnisotropy > 1.0f)
7209 return (uint32_t)pCreateInfo->maxAnisotropy;
7210
7211 return 0;
7212 }
7213
7214 static inline int S_FIXED(float value, unsigned frac_bits)
7215 {
7216 return value * (1 << frac_bits);
7217 }
7218
7219 static uint32_t radv_register_border_color(struct radv_device *device,
7220 VkClearColorValue value)
7221 {
7222 uint32_t slot;
7223
7224 pthread_mutex_lock(&device->border_color_data.mutex);
7225
7226 for (slot = 0; slot < RADV_BORDER_COLOR_COUNT; slot++) {
7227 if (!device->border_color_data.used[slot]) {
7228 /* Copy to the GPU wrt endian-ness. */
7229 util_memcpy_cpu_to_le32(&device->border_color_data.colors_gpu_ptr[slot],
7230 &value,
7231 sizeof(VkClearColorValue));
7232
7233 device->border_color_data.used[slot] = true;
7234 break;
7235 }
7236 }
7237
7238 pthread_mutex_unlock(&device->border_color_data.mutex);
7239
7240 return slot;
7241 }
7242
7243 static void radv_unregister_border_color(struct radv_device *device,
7244 uint32_t slot)
7245 {
7246 pthread_mutex_lock(&device->border_color_data.mutex);
7247
7248 device->border_color_data.used[slot] = false;
7249
7250 pthread_mutex_unlock(&device->border_color_data.mutex);
7251 }
7252
7253 static void
7254 radv_init_sampler(struct radv_device *device,
7255 struct radv_sampler *sampler,
7256 const VkSamplerCreateInfo *pCreateInfo)
7257 {
7258 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
7259 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
7260 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
7261 device->physical_device->rad_info.chip_class == GFX9;
7262 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
7263 unsigned depth_compare_func = V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
7264 bool trunc_coord = pCreateInfo->minFilter == VK_FILTER_NEAREST && pCreateInfo->magFilter == VK_FILTER_NEAREST;
7265 bool uses_border_color = pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
7266 pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER ||
7267 pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
7268 VkBorderColor border_color = uses_border_color ? pCreateInfo->borderColor : VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
7269 uint32_t border_color_ptr;
7270
7271 const struct VkSamplerReductionModeCreateInfo *sampler_reduction =
7272 vk_find_struct_const(pCreateInfo->pNext,
7273 SAMPLER_REDUCTION_MODE_CREATE_INFO);
7274 if (sampler_reduction)
7275 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
7276
7277 if (pCreateInfo->compareEnable)
7278 depth_compare_func = radv_tex_compare(pCreateInfo->compareOp);
7279
7280 sampler->border_color_slot = RADV_BORDER_COLOR_COUNT;
7281
7282 if (border_color == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT || border_color == VK_BORDER_COLOR_INT_CUSTOM_EXT) {
7283 const VkSamplerCustomBorderColorCreateInfoEXT *custom_border_color =
7284 vk_find_struct_const(pCreateInfo->pNext,
7285 SAMPLER_CUSTOM_BORDER_COLOR_CREATE_INFO_EXT);
7286
7287 assert(custom_border_color);
7288
7289 sampler->border_color_slot =
7290 radv_register_border_color(device, custom_border_color->customBorderColor);
7291
7292 /* Did we fail to find a slot? */
7293 if (sampler->border_color_slot == RADV_BORDER_COLOR_COUNT) {
7294 fprintf(stderr, "WARNING: no free border color slots, defaulting to TRANS_BLACK.\n");
7295 border_color = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
7296 }
7297 }
7298
7299 /* If we don't have a custom color, set the ptr to 0 */
7300 border_color_ptr = sampler->border_color_slot != RADV_BORDER_COLOR_COUNT
7301 ? sampler->border_color_slot
7302 : 0;
7303
7304 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
7305 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
7306 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
7307 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
7308 S_008F30_DEPTH_COMPARE_FUNC(depth_compare_func) |
7309 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
7310 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
7311 S_008F30_ANISO_BIAS(max_aniso_ratio) |
7312 S_008F30_DISABLE_CUBE_WRAP(0) |
7313 S_008F30_COMPAT_MODE(compat_mode) |
7314 S_008F30_FILTER_MODE(filter_mode) |
7315 S_008F30_TRUNC_COORD(trunc_coord));
7316 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
7317 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
7318 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
7319 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
7320 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
7321 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
7322 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
7323 S_008F38_MIP_POINT_PRECLAMP(0));
7324 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(border_color_ptr) |
7325 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(border_color)));
7326
7327 if (device->physical_device->rad_info.chip_class >= GFX10) {
7328 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
7329 } else {
7330 sampler->state[2] |=
7331 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
7332 S_008F38_FILTER_PREC_FIX(1) |
7333 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
7334 }
7335 }
7336
7337 VkResult radv_CreateSampler(
7338 VkDevice _device,
7339 const VkSamplerCreateInfo* pCreateInfo,
7340 const VkAllocationCallbacks* pAllocator,
7341 VkSampler* pSampler)
7342 {
7343 RADV_FROM_HANDLE(radv_device, device, _device);
7344 struct radv_sampler *sampler;
7345
7346 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
7347 vk_find_struct_const(pCreateInfo->pNext,
7348 SAMPLER_YCBCR_CONVERSION_INFO);
7349
7350 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
7351
7352 sampler = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*sampler), 8,
7353 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
7354 if (!sampler)
7355 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
7356
7357 vk_object_base_init(&device->vk, &sampler->base,
7358 VK_OBJECT_TYPE_SAMPLER);
7359
7360 radv_init_sampler(device, sampler, pCreateInfo);
7361
7362 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
7363 *pSampler = radv_sampler_to_handle(sampler);
7364
7365 return VK_SUCCESS;
7366 }
7367
7368 void radv_DestroySampler(
7369 VkDevice _device,
7370 VkSampler _sampler,
7371 const VkAllocationCallbacks* pAllocator)
7372 {
7373 RADV_FROM_HANDLE(radv_device, device, _device);
7374 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
7375
7376 if (!sampler)
7377 return;
7378
7379 if (sampler->border_color_slot != RADV_BORDER_COLOR_COUNT)
7380 radv_unregister_border_color(device, sampler->border_color_slot);
7381
7382 vk_object_base_finish(&sampler->base);
7383 vk_free2(&device->vk.alloc, pAllocator, sampler);
7384 }
7385
7386 /* vk_icd.h does not declare this function, so we declare it here to
7387 * suppress Wmissing-prototypes.
7388 */
7389 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
7390 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
7391
7392 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
7393 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
7394 {
7395 /* For the full details on loader interface versioning, see
7396 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
7397 * What follows is a condensed summary, to help you navigate the large and
7398 * confusing official doc.
7399 *
7400 * - Loader interface v0 is incompatible with later versions. We don't
7401 * support it.
7402 *
7403 * - In loader interface v1:
7404 * - The first ICD entrypoint called by the loader is
7405 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
7406 * entrypoint.
7407 * - The ICD must statically expose no other Vulkan symbol unless it is
7408 * linked with -Bsymbolic.
7409 * - Each dispatchable Vulkan handle created by the ICD must be
7410 * a pointer to a struct whose first member is VK_LOADER_DATA. The
7411 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
7412 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
7413 * vkDestroySurfaceKHR(). The ICD must be capable of working with
7414 * such loader-managed surfaces.
7415 *
7416 * - Loader interface v2 differs from v1 in:
7417 * - The first ICD entrypoint called by the loader is
7418 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
7419 * statically expose this entrypoint.
7420 *
7421 * - Loader interface v3 differs from v2 in:
7422 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
7423 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
7424 * because the loader no longer does so.
7425 */
7426 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
7427 return VK_SUCCESS;
7428 }
7429
7430 VkResult radv_GetMemoryFdKHR(VkDevice _device,
7431 const VkMemoryGetFdInfoKHR *pGetFdInfo,
7432 int *pFD)
7433 {
7434 RADV_FROM_HANDLE(radv_device, device, _device);
7435 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
7436
7437 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
7438
7439 /* At the moment, we support only the below handle types. */
7440 assert(pGetFdInfo->handleType ==
7441 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
7442 pGetFdInfo->handleType ==
7443 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
7444
7445 bool ret = radv_get_memory_fd(device, memory, pFD);
7446 if (ret == false)
7447 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
7448 return VK_SUCCESS;
7449 }
7450
7451 static uint32_t radv_compute_valid_memory_types_attempt(struct radv_physical_device *dev,
7452 enum radeon_bo_domain domains,
7453 enum radeon_bo_flag flags,
7454 enum radeon_bo_flag ignore_flags)
7455 {
7456 /* Don't count GTT/CPU as relevant:
7457 *
7458 * - We're not fully consistent between the two.
7459 * - Sometimes VRAM gets VRAM|GTT.
7460 */
7461 const enum radeon_bo_domain relevant_domains = RADEON_DOMAIN_VRAM |
7462 RADEON_DOMAIN_GDS |
7463 RADEON_DOMAIN_OA;
7464 uint32_t bits = 0;
7465 for (unsigned i = 0; i < dev->memory_properties.memoryTypeCount; ++i) {
7466 if ((domains & relevant_domains) != (dev->memory_domains[i] & relevant_domains))
7467 continue;
7468
7469 if ((flags & ~ignore_flags) != (dev->memory_flags[i] & ~ignore_flags))
7470 continue;
7471
7472 bits |= 1u << i;
7473 }
7474
7475 return bits;
7476 }
7477
7478 static uint32_t radv_compute_valid_memory_types(struct radv_physical_device *dev,
7479 enum radeon_bo_domain domains,
7480 enum radeon_bo_flag flags)
7481 {
7482 enum radeon_bo_flag ignore_flags = ~(RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_GTT_WC);
7483 uint32_t bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
7484
7485 if (!bits) {
7486 ignore_flags |= RADEON_FLAG_NO_CPU_ACCESS;
7487 bits = radv_compute_valid_memory_types_attempt(dev, domains, flags, ignore_flags);
7488 }
7489
7490 return bits;
7491 }
7492 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
7493 VkExternalMemoryHandleTypeFlagBits handleType,
7494 int fd,
7495 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
7496 {
7497 RADV_FROM_HANDLE(radv_device, device, _device);
7498
7499 switch (handleType) {
7500 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT: {
7501 enum radeon_bo_domain domains;
7502 enum radeon_bo_flag flags;
7503 if (!device->ws->buffer_get_flags_from_fd(device->ws, fd, &domains, &flags))
7504 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7505
7506 pMemoryFdProperties->memoryTypeBits = radv_compute_valid_memory_types(device->physical_device, domains, flags);
7507 return VK_SUCCESS;
7508 }
7509 default:
7510 /* The valid usage section for this function says:
7511 *
7512 * "handleType must not be one of the handle types defined as
7513 * opaque."
7514 *
7515 * So opaque handle types fall into the default "unsupported" case.
7516 */
7517 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7518 }
7519 }
7520
7521 static VkResult radv_import_opaque_fd(struct radv_device *device,
7522 int fd,
7523 uint32_t *syncobj)
7524 {
7525 uint32_t syncobj_handle = 0;
7526 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
7527 if (ret != 0)
7528 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7529
7530 if (*syncobj)
7531 device->ws->destroy_syncobj(device->ws, *syncobj);
7532
7533 *syncobj = syncobj_handle;
7534 close(fd);
7535
7536 return VK_SUCCESS;
7537 }
7538
7539 static VkResult radv_import_sync_fd(struct radv_device *device,
7540 int fd,
7541 uint32_t *syncobj)
7542 {
7543 /* If we create a syncobj we do it locally so that if we have an error, we don't
7544 * leave a syncobj in an undetermined state in the fence. */
7545 uint32_t syncobj_handle = *syncobj;
7546 if (!syncobj_handle) {
7547 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
7548 if (ret) {
7549 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7550 }
7551 }
7552
7553 if (fd == -1) {
7554 device->ws->signal_syncobj(device->ws, syncobj_handle);
7555 } else {
7556 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
7557 if (ret != 0)
7558 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7559 }
7560
7561 *syncobj = syncobj_handle;
7562 if (fd != -1)
7563 close(fd);
7564
7565 return VK_SUCCESS;
7566 }
7567
7568 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
7569 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
7570 {
7571 RADV_FROM_HANDLE(radv_device, device, _device);
7572 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
7573 VkResult result;
7574 struct radv_semaphore_part *dst = NULL;
7575
7576 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
7577 dst = &sem->temporary;
7578 } else {
7579 dst = &sem->permanent;
7580 }
7581
7582 uint32_t syncobj = dst->kind == RADV_SEMAPHORE_SYNCOBJ ? dst->syncobj : 0;
7583
7584 switch(pImportSemaphoreFdInfo->handleType) {
7585 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7586 result = radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7587 break;
7588 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7589 result = radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, &syncobj);
7590 break;
7591 default:
7592 unreachable("Unhandled semaphore handle type");
7593 }
7594
7595 if (result == VK_SUCCESS) {
7596 dst->syncobj = syncobj;
7597 dst->kind = RADV_SEMAPHORE_SYNCOBJ;
7598 }
7599
7600 return result;
7601 }
7602
7603 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
7604 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
7605 int *pFd)
7606 {
7607 RADV_FROM_HANDLE(radv_device, device, _device);
7608 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
7609 int ret;
7610 uint32_t syncobj_handle;
7611
7612 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7613 assert(sem->temporary.kind == RADV_SEMAPHORE_SYNCOBJ);
7614 syncobj_handle = sem->temporary.syncobj;
7615 } else {
7616 assert(sem->permanent.kind == RADV_SEMAPHORE_SYNCOBJ);
7617 syncobj_handle = sem->permanent.syncobj;
7618 }
7619
7620 switch(pGetFdInfo->handleType) {
7621 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
7622 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7623 break;
7624 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
7625 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7626 if (!ret) {
7627 if (sem->temporary.kind != RADV_SEMAPHORE_NONE) {
7628 radv_destroy_semaphore_part(device, &sem->temporary);
7629 } else {
7630 device->ws->reset_syncobj(device->ws, syncobj_handle);
7631 }
7632 }
7633 break;
7634 default:
7635 unreachable("Unhandled semaphore handle type");
7636 }
7637
7638 if (ret)
7639 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7640 return VK_SUCCESS;
7641 }
7642
7643 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
7644 VkPhysicalDevice physicalDevice,
7645 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
7646 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
7647 {
7648 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7649 VkSemaphoreTypeKHR type = radv_get_semaphore_type(pExternalSemaphoreInfo->pNext, NULL);
7650
7651 if (type == VK_SEMAPHORE_TYPE_TIMELINE) {
7652 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7653 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7654 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7655
7656 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
7657 } else if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7658 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7659 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
7660 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7661 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
7662 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7663 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7664 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
7665 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7666 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
7667 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
7668 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7669 } else {
7670 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
7671 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
7672 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
7673 }
7674 }
7675
7676 VkResult radv_ImportFenceFdKHR(VkDevice _device,
7677 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
7678 {
7679 RADV_FROM_HANDLE(radv_device, device, _device);
7680 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
7681 uint32_t *syncobj_dst = NULL;
7682
7683
7684 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
7685 syncobj_dst = &fence->temp_syncobj;
7686 } else {
7687 syncobj_dst = &fence->syncobj;
7688 }
7689
7690 switch(pImportFenceFdInfo->handleType) {
7691 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7692 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7693 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7694 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
7695 default:
7696 unreachable("Unhandled fence handle type");
7697 }
7698 }
7699
7700 VkResult radv_GetFenceFdKHR(VkDevice _device,
7701 const VkFenceGetFdInfoKHR *pGetFdInfo,
7702 int *pFd)
7703 {
7704 RADV_FROM_HANDLE(radv_device, device, _device);
7705 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
7706 int ret;
7707 uint32_t syncobj_handle;
7708
7709 if (fence->temp_syncobj)
7710 syncobj_handle = fence->temp_syncobj;
7711 else
7712 syncobj_handle = fence->syncobj;
7713
7714 switch(pGetFdInfo->handleType) {
7715 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
7716 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
7717 break;
7718 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
7719 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
7720 if (!ret) {
7721 if (fence->temp_syncobj) {
7722 close (fence->temp_syncobj);
7723 fence->temp_syncobj = 0;
7724 } else {
7725 device->ws->reset_syncobj(device->ws, syncobj_handle);
7726 }
7727 }
7728 break;
7729 default:
7730 unreachable("Unhandled fence handle type");
7731 }
7732
7733 if (ret)
7734 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
7735 return VK_SUCCESS;
7736 }
7737
7738 void radv_GetPhysicalDeviceExternalFenceProperties(
7739 VkPhysicalDevice physicalDevice,
7740 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
7741 VkExternalFenceProperties *pExternalFenceProperties)
7742 {
7743 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
7744
7745 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
7746 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
7747 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
7748 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7749 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
7750 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
7751 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
7752 } else {
7753 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
7754 pExternalFenceProperties->compatibleHandleTypes = 0;
7755 pExternalFenceProperties->externalFenceFeatures = 0;
7756 }
7757 }
7758
7759 VkResult
7760 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
7761 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
7762 const VkAllocationCallbacks* pAllocator,
7763 VkDebugReportCallbackEXT* pCallback)
7764 {
7765 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7766 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
7767 pCreateInfo, pAllocator, &instance->alloc,
7768 pCallback);
7769 }
7770
7771 void
7772 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
7773 VkDebugReportCallbackEXT _callback,
7774 const VkAllocationCallbacks* pAllocator)
7775 {
7776 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7777 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
7778 _callback, pAllocator, &instance->alloc);
7779 }
7780
7781 void
7782 radv_DebugReportMessageEXT(VkInstance _instance,
7783 VkDebugReportFlagsEXT flags,
7784 VkDebugReportObjectTypeEXT objectType,
7785 uint64_t object,
7786 size_t location,
7787 int32_t messageCode,
7788 const char* pLayerPrefix,
7789 const char* pMessage)
7790 {
7791 RADV_FROM_HANDLE(radv_instance, instance, _instance);
7792 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
7793 object, location, messageCode, pLayerPrefix, pMessage);
7794 }
7795
7796 void
7797 radv_GetDeviceGroupPeerMemoryFeatures(
7798 VkDevice device,
7799 uint32_t heapIndex,
7800 uint32_t localDeviceIndex,
7801 uint32_t remoteDeviceIndex,
7802 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
7803 {
7804 assert(localDeviceIndex == remoteDeviceIndex);
7805
7806 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
7807 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
7808 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
7809 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
7810 }
7811
7812 static const VkTimeDomainEXT radv_time_domains[] = {
7813 VK_TIME_DOMAIN_DEVICE_EXT,
7814 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
7815 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
7816 };
7817
7818 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
7819 VkPhysicalDevice physicalDevice,
7820 uint32_t *pTimeDomainCount,
7821 VkTimeDomainEXT *pTimeDomains)
7822 {
7823 int d;
7824 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
7825
7826 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
7827 vk_outarray_append(&out, i) {
7828 *i = radv_time_domains[d];
7829 }
7830 }
7831
7832 return vk_outarray_status(&out);
7833 }
7834
7835 static uint64_t
7836 radv_clock_gettime(clockid_t clock_id)
7837 {
7838 struct timespec current;
7839 int ret;
7840
7841 ret = clock_gettime(clock_id, &current);
7842 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
7843 ret = clock_gettime(CLOCK_MONOTONIC, &current);
7844 if (ret < 0)
7845 return 0;
7846
7847 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
7848 }
7849
7850 VkResult radv_GetCalibratedTimestampsEXT(
7851 VkDevice _device,
7852 uint32_t timestampCount,
7853 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
7854 uint64_t *pTimestamps,
7855 uint64_t *pMaxDeviation)
7856 {
7857 RADV_FROM_HANDLE(radv_device, device, _device);
7858 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
7859 int d;
7860 uint64_t begin, end;
7861 uint64_t max_clock_period = 0;
7862
7863 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7864
7865 for (d = 0; d < timestampCount; d++) {
7866 switch (pTimestampInfos[d].timeDomain) {
7867 case VK_TIME_DOMAIN_DEVICE_EXT:
7868 pTimestamps[d] = device->ws->query_value(device->ws,
7869 RADEON_TIMESTAMP);
7870 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
7871 max_clock_period = MAX2(max_clock_period, device_period);
7872 break;
7873 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
7874 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
7875 max_clock_period = MAX2(max_clock_period, 1);
7876 break;
7877
7878 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
7879 pTimestamps[d] = begin;
7880 break;
7881 default:
7882 pTimestamps[d] = 0;
7883 break;
7884 }
7885 }
7886
7887 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
7888
7889 /*
7890 * The maximum deviation is the sum of the interval over which we
7891 * perform the sampling and the maximum period of any sampled
7892 * clock. That's because the maximum skew between any two sampled
7893 * clock edges is when the sampled clock with the largest period is
7894 * sampled at the end of that period but right at the beginning of the
7895 * sampling interval and some other clock is sampled right at the
7896 * begining of its sampling period and right at the end of the
7897 * sampling interval. Let's assume the GPU has the longest clock
7898 * period and that the application is sampling GPU and monotonic:
7899 *
7900 * s e
7901 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
7902 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7903 *
7904 * g
7905 * 0 1 2 3
7906 * GPU -----_____-----_____-----_____-----_____
7907 *
7908 * m
7909 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
7910 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
7911 *
7912 * Interval <----------------->
7913 * Deviation <-------------------------->
7914 *
7915 * s = read(raw) 2
7916 * g = read(GPU) 1
7917 * m = read(monotonic) 2
7918 * e = read(raw) b
7919 *
7920 * We round the sample interval up by one tick to cover sampling error
7921 * in the interval clock
7922 */
7923
7924 uint64_t sample_interval = end - begin + 1;
7925
7926 *pMaxDeviation = sample_interval + max_clock_period;
7927
7928 return VK_SUCCESS;
7929 }
7930
7931 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
7932 VkPhysicalDevice physicalDevice,
7933 VkSampleCountFlagBits samples,
7934 VkMultisamplePropertiesEXT* pMultisampleProperties)
7935 {
7936 if (samples & (VK_SAMPLE_COUNT_2_BIT |
7937 VK_SAMPLE_COUNT_4_BIT |
7938 VK_SAMPLE_COUNT_8_BIT)) {
7939 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
7940 } else {
7941 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
7942 }
7943 }
7944
7945 VkResult radv_CreatePrivateDataSlotEXT(
7946 VkDevice _device,
7947 const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
7948 const VkAllocationCallbacks* pAllocator,
7949 VkPrivateDataSlotEXT* pPrivateDataSlot)
7950 {
7951 RADV_FROM_HANDLE(radv_device, device, _device);
7952 return vk_private_data_slot_create(&device->vk, pCreateInfo, pAllocator,
7953 pPrivateDataSlot);
7954 }
7955
7956 void radv_DestroyPrivateDataSlotEXT(
7957 VkDevice _device,
7958 VkPrivateDataSlotEXT privateDataSlot,
7959 const VkAllocationCallbacks* pAllocator)
7960 {
7961 RADV_FROM_HANDLE(radv_device, device, _device);
7962 vk_private_data_slot_destroy(&device->vk, privateDataSlot, pAllocator);
7963 }
7964
7965 VkResult radv_SetPrivateDataEXT(
7966 VkDevice _device,
7967 VkObjectType objectType,
7968 uint64_t objectHandle,
7969 VkPrivateDataSlotEXT privateDataSlot,
7970 uint64_t data)
7971 {
7972 RADV_FROM_HANDLE(radv_device, device, _device);
7973 return vk_object_base_set_private_data(&device->vk, objectType,
7974 objectHandle, privateDataSlot,
7975 data);
7976 }
7977
7978 void radv_GetPrivateDataEXT(
7979 VkDevice _device,
7980 VkObjectType objectType,
7981 uint64_t objectHandle,
7982 VkPrivateDataSlotEXT privateDataSlot,
7983 uint64_t* pData)
7984 {
7985 RADV_FROM_HANDLE(radv_device, device, _device);
7986 vk_object_base_get_private_data(&device->vk, objectType, objectHandle,
7987 privateDataSlot, pData);
7988 }