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