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