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