radv_device.c 179 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
/*
 * Copyright © 2016 Red Hat.
 * Copyright © 2016 Bas Nieuwenhuizen
 *
 * based in part on anv driver which is:
 * Copyright © 2015 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
32
#include "radv_debug.h"
33
#include "radv_private.h"
34
#include "radv_shader.h"
35
#include "radv_cs.h"
36
#include "util/disk_cache.h"
37
#include "util/strtod.h"
38
#include "vk_util.h"
39
#include <xf86drm.h>
40 41 42 43 44 45
#include <amdgpu.h>
#include <amdgpu_drm.h>
#include "winsys/amdgpu/radv_amdgpu_winsys_public.h"
#include "ac_llvm_util.h"
#include "vk_format.h"
#include "sid.h"
46
#include "git_sha1.h"
47
#include "gfx9d.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

53
static int
54
radv_device_get_cache_uuid(enum radeon_family family, void *uuid)
55
{
56 57 58
	struct mesa_sha1 ctx;
	unsigned char sha1[20];
	unsigned ptr_size = sizeof(void*);
59

60
	memset(uuid, 0, VK_UUID_SIZE);
61
	_mesa_sha1_init(&ctx);
62

63 64
	if (!disk_cache_get_function_identifier(radv_device_get_cache_uuid, &ctx) ||
	    !disk_cache_get_function_identifier(LLVMInitializeAMDGPUTargetInfo, &ctx))
65 66
		return -1;

67 68 69 70 71
	_mesa_sha1_update(&ctx, &family, sizeof(family));
	_mesa_sha1_update(&ctx, &ptr_size, sizeof(ptr_size));
	_mesa_sha1_final(&ctx, sha1);

	memcpy(uuid, sha1, VK_UUID_SIZE);
72
	return 0;
73 74
}

75 76 77 78 79 80
static void
radv_get_driver_uuid(void *uuid)
{
	ac_compute_driver_uuid(uuid, VK_UUID_SIZE);
}

81
static void
82 83 84
radv_get_device_uuid(struct radeon_info *info, void *uuid)
{
	ac_compute_device_uuid(info, uuid, VK_UUID_SIZE);
85 86
}

87 88
static void
radv_get_device_name(enum radeon_family family, char *name, size_t name_len)
89
{
90 91 92
	const char *chip_string;
	char llvm_string[32] = {};

93
	switch (family) {
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	case CHIP_TAHITI: chip_string = "AMD RADV TAHITI"; break;
	case CHIP_PITCAIRN: chip_string = "AMD RADV PITCAIRN"; break;
	case CHIP_VERDE: chip_string = "AMD RADV CAPE VERDE"; break;
	case CHIP_OLAND: chip_string = "AMD RADV OLAND"; break;
	case CHIP_HAINAN: chip_string = "AMD RADV HAINAN"; break;
	case CHIP_BONAIRE: chip_string = "AMD RADV BONAIRE"; break;
	case CHIP_KAVERI: chip_string = "AMD RADV KAVERI"; break;
	case CHIP_KABINI: chip_string = "AMD RADV KABINI"; break;
	case CHIP_HAWAII: chip_string = "AMD RADV HAWAII"; break;
	case CHIP_MULLINS: chip_string = "AMD RADV MULLINS"; break;
	case CHIP_TONGA: chip_string = "AMD RADV TONGA"; break;
	case CHIP_ICELAND: chip_string = "AMD RADV ICELAND"; break;
	case CHIP_CARRIZO: chip_string = "AMD RADV CARRIZO"; break;
	case CHIP_FIJI: chip_string = "AMD RADV FIJI"; break;
	case CHIP_POLARIS10: chip_string = "AMD RADV POLARIS10"; break;
	case CHIP_POLARIS11: chip_string = "AMD RADV POLARIS11"; break;
	case CHIP_POLARIS12: chip_string = "AMD RADV POLARIS12"; break;
	case CHIP_STONEY: chip_string = "AMD RADV STONEY"; break;
112
	case CHIP_VEGAM: chip_string = "AMD RADV VEGA M"; break;
113
	case CHIP_VEGA10: chip_string = "AMD RADV VEGA10"; break;
114
	case CHIP_VEGA12: chip_string = "AMD RADV VEGA12"; break;
115
	case CHIP_RAVEN: chip_string = "AMD RADV RAVEN"; break;
116
	case CHIP_RAVEN2: chip_string = "AMD RADV RAVEN2"; break;
117
	default: chip_string = "AMD RADV unknown"; break;
118
	}
119

120 121 122
	snprintf(llvm_string, sizeof(llvm_string),
		 " (LLVM %i.%i.%i)", (HAVE_LLVM >> 8) & 0xff,
		 HAVE_LLVM & 0xff, MESA_LLVM_VERSION_PATCH);
123
	snprintf(name, name_len, "%s%s", chip_string, llvm_string);
124 125
}

126 127 128 129 130 131 132 133 134 135 136 137
static uint64_t
radv_get_visible_vram_size(struct radv_physical_device *device)
{
	return MIN2(device->rad_info.vram_size, device->rad_info.vram_vis_size);
}

static uint64_t
radv_get_vram_size(struct radv_physical_device *device)
{
	return device->rad_info.vram_size - radv_get_visible_vram_size(device);
}

138 139 140 141
static void
radv_physical_device_init_mem_types(struct radv_physical_device *device)
{
	STATIC_ASSERT(RADV_MEM_HEAP_COUNT <= VK_MAX_MEMORY_HEAPS);
142 143
	uint64_t visible_vram_size = radv_get_visible_vram_size(device);
	uint64_t vram_size = radv_get_vram_size(device);
144 145
	int vram_index = -1, visible_vram_index = -1, gart_index = -1;
	device->memory_properties.memoryHeapCount = 0;
146
	if (vram_size > 0) {
147 148
		vram_index = device->memory_properties.memoryHeapCount++;
		device->memory_properties.memoryHeaps[vram_index] = (VkMemoryHeap) {
149
			.size = vram_size,
150 151 152 153 154 155 156 157 158 159 160 161 162 163
			.flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
		};
	}
	if (visible_vram_size) {
		visible_vram_index = device->memory_properties.memoryHeapCount++;
		device->memory_properties.memoryHeaps[visible_vram_index] = (VkMemoryHeap) {
			.size = visible_vram_size,
			.flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
		};
	}
	if (device->rad_info.gart_size > 0) {
		gart_index = device->memory_properties.memoryHeapCount++;
		device->memory_properties.memoryHeaps[gart_index] = (VkMemoryHeap) {
			.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 169 170 171 172 173 174 175 176 177 178 179 180
		};
	}

	STATIC_ASSERT(RADV_MEM_TYPE_COUNT <= VK_MAX_MEMORY_TYPES);
	unsigned type_count = 0;
	if (vram_index >= 0) {
		device->mem_type_indices[type_count] = RADV_MEM_TYPE_VRAM;
		device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
			.propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
			.heapIndex = vram_index,
		};
	}
	if (gart_index >= 0) {
		device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_WRITE_COMBINE;
		device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
			.propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
181 182
			VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
			(device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
			.heapIndex = gart_index,
		};
	}
	if (visible_vram_index >= 0) {
		device->mem_type_indices[type_count] = RADV_MEM_TYPE_VRAM_CPU_ACCESS;
		device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
			.propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
			VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
			VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
			.heapIndex = visible_vram_index,
		};
	}
	if (gart_index >= 0) {
		device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_CACHED;
		device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
			.propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
			VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
200 201
			VK_MEMORY_PROPERTY_HOST_CACHED_BIT |
			(device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
202 203 204 205 206 207
			.heapIndex = gart_index,
		};
	}
	device->memory_properties.memoryTypeCount = type_count;
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
static void
radv_handle_env_var_force_family(struct radv_physical_device *device)
{
	const char *family = getenv("RADV_FORCE_FAMILY");
	unsigned i;

	if (!family)
		return;

	for (i = CHIP_TAHITI; i < CHIP_LAST; i++) {
		if (!strcmp(family, ac_get_llvm_processor_name(i))) {
			/* Override family and chip_class. */
			device->rad_info.family = i;

			if (i >= CHIP_VEGA10)
				device->rad_info.chip_class = GFX9;
			else if (i >= CHIP_TONGA)
				device->rad_info.chip_class = VI;
			else if (i >= CHIP_BONAIRE)
				device->rad_info.chip_class = CIK;
			else
				device->rad_info.chip_class = SI;

			return;
		}
	}

	fprintf(stderr, "radv: Unknown family: %s\n", family);
	exit(1);
}

