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