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