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