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