239 240 241
static VkResult
radv_physical_device_init(struct radv_physical_device *device,
			  struct radv_instance *instance,
242
			  drmDevicePtr drm_device)
243
{
244
	const char *path = drm_device->nodes[DRM_NODE_RENDER];
245
	VkResult result;
246
	drmVersionPtr version;
247
	int fd;
248
	int master_fd = -1;
249 250

	fd = open(path, O_RDWR | O_CLOEXEC);
251 252 253 254
	if (fd < 0) {
		if (instance->debug_flags & RADV_DEBUG_STARTUP)
			radv_logi("Could not open device '%s'", path);

255
		return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
256
	}
257

258 259 260
	version = drmGetVersion(fd);
	if (!version) {
		close(fd);
261 262 263 264

		if (instance->debug_flags & RADV_DEBUG_STARTUP)
			radv_logi("Could not get the kernel driver version for device '%s'", path);

265
		return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
266 267 268 269 270 271
				 "failed to get version %s: %m", path);
	}

	if (strcmp(version->name, "amdgpu")) {
		drmFreeVersion(version);
		close(fd);
272 273 274 275

		if (instance->debug_flags & RADV_DEBUG_STARTUP)
			radv_logi("Device '%s' is not using the amdgpu kernel driver.", path);

276
		return VK_ERROR_INCOMPATIBLE_DRIVER;
277 278 279
	}
	drmFreeVersion(version);

280 281 282
	if (instance->debug_flags & RADV_DEBUG_STARTUP)
			radv_logi("Found compatible device '%s'.", path);

283 284 285
	device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
	device->instance = instance;

286 287
	device->ws = radv_amdgpu_winsys_create(fd, instance->debug_flags,
					       instance->perftest_flags);
288
	if (!device->ws) {
289
		result = vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
290 291
		goto fail;
	}
292

293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
	if (instance->enabled_extensions.KHR_display) {
		master_fd = open(drm_device->nodes[DRM_NODE_PRIMARY], O_RDWR | O_CLOEXEC);
		if (master_fd >= 0) {
			uint32_t accel_working = 0;
			struct drm_amdgpu_info request = {
				.return_pointer = (uintptr_t)&accel_working,
				.return_size = sizeof(accel_working),
				.query = AMDGPU_INFO_ACCEL_WORKING
			};

			if (drmCommandWrite(master_fd, DRM_AMDGPU_INFO, &request, sizeof (struct drm_amdgpu_info)) < 0 || !accel_working) {
				close(master_fd);
				master_fd = -1;
			}
		}
	}

310
	device->master_fd = master_fd;
311
	device->local_fd = fd;
312 313
	device->ws->query_info(device->ws, &device->rad_info);

314 315
	radv_handle_env_var_force_family(device);

316
	radv_get_device_name(device->rad_info.family, device->name, sizeof(device->name));
317

318
	if (radv_device_get_cache_uuid(device->rad_info.family, device->cache_uuid)) {
319
		device->ws->destroy(device->ws);
320
		result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
321
				   "cannot generate UUID");
322 323
		goto fail;
	}
324

325 326 327 328 329
	/* These flags affect shader compilation. */
	uint64_t shader_env_flags =
		(device->instance->perftest_flags & RADV_PERFTEST_SISCHED ? 0x1 : 0) |
		(device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH ? 0x2 : 0);

330
	/* The gpu id is already embedded in the uuid so we just pass "radv"
331 332
	 * when creating the cache.
	 */
333 334
	char buf[VK_UUID_SIZE * 2 + 1];
	disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
335
	device->disk_cache = disk_cache_create(device->name, buf, shader_env_flags);
336

337 338 339
	if (device->rad_info.chip_class < VI ||
	    device->rad_info.chip_class > GFX9)
		fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
340

341
	radv_get_driver_uuid(&device->device_uuid);
342
	radv_get_device_uuid(&device->rad_info, &device->device_uuid);
343

Dave Airlie's avatar
Dave Airlie committed
344 345 346
	if (device->rad_info.family == CHIP_STONEY ||
	    device->rad_info.chip_class >= GFX9) {
		device->has_rbplus = true;
347
		device->rbplus_allowed = device->rad_info.family == CHIP_STONEY ||
348
					 device->rad_info.family == CHIP_VEGA12 ||
349 350
		                         device->rad_info.family == CHIP_RAVEN ||
		                         device->rad_info.family == CHIP_RAVEN2;
Dave Airlie's avatar
Dave Airlie committed
351 352
	}

353
	/* The mere presence of CLEAR_STATE in the IB causes random GPU hangs
354 355 356 357
	 * on SI.
	 */
	device->has_clear_state = device->rad_info.chip_class >= CIK;

358 359
	device->cpdma_prefetch_writes_memory = device->rad_info.chip_class <= VI;

360 361 362 363
	/* Vega10/Raven need a special workaround for a hardware bug. */
	device->has_scissor_bug = device->rad_info.family == CHIP_VEGA10 ||
				  device->rad_info.family == CHIP_RAVEN;

364 365 366 367
	/* Out-of-order primitive rasterization. */
	device->has_out_of_order_rast = device->rad_info.chip_class >= VI &&
					device->rad_info.max_se >= 2;
	device->out_of_order_rast_allowed = device->has_out_of_order_rast &&
368
					    !(device->instance->debug_flags & RADV_DEBUG_NO_OUT_OF_ORDER);
369

370 371
	device->dcc_msaa_allowed =
		(device->instance->perftest_flags & RADV_PERFTEST_DCC_MSAA);
372

