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