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