53751e9e242598d6acb797bd558f9136c6240940
[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 ||
326 device->rad_info.chip_class > GFX9) && device->use_aco) {
327 fprintf(stderr, "WARNING: disabling ACO on unsupported GPUs.\n");
328 device->use_aco = false;
329 }
330
331 snprintf(device->name, sizeof(device->name),
332 "AMD RADV%s %s (LLVM " MESA_LLVM_VERSION_STRING ")", device->use_aco ? "/ACO" : "",
333 device->rad_info.name);
334
335 if (radv_device_get_cache_uuid(device->rad_info.family, device->cache_uuid)) {
336 device->ws->destroy(device->ws);
337 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
338 "cannot generate UUID");
339 goto fail;
340 }
341
342 /* These flags affect shader compilation. */
343 uint64_t shader_env_flags =
344 (device->instance->perftest_flags & RADV_PERFTEST_SISCHED ? 0x1 : 0) |
345 (device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH ? 0x2 : 0) |
346 (device->use_aco ? 0x4 : 0);
347
348 /* The gpu id is already embedded in the uuid so we just pass "radv"
349 * when creating the cache.
350 */
351 char buf[VK_UUID_SIZE * 2 + 1];
352 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
353 device->disk_cache = disk_cache_create(device->name, buf, shader_env_flags);
354
355 if (device->rad_info.chip_class < GFX8 ||
356 device->rad_info.chip_class > GFX9)
357 fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
358
359 radv_get_driver_uuid(&device->driver_uuid);
360 radv_get_device_uuid(&device->rad_info, &device->device_uuid);
361
362 device->out_of_order_rast_allowed = device->rad_info.has_out_of_order_rast &&
363 !(device->instance->debug_flags & RADV_DEBUG_NO_OUT_OF_ORDER);
364
365 device->dcc_msaa_allowed =
366 (device->instance->perftest_flags & RADV_PERFTEST_DCC_MSAA);
367
368 device->use_shader_ballot = device->rad_info.chip_class >= GFX8 &&
369 (device->use_aco || device->instance->perftest_flags & RADV_PERFTEST_SHADER_BALLOT);
370
371 device->use_ngg = device->rad_info.chip_class >= GFX10 &&
372 device->rad_info.family != CHIP_NAVI14 &&
373 !(device->instance->debug_flags & RADV_DEBUG_NO_NGG);
374 if (device->use_aco && device->use_ngg) {
375 fprintf(stderr, "WARNING: disabling NGG because ACO is used.\n");
376 device->use_ngg = false;
377 }
378
379 device->use_ngg_streamout = false;
380
381 /* Determine the number of threads per wave for all stages. */
382 device->cs_wave_size = 64;
383 device->ps_wave_size = 64;
384 device->ge_wave_size = 64;
385
386 if (device->rad_info.chip_class >= GFX10) {
387 if (device->instance->perftest_flags & RADV_PERFTEST_CS_WAVE_32)
388 device->cs_wave_size = 32;
389
390 /* For pixel shaders, wave64 is recommanded. */
391 if (device->instance->perftest_flags & RADV_PERFTEST_PS_WAVE_32)
392 device->ps_wave_size = 32;
393
394 if (device->instance->perftest_flags & RADV_PERFTEST_GE_WAVE_32)
395 device->ge_wave_size = 32;
396 }
397
398 radv_physical_device_init_mem_types(device);
399 radv_fill_device_extension_table(device, &device->supported_extensions);
400
401 device->bus_info = *drm_device->businfo.pci;
402
403 if ((device->instance->debug_flags & RADV_DEBUG_INFO))
404 ac_print_gpu_info(&device->rad_info);
405
406 /* The WSI is structured as a layer on top of the driver, so this has
407 * to be the last part of initialization (at least until we get other
408 * semi-layers).
409 */
410 result = radv_init_wsi(device);
411 if (result != VK_SUCCESS) {
412 device->ws->destroy(device->ws);
413 vk_error(instance, result);
414 goto fail;
415 }
416
417 return VK_SUCCESS;
418
419 fail:
420 close(fd);
421 if (master_fd != -1)
422 close(master_fd);
423 return result;
424 }
425
426 static void
427 radv_physical_device_finish(struct radv_physical_device *device)
428 {
429 radv_finish_wsi(device);
430 device->ws->destroy(device->ws);
431 disk_cache_destroy(device->disk_cache);
432 close(device->local_fd);
433 if (device->master_fd != -1)
434 close(device->master_fd);
435 }
436
437 static void *
438 default_alloc_func(void *pUserData, size_t size, size_t align,
439 VkSystemAllocationScope allocationScope)
440 {
441 return malloc(size);
442 }
443
444 static void *
445 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
446 size_t align, VkSystemAllocationScope allocationScope)
447 {
448 return realloc(pOriginal, size);
449 }
450
451 static void
452 default_free_func(void *pUserData, void *pMemory)
453 {
454 free(pMemory);
455 }
456
457 static const VkAllocationCallbacks default_alloc = {
458 .pUserData = NULL,
459 .pfnAllocation = default_alloc_func,
460 .pfnReallocation = default_realloc_func,
461 .pfnFree = default_free_func,
462 };
463
464 static const struct debug_control radv_debug_options[] = {
465 {"nofastclears", RADV_DEBUG_NO_FAST_CLEARS},
466 {"nodcc", RADV_DEBUG_NO_DCC},
467 {"shaders", RADV_DEBUG_DUMP_SHADERS},
468 {"nocache", RADV_DEBUG_NO_CACHE},
469 {"shaderstats", RADV_DEBUG_DUMP_SHADER_STATS},
470 {"nohiz", RADV_DEBUG_NO_HIZ},
471 {"nocompute", RADV_DEBUG_NO_COMPUTE_QUEUE},
472 {"unsafemath", RADV_DEBUG_UNSAFE_MATH},
473 {"allbos", RADV_DEBUG_ALL_BOS},
474 {"noibs", RADV_DEBUG_NO_IBS},
475 {"spirv", RADV_DEBUG_DUMP_SPIRV},
476 {"vmfaults", RADV_DEBUG_VM_FAULTS},
477 {"zerovram", RADV_DEBUG_ZERO_VRAM},
478 {"syncshaders", RADV_DEBUG_SYNC_SHADERS},
479 {"nosisched", RADV_DEBUG_NO_SISCHED},
480 {"preoptir", RADV_DEBUG_PREOPTIR},
481 {"nodynamicbounds", RADV_DEBUG_NO_DYNAMIC_BOUNDS},
482 {"nooutoforder", RADV_DEBUG_NO_OUT_OF_ORDER},
483 {"info", RADV_DEBUG_INFO},
484 {"errors", RADV_DEBUG_ERRORS},
485 {"startup", RADV_DEBUG_STARTUP},
486 {"checkir", RADV_DEBUG_CHECKIR},
487 {"nothreadllvm", RADV_DEBUG_NOTHREADLLVM},
488 {"nobinning", RADV_DEBUG_NOBINNING},
489 {"noloadstoreopt", RADV_DEBUG_NO_LOAD_STORE_OPT},
490 {"nongg", RADV_DEBUG_NO_NGG},
491 {"noshaderballot", RADV_DEBUG_NO_SHADER_BALLOT},
492 {"allentrypoints", RADV_DEBUG_ALL_ENTRYPOINTS},
493 {"metashaders", RADV_DEBUG_DUMP_META_SHADERS},
494 {"nomemorycache", RADV_DEBUG_NO_MEMORY_CACHE},
495 {NULL, 0}
496 };
497
498 const char *
499 radv_get_debug_option_name(int id)
500 {
501 assert(id < ARRAY_SIZE(radv_debug_options) - 1);
502 return radv_debug_options[id].string;
503 }
504
505 static const struct debug_control radv_perftest_options[] = {
506 {"nobatchchain", RADV_PERFTEST_NO_BATCHCHAIN},
507 {"sisched", RADV_PERFTEST_SISCHED},
508 {"localbos", RADV_PERFTEST_LOCAL_BOS},
509 {"dccmsaa", RADV_PERFTEST_DCC_MSAA},
510 {"bolist", RADV_PERFTEST_BO_LIST},
511 {"shader_ballot", RADV_PERFTEST_SHADER_BALLOT},
512 {"tccompatcmask", RADV_PERFTEST_TC_COMPAT_CMASK},
513 {"cswave32", RADV_PERFTEST_CS_WAVE_32},
514 {"pswave32", RADV_PERFTEST_PS_WAVE_32},
515 {"gewave32", RADV_PERFTEST_GE_WAVE_32},
516 {"dfsm", RADV_PERFTEST_DFSM},
517 {"aco", RADV_PERFTEST_ACO},
518 {NULL, 0}
519 };
520
521 const char *
522 radv_get_perftest_option_name(int id)
523 {
524 assert(id < ARRAY_SIZE(radv_perftest_options) - 1);
525 return radv_perftest_options[id].string;
526 }
527
528 static void
529 radv_handle_per_app_options(struct radv_instance *instance,
530 const VkApplicationInfo *info)
531 {
532 const char *name = info ? info->pApplicationName : NULL;
533
534 if (!name)
535 return;
536
537 if (!strcmp(name, "Talos - Linux - 32bit") ||
538 !strcmp(name, "Talos - Linux - 64bit")) {
539 if (!(instance->debug_flags & RADV_DEBUG_NO_SISCHED)) {
540 /* Force enable LLVM sisched for Talos because it looks
541 * safe and it gives few more FPS.
542 */
543 instance->perftest_flags |= RADV_PERFTEST_SISCHED;
544 }
545 } else if (!strcmp(name, "DOOM_VFR")) {
546 /* Work around a Doom VFR game bug */
547 instance->debug_flags |= RADV_DEBUG_NO_DYNAMIC_BOUNDS;
548 } else if (!strcmp(name, "MonsterHunterWorld.exe")) {
549 /* Workaround for a WaW hazard when LLVM moves/merges
550 * load/store memory operations.
551 * See https://reviews.llvm.org/D61313
552 */
553 if (LLVM_VERSION_MAJOR < 9)
554 instance->debug_flags |= RADV_DEBUG_NO_LOAD_STORE_OPT;
555 } else if (!strcmp(name, "Wolfenstein: Youngblood")) {
556 if (!(instance->debug_flags & RADV_DEBUG_NO_SHADER_BALLOT)) {
557 /* Force enable VK_AMD_shader_ballot because it looks
558 * safe and it gives a nice boost (+20% on Vega 56 at
559 * this time).
560 */
561 instance->perftest_flags |= RADV_PERFTEST_SHADER_BALLOT;
562 }
563 } else if (!strcmp(name, "Fledge")) {
564 /*
565 * Zero VRAM for "The Surge 2"
566 *
567 * This avoid a hang when when rendering any level. Likely
568 * uninitialized data in an indirect draw.
569 */
570 instance->debug_flags |= RADV_DEBUG_ZERO_VRAM;
571 }
572 }
573
574 static int radv_get_instance_extension_index(const char *name)
575 {
576 for (unsigned i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; ++i) {
577 if (strcmp(name, radv_instance_extensions[i].extensionName) == 0)
578 return i;
579 }
580 return -1;
581 }
582
583 static const char radv_dri_options_xml[] =
584 DRI_CONF_BEGIN
585 DRI_CONF_SECTION_PERFORMANCE
586 DRI_CONF_ADAPTIVE_SYNC("true")
587 DRI_CONF_VK_X11_OVERRIDE_MIN_IMAGE_COUNT(0)
588 DRI_CONF_VK_X11_STRICT_IMAGE_COUNT("false")
589 DRI_CONF_SECTION_END
590 DRI_CONF_END;
591
592 static void radv_init_dri_options(struct radv_instance *instance)
593 {
594 driParseOptionInfo(&instance->available_dri_options, radv_dri_options_xml);
595 driParseConfigFiles(&instance->dri_options,
596 &instance->available_dri_options,
597 0, "radv", NULL,
598 instance->engineName,
599 instance->engineVersion);
600 }
601
602 VkResult radv_CreateInstance(
603 const VkInstanceCreateInfo* pCreateInfo,
604 const VkAllocationCallbacks* pAllocator,
605 VkInstance* pInstance)
606 {
607 struct radv_instance *instance;
608 VkResult result;
609
610 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
611
612 uint32_t client_version;
613 if (pCreateInfo->pApplicationInfo &&
614 pCreateInfo->pApplicationInfo->apiVersion != 0) {
615 client_version = pCreateInfo->pApplicationInfo->apiVersion;
616 } else {
617 client_version = VK_API_VERSION_1_0;
618 }
619
620 const char *engine_name = NULL;
621 uint32_t engine_version = 0;
622 if (pCreateInfo->pApplicationInfo) {
623 engine_name = pCreateInfo->pApplicationInfo->pEngineName;
624 engine_version = pCreateInfo->pApplicationInfo->engineVersion;
625 }
626
627 instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
628 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
629 if (!instance)
630 return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
631
632 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
633
634 if (pAllocator)
635 instance->alloc = *pAllocator;
636 else
637 instance->alloc = default_alloc;
638
639 instance->apiVersion = client_version;
640 instance->physicalDeviceCount = -1;
641
642 /* Get secure compile thread count. NOTE: We cap this at 32 */
643 #define MAX_SC_PROCS 32
644 char *num_sc_threads = getenv("RADV_SECURE_COMPILE_THREADS");
645 if (num_sc_threads)
646 instance->num_sc_threads = MIN2(strtoul(num_sc_threads, NULL, 10), MAX_SC_PROCS);
647
648 instance->debug_flags = parse_debug_string(getenv("RADV_DEBUG"),
649 radv_debug_options);
650
651 /* Disable memory cache when secure compile is set */
652 if (radv_device_use_secure_compile(instance))
653 instance->debug_flags |= RADV_DEBUG_NO_MEMORY_CACHE;
654
655 instance->perftest_flags = parse_debug_string(getenv("RADV_PERFTEST"),
656 radv_perftest_options);
657
658 if (instance->perftest_flags & RADV_PERFTEST_ACO)
659 fprintf(stderr, "WARNING: Experimental compiler backend enabled. Here be dragons! Incorrect rendering, GPU hangs and/or resets are likely\n");
660
661 if (instance->debug_flags & RADV_DEBUG_STARTUP)
662 radv_logi("Created an instance");
663
664 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
665 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
666 int index = radv_get_instance_extension_index(ext_name);
667
668 if (index < 0 || !radv_supported_instance_extensions.extensions[index]) {
669 vk_free2(&default_alloc, pAllocator, instance);
670 return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
671 }
672
673 instance->enabled_extensions.extensions[index] = true;
674 }
675
676 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
677 if (result != VK_SUCCESS) {
678 vk_free2(&default_alloc, pAllocator, instance);
679 return vk_error(instance, result);
680 }
681
682 instance->engineName = vk_strdup(&instance->alloc, engine_name,
683 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
684 instance->engineVersion = engine_version;
685
686 _mesa_locale_init();
687 glsl_type_singleton_init_or_ref();
688
689 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
690
691 radv_init_dri_options(instance);
692 radv_handle_per_app_options(instance, pCreateInfo->pApplicationInfo);
693
694 *pInstance = radv_instance_to_handle(instance);
695
696 return VK_SUCCESS;
697 }
698
699 void radv_DestroyInstance(
700 VkInstance _instance,
701 const VkAllocationCallbacks* pAllocator)
702 {
703 RADV_FROM_HANDLE(radv_instance, instance, _instance);
704
705 if (!instance)
706 return;
707
708 for (int i = 0; i < instance->physicalDeviceCount; ++i) {
709 radv_physical_device_finish(instance->physicalDevices + i);
710 }
711
712 vk_free(&instance->alloc, instance->engineName);
713
714 VG(VALGRIND_DESTROY_MEMPOOL(instance));
715
716 glsl_type_singleton_decref();
717 _mesa_locale_fini();
718
719 driDestroyOptionCache(&instance->dri_options);
720 driDestroyOptionInfo(&instance->available_dri_options);
721
722 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
723
724 vk_free(&instance->alloc, instance);
725 }
726
727 static VkResult
728 radv_enumerate_devices(struct radv_instance *instance)
729 {
730 /* TODO: Check for more devices ? */
731 drmDevicePtr devices[8];
732 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
733 int max_devices;
734
735 instance->physicalDeviceCount = 0;
736
737 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
738
739 if (instance->debug_flags & RADV_DEBUG_STARTUP)
740 radv_logi("Found %d drm nodes", max_devices);
741
742 if (max_devices < 1)
743 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
744
745 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
746 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
747 devices[i]->bustype == DRM_BUS_PCI &&
748 devices[i]->deviceinfo.pci->vendor_id == ATI_VENDOR_ID) {
749
750 result = radv_physical_device_init(instance->physicalDevices +
751 instance->physicalDeviceCount,
752 instance,
753 devices[i]);
754 if (result == VK_SUCCESS)
755 ++instance->physicalDeviceCount;
756 else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
757 break;
758 }
759 }
760 drmFreeDevices(devices, max_devices);
761
762 return result;
763 }
764
765 VkResult radv_EnumeratePhysicalDevices(
766 VkInstance _instance,
767 uint32_t* pPhysicalDeviceCount,
768 VkPhysicalDevice* pPhysicalDevices)
769 {
770 RADV_FROM_HANDLE(radv_instance, instance, _instance);
771 VkResult result;
772
773 if (instance->physicalDeviceCount < 0) {
774 result = radv_enumerate_devices(instance);
775 if (result != VK_SUCCESS &&
776 result != VK_ERROR_INCOMPATIBLE_DRIVER)
777 return result;
778 }
779
780 if (!pPhysicalDevices) {
781 *pPhysicalDeviceCount = instance->physicalDeviceCount;
782 } else {
783 *pPhysicalDeviceCount = MIN2(*pPhysicalDeviceCount, instance->physicalDeviceCount);
784 for (unsigned i = 0; i < *pPhysicalDeviceCount; ++i)
785 pPhysicalDevices[i] = radv_physical_device_to_handle(instance->physicalDevices + i);
786 }
787
788 return *pPhysicalDeviceCount < instance->physicalDeviceCount ? VK_INCOMPLETE
789 : VK_SUCCESS;
790 }
791
792 VkResult radv_EnumeratePhysicalDeviceGroups(
793 VkInstance _instance,
794 uint32_t* pPhysicalDeviceGroupCount,
795 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
796 {
797 RADV_FROM_HANDLE(radv_instance, instance, _instance);
798 VkResult result;
799
800 if (instance->physicalDeviceCount < 0) {
801 result = radv_enumerate_devices(instance);
802 if (result != VK_SUCCESS &&
803 result != VK_ERROR_INCOMPATIBLE_DRIVER)
804 return result;
805 }
806
807 if (!pPhysicalDeviceGroupProperties) {
808 *pPhysicalDeviceGroupCount = instance->physicalDeviceCount;
809 } else {
810 *pPhysicalDeviceGroupCount = MIN2(*pPhysicalDeviceGroupCount, instance->physicalDeviceCount);
811 for (unsigned i = 0; i < *pPhysicalDeviceGroupCount; ++i) {
812 pPhysicalDeviceGroupProperties[i].physicalDeviceCount = 1;
813 pPhysicalDeviceGroupProperties[i].physicalDevices[0] = radv_physical_device_to_handle(instance->physicalDevices + i);
814 pPhysicalDeviceGroupProperties[i].subsetAllocation = false;
815 }
816 }
817 return *pPhysicalDeviceGroupCount < instance->physicalDeviceCount ? VK_INCOMPLETE
818 : VK_SUCCESS;
819 }
820
821 void radv_GetPhysicalDeviceFeatures(
822 VkPhysicalDevice physicalDevice,
823 VkPhysicalDeviceFeatures* pFeatures)
824 {
825 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
826 memset(pFeatures, 0, sizeof(*pFeatures));
827
828 *pFeatures = (VkPhysicalDeviceFeatures) {
829 .robustBufferAccess = true,
830 .fullDrawIndexUint32 = true,
831 .imageCubeArray = true,
832 .independentBlend = true,
833 .geometryShader = true,
834 .tessellationShader = true,
835 .sampleRateShading = true,
836 .dualSrcBlend = true,
837 .logicOp = true,
838 .multiDrawIndirect = true,
839 .drawIndirectFirstInstance = true,
840 .depthClamp = true,
841 .depthBiasClamp = true,
842 .fillModeNonSolid = true,
843 .depthBounds = true,
844 .wideLines = true,
845 .largePoints = true,
846 .alphaToOne = true,
847 .multiViewport = true,
848 .samplerAnisotropy = true,
849 .textureCompressionETC2 = radv_device_supports_etc(pdevice),
850 .textureCompressionASTC_LDR = false,
851 .textureCompressionBC = true,
852 .occlusionQueryPrecise = true,
853 .pipelineStatisticsQuery = true,
854 .vertexPipelineStoresAndAtomics = true,
855 .fragmentStoresAndAtomics = true,
856 .shaderTessellationAndGeometryPointSize = true,
857 .shaderImageGatherExtended = true,
858 .shaderStorageImageExtendedFormats = true,
859 .shaderStorageImageMultisample = pdevice->rad_info.chip_class >= GFX8,
860 .shaderUniformBufferArrayDynamicIndexing = true,
861 .shaderSampledImageArrayDynamicIndexing = true,
862 .shaderStorageBufferArrayDynamicIndexing = true,
863 .shaderStorageImageArrayDynamicIndexing = true,
864 .shaderStorageImageReadWithoutFormat = true,
865 .shaderStorageImageWriteWithoutFormat = true,
866 .shaderClipDistance = true,
867 .shaderCullDistance = true,
868 .shaderFloat64 = true,
869 .shaderInt64 = true,
870 .shaderInt16 = pdevice->rad_info.chip_class >= GFX9 && !pdevice->use_aco,
871 .sparseBinding = true,
872 .variableMultisampleRate = true,
873 .inheritedQueries = true,
874 };
875 }
876
877 void radv_GetPhysicalDeviceFeatures2(
878 VkPhysicalDevice physicalDevice,
879 VkPhysicalDeviceFeatures2 *pFeatures)
880 {
881 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
882 vk_foreach_struct(ext, pFeatures->pNext) {
883 switch (ext->sType) {
884 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
885 VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
886 features->variablePointersStorageBuffer = true;
887 features->variablePointers = true;
888 break;
889 }
890 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
891 VkPhysicalDeviceMultiviewFeatures *features = (VkPhysicalDeviceMultiviewFeatures*)ext;
892 features->multiview = true;
893 features->multiviewGeometryShader = true;
894 features->multiviewTessellationShader = true;
895 break;
896 }
897 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
898 VkPhysicalDeviceShaderDrawParametersFeatures *features =
899 (VkPhysicalDeviceShaderDrawParametersFeatures*)ext;
900 features->shaderDrawParameters = true;
901 break;
902 }
903 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
904 VkPhysicalDeviceProtectedMemoryFeatures *features =
905 (VkPhysicalDeviceProtectedMemoryFeatures*)ext;
906 features->protectedMemory = false;
907 break;
908 }
909 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
910 VkPhysicalDevice16BitStorageFeatures *features =
911 (VkPhysicalDevice16BitStorageFeatures*)ext;
912 bool enabled = pdevice->rad_info.chip_class >= GFX8 && !pdevice->use_aco;
913 features->storageBuffer16BitAccess = enabled;
914 features->uniformAndStorageBuffer16BitAccess = enabled;
915 features->storagePushConstant16 = enabled;
916 features->storageInputOutput16 = enabled && LLVM_VERSION_MAJOR >= 9;
917 break;
918 }
919 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
920 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
921 (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)ext;
922 features->samplerYcbcrConversion = true;
923 break;
924 }
925 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
926 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
927 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT*)ext;
928 features->shaderInputAttachmentArrayDynamicIndexing = true;
929 features->shaderUniformTexelBufferArrayDynamicIndexing = true;
930 features->shaderStorageTexelBufferArrayDynamicIndexing = true;
931 features->shaderUniformBufferArrayNonUniformIndexing = true;
932 features->shaderSampledImageArrayNonUniformIndexing = true;
933 features->shaderStorageBufferArrayNonUniformIndexing = true;
934 features->shaderStorageImageArrayNonUniformIndexing = true;
935 features->shaderInputAttachmentArrayNonUniformIndexing = true;
936 features->shaderUniformTexelBufferArrayNonUniformIndexing = true;
937 features->shaderStorageTexelBufferArrayNonUniformIndexing = true;
938 features->descriptorBindingUniformBufferUpdateAfterBind = true;
939 features->descriptorBindingSampledImageUpdateAfterBind = true;
940 features->descriptorBindingStorageImageUpdateAfterBind = true;
941 features->descriptorBindingStorageBufferUpdateAfterBind = true;
942 features->descriptorBindingUniformTexelBufferUpdateAfterBind = true;
943 features->descriptorBindingStorageTexelBufferUpdateAfterBind = true;
944 features->descriptorBindingUpdateUnusedWhilePending = true;
945 features->descriptorBindingPartiallyBound = true;
946 features->descriptorBindingVariableDescriptorCount = true;
947 features->runtimeDescriptorArray = true;
948 break;
949 }
950 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
951 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
952 (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
953 features->conditionalRendering = true;
954 features->inheritedConditionalRendering = false;
955 break;
956 }
957 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
958 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
959 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
960 features->vertexAttributeInstanceRateDivisor = VK_TRUE;
961 features->vertexAttributeInstanceRateZeroDivisor = VK_TRUE;
962 break;
963 }
964 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
965 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
966 (VkPhysicalDeviceTransformFeedbackFeaturesEXT*)ext;
967 features->transformFeedback = true;
968 features->geometryStreams = !pdevice->use_ngg_streamout;
969 break;
970 }
971 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
972 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
973 (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
974 features->scalarBlockLayout = pdevice->rad_info.chip_class >= GFX7;
975 break;
976 }
977 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT: {
978 VkPhysicalDeviceMemoryPriorityFeaturesEXT *features =
979 (VkPhysicalDeviceMemoryPriorityFeaturesEXT *)ext;
980 features->memoryPriority = VK_TRUE;
981 break;
982 }
983 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT: {
984 VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *features =
985 (VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *)ext;
986 features->bufferDeviceAddress = true;
987 features->bufferDeviceAddressCaptureReplay = false;
988 features->bufferDeviceAddressMultiDevice = false;
989 break;
990 }
991 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
992 VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
993 (VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
994 features->depthClipEnable = true;
995 break;
996 }
997 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT: {
998 VkPhysicalDeviceHostQueryResetFeaturesEXT *features =
999 (VkPhysicalDeviceHostQueryResetFeaturesEXT *)ext;
1000 features->hostQueryReset = true;
1001 break;
1002 }
1003 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
1004 VkPhysicalDevice8BitStorageFeaturesKHR *features =
1005 (VkPhysicalDevice8BitStorageFeaturesKHR*)ext;
1006 bool enabled = pdevice->rad_info.chip_class >= GFX8 && !pdevice->use_aco;
1007 features->storageBuffer8BitAccess = enabled;
1008 features->uniformAndStorageBuffer8BitAccess = enabled;
1009 features->storagePushConstant8 = enabled;
1010 break;
1011 }
1012 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES_KHR: {
1013 VkPhysicalDeviceShaderFloat16Int8FeaturesKHR *features =
1014 (VkPhysicalDeviceShaderFloat16Int8FeaturesKHR*)ext;
1015 features->shaderFloat16 = pdevice->rad_info.chip_class >= GFX8 && !pdevice->use_aco;
1016 features->shaderInt8 = !pdevice->use_aco;
1017 break;
1018 }
1019 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR: {
1020 VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *features =
1021 (VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *)ext;
1022 features->shaderBufferInt64Atomics = LLVM_VERSION_MAJOR >= 9;
1023 features->shaderSharedInt64Atomics = LLVM_VERSION_MAJOR >= 9;
1024 break;
1025 }
1026 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT: {
1027 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT *features =
1028 (VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT *)ext;
1029 features->shaderDemoteToHelperInvocation = pdevice->use_aco;
1030 break;
1031 }
1032 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
1033 VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
1034 (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
1035
1036 features->inlineUniformBlock = true;
1037 features->descriptorBindingInlineUniformBlockUpdateAfterBind = true;
1038 break;
1039 }
1040 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV: {
1041 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *features =
1042 (VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *)ext;
1043 features->computeDerivativeGroupQuads = false;
1044 features->computeDerivativeGroupLinear = true;
1045 break;
1046 }
1047 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
1048 VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
1049 (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT*)ext;
1050 features->ycbcrImageArrays = true;
1051 break;
1052 }
1053 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR: {
1054 VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *features =
1055 (VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *)ext;
1056 features->uniformBufferStandardLayout = true;
1057 break;
1058 }
1059 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT: {
1060 VkPhysicalDeviceIndexTypeUint8FeaturesEXT *features =
1061 (VkPhysicalDeviceIndexTypeUint8FeaturesEXT *)ext;
1062 features->indexTypeUint8 = pdevice->rad_info.chip_class >= GFX8;
1063 break;
1064 }
1065 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES_KHR: {
1066 VkPhysicalDeviceImagelessFramebufferFeaturesKHR *features =
1067 (VkPhysicalDeviceImagelessFramebufferFeaturesKHR *)ext;
1068 features->imagelessFramebuffer = true;
1069 break;
1070 }
1071 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR: {
1072 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *features =
1073 (VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *)ext;
1074 features->pipelineExecutableInfo = true;
1075 break;
1076 }
1077 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR: {
1078 VkPhysicalDeviceShaderClockFeaturesKHR *features =
1079 (VkPhysicalDeviceShaderClockFeaturesKHR *)ext;
1080 features->shaderSubgroupClock = true;
1081 features->shaderDeviceClock = false;
1082 break;
1083 }
1084 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_FEATURES_EXT: {
1085 VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *features =
1086 (VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *)ext;
1087 features->texelBufferAlignment = true;
1088 break;
1089 }
1090 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR: {
1091 VkPhysicalDeviceTimelineSemaphoreFeaturesKHR *features =
1092 (VkPhysicalDeviceTimelineSemaphoreFeaturesKHR *) ext;
1093 features->timelineSemaphore = true;
1094 break;
1095 }
1096 default:
1097 break;
1098 }
1099 }
1100 return radv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
1101 }
1102
1103 void radv_GetPhysicalDeviceProperties(
1104 VkPhysicalDevice physicalDevice,
1105 VkPhysicalDeviceProperties* pProperties)
1106 {
1107 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1108 VkSampleCountFlags sample_counts = 0xf;
1109
1110 /* make sure that the entire descriptor set is addressable with a signed
1111 * 32-bit int. So the sum of all limits scaled by descriptor size has to
1112 * be at most 2 GiB. the combined image & samples object count as one of
1113 * both. This limit is for the pipeline layout, not for the set layout, but
1114 * there is no set limit, so we just set a pipeline limit. I don't think
1115 * any app is going to hit this soon. */
1116 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
1117 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1118 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1119 32 /* sampler, largest when combined with image */ +
1120 64 /* sampled image */ +
1121 64 /* storage image */);
1122
1123 VkPhysicalDeviceLimits limits = {
1124 .maxImageDimension1D = (1 << 14),
1125 .maxImageDimension2D = (1 << 14),
1126 .maxImageDimension3D = (1 << 11),
1127 .maxImageDimensionCube = (1 << 14),
1128 .maxImageArrayLayers = (1 << 11),
1129 .maxTexelBufferElements = 128 * 1024 * 1024,
1130 .maxUniformBufferRange = UINT32_MAX,
1131 .maxStorageBufferRange = UINT32_MAX,
1132 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
1133 .maxMemoryAllocationCount = UINT32_MAX,
1134 .maxSamplerAllocationCount = 64 * 1024,
1135 .bufferImageGranularity = 64, /* A cache line */
1136 .sparseAddressSpaceSize = 0xffffffffu, /* buffer max size */
1137 .maxBoundDescriptorSets = MAX_SETS,
1138 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
1139 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
1140 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
1141 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
1142 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
1143 .maxPerStageDescriptorInputAttachments = max_descriptor_set_size,
1144 .maxPerStageResources = max_descriptor_set_size,
1145 .maxDescriptorSetSamplers = max_descriptor_set_size,
1146 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
1147 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS,
1148 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
1149 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS,
1150 .maxDescriptorSetSampledImages = max_descriptor_set_size,
1151 .maxDescriptorSetStorageImages = max_descriptor_set_size,
1152 .maxDescriptorSetInputAttachments = max_descriptor_set_size,
1153 .maxVertexInputAttributes = MAX_VERTEX_ATTRIBS,
1154 .maxVertexInputBindings = MAX_VBS,
1155 .maxVertexInputAttributeOffset = 2047,
1156 .maxVertexInputBindingStride = 2048,
1157 .maxVertexOutputComponents = 128,
1158 .maxTessellationGenerationLevel = 64,
1159 .maxTessellationPatchSize = 32,
1160 .maxTessellationControlPerVertexInputComponents = 128,
1161 .maxTessellationControlPerVertexOutputComponents = 128,
1162 .maxTessellationControlPerPatchOutputComponents = 120,
1163 .maxTessellationControlTotalOutputComponents = 4096,
1164 .maxTessellationEvaluationInputComponents = 128,
1165 .maxTessellationEvaluationOutputComponents = 128,
1166 .maxGeometryShaderInvocations = 127,
1167 .maxGeometryInputComponents = 64,
1168 .maxGeometryOutputComponents = 128,
1169 .maxGeometryOutputVertices = 256,
1170 .maxGeometryTotalOutputComponents = 1024,
1171 .maxFragmentInputComponents = 128,
1172 .maxFragmentOutputAttachments = 8,
1173 .maxFragmentDualSrcAttachments = 1,
1174 .maxFragmentCombinedOutputResources = 8,
1175 .maxComputeSharedMemorySize = 32768,
1176 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1177 .maxComputeWorkGroupInvocations = 2048,
1178 .maxComputeWorkGroupSize = {
1179 2048,
1180 2048,
1181 2048
1182 },
1183 .subPixelPrecisionBits = 8,
1184 .subTexelPrecisionBits = 8,
1185 .mipmapPrecisionBits = 8,
1186 .maxDrawIndexedIndexValue = UINT32_MAX,
1187 .maxDrawIndirectCount = UINT32_MAX,
1188 .maxSamplerLodBias = 16,
1189 .maxSamplerAnisotropy = 16,
1190 .maxViewports = MAX_VIEWPORTS,
1191 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1192 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1193 .viewportSubPixelBits = 8,
1194 .minMemoryMapAlignment = 4096, /* A page */
1195 .minTexelBufferOffsetAlignment = 4,
1196 .minUniformBufferOffsetAlignment = 4,
1197 .minStorageBufferOffsetAlignment = 4,
1198 .minTexelOffset = -32,
1199 .maxTexelOffset = 31,
1200 .minTexelGatherOffset = -32,
1201 .maxTexelGatherOffset = 31,
1202 .minInterpolationOffset = -2,
1203 .maxInterpolationOffset = 2,
1204 .subPixelInterpolationOffsetBits = 8,
1205 .maxFramebufferWidth = (1 << 14),
1206 .maxFramebufferHeight = (1 << 14),
1207 .maxFramebufferLayers = (1 << 10),
1208 .framebufferColorSampleCounts = sample_counts,
1209 .framebufferDepthSampleCounts = sample_counts,
1210 .framebufferStencilSampleCounts = sample_counts,
1211 .framebufferNoAttachmentsSampleCounts = sample_counts,
1212 .maxColorAttachments = MAX_RTS,
1213 .sampledImageColorSampleCounts = sample_counts,
1214 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1215 .sampledImageDepthSampleCounts = sample_counts,
1216 .sampledImageStencilSampleCounts = sample_counts,
1217 .storageImageSampleCounts = pdevice->rad_info.chip_class >= GFX8 ? sample_counts : VK_SAMPLE_COUNT_1_BIT,
1218 .maxSampleMaskWords = 1,
1219 .timestampComputeAndGraphics = true,
1220 .timestampPeriod = 1000000.0 / pdevice->rad_info.clock_crystal_freq,
1221 .maxClipDistances = 8,
1222 .maxCullDistances = 8,
1223 .maxCombinedClipAndCullDistances = 8,
1224 .discreteQueuePriorities = 2,
1225 .pointSizeRange = { 0.0, 8192.0 },
1226 .lineWidthRange = { 0.0, 7.9921875 },
1227 .pointSizeGranularity = (1.0 / 8.0),
1228 .lineWidthGranularity = (1.0 / 128.0),
1229 .strictLines = false, /* FINISHME */
1230 .standardSampleLocations = true,
1231 .optimalBufferCopyOffsetAlignment = 128,
1232 .optimalBufferCopyRowPitchAlignment = 128,
1233 .nonCoherentAtomSize = 64,
1234 };
1235
1236 *pProperties = (VkPhysicalDeviceProperties) {
1237 .apiVersion = radv_physical_device_api_version(pdevice),
1238 .driverVersion = vk_get_driver_version(),
1239 .vendorID = ATI_VENDOR_ID,
1240 .deviceID = pdevice->rad_info.pci_id,
1241 .deviceType = pdevice->rad_info.has_dedicated_vram ? VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1242 .limits = limits,
1243 .sparseProperties = {0},
1244 };
1245
1246 strcpy(pProperties->deviceName, pdevice->name);
1247 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
1248 }
1249
1250 void radv_GetPhysicalDeviceProperties2(
1251 VkPhysicalDevice physicalDevice,
1252 VkPhysicalDeviceProperties2 *pProperties)
1253 {
1254 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1255 radv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1256
1257 vk_foreach_struct(ext, pProperties->pNext) {
1258 switch (ext->sType) {
1259 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1260 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1261 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1262 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1263 break;
1264 }
1265 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1266 VkPhysicalDeviceIDProperties *properties = (VkPhysicalDeviceIDProperties*)ext;
1267 memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1268 memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1269 properties->deviceLUIDValid = false;
1270 break;
1271 }
1272 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1273 VkPhysicalDeviceMultiviewProperties *properties = (VkPhysicalDeviceMultiviewProperties*)ext;
1274 properties->maxMultiviewViewCount = MAX_VIEWS;
1275 properties->maxMultiviewInstanceIndex = INT_MAX;
1276 break;
1277 }
1278 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1279 VkPhysicalDevicePointClippingProperties *properties =
1280 (VkPhysicalDevicePointClippingProperties*)ext;
1281 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1282 break;
1283 }
1284 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT: {
1285 VkPhysicalDeviceDiscardRectanglePropertiesEXT *properties =
1286 (VkPhysicalDeviceDiscardRectanglePropertiesEXT*)ext;
1287 properties->maxDiscardRectangles = MAX_DISCARD_RECTANGLES;
1288 break;
1289 }
1290 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1291 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *properties =
1292 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1293 properties->minImportedHostPointerAlignment = 4096;
1294 break;
1295 }
1296 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1297 VkPhysicalDeviceSubgroupProperties *properties =
1298 (VkPhysicalDeviceSubgroupProperties*)ext;
1299 properties->subgroupSize = 64;
1300 properties->supportedStages = VK_SHADER_STAGE_ALL;
1301 properties->supportedOperations =
1302 VK_SUBGROUP_FEATURE_BASIC_BIT |
1303 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1304 VK_SUBGROUP_FEATURE_QUAD_BIT |
1305 VK_SUBGROUP_FEATURE_VOTE_BIT;
1306 if (pdevice->rad_info.chip_class >= GFX8) {
1307 properties->supportedOperations |=
1308 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1309 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1310 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1311 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT;
1312 }
1313 properties->quadOperationsInAllStages = true;
1314 break;
1315 }
1316 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1317 VkPhysicalDeviceMaintenance3Properties *properties =
1318 (VkPhysicalDeviceMaintenance3Properties*)ext;
1319 /* Make sure everything is addressable by a signed 32-bit int, and
1320 * our largest descriptors are 96 bytes. */
1321 properties->maxPerSetDescriptors = (1ull << 31) / 96;
1322 /* Our buffer size fields allow only this much */
1323 properties->maxMemoryAllocationSize = 0xFFFFFFFFull;
1324 break;
1325 }
1326 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
1327 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
1328 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
1329 /* GFX6-8 only support single channel min/max filter. */
1330 properties->filterMinmaxImageComponentMapping = pdevice->rad_info.chip_class >= GFX9;
1331 properties->filterMinmaxSingleComponentFormats = true;
1332 break;
1333 }
1334 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD: {
1335 VkPhysicalDeviceShaderCorePropertiesAMD *properties =
1336 (VkPhysicalDeviceShaderCorePropertiesAMD *)ext;
1337
1338 /* Shader engines. */
1339 properties->shaderEngineCount =
1340 pdevice->rad_info.max_se;
1341 properties->shaderArraysPerEngineCount =
1342 pdevice->rad_info.max_sh_per_se;
1343 properties->computeUnitsPerShaderArray =
1344 pdevice->rad_info.num_good_cu_per_sh;
1345 properties->simdPerComputeUnit = 4;
1346 properties->wavefrontsPerSimd =
1347 pdevice->rad_info.family == CHIP_TONGA ||
1348 pdevice->rad_info.family == CHIP_ICELAND ||
1349 pdevice->rad_info.family == CHIP_POLARIS10 ||
1350 pdevice->rad_info.family == CHIP_POLARIS11 ||
1351 pdevice->rad_info.family == CHIP_POLARIS12 ||
1352 pdevice->rad_info.family == CHIP_VEGAM ? 8 : 10;
1353 properties->wavefrontSize = 64;
1354
1355 /* SGPR. */
1356 properties->sgprsPerSimd =
1357 pdevice->rad_info.num_physical_sgprs_per_simd;
1358 properties->minSgprAllocation =
1359 pdevice->rad_info.chip_class >= GFX8 ? 16 : 8;
1360 properties->maxSgprAllocation =
1361 pdevice->rad_info.family == CHIP_TONGA ||
1362 pdevice->rad_info.family == CHIP_ICELAND ? 96 : 104;
1363 properties->sgprAllocationGranularity =
1364 pdevice->rad_info.chip_class >= GFX8 ? 16 : 8;
1365
1366 /* VGPR. */
1367 properties->vgprsPerSimd = RADV_NUM_PHYSICAL_VGPRS;
1368 properties->minVgprAllocation = 4;
1369 properties->maxVgprAllocation = 256;
1370 properties->vgprAllocationGranularity = 4;
1371 break;
1372 }
1373 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_2_AMD: {
1374 VkPhysicalDeviceShaderCoreProperties2AMD *properties =
1375 (VkPhysicalDeviceShaderCoreProperties2AMD *)ext;
1376
1377 properties->shaderCoreFeatures = 0;
1378 properties->activeComputeUnitCount =
1379 pdevice->rad_info.num_good_compute_units;
1380 break;
1381 }
1382 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1383 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *properties =
1384 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1385 properties->maxVertexAttribDivisor = UINT32_MAX;
1386 break;
1387 }
1388 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
1389 VkPhysicalDeviceDescriptorIndexingPropertiesEXT *properties =
1390 (VkPhysicalDeviceDescriptorIndexingPropertiesEXT*)ext;
1391 properties->maxUpdateAfterBindDescriptorsInAllPools = UINT32_MAX / 64;
1392 properties->shaderUniformBufferArrayNonUniformIndexingNative = false;
1393 properties->shaderSampledImageArrayNonUniformIndexingNative = false;
1394 properties->shaderStorageBufferArrayNonUniformIndexingNative = false;
1395 properties->shaderStorageImageArrayNonUniformIndexingNative = false;
1396 properties->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1397 properties->robustBufferAccessUpdateAfterBind = false;
1398 properties->quadDivergentImplicitLod = false;
1399
1400 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS -
1401 MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_INLINE_UNIFORM_BLOCK_COUNT) /
1402 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1403 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1404 32 /* sampler, largest when combined with image */ +
1405 64 /* sampled image */ +
1406 64 /* storage image */);
1407 properties->maxPerStageDescriptorUpdateAfterBindSamplers = max_descriptor_set_size;
1408 properties->maxPerStageDescriptorUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1409 properties->maxPerStageDescriptorUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1410 properties->maxPerStageDescriptorUpdateAfterBindSampledImages = max_descriptor_set_size;
1411 properties->maxPerStageDescriptorUpdateAfterBindStorageImages = max_descriptor_set_size;
1412 properties->maxPerStageDescriptorUpdateAfterBindInputAttachments = max_descriptor_set_size;
1413 properties->maxPerStageUpdateAfterBindResources = max_descriptor_set_size;
1414 properties->maxDescriptorSetUpdateAfterBindSamplers = max_descriptor_set_size;
1415 properties->maxDescriptorSetUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1416 properties->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS;
1417 properties->maxDescriptorSetUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1418 properties->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS;
1419 properties->maxDescriptorSetUpdateAfterBindSampledImages = max_descriptor_set_size;
1420 properties->maxDescriptorSetUpdateAfterBindStorageImages = max_descriptor_set_size;
1421 properties->maxDescriptorSetUpdateAfterBindInputAttachments = max_descriptor_set_size;
1422 break;
1423 }
1424 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1425 VkPhysicalDeviceProtectedMemoryProperties *properties =
1426 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1427 properties->protectedNoFault = false;
1428 break;
1429 }
1430 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT: {
1431 VkPhysicalDeviceConservativeRasterizationPropertiesEXT *properties =
1432 (VkPhysicalDeviceConservativeRasterizationPropertiesEXT *)ext;
1433 properties->primitiveOverestimationSize = 0;
1434 properties->maxExtraPrimitiveOverestimationSize = 0;
1435 properties->extraPrimitiveOverestimationSizeGranularity = 0;
1436 properties->primitiveUnderestimation = VK_FALSE;
1437 properties->conservativePointAndLineRasterization = VK_FALSE;
1438 properties->degenerateTrianglesRasterized = VK_FALSE;
1439 properties->degenerateLinesRasterized = VK_FALSE;
1440 properties->fullyCoveredFragmentShaderInputVariable = VK_FALSE;
1441 properties->conservativeRasterizationPostDepthCoverage = VK_FALSE;
1442 break;
1443 }
1444 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1445 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1446 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1447 properties->pciDomain = pdevice->bus_info.domain;
1448 properties->pciBus = pdevice->bus_info.bus;
1449 properties->pciDevice = pdevice->bus_info.dev;
1450 properties->pciFunction = pdevice->bus_info.func;
1451 break;
1452 }
1453 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1454 VkPhysicalDeviceDriverPropertiesKHR *driver_props =
1455 (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1456
1457 driver_props->driverID = VK_DRIVER_ID_MESA_RADV_KHR;
1458 snprintf(driver_props->driverName, VK_MAX_DRIVER_NAME_SIZE_KHR, "radv");
1459 snprintf(driver_props->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1460 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1
1461 " (LLVM " MESA_LLVM_VERSION_STRING ")");
1462
1463 driver_props->conformanceVersion = (VkConformanceVersionKHR) {
1464 .major = 1,
1465 .minor = 1,
1466 .subminor = 2,
1467 .patch = 0,
1468 };
1469 break;
1470 }
1471 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
1472 VkPhysicalDeviceTransformFeedbackPropertiesEXT *properties =
1473 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
1474 properties->maxTransformFeedbackStreams = MAX_SO_STREAMS;
1475 properties->maxTransformFeedbackBuffers = MAX_SO_BUFFERS;
1476 properties->maxTransformFeedbackBufferSize = UINT32_MAX;
1477 properties->maxTransformFeedbackStreamDataSize = 512;
1478 properties->maxTransformFeedbackBufferDataSize = UINT32_MAX;
1479 properties->maxTransformFeedbackBufferDataStride = 512;
1480 properties->transformFeedbackQueries = !pdevice->use_ngg_streamout;
1481 properties->transformFeedbackStreamsLinesTriangles = !pdevice->use_ngg_streamout;
1482 properties->transformFeedbackRasterizationStreamSelect = false;
1483 properties->transformFeedbackDraw = true;
1484 break;
1485 }
1486 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1487 VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1488 (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1489
1490 props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1491 props->maxPerStageDescriptorInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_SETS;
1492 props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_SETS;
1493 props->maxDescriptorSetInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_COUNT;
1494 props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_COUNT;
1495 break;
1496 }
1497 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT: {
1498 VkPhysicalDeviceSampleLocationsPropertiesEXT *properties =
1499 (VkPhysicalDeviceSampleLocationsPropertiesEXT *)ext;
1500 properties->sampleLocationSampleCounts = VK_SAMPLE_COUNT_2_BIT |
1501 VK_SAMPLE_COUNT_4_BIT |
1502 VK_SAMPLE_COUNT_8_BIT;
1503 properties->maxSampleLocationGridSize = (VkExtent2D){ 2 , 2 };
1504 properties->sampleLocationCoordinateRange[0] = 0.0f;
1505 properties->sampleLocationCoordinateRange[1] = 0.9375f;
1506 properties->sampleLocationSubPixelBits = 4;
1507 properties->variableSampleLocations = VK_FALSE;
1508 break;
1509 }
1510 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR: {
1511 VkPhysicalDeviceDepthStencilResolvePropertiesKHR *properties =
1512 (VkPhysicalDeviceDepthStencilResolvePropertiesKHR *)ext;
1513
1514 /* We support all of the depth resolve modes */
1515 properties->supportedDepthResolveModes =
1516 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1517 VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1518 VK_RESOLVE_MODE_MIN_BIT_KHR |
1519 VK_RESOLVE_MODE_MAX_BIT_KHR;
1520
1521 /* Average doesn't make sense for stencil so we don't support that */
1522 properties->supportedStencilResolveModes =
1523 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1524 VK_RESOLVE_MODE_MIN_BIT_KHR |
1525 VK_RESOLVE_MODE_MAX_BIT_KHR;
1526
1527 properties->independentResolveNone = VK_TRUE;
1528 properties->independentResolve = VK_TRUE;
1529 break;
1530 }
1531 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT: {
1532 VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *properties =
1533 (VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *)ext;
1534 properties->storageTexelBufferOffsetAlignmentBytes = 4;
1535 properties->storageTexelBufferOffsetSingleTexelAlignment = true;
1536 properties->uniformTexelBufferOffsetAlignmentBytes = 4;
1537 properties->uniformTexelBufferOffsetSingleTexelAlignment = true;
1538 break;
1539 }
1540 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES_KHR : {
1541 VkPhysicalDeviceFloatControlsPropertiesKHR *properties =
1542 (VkPhysicalDeviceFloatControlsPropertiesKHR *)ext;
1543
1544 /* On AMD hardware, denormals and rounding modes for
1545 * fp16/fp64 are controlled by the same config
1546 * register.
1547 */
1548 properties->denormBehaviorIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR;
1549 properties->roundingModeIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY_KHR;
1550
1551 /* Do not allow both preserving and flushing denorms
1552 * because different shaders in the same pipeline can
1553 * have different settings and this won't work for
1554 * merged shaders. To make it work, this requires LLVM
1555 * support for changing the register. The same logic
1556 * applies for the rounding modes because they are
1557 * configured with the same config register.
1558 */
1559 properties->shaderDenormFlushToZeroFloat32 = true;
1560 properties->shaderDenormPreserveFloat32 = false;
1561 properties->shaderRoundingModeRTEFloat32 = true;
1562 properties->shaderRoundingModeRTZFloat32 = false;
1563 properties->shaderSignedZeroInfNanPreserveFloat32 = true;
1564
1565 properties->shaderDenormFlushToZeroFloat16 = false;
1566 properties->shaderDenormPreserveFloat16 = pdevice->rad_info.chip_class >= GFX8;
1567 properties->shaderRoundingModeRTEFloat16 = pdevice->rad_info.chip_class >= GFX8;
1568 properties->shaderRoundingModeRTZFloat16 = false;
1569 properties->shaderSignedZeroInfNanPreserveFloat16 = pdevice->rad_info.chip_class >= GFX8;
1570
1571 properties->shaderDenormFlushToZeroFloat64 = false;
1572 properties->shaderDenormPreserveFloat64 = pdevice->rad_info.chip_class >= GFX8;
1573 properties->shaderRoundingModeRTEFloat64 = pdevice->rad_info.chip_class >= GFX8;
1574 properties->shaderRoundingModeRTZFloat64 = false;
1575 properties->shaderSignedZeroInfNanPreserveFloat64 = pdevice->rad_info.chip_class >= GFX8;
1576 break;
1577 }
1578 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_PROPERTIES_KHR: {
1579 VkPhysicalDeviceTimelineSemaphorePropertiesKHR *props =
1580 (VkPhysicalDeviceTimelineSemaphorePropertiesKHR *) ext;
1581 props->maxTimelineSemaphoreValueDifference = UINT64_MAX;
1582 break;
1583 }
1584 default:
1585 break;
1586 }
1587 }
1588 }
1589
1590 static void radv_get_physical_device_queue_family_properties(
1591 struct radv_physical_device* pdevice,
1592 uint32_t* pCount,
1593 VkQueueFamilyProperties** pQueueFamilyProperties)
1594 {
1595 int num_queue_families = 1;
1596 int idx;
1597 if (pdevice->rad_info.num_compute_rings > 0 &&
1598 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE))
1599 num_queue_families++;
1600
1601 if (pQueueFamilyProperties == NULL) {
1602 *pCount = num_queue_families;
1603 return;
1604 }
1605
1606 if (!*pCount)
1607 return;
1608
1609 idx = 0;
1610 if (*pCount >= 1) {
1611 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
1612 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1613 VK_QUEUE_COMPUTE_BIT |
1614 VK_QUEUE_TRANSFER_BIT |
1615 VK_QUEUE_SPARSE_BINDING_BIT,
1616 .queueCount = 1,
1617 .timestampValidBits = 64,
1618 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
1619 };
1620 idx++;
1621 }
1622
1623 if (pdevice->rad_info.num_compute_rings > 0 &&
1624 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE)) {
1625 if (*pCount > idx) {
1626 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
1627 .queueFlags = VK_QUEUE_COMPUTE_BIT |
1628 VK_QUEUE_TRANSFER_BIT |
1629 VK_QUEUE_SPARSE_BINDING_BIT,
1630 .queueCount = pdevice->rad_info.num_compute_rings,
1631 .timestampValidBits = 64,
1632 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
1633 };
1634 idx++;
1635 }
1636 }
1637 *pCount = idx;
1638 }
1639
1640 void radv_GetPhysicalDeviceQueueFamilyProperties(
1641 VkPhysicalDevice physicalDevice,
1642 uint32_t* pCount,
1643 VkQueueFamilyProperties* pQueueFamilyProperties)
1644 {
1645 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1646 if (!pQueueFamilyProperties) {
1647 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
1648 return;
1649 }
1650 VkQueueFamilyProperties *properties[] = {
1651 pQueueFamilyProperties + 0,
1652 pQueueFamilyProperties + 1,
1653 pQueueFamilyProperties + 2,
1654 };
1655 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
1656 assert(*pCount <= 3);
1657 }
1658
1659 void radv_GetPhysicalDeviceQueueFamilyProperties2(
1660 VkPhysicalDevice physicalDevice,
1661 uint32_t* pCount,
1662 VkQueueFamilyProperties2 *pQueueFamilyProperties)
1663 {
1664 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1665 if (!pQueueFamilyProperties) {
1666 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
1667 return;
1668 }
1669 VkQueueFamilyProperties *properties[] = {
1670 &pQueueFamilyProperties[0].queueFamilyProperties,
1671 &pQueueFamilyProperties[1].queueFamilyProperties,
1672 &pQueueFamilyProperties[2].queueFamilyProperties,
1673 };
1674 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
1675 assert(*pCount <= 3);
1676 }
1677
1678 void radv_GetPhysicalDeviceMemoryProperties(
1679 VkPhysicalDevice physicalDevice,
1680 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
1681 {
1682 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
1683
1684 *pMemoryProperties = physical_device->memory_properties;
1685 }
1686
1687 static void
1688 radv_get_memory_budget_properties(VkPhysicalDevice physicalDevice,
1689 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memoryBudget)
1690 {
1691 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
1692 VkPhysicalDeviceMemoryProperties *memory_properties = &device->memory_properties;
1693 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
1694 uint64_t vram_size = radv_get_vram_size(device);
1695 uint64_t gtt_size = device->rad_info.gart_size;
1696 uint64_t heap_budget, heap_usage;
1697
1698 /* For all memory heaps, the computation of budget is as follow:
1699 * heap_budget = heap_size - global_heap_usage + app_heap_usage
1700 *
1701 * The Vulkan spec 1.1.97 says that the budget should include any
1702 * currently allocated device memory.
1703 *
1704 * Note that the application heap usages are not really accurate (eg.
1705 * in presence of shared buffers).
1706 */
1707 for (int i = 0; i < device->memory_properties.memoryTypeCount; i++) {
1708 uint32_t heap_index = device->memory_properties.memoryTypes[i].heapIndex;
1709
1710 switch (device->mem_type_indices[i]) {
1711 case RADV_MEM_TYPE_VRAM:
1712 heap_usage = device->ws->query_value(device->ws,
1713 RADEON_ALLOCATED_VRAM);
1714
1715 heap_budget = vram_size -
1716 device->ws->query_value(device->ws, RADEON_VRAM_USAGE) +
1717 heap_usage;
1718
1719 memoryBudget->heapBudget[heap_index] = heap_budget;
1720 memoryBudget->heapUsage[heap_index] = heap_usage;
1721 break;
1722 case RADV_MEM_TYPE_VRAM_CPU_ACCESS:
1723 heap_usage = device->ws->query_value(device->ws,
1724 RADEON_ALLOCATED_VRAM_VIS);
1725
1726 heap_budget = visible_vram_size -
1727 device->ws->query_value(device->ws, RADEON_VRAM_VIS_USAGE) +
1728 heap_usage;
1729
1730 memoryBudget->heapBudget[heap_index] = heap_budget;
1731 memoryBudget->heapUsage[heap_index] = heap_usage;
1732 break;
1733 case RADV_MEM_TYPE_GTT_WRITE_COMBINE:
1734 heap_usage = device->ws->query_value(device->ws,
1735 RADEON_ALLOCATED_GTT);
1736
1737 heap_budget = gtt_size -
1738 device->ws->query_value(device->ws, RADEON_GTT_USAGE) +
1739 heap_usage;
1740
1741 memoryBudget->heapBudget[heap_index] = heap_budget;
1742 memoryBudget->heapUsage[heap_index] = heap_usage;
1743 break;
1744 default:
1745 break;
1746 }
1747 }
1748
1749 /* The heapBudget and heapUsage values must be zero for array elements
1750 * greater than or equal to
1751 * VkPhysicalDeviceMemoryProperties::memoryHeapCount.
1752 */
1753 for (uint32_t i = memory_properties->memoryHeapCount; i < VK_MAX_MEMORY_HEAPS; i++) {
1754 memoryBudget->heapBudget[i] = 0;
1755 memoryBudget->heapUsage[i] = 0;
1756 }
1757 }
1758
1759 void radv_GetPhysicalDeviceMemoryProperties2(
1760 VkPhysicalDevice physicalDevice,
1761 VkPhysicalDeviceMemoryProperties2 *pMemoryProperties)
1762 {
1763 radv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1764 &pMemoryProperties->memoryProperties);
1765
1766 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memory_budget =
1767 vk_find_struct(pMemoryProperties->pNext,
1768 PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT);
1769 if (memory_budget)
1770 radv_get_memory_budget_properties(physicalDevice, memory_budget);
1771 }
1772
1773 VkResult radv_GetMemoryHostPointerPropertiesEXT(
1774 VkDevice _device,
1775 VkExternalMemoryHandleTypeFlagBits handleType,
1776 const void *pHostPointer,
1777 VkMemoryHostPointerPropertiesEXT *pMemoryHostPointerProperties)
1778 {
1779 RADV_FROM_HANDLE(radv_device, device, _device);
1780
1781 switch (handleType)
1782 {
1783 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT: {
1784 const struct radv_physical_device *physical_device = device->physical_device;
1785 uint32_t memoryTypeBits = 0;
1786 for (int i = 0; i < physical_device->memory_properties.memoryTypeCount; i++) {
1787 if (physical_device->mem_type_indices[i] == RADV_MEM_TYPE_GTT_CACHED) {
1788 memoryTypeBits = (1 << i);
1789 break;
1790 }
1791 }
1792 pMemoryHostPointerProperties->memoryTypeBits = memoryTypeBits;
1793 return VK_SUCCESS;
1794 }
1795 default:
1796 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
1797 }
1798 }
1799
1800 static enum radeon_ctx_priority
1801 radv_get_queue_global_priority(const VkDeviceQueueGlobalPriorityCreateInfoEXT *pObj)
1802 {
1803 /* Default to MEDIUM when a specific global priority isn't requested */
1804 if (!pObj)
1805 return RADEON_CTX_PRIORITY_MEDIUM;
1806
1807 switch(pObj->globalPriority) {
1808 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1809 return RADEON_CTX_PRIORITY_REALTIME;
1810 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1811 return RADEON_CTX_PRIORITY_HIGH;
1812 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1813 return RADEON_CTX_PRIORITY_MEDIUM;
1814 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1815 return RADEON_CTX_PRIORITY_LOW;
1816 default:
1817 unreachable("Illegal global priority value");
1818 return RADEON_CTX_PRIORITY_INVALID;
1819 }
1820 }
1821
1822 static int
1823 radv_queue_init(struct radv_device *device, struct radv_queue *queue,
1824 uint32_t queue_family_index, int idx,
1825 VkDeviceQueueCreateFlags flags,
1826 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority)
1827 {
1828 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1829 queue->device = device;
1830 queue->queue_family_index = queue_family_index;
1831 queue->queue_idx = idx;
1832 queue->priority = radv_get_queue_global_priority(global_priority);
1833 queue->flags = flags;
1834
1835 queue->hw_ctx = device->ws->ctx_create(device->ws, queue->priority);
1836 if (!queue->hw_ctx)
1837 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1838
1839 list_inithead(&queue->pending_submissions);
1840 pthread_mutex_init(&queue->pending_mutex, NULL);
1841
1842 return VK_SUCCESS;
1843 }
1844
1845 static void
1846 radv_queue_finish(struct radv_queue *queue)
1847 {
1848 pthread_mutex_destroy(&queue->pending_mutex);
1849
1850 if (queue->hw_ctx)
1851 queue->device->ws->ctx_destroy(queue->hw_ctx);
1852
1853 if (queue->initial_full_flush_preamble_cs)
1854 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
1855 if (queue->initial_preamble_cs)
1856 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
1857 if (queue->continue_preamble_cs)
1858 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
1859 if (queue->descriptor_bo)
1860 queue->device->ws->buffer_destroy(queue->descriptor_bo);
1861 if (queue->scratch_bo)
1862 queue->device->ws->buffer_destroy(queue->scratch_bo);
1863 if (queue->esgs_ring_bo)
1864 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
1865 if (queue->gsvs_ring_bo)
1866 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
1867 if (queue->tess_rings_bo)
1868 queue->device->ws->buffer_destroy(queue->tess_rings_bo);
1869 if (queue->gds_bo)
1870 queue->device->ws->buffer_destroy(queue->gds_bo);
1871 if (queue->gds_oa_bo)
1872 queue->device->ws->buffer_destroy(queue->gds_oa_bo);
1873 if (queue->compute_scratch_bo)
1874 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
1875 }
1876
1877 static void
1878 radv_bo_list_init(struct radv_bo_list *bo_list)
1879 {
1880 pthread_mutex_init(&bo_list->mutex, NULL);
1881 bo_list->list.count = bo_list->capacity = 0;
1882 bo_list->list.bos = NULL;
1883 }
1884
1885 static void
1886 radv_bo_list_finish(struct radv_bo_list *bo_list)
1887 {
1888 free(bo_list->list.bos);
1889 pthread_mutex_destroy(&bo_list->mutex);
1890 }
1891
1892 static VkResult radv_bo_list_add(struct radv_device *device,
1893 struct radeon_winsys_bo *bo)
1894 {
1895 struct radv_bo_list *bo_list = &device->bo_list;
1896
1897 if (bo->is_local)
1898 return VK_SUCCESS;
1899
1900 if (unlikely(!device->use_global_bo_list))
1901 return VK_SUCCESS;
1902
1903 pthread_mutex_lock(&bo_list->mutex);
1904 if (bo_list->list.count == bo_list->capacity) {
1905 unsigned capacity = MAX2(4, bo_list->capacity * 2);
1906 void *data = realloc(bo_list->list.bos, capacity * sizeof(struct radeon_winsys_bo*));
1907
1908 if (!data) {
1909 pthread_mutex_unlock(&bo_list->mutex);
1910 return VK_ERROR_OUT_OF_HOST_MEMORY;
1911 }
1912
1913 bo_list->list.bos = (struct radeon_winsys_bo**)data;
1914 bo_list->capacity = capacity;
1915 }
1916
1917 bo_list->list.bos[bo_list->list.count++] = bo;
1918 pthread_mutex_unlock(&bo_list->mutex);
1919 return VK_SUCCESS;
1920 }
1921
1922 static void radv_bo_list_remove(struct radv_device *device,
1923 struct radeon_winsys_bo *bo)
1924 {
1925 struct radv_bo_list *bo_list = &device->bo_list;
1926
1927 if (bo->is_local)
1928 return;
1929
1930 if (unlikely(!device->use_global_bo_list))
1931 return;
1932
1933 pthread_mutex_lock(&bo_list->mutex);
1934 for(unsigned i = 0; i < bo_list->list.count; ++i) {
1935 if (bo_list->list.bos[i] == bo) {
1936 bo_list->list.bos[i] = bo_list->list.bos[bo_list->list.count - 1];
1937 --bo_list->list.count;
1938 break;
1939 }
1940 }
1941 pthread_mutex_unlock(&bo_list->mutex);
1942 }
1943
1944 static void
1945 radv_device_init_gs_info(struct radv_device *device)
1946 {
1947 device->gs_table_depth = ac_get_gs_table_depth(device->physical_device->rad_info.chip_class,
1948 device->physical_device->rad_info.family);
1949 }
1950
1951 static int radv_get_device_extension_index(const char *name)
1952 {
1953 for (unsigned i = 0; i < RADV_DEVICE_EXTENSION_COUNT; ++i) {
1954 if (strcmp(name, radv_device_extensions[i].extensionName) == 0)
1955 return i;
1956 }
1957 return -1;
1958 }
1959
1960 static int
1961 radv_get_int_debug_option(const char *name, int default_value)
1962 {
1963 const char *str;
1964 int result;
1965
1966 str = getenv(name);
1967 if (!str) {
1968 result = default_value;
1969 } else {
1970 char *endptr;
1971
1972 result = strtol(str, &endptr, 0);
1973 if (str == endptr) {
1974 /* No digits founs. */
1975 result = default_value;
1976 }
1977 }
1978
1979 return result;
1980 }
1981
1982 static int install_seccomp_filter() {
1983
1984 struct sock_filter filter[] = {
1985 /* Check arch is 64bit x86 */
1986 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, arch))),
1987 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, AUDIT_ARCH_X86_64, 0, 12),
1988
1989 /* Futex is required for mutex locks */
1990 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1991 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_select, 11, 0),
1992
1993 /* Allow system exit calls for the forked process */
1994 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1995 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_exit_group, 9, 0),
1996
1997 /* Allow system read calls */
1998 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1999 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_read, 7, 0),
2000
2001 /* Allow system write calls */
2002 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
2003 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_write, 5, 0),
2004
2005 /* Allow system brk calls (we need this for malloc) */
2006 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
2007 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_brk, 3, 0),
2008
2009 /* Futex is required for mutex locks */
2010 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
2011 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_futex, 1, 0),
2012
2013 /* Return error if we hit a system call not on the whitelist */
2014 BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
2015
2016 /* Allow whitelisted system calls */
2017 BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW),
2018 };
2019
2020 struct sock_fprog prog = {
2021 .len = (unsigned short)(sizeof(filter) / sizeof(filter[0])),
2022 .filter = filter,
2023 };
2024
2025 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
2026 return -1;
2027
2028 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog))
2029 return -1;
2030
2031 return 0;
2032 }
2033
2034 /* Helper function with timeout support for reading from the pipe between
2035 * processes used for secure compile.
2036 */
2037 bool radv_sc_read(int fd, void *buf, size_t size, bool timeout)
2038 {
2039 fd_set fds;
2040 struct timeval tv;
2041
2042 FD_ZERO(&fds);
2043 FD_SET(fd, &fds);
2044
2045 while (true) {
2046 /* We can't rely on the value of tv after calling select() so
2047 * we must reset it on each iteration of the loop.
2048 */
2049 tv.tv_sec = 5;
2050 tv.tv_usec = 0;
2051
2052 int rval = select(fd + 1, &fds, NULL, NULL, timeout ? &tv : NULL);
2053
2054 if (rval == -1) {
2055 /* select error */
2056 return false;
2057 } else if (rval) {
2058 ssize_t bytes_read = read(fd, buf, size);
2059 if (bytes_read < 0)
2060 return false;
2061
2062 buf += bytes_read;
2063 size -= bytes_read;
2064 if (size == 0)
2065 return true;
2066 } else {
2067 /* select timeout */
2068 return false;
2069 }
2070 }
2071 }
2072
2073 static void run_secure_compile_device(struct radv_device *device, unsigned process,
2074 int *fd_secure_input, int *fd_secure_output)
2075 {
2076 enum radv_secure_compile_type sc_type;
2077 if (install_seccomp_filter() == -1) {
2078 sc_type = RADV_SC_TYPE_INIT_FAILURE;
2079 } else {
2080 sc_type = RADV_SC_TYPE_INIT_SUCCESS;
2081 device->sc_state->secure_compile_processes[process].fd_secure_input = fd_secure_input[0];
2082 device->sc_state->secure_compile_processes[process].fd_secure_output = fd_secure_output[1];
2083 }
2084
2085 write(fd_secure_output[1], &sc_type, sizeof(sc_type));
2086
2087 if (sc_type == RADV_SC_TYPE_INIT_FAILURE)
2088 goto secure_compile_exit;
2089
2090 while (true) {
2091 radv_sc_read(fd_secure_input[0], &sc_type, sizeof(sc_type), false);
2092
2093 if (sc_type == RADV_SC_TYPE_COMPILE_PIPELINE) {
2094 struct radv_pipeline *pipeline;
2095 bool sc_read = true;
2096
2097 pipeline = vk_zalloc2(&device->alloc, NULL, sizeof(*pipeline), 8,
2098 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2099
2100 pipeline->device = device;
2101
2102 /* Read pipeline layout */
2103 struct radv_pipeline_layout layout;
2104 sc_read = radv_sc_read(fd_secure_input[0], &layout, sizeof(struct radv_pipeline_layout), true);
2105 sc_read &= radv_sc_read(fd_secure_input[0], &layout.num_sets, sizeof(uint32_t), true);
2106 if (!sc_read)
2107 goto secure_compile_exit;
2108
2109 for (uint32_t set = 0; set < layout.num_sets; set++) {
2110 uint32_t layout_size;
2111 sc_read &= radv_sc_read(fd_secure_input[0], &layout_size, sizeof(uint32_t), true);
2112 if (!sc_read)
2113 goto secure_compile_exit;
2114
2115 layout.set[set].layout = malloc(layout_size);
2116 layout.set[set].layout->layout_size = layout_size;
2117 sc_read &= radv_sc_read(fd_secure_input[0], layout.set[set].layout,
2118 layout.set[set].layout->layout_size, true);
2119 }
2120
2121 pipeline->layout = &layout;
2122
2123 /* Read pipeline key */
2124 struct radv_pipeline_key key;
2125 sc_read &= radv_sc_read(fd_secure_input[0], &key, sizeof(struct radv_pipeline_key), true);
2126
2127 /* Read pipeline create flags */
2128 VkPipelineCreateFlags flags;
2129 sc_read &= radv_sc_read(fd_secure_input[0], &flags, sizeof(VkPipelineCreateFlags), true);
2130
2131 /* Read stage and shader information */
2132 uint32_t num_stages;
2133 const VkPipelineShaderStageCreateInfo *pStages[MESA_SHADER_STAGES] = { 0, };
2134 sc_read &= radv_sc_read(fd_secure_input[0], &num_stages, sizeof(uint32_t), true);
2135 if (!sc_read)
2136 goto secure_compile_exit;
2137
2138 for (uint32_t i = 0; i < num_stages; i++) {
2139
2140 /* Read stage */
2141 gl_shader_stage stage;
2142 sc_read &= radv_sc_read(fd_secure_input[0], &stage, sizeof(gl_shader_stage), true);
2143
2144 VkPipelineShaderStageCreateInfo *pStage = calloc(1, sizeof(VkPipelineShaderStageCreateInfo));
2145
2146 /* Read entry point name */
2147 size_t name_size;
2148 sc_read &= radv_sc_read(fd_secure_input[0], &name_size, sizeof(size_t), true);
2149 if (!sc_read)
2150 goto secure_compile_exit;
2151
2152 char *ep_name = malloc(name_size);
2153 sc_read &= radv_sc_read(fd_secure_input[0], ep_name, name_size, true);
2154 pStage->pName = ep_name;
2155
2156 /* Read shader module */
2157 size_t module_size;
2158 sc_read &= radv_sc_read(fd_secure_input[0], &module_size, sizeof(size_t), true);
2159 if (!sc_read)
2160 goto secure_compile_exit;
2161
2162 struct radv_shader_module *module = malloc(module_size);
2163 sc_read &= radv_sc_read(fd_secure_input[0], module, module_size, true);
2164 pStage->module = radv_shader_module_to_handle(module);
2165
2166 /* Read specialization info */
2167 bool has_spec_info;
2168 sc_read &= radv_sc_read(fd_secure_input[0], &has_spec_info, sizeof(bool), true);
2169 if (!sc_read)
2170 goto secure_compile_exit;
2171
2172 if (has_spec_info) {
2173 VkSpecializationInfo *specInfo = malloc(sizeof(VkSpecializationInfo));
2174 pStage->pSpecializationInfo = specInfo;
2175
2176 sc_read &= radv_sc_read(fd_secure_input[0], &specInfo->dataSize, sizeof(size_t), true);
2177 if (!sc_read)
2178 goto secure_compile_exit;
2179
2180 void *si_data = malloc(specInfo->dataSize);
2181 sc_read &= radv_sc_read(fd_secure_input[0], si_data, specInfo->dataSize, true);
2182 specInfo->pData = si_data;
2183
2184 sc_read &= radv_sc_read(fd_secure_input[0], &specInfo->mapEntryCount, sizeof(uint32_t), true);
2185 if (!sc_read)
2186 goto secure_compile_exit;
2187
2188 VkSpecializationMapEntry *mapEntries = malloc(sizeof(VkSpecializationMapEntry) * specInfo->mapEntryCount);
2189 for (uint32_t j = 0; j < specInfo->mapEntryCount; j++) {
2190 sc_read &= radv_sc_read(fd_secure_input[0], &mapEntries[j], sizeof(VkSpecializationMapEntry), true);
2191 if (!sc_read)
2192 goto secure_compile_exit;
2193 }
2194
2195 specInfo->pMapEntries = mapEntries;
2196 }
2197
2198 pStages[stage] = pStage;
2199 }
2200
2201 /* Compile the shaders */
2202 VkPipelineCreationFeedbackEXT *stage_feedbacks[MESA_SHADER_STAGES] = { 0 };
2203 radv_create_shaders(pipeline, device, NULL, &key, pStages, flags, NULL, stage_feedbacks);
2204
2205 /* free memory allocated above */
2206 for (uint32_t set = 0; set < layout.num_sets; set++)
2207 free(layout.set[set].layout);
2208
2209 for (uint32_t i = 0; i < MESA_SHADER_STAGES; i++) {
2210 if (!pStages[i])
2211 continue;
2212
2213 free((void *) pStages[i]->pName);
2214 free(radv_shader_module_from_handle(pStages[i]->module));
2215 if (pStages[i]->pSpecializationInfo) {
2216 free((void *) pStages[i]->pSpecializationInfo->pData);
2217 free((void *) pStages[i]->pSpecializationInfo->pMapEntries);
2218 free((void *) pStages[i]->pSpecializationInfo);
2219 }
2220 free((void *) pStages[i]);
2221 }
2222
2223 vk_free(&device->alloc, pipeline);
2224
2225 sc_type = RADV_SC_TYPE_COMPILE_PIPELINE_FINISHED;
2226 write(fd_secure_output[1], &sc_type, sizeof(sc_type));
2227
2228 } else if (sc_type == RADV_SC_TYPE_DESTROY_DEVICE) {
2229 goto secure_compile_exit;
2230 }
2231 }
2232
2233 secure_compile_exit:
2234 close(fd_secure_input[1]);
2235 close(fd_secure_input[0]);
2236 close(fd_secure_output[1]);
2237 close(fd_secure_output[0]);
2238 _exit(0);
2239 }
2240
2241 static void destroy_secure_compile_device(struct radv_device *device, unsigned process)
2242 {
2243 int fd_secure_input = device->sc_state->secure_compile_processes[process].fd_secure_input;
2244
2245 enum radv_secure_compile_type sc_type = RADV_SC_TYPE_DESTROY_DEVICE;
2246 write(fd_secure_input, &sc_type, sizeof(sc_type));
2247
2248 close(device->sc_state->secure_compile_processes[process].fd_secure_input);
2249 close(device->sc_state->secure_compile_processes[process].fd_secure_output);
2250
2251 int status;
2252 waitpid(device->sc_state->secure_compile_processes[process].sc_pid, &status, 0);
2253 }
2254
2255 static VkResult fork_secure_compile_device(struct radv_device *device)
2256 {
2257 device->sc_state = vk_zalloc(&device->alloc,
2258 sizeof(struct radv_secure_compile_state),
2259 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2260
2261 mtx_init(&device->sc_state->secure_compile_mutex, mtx_plain);
2262
2263 uint8_t sc_threads = device->instance->num_sc_threads;
2264 int fd_secure_input[MAX_SC_PROCS][2];
2265 int fd_secure_output[MAX_SC_PROCS][2];
2266
2267 /* create pipe descriptors (used to communicate between processes) */
2268 for (unsigned i = 0; i < sc_threads; i++) {
2269 if (pipe(fd_secure_input[i]) == -1 ||
2270 pipe(fd_secure_output[i]) == -1) {
2271 return VK_ERROR_INITIALIZATION_FAILED;
2272 }
2273 }
2274
2275 device->sc_state->secure_compile_processes = vk_zalloc(&device->alloc,
2276 sizeof(struct radv_secure_compile_process) * sc_threads, 8,
2277 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2278
2279 for (unsigned process = 0; process < sc_threads; process++) {
2280 if ((device->sc_state->secure_compile_processes[process].sc_pid = fork()) == 0) {
2281 device->sc_state->secure_compile_thread_counter = process;
2282 run_secure_compile_device(device, process, fd_secure_input[process], fd_secure_output[process]);
2283 } else {
2284 if (device->sc_state->secure_compile_processes[process].sc_pid == -1)
2285 return VK_ERROR_INITIALIZATION_FAILED;
2286
2287 /* Read the init result returned from the secure process */
2288 enum radv_secure_compile_type sc_type;
2289 bool sc_read = radv_sc_read(fd_secure_output[process][0], &sc_type, sizeof(sc_type), true);
2290
2291 if (sc_type == RADV_SC_TYPE_INIT_FAILURE || !sc_read) {
2292 close(fd_secure_input[process][0]);
2293 close(fd_secure_input[process][1]);
2294 close(fd_secure_output[process][1]);
2295 close(fd_secure_output[process][0]);
2296 int status;
2297 waitpid(device->sc_state->secure_compile_processes[process].sc_pid, &status, 0);
2298
2299 /* Destroy any forks that were created sucessfully */
2300 for (unsigned i = 0; i < process; i++) {
2301 destroy_secure_compile_device(device, i);
2302 }
2303
2304 return VK_ERROR_INITIALIZATION_FAILED;
2305 } else {
2306 assert(sc_type == RADV_SC_TYPE_INIT_SUCCESS);
2307 device->sc_state->secure_compile_processes[process].fd_secure_input = fd_secure_input[process][1];
2308 device->sc_state->secure_compile_processes[process].fd_secure_output = fd_secure_output[process][0];
2309 }
2310 }
2311 }
2312 return VK_SUCCESS;
2313 }
2314
2315 static VkResult
2316 radv_create_pthread_cond(pthread_cond_t *cond)
2317 {
2318 pthread_condattr_t condattr;
2319 if (pthread_condattr_init(&condattr)) {
2320 return VK_ERROR_INITIALIZATION_FAILED;
2321 }
2322
2323 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC)) {
2324 pthread_condattr_destroy(&condattr);
2325 return VK_ERROR_INITIALIZATION_FAILED;
2326 }
2327 if (pthread_cond_init(cond, &condattr)) {
2328 pthread_condattr_destroy(&condattr);
2329 return VK_ERROR_INITIALIZATION_FAILED;
2330 }
2331 pthread_condattr_destroy(&condattr);
2332 return VK_SUCCESS;
2333 }
2334
2335 VkResult radv_CreateDevice(
2336 VkPhysicalDevice physicalDevice,
2337 const VkDeviceCreateInfo* pCreateInfo,
2338 const VkAllocationCallbacks* pAllocator,
2339 VkDevice* pDevice)
2340 {
2341 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2342 VkResult result;
2343 struct radv_device *device;
2344
2345 bool keep_shader_info = false;
2346
2347 /* Check enabled features */
2348 if (pCreateInfo->pEnabledFeatures) {
2349 VkPhysicalDeviceFeatures supported_features;
2350 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2351 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2352 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
2353 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2354 for (uint32_t i = 0; i < num_features; i++) {
2355 if (enabled_feature[i] && !supported_feature[i])
2356 return vk_error(physical_device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
2357 }
2358 }
2359
2360 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
2361 sizeof(*device), 8,
2362 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2363 if (!device)
2364 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2365
2366 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
2367 device->instance = physical_device->instance;
2368 device->physical_device = physical_device;
2369
2370 device->ws = physical_device->ws;
2371 if (pAllocator)
2372 device->alloc = *pAllocator;
2373 else
2374 device->alloc = physical_device->instance->alloc;
2375
2376 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
2377 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
2378 int index = radv_get_device_extension_index(ext_name);
2379 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
2380 vk_free(&device->alloc, device);
2381 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
2382 }
2383
2384 device->enabled_extensions.extensions[index] = true;
2385 }
2386
2387 keep_shader_info = device->enabled_extensions.AMD_shader_info;
2388
2389 /* With update after bind we can't attach bo's to the command buffer
2390 * from the descriptor set anymore, so we have to use a global BO list.
2391 */
2392 device->use_global_bo_list =
2393 (device->instance->perftest_flags & RADV_PERFTEST_BO_LIST) ||
2394 device->enabled_extensions.EXT_descriptor_indexing ||
2395 device->enabled_extensions.EXT_buffer_device_address;
2396
2397 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
2398 pCreateInfo->pEnabledFeatures->robustBufferAccess;
2399
2400 mtx_init(&device->shader_slab_mutex, mtx_plain);
2401 list_inithead(&device->shader_slabs);
2402
2403 radv_bo_list_init(&device->bo_list);
2404
2405 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
2406 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
2407 uint32_t qfi = queue_create->queueFamilyIndex;
2408 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
2409 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
2410
2411 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
2412
2413 device->queues[qfi] = vk_alloc(&device->alloc,
2414 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2415 if (!device->queues[qfi]) {
2416 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2417 goto fail;
2418 }
2419
2420 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
2421
2422 device->queue_count[qfi] = queue_create->queueCount;
2423
2424 for (unsigned q = 0; q < queue_create->queueCount; q++) {
2425 result = radv_queue_init(device, &device->queues[qfi][q],
2426 qfi, q, queue_create->flags,
2427 global_priority);
2428 if (result != VK_SUCCESS)
2429 goto fail;
2430 }
2431 }
2432
2433 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
2434 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
2435
2436 /* Disable DFSM by default. As of 2019-09-15 Talos on Low is still 3% slower on Raven. */
2437 device->dfsm_allowed = device->pbb_allowed &&
2438 (device->instance->perftest_flags & RADV_PERFTEST_DFSM);
2439
2440 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
2441
2442 /* The maximum number of scratch waves. Scratch space isn't divided
2443 * evenly between CUs. The number is only a function of the number of CUs.
2444 * We can decrease the constant to decrease the scratch buffer size.
2445 *
2446 * sctx->scratch_waves must be >= the maximum possible size of
2447 * 1 threadgroup, so that the hw doesn't hang from being unable
2448 * to start any.
2449 *
2450 * The recommended value is 4 per CU at most. Higher numbers don't
2451 * bring much benefit, but they still occupy chip resources (think
2452 * async compute). I've seen ~2% performance difference between 4 and 32.
2453 */
2454 uint32_t max_threads_per_block = 2048;
2455 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
2456 max_threads_per_block / 64);
2457
2458 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1) |
2459 S_00B800_CS_W32_EN(device->physical_device->cs_wave_size == 32);
2460
2461 if (device->physical_device->rad_info.chip_class >= GFX7) {
2462 /* If the KMD allows it (there is a KMD hw register for it),
2463 * allow launching waves out-of-order.
2464 */
2465 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
2466 }
2467
2468 radv_device_init_gs_info(device);
2469
2470 device->tess_offchip_block_dw_size =
2471 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
2472
2473 if (getenv("RADV_TRACE_FILE")) {
2474 const char *filename = getenv("RADV_TRACE_FILE");
2475
2476 keep_shader_info = true;
2477
2478 if (!radv_init_trace(device))
2479 goto fail;
2480
2481 fprintf(stderr, "*****************************************************************************\n");
2482 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
2483 fprintf(stderr, "*****************************************************************************\n");
2484
2485 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
2486 radv_dump_enabled_options(device, stderr);
2487 }
2488
2489 /* Temporarily disable secure compile while we create meta shaders, etc */
2490 uint8_t sc_threads = device->instance->num_sc_threads;
2491 if (sc_threads)
2492 device->instance->num_sc_threads = 0;
2493
2494 device->keep_shader_info = keep_shader_info;
2495 result = radv_device_init_meta(device);
2496 if (result != VK_SUCCESS)
2497 goto fail;
2498
2499 radv_device_init_msaa(device);
2500
2501 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
2502 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
2503 switch (family) {
2504 case RADV_QUEUE_GENERAL:
2505 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
2506 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_LOAD_ENABLE(1));
2507 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_SHADOW_ENABLE(1));
2508 break;
2509 case RADV_QUEUE_COMPUTE:
2510 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
2511 radeon_emit(device->empty_cs[family], 0);
2512 break;
2513 }
2514 device->ws->cs_finalize(device->empty_cs[family]);
2515 }
2516
2517 if (device->physical_device->rad_info.chip_class >= GFX7)
2518 cik_create_gfx_config(device);
2519
2520 VkPipelineCacheCreateInfo ci;
2521 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2522 ci.pNext = NULL;
2523 ci.flags = 0;
2524 ci.pInitialData = NULL;
2525 ci.initialDataSize = 0;
2526 VkPipelineCache pc;
2527 result = radv_CreatePipelineCache(radv_device_to_handle(device),
2528 &ci, NULL, &pc);
2529 if (result != VK_SUCCESS)
2530 goto fail_meta;
2531
2532 device->mem_cache = radv_pipeline_cache_from_handle(pc);
2533
2534 result = radv_create_pthread_cond(&device->timeline_cond);
2535 if (result != VK_SUCCESS)
2536 goto fail_mem_cache;
2537
2538 device->force_aniso =
2539 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
2540 if (device->force_aniso >= 0) {
2541 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
2542 1 << util_logbase2(device->force_aniso));
2543 }
2544
2545 /* Fork device for secure compile as required */
2546 device->instance->num_sc_threads = sc_threads;
2547 if (radv_device_use_secure_compile(device->instance)) {
2548 result = fork_secure_compile_device(device);
2549 if (result != VK_SUCCESS)
2550 goto fail_meta;
2551 }
2552
2553 *pDevice = radv_device_to_handle(device);
2554 return VK_SUCCESS;
2555
2556 fail_mem_cache:
2557 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
2558 fail_meta:
2559 radv_device_finish_meta(device);
2560 fail:
2561 radv_bo_list_finish(&device->bo_list);
2562
2563 if (device->trace_bo)
2564 device->ws->buffer_destroy(device->trace_bo);
2565
2566 if (device->gfx_init)
2567 device->ws->buffer_destroy(device->gfx_init);
2568
2569 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2570 for (unsigned q = 0; q < device->queue_count[i]; q++)
2571 radv_queue_finish(&device->queues[i][q]);
2572 if (device->queue_count[i])
2573 vk_free(&device->alloc, device->queues[i]);
2574 }
2575
2576 vk_free(&device->alloc, device);
2577 return result;
2578 }
2579
2580 void radv_DestroyDevice(
2581 VkDevice _device,
2582 const VkAllocationCallbacks* pAllocator)
2583 {
2584 RADV_FROM_HANDLE(radv_device, device, _device);
2585
2586 if (!device)
2587 return;
2588
2589 if (device->trace_bo)
2590 device->ws->buffer_destroy(device->trace_bo);
2591
2592 if (device->gfx_init)
2593 device->ws->buffer_destroy(device->gfx_init);
2594
2595 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2596 for (unsigned q = 0; q < device->queue_count[i]; q++)
2597 radv_queue_finish(&device->queues[i][q]);
2598 if (device->queue_count[i])
2599 vk_free(&device->alloc, device->queues[i]);
2600 if (device->empty_cs[i])
2601 device->ws->cs_destroy(device->empty_cs[i]);
2602 }
2603 radv_device_finish_meta(device);
2604
2605 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
2606 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
2607
2608 radv_destroy_shader_slabs(device);
2609
2610 pthread_cond_destroy(&device->timeline_cond);
2611 radv_bo_list_finish(&device->bo_list);
2612
2613 if (radv_device_use_secure_compile(device->instance)) {
2614 for (unsigned i = 0; i < device->instance->num_sc_threads; i++ ) {
2615 destroy_secure_compile_device(device, i);
2616 }
2617 }
2618
2619 if (device->sc_state)
2620 vk_free(&device->alloc, device->sc_state->secure_compile_processes);
2621 vk_free(&device->alloc, device->sc_state);
2622 vk_free(&device->alloc, device);
2623 }
2624
2625 VkResult radv_EnumerateInstanceLayerProperties(
2626 uint32_t* pPropertyCount,
2627 VkLayerProperties* pProperties)
2628 {
2629 if (pProperties == NULL) {
2630 *pPropertyCount = 0;
2631 return VK_SUCCESS;
2632 }
2633
2634 /* None supported at this time */
2635 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2636 }
2637
2638 VkResult radv_EnumerateDeviceLayerProperties(
2639 VkPhysicalDevice physicalDevice,
2640 uint32_t* pPropertyCount,
2641 VkLayerProperties* pProperties)
2642 {
2643 if (pProperties == NULL) {
2644 *pPropertyCount = 0;
2645 return VK_SUCCESS;
2646 }
2647
2648 /* None supported at this time */
2649 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2650 }
2651
2652 void radv_GetDeviceQueue2(
2653 VkDevice _device,
2654 const VkDeviceQueueInfo2* pQueueInfo,
2655 VkQueue* pQueue)
2656 {
2657 RADV_FROM_HANDLE(radv_device, device, _device);
2658 struct radv_queue *queue;
2659
2660 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
2661 if (pQueueInfo->flags != queue->flags) {
2662 /* From the Vulkan 1.1.70 spec:
2663 *
2664 * "The queue returned by vkGetDeviceQueue2 must have the same
2665 * flags value from this structure as that used at device
2666 * creation time in a VkDeviceQueueCreateInfo instance. If no
2667 * matching flags were specified at device creation time then
2668 * pQueue will return VK_NULL_HANDLE."
2669 */
2670 *pQueue = VK_NULL_HANDLE;
2671 return;
2672 }
2673
2674 *pQueue = radv_queue_to_handle(queue);
2675 }
2676
2677 void radv_GetDeviceQueue(
2678 VkDevice _device,
2679 uint32_t queueFamilyIndex,
2680 uint32_t queueIndex,
2681 VkQueue* pQueue)
2682 {
2683 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
2684 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
2685 .queueFamilyIndex = queueFamilyIndex,
2686 .queueIndex = queueIndex
2687 };
2688
2689 radv_GetDeviceQueue2(_device, &info, pQueue);
2690 }
2691
2692 static void
2693 fill_geom_tess_rings(struct radv_queue *queue,
2694 uint32_t *map,
2695 bool add_sample_positions,
2696 uint32_t esgs_ring_size,
2697 struct radeon_winsys_bo *esgs_ring_bo,
2698 uint32_t gsvs_ring_size,
2699 struct radeon_winsys_bo *gsvs_ring_bo,
2700 uint32_t tess_factor_ring_size,
2701 uint32_t tess_offchip_ring_offset,
2702 uint32_t tess_offchip_ring_size,
2703 struct radeon_winsys_bo *tess_rings_bo)
2704 {
2705 uint32_t *desc = &map[4];
2706
2707 if (esgs_ring_bo) {
2708 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
2709
2710 /* stride 0, num records - size, add tid, swizzle, elsize4,
2711 index stride 64 */
2712 desc[0] = esgs_va;
2713 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
2714 S_008F04_SWIZZLE_ENABLE(true);
2715 desc[2] = esgs_ring_size;
2716 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2717 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2718 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2719 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2720 S_008F0C_INDEX_STRIDE(3) |
2721 S_008F0C_ADD_TID_ENABLE(1);
2722
2723 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2724 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2725 S_008F0C_OOB_SELECT(2) |
2726 S_008F0C_RESOURCE_LEVEL(1);
2727 } else {
2728 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2729 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2730 S_008F0C_ELEMENT_SIZE(1);
2731 }
2732
2733 /* GS entry for ES->GS ring */
2734 /* stride 0, num records - size, elsize0,
2735 index stride 0 */
2736 desc[4] = esgs_va;
2737 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32);
2738 desc[6] = esgs_ring_size;
2739 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2740 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2741 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2742 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2743
2744 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2745 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2746 S_008F0C_OOB_SELECT(2) |
2747 S_008F0C_RESOURCE_LEVEL(1);
2748 } else {
2749 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2750 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2751 }
2752 }
2753
2754 desc += 8;
2755
2756 if (gsvs_ring_bo) {
2757 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
2758
2759 /* VS entry for GS->VS ring */
2760 /* stride 0, num records - size, elsize0,
2761 index stride 0 */
2762 desc[0] = gsvs_va;
2763 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32);
2764 desc[2] = gsvs_ring_size;
2765 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2766 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2767 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2768 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2769
2770 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2771 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2772 S_008F0C_OOB_SELECT(2) |
2773 S_008F0C_RESOURCE_LEVEL(1);
2774 } else {
2775 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2776 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2777 }
2778
2779 /* stride gsvs_itemsize, num records 64
2780 elsize 4, index stride 16 */
2781 /* shader will patch stride and desc[2] */
2782 desc[4] = gsvs_va;
2783 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32) |
2784 S_008F04_SWIZZLE_ENABLE(1);
2785 desc[6] = 0;
2786 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2787 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2788 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2789 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2790 S_008F0C_INDEX_STRIDE(1) |
2791 S_008F0C_ADD_TID_ENABLE(true);
2792
2793 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2794 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2795 S_008F0C_OOB_SELECT(2) |
2796 S_008F0C_RESOURCE_LEVEL(1);
2797 } else {
2798 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2799 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2800 S_008F0C_ELEMENT_SIZE(1);
2801 }
2802
2803 }
2804
2805 desc += 8;
2806
2807 if (tess_rings_bo) {
2808 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
2809 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
2810
2811 desc[0] = tess_va;
2812 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32);
2813 desc[2] = tess_factor_ring_size;
2814 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2815 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2816 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2817 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2818
2819 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2820 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2821 S_008F0C_OOB_SELECT(3) |
2822 S_008F0C_RESOURCE_LEVEL(1);
2823 } else {
2824 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2825 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2826 }
2827
2828 desc[4] = tess_offchip_va;
2829 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32);
2830 desc[6] = tess_offchip_ring_size;
2831 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2832 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2833 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2834 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2835
2836 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2837 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2838 S_008F0C_OOB_SELECT(3) |
2839 S_008F0C_RESOURCE_LEVEL(1);
2840 } else {
2841 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2842 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2843 }
2844 }
2845
2846 desc += 8;
2847
2848 if (add_sample_positions) {
2849 /* add sample positions after all rings */
2850 memcpy(desc, queue->device->sample_locations_1x, 8);
2851 desc += 2;
2852 memcpy(desc, queue->device->sample_locations_2x, 16);
2853 desc += 4;
2854 memcpy(desc, queue->device->sample_locations_4x, 32);
2855 desc += 8;
2856 memcpy(desc, queue->device->sample_locations_8x, 64);
2857 }
2858 }
2859
2860 static unsigned
2861 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
2862 {
2863 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= GFX7 &&
2864 device->physical_device->rad_info.family != CHIP_CARRIZO &&
2865 device->physical_device->rad_info.family != CHIP_STONEY;
2866 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
2867 unsigned max_offchip_buffers;
2868 unsigned offchip_granularity;
2869 unsigned hs_offchip_param;
2870
2871 /*
2872 * Per RadeonSI:
2873 * This must be one less than the maximum number due to a hw limitation.
2874 * Various hardware bugs need thGFX7
2875 *
2876 * Per AMDVLK:
2877 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
2878 * Gfx7 should limit max_offchip_buffers to 508
2879 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
2880 *
2881 * Follow AMDVLK here.
2882 */
2883 if (device->physical_device->rad_info.chip_class >= GFX10) {
2884 max_offchip_buffers_per_se = 256;
2885 } else if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
2886 device->physical_device->rad_info.chip_class == GFX7 ||
2887 device->physical_device->rad_info.chip_class == GFX6)
2888 --max_offchip_buffers_per_se;
2889
2890 max_offchip_buffers = max_offchip_buffers_per_se *
2891 device->physical_device->rad_info.max_se;
2892
2893 /* Hawaii has a bug with offchip buffers > 256 that can be worked
2894 * around by setting 4K granularity.
2895 */
2896 if (device->tess_offchip_block_dw_size == 4096) {
2897 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
2898 offchip_granularity = V_03093C_X_4K_DWORDS;
2899 } else {
2900 assert(device->tess_offchip_block_dw_size == 8192);
2901 offchip_granularity = V_03093C_X_8K_DWORDS;
2902 }
2903
2904 switch (device->physical_device->rad_info.chip_class) {
2905 case GFX6:
2906 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
2907 break;
2908 case GFX7:
2909 case GFX8:
2910 case GFX9:
2911 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
2912 break;
2913 case GFX10:
2914 break;
2915 default:
2916 break;
2917 }
2918
2919 *max_offchip_buffers_p = max_offchip_buffers;
2920 if (device->physical_device->rad_info.chip_class >= GFX7) {
2921 if (device->physical_device->rad_info.chip_class >= GFX8)
2922 --max_offchip_buffers;
2923 hs_offchip_param =
2924 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
2925 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
2926 } else {
2927 hs_offchip_param =
2928 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
2929 }
2930 return hs_offchip_param;
2931 }
2932
2933 static void
2934 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2935 struct radeon_winsys_bo *esgs_ring_bo,
2936 uint32_t esgs_ring_size,
2937 struct radeon_winsys_bo *gsvs_ring_bo,
2938 uint32_t gsvs_ring_size)
2939 {
2940 if (!esgs_ring_bo && !gsvs_ring_bo)
2941 return;
2942
2943 if (esgs_ring_bo)
2944 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
2945
2946 if (gsvs_ring_bo)
2947 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
2948
2949 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
2950 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
2951 radeon_emit(cs, esgs_ring_size >> 8);
2952 radeon_emit(cs, gsvs_ring_size >> 8);
2953 } else {
2954 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
2955 radeon_emit(cs, esgs_ring_size >> 8);
2956 radeon_emit(cs, gsvs_ring_size >> 8);
2957 }
2958 }
2959
2960 static void
2961 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2962 unsigned hs_offchip_param, unsigned tf_ring_size,
2963 struct radeon_winsys_bo *tess_rings_bo)
2964 {
2965 uint64_t tf_va;
2966
2967 if (!tess_rings_bo)
2968 return;
2969
2970 tf_va = radv_buffer_get_va(tess_rings_bo);
2971
2972 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
2973
2974 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
2975 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
2976 S_030938_SIZE(tf_ring_size / 4));
2977 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
2978 tf_va >> 8);
2979
2980 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2981 radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
2982 S_030984_BASE_HI(tf_va >> 40));
2983 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
2984 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
2985 S_030944_BASE_HI(tf_va >> 40));
2986 }
2987 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
2988 hs_offchip_param);
2989 } else {
2990 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
2991 S_008988_SIZE(tf_ring_size / 4));
2992 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
2993 tf_va >> 8);
2994 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
2995 hs_offchip_param);
2996 }
2997 }
2998
2999 static void
3000 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
3001 struct radeon_winsys_bo *compute_scratch_bo)
3002 {
3003 uint64_t scratch_va;
3004
3005 if (!compute_scratch_bo)
3006 return;
3007
3008 scratch_va = radv_buffer_get_va(compute_scratch_bo);
3009
3010 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
3011
3012 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
3013 radeon_emit(cs, scratch_va);
3014 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3015 S_008F04_SWIZZLE_ENABLE(1));
3016 }
3017
3018 static void
3019 radv_emit_global_shader_pointers(struct radv_queue *queue,
3020 struct radeon_cmdbuf *cs,
3021 struct radeon_winsys_bo *descriptor_bo)
3022 {
3023 uint64_t va;
3024
3025 if (!descriptor_bo)
3026 return;
3027
3028 va = radv_buffer_get_va(descriptor_bo);
3029
3030 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
3031
3032 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
3033 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3034 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3035 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3036 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3037
3038 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3039 radv_emit_shader_pointer(queue->device, cs, regs[i],
3040 va, true);
3041 }
3042 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
3043 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3044 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3045 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
3046 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
3047
3048 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3049 radv_emit_shader_pointer(queue->device, cs, regs[i],
3050 va, true);
3051 }
3052 } else {
3053 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
3054 R_00B130_SPI_SHADER_USER_DATA_VS_0,
3055 R_00B230_SPI_SHADER_USER_DATA_GS_0,
3056 R_00B330_SPI_SHADER_USER_DATA_ES_0,
3057 R_00B430_SPI_SHADER_USER_DATA_HS_0,
3058 R_00B530_SPI_SHADER_USER_DATA_LS_0};
3059
3060 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
3061 radv_emit_shader_pointer(queue->device, cs, regs[i],
3062 va, true);
3063 }
3064 }
3065 }
3066
3067 static void
3068 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3069 {
3070 struct radv_device *device = queue->device;
3071
3072 if (device->gfx_init) {
3073 uint64_t va = radv_buffer_get_va(device->gfx_init);
3074
3075 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
3076 radeon_emit(cs, va);
3077 radeon_emit(cs, va >> 32);
3078 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
3079
3080 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
3081 } else {
3082 struct radv_physical_device *physical_device = device->physical_device;
3083 si_emit_graphics(physical_device, cs);
3084 }
3085 }
3086
3087 static void
3088 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
3089 {
3090 struct radv_physical_device *physical_device = queue->device->physical_device;
3091 si_emit_compute(physical_device, cs);
3092 }
3093
3094 static VkResult
3095 radv_get_preamble_cs(struct radv_queue *queue,
3096 uint32_t scratch_size,
3097 uint32_t compute_scratch_size,
3098 uint32_t esgs_ring_size,
3099 uint32_t gsvs_ring_size,
3100 bool needs_tess_rings,
3101 bool needs_gds,
3102 bool needs_sample_positions,
3103 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
3104 struct radeon_cmdbuf **initial_preamble_cs,
3105 struct radeon_cmdbuf **continue_preamble_cs)
3106 {
3107 struct radeon_winsys_bo *scratch_bo = NULL;
3108 struct radeon_winsys_bo *descriptor_bo = NULL;
3109 struct radeon_winsys_bo *compute_scratch_bo = NULL;
3110 struct radeon_winsys_bo *esgs_ring_bo = NULL;
3111 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
3112 struct radeon_winsys_bo *tess_rings_bo = NULL;
3113 struct radeon_winsys_bo *gds_bo = NULL;
3114 struct radeon_winsys_bo *gds_oa_bo = NULL;
3115 struct radeon_cmdbuf *dest_cs[3] = {0};
3116 bool add_tess_rings = false, add_gds = false, add_sample_positions = false;
3117 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
3118 unsigned max_offchip_buffers;
3119 unsigned hs_offchip_param = 0;
3120 unsigned tess_offchip_ring_offset;
3121 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
3122 if (!queue->has_tess_rings) {
3123 if (needs_tess_rings)
3124 add_tess_rings = true;
3125 }
3126 if (!queue->has_gds) {
3127 if (needs_gds)
3128 add_gds = true;
3129 }
3130 if (!queue->has_sample_positions) {
3131 if (needs_sample_positions)
3132 add_sample_positions = true;
3133 }
3134 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
3135 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
3136 &max_offchip_buffers);
3137 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
3138 tess_offchip_ring_size = max_offchip_buffers *
3139 queue->device->tess_offchip_block_dw_size * 4;
3140
3141 if (scratch_size <= queue->scratch_size &&
3142 compute_scratch_size <= queue->compute_scratch_size &&
3143 esgs_ring_size <= queue->esgs_ring_size &&
3144 gsvs_ring_size <= queue->gsvs_ring_size &&
3145 !add_tess_rings && !add_gds && !add_sample_positions &&
3146 queue->initial_preamble_cs) {
3147 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3148 *initial_preamble_cs = queue->initial_preamble_cs;
3149 *continue_preamble_cs = queue->continue_preamble_cs;
3150 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size &&
3151 !needs_tess_rings && !needs_gds && !needs_sample_positions)
3152 *continue_preamble_cs = NULL;
3153 return VK_SUCCESS;
3154 }
3155
3156 if (scratch_size > queue->scratch_size) {
3157 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3158 scratch_size,
3159 4096,
3160 RADEON_DOMAIN_VRAM,
3161 ring_bo_flags,
3162 RADV_BO_PRIORITY_SCRATCH);
3163 if (!scratch_bo)
3164 goto fail;
3165 } else
3166 scratch_bo = queue->scratch_bo;
3167
3168 if (compute_scratch_size > queue->compute_scratch_size) {
3169 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3170 compute_scratch_size,
3171 4096,
3172 RADEON_DOMAIN_VRAM,
3173 ring_bo_flags,
3174 RADV_BO_PRIORITY_SCRATCH);
3175 if (!compute_scratch_bo)
3176 goto fail;
3177
3178 } else
3179 compute_scratch_bo = queue->compute_scratch_bo;
3180
3181 if (esgs_ring_size > queue->esgs_ring_size) {
3182 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3183 esgs_ring_size,
3184 4096,
3185 RADEON_DOMAIN_VRAM,
3186 ring_bo_flags,
3187 RADV_BO_PRIORITY_SCRATCH);
3188 if (!esgs_ring_bo)
3189 goto fail;
3190 } else {
3191 esgs_ring_bo = queue->esgs_ring_bo;
3192 esgs_ring_size = queue->esgs_ring_size;
3193 }
3194
3195 if (gsvs_ring_size > queue->gsvs_ring_size) {
3196 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3197 gsvs_ring_size,
3198 4096,
3199 RADEON_DOMAIN_VRAM,
3200 ring_bo_flags,
3201 RADV_BO_PRIORITY_SCRATCH);
3202 if (!gsvs_ring_bo)
3203 goto fail;
3204 } else {
3205 gsvs_ring_bo = queue->gsvs_ring_bo;
3206 gsvs_ring_size = queue->gsvs_ring_size;
3207 }
3208
3209 if (add_tess_rings) {
3210 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
3211 tess_offchip_ring_offset + tess_offchip_ring_size,
3212 256,
3213 RADEON_DOMAIN_VRAM,
3214 ring_bo_flags,
3215 RADV_BO_PRIORITY_SCRATCH);
3216 if (!tess_rings_bo)
3217 goto fail;
3218 } else {
3219 tess_rings_bo = queue->tess_rings_bo;
3220 }
3221
3222 if (add_gds) {
3223 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
3224
3225 /* 4 streamout GDS counters.
3226 * We need 256B (64 dw) of GDS, otherwise streamout hangs.
3227 */
3228 gds_bo = queue->device->ws->buffer_create(queue->device->ws,
3229 256, 4,
3230 RADEON_DOMAIN_GDS,
3231 ring_bo_flags,
3232 RADV_BO_PRIORITY_SCRATCH);
3233 if (!gds_bo)
3234 goto fail;
3235
3236 gds_oa_bo = queue->device->ws->buffer_create(queue->device->ws,
3237 4, 1,
3238 RADEON_DOMAIN_OA,
3239 ring_bo_flags,
3240 RADV_BO_PRIORITY_SCRATCH);
3241 if (!gds_oa_bo)
3242 goto fail;
3243 } else {
3244 gds_bo = queue->gds_bo;
3245 gds_oa_bo = queue->gds_oa_bo;
3246 }
3247
3248 if (scratch_bo != queue->scratch_bo ||
3249 esgs_ring_bo != queue->esgs_ring_bo ||
3250 gsvs_ring_bo != queue->gsvs_ring_bo ||
3251 tess_rings_bo != queue->tess_rings_bo ||
3252 add_sample_positions) {
3253 uint32_t size = 0;
3254 if (gsvs_ring_bo || esgs_ring_bo ||
3255 tess_rings_bo || add_sample_positions) {
3256 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
3257 if (add_sample_positions)
3258 size += 128; /* 64+32+16+8 = 120 bytes */
3259 }
3260 else if (scratch_bo)
3261 size = 8; /* 2 dword */
3262
3263 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
3264 size,
3265 4096,
3266 RADEON_DOMAIN_VRAM,
3267 RADEON_FLAG_CPU_ACCESS |
3268 RADEON_FLAG_NO_INTERPROCESS_SHARING |
3269 RADEON_FLAG_READ_ONLY,
3270 RADV_BO_PRIORITY_DESCRIPTOR);
3271 if (!descriptor_bo)
3272 goto fail;
3273 } else
3274 descriptor_bo = queue->descriptor_bo;
3275
3276 if (descriptor_bo != queue->descriptor_bo) {
3277 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
3278
3279 if (scratch_bo) {
3280 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
3281 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3282 S_008F04_SWIZZLE_ENABLE(1);
3283 map[0] = scratch_va;
3284 map[1] = rsrc1;
3285 }
3286
3287 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
3288 fill_geom_tess_rings(queue, map, add_sample_positions,
3289 esgs_ring_size, esgs_ring_bo,
3290 gsvs_ring_size, gsvs_ring_bo,
3291 tess_factor_ring_size,
3292 tess_offchip_ring_offset,
3293 tess_offchip_ring_size,
3294 tess_rings_bo);
3295
3296 queue->device->ws->buffer_unmap(descriptor_bo);
3297 }
3298
3299 for(int i = 0; i < 3; ++i) {
3300 struct radeon_cmdbuf *cs = NULL;
3301 cs = queue->device->ws->cs_create(queue->device->ws,
3302 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
3303 if (!cs)
3304 goto fail;
3305
3306 dest_cs[i] = cs;
3307
3308 if (scratch_bo)
3309 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
3310
3311 /* Emit initial configuration. */
3312 switch (queue->queue_family_index) {
3313 case RADV_QUEUE_GENERAL:
3314 radv_init_graphics_state(cs, queue);
3315 break;
3316 case RADV_QUEUE_COMPUTE:
3317 radv_init_compute_state(cs, queue);
3318 break;
3319 case RADV_QUEUE_TRANSFER:
3320 break;
3321 }
3322
3323 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
3324 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3325 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3326
3327 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3328 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3329 }
3330
3331 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
3332 gsvs_ring_bo, gsvs_ring_size);
3333 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
3334 tess_factor_ring_size, tess_rings_bo);
3335 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
3336 radv_emit_compute_scratch(queue, cs, compute_scratch_bo);
3337
3338 if (gds_bo)
3339 radv_cs_add_buffer(queue->device->ws, cs, gds_bo);
3340 if (gds_oa_bo)
3341 radv_cs_add_buffer(queue->device->ws, cs, gds_oa_bo);
3342
3343 if (i == 0) {
3344 si_cs_emit_cache_flush(cs,
3345 queue->device->physical_device->rad_info.chip_class,
3346 NULL, 0,
3347 queue->queue_family_index == RING_COMPUTE &&
3348 queue->device->physical_device->rad_info.chip_class >= GFX7,
3349 (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)) |
3350 RADV_CMD_FLAG_INV_ICACHE |
3351 RADV_CMD_FLAG_INV_SCACHE |
3352 RADV_CMD_FLAG_INV_VCACHE |
3353 RADV_CMD_FLAG_INV_L2 |
3354 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3355 } else if (i == 1) {
3356 si_cs_emit_cache_flush(cs,
3357 queue->device->physical_device->rad_info.chip_class,
3358 NULL, 0,
3359 queue->queue_family_index == RING_COMPUTE &&
3360 queue->device->physical_device->rad_info.chip_class >= GFX7,
3361 RADV_CMD_FLAG_INV_ICACHE |
3362 RADV_CMD_FLAG_INV_SCACHE |
3363 RADV_CMD_FLAG_INV_VCACHE |
3364 RADV_CMD_FLAG_INV_L2 |
3365 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3366 }
3367
3368 if (!queue->device->ws->cs_finalize(cs))
3369 goto fail;
3370 }
3371
3372 if (queue->initial_full_flush_preamble_cs)
3373 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
3374
3375 if (queue->initial_preamble_cs)
3376 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
3377
3378 if (queue->continue_preamble_cs)
3379 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
3380
3381 queue->initial_full_flush_preamble_cs = dest_cs[0];
3382 queue->initial_preamble_cs = dest_cs[1];
3383 queue->continue_preamble_cs = dest_cs[2];
3384
3385 if (scratch_bo != queue->scratch_bo) {
3386 if (queue->scratch_bo)
3387 queue->device->ws->buffer_destroy(queue->scratch_bo);
3388 queue->scratch_bo = scratch_bo;
3389 queue->scratch_size = scratch_size;
3390 }
3391
3392 if (compute_scratch_bo != queue->compute_scratch_bo) {
3393 if (queue->compute_scratch_bo)
3394 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
3395 queue->compute_scratch_bo = compute_scratch_bo;
3396 queue->compute_scratch_size = compute_scratch_size;
3397 }
3398
3399 if (esgs_ring_bo != queue->esgs_ring_bo) {
3400 if (queue->esgs_ring_bo)
3401 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
3402 queue->esgs_ring_bo = esgs_ring_bo;
3403 queue->esgs_ring_size = esgs_ring_size;
3404 }
3405
3406 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
3407 if (queue->gsvs_ring_bo)
3408 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
3409 queue->gsvs_ring_bo = gsvs_ring_bo;
3410 queue->gsvs_ring_size = gsvs_ring_size;
3411 }
3412
3413 if (tess_rings_bo != queue->tess_rings_bo) {
3414 queue->tess_rings_bo = tess_rings_bo;
3415 queue->has_tess_rings = true;
3416 }
3417
3418 if (gds_bo != queue->gds_bo) {
3419 queue->gds_bo = gds_bo;
3420 queue->has_gds = true;
3421 }
3422
3423 if (gds_oa_bo != queue->gds_oa_bo)
3424 queue->gds_oa_bo = gds_oa_bo;
3425
3426 if (descriptor_bo != queue->descriptor_bo) {
3427 if (queue->descriptor_bo)
3428 queue->device->ws->buffer_destroy(queue->descriptor_bo);
3429
3430 queue->descriptor_bo = descriptor_bo;
3431 }
3432
3433 if (add_sample_positions)
3434 queue->has_sample_positions = true;
3435
3436 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3437 *initial_preamble_cs = queue->initial_preamble_cs;
3438 *continue_preamble_cs = queue->continue_preamble_cs;
3439 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
3440 *continue_preamble_cs = NULL;
3441 return VK_SUCCESS;
3442 fail:
3443 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
3444 if (dest_cs[i])
3445 queue->device->ws->cs_destroy(dest_cs[i]);
3446 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
3447 queue->device->ws->buffer_destroy(descriptor_bo);
3448 if (scratch_bo && scratch_bo != queue->scratch_bo)
3449 queue->device->ws->buffer_destroy(scratch_bo);
3450 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
3451 queue->device->ws->buffer_destroy(compute_scratch_bo);
3452 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
3453 queue->device->ws->buffer_destroy(esgs_ring_bo);
3454 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
3455 queue->device->ws->buffer_destroy(gsvs_ring_bo);
3456 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
3457 queue->device->ws->buffer_destroy(tess_rings_bo);
3458 if (gds_bo && gds_bo != queue->gds_bo)
3459 queue->device->ws->buffer_destroy(gds_bo);
3460 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
3461 queue->device->ws->buffer_destroy(gds_oa_bo);
3462
3463 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3464 }
3465
3466 static VkResult radv_alloc_sem_counts(struct radv_device *device,
3467 struct radv_winsys_sem_counts *counts,
3468 int num_sems,
3469 struct radv_semaphore_part **sems,
3470 const uint64_t *timeline_values,
3471 VkFence _fence,
3472 bool is_signal)
3473 {
3474 int syncobj_idx = 0, sem_idx = 0;
3475
3476 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
3477 return VK_SUCCESS;
3478
3479 for (uint32_t i = 0; i < num_sems; i++) {
3480 switch(sems[i]->kind) {
3481 case RADV_SEMAPHORE_SYNCOBJ:
3482 counts->syncobj_count++;
3483 break;
3484 case RADV_SEMAPHORE_WINSYS:
3485 counts->sem_count++;
3486 break;
3487 case RADV_SEMAPHORE_NONE:
3488 break;
3489 case RADV_SEMAPHORE_TIMELINE:
3490 counts->syncobj_count++;
3491 break;
3492 }
3493 }
3494
3495 if (_fence != VK_NULL_HANDLE) {
3496 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3497 if (fence->temp_syncobj || fence->syncobj)
3498 counts->syncobj_count++;
3499 }
3500
3501 if (counts->syncobj_count) {
3502 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
3503 if (!counts->syncobj)
3504 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3505 }
3506
3507 if (counts->sem_count) {
3508 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
3509 if (!counts->sem) {
3510 free(counts->syncobj);
3511 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3512 }
3513 }
3514
3515 for (uint32_t i = 0; i < num_sems; i++) {
3516 switch(sems[i]->kind) {
3517 case RADV_SEMAPHORE_NONE:
3518 unreachable("Empty semaphore");
3519 break;
3520 case RADV_SEMAPHORE_SYNCOBJ:
3521 counts->syncobj[syncobj_idx++] = sems[i]->syncobj;
3522 break;
3523 case RADV_SEMAPHORE_WINSYS:
3524 counts->sem[sem_idx++] = sems[i]->ws_sem;
3525 break;
3526 case RADV_SEMAPHORE_TIMELINE: {
3527 pthread_mutex_lock(&sems[i]->timeline.mutex);
3528 struct radv_timeline_point *point = NULL;
3529 if (is_signal) {
3530 point = radv_timeline_add_point_locked(device, &sems[i]->timeline, timeline_values[i]);
3531 } else {
3532 point = radv_timeline_find_point_at_least_locked(device, &sems[i]->timeline, timeline_values[i]);
3533 }
3534
3535 pthread_mutex_unlock(&sems[i]->timeline.mutex);
3536
3537 if (point) {
3538 counts->syncobj[syncobj_idx++] = point->syncobj;
3539 } else {
3540 /* Explicitly remove the semaphore so we might not find
3541 * a point later post-submit. */
3542 sems[i] = NULL;
3543 }
3544 break;
3545 }
3546 }
3547 }
3548
3549 if (_fence != VK_NULL_HANDLE) {
3550 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3551 if (fence->temp_syncobj)
3552 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
3553 else if (fence->syncobj)
3554 counts->syncobj[syncobj_idx++] = fence->syncobj;
3555 }
3556
3557 assert(syncobj_idx <= counts->syncobj_count);
3558 counts->syncobj_count = syncobj_idx;
3559
3560 return VK_SUCCESS;
3561 }
3562
3563 static void
3564 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
3565 {
3566 free(sem_info->wait.syncobj);
3567 free(sem_info->wait.sem);
3568 free(sem_info->signal.syncobj);
3569 free(sem_info->signal.sem);
3570 }
3571
3572
3573 static void radv_free_temp_syncobjs(struct radv_device *device,
3574 int num_sems,
3575 struct radv_semaphore_part *sems)
3576 {
3577 for (uint32_t i = 0; i < num_sems; i++) {
3578 radv_destroy_semaphore_part(device, sems + i);
3579 }
3580 }
3581
3582 static VkResult
3583 radv_alloc_sem_info(struct radv_device *device,
3584 struct radv_winsys_sem_info *sem_info,
3585 int num_wait_sems,
3586 struct radv_semaphore_part **wait_sems,
3587 const uint64_t *wait_values,
3588 int num_signal_sems,
3589 struct radv_semaphore_part **signal_sems,
3590 const uint64_t *signal_values,
3591 VkFence fence)
3592 {
3593 VkResult ret;
3594 memset(sem_info, 0, sizeof(*sem_info));
3595
3596 ret = radv_alloc_sem_counts(device, &sem_info->wait, num_wait_sems, wait_sems, wait_values, VK_NULL_HANDLE, false);
3597 if (ret)
3598 return ret;
3599 ret = radv_alloc_sem_counts(device, &sem_info->signal, num_signal_sems, signal_sems, signal_values, fence, true);
3600 if (ret)
3601 radv_free_sem_info(sem_info);
3602
3603 /* caller can override these */
3604 sem_info->cs_emit_wait = true;
3605 sem_info->cs_emit_signal = true;
3606 return ret;
3607 }
3608
3609 static void
3610 radv_finalize_timelines(struct radv_device *device,
3611 uint32_t num_wait_sems,
3612 struct radv_semaphore_part **wait_sems,
3613 const uint64_t *wait_values,
3614 uint32_t num_signal_sems,
3615 struct radv_semaphore_part **signal_sems,
3616 const uint64_t *signal_values,
3617 struct list_head *processing_list)
3618 {
3619 for (uint32_t i = 0; i < num_wait_sems; ++i) {
3620 if (wait_sems[i] && wait_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
3621 pthread_mutex_lock(&wait_sems[i]->timeline.mutex);
3622 struct radv_timeline_point *point =
3623 radv_timeline_find_point_at_least_locked(device, &wait_sems[i]->timeline, wait_values[i]);
3624 if (point)
3625 --point->wait_count;
3626 pthread_mutex_unlock(&wait_sems[i]->timeline.mutex);
3627 }
3628 }
3629 for (uint32_t i = 0; i < num_signal_sems; ++i) {
3630 if (signal_sems[i] && signal_sems[i]->kind == RADV_SEMAPHORE_TIMELINE) {
3631 pthread_mutex_lock(&signal_sems[i]->timeline.mutex);
3632 struct radv_timeline_point *point =
3633 radv_timeline_find_point_at_least_locked(device, &signal_sems[i]->timeline, signal_values[i]);
3634 if (point) {
3635 signal_sems[i]->timeline.highest_submitted =
3636 MAX2(signal_sems[i]->timeline.highest_submitted, point->value);
3637 point->wait_count--;
3638 }
3639 radv_timeline_trigger_waiters_locked(&signal_sems[i]->timeline, processing_list);
3640 pthread_mutex_unlock(&signal_sems[i]->timeline.mutex);
3641 }
3642 }
3643 }
3644
3645 static void
3646 radv_sparse_buffer_bind_memory(struct radv_device *device,
3647 const VkSparseBufferMemoryBindInfo *bind)
3648 {
3649 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
3650
3651 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3652 struct radv_device_memory *mem = NULL;
3653
3654 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3655 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3656
3657 device->ws->buffer_virtual_bind(buffer->bo,
3658 bind->pBinds[i].resourceOffset,
3659 bind->pBinds[i].size,
3660 mem ? mem->bo : NULL,
3661 bind->pBinds[i].memoryOffset);
3662 }
3663 }
3664
3665 static void
3666 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
3667 const VkSparseImageOpaqueMemoryBindInfo *bind)
3668 {
3669 RADV_FROM_HANDLE(radv_image, image, bind->image);
3670
3671 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3672 struct radv_device_memory *mem = NULL;
3673
3674 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3675 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3676
3677 device->ws->buffer_virtual_bind(image->bo,
3678 bind->pBinds[i].resourceOffset,
3679 bind->pBinds[i].size,
3680 mem ? mem->bo : NULL,
3681 bind->pBinds[i].memoryOffset);
3682 }
3683 }
3684
3685 static VkResult
3686 radv_get_preambles(struct radv_queue *queue,
3687 const VkCommandBuffer *cmd_buffers,
3688 uint32_t cmd_buffer_count,
3689 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
3690 struct radeon_cmdbuf **initial_preamble_cs,
3691 struct radeon_cmdbuf **continue_preamble_cs)
3692 {
3693 uint32_t scratch_size = 0;
3694 uint32_t compute_scratch_size = 0;
3695 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
3696 bool tess_rings_needed = false;
3697 bool gds_needed = false;
3698 bool sample_positions_needed = false;
3699
3700 for (uint32_t j = 0; j < cmd_buffer_count; j++) {
3701 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
3702 cmd_buffers[j]);
3703
3704 scratch_size = MAX2(scratch_size, cmd_buffer->scratch_size_needed);
3705 compute_scratch_size = MAX2(compute_scratch_size,
3706 cmd_buffer->compute_scratch_size_needed);
3707 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
3708 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
3709 tess_rings_needed |= cmd_buffer->tess_rings_needed;
3710 gds_needed |= cmd_buffer->gds_needed;
3711 sample_positions_needed |= cmd_buffer->sample_positions_needed;
3712 }
3713
3714 return radv_get_preamble_cs(queue, scratch_size, compute_scratch_size,
3715 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
3716 gds_needed, sample_positions_needed,
3717 initial_full_flush_preamble_cs,
3718 initial_preamble_cs, continue_preamble_cs);
3719 }
3720
3721 struct radv_deferred_queue_submission {
3722 struct radv_queue *queue;
3723 VkCommandBuffer *cmd_buffers;
3724 uint32_t cmd_buffer_count;
3725
3726 /* Sparse bindings that happen on a queue. */
3727 VkSparseBufferMemoryBindInfo *buffer_binds;
3728 uint32_t buffer_bind_count;
3729 VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
3730 uint32_t image_opaque_bind_count;
3731
3732 bool flush_caches;
3733 VkShaderStageFlags wait_dst_stage_mask;
3734 struct radv_semaphore_part **wait_semaphores;
3735 uint32_t wait_semaphore_count;
3736 struct radv_semaphore_part **signal_semaphores;
3737 uint32_t signal_semaphore_count;
3738 VkFence fence;
3739
3740 uint64_t *wait_values;
3741 uint64_t *signal_values;
3742
3743 struct radv_semaphore_part *temporary_semaphore_parts;
3744 uint32_t temporary_semaphore_part_count;
3745
3746 struct list_head queue_pending_list;
3747 uint32_t submission_wait_count;
3748 struct radv_timeline_waiter *wait_nodes;
3749
3750 struct list_head processing_list;
3751 };
3752
3753 struct radv_queue_submission {
3754 const VkCommandBuffer *cmd_buffers;
3755 uint32_t cmd_buffer_count;
3756
3757 /* Sparse bindings that happen on a queue. */
3758 const VkSparseBufferMemoryBindInfo *buffer_binds;
3759 uint32_t buffer_bind_count;
3760 const VkSparseImageOpaqueMemoryBindInfo *image_opaque_binds;
3761 uint32_t image_opaque_bind_count;
3762
3763 bool flush_caches;
3764 VkPipelineStageFlags wait_dst_stage_mask;
3765 const VkSemaphore *wait_semaphores;
3766 uint32_t wait_semaphore_count;
3767 const VkSemaphore *signal_semaphores;
3768 uint32_t signal_semaphore_count;
3769 VkFence fence;
3770
3771 const uint64_t *wait_values;
3772 uint32_t wait_value_count;
3773 const uint64_t *signal_values;
3774 uint32_t signal_value_count;
3775 };
3776
3777 static VkResult
3778 radv_create_deferred_submission(struct radv_queue *queue,
3779 const struct radv_queue_submission *submission,
3780 struct radv_deferred_queue_submission **out)
3781 {
3782 struct radv_deferred_queue_submission *deferred = NULL;
3783 size_t size = sizeof(struct radv_deferred_queue_submission);
3784
3785 uint32_t temporary_count = 0;
3786 for (uint32_t i = 0; i < submission->wait_semaphore_count; ++i) {
3787 RADV_FROM_HANDLE(radv_semaphore, semaphore, submission->wait_semaphores[i]);
3788 if (semaphore->temporary.kind != RADV_SEMAPHORE_NONE)
3789 ++temporary_count;
3790 }
3791
3792 size += submission->cmd_buffer_count * sizeof(VkCommandBuffer);
3793 size += submission->buffer_bind_count * sizeof(VkSparseBufferMemoryBindInfo);
3794 size += submission->image_opaque_bind_count * sizeof(VkSparseImageOpaqueMemoryBindInfo);
3795 size += submission->wait_semaphore_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 }