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