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