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