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