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