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