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