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