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