373 374 375 376 377
	/* TODO: Figure out how to use LOAD_CONTEXT_REG on SI/CIK. */
	device->has_load_ctx_reg_pkt = device->rad_info.chip_class >= GFX9 ||
				       (device->rad_info.chip_class >= VI &&
				        device->rad_info.me_fw_feature >= 41);

378
	radv_physical_device_init_mem_types(device);
379
	radv_fill_device_extension_table(device, &device->supported_extensions);
380

381 382 383 384 385 386 387 388 389
	device->bus_info = *drm_device->businfo.pci;

	if ((device->instance->debug_flags & RADV_DEBUG_INFO))
		ac_print_gpu_info(&device->rad_info);

	/* The WSI is structured as a layer on top of the driver, so this has
	 * to be the last part of initialization (at least until we get other
	 * semi-layers).
	 */
390 391 392
	result = radv_init_wsi(device);
	if (result != VK_SUCCESS) {
		device->ws->destroy(device->ws);
393
		vk_error(instance, result);
394 395 396
		goto fail;
	}

397 398 399 400
	return VK_SUCCESS;

fail:
	close(fd);
401 402
	if (master_fd != -1)
		close(master_fd);
403 404 405 406 407 408 409 410
	return result;
}

static void
radv_physical_device_finish(struct radv_physical_device *device)
{
	radv_finish_wsi(device);
	device->ws->destroy(device->ws);
411
	disk_cache_destroy(device->disk_cache);
412
	close(device->local_fd);
413 414
	if (device->master_fd != -1)
		close(device->master_fd);
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
}

static void *
default_alloc_func(void *pUserData, size_t size, size_t align,
                   VkSystemAllocationScope allocationScope)
{
	return malloc(size);
}

static void *
default_realloc_func(void *pUserData, void *pOriginal, size_t size,
                     size_t align, VkSystemAllocationScope allocationScope)
{
	return realloc(pOriginal, size);
}

static void
default_free_func(void *pUserData, void *pMemory)
{
	free(pMemory);
}

static const VkAllocationCallbacks default_alloc = {
	.pUserData = NULL,
	.pfnAllocation = default_alloc_func,
	.pfnReallocation = default_realloc_func,
	.pfnFree = default_free_func,
};

444
static const struct debug_control radv_debug_options[] = {
445
	{"nofastclears", RADV_DEBUG_NO_FAST_CLEARS},
446 447 448 449 450 451 452
	{"nodcc", RADV_DEBUG_NO_DCC},
	{"shaders", RADV_DEBUG_DUMP_SHADERS},
	{"nocache", RADV_DEBUG_NO_CACHE},
	{"shaderstats", RADV_DEBUG_DUMP_SHADER_STATS},
	{"nohiz", RADV_DEBUG_NO_HIZ},
	{"nocompute", RADV_DEBUG_NO_COMPUTE_QUEUE},
	{"unsafemath", RADV_DEBUG_UNSAFE_MATH},
453 454
	{"allbos", RADV_DEBUG_ALL_BOS},
	{"noibs", RADV_DEBUG_NO_IBS},
455
	{"spirv", RADV_DEBUG_DUMP_SPIRV},
456
	{"vmfaults", RADV_DEBUG_VM_FAULTS},
457
	{"zerovram", RADV_DEBUG_ZERO_VRAM},
458
	{"syncshaders", RADV_DEBUG_SYNC_SHADERS},
459
	{"nosisched", RADV_DEBUG_NO_SISCHED},
460
	{"preoptir", RADV_DEBUG_PREOPTIR},
461
	{"nodynamicbounds", RADV_DEBUG_NO_DYNAMIC_BOUNDS},
462
	{"nooutoforder", RADV_DEBUG_NO_OUT_OF_ORDER},
463
	{"info", RADV_DEBUG_INFO},
464
	{"errors", RADV_DEBUG_ERRORS},
465
	{"startup", RADV_DEBUG_STARTUP},
466
	{"checkir", RADV_DEBUG_CHECKIR},
467
	{"nothreadllvm", RADV_DEBUG_NOTHREADLLVM},
468
	{"nobinning", RADV_DEBUG_NOBINNING},
469 470 471
	{NULL, 0}
};

472 473 474 475 476 477 478
const char *
radv_get_debug_option_name(int id)
{
	assert(id < ARRAY_SIZE(radv_debug_options) - 1);
	return radv_debug_options[id].string;
}

479
static const struct debug_control radv_perftest_options[] = {
480
	{"nobatchchain", RADV_PERFTEST_NO_BATCHCHAIN},
481
	{"sisched", RADV_PERFTEST_SISCHED},
482
	{"localbos", RADV_PERFTEST_LOCAL_BOS},
483
	{"dccmsaa", RADV_PERFTEST_DCC_MSAA},
484 485 486
	{NULL, 0}
};

487 488 489
const char *
radv_get_perftest_option_name(int id)
{
490
	assert(id < ARRAY_SIZE(radv_perftest_options) - 1);
491 492 493
	return radv_perftest_options[id].string;
}

494 495 496 497 498 499 500 501 502 503 504
static void
radv_handle_per_app_options(struct radv_instance *instance,
			    const VkApplicationInfo *info)
{
	const char *name = info ? info->pApplicationName : NULL;

	if (!name)
		return;

	if (!strcmp(name, "Talos - Linux - 32bit") ||
	    !strcmp(name, "Talos - Linux - 64bit")) {
505 506 507 508 509 510
		if (!(instance->debug_flags & RADV_DEBUG_NO_SISCHED)) {
			/* Force enable LLVM sisched for Talos because it looks
			 * safe and it gives few more FPS.
			 */
			instance->perftest_flags |= RADV_PERFTEST_SISCHED;
		}
Timothy Arceri's avatar
Timothy Arceri committed
511 512 513
	} else if (!strcmp(name, "DOOM_VFR")) {
		/* Work around a Doom VFR game bug */
		instance->debug_flags |= RADV_DEBUG_NO_DYNAMIC_BOUNDS;
514 515 516
	}
}

517 518 519 520 521 522 523 524 525 526
static int radv_get_instance_extension_index(const char *name)
{
	for (unsigned i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; ++i) {
		if (strcmp(name, radv_instance_extensions[i].extensionName) == 0)
			return i;
	}
	return -1;
}


527 528 529 530 531 532
VkResult radv_CreateInstance(
	const VkInstanceCreateInfo*                 pCreateInfo,
	const VkAllocationCallbacks*                pAllocator,
	VkInstance*                                 pInstance)
{
	struct radv_instance *instance;
533
	VkResult result;
534 535 536 537 538 539 540 541

	assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);

	uint32_t client_version;
	if (pCreateInfo->pApplicationInfo &&
	    pCreateInfo->pApplicationInfo->apiVersion != 0) {
		client_version = pCreateInfo->pApplicationInfo->apiVersion;
	} else {
542
		client_version = VK_API_VERSION_1_0;
543 544
	}

545 546
	instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
			      VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
547
	if (!instance)
548
		return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
