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