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