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