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