549 550 551 552 553 554 555 556 557 558 559

	instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;

	if (pAllocator)
		instance->alloc = *pAllocator;
	else
		instance->alloc = default_alloc;

	instance->apiVersion = client_version;
	instance->physicalDeviceCount = -1;

560 561 562 563 564 565
	instance->debug_flags = parse_debug_string(getenv("RADV_DEBUG"),
						   radv_debug_options);

	instance->perftest_flags = parse_debug_string(getenv("RADV_PERFTEST"),
						   radv_perftest_options);

566 567 568 569

	if (instance->debug_flags & RADV_DEBUG_STARTUP)
		radv_logi("Created an instance");

570 571 572 573 574 575
	for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
		const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
		int index = radv_get_instance_extension_index(ext_name);

		if (index < 0 || !radv_supported_instance_extensions.extensions[index]) {
			vk_free2(&default_alloc, pAllocator, instance);
576
			return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
577 578 579 580 581
		}

		instance->enabled_extensions.extensions[index] = true;
	}

582 583 584
	result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
	if (result != VK_SUCCESS) {
		vk_free2(&default_alloc, pAllocator, instance);
585
		return vk_error(instance, result);
586 587
	}

588 589 590 591
	_mesa_locale_init();

	VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));

592 593
	radv_handle_per_app_options(instance, pCreateInfo->pApplicationInfo);

594 595 596 597 598 599 600 601 602 603 604
	*pInstance = radv_instance_to_handle(instance);

	return VK_SUCCESS;
}

void radv_DestroyInstance(
	VkInstance                                  _instance,
	const VkAllocationCallbacks*                pAllocator)
{
	RADV_FROM_HANDLE(radv_instance, instance, _instance);

605 606 607
	if (!instance)
		return;

608 609
	for (int i = 0; i < instance->physicalDeviceCount; ++i) {
		radv_physical_device_finish(instance->physicalDevices + i);
610 611 612 613
	}

	VG(VALGRIND_DESTROY_MEMPOOL(instance));

614
	_mesa_glsl_release_types();
615 616
	_mesa_locale_fini();

617 618
	vk_debug_report_instance_destroy(&instance->debug_report_callbacks);

619
	vk_free(&instance->alloc, instance);
620 621
}

622 623
static VkResult
radv_enumerate_devices(struct radv_instance *instance)
624
{
625 626 627 628 629 630 631
	/* TODO: Check for more devices ? */
	drmDevicePtr devices[8];
	VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
	int max_devices;

	instance->physicalDeviceCount = 0;

632
	max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
633 634 635 636

	if (instance->debug_flags & RADV_DEBUG_STARTUP)
		radv_logi("Found %d drm nodes", max_devices);

637
	if (max_devices < 1)
638
		return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
639 640 641 642

	for (unsigned i = 0; i < (unsigned)max_devices; i++) {
		if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
		    devices[i]->bustype == DRM_BUS_PCI &&
643
		    devices[i]->deviceinfo.pci->vendor_id == ATI_VENDOR_ID) {
644

645 646
			result = radv_physical_device_init(instance->physicalDevices +
			                                   instance->physicalDeviceCount,
647
			                                   instance,
648
			                                   devices[i]);
649 650 651
			if (result == VK_SUCCESS)
				++instance->physicalDeviceCount;
			else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
652
				break;
653 654
		}
	}
655 656
	drmFreeDevices(devices, max_devices);

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
	return result;
}

VkResult radv_EnumeratePhysicalDevices(
	VkInstance                                  _instance,
	uint32_t*                                   pPhysicalDeviceCount,
	VkPhysicalDevice*                           pPhysicalDevices)
{
	RADV_FROM_HANDLE(radv_instance, instance, _instance);
	VkResult result;

	if (instance->physicalDeviceCount < 0) {
		result = radv_enumerate_devices(instance);
		if (result != VK_SUCCESS &&
		    result != VK_ERROR_INCOMPATIBLE_DRIVER)
			return result;
	}
674 675 676 677

	if (!pPhysicalDevices) {
		*pPhysicalDeviceCount = instance->physicalDeviceCount;
	} else {
678 679 680
		*pPhysicalDeviceCount = MIN2(*pPhysicalDeviceCount, instance->physicalDeviceCount);
		for (unsigned i = 0; i < *pPhysicalDeviceCount; ++i)
			pPhysicalDevices[i] = radv_physical_device_to_handle(instance->physicalDevices + i);
681 682
	}

683 684
	return *pPhysicalDeviceCount < instance->physicalDeviceCount ? VK_INCOMPLETE
	                                                             : VK_SUCCESS;
685 686
}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
VkResult radv_EnumeratePhysicalDeviceGroups(
    VkInstance                                  _instance,
    uint32_t*                                   pPhysicalDeviceGroupCount,
    VkPhysicalDeviceGroupProperties*            pPhysicalDeviceGroupProperties)
{
	RADV_FROM_HANDLE(radv_instance, instance, _instance);
	VkResult result;

	if (instance->physicalDeviceCount < 0) {
		result = radv_enumerate_devices(instance);
		if (result != VK_SUCCESS &&
		    result != VK_ERROR_INCOMPATIBLE_DRIVER)
			return result;
	}

	if (!pPhysicalDeviceGroupProperties) {
		*pPhysicalDeviceGroupCount = instance->physicalDeviceCount;
	} else {
		*pPhysicalDeviceGroupCount = MIN2(*pPhysicalDeviceGroupCount, instance->physicalDeviceCount);
		for (unsigned i = 0; i < *pPhysicalDeviceGroupCount; ++i) {
			pPhysicalDeviceGroupProperties[i].physicalDeviceCount = 1;
			pPhysicalDeviceGroupProperties[i].physicalDevices[0] = radv_physical_device_to_handle(instance->physicalDevices + i);
			pPhysicalDeviceGroupProperties[i].subsetAllocation = false;
		}
	}
	return *pPhysicalDeviceGroupCount < instance->physicalDeviceCount ? VK_INCOMPLETE
	                                                                  : VK_SUCCESS;
}

