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