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