716 717 718 719
void radv_GetPhysicalDeviceFeatures(
	VkPhysicalDevice                            physicalDevice,
	VkPhysicalDeviceFeatures*                   pFeatures)
{
720
	RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
721 722 723 724 725 726 727
	memset(pFeatures, 0, sizeof(*pFeatures));

	*pFeatures = (VkPhysicalDeviceFeatures) {
		.robustBufferAccess                       = true,
		.fullDrawIndexUint32                      = true,
		.imageCubeArray                           = true,
		.independentBlend                         = true,
Bas Nieuwenhuizen's avatar
Bas Nieuwenhuizen committed
728
		.geometryShader                           = true,
729
		.tessellationShader                       = true,
Dave Airlie's avatar
Dave Airlie committed
730
		.sampleRateShading                        = true,
731 732 733 734 735 736 737 738 739 740 741
		.dualSrcBlend                             = true,
		.logicOp                                  = true,
		.multiDrawIndirect                        = true,
		.drawIndirectFirstInstance                = true,
		.depthClamp                               = true,
		.depthBiasClamp                           = true,
		.fillModeNonSolid                         = true,
		.depthBounds                              = true,
		.wideLines                                = true,
		.largePoints                              = true,
		.alphaToOne                               = true,
742
		.multiViewport                            = true,
743
		.samplerAnisotropy                        = true,
744
		.textureCompressionETC2                   = radv_device_supports_etc(pdevice),
745 746 747
		.textureCompressionASTC_LDR               = false,
		.textureCompressionBC                     = true,
		.occlusionQueryPrecise                    = true,
748
		.pipelineStatisticsQuery                  = true,
749 750 751
		.vertexPipelineStoresAndAtomics           = true,
		.fragmentStoresAndAtomics                 = true,
		.shaderTessellationAndGeometryPointSize   = true,
752
		.shaderImageGatherExtended                = true,
753
		.shaderStorageImageExtendedFormats        = true,
754
		.shaderStorageImageMultisample            = pdevice->rad_info.chip_class >= VI,
755 756 757 758
		.shaderUniformBufferArrayDynamicIndexing  = true,
		.shaderSampledImageArrayDynamicIndexing   = true,
		.shaderStorageBufferArrayDynamicIndexing  = true,
		.shaderStorageImageArrayDynamicIndexing   = true,
759
		.shaderStorageImageReadWithoutFormat      = true,
760
		.shaderStorageImageWriteWithoutFormat     = true,
761 762
		.shaderClipDistance                       = true,
		.shaderCullDistance                       = true,
763
		.shaderFloat64                            = true,
764
		.shaderInt64                              = true,
765
		.shaderInt16                              = pdevice->rad_info.chip_class >= GFX9,
766
		.sparseBinding                            = true,
767
		.variableMultisampleRate                  = true,
768
		.inheritedQueries                         = true,
769 770 771
	};
}

772
void radv_GetPhysicalDeviceFeatures2(
773
	VkPhysicalDevice                            physicalDevice,
774
	VkPhysicalDeviceFeatures2                  *pFeatures)
775
{
776
	RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
777 778
	vk_foreach_struct(ext, pFeatures->pNext) {
		switch (ext->sType) {
779 780
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES: {
			VkPhysicalDeviceVariablePointerFeatures *features = (void *)ext;
781
			features->variablePointersStorageBuffer = true;
782
			features->variablePointers = true;
783 784
			break;
		}
785 786
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
			VkPhysicalDeviceMultiviewFeatures *features = (VkPhysicalDeviceMultiviewFeatures*)ext;
787 788 789 790 791
			features->multiview = true;
			features->multiviewGeometryShader = true;
			features->multiviewTessellationShader = true;
			break;
		}
792 793 794 795 796 797
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES: {
			VkPhysicalDeviceShaderDrawParameterFeatures *features =
			    (VkPhysicalDeviceShaderDrawParameterFeatures*)ext;
			features->shaderDrawParameters = true;
			break;
		}
798 799 800 801 802 803
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
			VkPhysicalDeviceProtectedMemoryFeatures *features =
			    (VkPhysicalDeviceProtectedMemoryFeatures*)ext;
			features->protectedMemory = false;
			break;
		}
804 805 806
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
			VkPhysicalDevice16BitStorageFeatures *features =
			    (VkPhysicalDevice16BitStorageFeatures*)ext;
807
			bool enabled = pdevice->rad_info.chip_class >= VI;
808 809 810
			features->storageBuffer16BitAccess = enabled;
			features->uniformAndStorageBuffer16BitAccess = enabled;
			features->storagePushConstant16 = enabled;
811
			features->storageInputOutput16 = enabled && HAVE_LLVM >= 0x900;
812 813
			break;
		}
814 815 816 817 818 819
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
			VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
			    (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)ext;
			features->samplerYcbcrConversion = false;
			break;
		}
820 821
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
			VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
822
				(VkPhysicalDeviceDescriptorIndexingFeaturesEXT*)ext;
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
			features->shaderInputAttachmentArrayDynamicIndexing = true;
			features->shaderUniformTexelBufferArrayDynamicIndexing = true;
			features->shaderStorageTexelBufferArrayDynamicIndexing = true;
			features->shaderUniformBufferArrayNonUniformIndexing = false;
			features->shaderSampledImageArrayNonUniformIndexing = false;
			features->shaderStorageBufferArrayNonUniformIndexing = false;
			features->shaderStorageImageArrayNonUniformIndexing = false;
			features->shaderInputAttachmentArrayNonUniformIndexing = false;
			features->shaderUniformTexelBufferArrayNonUniformIndexing = false;
			features->shaderStorageTexelBufferArrayNonUniformIndexing = false;
			features->descriptorBindingUniformBufferUpdateAfterBind = true;
			features->descriptorBindingSampledImageUpdateAfterBind = true;
			features->descriptorBindingStorageImageUpdateAfterBind = true;
			features->descriptorBindingStorageBufferUpdateAfterBind = true;
			features->descriptorBindingUniformTexelBufferUpdateAfterBind = true;
			features->descriptorBindingStorageTexelBufferUpdateAfterBind = true;
			features->descriptorBindingUpdateUnusedWhilePending = true;
			features->descriptorBindingPartiallyBound = true;
			features->descriptorBindingVariableDescriptorCount = true;
			features->runtimeDescriptorArray = true;
			break;
		}
845 846 847 848 849 850 851
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
			VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
				(VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
			features->conditionalRendering = true;
			features->inheritedConditionalRendering = false;
			break;
		}
852 853 854 855 856 857 858
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
			VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
				(VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
			features->vertexAttributeInstanceRateDivisor = VK_TRUE;
			features->vertexAttributeInstanceRateZeroDivisor = VK_TRUE;
			break;
		}
859 860 861 862 863 864 865
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
			VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
				(VkPhysicalDeviceTransformFeedbackFeaturesEXT*)ext;
			features->transformFeedback = true;
			features->geometryStreams = true;
			break;
		}
866 867 868 869 870 871
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
			VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
				(VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
			features->scalarBlockLayout = pdevice->rad_info.chip_class >= CIK;
			break;
		}
872 873 874 875 876 877
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT: {
			VkPhysicalDeviceMemoryPriorityFeaturesEXT *features =
				(VkPhysicalDeviceMemoryPriorityFeaturesEXT *)ext;
			features->memoryPriority = VK_TRUE;
			break;
		}
878 879 880 881 882 883 884 885
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_ADDRESS_FEATURES_EXT: {
			VkPhysicalDeviceBufferAddressFeaturesEXT *features =
				(VkPhysicalDeviceBufferAddressFeaturesEXT *)ext;
			features->bufferDeviceAddress = true;
			features->bufferDeviceAddressCaptureReplay = false;
			features->bufferDeviceAddressMultiDevice = false;
			break;
		}
886 887 888 889 890 891
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
			VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
				(VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
			features->depthClipEnable = true;
			break;
		}
892 893 894 895 896 897
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT: {
			VkPhysicalDeviceHostQueryResetFeaturesEXT *features =
				(VkPhysicalDeviceHostQueryResetFeaturesEXT *)ext;
			features->hostQueryReset = true;
			break;
		}
