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