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