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