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