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