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