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