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