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