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