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