898 899 900 901 902 903 904 905 906
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
			VkPhysicalDevice8BitStorageFeaturesKHR *features =
			    (VkPhysicalDevice8BitStorageFeaturesKHR*)ext;
			bool enabled = pdevice->rad_info.chip_class >= VI;
			features->storageBuffer8BitAccess = enabled;
			features->uniformAndStorageBuffer8BitAccess = enabled;
			features->storagePushConstant8 = enabled;
			break;
		}
907 908 909 910
		default:
			break;
		}
	}
911 912 913
	return radv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
}

914 915 916 917 918 919
void radv_GetPhysicalDeviceProperties(
	VkPhysicalDevice                            physicalDevice,
	VkPhysicalDeviceProperties*                 pProperties)
{
	RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
	VkSampleCountFlags sample_counts = 0xf;
920 921 922 923 924 925 926 927

	/* make sure that the entire descriptor set is addressable with a signed
	 * 32-bit int. So the sum of all limits scaled by descriptor size has to
	 * be at most 2 GiB. the combined image & samples object count as one of
	 * both. This limit is for the pipeline layout, not for the set layout, but
	 * there is no set limit, so we just set a pipeline limit. I don't think
	 * any app is going to hit this soon. */
	size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
Bas Nieuwenhuizen's avatar
Bas Nieuwenhuizen committed
928 929
	          (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
	           32 /* storage buffer, 32 due to potential space wasted on alignment */ +
930 931 932 933
	           32 /* sampler, largest when combined with image */ +
	           64 /* sampled image */ +
	           64 /* storage image */);

934 935 936 937 938 939 940 941 942 943 944 945 946
	VkPhysicalDeviceLimits limits = {
		.maxImageDimension1D                      = (1 << 14),
		.maxImageDimension2D                      = (1 << 14),
		.maxImageDimension3D                      = (1 << 11),
		.maxImageDimensionCube                    = (1 << 14),
		.maxImageArrayLayers                      = (1 << 11),
		.maxTexelBufferElements                   = 128 * 1024 * 1024,
		.maxUniformBufferRange                    = UINT32_MAX,
		.maxStorageBufferRange                    = UINT32_MAX,
		.maxPushConstantsSize                     = MAX_PUSH_CONSTANTS_SIZE,
		.maxMemoryAllocationCount                 = UINT32_MAX,
		.maxSamplerAllocationCount                = 64 * 1024,
		.bufferImageGranularity                   = 64, /* A cache line */
947
		.sparseAddressSpaceSize                   = 0xffffffffu, /* buffer max size */
948
		.maxBoundDescriptorSets                   = MAX_SETS,
949 950 951 952 953 954 955 956 957
		.maxPerStageDescriptorSamplers            = max_descriptor_set_size,
		.maxPerStageDescriptorUniformBuffers      = max_descriptor_set_size,
		.maxPerStageDescriptorStorageBuffers      = max_descriptor_set_size,
		.maxPerStageDescriptorSampledImages       = max_descriptor_set_size,
		.maxPerStageDescriptorStorageImages       = max_descriptor_set_size,
		.maxPerStageDescriptorInputAttachments    = max_descriptor_set_size,
		.maxPerStageResources                     = max_descriptor_set_size,
		.maxDescriptorSetSamplers                 = max_descriptor_set_size,
		.maxDescriptorSetUniformBuffers           = max_descriptor_set_size,
958
		.maxDescriptorSetUniformBuffersDynamic    = MAX_DYNAMIC_UNIFORM_BUFFERS,
959
		.maxDescriptorSetStorageBuffers           = max_descriptor_set_size,
960
		.maxDescriptorSetStorageBuffersDynamic    = MAX_DYNAMIC_STORAGE_BUFFERS,
961 962 963
		.maxDescriptorSetSampledImages            = max_descriptor_set_size,
		.maxDescriptorSetStorageImages            = max_descriptor_set_size,
		.maxDescriptorSetInputAttachments         = max_descriptor_set_size,
964 965
		.maxVertexInputAttributes                 = MAX_VERTEX_ATTRIBS,
		.maxVertexInputBindings                   = MAX_VBS,
966 967 968
		.maxVertexInputAttributeOffset            = 2047,
		.maxVertexInputBindingStride              = 2048,
		.maxVertexOutputComponents                = 128,
969 970 971 972 973 974 975 976
		.maxTessellationGenerationLevel           = 64,
		.maxTessellationPatchSize                 = 32,
		.maxTessellationControlPerVertexInputComponents = 128,
		.maxTessellationControlPerVertexOutputComponents = 128,
		.maxTessellationControlPerPatchOutputComponents = 120,
		.maxTessellationControlTotalOutputComponents = 4096,
		.maxTessellationEvaluationInputComponents = 128,
		.maxTessellationEvaluationOutputComponents = 128,
977
		.maxGeometryShaderInvocations             = 127,
978 979 980 981 982 983
		.maxGeometryInputComponents               = 64,
		.maxGeometryOutputComponents              = 128,
		.maxGeometryOutputVertices                = 256,
		.maxGeometryTotalOutputComponents         = 1024,
		.maxFragmentInputComponents               = 128,
		.maxFragmentOutputAttachments             = 8,
984
		.maxFragmentDualSrcAttachments            = 1,
985 986 987
		.maxFragmentCombinedOutputResources       = 8,
		.maxComputeSharedMemorySize               = 32768,
		.maxComputeWorkGroupCount                 = { 65535, 65535, 65535 },
988
		.maxComputeWorkGroupInvocations           = 2048,
989
		.maxComputeWorkGroupSize = {
990 991 992
			2048,
			2048,
			2048
993
		},
994 995 996
		.subPixelPrecisionBits                    = 8,
		.subTexelPrecisionBits                    = 8,
		.mipmapPrecisionBits                      = 8,
997 998 999 1000 1001 1002 1003
		.maxDrawIndexedIndexValue                 = UINT32_MAX,
		.maxDrawIndirectCount                     = UINT32_MAX,
		.maxSamplerLodBias                        = 16,
		.maxSamplerAnisotropy                     = 16,
		.maxViewports                             = MAX_VIEWPORTS,
		.maxViewportDimensions                    = { (1 << 14), (1 << 14) },
		.viewportBoundsRange                      = { INT16_MIN, INT16_MAX },
1004
		.viewportSubPixelBits                     = 8,
1005 1006 1007 1008
		.minMemoryMapAlignment                    = 4096, /* A page */
		.minTexelBufferOffsetAlignment            = 1,
		.minUniformBufferOffsetAlignment          = 4,
		.minStorageBufferOffsetAlignment          = 4,
1009 1010 1011 1012
		.minTexelOffset                           = -32,
		.maxTexelOffset                           = 31,
		.minTexelGatherOffset                     = -32,
		.maxTexelGatherOffset                     = 31,
1013 1014 1015
		.minInterpolationOffset                   = -2,
		.maxInterpolationOffset                   = 2,
		.subPixelInterpolationOffsetBits          = 8,
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
		.maxFramebufferWidth                      = (1 << 14),
		.maxFramebufferHeight                     = (1 << 14),
		.maxFramebufferLayers                     = (1 << 10),
		.framebufferColorSampleCounts             = sample_counts,
		.framebufferDepthSampleCounts             = sample_counts,
		.framebufferStencilSampleCounts           = sample_counts,
		.framebufferNoAttachmentsSampleCounts     = sample_counts,
		.maxColorAttachments                      = MAX_RTS,
		.sampledImageColorSampleCounts            = sample_counts,
		.sampledImageIntegerSampleCounts          = VK_SAMPLE_COUNT_1_BIT,
		.sampledImageDepthSampleCounts            = sample_counts,
		.sampledImageStencilSampleCounts          = sample_counts,
1028
		.storageImageSampleCounts                 = pdevice->rad_info.chip_class >= VI ? sample_counts : VK_SAMPLE_COUNT_1_BIT,
1029
		.maxSampleMaskWords                       = 1,
1030
		.timestampComputeAndGraphics              = true,
1031
		.timestampPeriod                          = 1000000.0 / pdevice->rad_info.clock_crystal_freq,
1032 1033 1034
		.maxClipDistances                         = 8,
		.maxCullDistances                         = 8,
		.maxCombinedClipAndCullDistances          = 8,
1035
		.discreteQueuePriorities                  = 2,
1036
		.pointSizeRange                           = { 0.0, 8192.0 },
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
		.lineWidthRange                           = { 0.0, 7.9921875 },
		.pointSizeGranularity                     = (1.0 / 8.0),
		.lineWidthGranularity                     = (1.0 / 128.0),
		.strictLines                              = false, /* FINISHME */
		.standardSampleLocations                  = true,
		.optimalBufferCopyOffsetAlignment         = 128,
		.optimalBufferCopyRowPitchAlignment       = 128,
		.nonCoherentAtomSize                      = 64,
	};

	*pProperties = (VkPhysicalDeviceProperties) {
1048
		.apiVersion = radv_physical_device_api_version(pdevice),
1049
		.driverVersion = vk_get_driver_version(),
1050
		.vendorID = ATI_VENDOR_ID,
1051
		.deviceID = pdevice->rad_info.pci_id,
1052
		.deviceType = pdevice->rad_info.has_dedicated_vram ? VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1053
		.limits = limits,
1054
		.sparseProperties = {0},
1055 1056 1057
	};

	strcpy(pProperties->deviceName, pdevice->name);
1058
	memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
1059 1060
}

