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