radv: enable secure compile support
[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, 10),
1951
1952 /* Allow system exit calls for the forked process */
1953 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1954 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_exit_group, 9, 0),
1955
1956 /* Allow system read calls */
1957 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1958 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_read, 7, 0),
1959
1960 /* Allow system write 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_write, 5, 0),
1963
1964 /* Allow system brk calls (we need this for malloc) */
1965 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1966 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_brk, 3, 0),
1967
1968 /* Futex is required for mutex locks */
1969 BPF_STMT(BPF_LD + BPF_W + BPF_ABS, (offsetof(struct seccomp_data, nr))),
1970 BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_futex, 1, 0),
1971
1972 /* Return error if we hit a system call not on the whitelist */
1973 BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
1974
1975 /* Allow whitelisted system calls */
1976 BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW),
1977 };
1978
1979 struct sock_fprog prog = {
1980 .len = (unsigned short)(sizeof(filter) / sizeof(filter[0])),
1981 .filter = filter,
1982 };
1983
1984 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0))
1985 return -1;
1986
1987 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog))
1988 return -1;
1989
1990 return 0;
1991 }
1992
1993 static void run_secure_compile_device(struct radv_device *device, unsigned process,
1994 int *fd_secure_input, int *fd_secure_output)
1995 {
1996 enum radv_secure_compile_type sc_type;
1997 if (install_seccomp_filter() == -1) {
1998 sc_type = RADV_SC_TYPE_INIT_FAILURE;
1999 } else {
2000 sc_type = RADV_SC_TYPE_INIT_SUCCESS;
2001 device->sc_state->secure_compile_processes[process].fd_secure_input = fd_secure_input[0];
2002 device->sc_state->secure_compile_processes[process].fd_secure_output = fd_secure_output[1];
2003 }
2004
2005 write(fd_secure_output[1], &sc_type, sizeof(sc_type));
2006
2007 if (sc_type == RADV_SC_TYPE_INIT_FAILURE)
2008 goto secure_compile_exit;
2009
2010 while (true) {
2011 read(fd_secure_input[0], &sc_type, sizeof(sc_type));
2012
2013 if (sc_type == RADV_SC_TYPE_COMPILE_PIPELINE) {
2014 struct radv_pipeline *pipeline;
2015
2016 pipeline = vk_zalloc2(&device->alloc, NULL, sizeof(*pipeline), 8,
2017 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2018
2019 pipeline->device = device;
2020
2021 /* Read pipeline layout */
2022 struct radv_pipeline_layout layout;
2023 read(fd_secure_input[0], &layout, sizeof(struct radv_pipeline_layout));
2024 read(fd_secure_input[0], &layout.num_sets, sizeof(uint32_t));
2025 for (uint32_t set = 0; set < layout.num_sets; set++) {
2026 uint32_t layout_size;
2027 read(fd_secure_input[0], &layout_size, sizeof(uint32_t));
2028 layout.set[set].layout = malloc(layout_size);
2029 layout.set[set].layout->layout_size = layout_size;
2030 read(fd_secure_input[0], layout.set[set].layout, layout.set[set].layout->layout_size);
2031 }
2032
2033 pipeline->layout = &layout;
2034
2035 /* Read pipeline key */
2036 struct radv_pipeline_key key;
2037 read(fd_secure_input[0], &key, sizeof(struct radv_pipeline_key));
2038
2039 /* Read pipeline create flags */
2040 VkPipelineCreateFlags flags;
2041 read(fd_secure_input[0], &flags, sizeof(VkPipelineCreateFlags));
2042
2043 /* Read stage and shader information */
2044 uint32_t num_stages;
2045 const VkPipelineShaderStageCreateInfo *pStages[MESA_SHADER_STAGES] = { 0, };
2046 read(fd_secure_input[0], &num_stages, sizeof(uint32_t));
2047 for (uint32_t i = 0; i < num_stages; i++) {
2048
2049 /* Read stage */
2050 gl_shader_stage stage;
2051 read(fd_secure_input[0], &stage, sizeof(gl_shader_stage));
2052
2053 VkPipelineShaderStageCreateInfo *pStage = calloc(1, sizeof(VkPipelineShaderStageCreateInfo));
2054
2055 /* Read entry point name */
2056 size_t name_size;
2057 read(fd_secure_input[0], &name_size, sizeof(size_t));
2058 char *ep_name = malloc(name_size);
2059 read(fd_secure_input[0], ep_name, name_size);
2060 pStage->pName = ep_name;
2061
2062 /* Read shader module */
2063 size_t module_size;
2064 read(fd_secure_input[0], &module_size, sizeof(size_t));
2065 struct radv_shader_module *module = malloc(module_size);
2066 read(fd_secure_input[0], module, module_size);
2067 pStage->module = radv_shader_module_to_handle(module);
2068
2069 /* Read specialization info */
2070 bool has_spec_info;
2071 read(fd_secure_input[0], &has_spec_info, sizeof(bool));
2072 if (has_spec_info) {
2073 VkSpecializationInfo *specInfo = malloc(sizeof(VkSpecializationInfo));
2074 pStage->pSpecializationInfo = specInfo;
2075
2076 read(fd_secure_input[0], &specInfo->dataSize, sizeof(size_t));
2077
2078 void *si_data = malloc(specInfo->dataSize);
2079 read(fd_secure_input[0], si_data, specInfo->dataSize);
2080 specInfo->pData = si_data;
2081
2082 read(fd_secure_input[0], &specInfo->mapEntryCount, sizeof(uint32_t));
2083 VkSpecializationMapEntry *mapEntries = malloc(sizeof(VkSpecializationMapEntry) * specInfo->mapEntryCount);
2084 for (uint32_t j = 0; j < specInfo->mapEntryCount; j++)
2085 read(fd_secure_input[0], &mapEntries[j], sizeof(VkSpecializationMapEntry));
2086
2087 specInfo->pMapEntries = mapEntries;
2088 }
2089
2090 pStages[stage] = pStage;
2091 }
2092
2093 /* Compile the shaders */
2094 VkPipelineCreationFeedbackEXT *stage_feedbacks[MESA_SHADER_STAGES] = { 0 };
2095 radv_create_shaders(pipeline, device, NULL, &key, pStages, flags, NULL, stage_feedbacks);
2096
2097 /* free memory allocated above */
2098 for (uint32_t set = 0; set < layout.num_sets; set++)
2099 free(layout.set[set].layout);
2100
2101 for (uint32_t i = 0; i < MESA_SHADER_STAGES; i++) {
2102 if (!pStages[i])
2103 continue;
2104
2105 free((void *) pStages[i]->pName);
2106 free(radv_shader_module_from_handle(pStages[i]->module));
2107 if (pStages[i]->pSpecializationInfo) {
2108 free((void *) pStages[i]->pSpecializationInfo->pData);
2109 free((void *) pStages[i]->pSpecializationInfo->pMapEntries);
2110 free((void *) pStages[i]->pSpecializationInfo);
2111 }
2112 free((void *) pStages[i]);
2113 }
2114
2115 vk_free(&device->alloc, pipeline);
2116
2117 sc_type = RADV_SC_TYPE_COMPILE_PIPELINE_FINISHED;
2118 write(fd_secure_output[1], &sc_type, sizeof(sc_type));
2119
2120 } else if (sc_type == RADV_SC_TYPE_DESTROY_DEVICE) {
2121 goto secure_compile_exit;
2122 }
2123 }
2124
2125 secure_compile_exit:
2126 close(fd_secure_input[1]);
2127 close(fd_secure_input[0]);
2128 close(fd_secure_output[1]);
2129 close(fd_secure_output[0]);
2130 _exit(0);
2131 }
2132
2133 static void destroy_secure_compile_device(struct radv_device *device, unsigned process)
2134 {
2135 int fd_secure_input = device->sc_state->secure_compile_processes[process].fd_secure_input;
2136
2137 enum radv_secure_compile_type sc_type = RADV_SC_TYPE_DESTROY_DEVICE;
2138 write(fd_secure_input, &sc_type, sizeof(sc_type));
2139
2140 close(device->sc_state->secure_compile_processes[process].fd_secure_input);
2141 close(device->sc_state->secure_compile_processes[process].fd_secure_output);
2142
2143 int status;
2144 waitpid(device->sc_state->secure_compile_processes[process].sc_pid, &status, 0);
2145 }
2146
2147 static VkResult fork_secure_compile_device(struct radv_device *device)
2148 {
2149 device->sc_state = vk_zalloc(&device->alloc,
2150 sizeof(struct radv_secure_compile_state),
2151 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2152
2153 mtx_init(&device->sc_state->secure_compile_mutex, mtx_plain);
2154
2155 uint8_t sc_threads = device->instance->num_sc_threads;
2156 int fd_secure_input[MAX_SC_PROCS][2];
2157 int fd_secure_output[MAX_SC_PROCS][2];
2158
2159 /* create pipe descriptors (used to communicate between processes) */
2160 for (unsigned i = 0; i < sc_threads; i++) {
2161 if (pipe(fd_secure_input[i]) == -1 ||
2162 pipe(fd_secure_output[i]) == -1) {
2163 return VK_ERROR_INITIALIZATION_FAILED;
2164 }
2165 }
2166
2167 device->sc_state->secure_compile_processes = vk_zalloc(&device->alloc,
2168 sizeof(struct radv_secure_compile_process) * sc_threads, 8,
2169 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2170
2171 for (unsigned process = 0; process < sc_threads; process++) {
2172 if ((device->sc_state->secure_compile_processes[process].sc_pid = fork()) == 0) {
2173 device->sc_state->secure_compile_thread_counter = process;
2174 run_secure_compile_device(device, process, fd_secure_input[process], fd_secure_output[process]);
2175 } else {
2176 if (device->sc_state->secure_compile_processes[process].sc_pid == -1)
2177 return VK_ERROR_INITIALIZATION_FAILED;
2178
2179 /* Read the init result returned from the secure process */
2180 enum radv_secure_compile_type sc_type;
2181 read(fd_secure_output[process][0], &sc_type, sizeof(sc_type));
2182
2183 if (sc_type == RADV_SC_TYPE_INIT_FAILURE) {
2184 close(fd_secure_input[process][0]);
2185 close(fd_secure_input[process][1]);
2186 close(fd_secure_output[process][1]);
2187 close(fd_secure_output[process][0]);
2188 int status;
2189 waitpid(device->sc_state->secure_compile_processes[process].sc_pid, &status, 0);
2190
2191 /* Destroy any forks that were created sucessfully */
2192 for (unsigned i = 0; i < process; i++) {
2193 destroy_secure_compile_device(device, i);
2194 }
2195
2196 return VK_ERROR_INITIALIZATION_FAILED;
2197 } else {
2198 assert(sc_type == RADV_SC_TYPE_INIT_SUCCESS);
2199 device->sc_state->secure_compile_processes[process].fd_secure_input = fd_secure_input[process][1];
2200 device->sc_state->secure_compile_processes[process].fd_secure_output = fd_secure_output[process][0];
2201 }
2202 }
2203 }
2204
2205 return VK_SUCCESS;
2206 }
2207
2208 VkResult radv_CreateDevice(
2209 VkPhysicalDevice physicalDevice,
2210 const VkDeviceCreateInfo* pCreateInfo,
2211 const VkAllocationCallbacks* pAllocator,
2212 VkDevice* pDevice)
2213 {
2214 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
2215 VkResult result;
2216 struct radv_device *device;
2217
2218 bool keep_shader_info = false;
2219
2220 /* Check enabled features */
2221 if (pCreateInfo->pEnabledFeatures) {
2222 VkPhysicalDeviceFeatures supported_features;
2223 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2224 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2225 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
2226 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2227 for (uint32_t i = 0; i < num_features; i++) {
2228 if (enabled_feature[i] && !supported_feature[i])
2229 return vk_error(physical_device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
2230 }
2231 }
2232
2233 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
2234 sizeof(*device), 8,
2235 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2236 if (!device)
2237 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2238
2239 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
2240 device->instance = physical_device->instance;
2241 device->physical_device = physical_device;
2242
2243 device->ws = physical_device->ws;
2244 if (pAllocator)
2245 device->alloc = *pAllocator;
2246 else
2247 device->alloc = physical_device->instance->alloc;
2248
2249 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
2250 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
2251 int index = radv_get_device_extension_index(ext_name);
2252 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
2253 vk_free(&device->alloc, device);
2254 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
2255 }
2256
2257 device->enabled_extensions.extensions[index] = true;
2258 }
2259
2260 keep_shader_info = device->enabled_extensions.AMD_shader_info;
2261
2262 /* With update after bind we can't attach bo's to the command buffer
2263 * from the descriptor set anymore, so we have to use a global BO list.
2264 */
2265 device->use_global_bo_list =
2266 (device->instance->perftest_flags & RADV_PERFTEST_BO_LIST) ||
2267 device->enabled_extensions.EXT_descriptor_indexing ||
2268 device->enabled_extensions.EXT_buffer_device_address;
2269
2270 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
2271 pCreateInfo->pEnabledFeatures->robustBufferAccess;
2272
2273 mtx_init(&device->shader_slab_mutex, mtx_plain);
2274 list_inithead(&device->shader_slabs);
2275
2276 radv_bo_list_init(&device->bo_list);
2277
2278 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
2279 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
2280 uint32_t qfi = queue_create->queueFamilyIndex;
2281 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
2282 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
2283
2284 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
2285
2286 device->queues[qfi] = vk_alloc(&device->alloc,
2287 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2288 if (!device->queues[qfi]) {
2289 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2290 goto fail;
2291 }
2292
2293 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
2294
2295 device->queue_count[qfi] = queue_create->queueCount;
2296
2297 for (unsigned q = 0; q < queue_create->queueCount; q++) {
2298 result = radv_queue_init(device, &device->queues[qfi][q],
2299 qfi, q, queue_create->flags,
2300 global_priority);
2301 if (result != VK_SUCCESS)
2302 goto fail;
2303 }
2304 }
2305
2306 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
2307 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
2308
2309 /* Disable DFSM by default. As of 2019-09-15 Talos on Low is still 3% slower on Raven. */
2310 device->dfsm_allowed = device->pbb_allowed &&
2311 (device->instance->perftest_flags & RADV_PERFTEST_DFSM);
2312
2313 #ifdef ANDROID
2314 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
2315 #endif
2316
2317 /* The maximum number of scratch waves. Scratch space isn't divided
2318 * evenly between CUs. The number is only a function of the number of CUs.
2319 * We can decrease the constant to decrease the scratch buffer size.
2320 *
2321 * sctx->scratch_waves must be >= the maximum possible size of
2322 * 1 threadgroup, so that the hw doesn't hang from being unable
2323 * to start any.
2324 *
2325 * The recommended value is 4 per CU at most. Higher numbers don't
2326 * bring much benefit, but they still occupy chip resources (think
2327 * async compute). I've seen ~2% performance difference between 4 and 32.
2328 */
2329 uint32_t max_threads_per_block = 2048;
2330 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
2331 max_threads_per_block / 64);
2332
2333 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1) |
2334 S_00B800_CS_W32_EN(device->physical_device->cs_wave_size == 32);
2335
2336 if (device->physical_device->rad_info.chip_class >= GFX7) {
2337 /* If the KMD allows it (there is a KMD hw register for it),
2338 * allow launching waves out-of-order.
2339 */
2340 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
2341 }
2342
2343 radv_device_init_gs_info(device);
2344
2345 device->tess_offchip_block_dw_size =
2346 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
2347
2348 if (getenv("RADV_TRACE_FILE")) {
2349 const char *filename = getenv("RADV_TRACE_FILE");
2350
2351 keep_shader_info = true;
2352
2353 if (!radv_init_trace(device))
2354 goto fail;
2355
2356 fprintf(stderr, "*****************************************************************************\n");
2357 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
2358 fprintf(stderr, "*****************************************************************************\n");
2359
2360 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
2361 radv_dump_enabled_options(device, stderr);
2362 }
2363
2364 /* Temporarily disable secure compile while we create meta shaders, etc */
2365 uint8_t sc_threads = device->instance->num_sc_threads;
2366 if (sc_threads)
2367 device->instance->num_sc_threads = 0;
2368
2369 device->keep_shader_info = keep_shader_info;
2370 result = radv_device_init_meta(device);
2371 if (result != VK_SUCCESS)
2372 goto fail;
2373
2374 radv_device_init_msaa(device);
2375
2376 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
2377 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
2378 switch (family) {
2379 case RADV_QUEUE_GENERAL:
2380 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
2381 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_LOAD_ENABLE(1));
2382 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_SHADOW_ENABLE(1));
2383 break;
2384 case RADV_QUEUE_COMPUTE:
2385 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
2386 radeon_emit(device->empty_cs[family], 0);
2387 break;
2388 }
2389 device->ws->cs_finalize(device->empty_cs[family]);
2390 }
2391
2392 if (device->physical_device->rad_info.chip_class >= GFX7)
2393 cik_create_gfx_config(device);
2394
2395 VkPipelineCacheCreateInfo ci;
2396 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2397 ci.pNext = NULL;
2398 ci.flags = 0;
2399 ci.pInitialData = NULL;
2400 ci.initialDataSize = 0;
2401 VkPipelineCache pc;
2402 result = radv_CreatePipelineCache(radv_device_to_handle(device),
2403 &ci, NULL, &pc);
2404 if (result != VK_SUCCESS)
2405 goto fail_meta;
2406
2407 device->mem_cache = radv_pipeline_cache_from_handle(pc);
2408
2409 device->force_aniso =
2410 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
2411 if (device->force_aniso >= 0) {
2412 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
2413 1 << util_logbase2(device->force_aniso));
2414 }
2415
2416 /* Fork device for secure compile as required */
2417 device->instance->num_sc_threads = sc_threads;
2418 if (radv_device_use_secure_compile(device->instance)) {
2419 result = fork_secure_compile_device(device);
2420 if (result != VK_SUCCESS)
2421 goto fail_meta;
2422 }
2423
2424 *pDevice = radv_device_to_handle(device);
2425 return VK_SUCCESS;
2426
2427 fail_meta:
2428 radv_device_finish_meta(device);
2429 fail:
2430 radv_bo_list_finish(&device->bo_list);
2431
2432 if (device->trace_bo)
2433 device->ws->buffer_destroy(device->trace_bo);
2434
2435 if (device->gfx_init)
2436 device->ws->buffer_destroy(device->gfx_init);
2437
2438 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2439 for (unsigned q = 0; q < device->queue_count[i]; q++)
2440 radv_queue_finish(&device->queues[i][q]);
2441 if (device->queue_count[i])
2442 vk_free(&device->alloc, device->queues[i]);
2443 }
2444
2445 vk_free(&device->alloc, device);
2446 return result;
2447 }
2448
2449 void radv_DestroyDevice(
2450 VkDevice _device,
2451 const VkAllocationCallbacks* pAllocator)
2452 {
2453 RADV_FROM_HANDLE(radv_device, device, _device);
2454
2455 if (!device)
2456 return;
2457
2458 if (device->trace_bo)
2459 device->ws->buffer_destroy(device->trace_bo);
2460
2461 if (device->gfx_init)
2462 device->ws->buffer_destroy(device->gfx_init);
2463
2464 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2465 for (unsigned q = 0; q < device->queue_count[i]; q++)
2466 radv_queue_finish(&device->queues[i][q]);
2467 if (device->queue_count[i])
2468 vk_free(&device->alloc, device->queues[i]);
2469 if (device->empty_cs[i])
2470 device->ws->cs_destroy(device->empty_cs[i]);
2471 }
2472 radv_device_finish_meta(device);
2473
2474 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
2475 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
2476
2477 radv_destroy_shader_slabs(device);
2478
2479 radv_bo_list_finish(&device->bo_list);
2480
2481 if (radv_device_use_secure_compile(device->instance)) {
2482 for (unsigned i = 0; i < device->instance->num_sc_threads; i++ ) {
2483 destroy_secure_compile_device(device, i);
2484 }
2485 }
2486
2487 if (device->sc_state)
2488 vk_free(&device->alloc, device->sc_state->secure_compile_processes);
2489 vk_free(&device->alloc, device->sc_state);
2490 vk_free(&device->alloc, device);
2491 }
2492
2493 VkResult radv_EnumerateInstanceLayerProperties(
2494 uint32_t* pPropertyCount,
2495 VkLayerProperties* pProperties)
2496 {
2497 if (pProperties == NULL) {
2498 *pPropertyCount = 0;
2499 return VK_SUCCESS;
2500 }
2501
2502 /* None supported at this time */
2503 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2504 }
2505
2506 VkResult radv_EnumerateDeviceLayerProperties(
2507 VkPhysicalDevice physicalDevice,
2508 uint32_t* pPropertyCount,
2509 VkLayerProperties* pProperties)
2510 {
2511 if (pProperties == NULL) {
2512 *pPropertyCount = 0;
2513 return VK_SUCCESS;
2514 }
2515
2516 /* None supported at this time */
2517 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2518 }
2519
2520 void radv_GetDeviceQueue2(
2521 VkDevice _device,
2522 const VkDeviceQueueInfo2* pQueueInfo,
2523 VkQueue* pQueue)
2524 {
2525 RADV_FROM_HANDLE(radv_device, device, _device);
2526 struct radv_queue *queue;
2527
2528 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
2529 if (pQueueInfo->flags != queue->flags) {
2530 /* From the Vulkan 1.1.70 spec:
2531 *
2532 * "The queue returned by vkGetDeviceQueue2 must have the same
2533 * flags value from this structure as that used at device
2534 * creation time in a VkDeviceQueueCreateInfo instance. If no
2535 * matching flags were specified at device creation time then
2536 * pQueue will return VK_NULL_HANDLE."
2537 */
2538 *pQueue = VK_NULL_HANDLE;
2539 return;
2540 }
2541
2542 *pQueue = radv_queue_to_handle(queue);
2543 }
2544
2545 void radv_GetDeviceQueue(
2546 VkDevice _device,
2547 uint32_t queueFamilyIndex,
2548 uint32_t queueIndex,
2549 VkQueue* pQueue)
2550 {
2551 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
2552 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
2553 .queueFamilyIndex = queueFamilyIndex,
2554 .queueIndex = queueIndex
2555 };
2556
2557 radv_GetDeviceQueue2(_device, &info, pQueue);
2558 }
2559
2560 static void
2561 fill_geom_tess_rings(struct radv_queue *queue,
2562 uint32_t *map,
2563 bool add_sample_positions,
2564 uint32_t esgs_ring_size,
2565 struct radeon_winsys_bo *esgs_ring_bo,
2566 uint32_t gsvs_ring_size,
2567 struct radeon_winsys_bo *gsvs_ring_bo,
2568 uint32_t tess_factor_ring_size,
2569 uint32_t tess_offchip_ring_offset,
2570 uint32_t tess_offchip_ring_size,
2571 struct radeon_winsys_bo *tess_rings_bo)
2572 {
2573 uint32_t *desc = &map[4];
2574
2575 if (esgs_ring_bo) {
2576 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
2577
2578 /* stride 0, num records - size, add tid, swizzle, elsize4,
2579 index stride 64 */
2580 desc[0] = esgs_va;
2581 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
2582 S_008F04_SWIZZLE_ENABLE(true);
2583 desc[2] = esgs_ring_size;
2584 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2585 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2586 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2587 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2588 S_008F0C_INDEX_STRIDE(3) |
2589 S_008F0C_ADD_TID_ENABLE(1);
2590
2591 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2592 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2593 S_008F0C_OOB_SELECT(2) |
2594 S_008F0C_RESOURCE_LEVEL(1);
2595 } else {
2596 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2597 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2598 S_008F0C_ELEMENT_SIZE(1);
2599 }
2600
2601 /* GS entry for ES->GS ring */
2602 /* stride 0, num records - size, elsize0,
2603 index stride 0 */
2604 desc[4] = esgs_va;
2605 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32);
2606 desc[6] = esgs_ring_size;
2607 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2608 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2609 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2610 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2611
2612 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2613 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2614 S_008F0C_OOB_SELECT(2) |
2615 S_008F0C_RESOURCE_LEVEL(1);
2616 } else {
2617 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2618 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2619 }
2620 }
2621
2622 desc += 8;
2623
2624 if (gsvs_ring_bo) {
2625 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
2626
2627 /* VS entry for GS->VS ring */
2628 /* stride 0, num records - size, elsize0,
2629 index stride 0 */
2630 desc[0] = gsvs_va;
2631 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32);
2632 desc[2] = gsvs_ring_size;
2633 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2634 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2635 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2636 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2637
2638 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2639 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2640 S_008F0C_OOB_SELECT(2) |
2641 S_008F0C_RESOURCE_LEVEL(1);
2642 } else {
2643 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2644 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2645 }
2646
2647 /* stride gsvs_itemsize, num records 64
2648 elsize 4, index stride 16 */
2649 /* shader will patch stride and desc[2] */
2650 desc[4] = gsvs_va;
2651 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32) |
2652 S_008F04_SWIZZLE_ENABLE(1);
2653 desc[6] = 0;
2654 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2655 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2656 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2657 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2658 S_008F0C_INDEX_STRIDE(1) |
2659 S_008F0C_ADD_TID_ENABLE(true);
2660
2661 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2662 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2663 S_008F0C_OOB_SELECT(2) |
2664 S_008F0C_RESOURCE_LEVEL(1);
2665 } else {
2666 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2667 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2668 S_008F0C_ELEMENT_SIZE(1);
2669 }
2670
2671 }
2672
2673 desc += 8;
2674
2675 if (tess_rings_bo) {
2676 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
2677 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
2678
2679 desc[0] = tess_va;
2680 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32);
2681 desc[2] = tess_factor_ring_size;
2682 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2683 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2684 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2685 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2686
2687 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2688 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2689 S_008F0C_OOB_SELECT(3) |
2690 S_008F0C_RESOURCE_LEVEL(1);
2691 } else {
2692 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2693 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2694 }
2695
2696 desc[4] = tess_offchip_va;
2697 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32);
2698 desc[6] = tess_offchip_ring_size;
2699 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2700 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2701 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2702 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2703
2704 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2705 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2706 S_008F0C_OOB_SELECT(3) |
2707 S_008F0C_RESOURCE_LEVEL(1);
2708 } else {
2709 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2710 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2711 }
2712 }
2713
2714 desc += 8;
2715
2716 if (add_sample_positions) {
2717 /* add sample positions after all rings */
2718 memcpy(desc, queue->device->sample_locations_1x, 8);
2719 desc += 2;
2720 memcpy(desc, queue->device->sample_locations_2x, 16);
2721 desc += 4;
2722 memcpy(desc, queue->device->sample_locations_4x, 32);
2723 desc += 8;
2724 memcpy(desc, queue->device->sample_locations_8x, 64);
2725 }
2726 }
2727
2728 static unsigned
2729 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
2730 {
2731 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= GFX7 &&
2732 device->physical_device->rad_info.family != CHIP_CARRIZO &&
2733 device->physical_device->rad_info.family != CHIP_STONEY;
2734 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
2735 unsigned max_offchip_buffers;
2736 unsigned offchip_granularity;
2737 unsigned hs_offchip_param;
2738
2739 /*
2740 * Per RadeonSI:
2741 * This must be one less than the maximum number due to a hw limitation.
2742 * Various hardware bugs need thGFX7
2743 *
2744 * Per AMDVLK:
2745 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
2746 * Gfx7 should limit max_offchip_buffers to 508
2747 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
2748 *
2749 * Follow AMDVLK here.
2750 */
2751 if (device->physical_device->rad_info.chip_class >= GFX10) {
2752 max_offchip_buffers_per_se = 256;
2753 } else if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
2754 device->physical_device->rad_info.chip_class == GFX7 ||
2755 device->physical_device->rad_info.chip_class == GFX6)
2756 --max_offchip_buffers_per_se;
2757
2758 max_offchip_buffers = max_offchip_buffers_per_se *
2759 device->physical_device->rad_info.max_se;
2760
2761 /* Hawaii has a bug with offchip buffers > 256 that can be worked
2762 * around by setting 4K granularity.
2763 */
2764 if (device->tess_offchip_block_dw_size == 4096) {
2765 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
2766 offchip_granularity = V_03093C_X_4K_DWORDS;
2767 } else {
2768 assert(device->tess_offchip_block_dw_size == 8192);
2769 offchip_granularity = V_03093C_X_8K_DWORDS;
2770 }
2771
2772 switch (device->physical_device->rad_info.chip_class) {
2773 case GFX6:
2774 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
2775 break;
2776 case GFX7:
2777 case GFX8:
2778 case GFX9:
2779 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
2780 break;
2781 case GFX10:
2782 break;
2783 default:
2784 break;
2785 }
2786
2787 *max_offchip_buffers_p = max_offchip_buffers;
2788 if (device->physical_device->rad_info.chip_class >= GFX7) {
2789 if (device->physical_device->rad_info.chip_class >= GFX8)
2790 --max_offchip_buffers;
2791 hs_offchip_param =
2792 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
2793 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
2794 } else {
2795 hs_offchip_param =
2796 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
2797 }
2798 return hs_offchip_param;
2799 }
2800
2801 static void
2802 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2803 struct radeon_winsys_bo *esgs_ring_bo,
2804 uint32_t esgs_ring_size,
2805 struct radeon_winsys_bo *gsvs_ring_bo,
2806 uint32_t gsvs_ring_size)
2807 {
2808 if (!esgs_ring_bo && !gsvs_ring_bo)
2809 return;
2810
2811 if (esgs_ring_bo)
2812 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
2813
2814 if (gsvs_ring_bo)
2815 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
2816
2817 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
2818 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
2819 radeon_emit(cs, esgs_ring_size >> 8);
2820 radeon_emit(cs, gsvs_ring_size >> 8);
2821 } else {
2822 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
2823 radeon_emit(cs, esgs_ring_size >> 8);
2824 radeon_emit(cs, gsvs_ring_size >> 8);
2825 }
2826 }
2827
2828 static void
2829 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2830 unsigned hs_offchip_param, unsigned tf_ring_size,
2831 struct radeon_winsys_bo *tess_rings_bo)
2832 {
2833 uint64_t tf_va;
2834
2835 if (!tess_rings_bo)
2836 return;
2837
2838 tf_va = radv_buffer_get_va(tess_rings_bo);
2839
2840 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
2841
2842 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
2843 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
2844 S_030938_SIZE(tf_ring_size / 4));
2845 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
2846 tf_va >> 8);
2847
2848 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2849 radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
2850 S_030984_BASE_HI(tf_va >> 40));
2851 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
2852 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
2853 S_030944_BASE_HI(tf_va >> 40));
2854 }
2855 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
2856 hs_offchip_param);
2857 } else {
2858 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
2859 S_008988_SIZE(tf_ring_size / 4));
2860 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
2861 tf_va >> 8);
2862 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
2863 hs_offchip_param);
2864 }
2865 }
2866
2867 static void
2868 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2869 struct radeon_winsys_bo *compute_scratch_bo)
2870 {
2871 uint64_t scratch_va;
2872
2873 if (!compute_scratch_bo)
2874 return;
2875
2876 scratch_va = radv_buffer_get_va(compute_scratch_bo);
2877
2878 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
2879
2880 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
2881 radeon_emit(cs, scratch_va);
2882 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
2883 S_008F04_SWIZZLE_ENABLE(1));
2884 }
2885
2886 static void
2887 radv_emit_global_shader_pointers(struct radv_queue *queue,
2888 struct radeon_cmdbuf *cs,
2889 struct radeon_winsys_bo *descriptor_bo)
2890 {
2891 uint64_t va;
2892
2893 if (!descriptor_bo)
2894 return;
2895
2896 va = radv_buffer_get_va(descriptor_bo);
2897
2898 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
2899
2900 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2901 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2902 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2903 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
2904 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
2905
2906 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2907 radv_emit_shader_pointer(queue->device, cs, regs[i],
2908 va, true);
2909 }
2910 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
2911 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2912 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2913 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
2914 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
2915
2916 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2917 radv_emit_shader_pointer(queue->device, cs, regs[i],
2918 va, true);
2919 }
2920 } else {
2921 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2922 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2923 R_00B230_SPI_SHADER_USER_DATA_GS_0,
2924 R_00B330_SPI_SHADER_USER_DATA_ES_0,
2925 R_00B430_SPI_SHADER_USER_DATA_HS_0,
2926 R_00B530_SPI_SHADER_USER_DATA_LS_0};
2927
2928 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2929 radv_emit_shader_pointer(queue->device, cs, regs[i],
2930 va, true);
2931 }
2932 }
2933 }
2934
2935 static void
2936 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
2937 {
2938 struct radv_device *device = queue->device;
2939
2940 if (device->gfx_init) {
2941 uint64_t va = radv_buffer_get_va(device->gfx_init);
2942
2943 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
2944 radeon_emit(cs, va);
2945 radeon_emit(cs, va >> 32);
2946 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
2947
2948 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
2949 } else {
2950 struct radv_physical_device *physical_device = device->physical_device;
2951 si_emit_graphics(physical_device, cs);
2952 }
2953 }
2954
2955 static void
2956 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
2957 {
2958 struct radv_physical_device *physical_device = queue->device->physical_device;
2959 si_emit_compute(physical_device, cs);
2960 }
2961
2962 static VkResult
2963 radv_get_preamble_cs(struct radv_queue *queue,
2964 uint32_t scratch_size,
2965 uint32_t compute_scratch_size,
2966 uint32_t esgs_ring_size,
2967 uint32_t gsvs_ring_size,
2968 bool needs_tess_rings,
2969 bool needs_gds,
2970 bool needs_sample_positions,
2971 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
2972 struct radeon_cmdbuf **initial_preamble_cs,
2973 struct radeon_cmdbuf **continue_preamble_cs)
2974 {
2975 struct radeon_winsys_bo *scratch_bo = NULL;
2976 struct radeon_winsys_bo *descriptor_bo = NULL;
2977 struct radeon_winsys_bo *compute_scratch_bo = NULL;
2978 struct radeon_winsys_bo *esgs_ring_bo = NULL;
2979 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
2980 struct radeon_winsys_bo *tess_rings_bo = NULL;
2981 struct radeon_winsys_bo *gds_bo = NULL;
2982 struct radeon_winsys_bo *gds_oa_bo = NULL;
2983 struct radeon_cmdbuf *dest_cs[3] = {0};
2984 bool add_tess_rings = false, add_gds = false, add_sample_positions = false;
2985 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
2986 unsigned max_offchip_buffers;
2987 unsigned hs_offchip_param = 0;
2988 unsigned tess_offchip_ring_offset;
2989 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
2990 if (!queue->has_tess_rings) {
2991 if (needs_tess_rings)
2992 add_tess_rings = true;
2993 }
2994 if (!queue->has_gds) {
2995 if (needs_gds)
2996 add_gds = true;
2997 }
2998 if (!queue->has_sample_positions) {
2999 if (needs_sample_positions)
3000 add_sample_positions = true;
3001 }
3002 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
3003 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
3004 &max_offchip_buffers);
3005 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
3006 tess_offchip_ring_size = max_offchip_buffers *
3007 queue->device->tess_offchip_block_dw_size * 4;
3008
3009 if (scratch_size <= queue->scratch_size &&
3010 compute_scratch_size <= queue->compute_scratch_size &&
3011 esgs_ring_size <= queue->esgs_ring_size &&
3012 gsvs_ring_size <= queue->gsvs_ring_size &&
3013 !add_tess_rings && !add_gds && !add_sample_positions &&
3014 queue->initial_preamble_cs) {
3015 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3016 *initial_preamble_cs = queue->initial_preamble_cs;
3017 *continue_preamble_cs = queue->continue_preamble_cs;
3018 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size &&
3019 !needs_tess_rings && !needs_gds && !needs_sample_positions)
3020 *continue_preamble_cs = NULL;
3021 return VK_SUCCESS;
3022 }
3023
3024 if (scratch_size > queue->scratch_size) {
3025 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3026 scratch_size,
3027 4096,
3028 RADEON_DOMAIN_VRAM,
3029 ring_bo_flags,
3030 RADV_BO_PRIORITY_SCRATCH);
3031 if (!scratch_bo)
3032 goto fail;
3033 } else
3034 scratch_bo = queue->scratch_bo;
3035
3036 if (compute_scratch_size > queue->compute_scratch_size) {
3037 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
3038 compute_scratch_size,
3039 4096,
3040 RADEON_DOMAIN_VRAM,
3041 ring_bo_flags,
3042 RADV_BO_PRIORITY_SCRATCH);
3043 if (!compute_scratch_bo)
3044 goto fail;
3045
3046 } else
3047 compute_scratch_bo = queue->compute_scratch_bo;
3048
3049 if (esgs_ring_size > queue->esgs_ring_size) {
3050 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3051 esgs_ring_size,
3052 4096,
3053 RADEON_DOMAIN_VRAM,
3054 ring_bo_flags,
3055 RADV_BO_PRIORITY_SCRATCH);
3056 if (!esgs_ring_bo)
3057 goto fail;
3058 } else {
3059 esgs_ring_bo = queue->esgs_ring_bo;
3060 esgs_ring_size = queue->esgs_ring_size;
3061 }
3062
3063 if (gsvs_ring_size > queue->gsvs_ring_size) {
3064 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
3065 gsvs_ring_size,
3066 4096,
3067 RADEON_DOMAIN_VRAM,
3068 ring_bo_flags,
3069 RADV_BO_PRIORITY_SCRATCH);
3070 if (!gsvs_ring_bo)
3071 goto fail;
3072 } else {
3073 gsvs_ring_bo = queue->gsvs_ring_bo;
3074 gsvs_ring_size = queue->gsvs_ring_size;
3075 }
3076
3077 if (add_tess_rings) {
3078 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
3079 tess_offchip_ring_offset + tess_offchip_ring_size,
3080 256,
3081 RADEON_DOMAIN_VRAM,
3082 ring_bo_flags,
3083 RADV_BO_PRIORITY_SCRATCH);
3084 if (!tess_rings_bo)
3085 goto fail;
3086 } else {
3087 tess_rings_bo = queue->tess_rings_bo;
3088 }
3089
3090 if (add_gds) {
3091 assert(queue->device->physical_device->rad_info.chip_class >= GFX10);
3092
3093 /* 4 streamout GDS counters.
3094 * We need 256B (64 dw) of GDS, otherwise streamout hangs.
3095 */
3096 gds_bo = queue->device->ws->buffer_create(queue->device->ws,
3097 256, 4,
3098 RADEON_DOMAIN_GDS,
3099 ring_bo_flags,
3100 RADV_BO_PRIORITY_SCRATCH);
3101 if (!gds_bo)
3102 goto fail;
3103
3104 gds_oa_bo = queue->device->ws->buffer_create(queue->device->ws,
3105 4, 1,
3106 RADEON_DOMAIN_OA,
3107 ring_bo_flags,
3108 RADV_BO_PRIORITY_SCRATCH);
3109 if (!gds_oa_bo)
3110 goto fail;
3111 } else {
3112 gds_bo = queue->gds_bo;
3113 gds_oa_bo = queue->gds_oa_bo;
3114 }
3115
3116 if (scratch_bo != queue->scratch_bo ||
3117 esgs_ring_bo != queue->esgs_ring_bo ||
3118 gsvs_ring_bo != queue->gsvs_ring_bo ||
3119 tess_rings_bo != queue->tess_rings_bo ||
3120 add_sample_positions) {
3121 uint32_t size = 0;
3122 if (gsvs_ring_bo || esgs_ring_bo ||
3123 tess_rings_bo || add_sample_positions) {
3124 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
3125 if (add_sample_positions)
3126 size += 128; /* 64+32+16+8 = 120 bytes */
3127 }
3128 else if (scratch_bo)
3129 size = 8; /* 2 dword */
3130
3131 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
3132 size,
3133 4096,
3134 RADEON_DOMAIN_VRAM,
3135 RADEON_FLAG_CPU_ACCESS |
3136 RADEON_FLAG_NO_INTERPROCESS_SHARING |
3137 RADEON_FLAG_READ_ONLY,
3138 RADV_BO_PRIORITY_DESCRIPTOR);
3139 if (!descriptor_bo)
3140 goto fail;
3141 } else
3142 descriptor_bo = queue->descriptor_bo;
3143
3144 if (descriptor_bo != queue->descriptor_bo) {
3145 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
3146
3147 if (scratch_bo) {
3148 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
3149 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
3150 S_008F04_SWIZZLE_ENABLE(1);
3151 map[0] = scratch_va;
3152 map[1] = rsrc1;
3153 }
3154
3155 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
3156 fill_geom_tess_rings(queue, map, add_sample_positions,
3157 esgs_ring_size, esgs_ring_bo,
3158 gsvs_ring_size, gsvs_ring_bo,
3159 tess_factor_ring_size,
3160 tess_offchip_ring_offset,
3161 tess_offchip_ring_size,
3162 tess_rings_bo);
3163
3164 queue->device->ws->buffer_unmap(descriptor_bo);
3165 }
3166
3167 for(int i = 0; i < 3; ++i) {
3168 struct radeon_cmdbuf *cs = NULL;
3169 cs = queue->device->ws->cs_create(queue->device->ws,
3170 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
3171 if (!cs)
3172 goto fail;
3173
3174 dest_cs[i] = cs;
3175
3176 if (scratch_bo)
3177 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
3178
3179 /* Emit initial configuration. */
3180 switch (queue->queue_family_index) {
3181 case RADV_QUEUE_GENERAL:
3182 radv_init_graphics_state(cs, queue);
3183 break;
3184 case RADV_QUEUE_COMPUTE:
3185 radv_init_compute_state(cs, queue);
3186 break;
3187 case RADV_QUEUE_TRANSFER:
3188 break;
3189 }
3190
3191 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
3192 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3193 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
3194
3195 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3196 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
3197 }
3198
3199 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
3200 gsvs_ring_bo, gsvs_ring_size);
3201 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
3202 tess_factor_ring_size, tess_rings_bo);
3203 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
3204 radv_emit_compute_scratch(queue, cs, compute_scratch_bo);
3205
3206 if (gds_bo)
3207 radv_cs_add_buffer(queue->device->ws, cs, gds_bo);
3208 if (gds_oa_bo)
3209 radv_cs_add_buffer(queue->device->ws, cs, gds_oa_bo);
3210
3211 if (i == 0) {
3212 si_cs_emit_cache_flush(cs,
3213 queue->device->physical_device->rad_info.chip_class,
3214 NULL, 0,
3215 queue->queue_family_index == RING_COMPUTE &&
3216 queue->device->physical_device->rad_info.chip_class >= GFX7,
3217 (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)) |
3218 RADV_CMD_FLAG_INV_ICACHE |
3219 RADV_CMD_FLAG_INV_SCACHE |
3220 RADV_CMD_FLAG_INV_VCACHE |
3221 RADV_CMD_FLAG_INV_L2 |
3222 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3223 } else if (i == 1) {
3224 si_cs_emit_cache_flush(cs,
3225 queue->device->physical_device->rad_info.chip_class,
3226 NULL, 0,
3227 queue->queue_family_index == RING_COMPUTE &&
3228 queue->device->physical_device->rad_info.chip_class >= GFX7,
3229 RADV_CMD_FLAG_INV_ICACHE |
3230 RADV_CMD_FLAG_INV_SCACHE |
3231 RADV_CMD_FLAG_INV_VCACHE |
3232 RADV_CMD_FLAG_INV_L2 |
3233 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
3234 }
3235
3236 if (!queue->device->ws->cs_finalize(cs))
3237 goto fail;
3238 }
3239
3240 if (queue->initial_full_flush_preamble_cs)
3241 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
3242
3243 if (queue->initial_preamble_cs)
3244 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
3245
3246 if (queue->continue_preamble_cs)
3247 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
3248
3249 queue->initial_full_flush_preamble_cs = dest_cs[0];
3250 queue->initial_preamble_cs = dest_cs[1];
3251 queue->continue_preamble_cs = dest_cs[2];
3252
3253 if (scratch_bo != queue->scratch_bo) {
3254 if (queue->scratch_bo)
3255 queue->device->ws->buffer_destroy(queue->scratch_bo);
3256 queue->scratch_bo = scratch_bo;
3257 queue->scratch_size = scratch_size;
3258 }
3259
3260 if (compute_scratch_bo != queue->compute_scratch_bo) {
3261 if (queue->compute_scratch_bo)
3262 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
3263 queue->compute_scratch_bo = compute_scratch_bo;
3264 queue->compute_scratch_size = compute_scratch_size;
3265 }
3266
3267 if (esgs_ring_bo != queue->esgs_ring_bo) {
3268 if (queue->esgs_ring_bo)
3269 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
3270 queue->esgs_ring_bo = esgs_ring_bo;
3271 queue->esgs_ring_size = esgs_ring_size;
3272 }
3273
3274 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
3275 if (queue->gsvs_ring_bo)
3276 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
3277 queue->gsvs_ring_bo = gsvs_ring_bo;
3278 queue->gsvs_ring_size = gsvs_ring_size;
3279 }
3280
3281 if (tess_rings_bo != queue->tess_rings_bo) {
3282 queue->tess_rings_bo = tess_rings_bo;
3283 queue->has_tess_rings = true;
3284 }
3285
3286 if (gds_bo != queue->gds_bo) {
3287 queue->gds_bo = gds_bo;
3288 queue->has_gds = true;
3289 }
3290
3291 if (gds_oa_bo != queue->gds_oa_bo)
3292 queue->gds_oa_bo = gds_oa_bo;
3293
3294 if (descriptor_bo != queue->descriptor_bo) {
3295 if (queue->descriptor_bo)
3296 queue->device->ws->buffer_destroy(queue->descriptor_bo);
3297
3298 queue->descriptor_bo = descriptor_bo;
3299 }
3300
3301 if (add_sample_positions)
3302 queue->has_sample_positions = true;
3303
3304 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
3305 *initial_preamble_cs = queue->initial_preamble_cs;
3306 *continue_preamble_cs = queue->continue_preamble_cs;
3307 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
3308 *continue_preamble_cs = NULL;
3309 return VK_SUCCESS;
3310 fail:
3311 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
3312 if (dest_cs[i])
3313 queue->device->ws->cs_destroy(dest_cs[i]);
3314 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
3315 queue->device->ws->buffer_destroy(descriptor_bo);
3316 if (scratch_bo && scratch_bo != queue->scratch_bo)
3317 queue->device->ws->buffer_destroy(scratch_bo);
3318 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
3319 queue->device->ws->buffer_destroy(compute_scratch_bo);
3320 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
3321 queue->device->ws->buffer_destroy(esgs_ring_bo);
3322 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
3323 queue->device->ws->buffer_destroy(gsvs_ring_bo);
3324 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
3325 queue->device->ws->buffer_destroy(tess_rings_bo);
3326 if (gds_bo && gds_bo != queue->gds_bo)
3327 queue->device->ws->buffer_destroy(gds_bo);
3328 if (gds_oa_bo && gds_oa_bo != queue->gds_oa_bo)
3329 queue->device->ws->buffer_destroy(gds_oa_bo);
3330
3331 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
3332 }
3333
3334 static VkResult radv_alloc_sem_counts(struct radv_instance *instance,
3335 struct radv_winsys_sem_counts *counts,
3336 int num_sems,
3337 const VkSemaphore *sems,
3338 VkFence _fence,
3339 bool reset_temp)
3340 {
3341 int syncobj_idx = 0, sem_idx = 0;
3342
3343 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
3344 return VK_SUCCESS;
3345
3346 for (uint32_t i = 0; i < num_sems; i++) {
3347 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
3348
3349 if (sem->temp_syncobj || sem->syncobj)
3350 counts->syncobj_count++;
3351 else
3352 counts->sem_count++;
3353 }
3354
3355 if (_fence != VK_NULL_HANDLE) {
3356 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3357 if (fence->temp_syncobj || fence->syncobj)
3358 counts->syncobj_count++;
3359 }
3360
3361 if (counts->syncobj_count) {
3362 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
3363 if (!counts->syncobj)
3364 return vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3365 }
3366
3367 if (counts->sem_count) {
3368 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
3369 if (!counts->sem) {
3370 free(counts->syncobj);
3371 return vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3372 }
3373 }
3374
3375 for (uint32_t i = 0; i < num_sems; i++) {
3376 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
3377
3378 if (sem->temp_syncobj) {
3379 counts->syncobj[syncobj_idx++] = sem->temp_syncobj;
3380 }
3381 else if (sem->syncobj)
3382 counts->syncobj[syncobj_idx++] = sem->syncobj;
3383 else {
3384 assert(sem->sem);
3385 counts->sem[sem_idx++] = sem->sem;
3386 }
3387 }
3388
3389 if (_fence != VK_NULL_HANDLE) {
3390 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3391 if (fence->temp_syncobj)
3392 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
3393 else if (fence->syncobj)
3394 counts->syncobj[syncobj_idx++] = fence->syncobj;
3395 }
3396
3397 return VK_SUCCESS;
3398 }
3399
3400 static void
3401 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
3402 {
3403 free(sem_info->wait.syncobj);
3404 free(sem_info->wait.sem);
3405 free(sem_info->signal.syncobj);
3406 free(sem_info->signal.sem);
3407 }
3408
3409
3410 static void radv_free_temp_syncobjs(struct radv_device *device,
3411 int num_sems,
3412 const VkSemaphore *sems)
3413 {
3414 for (uint32_t i = 0; i < num_sems; i++) {
3415 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
3416
3417 if (sem->temp_syncobj) {
3418 device->ws->destroy_syncobj(device->ws, sem->temp_syncobj);
3419 sem->temp_syncobj = 0;
3420 }
3421 }
3422 }
3423
3424 static VkResult
3425 radv_alloc_sem_info(struct radv_instance *instance,
3426 struct radv_winsys_sem_info *sem_info,
3427 int num_wait_sems,
3428 const VkSemaphore *wait_sems,
3429 int num_signal_sems,
3430 const VkSemaphore *signal_sems,
3431 VkFence fence)
3432 {
3433 VkResult ret;
3434 memset(sem_info, 0, sizeof(*sem_info));
3435
3436 ret = radv_alloc_sem_counts(instance, &sem_info->wait, num_wait_sems, wait_sems, VK_NULL_HANDLE, true);
3437 if (ret)
3438 return ret;
3439 ret = radv_alloc_sem_counts(instance, &sem_info->signal, num_signal_sems, signal_sems, fence, false);
3440 if (ret)
3441 radv_free_sem_info(sem_info);
3442
3443 /* caller can override these */
3444 sem_info->cs_emit_wait = true;
3445 sem_info->cs_emit_signal = true;
3446 return ret;
3447 }
3448
3449 /* Signals fence as soon as all the work currently put on queue is done. */
3450 static VkResult radv_signal_fence(struct radv_queue *queue,
3451 struct radv_fence *fence)
3452 {
3453 int ret;
3454 VkResult result;
3455 struct radv_winsys_sem_info sem_info;
3456
3457 result = radv_alloc_sem_info(queue->device->instance, &sem_info, 0, NULL, 0, NULL,
3458 radv_fence_to_handle(fence));
3459 if (result != VK_SUCCESS)
3460 return result;
3461
3462 ret = queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
3463 &queue->device->empty_cs[queue->queue_family_index],
3464 1, NULL, NULL, &sem_info, NULL,
3465 false, fence->fence);
3466 radv_free_sem_info(&sem_info);
3467
3468 if (ret)
3469 return vk_error(queue->device->instance, VK_ERROR_DEVICE_LOST);
3470
3471 return VK_SUCCESS;
3472 }
3473
3474 VkResult radv_QueueSubmit(
3475 VkQueue _queue,
3476 uint32_t submitCount,
3477 const VkSubmitInfo* pSubmits,
3478 VkFence _fence)
3479 {
3480 RADV_FROM_HANDLE(radv_queue, queue, _queue);
3481 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3482 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
3483 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
3484 int ret;
3485 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
3486 uint32_t scratch_size = 0;
3487 uint32_t compute_scratch_size = 0;
3488 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
3489 struct radeon_cmdbuf *initial_preamble_cs = NULL, *initial_flush_preamble_cs = NULL, *continue_preamble_cs = NULL;
3490 VkResult result;
3491 bool fence_emitted = false;
3492 bool tess_rings_needed = false;
3493 bool gds_needed = false;
3494 bool sample_positions_needed = false;
3495
3496 /* Do this first so failing to allocate scratch buffers can't result in
3497 * partially executed submissions. */
3498 for (uint32_t i = 0; i < submitCount; i++) {
3499 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
3500 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
3501 pSubmits[i].pCommandBuffers[j]);
3502
3503 scratch_size = MAX2(scratch_size, cmd_buffer->scratch_size_needed);
3504 compute_scratch_size = MAX2(compute_scratch_size,
3505 cmd_buffer->compute_scratch_size_needed);
3506 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
3507 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
3508 tess_rings_needed |= cmd_buffer->tess_rings_needed;
3509 gds_needed |= cmd_buffer->gds_needed;
3510 sample_positions_needed |= cmd_buffer->sample_positions_needed;
3511 }
3512 }
3513
3514 result = radv_get_preamble_cs(queue, scratch_size, compute_scratch_size,
3515 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
3516 gds_needed, sample_positions_needed,
3517 &initial_flush_preamble_cs,
3518 &initial_preamble_cs, &continue_preamble_cs);
3519 if (result != VK_SUCCESS)
3520 return result;
3521
3522 for (uint32_t i = 0; i < submitCount; i++) {
3523 struct radeon_cmdbuf **cs_array;
3524 bool do_flush = !i || pSubmits[i].pWaitDstStageMask;
3525 bool can_patch = true;
3526 uint32_t advance;
3527 struct radv_winsys_sem_info sem_info;
3528
3529 result = radv_alloc_sem_info(queue->device->instance,
3530 &sem_info,
3531 pSubmits[i].waitSemaphoreCount,
3532 pSubmits[i].pWaitSemaphores,
3533 pSubmits[i].signalSemaphoreCount,
3534 pSubmits[i].pSignalSemaphores,
3535 _fence);
3536 if (result != VK_SUCCESS)
3537 return result;
3538
3539 if (!pSubmits[i].commandBufferCount) {
3540 if (pSubmits[i].waitSemaphoreCount || pSubmits[i].signalSemaphoreCount) {
3541 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
3542 &queue->device->empty_cs[queue->queue_family_index],
3543 1, NULL, NULL,
3544 &sem_info, NULL,
3545 false, base_fence);
3546 if (ret) {
3547 radv_loge("failed to submit CS %d\n", i);
3548 abort();
3549 }
3550 fence_emitted = true;
3551 }
3552 radv_free_sem_info(&sem_info);
3553 continue;
3554 }
3555
3556 cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
3557 (pSubmits[i].commandBufferCount));
3558
3559 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
3560 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
3561 pSubmits[i].pCommandBuffers[j]);
3562 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
3563
3564 cs_array[j] = cmd_buffer->cs;
3565 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
3566 can_patch = false;
3567
3568 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
3569 }
3570
3571 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j += advance) {
3572 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
3573 const struct radv_winsys_bo_list *bo_list = NULL;
3574
3575 advance = MIN2(max_cs_submission,
3576 pSubmits[i].commandBufferCount - j);
3577
3578 if (queue->device->trace_bo)
3579 *queue->device->trace_id_ptr = 0;
3580
3581 sem_info.cs_emit_wait = j == 0;
3582 sem_info.cs_emit_signal = j + advance == pSubmits[i].commandBufferCount;
3583
3584 if (unlikely(queue->device->use_global_bo_list)) {
3585 pthread_mutex_lock(&queue->device->bo_list.mutex);
3586 bo_list = &queue->device->bo_list.list;
3587 }
3588
3589 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
3590 advance, initial_preamble, continue_preamble_cs,
3591 &sem_info, bo_list,
3592 can_patch, base_fence);
3593
3594 if (unlikely(queue->device->use_global_bo_list))
3595 pthread_mutex_unlock(&queue->device->bo_list.mutex);
3596
3597 if (ret) {
3598 radv_loge("failed to submit CS %d\n", i);
3599 abort();
3600 }
3601 fence_emitted = true;
3602 if (queue->device->trace_bo) {
3603 radv_check_gpu_hangs(queue, cs_array[j]);
3604 }
3605 }
3606
3607 radv_free_temp_syncobjs(queue->device,
3608 pSubmits[i].waitSemaphoreCount,
3609 pSubmits[i].pWaitSemaphores);
3610 radv_free_sem_info(&sem_info);
3611 free(cs_array);
3612 }
3613
3614 if (fence) {
3615 if (!fence_emitted) {
3616 result = radv_signal_fence(queue, fence);
3617 if (result != VK_SUCCESS)
3618 return result;
3619 }
3620 }
3621
3622 return VK_SUCCESS;
3623 }
3624
3625 VkResult radv_QueueWaitIdle(
3626 VkQueue _queue)
3627 {
3628 RADV_FROM_HANDLE(radv_queue, queue, _queue);
3629
3630 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
3631 radv_queue_family_to_ring(queue->queue_family_index),
3632 queue->queue_idx);
3633 return VK_SUCCESS;
3634 }
3635
3636 VkResult radv_DeviceWaitIdle(
3637 VkDevice _device)
3638 {
3639 RADV_FROM_HANDLE(radv_device, device, _device);
3640
3641 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
3642 for (unsigned q = 0; q < device->queue_count[i]; q++) {
3643 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
3644 }
3645 }
3646 return VK_SUCCESS;
3647 }
3648
3649 VkResult radv_EnumerateInstanceExtensionProperties(
3650 const char* pLayerName,
3651 uint32_t* pPropertyCount,
3652 VkExtensionProperties* pProperties)
3653 {
3654 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
3655
3656 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
3657 if (radv_supported_instance_extensions.extensions[i]) {
3658 vk_outarray_append(&out, prop) {
3659 *prop = radv_instance_extensions[i];
3660 }
3661 }
3662 }
3663
3664 return vk_outarray_status(&out);
3665 }
3666
3667 VkResult radv_EnumerateDeviceExtensionProperties(
3668 VkPhysicalDevice physicalDevice,
3669 const char* pLayerName,
3670 uint32_t* pPropertyCount,
3671 VkExtensionProperties* pProperties)
3672 {
3673 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
3674 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
3675
3676 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
3677 if (device->supported_extensions.extensions[i]) {
3678 vk_outarray_append(&out, prop) {
3679 *prop = radv_device_extensions[i];
3680 }
3681 }
3682 }
3683
3684 return vk_outarray_status(&out);
3685 }
3686
3687 PFN_vkVoidFunction radv_GetInstanceProcAddr(
3688 VkInstance _instance,
3689 const char* pName)
3690 {
3691 RADV_FROM_HANDLE(radv_instance, instance, _instance);
3692 bool unchecked = instance ? instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS : false;
3693
3694 if (unchecked) {
3695 return radv_lookup_entrypoint_unchecked(pName);
3696 } else {
3697 return radv_lookup_entrypoint_checked(pName,
3698 instance ? instance->apiVersion : 0,
3699 instance ? &instance->enabled_extensions : NULL,
3700 NULL);
3701 }
3702 }
3703
3704 /* The loader wants us to expose a second GetInstanceProcAddr function
3705 * to work around certain LD_PRELOAD issues seen in apps.
3706 */
3707 PUBLIC
3708 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
3709 VkInstance instance,
3710 const char* pName);
3711
3712 PUBLIC
3713 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
3714 VkInstance instance,
3715 const char* pName)
3716 {
3717 return radv_GetInstanceProcAddr(instance, pName);
3718 }
3719
3720 PUBLIC
3721 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
3722 VkInstance _instance,
3723 const char* pName);
3724
3725 PUBLIC
3726 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
3727 VkInstance _instance,
3728 const char* pName)
3729 {
3730 RADV_FROM_HANDLE(radv_instance, instance, _instance);
3731
3732 return radv_lookup_physical_device_entrypoint_checked(pName,
3733 instance ? instance->apiVersion : 0,
3734 instance ? &instance->enabled_extensions : NULL);
3735 }
3736
3737 PFN_vkVoidFunction radv_GetDeviceProcAddr(
3738 VkDevice _device,
3739 const char* pName)
3740 {
3741 RADV_FROM_HANDLE(radv_device, device, _device);
3742 bool unchecked = device ? device->instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS : false;
3743
3744 if (unchecked) {
3745 return radv_lookup_entrypoint_unchecked(pName);
3746 } else {
3747 return radv_lookup_entrypoint_checked(pName,
3748 device->instance->apiVersion,
3749 &device->instance->enabled_extensions,
3750 &device->enabled_extensions);
3751 }
3752 }
3753
3754 bool radv_get_memory_fd(struct radv_device *device,
3755 struct radv_device_memory *memory,
3756 int *pFD)
3757 {
3758 struct radeon_bo_metadata metadata;
3759
3760 if (memory->image) {
3761 radv_init_metadata(device, memory->image, &metadata);
3762 device->ws->buffer_set_metadata(memory->bo, &metadata);
3763 }
3764
3765 return device->ws->buffer_get_fd(device->ws, memory->bo,
3766 pFD);
3767 }
3768
3769
3770 static void radv_free_memory(struct radv_device *device,
3771 const VkAllocationCallbacks* pAllocator,
3772 struct radv_device_memory *mem)
3773 {
3774 if (mem == NULL)
3775 return;
3776
3777 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
3778 if (mem->android_hardware_buffer)
3779 AHardwareBuffer_release(mem->android_hardware_buffer);
3780 #endif
3781
3782 if (mem->bo) {
3783 radv_bo_list_remove(device, mem->bo);
3784 device->ws->buffer_destroy(mem->bo);
3785 mem->bo = NULL;
3786 }
3787
3788 vk_free2(&device->alloc, pAllocator, mem);
3789 }
3790
3791 static VkResult radv_alloc_memory(struct radv_device *device,
3792 const VkMemoryAllocateInfo* pAllocateInfo,
3793 const VkAllocationCallbacks* pAllocator,
3794 VkDeviceMemory* pMem)
3795 {
3796 struct radv_device_memory *mem;
3797 VkResult result;
3798 enum radeon_bo_domain domain;
3799 uint32_t flags = 0;
3800 enum radv_mem_type mem_type_index = device->physical_device->mem_type_indices[pAllocateInfo->memoryTypeIndex];
3801
3802 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
3803
3804 const VkImportMemoryFdInfoKHR *import_info =
3805 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
3806 const VkMemoryDedicatedAllocateInfo *dedicate_info =
3807 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
3808 const VkExportMemoryAllocateInfo *export_info =
3809 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
3810 const struct VkImportAndroidHardwareBufferInfoANDROID *ahb_import_info =
3811 vk_find_struct_const(pAllocateInfo->pNext,
3812 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
3813 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
3814 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
3815
3816 const struct wsi_memory_allocate_info *wsi_info =
3817 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
3818
3819 if (pAllocateInfo->allocationSize == 0 && !ahb_import_info &&
3820 !(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) {
3821 /* Apparently, this is allowed */
3822 *pMem = VK_NULL_HANDLE;
3823 return VK_SUCCESS;
3824 }
3825
3826 mem = vk_zalloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
3827 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3828 if (mem == NULL)
3829 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3830
3831 if (wsi_info && wsi_info->implicit_sync)
3832 flags |= RADEON_FLAG_IMPLICIT_SYNC;
3833
3834 if (dedicate_info) {
3835 mem->image = radv_image_from_handle(dedicate_info->image);
3836 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
3837 } else {
3838 mem->image = NULL;
3839 mem->buffer = NULL;
3840 }
3841
3842 float priority_float = 0.5;
3843 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
3844 vk_find_struct_const(pAllocateInfo->pNext,
3845 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
3846 if (priority_ext)
3847 priority_float = priority_ext->priority;
3848
3849 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
3850 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
3851
3852 mem->user_ptr = NULL;
3853 mem->bo = NULL;
3854
3855 #if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER
3856 mem->android_hardware_buffer = NULL;
3857 #endif
3858
3859 if (ahb_import_info) {
3860 result = radv_import_ahb_memory(device, mem, priority, ahb_import_info);
3861 if (result != VK_SUCCESS)
3862 goto fail;
3863 } else if(export_info && (export_info->handleTypes & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)) {
3864 result = radv_create_ahb_memory(device, mem, priority, pAllocateInfo);
3865 if (result != VK_SUCCESS)
3866 goto fail;
3867 } else if (import_info) {
3868 assert(import_info->handleType ==
3869 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3870 import_info->handleType ==
3871 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3872 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
3873 priority, NULL);
3874 if (!mem->bo) {
3875 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
3876 goto fail;
3877 } else {
3878 close(import_info->fd);
3879 }
3880 } else if (host_ptr_info) {
3881 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
3882 assert(mem_type_index == RADV_MEM_TYPE_GTT_CACHED);
3883 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
3884 pAllocateInfo->allocationSize,
3885 priority);
3886 if (!mem->bo) {
3887 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
3888 goto fail;
3889 } else {
3890 mem->user_ptr = host_ptr_info->pHostPointer;
3891 }
3892 } else {
3893 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
3894 if (mem_type_index == RADV_MEM_TYPE_GTT_WRITE_COMBINE ||
3895 mem_type_index == RADV_MEM_TYPE_GTT_CACHED)
3896 domain = RADEON_DOMAIN_GTT;
3897 else
3898 domain = RADEON_DOMAIN_VRAM;
3899
3900 if (mem_type_index == RADV_MEM_TYPE_VRAM)
3901 flags |= RADEON_FLAG_NO_CPU_ACCESS;
3902 else
3903 flags |= RADEON_FLAG_CPU_ACCESS;
3904
3905 if (mem_type_index == RADV_MEM_TYPE_GTT_WRITE_COMBINE)
3906 flags |= RADEON_FLAG_GTT_WC;
3907
3908 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
3909 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
3910 if (device->use_global_bo_list) {
3911 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
3912 }
3913 }
3914
3915 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
3916 domain, flags, priority);
3917
3918 if (!mem->bo) {
3919 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
3920 goto fail;
3921 }
3922 mem->type_index = mem_type_index;
3923 }
3924
3925 result = radv_bo_list_add(device, mem->bo);
3926 if (result != VK_SUCCESS)
3927 goto fail;
3928
3929 *pMem = radv_device_memory_to_handle(mem);
3930
3931 return VK_SUCCESS;
3932
3933 fail:
3934 radv_free_memory(device, pAllocator,mem);
3935 vk_free2(&device->alloc, pAllocator, mem);
3936
3937 return result;
3938 }
3939
3940 VkResult radv_AllocateMemory(
3941 VkDevice _device,
3942 const VkMemoryAllocateInfo* pAllocateInfo,
3943 const VkAllocationCallbacks* pAllocator,
3944 VkDeviceMemory* pMem)
3945 {
3946 RADV_FROM_HANDLE(radv_device, device, _device);
3947 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
3948 }
3949
3950 void radv_FreeMemory(
3951 VkDevice _device,
3952 VkDeviceMemory _mem,
3953 const VkAllocationCallbacks* pAllocator)
3954 {
3955 RADV_FROM_HANDLE(radv_device, device, _device);
3956 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
3957
3958 radv_free_memory(device, pAllocator, mem);
3959 }
3960
3961 VkResult radv_MapMemory(
3962 VkDevice _device,
3963 VkDeviceMemory _memory,
3964 VkDeviceSize offset,
3965 VkDeviceSize size,
3966 VkMemoryMapFlags flags,
3967 void** ppData)
3968 {
3969 RADV_FROM_HANDLE(radv_device, device, _device);
3970 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
3971
3972 if (mem == NULL) {
3973 *ppData = NULL;
3974 return VK_SUCCESS;
3975 }
3976
3977 if (mem->user_ptr)
3978 *ppData = mem->user_ptr;
3979 else
3980 *ppData = device->ws->buffer_map(mem->bo);
3981
3982 if (*ppData) {
3983 *ppData += offset;
3984 return VK_SUCCESS;
3985 }
3986
3987 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
3988 }
3989
3990 void radv_UnmapMemory(
3991 VkDevice _device,
3992 VkDeviceMemory _memory)
3993 {
3994 RADV_FROM_HANDLE(radv_device, device, _device);
3995 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
3996
3997 if (mem == NULL)
3998 return;
3999
4000 if (mem->user_ptr == NULL)
4001 device->ws->buffer_unmap(mem->bo);
4002 }
4003
4004 VkResult radv_FlushMappedMemoryRanges(
4005 VkDevice _device,
4006 uint32_t memoryRangeCount,
4007 const VkMappedMemoryRange* pMemoryRanges)
4008 {
4009 return VK_SUCCESS;
4010 }
4011
4012 VkResult radv_InvalidateMappedMemoryRanges(
4013 VkDevice _device,
4014 uint32_t memoryRangeCount,
4015 const VkMappedMemoryRange* pMemoryRanges)
4016 {
4017 return VK_SUCCESS;
4018 }
4019
4020 void radv_GetBufferMemoryRequirements(
4021 VkDevice _device,
4022 VkBuffer _buffer,
4023 VkMemoryRequirements* pMemoryRequirements)
4024 {
4025 RADV_FROM_HANDLE(radv_device, device, _device);
4026 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
4027
4028 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
4029
4030 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
4031 pMemoryRequirements->alignment = 4096;
4032 else
4033 pMemoryRequirements->alignment = 16;
4034
4035 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
4036 }
4037
4038 void radv_GetBufferMemoryRequirements2(
4039 VkDevice device,
4040 const VkBufferMemoryRequirementsInfo2 *pInfo,
4041 VkMemoryRequirements2 *pMemoryRequirements)
4042 {
4043 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
4044 &pMemoryRequirements->memoryRequirements);
4045 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
4046 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
4047 switch (ext->sType) {
4048 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4049 VkMemoryDedicatedRequirements *req =
4050 (VkMemoryDedicatedRequirements *) ext;
4051 req->requiresDedicatedAllocation = buffer->shareable;
4052 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
4053 break;
4054 }
4055 default:
4056 break;
4057 }
4058 }
4059 }
4060
4061 void radv_GetImageMemoryRequirements(
4062 VkDevice _device,
4063 VkImage _image,
4064 VkMemoryRequirements* pMemoryRequirements)
4065 {
4066 RADV_FROM_HANDLE(radv_device, device, _device);
4067 RADV_FROM_HANDLE(radv_image, image, _image);
4068
4069 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
4070
4071 pMemoryRequirements->size = image->size;
4072 pMemoryRequirements->alignment = image->alignment;
4073 }
4074
4075 void radv_GetImageMemoryRequirements2(
4076 VkDevice device,
4077 const VkImageMemoryRequirementsInfo2 *pInfo,
4078 VkMemoryRequirements2 *pMemoryRequirements)
4079 {
4080 radv_GetImageMemoryRequirements(device, pInfo->image,
4081 &pMemoryRequirements->memoryRequirements);
4082
4083 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
4084
4085 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
4086 switch (ext->sType) {
4087 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4088 VkMemoryDedicatedRequirements *req =
4089 (VkMemoryDedicatedRequirements *) ext;
4090 req->requiresDedicatedAllocation = image->shareable;
4091 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
4092 break;
4093 }
4094 default:
4095 break;
4096 }
4097 }
4098 }
4099
4100 void radv_GetImageSparseMemoryRequirements(
4101 VkDevice device,
4102 VkImage image,
4103 uint32_t* pSparseMemoryRequirementCount,
4104 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
4105 {
4106 stub();
4107 }
4108
4109 void radv_GetImageSparseMemoryRequirements2(
4110 VkDevice device,
4111 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
4112 uint32_t* pSparseMemoryRequirementCount,
4113 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
4114 {
4115 stub();
4116 }
4117
4118 void radv_GetDeviceMemoryCommitment(
4119 VkDevice device,
4120 VkDeviceMemory memory,
4121 VkDeviceSize* pCommittedMemoryInBytes)
4122 {
4123 *pCommittedMemoryInBytes = 0;
4124 }
4125
4126 VkResult radv_BindBufferMemory2(VkDevice device,
4127 uint32_t bindInfoCount,
4128 const VkBindBufferMemoryInfo *pBindInfos)
4129 {
4130 for (uint32_t i = 0; i < bindInfoCount; ++i) {
4131 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
4132 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
4133
4134 if (mem) {
4135 buffer->bo = mem->bo;
4136 buffer->offset = pBindInfos[i].memoryOffset;
4137 } else {
4138 buffer->bo = NULL;
4139 }
4140 }
4141 return VK_SUCCESS;
4142 }
4143
4144 VkResult radv_BindBufferMemory(
4145 VkDevice device,
4146 VkBuffer buffer,
4147 VkDeviceMemory memory,
4148 VkDeviceSize memoryOffset)
4149 {
4150 const VkBindBufferMemoryInfo info = {
4151 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
4152 .buffer = buffer,
4153 .memory = memory,
4154 .memoryOffset = memoryOffset
4155 };
4156
4157 return radv_BindBufferMemory2(device, 1, &info);
4158 }
4159
4160 VkResult radv_BindImageMemory2(VkDevice device,
4161 uint32_t bindInfoCount,
4162 const VkBindImageMemoryInfo *pBindInfos)
4163 {
4164 for (uint32_t i = 0; i < bindInfoCount; ++i) {
4165 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
4166 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
4167
4168 if (mem) {
4169 image->bo = mem->bo;
4170 image->offset = pBindInfos[i].memoryOffset;
4171 } else {
4172 image->bo = NULL;
4173 image->offset = 0;
4174 }
4175 }
4176 return VK_SUCCESS;
4177 }
4178
4179
4180 VkResult radv_BindImageMemory(
4181 VkDevice device,
4182 VkImage image,
4183 VkDeviceMemory memory,
4184 VkDeviceSize memoryOffset)
4185 {
4186 const VkBindImageMemoryInfo info = {
4187 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
4188 .image = image,
4189 .memory = memory,
4190 .memoryOffset = memoryOffset
4191 };
4192
4193 return radv_BindImageMemory2(device, 1, &info);
4194 }
4195
4196
4197 static void
4198 radv_sparse_buffer_bind_memory(struct radv_device *device,
4199 const VkSparseBufferMemoryBindInfo *bind)
4200 {
4201 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
4202
4203 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4204 struct radv_device_memory *mem = NULL;
4205
4206 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4207 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4208
4209 device->ws->buffer_virtual_bind(buffer->bo,
4210 bind->pBinds[i].resourceOffset,
4211 bind->pBinds[i].size,
4212 mem ? mem->bo : NULL,
4213 bind->pBinds[i].memoryOffset);
4214 }
4215 }
4216
4217 static void
4218 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
4219 const VkSparseImageOpaqueMemoryBindInfo *bind)
4220 {
4221 RADV_FROM_HANDLE(radv_image, image, bind->image);
4222
4223 for (uint32_t i = 0; i < bind->bindCount; ++i) {
4224 struct radv_device_memory *mem = NULL;
4225
4226 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
4227 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
4228
4229 device->ws->buffer_virtual_bind(image->bo,
4230 bind->pBinds[i].resourceOffset,
4231 bind->pBinds[i].size,
4232 mem ? mem->bo : NULL,
4233 bind->pBinds[i].memoryOffset);
4234 }
4235 }
4236
4237 VkResult radv_QueueBindSparse(
4238 VkQueue _queue,
4239 uint32_t bindInfoCount,
4240 const VkBindSparseInfo* pBindInfo,
4241 VkFence _fence)
4242 {
4243 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4244 RADV_FROM_HANDLE(radv_queue, queue, _queue);
4245 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
4246 bool fence_emitted = false;
4247 VkResult result;
4248 int ret;
4249
4250 for (uint32_t i = 0; i < bindInfoCount; ++i) {
4251 struct radv_winsys_sem_info sem_info;
4252 for (uint32_t j = 0; j < pBindInfo[i].bufferBindCount; ++j) {
4253 radv_sparse_buffer_bind_memory(queue->device,
4254 pBindInfo[i].pBufferBinds + j);
4255 }
4256
4257 for (uint32_t j = 0; j < pBindInfo[i].imageOpaqueBindCount; ++j) {
4258 radv_sparse_image_opaque_bind_memory(queue->device,
4259 pBindInfo[i].pImageOpaqueBinds + j);
4260 }
4261
4262 VkResult result;
4263 result = radv_alloc_sem_info(queue->device->instance,
4264 &sem_info,
4265 pBindInfo[i].waitSemaphoreCount,
4266 pBindInfo[i].pWaitSemaphores,
4267 pBindInfo[i].signalSemaphoreCount,
4268 pBindInfo[i].pSignalSemaphores,
4269 _fence);
4270 if (result != VK_SUCCESS)
4271 return result;
4272
4273 if (pBindInfo[i].waitSemaphoreCount || pBindInfo[i].signalSemaphoreCount) {
4274 ret = queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
4275 &queue->device->empty_cs[queue->queue_family_index],
4276 1, NULL, NULL,
4277 &sem_info, NULL,
4278 false, base_fence);
4279 if (ret) {
4280 radv_loge("failed to submit CS %d\n", i);
4281 abort();
4282 }
4283
4284 fence_emitted = true;
4285 }
4286
4287 radv_free_sem_info(&sem_info);
4288
4289 }
4290
4291 if (fence) {
4292 if (!fence_emitted) {
4293 result = radv_signal_fence(queue, fence);
4294 if (result != VK_SUCCESS)
4295 return result;
4296 }
4297 }
4298
4299 return VK_SUCCESS;
4300 }
4301
4302 VkResult radv_CreateFence(
4303 VkDevice _device,
4304 const VkFenceCreateInfo* pCreateInfo,
4305 const VkAllocationCallbacks* pAllocator,
4306 VkFence* pFence)
4307 {
4308 RADV_FROM_HANDLE(radv_device, device, _device);
4309 const VkExportFenceCreateInfo *export =
4310 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
4311 VkExternalFenceHandleTypeFlags handleTypes =
4312 export ? export->handleTypes : 0;
4313
4314 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
4315 sizeof(*fence), 8,
4316 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4317
4318 if (!fence)
4319 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4320
4321 fence->fence_wsi = NULL;
4322 fence->temp_syncobj = 0;
4323 if (device->always_use_syncobj || handleTypes) {
4324 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
4325 if (ret) {
4326 vk_free2(&device->alloc, pAllocator, fence);
4327 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4328 }
4329 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
4330 device->ws->signal_syncobj(device->ws, fence->syncobj);
4331 }
4332 fence->fence = NULL;
4333 } else {
4334 fence->fence = device->ws->create_fence();
4335 if (!fence->fence) {
4336 vk_free2(&device->alloc, pAllocator, fence);
4337 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4338 }
4339 fence->syncobj = 0;
4340 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
4341 device->ws->signal_fence(fence->fence);
4342 }
4343
4344 *pFence = radv_fence_to_handle(fence);
4345
4346 return VK_SUCCESS;
4347 }
4348
4349 void radv_DestroyFence(
4350 VkDevice _device,
4351 VkFence _fence,
4352 const VkAllocationCallbacks* pAllocator)
4353 {
4354 RADV_FROM_HANDLE(radv_device, device, _device);
4355 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4356
4357 if (!fence)
4358 return;
4359
4360 if (fence->temp_syncobj)
4361 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
4362 if (fence->syncobj)
4363 device->ws->destroy_syncobj(device->ws, fence->syncobj);
4364 if (fence->fence)
4365 device->ws->destroy_fence(fence->fence);
4366 if (fence->fence_wsi)
4367 fence->fence_wsi->destroy(fence->fence_wsi);
4368 vk_free2(&device->alloc, pAllocator, fence);
4369 }
4370
4371
4372 uint64_t radv_get_current_time(void)
4373 {
4374 struct timespec tv;
4375 clock_gettime(CLOCK_MONOTONIC, &tv);
4376 return tv.tv_nsec + tv.tv_sec*1000000000ull;
4377 }
4378
4379 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
4380 {
4381 uint64_t current_time = radv_get_current_time();
4382
4383 timeout = MIN2(UINT64_MAX - current_time, timeout);
4384
4385 return current_time + timeout;
4386 }
4387
4388
4389 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
4390 uint32_t fenceCount, const VkFence *pFences)
4391 {
4392 for (uint32_t i = 0; i < fenceCount; ++i) {
4393 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4394 if (fence->fence == NULL || fence->syncobj ||
4395 fence->temp_syncobj || fence->fence_wsi ||
4396 (!device->ws->is_fence_waitable(fence->fence)))
4397 return false;
4398 }
4399 return true;
4400 }
4401
4402 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
4403 {
4404 for (uint32_t i = 0; i < fenceCount; ++i) {
4405 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4406 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
4407 return false;
4408 }
4409 return true;
4410 }
4411
4412 VkResult radv_WaitForFences(
4413 VkDevice _device,
4414 uint32_t fenceCount,
4415 const VkFence* pFences,
4416 VkBool32 waitAll,
4417 uint64_t timeout)
4418 {
4419 RADV_FROM_HANDLE(radv_device, device, _device);
4420 timeout = radv_get_absolute_timeout(timeout);
4421
4422 if (device->always_use_syncobj &&
4423 radv_all_fences_syncobj(fenceCount, pFences))
4424 {
4425 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
4426 if (!handles)
4427 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4428
4429 for (uint32_t i = 0; i < fenceCount; ++i) {
4430 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4431 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
4432 }
4433
4434 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
4435
4436 free(handles);
4437 return success ? VK_SUCCESS : VK_TIMEOUT;
4438 }
4439
4440 if (!waitAll && fenceCount > 1) {
4441 /* Not doing this by default for waitAll, due to needing to allocate twice. */
4442 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
4443 uint32_t wait_count = 0;
4444 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
4445 if (!fences)
4446 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4447
4448 for (uint32_t i = 0; i < fenceCount; ++i) {
4449 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4450
4451 if (device->ws->fence_wait(device->ws, fence->fence, false, 0)) {
4452 free(fences);
4453 return VK_SUCCESS;
4454 }
4455
4456 fences[wait_count++] = fence->fence;
4457 }
4458
4459 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
4460 waitAll, timeout - radv_get_current_time());
4461
4462 free(fences);
4463 return success ? VK_SUCCESS : VK_TIMEOUT;
4464 }
4465
4466 while(radv_get_current_time() <= timeout) {
4467 for (uint32_t i = 0; i < fenceCount; ++i) {
4468 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
4469 return VK_SUCCESS;
4470 }
4471 }
4472 return VK_TIMEOUT;
4473 }
4474
4475 for (uint32_t i = 0; i < fenceCount; ++i) {
4476 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4477 bool expired = false;
4478
4479 if (fence->temp_syncobj) {
4480 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
4481 return VK_TIMEOUT;
4482 continue;
4483 }
4484
4485 if (fence->syncobj) {
4486 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
4487 return VK_TIMEOUT;
4488 continue;
4489 }
4490
4491 if (fence->fence) {
4492 if (!device->ws->is_fence_waitable(fence->fence)) {
4493 while(!device->ws->is_fence_waitable(fence->fence) &&
4494 radv_get_current_time() <= timeout)
4495 /* Do nothing */;
4496 }
4497
4498 expired = device->ws->fence_wait(device->ws,
4499 fence->fence,
4500 true, timeout);
4501 if (!expired)
4502 return VK_TIMEOUT;
4503 }
4504
4505 if (fence->fence_wsi) {
4506 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
4507 if (result != VK_SUCCESS)
4508 return result;
4509 }
4510 }
4511
4512 return VK_SUCCESS;
4513 }
4514
4515 VkResult radv_ResetFences(VkDevice _device,
4516 uint32_t fenceCount,
4517 const VkFence *pFences)
4518 {
4519 RADV_FROM_HANDLE(radv_device, device, _device);
4520
4521 for (unsigned i = 0; i < fenceCount; ++i) {
4522 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4523 if (fence->fence)
4524 device->ws->reset_fence(fence->fence);
4525
4526 /* Per spec, we first restore the permanent payload, and then reset, so
4527 * having a temp syncobj should not skip resetting the permanent syncobj. */
4528 if (fence->temp_syncobj) {
4529 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
4530 fence->temp_syncobj = 0;
4531 }
4532
4533 if (fence->syncobj) {
4534 device->ws->reset_syncobj(device->ws, fence->syncobj);
4535 }
4536 }
4537
4538 return VK_SUCCESS;
4539 }
4540
4541 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
4542 {
4543 RADV_FROM_HANDLE(radv_device, device, _device);
4544 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4545
4546 if (fence->temp_syncobj) {
4547 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
4548 return success ? VK_SUCCESS : VK_NOT_READY;
4549 }
4550
4551 if (fence->syncobj) {
4552 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
4553 return success ? VK_SUCCESS : VK_NOT_READY;
4554 }
4555
4556 if (fence->fence) {
4557 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
4558 return VK_NOT_READY;
4559 }
4560 if (fence->fence_wsi) {
4561 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
4562
4563 if (result != VK_SUCCESS) {
4564 if (result == VK_TIMEOUT)
4565 return VK_NOT_READY;
4566 return result;
4567 }
4568 }
4569 return VK_SUCCESS;
4570 }
4571
4572
4573 // Queue semaphore functions
4574
4575 VkResult radv_CreateSemaphore(
4576 VkDevice _device,
4577 const VkSemaphoreCreateInfo* pCreateInfo,
4578 const VkAllocationCallbacks* pAllocator,
4579 VkSemaphore* pSemaphore)
4580 {
4581 RADV_FROM_HANDLE(radv_device, device, _device);
4582 const VkExportSemaphoreCreateInfo *export =
4583 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
4584 VkExternalSemaphoreHandleTypeFlags handleTypes =
4585 export ? export->handleTypes : 0;
4586
4587 struct radv_semaphore *sem = vk_alloc2(&device->alloc, pAllocator,
4588 sizeof(*sem), 8,
4589 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4590 if (!sem)
4591 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4592
4593 sem->temp_syncobj = 0;
4594 /* create a syncobject if we are going to export this semaphore */
4595 if (device->always_use_syncobj || handleTypes) {
4596 assert (device->physical_device->rad_info.has_syncobj);
4597 int ret = device->ws->create_syncobj(device->ws, &sem->syncobj);
4598 if (ret) {
4599 vk_free2(&device->alloc, pAllocator, sem);
4600 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4601 }
4602 sem->sem = NULL;
4603 } else {
4604 sem->sem = device->ws->create_sem(device->ws);
4605 if (!sem->sem) {
4606 vk_free2(&device->alloc, pAllocator, sem);
4607 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4608 }
4609 sem->syncobj = 0;
4610 }
4611
4612 *pSemaphore = radv_semaphore_to_handle(sem);
4613 return VK_SUCCESS;
4614 }
4615
4616 void radv_DestroySemaphore(
4617 VkDevice _device,
4618 VkSemaphore _semaphore,
4619 const VkAllocationCallbacks* pAllocator)
4620 {
4621 RADV_FROM_HANDLE(radv_device, device, _device);
4622 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
4623 if (!_semaphore)
4624 return;
4625
4626 if (sem->syncobj)
4627 device->ws->destroy_syncobj(device->ws, sem->syncobj);
4628 else
4629 device->ws->destroy_sem(sem->sem);
4630 vk_free2(&device->alloc, pAllocator, sem);
4631 }
4632
4633 VkResult radv_CreateEvent(
4634 VkDevice _device,
4635 const VkEventCreateInfo* pCreateInfo,
4636 const VkAllocationCallbacks* pAllocator,
4637 VkEvent* pEvent)
4638 {
4639 RADV_FROM_HANDLE(radv_device, device, _device);
4640 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
4641 sizeof(*event), 8,
4642 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4643
4644 if (!event)
4645 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4646
4647 event->bo = device->ws->buffer_create(device->ws, 8, 8,
4648 RADEON_DOMAIN_GTT,
4649 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
4650 RADV_BO_PRIORITY_FENCE);
4651 if (!event->bo) {
4652 vk_free2(&device->alloc, pAllocator, event);
4653 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4654 }
4655
4656 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
4657
4658 *pEvent = radv_event_to_handle(event);
4659
4660 return VK_SUCCESS;
4661 }
4662
4663 void radv_DestroyEvent(
4664 VkDevice _device,
4665 VkEvent _event,
4666 const VkAllocationCallbacks* pAllocator)
4667 {
4668 RADV_FROM_HANDLE(radv_device, device, _device);
4669 RADV_FROM_HANDLE(radv_event, event, _event);
4670
4671 if (!event)
4672 return;
4673 device->ws->buffer_destroy(event->bo);
4674 vk_free2(&device->alloc, pAllocator, event);
4675 }
4676
4677 VkResult radv_GetEventStatus(
4678 VkDevice _device,
4679 VkEvent _event)
4680 {
4681 RADV_FROM_HANDLE(radv_event, event, _event);
4682
4683 if (*event->map == 1)
4684 return VK_EVENT_SET;
4685 return VK_EVENT_RESET;
4686 }
4687
4688 VkResult radv_SetEvent(
4689 VkDevice _device,
4690 VkEvent _event)
4691 {
4692 RADV_FROM_HANDLE(radv_event, event, _event);
4693 *event->map = 1;
4694
4695 return VK_SUCCESS;
4696 }
4697
4698 VkResult radv_ResetEvent(
4699 VkDevice _device,
4700 VkEvent _event)
4701 {
4702 RADV_FROM_HANDLE(radv_event, event, _event);
4703 *event->map = 0;
4704
4705 return VK_SUCCESS;
4706 }
4707
4708 VkResult radv_CreateBuffer(
4709 VkDevice _device,
4710 const VkBufferCreateInfo* pCreateInfo,
4711 const VkAllocationCallbacks* pAllocator,
4712 VkBuffer* pBuffer)
4713 {
4714 RADV_FROM_HANDLE(radv_device, device, _device);
4715 struct radv_buffer *buffer;
4716
4717 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
4718
4719 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
4720 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4721 if (buffer == NULL)
4722 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4723
4724 buffer->size = pCreateInfo->size;
4725 buffer->usage = pCreateInfo->usage;
4726 buffer->bo = NULL;
4727 buffer->offset = 0;
4728 buffer->flags = pCreateInfo->flags;
4729
4730 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
4731 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
4732
4733 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
4734 buffer->bo = device->ws->buffer_create(device->ws,
4735 align64(buffer->size, 4096),
4736 4096, 0, RADEON_FLAG_VIRTUAL,
4737 RADV_BO_PRIORITY_VIRTUAL);
4738 if (!buffer->bo) {
4739 vk_free2(&device->alloc, pAllocator, buffer);
4740 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4741 }
4742 }
4743
4744 *pBuffer = radv_buffer_to_handle(buffer);
4745
4746 return VK_SUCCESS;
4747 }
4748
4749 void radv_DestroyBuffer(
4750 VkDevice _device,
4751 VkBuffer _buffer,
4752 const VkAllocationCallbacks* pAllocator)
4753 {
4754 RADV_FROM_HANDLE(radv_device, device, _device);
4755 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
4756
4757 if (!buffer)
4758 return;
4759
4760 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
4761 device->ws->buffer_destroy(buffer->bo);
4762
4763 vk_free2(&device->alloc, pAllocator, buffer);
4764 }
4765
4766 VkDeviceAddress radv_GetBufferDeviceAddressEXT(
4767 VkDevice device,
4768 const VkBufferDeviceAddressInfoEXT* pInfo)
4769 {
4770 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
4771 return radv_buffer_get_va(buffer->bo) + buffer->offset;
4772 }
4773
4774
4775 static inline unsigned
4776 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
4777 {
4778 if (stencil)
4779 return plane->surface.u.legacy.stencil_tiling_index[level];
4780 else
4781 return plane->surface.u.legacy.tiling_index[level];
4782 }
4783
4784 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
4785 {
4786 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
4787 }
4788
4789 static uint32_t
4790 radv_init_dcc_control_reg(struct radv_device *device,
4791 struct radv_image_view *iview)
4792 {
4793 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
4794 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
4795 unsigned max_compressed_block_size;
4796 unsigned independent_128b_blocks;
4797 unsigned independent_64b_blocks;
4798
4799 if (!radv_dcc_enabled(iview->image, iview->base_mip))
4800 return 0;
4801
4802 if (!device->physical_device->rad_info.has_dedicated_vram) {
4803 /* amdvlk: [min-compressed-block-size] should be set to 32 for
4804 * dGPU and 64 for APU because all of our APUs to date use
4805 * DIMMs which have a request granularity size of 64B while all
4806 * other chips have a 32B request size.
4807 */
4808 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
4809 }
4810
4811 if (device->physical_device->rad_info.chip_class >= GFX10) {
4812 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
4813 independent_64b_blocks = 0;
4814 independent_128b_blocks = 1;
4815 } else {
4816 independent_128b_blocks = 0;
4817
4818 if (iview->image->info.samples > 1) {
4819 if (iview->image->planes[0].surface.bpe == 1)
4820 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
4821 else if (iview->image->planes[0].surface.bpe == 2)
4822 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
4823 }
4824
4825 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
4826 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
4827 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
4828 /* If this DCC image is potentially going to be used in texture
4829 * fetches, we need some special settings.
4830 */
4831 independent_64b_blocks = 1;
4832 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
4833 } else {
4834 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
4835 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
4836 * big as possible for better compression state.
4837 */
4838 independent_64b_blocks = 0;
4839 max_compressed_block_size = max_uncompressed_block_size;
4840 }
4841 }
4842
4843 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
4844 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
4845 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
4846 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
4847 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
4848 }
4849
4850 void
4851 radv_initialise_color_surface(struct radv_device *device,
4852 struct radv_color_buffer_info *cb,
4853 struct radv_image_view *iview)
4854 {
4855 const struct vk_format_description *desc;
4856 unsigned ntype, format, swap, endian;
4857 unsigned blend_clamp = 0, blend_bypass = 0;
4858 uint64_t va;
4859 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
4860 const struct radeon_surf *surf = &plane->surface;
4861
4862 desc = vk_format_description(iview->vk_format);
4863
4864 memset(cb, 0, sizeof(*cb));
4865
4866 /* Intensity is implemented as Red, so treat it that way. */
4867 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
4868
4869 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
4870
4871 cb->cb_color_base = va >> 8;
4872
4873 if (device->physical_device->rad_info.chip_class >= GFX9) {
4874 struct gfx9_surf_meta_flags meta;
4875 if (iview->image->dcc_offset)
4876 meta = surf->u.gfx9.dcc;
4877 else
4878 meta = surf->u.gfx9.cmask;
4879
4880 if (device->physical_device->rad_info.chip_class >= GFX10) {
4881 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
4882 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
4883 S_028EE0_CMASK_PIPE_ALIGNED(surf->u.gfx9.cmask.pipe_aligned) |
4884 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
4885 } else {
4886 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
4887 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
4888 S_028C74_RB_ALIGNED(meta.rb_aligned) |
4889 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
4890 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
4891 }
4892
4893 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
4894 cb->cb_color_base |= surf->tile_swizzle;
4895 } else {
4896 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
4897 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
4898
4899 cb->cb_color_base += level_info->offset >> 8;
4900 if (level_info->mode == RADEON_SURF_MODE_2D)
4901 cb->cb_color_base |= surf->tile_swizzle;
4902
4903 pitch_tile_max = level_info->nblk_x / 8 - 1;
4904 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
4905 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
4906
4907 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
4908 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
4909 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
4910
4911 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
4912
4913 if (radv_image_has_fmask(iview->image)) {
4914 if (device->physical_device->rad_info.chip_class >= GFX7)
4915 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
4916 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
4917 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
4918 } else {
4919 /* This must be set for fast clear to work without FMASK. */
4920 if (device->physical_device->rad_info.chip_class >= GFX7)
4921 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
4922 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
4923 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
4924 }
4925 }
4926
4927 /* CMASK variables */
4928 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4929 va += iview->image->cmask_offset;
4930 cb->cb_color_cmask = va >> 8;
4931
4932 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4933 va += iview->image->dcc_offset;
4934
4935 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
4936 device->physical_device->rad_info.chip_class <= GFX8)
4937 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
4938
4939 unsigned dcc_tile_swizzle = surf->tile_swizzle;
4940 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
4941
4942 cb->cb_dcc_base = va >> 8;
4943 cb->cb_dcc_base |= dcc_tile_swizzle;
4944
4945 /* GFX10 field has the same base shift as the GFX6 field. */
4946 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
4947 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
4948 S_028C6C_SLICE_MAX_GFX10(max_slice);
4949
4950 if (iview->image->info.samples > 1) {
4951 unsigned log_samples = util_logbase2(iview->image->info.samples);
4952
4953 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
4954 S_028C74_NUM_FRAGMENTS(log_samples);
4955 }
4956
4957 if (radv_image_has_fmask(iview->image)) {
4958 va = radv_buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask_offset;
4959 cb->cb_color_fmask = va >> 8;
4960 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
4961 } else {
4962 cb->cb_color_fmask = cb->cb_color_base;
4963 }
4964
4965 ntype = radv_translate_color_numformat(iview->vk_format,
4966 desc,
4967 vk_format_get_first_non_void_channel(iview->vk_format));
4968 format = radv_translate_colorformat(iview->vk_format);
4969 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
4970 radv_finishme("Illegal color\n");
4971 swap = radv_translate_colorswap(iview->vk_format, false);
4972 endian = radv_colorformat_endian_swap(format);
4973
4974 /* blend clamp should be set for all NORM/SRGB types */
4975 if (ntype == V_028C70_NUMBER_UNORM ||
4976 ntype == V_028C70_NUMBER_SNORM ||
4977 ntype == V_028C70_NUMBER_SRGB)
4978 blend_clamp = 1;
4979
4980 /* set blend bypass according to docs if SINT/UINT or
4981 8/24 COLOR variants */
4982 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
4983 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
4984 format == V_028C70_COLOR_X24_8_32_FLOAT) {
4985 blend_clamp = 0;
4986 blend_bypass = 1;
4987 }
4988 #if 0
4989 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
4990 (format == V_028C70_COLOR_8 ||
4991 format == V_028C70_COLOR_8_8 ||
4992 format == V_028C70_COLOR_8_8_8_8))
4993 ->color_is_int8 = true;
4994 #endif
4995 cb->cb_color_info = S_028C70_FORMAT(format) |
4996 S_028C70_COMP_SWAP(swap) |
4997 S_028C70_BLEND_CLAMP(blend_clamp) |
4998 S_028C70_BLEND_BYPASS(blend_bypass) |
4999 S_028C70_SIMPLE_FLOAT(1) |
5000 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
5001 ntype != V_028C70_NUMBER_SNORM &&
5002 ntype != V_028C70_NUMBER_SRGB &&
5003 format != V_028C70_COLOR_8_24 &&
5004 format != V_028C70_COLOR_24_8) |
5005 S_028C70_NUMBER_TYPE(ntype) |
5006 S_028C70_ENDIAN(endian);
5007 if (radv_image_has_fmask(iview->image)) {
5008 cb->cb_color_info |= S_028C70_COMPRESSION(1);
5009 if (device->physical_device->rad_info.chip_class == GFX6) {
5010 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
5011 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
5012 }
5013
5014 if (radv_image_is_tc_compat_cmask(iview->image)) {
5015 /* Allow the texture block to read FMASK directly
5016 * without decompressing it. This bit must be cleared
5017 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
5018 * otherwise the operation doesn't happen.
5019 */
5020 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
5021
5022 /* Set CMASK into a tiling format that allows the
5023 * texture block to read it.
5024 */
5025 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
5026 }
5027 }
5028
5029 if (radv_image_has_cmask(iview->image) &&
5030 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
5031 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
5032
5033 if (radv_dcc_enabled(iview->image, iview->base_mip))
5034 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
5035
5036 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
5037
5038 /* This must be set for fast clear to work without FMASK. */
5039 if (!radv_image_has_fmask(iview->image) &&
5040 device->physical_device->rad_info.chip_class == GFX6) {
5041 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
5042 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
5043 }
5044
5045 if (device->physical_device->rad_info.chip_class >= GFX9) {
5046 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
5047
5048 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
5049 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
5050 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
5051 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
5052
5053 if (device->physical_device->rad_info.chip_class >= GFX10) {
5054 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
5055
5056 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
5057 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
5058 S_028EE0_RESOURCE_LEVEL(1);
5059 } else {
5060 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
5061 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
5062 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
5063 }
5064
5065 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
5066 S_028C68_MIP0_HEIGHT(height - 1) |
5067 S_028C68_MAX_MIP(iview->image->info.levels - 1);
5068 }
5069 }
5070
5071 static unsigned
5072 radv_calc_decompress_on_z_planes(struct radv_device *device,
5073 struct radv_image_view *iview)
5074 {
5075 unsigned max_zplanes = 0;
5076
5077 assert(radv_image_is_tc_compat_htile(iview->image));
5078
5079 if (device->physical_device->rad_info.chip_class >= GFX9) {
5080 /* Default value for 32-bit depth surfaces. */
5081 max_zplanes = 4;
5082
5083 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
5084 iview->image->info.samples > 1)
5085 max_zplanes = 2;
5086
5087 max_zplanes = max_zplanes + 1;
5088 } else {
5089 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
5090 /* Do not enable Z plane compression for 16-bit depth
5091 * surfaces because isn't supported on GFX8. Only
5092 * 32-bit depth surfaces are supported by the hardware.
5093 * This allows to maintain shader compatibility and to
5094 * reduce the number of depth decompressions.
5095 */
5096 max_zplanes = 1;
5097 } else {
5098 if (iview->image->info.samples <= 1)
5099 max_zplanes = 5;
5100 else if (iview->image->info.samples <= 4)
5101 max_zplanes = 3;
5102 else
5103 max_zplanes = 2;
5104 }
5105 }
5106
5107 return max_zplanes;
5108 }
5109
5110 void
5111 radv_initialise_ds_surface(struct radv_device *device,
5112 struct radv_ds_buffer_info *ds,
5113 struct radv_image_view *iview)
5114 {
5115 unsigned level = iview->base_mip;
5116 unsigned format, stencil_format;
5117 uint64_t va, s_offs, z_offs;
5118 bool stencil_only = false;
5119 const struct radv_image_plane *plane = &iview->image->planes[0];
5120 const struct radeon_surf *surf = &plane->surface;
5121
5122 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
5123
5124 memset(ds, 0, sizeof(*ds));
5125 switch (iview->image->vk_format) {
5126 case VK_FORMAT_D24_UNORM_S8_UINT:
5127 case VK_FORMAT_X8_D24_UNORM_PACK32:
5128 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
5129 ds->offset_scale = 2.0f;
5130 break;
5131 case VK_FORMAT_D16_UNORM:
5132 case VK_FORMAT_D16_UNORM_S8_UINT:
5133 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
5134 ds->offset_scale = 4.0f;
5135 break;
5136 case VK_FORMAT_D32_SFLOAT:
5137 case VK_FORMAT_D32_SFLOAT_S8_UINT:
5138 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
5139 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
5140 ds->offset_scale = 1.0f;
5141 break;
5142 case VK_FORMAT_S8_UINT:
5143 stencil_only = true;
5144 break;
5145 default:
5146 break;
5147 }
5148
5149 format = radv_translate_dbformat(iview->image->vk_format);
5150 stencil_format = surf->has_stencil ?
5151 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
5152
5153 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
5154 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
5155 S_028008_SLICE_MAX(max_slice);
5156 if (device->physical_device->rad_info.chip_class >= GFX10) {
5157 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
5158 S_028008_SLICE_MAX_HI(max_slice >> 11);
5159 }
5160
5161 ds->db_htile_data_base = 0;
5162 ds->db_htile_surface = 0;
5163
5164 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
5165 s_offs = z_offs = va;
5166
5167 if (device->physical_device->rad_info.chip_class >= GFX9) {
5168 assert(surf->u.gfx9.surf_offset == 0);
5169 s_offs += surf->u.gfx9.stencil_offset;
5170
5171 ds->db_z_info = S_028038_FORMAT(format) |
5172 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
5173 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
5174 S_028038_MAXMIP(iview->image->info.levels - 1) |
5175 S_028038_ZRANGE_PRECISION(1);
5176 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
5177 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
5178
5179 if (device->physical_device->rad_info.chip_class == GFX9) {
5180 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
5181 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
5182 }
5183
5184 ds->db_depth_view |= S_028008_MIPID(level);
5185 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
5186 S_02801C_Y_MAX(iview->image->info.height - 1);
5187
5188 if (radv_htile_enabled(iview->image, level)) {
5189 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
5190
5191 if (radv_image_is_tc_compat_htile(iview->image)) {
5192 unsigned max_zplanes =
5193 radv_calc_decompress_on_z_planes(device, iview);
5194
5195 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
5196
5197 if (device->physical_device->rad_info.chip_class >= GFX10) {
5198 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
5199 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
5200 } else {
5201 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
5202 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
5203 }
5204 }
5205
5206 if (!surf->has_stencil)
5207 /* Use all of the htile_buffer for depth if there's no stencil. */
5208 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
5209 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
5210 iview->image->htile_offset;
5211 ds->db_htile_data_base = va >> 8;
5212 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
5213 S_028ABC_PIPE_ALIGNED(surf->u.gfx9.htile.pipe_aligned);
5214
5215 if (device->physical_device->rad_info.chip_class == GFX9) {
5216 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(surf->u.gfx9.htile.rb_aligned);
5217 }
5218 }
5219 } else {
5220 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
5221
5222 if (stencil_only)
5223 level_info = &surf->u.legacy.stencil_level[level];
5224
5225 z_offs += surf->u.legacy.level[level].offset;
5226 s_offs += surf->u.legacy.stencil_level[level].offset;
5227
5228 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
5229 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
5230 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
5231
5232 if (iview->image->info.samples > 1)
5233 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
5234
5235 if (device->physical_device->rad_info.chip_class >= GFX7) {
5236 struct radeon_info *info = &device->physical_device->rad_info;
5237 unsigned tiling_index = surf->u.legacy.tiling_index[level];
5238 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
5239 unsigned macro_index = surf->u.legacy.macro_tile_index;
5240 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
5241 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
5242 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
5243
5244 if (stencil_only)
5245 tile_mode = stencil_tile_mode;
5246
5247 ds->db_depth_info |=
5248 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
5249 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
5250 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
5251 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
5252 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
5253 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
5254 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
5255 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
5256 } else {
5257 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
5258 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
5259 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
5260 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
5261 if (stencil_only)
5262 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
5263 }
5264
5265 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
5266 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
5267 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
5268
5269 if (radv_htile_enabled(iview->image, level)) {
5270 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
5271
5272 if (!surf->has_stencil &&
5273 !radv_image_is_tc_compat_htile(iview->image))
5274 /* Use all of the htile_buffer for depth if there's no stencil. */
5275 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
5276
5277 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
5278 iview->image->htile_offset;
5279 ds->db_htile_data_base = va >> 8;
5280 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
5281
5282 if (radv_image_is_tc_compat_htile(iview->image)) {
5283 unsigned max_zplanes =
5284 radv_calc_decompress_on_z_planes(device, iview);
5285
5286 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
5287 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
5288 }
5289 }
5290 }
5291
5292 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
5293 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
5294 }
5295
5296 VkResult radv_CreateFramebuffer(
5297 VkDevice _device,
5298 const VkFramebufferCreateInfo* pCreateInfo,
5299 const VkAllocationCallbacks* pAllocator,
5300 VkFramebuffer* pFramebuffer)
5301 {
5302 RADV_FROM_HANDLE(radv_device, device, _device);
5303 struct radv_framebuffer *framebuffer;
5304 const VkFramebufferAttachmentsCreateInfoKHR *imageless_create_info =
5305 vk_find_struct_const(pCreateInfo->pNext,
5306 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO_KHR);
5307
5308 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
5309
5310 size_t size = sizeof(*framebuffer);
5311 if (!imageless_create_info)
5312 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
5313 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
5314 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5315 if (framebuffer == NULL)
5316 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5317
5318 framebuffer->attachment_count = pCreateInfo->attachmentCount;
5319 framebuffer->width = pCreateInfo->width;
5320 framebuffer->height = pCreateInfo->height;
5321 framebuffer->layers = pCreateInfo->layers;
5322 if (imageless_create_info) {
5323 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
5324 const VkFramebufferAttachmentImageInfoKHR *attachment =
5325 imageless_create_info->pAttachmentImageInfos + i;
5326 framebuffer->width = MIN2(framebuffer->width, attachment->width);
5327 framebuffer->height = MIN2(framebuffer->height, attachment->height);
5328 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
5329 }
5330 } else {
5331 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
5332 VkImageView _iview = pCreateInfo->pAttachments[i];
5333 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
5334 framebuffer->attachments[i] = iview;
5335 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
5336 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
5337 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
5338 }
5339 }
5340
5341 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
5342 return VK_SUCCESS;
5343 }
5344
5345 void radv_DestroyFramebuffer(
5346 VkDevice _device,
5347 VkFramebuffer _fb,
5348 const VkAllocationCallbacks* pAllocator)
5349 {
5350 RADV_FROM_HANDLE(radv_device, device, _device);
5351 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
5352
5353 if (!fb)
5354 return;
5355 vk_free2(&device->alloc, pAllocator, fb);
5356 }
5357
5358 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
5359 {
5360 switch (address_mode) {
5361 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
5362 return V_008F30_SQ_TEX_WRAP;
5363 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
5364 return V_008F30_SQ_TEX_MIRROR;
5365 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
5366 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
5367 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
5368 return V_008F30_SQ_TEX_CLAMP_BORDER;
5369 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
5370 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
5371 default:
5372 unreachable("illegal tex wrap mode");
5373 break;
5374 }
5375 }
5376
5377 static unsigned
5378 radv_tex_compare(VkCompareOp op)
5379 {
5380 switch (op) {
5381 case VK_COMPARE_OP_NEVER:
5382 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
5383 case VK_COMPARE_OP_LESS:
5384 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
5385 case VK_COMPARE_OP_EQUAL:
5386 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
5387 case VK_COMPARE_OP_LESS_OR_EQUAL:
5388 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
5389 case VK_COMPARE_OP_GREATER:
5390 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
5391 case VK_COMPARE_OP_NOT_EQUAL:
5392 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
5393 case VK_COMPARE_OP_GREATER_OR_EQUAL:
5394 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
5395 case VK_COMPARE_OP_ALWAYS:
5396 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
5397 default:
5398 unreachable("illegal compare mode");
5399 break;
5400 }
5401 }
5402
5403 static unsigned
5404 radv_tex_filter(VkFilter filter, unsigned max_ansio)
5405 {
5406 switch (filter) {
5407 case VK_FILTER_NEAREST:
5408 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
5409 V_008F38_SQ_TEX_XY_FILTER_POINT);
5410 case VK_FILTER_LINEAR:
5411 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
5412 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
5413 case VK_FILTER_CUBIC_IMG:
5414 default:
5415 fprintf(stderr, "illegal texture filter");
5416 return 0;
5417 }
5418 }
5419
5420 static unsigned
5421 radv_tex_mipfilter(VkSamplerMipmapMode mode)
5422 {
5423 switch (mode) {
5424 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
5425 return V_008F38_SQ_TEX_Z_FILTER_POINT;
5426 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
5427 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
5428 default:
5429 return V_008F38_SQ_TEX_Z_FILTER_NONE;
5430 }
5431 }
5432
5433 static unsigned
5434 radv_tex_bordercolor(VkBorderColor bcolor)
5435 {
5436 switch (bcolor) {
5437 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
5438 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
5439 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
5440 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
5441 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
5442 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
5443 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
5444 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
5445 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
5446 default:
5447 break;
5448 }
5449 return 0;
5450 }
5451
5452 static unsigned
5453 radv_tex_aniso_filter(unsigned filter)
5454 {
5455 if (filter < 2)
5456 return 0;
5457 if (filter < 4)
5458 return 1;
5459 if (filter < 8)
5460 return 2;
5461 if (filter < 16)
5462 return 3;
5463 return 4;
5464 }
5465
5466 static unsigned
5467 radv_tex_filter_mode(VkSamplerReductionModeEXT mode)
5468 {
5469 switch (mode) {
5470 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
5471 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
5472 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
5473 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
5474 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
5475 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
5476 default:
5477 break;
5478 }
5479 return 0;
5480 }
5481
5482 static uint32_t
5483 radv_get_max_anisotropy(struct radv_device *device,
5484 const VkSamplerCreateInfo *pCreateInfo)
5485 {
5486 if (device->force_aniso >= 0)
5487 return device->force_aniso;
5488
5489 if (pCreateInfo->anisotropyEnable &&
5490 pCreateInfo->maxAnisotropy > 1.0f)
5491 return (uint32_t)pCreateInfo->maxAnisotropy;
5492
5493 return 0;
5494 }
5495
5496 static void
5497 radv_init_sampler(struct radv_device *device,
5498 struct radv_sampler *sampler,
5499 const VkSamplerCreateInfo *pCreateInfo)
5500 {
5501 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
5502 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
5503 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
5504 device->physical_device->rad_info.chip_class == GFX9;
5505 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
5506
5507 const struct VkSamplerReductionModeCreateInfoEXT *sampler_reduction =
5508 vk_find_struct_const(pCreateInfo->pNext,
5509 SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT);
5510 if (sampler_reduction)
5511 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
5512
5513 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
5514 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
5515 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
5516 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
5517 S_008F30_DEPTH_COMPARE_FUNC(radv_tex_compare(pCreateInfo->compareOp)) |
5518 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
5519 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
5520 S_008F30_ANISO_BIAS(max_aniso_ratio) |
5521 S_008F30_DISABLE_CUBE_WRAP(0) |
5522 S_008F30_COMPAT_MODE(compat_mode) |
5523 S_008F30_FILTER_MODE(filter_mode));
5524 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
5525 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
5526 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
5527 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
5528 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
5529 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
5530 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
5531 S_008F38_MIP_POINT_PRECLAMP(0));
5532 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
5533 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
5534
5535 if (device->physical_device->rad_info.chip_class >= GFX10) {
5536 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
5537 } else {
5538 sampler->state[2] |=
5539 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
5540 S_008F38_FILTER_PREC_FIX(1) |
5541 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
5542 }
5543 }
5544
5545 VkResult radv_CreateSampler(
5546 VkDevice _device,
5547 const VkSamplerCreateInfo* pCreateInfo,
5548 const VkAllocationCallbacks* pAllocator,
5549 VkSampler* pSampler)
5550 {
5551 RADV_FROM_HANDLE(radv_device, device, _device);
5552 struct radv_sampler *sampler;
5553
5554 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
5555 vk_find_struct_const(pCreateInfo->pNext,
5556 SAMPLER_YCBCR_CONVERSION_INFO);
5557
5558 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
5559
5560 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
5561 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5562 if (!sampler)
5563 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5564
5565 radv_init_sampler(device, sampler, pCreateInfo);
5566
5567 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
5568 *pSampler = radv_sampler_to_handle(sampler);
5569
5570 return VK_SUCCESS;
5571 }
5572
5573 void radv_DestroySampler(
5574 VkDevice _device,
5575 VkSampler _sampler,
5576 const VkAllocationCallbacks* pAllocator)
5577 {
5578 RADV_FROM_HANDLE(radv_device, device, _device);
5579 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
5580
5581 if (!sampler)
5582 return;
5583 vk_free2(&device->alloc, pAllocator, sampler);
5584 }
5585
5586 /* vk_icd.h does not declare this function, so we declare it here to
5587 * suppress Wmissing-prototypes.
5588 */
5589 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
5590 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
5591
5592 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
5593 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
5594 {
5595 /* For the full details on loader interface versioning, see
5596 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
5597 * What follows is a condensed summary, to help you navigate the large and
5598 * confusing official doc.
5599 *
5600 * - Loader interface v0 is incompatible with later versions. We don't
5601 * support it.
5602 *
5603 * - In loader interface v1:
5604 * - The first ICD entrypoint called by the loader is
5605 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
5606 * entrypoint.
5607 * - The ICD must statically expose no other Vulkan symbol unless it is
5608 * linked with -Bsymbolic.
5609 * - Each dispatchable Vulkan handle created by the ICD must be
5610 * a pointer to a struct whose first member is VK_LOADER_DATA. The
5611 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
5612 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
5613 * vkDestroySurfaceKHR(). The ICD must be capable of working with
5614 * such loader-managed surfaces.
5615 *
5616 * - Loader interface v2 differs from v1 in:
5617 * - The first ICD entrypoint called by the loader is
5618 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
5619 * statically expose this entrypoint.
5620 *
5621 * - Loader interface v3 differs from v2 in:
5622 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
5623 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
5624 * because the loader no longer does so.
5625 */
5626 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
5627 return VK_SUCCESS;
5628 }
5629
5630 VkResult radv_GetMemoryFdKHR(VkDevice _device,
5631 const VkMemoryGetFdInfoKHR *pGetFdInfo,
5632 int *pFD)
5633 {
5634 RADV_FROM_HANDLE(radv_device, device, _device);
5635 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
5636
5637 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
5638
5639 /* At the moment, we support only the below handle types. */
5640 assert(pGetFdInfo->handleType ==
5641 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
5642 pGetFdInfo->handleType ==
5643 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
5644
5645 bool ret = radv_get_memory_fd(device, memory, pFD);
5646 if (ret == false)
5647 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
5648 return VK_SUCCESS;
5649 }
5650
5651 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
5652 VkExternalMemoryHandleTypeFlagBits handleType,
5653 int fd,
5654 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
5655 {
5656 RADV_FROM_HANDLE(radv_device, device, _device);
5657
5658 switch (handleType) {
5659 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
5660 pMemoryFdProperties->memoryTypeBits = (1 << RADV_MEM_TYPE_COUNT) - 1;
5661 return VK_SUCCESS;
5662
5663 default:
5664 /* The valid usage section for this function says:
5665 *
5666 * "handleType must not be one of the handle types defined as
5667 * opaque."
5668 *
5669 * So opaque handle types fall into the default "unsupported" case.
5670 */
5671 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5672 }
5673 }
5674
5675 static VkResult radv_import_opaque_fd(struct radv_device *device,
5676 int fd,
5677 uint32_t *syncobj)
5678 {
5679 uint32_t syncobj_handle = 0;
5680 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
5681 if (ret != 0)
5682 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5683
5684 if (*syncobj)
5685 device->ws->destroy_syncobj(device->ws, *syncobj);
5686
5687 *syncobj = syncobj_handle;
5688 close(fd);
5689
5690 return VK_SUCCESS;
5691 }
5692
5693 static VkResult radv_import_sync_fd(struct radv_device *device,
5694 int fd,
5695 uint32_t *syncobj)
5696 {
5697 /* If we create a syncobj we do it locally so that if we have an error, we don't
5698 * leave a syncobj in an undetermined state in the fence. */
5699 uint32_t syncobj_handle = *syncobj;
5700 if (!syncobj_handle) {
5701 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
5702 if (ret) {
5703 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5704 }
5705 }
5706
5707 if (fd == -1) {
5708 device->ws->signal_syncobj(device->ws, syncobj_handle);
5709 } else {
5710 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
5711 if (ret != 0)
5712 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5713 }
5714
5715 *syncobj = syncobj_handle;
5716 if (fd != -1)
5717 close(fd);
5718
5719 return VK_SUCCESS;
5720 }
5721
5722 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
5723 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
5724 {
5725 RADV_FROM_HANDLE(radv_device, device, _device);
5726 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
5727 uint32_t *syncobj_dst = NULL;
5728
5729 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
5730 syncobj_dst = &sem->temp_syncobj;
5731 } else {
5732 syncobj_dst = &sem->syncobj;
5733 }
5734
5735 switch(pImportSemaphoreFdInfo->handleType) {
5736 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
5737 return radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, syncobj_dst);
5738 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
5739 return radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, syncobj_dst);
5740 default:
5741 unreachable("Unhandled semaphore handle type");
5742 }
5743 }
5744
5745 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
5746 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
5747 int *pFd)
5748 {
5749 RADV_FROM_HANDLE(radv_device, device, _device);
5750 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
5751 int ret;
5752 uint32_t syncobj_handle;
5753
5754 if (sem->temp_syncobj)
5755 syncobj_handle = sem->temp_syncobj;
5756 else
5757 syncobj_handle = sem->syncobj;
5758
5759 switch(pGetFdInfo->handleType) {
5760 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
5761 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
5762 break;
5763 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
5764 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
5765 if (!ret) {
5766 if (sem->temp_syncobj) {
5767 close (sem->temp_syncobj);
5768 sem->temp_syncobj = 0;
5769 } else {
5770 device->ws->reset_syncobj(device->ws, syncobj_handle);
5771 }
5772 }
5773 break;
5774 default:
5775 unreachable("Unhandled semaphore handle type");
5776 }
5777
5778 if (ret)
5779 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5780 return VK_SUCCESS;
5781 }
5782
5783 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
5784 VkPhysicalDevice physicalDevice,
5785 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
5786 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
5787 {
5788 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
5789
5790 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
5791 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
5792 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
5793 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
5794 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
5795 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
5796 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
5797 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5798 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
5799 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
5800 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
5801 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
5802 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5803 } else {
5804 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
5805 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
5806 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
5807 }
5808 }
5809
5810 VkResult radv_ImportFenceFdKHR(VkDevice _device,
5811 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
5812 {
5813 RADV_FROM_HANDLE(radv_device, device, _device);
5814 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
5815 uint32_t *syncobj_dst = NULL;
5816
5817
5818 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
5819 syncobj_dst = &fence->temp_syncobj;
5820 } else {
5821 syncobj_dst = &fence->syncobj;
5822 }
5823
5824 switch(pImportFenceFdInfo->handleType) {
5825 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
5826 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
5827 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
5828 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
5829 default:
5830 unreachable("Unhandled fence handle type");
5831 }
5832 }
5833
5834 VkResult radv_GetFenceFdKHR(VkDevice _device,
5835 const VkFenceGetFdInfoKHR *pGetFdInfo,
5836 int *pFd)
5837 {
5838 RADV_FROM_HANDLE(radv_device, device, _device);
5839 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
5840 int ret;
5841 uint32_t syncobj_handle;
5842
5843 if (fence->temp_syncobj)
5844 syncobj_handle = fence->temp_syncobj;
5845 else
5846 syncobj_handle = fence->syncobj;
5847
5848 switch(pGetFdInfo->handleType) {
5849 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
5850 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
5851 break;
5852 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
5853 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
5854 if (!ret) {
5855 if (fence->temp_syncobj) {
5856 close (fence->temp_syncobj);
5857 fence->temp_syncobj = 0;
5858 } else {
5859 device->ws->reset_syncobj(device->ws, syncobj_handle);
5860 }
5861 }
5862 break;
5863 default:
5864 unreachable("Unhandled fence handle type");
5865 }
5866
5867 if (ret)
5868 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5869 return VK_SUCCESS;
5870 }
5871
5872 void radv_GetPhysicalDeviceExternalFenceProperties(
5873 VkPhysicalDevice physicalDevice,
5874 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
5875 VkExternalFenceProperties *pExternalFenceProperties)
5876 {
5877 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
5878
5879 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
5880 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
5881 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
5882 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
5883 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
5884 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
5885 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5886 } else {
5887 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
5888 pExternalFenceProperties->compatibleHandleTypes = 0;
5889 pExternalFenceProperties->externalFenceFeatures = 0;
5890 }
5891 }
5892
5893 VkResult
5894 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
5895 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
5896 const VkAllocationCallbacks* pAllocator,
5897 VkDebugReportCallbackEXT* pCallback)
5898 {
5899 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5900 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
5901 pCreateInfo, pAllocator, &instance->alloc,
5902 pCallback);
5903 }
5904
5905 void
5906 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
5907 VkDebugReportCallbackEXT _callback,
5908 const VkAllocationCallbacks* pAllocator)
5909 {
5910 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5911 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
5912 _callback, pAllocator, &instance->alloc);
5913 }
5914
5915 void
5916 radv_DebugReportMessageEXT(VkInstance _instance,
5917 VkDebugReportFlagsEXT flags,
5918 VkDebugReportObjectTypeEXT objectType,
5919 uint64_t object,
5920 size_t location,
5921 int32_t messageCode,
5922 const char* pLayerPrefix,
5923 const char* pMessage)
5924 {
5925 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5926 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
5927 object, location, messageCode, pLayerPrefix, pMessage);
5928 }
5929
5930 void
5931 radv_GetDeviceGroupPeerMemoryFeatures(
5932 VkDevice device,
5933 uint32_t heapIndex,
5934 uint32_t localDeviceIndex,
5935 uint32_t remoteDeviceIndex,
5936 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
5937 {
5938 assert(localDeviceIndex == remoteDeviceIndex);
5939
5940 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
5941 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
5942 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
5943 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
5944 }
5945
5946 static const VkTimeDomainEXT radv_time_domains[] = {
5947 VK_TIME_DOMAIN_DEVICE_EXT,
5948 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
5949 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
5950 };
5951
5952 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
5953 VkPhysicalDevice physicalDevice,
5954 uint32_t *pTimeDomainCount,
5955 VkTimeDomainEXT *pTimeDomains)
5956 {
5957 int d;
5958 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
5959
5960 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
5961 vk_outarray_append(&out, i) {
5962 *i = radv_time_domains[d];
5963 }
5964 }
5965
5966 return vk_outarray_status(&out);
5967 }
5968
5969 static uint64_t
5970 radv_clock_gettime(clockid_t clock_id)
5971 {
5972 struct timespec current;
5973 int ret;
5974
5975 ret = clock_gettime(clock_id, &current);
5976 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
5977 ret = clock_gettime(CLOCK_MONOTONIC, &current);
5978 if (ret < 0)
5979 return 0;
5980
5981 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
5982 }
5983
5984 VkResult radv_GetCalibratedTimestampsEXT(
5985 VkDevice _device,
5986 uint32_t timestampCount,
5987 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
5988 uint64_t *pTimestamps,
5989 uint64_t *pMaxDeviation)
5990 {
5991 RADV_FROM_HANDLE(radv_device, device, _device);
5992 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
5993 int d;
5994 uint64_t begin, end;
5995 uint64_t max_clock_period = 0;
5996
5997 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
5998
5999 for (d = 0; d < timestampCount; d++) {
6000 switch (pTimestampInfos[d].timeDomain) {
6001 case VK_TIME_DOMAIN_DEVICE_EXT:
6002 pTimestamps[d] = device->ws->query_value(device->ws,
6003 RADEON_TIMESTAMP);
6004 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
6005 max_clock_period = MAX2(max_clock_period, device_period);
6006 break;
6007 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
6008 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
6009 max_clock_period = MAX2(max_clock_period, 1);
6010 break;
6011
6012 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
6013 pTimestamps[d] = begin;
6014 break;
6015 default:
6016 pTimestamps[d] = 0;
6017 break;
6018 }
6019 }
6020
6021 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
6022
6023 /*
6024 * The maximum deviation is the sum of the interval over which we
6025 * perform the sampling and the maximum period of any sampled
6026 * clock. That's because the maximum skew between any two sampled
6027 * clock edges is when the sampled clock with the largest period is
6028 * sampled at the end of that period but right at the beginning of the
6029 * sampling interval and some other clock is sampled right at the
6030 * begining of its sampling period and right at the end of the
6031 * sampling interval. Let's assume the GPU has the longest clock
6032 * period and that the application is sampling GPU and monotonic:
6033 *
6034 * s e
6035 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
6036 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
6037 *
6038 * g
6039 * 0 1 2 3
6040 * GPU -----_____-----_____-----_____-----_____
6041 *
6042 * m
6043 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
6044 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
6045 *
6046 * Interval <----------------->
6047 * Deviation <-------------------------->
6048 *
6049 * s = read(raw) 2
6050 * g = read(GPU) 1
6051 * m = read(monotonic) 2
6052 * e = read(raw) b
6053 *
6054 * We round the sample interval up by one tick to cover sampling error
6055 * in the interval clock
6056 */
6057
6058 uint64_t sample_interval = end - begin + 1;
6059
6060 *pMaxDeviation = sample_interval + max_clock_period;
6061
6062 return VK_SUCCESS;
6063 }
6064
6065 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
6066 VkPhysicalDevice physicalDevice,
6067 VkSampleCountFlagBits samples,
6068 VkMultisamplePropertiesEXT* pMultisampleProperties)
6069 {
6070 if (samples & (VK_SAMPLE_COUNT_2_BIT |
6071 VK_SAMPLE_COUNT_4_BIT |
6072 VK_SAMPLE_COUNT_8_BIT)) {
6073 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
6074 } else {
6075 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
6076 }
6077 }