1061
void radv_GetPhysicalDeviceProperties2(
1062
	VkPhysicalDevice                            physicalDevice,
1063
	VkPhysicalDeviceProperties2                *pProperties)
1064
{
1065
	RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	radv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);

	vk_foreach_struct(ext, pProperties->pNext) {
		switch (ext->sType) {
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
			VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
				(VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
			properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
			break;
		}
1076 1077
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
			VkPhysicalDeviceIDProperties *properties = (VkPhysicalDeviceIDProperties*)ext;
1078
			memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1079 1080 1081 1082
			memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
			properties->deviceLUIDValid = false;
			break;
		}
1083 1084
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
			VkPhysicalDeviceMultiviewProperties *properties = (VkPhysicalDeviceMultiviewProperties*)ext;
1085 1086 1087 1088
			properties->maxMultiviewViewCount = MAX_VIEWS;
			properties->maxMultiviewInstanceIndex = INT_MAX;
			break;
		}
1089 1090 1091 1092
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
			VkPhysicalDevicePointClippingProperties *properties =
			    (VkPhysicalDevicePointClippingProperties*)ext;
			properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1093 1094
			break;
		}
1095 1096 1097 1098 1099 1100
		case  VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT: {
			VkPhysicalDeviceDiscardRectanglePropertiesEXT *properties =
			    (VkPhysicalDeviceDiscardRectanglePropertiesEXT*)ext;
			properties->maxDiscardRectangles = MAX_DISCARD_RECTANGLES;
			break;
		}
1101 1102 1103 1104 1105 1106
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
			VkPhysicalDeviceExternalMemoryHostPropertiesEXT *properties =
			    (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
			properties->minImportedHostPointerAlignment = 4096;
			break;
		}
1107 1108 1109 1110 1111
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
			VkPhysicalDeviceSubgroupProperties *properties =
			    (VkPhysicalDeviceSubgroupProperties*)ext;
			properties->subgroupSize = 64;
			properties->supportedStages = VK_SHADER_STAGE_ALL;
1112 1113 1114
			properties->supportedOperations =
							VK_SUBGROUP_FEATURE_BASIC_BIT |
							VK_SUBGROUP_FEATURE_BALLOT_BIT |
1115 1116
							VK_SUBGROUP_FEATURE_QUAD_BIT |
							VK_SUBGROUP_FEATURE_VOTE_BIT;
1117 1118
			if (pdevice->rad_info.chip_class >= VI) {
				properties->supportedOperations |=
1119
							VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1120 1121 1122
							VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
							VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT;
			}
1123
			properties->quadOperationsInAllStages = true;
1124 1125
			break;
		}
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
			VkPhysicalDeviceMaintenance3Properties *properties =
			    (VkPhysicalDeviceMaintenance3Properties*)ext;
			/* Make sure everything is addressable by a signed 32-bit int, and
			 * our largest descriptors are 96 bytes. */
			properties->maxPerSetDescriptors = (1ull << 31) / 96;
			/* Our buffer size fields allow only this much */
			properties->maxMemoryAllocationSize = 0xFFFFFFFFull;
			break;
		}
1136 1137 1138 1139 1140 1141 1142 1143
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
			VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
				(VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
			/* GFX6-8 only support single channel min/max filter. */
			properties->filterMinmaxImageComponentMapping = pdevice->rad_info.chip_class >= GFX9;
			properties->filterMinmaxSingleComponentFormats = true;
			break;
		}
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD: {
			VkPhysicalDeviceShaderCorePropertiesAMD *properties =
				(VkPhysicalDeviceShaderCorePropertiesAMD *)ext;

			/* Shader engines. */
			properties->shaderEngineCount =
				pdevice->rad_info.max_se;
			properties->shaderArraysPerEngineCount =
				pdevice->rad_info.max_sh_per_se;
			properties->computeUnitsPerShaderArray =
1154
				pdevice->rad_info.num_good_cu_per_sh;
1155 1156 1157 1158 1159 1160
			properties->simdPerComputeUnit = 4;
			properties->wavefrontsPerSimd =
				pdevice->rad_info.family == CHIP_TONGA ||
				pdevice->rad_info.family == CHIP_ICELAND ||
				pdevice->rad_info.family == CHIP_POLARIS10 ||
				pdevice->rad_info.family == CHIP_POLARIS11 ||
1161 1162
				pdevice->rad_info.family == CHIP_POLARIS12 ||
				pdevice->rad_info.family == CHIP_VEGAM ? 8 : 10;
1163 1164 1165 1166
			properties->wavefrontSize = 64;

			/* SGPR. */
			properties->sgprsPerSimd =
1167
				ac_get_num_physical_sgprs(pdevice->rad_info.chip_class);
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
			properties->minSgprAllocation =
				pdevice->rad_info.chip_class >= VI ? 16 : 8;
			properties->maxSgprAllocation =
				pdevice->rad_info.family == CHIP_TONGA ||
				pdevice->rad_info.family == CHIP_ICELAND ? 96 : 104;
			properties->sgprAllocationGranularity =
				pdevice->rad_info.chip_class >= VI ? 16 : 8;

			/* VGPR. */
			properties->vgprsPerSimd = RADV_NUM_PHYSICAL_VGPRS;
			properties->minVgprAllocation = 4;
			properties->maxVgprAllocation = 256;
			properties->vgprAllocationGranularity = 4;
			break;
		}
