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