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