1183 1184 1185 1186 1187 1188
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
			VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *properties =
				(VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
			properties->maxVertexAttribDivisor = UINT32_MAX;
			break;
		}
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
			VkPhysicalDeviceDescriptorIndexingPropertiesEXT *properties =
				(VkPhysicalDeviceDescriptorIndexingPropertiesEXT*)ext;
			properties->maxUpdateAfterBindDescriptorsInAllPools = UINT32_MAX / 64;
			properties->shaderUniformBufferArrayNonUniformIndexingNative = false;
			properties->shaderSampledImageArrayNonUniformIndexingNative = false;
			properties->shaderStorageBufferArrayNonUniformIndexingNative = false;
			properties->shaderStorageImageArrayNonUniformIndexingNative = false;
			properties->shaderInputAttachmentArrayNonUniformIndexingNative = false;
			properties->robustBufferAccessUpdateAfterBind = false;
			properties->quadDivergentImplicitLod = false;

			size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
			          (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
			           32 /* storage buffer, 32 due to potential space wasted on alignment */ +
			           32 /* sampler, largest when combined with image */ +
			           64 /* sampled image */ +
			           64 /* storage image */);
			properties->maxPerStageDescriptorUpdateAfterBindSamplers = max_descriptor_set_size;
			properties->maxPerStageDescriptorUpdateAfterBindUniformBuffers = max_descriptor_set_size;
			properties->maxPerStageDescriptorUpdateAfterBindStorageBuffers = max_descriptor_set_size;
			properties->maxPerStageDescriptorUpdateAfterBindSampledImages = max_descriptor_set_size;
			properties->maxPerStageDescriptorUpdateAfterBindStorageImages = max_descriptor_set_size;
			properties->maxPerStageDescriptorUpdateAfterBindInputAttachments = max_descriptor_set_size;
			properties->maxPerStageUpdateAfterBindResources = max_descriptor_set_size;
			properties->maxDescriptorSetUpdateAfterBindSamplers = max_descriptor_set_size;
			properties->maxDescriptorSetUpdateAfterBindUniformBuffers = max_descriptor_set_size;
			properties->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS;
			properties->maxDescriptorSetUpdateAfterBindStorageBuffers = max_descriptor_set_size;
			properties->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS;
			properties->maxDescriptorSetUpdateAfterBindSampledImages = max_descriptor_set_size;
			properties->maxDescriptorSetUpdateAfterBindStorageImages = max_descriptor_set_size;
			properties->maxDescriptorSetUpdateAfterBindInputAttachments = max_descriptor_set_size;
			break;
		}
1224 1225 1226 1227 1228 1229
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
			VkPhysicalDeviceProtectedMemoryProperties *properties =
				(VkPhysicalDeviceProtectedMemoryProperties *)ext;
			properties->protectedNoFault = false;
			break;
		}
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT: {
			VkPhysicalDeviceConservativeRasterizationPropertiesEXT *properties =
				(VkPhysicalDeviceConservativeRasterizationPropertiesEXT *)ext;
			properties->primitiveOverestimationSize = 0;
			properties->maxExtraPrimitiveOverestimationSize = 0;
			properties->extraPrimitiveOverestimationSizeGranularity = 0;
			properties->primitiveUnderestimation = VK_FALSE;
			properties->conservativePointAndLineRasterization = VK_FALSE;
			properties->degenerateTrianglesRasterized = VK_FALSE;
			properties->degenerateLinesRasterized = VK_FALSE;
			properties->fullyCoveredFragmentShaderInputVariable = VK_FALSE;
			properties->conservativeRasterizationPostDepthCoverage = VK_FALSE;
			break;
		}
1244 1245 1246 1247 1248 1249 1250 1251 1252
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
			VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
				(VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
			properties->pciDomain = pdevice->bus_info.domain;
			properties->pciBus = pdevice->bus_info.bus;
			properties->pciDevice = pdevice->bus_info.dev;
			properties->pciFunction = pdevice->bus_info.func;
			break;
		}
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
			VkPhysicalDeviceDriverPropertiesKHR *driver_props =
				(VkPhysicalDeviceDriverPropertiesKHR *) ext;

			driver_props->driverID = VK_DRIVER_ID_MESA_RADV_KHR;
			memset(driver_props->driverName, 0, VK_MAX_DRIVER_NAME_SIZE_KHR);
			strcpy(driver_props->driverName, "radv");

			memset(driver_props->driverInfo, 0, VK_MAX_DRIVER_INFO_SIZE_KHR);
			snprintf(driver_props->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1263
				"Mesa " PACKAGE_VERSION MESA_GIT_SHA1
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
				" (LLVM %d.%d.%d)",
				 (HAVE_LLVM >> 8) & 0xff, HAVE_LLVM & 0xff,
				 MESA_LLVM_VERSION_PATCH);

			driver_props->conformanceVersion = (VkConformanceVersionKHR) {
				.major = 1,
				.minor = 1,
				.subminor = 2,
				.patch = 0,
			};
			break;
		}
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
			VkPhysicalDeviceTransformFeedbackPropertiesEXT *properties =
				(VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
			properties->maxTransformFeedbackStreams = MAX_SO_STREAMS;
			properties->maxTransformFeedbackBuffers = MAX_SO_BUFFERS;
			properties->maxTransformFeedbackBufferSize = UINT32_MAX;
			properties->maxTransformFeedbackStreamDataSize = 512;
			properties->maxTransformFeedbackBufferDataSize = UINT32_MAX;
			properties->maxTransformFeedbackBufferDataStride = 512;
			properties->transformFeedbackQueries = true;
			properties->transformFeedbackStreamsLinesTriangles = false;
			properties->transformFeedbackRasterizationStreamSelect = false;
			properties->transformFeedbackDraw = true;
			break;
		}
1291 1292 1293 1294
		default:
			break;
		}
	}
1295 1296
}

1297 1298
static void radv_get_physical_device_queue_family_properties(
	struct radv_physical_device*                pdevice,
1299
	uint32_t*                                   pCount,
1300
	VkQueueFamilyProperties**                    pQueueFamilyProperties)
1301
{
Dave Airlie's avatar
Dave Airlie committed
1302 1303
	int num_queue_families = 1;
	int idx;
Nicolai Hähnle's avatar
Nicolai Hähnle committed
1304
	if (pdevice->rad_info.num_compute_rings > 0 &&
1305 1306
	    !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE))
		num_queue_families++;
Dave Airlie's avatar
Dave Airlie committed
1307