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