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