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