anv/device: expose shaderInt16 support in gen8+
[mesa.git] / src / intel / vulkan / anv_device.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <sys/mman.h>
28 #include <sys/sysinfo.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <xf86drm.h>
32 #include <drm_fourcc.h>
33
34 #include "anv_private.h"
35 #include "util/strtod.h"
36 #include "util/debug.h"
37 #include "util/build_id.h"
38 #include "util/mesa-sha1.h"
39 #include "vk_util.h"
40 #include "common/gen_defines.h"
41
42 #include "genxml/gen7_pack.h"
43
44 static void
45 compiler_debug_log(void *data, const char *fmt, ...)
46 { }
47
48 static void
49 compiler_perf_log(void *data, const char *fmt, ...)
50 {
51 va_list args;
52 va_start(args, fmt);
53
54 if (unlikely(INTEL_DEBUG & DEBUG_PERF))
55 intel_logd_v(fmt, args);
56
57 va_end(args);
58 }
59
60 static VkResult
61 anv_compute_heap_size(int fd, uint64_t gtt_size, uint64_t *heap_size)
62 {
63 /* Query the total ram from the system */
64 struct sysinfo info;
65 sysinfo(&info);
66
67 uint64_t total_ram = (uint64_t)info.totalram * (uint64_t)info.mem_unit;
68
69 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
70 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
71 */
72 uint64_t available_ram;
73 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
74 available_ram = total_ram / 2;
75 else
76 available_ram = total_ram * 3 / 4;
77
78 /* We also want to leave some padding for things we allocate in the driver,
79 * so don't go over 3/4 of the GTT either.
80 */
81 uint64_t available_gtt = gtt_size * 3 / 4;
82
83 *heap_size = MIN2(available_ram, available_gtt);
84
85 return VK_SUCCESS;
86 }
87
88 static VkResult
89 anv_physical_device_init_heaps(struct anv_physical_device *device, int fd)
90 {
91 uint64_t gtt_size;
92 if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
93 &gtt_size) == -1) {
94 /* If, for whatever reason, we can't actually get the GTT size from the
95 * kernel (too old?) fall back to the aperture size.
96 */
97 anv_perf_warn(NULL, NULL,
98 "Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
99
100 if (anv_gem_get_aperture(fd, &gtt_size) == -1) {
101 return vk_errorf(NULL, NULL, VK_ERROR_INITIALIZATION_FAILED,
102 "failed to get aperture size: %m");
103 }
104 }
105
106 device->supports_48bit_addresses = (device->info.gen >= 8) &&
107 gtt_size > (4ULL << 30 /* GiB */);
108
109 uint64_t heap_size = 0;
110 VkResult result = anv_compute_heap_size(fd, gtt_size, &heap_size);
111 if (result != VK_SUCCESS)
112 return result;
113
114 if (heap_size > (2ull << 30) && !device->supports_48bit_addresses) {
115 /* When running with an overridden PCI ID, we may get a GTT size from
116 * the kernel that is greater than 2 GiB but the execbuf check for 48bit
117 * address support can still fail. Just clamp the address space size to
118 * 2 GiB if we don't have 48-bit support.
119 */
120 intel_logw("%s:%d: The kernel reported a GTT size larger than 2 GiB but "
121 "not support for 48-bit addresses",
122 __FILE__, __LINE__);
123 heap_size = 2ull << 30;
124 }
125
126 if (heap_size <= 3ull * (1ull << 30)) {
127 /* In this case, everything fits nicely into the 32-bit address space,
128 * so there's no need for supporting 48bit addresses on client-allocated
129 * memory objects.
130 */
131 device->memory.heap_count = 1;
132 device->memory.heaps[0] = (struct anv_memory_heap) {
133 .size = heap_size,
134 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
135 .supports_48bit_addresses = false,
136 };
137 } else {
138 /* Not everything will fit nicely into a 32-bit address space. In this
139 * case we need a 64-bit heap. Advertise a small 32-bit heap and a
140 * larger 48-bit heap. If we're in this case, then we have a total heap
141 * size larger than 3GiB which most likely means they have 8 GiB of
142 * video memory and so carving off 1 GiB for the 32-bit heap should be
143 * reasonable.
144 */
145 const uint64_t heap_size_32bit = 1ull << 30;
146 const uint64_t heap_size_48bit = heap_size - heap_size_32bit;
147
148 assert(device->supports_48bit_addresses);
149
150 device->memory.heap_count = 2;
151 device->memory.heaps[0] = (struct anv_memory_heap) {
152 .size = heap_size_48bit,
153 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
154 .supports_48bit_addresses = true,
155 };
156 device->memory.heaps[1] = (struct anv_memory_heap) {
157 .size = heap_size_32bit,
158 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
159 .supports_48bit_addresses = false,
160 };
161 }
162
163 uint32_t type_count = 0;
164 for (uint32_t heap = 0; heap < device->memory.heap_count; heap++) {
165 uint32_t valid_buffer_usage = ~0;
166
167 /* There appears to be a hardware issue in the VF cache where it only
168 * considers the bottom 32 bits of memory addresses. If you happen to
169 * have two vertex buffers which get placed exactly 4 GiB apart and use
170 * them in back-to-back draw calls, you can get collisions. In order to
171 * solve this problem, we require vertex and index buffers be bound to
172 * memory allocated out of the 32-bit heap.
173 */
174 if (device->memory.heaps[heap].supports_48bit_addresses) {
175 valid_buffer_usage &= ~(VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
176 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
177 }
178
179 if (device->info.has_llc) {
180 /* Big core GPUs share LLC with the CPU and thus one memory type can be
181 * both cached and coherent at the same time.
182 */
183 device->memory.types[type_count++] = (struct anv_memory_type) {
184 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
185 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
186 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
187 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
188 .heapIndex = heap,
189 .valid_buffer_usage = valid_buffer_usage,
190 };
191 } else {
192 /* The spec requires that we expose a host-visible, coherent memory
193 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
194 * to give the application a choice between cached, but not coherent and
195 * coherent but uncached (WC though).
196 */
197 device->memory.types[type_count++] = (struct anv_memory_type) {
198 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
199 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
200 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
201 .heapIndex = heap,
202 .valid_buffer_usage = valid_buffer_usage,
203 };
204 device->memory.types[type_count++] = (struct anv_memory_type) {
205 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
206 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
207 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
208 .heapIndex = heap,
209 .valid_buffer_usage = valid_buffer_usage,
210 };
211 }
212 }
213 device->memory.type_count = type_count;
214
215 return VK_SUCCESS;
216 }
217
218 static VkResult
219 anv_physical_device_init_uuids(struct anv_physical_device *device)
220 {
221 const struct build_id_note *note =
222 build_id_find_nhdr_for_addr(anv_physical_device_init_uuids);
223 if (!note) {
224 return vk_errorf(device->instance, device,
225 VK_ERROR_INITIALIZATION_FAILED,
226 "Failed to find build-id");
227 }
228
229 unsigned build_id_len = build_id_length(note);
230 if (build_id_len < 20) {
231 return vk_errorf(device->instance, device,
232 VK_ERROR_INITIALIZATION_FAILED,
233 "build-id too short. It needs to be a SHA");
234 }
235
236 struct mesa_sha1 sha1_ctx;
237 uint8_t sha1[20];
238 STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
239
240 /* The pipeline cache UUID is used for determining when a pipeline cache is
241 * invalid. It needs both a driver build and the PCI ID of the device.
242 */
243 _mesa_sha1_init(&sha1_ctx);
244 _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
245 _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
246 sizeof(device->chipset_id));
247 _mesa_sha1_final(&sha1_ctx, sha1);
248 memcpy(device->pipeline_cache_uuid, sha1, VK_UUID_SIZE);
249
250 /* The driver UUID is used for determining sharability of images and memory
251 * between two Vulkan instances in separate processes. People who want to
252 * share memory need to also check the device UUID (below) so all this
253 * needs to be is the build-id.
254 */
255 memcpy(device->driver_uuid, build_id_data(note), VK_UUID_SIZE);
256
257 /* The device UUID uniquely identifies the given device within the machine.
258 * Since we never have more than one device, this doesn't need to be a real
259 * UUID. However, on the off-chance that someone tries to use this to
260 * cache pre-tiled images or something of the like, we use the PCI ID and
261 * some bits of ISL info to ensure that this is safe.
262 */
263 _mesa_sha1_init(&sha1_ctx);
264 _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
265 sizeof(device->chipset_id));
266 _mesa_sha1_update(&sha1_ctx, &device->isl_dev.has_bit6_swizzling,
267 sizeof(device->isl_dev.has_bit6_swizzling));
268 _mesa_sha1_final(&sha1_ctx, sha1);
269 memcpy(device->device_uuid, sha1, VK_UUID_SIZE);
270
271 return VK_SUCCESS;
272 }
273
274 static VkResult
275 anv_physical_device_init(struct anv_physical_device *device,
276 struct anv_instance *instance,
277 const char *path)
278 {
279 VkResult result;
280 int fd;
281
282 brw_process_intel_debug_variable();
283
284 fd = open(path, O_RDWR | O_CLOEXEC);
285 if (fd < 0)
286 return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
287
288 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
289 device->instance = instance;
290
291 assert(strlen(path) < ARRAY_SIZE(device->path));
292 strncpy(device->path, path, ARRAY_SIZE(device->path));
293
294 device->no_hw = getenv("INTEL_NO_HW") != NULL;
295
296 const int pci_id_override = gen_get_pci_device_id_override();
297 if (pci_id_override < 0) {
298 device->chipset_id = anv_gem_get_param(fd, I915_PARAM_CHIPSET_ID);
299 if (!device->chipset_id) {
300 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
301 goto fail;
302 }
303 } else {
304 device->chipset_id = pci_id_override;
305 device->no_hw = true;
306 }
307
308 device->name = gen_get_device_name(device->chipset_id);
309 if (!gen_get_device_info(device->chipset_id, &device->info)) {
310 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
311 goto fail;
312 }
313
314 if (device->info.is_haswell) {
315 intel_logw("Haswell Vulkan support is incomplete");
316 } else if (device->info.gen == 7 && !device->info.is_baytrail) {
317 intel_logw("Ivy Bridge Vulkan support is incomplete");
318 } else if (device->info.gen == 7 && device->info.is_baytrail) {
319 intel_logw("Bay Trail Vulkan support is incomplete");
320 } else if (device->info.gen >= 8 && device->info.gen <= 10) {
321 /* Gen8-10 fully supported */
322 } else if (device->info.gen == 11) {
323 intel_logw("Vulkan is not yet fully supported on gen11.");
324 } else {
325 result = vk_errorf(device->instance, device,
326 VK_ERROR_INCOMPATIBLE_DRIVER,
327 "Vulkan not yet supported on %s", device->name);
328 goto fail;
329 }
330
331 device->cmd_parser_version = -1;
332 if (device->info.gen == 7) {
333 device->cmd_parser_version =
334 anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
335 if (device->cmd_parser_version == -1) {
336 result = vk_errorf(device->instance, device,
337 VK_ERROR_INITIALIZATION_FAILED,
338 "failed to get command parser version");
339 goto fail;
340 }
341 }
342
343 if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
344 result = vk_errorf(device->instance, device,
345 VK_ERROR_INITIALIZATION_FAILED,
346 "kernel missing gem wait");
347 goto fail;
348 }
349
350 if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
351 result = vk_errorf(device->instance, device,
352 VK_ERROR_INITIALIZATION_FAILED,
353 "kernel missing execbuf2");
354 goto fail;
355 }
356
357 if (!device->info.has_llc &&
358 anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
359 result = vk_errorf(device->instance, device,
360 VK_ERROR_INITIALIZATION_FAILED,
361 "kernel missing wc mmap");
362 goto fail;
363 }
364
365 result = anv_physical_device_init_heaps(device, fd);
366 if (result != VK_SUCCESS)
367 goto fail;
368
369 device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
370 device->has_exec_capture = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_CAPTURE);
371 device->has_exec_fence = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE);
372 device->has_syncobj = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE_ARRAY);
373 device->has_syncobj_wait = device->has_syncobj &&
374 anv_gem_supports_syncobj_wait(fd);
375 device->has_context_priority = anv_gem_has_context_priority(fd);
376
377 bool swizzled = anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
378
379 /* Starting with Gen10, the timestamp frequency of the command streamer may
380 * vary from one part to another. We can query the value from the kernel.
381 */
382 if (device->info.gen >= 10) {
383 int timestamp_frequency =
384 anv_gem_get_param(fd, I915_PARAM_CS_TIMESTAMP_FREQUENCY);
385
386 if (timestamp_frequency < 0)
387 intel_logw("Kernel 4.16-rc1+ required to properly query CS timestamp frequency");
388 else
389 device->info.timestamp_frequency = timestamp_frequency;
390 }
391
392 /* GENs prior to 8 do not support EU/Subslice info */
393 if (device->info.gen >= 8) {
394 device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
395 device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
396
397 /* Without this information, we cannot get the right Braswell
398 * brandstrings, and we have to use conservative numbers for GPGPU on
399 * many platforms, but otherwise, things will just work.
400 */
401 if (device->subslice_total < 1 || device->eu_total < 1) {
402 intel_logw("Kernel 4.1 required to properly query GPU properties");
403 }
404 } else if (device->info.gen == 7) {
405 device->subslice_total = 1 << (device->info.gt - 1);
406 }
407
408 if (device->info.is_cherryview &&
409 device->subslice_total > 0 && device->eu_total > 0) {
410 /* Logical CS threads = EUs per subslice * num threads per EU */
411 uint32_t max_cs_threads =
412 device->eu_total / device->subslice_total * device->info.num_thread_per_eu;
413
414 /* Fuse configurations may give more threads than expected, never less. */
415 if (max_cs_threads > device->info.max_cs_threads)
416 device->info.max_cs_threads = max_cs_threads;
417 }
418
419 device->compiler = brw_compiler_create(NULL, &device->info);
420 if (device->compiler == NULL) {
421 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
422 goto fail;
423 }
424 device->compiler->shader_debug_log = compiler_debug_log;
425 device->compiler->shader_perf_log = compiler_perf_log;
426 device->compiler->supports_pull_constants = false;
427 device->compiler->constant_buffer_0_is_relative = true;
428
429 isl_device_init(&device->isl_dev, &device->info, swizzled);
430
431 result = anv_physical_device_init_uuids(device);
432 if (result != VK_SUCCESS)
433 goto fail;
434
435 result = anv_init_wsi(device);
436 if (result != VK_SUCCESS) {
437 ralloc_free(device->compiler);
438 goto fail;
439 }
440
441 anv_physical_device_get_supported_extensions(device,
442 &device->supported_extensions);
443
444 device->local_fd = fd;
445 return VK_SUCCESS;
446
447 fail:
448 close(fd);
449 return result;
450 }
451
452 static void
453 anv_physical_device_finish(struct anv_physical_device *device)
454 {
455 anv_finish_wsi(device);
456 ralloc_free(device->compiler);
457 close(device->local_fd);
458 }
459
460 static void *
461 default_alloc_func(void *pUserData, size_t size, size_t align,
462 VkSystemAllocationScope allocationScope)
463 {
464 return malloc(size);
465 }
466
467 static void *
468 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
469 size_t align, VkSystemAllocationScope allocationScope)
470 {
471 return realloc(pOriginal, size);
472 }
473
474 static void
475 default_free_func(void *pUserData, void *pMemory)
476 {
477 free(pMemory);
478 }
479
480 static const VkAllocationCallbacks default_alloc = {
481 .pUserData = NULL,
482 .pfnAllocation = default_alloc_func,
483 .pfnReallocation = default_realloc_func,
484 .pfnFree = default_free_func,
485 };
486
487 VkResult anv_EnumerateInstanceExtensionProperties(
488 const char* pLayerName,
489 uint32_t* pPropertyCount,
490 VkExtensionProperties* pProperties)
491 {
492 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
493
494 for (int i = 0; i < ANV_INSTANCE_EXTENSION_COUNT; i++) {
495 if (anv_instance_extensions_supported.extensions[i]) {
496 vk_outarray_append(&out, prop) {
497 *prop = anv_instance_extensions[i];
498 }
499 }
500 }
501
502 return vk_outarray_status(&out);
503 }
504
505 VkResult anv_CreateInstance(
506 const VkInstanceCreateInfo* pCreateInfo,
507 const VkAllocationCallbacks* pAllocator,
508 VkInstance* pInstance)
509 {
510 struct anv_instance *instance;
511 VkResult result;
512
513 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
514
515 struct anv_instance_extension_table enabled_extensions = {};
516 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
517 int idx;
518 for (idx = 0; idx < ANV_INSTANCE_EXTENSION_COUNT; idx++) {
519 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
520 anv_instance_extensions[idx].extensionName) == 0)
521 break;
522 }
523
524 if (idx >= ANV_INSTANCE_EXTENSION_COUNT)
525 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
526
527 if (!anv_instance_extensions_supported.extensions[idx])
528 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
529
530 enabled_extensions.extensions[idx] = true;
531 }
532
533 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
534 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
535 if (!instance)
536 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
537
538 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
539
540 if (pAllocator)
541 instance->alloc = *pAllocator;
542 else
543 instance->alloc = default_alloc;
544
545 if (pCreateInfo->pApplicationInfo &&
546 pCreateInfo->pApplicationInfo->apiVersion != 0) {
547 instance->apiVersion = pCreateInfo->pApplicationInfo->apiVersion;
548 } else {
549 anv_EnumerateInstanceVersion(&instance->apiVersion);
550 }
551
552 instance->enabled_extensions = enabled_extensions;
553
554 for (unsigned i = 0; i < ARRAY_SIZE(instance->dispatch.entrypoints); i++) {
555 /* Vulkan requires that entrypoints for extensions which have not been
556 * enabled must not be advertised.
557 */
558 if (!anv_entrypoint_is_enabled(i, instance->apiVersion,
559 &instance->enabled_extensions, NULL)) {
560 instance->dispatch.entrypoints[i] = NULL;
561 } else if (anv_dispatch_table.entrypoints[i] != NULL) {
562 instance->dispatch.entrypoints[i] = anv_dispatch_table.entrypoints[i];
563 } else {
564 instance->dispatch.entrypoints[i] =
565 anv_tramp_dispatch_table.entrypoints[i];
566 }
567 }
568
569 instance->physicalDeviceCount = -1;
570
571 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
572 if (result != VK_SUCCESS) {
573 vk_free2(&default_alloc, pAllocator, instance);
574 return vk_error(result);
575 }
576
577 _mesa_locale_init();
578
579 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
580
581 *pInstance = anv_instance_to_handle(instance);
582
583 return VK_SUCCESS;
584 }
585
586 void anv_DestroyInstance(
587 VkInstance _instance,
588 const VkAllocationCallbacks* pAllocator)
589 {
590 ANV_FROM_HANDLE(anv_instance, instance, _instance);
591
592 if (!instance)
593 return;
594
595 if (instance->physicalDeviceCount > 0) {
596 /* We support at most one physical device. */
597 assert(instance->physicalDeviceCount == 1);
598 anv_physical_device_finish(&instance->physicalDevice);
599 }
600
601 VG(VALGRIND_DESTROY_MEMPOOL(instance));
602
603 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
604
605 _mesa_locale_fini();
606
607 vk_free(&instance->alloc, instance);
608 }
609
610 static VkResult
611 anv_enumerate_devices(struct anv_instance *instance)
612 {
613 /* TODO: Check for more devices ? */
614 drmDevicePtr devices[8];
615 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
616 int max_devices;
617
618 instance->physicalDeviceCount = 0;
619
620 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
621 if (max_devices < 1)
622 return VK_ERROR_INCOMPATIBLE_DRIVER;
623
624 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
625 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
626 devices[i]->bustype == DRM_BUS_PCI &&
627 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
628
629 result = anv_physical_device_init(&instance->physicalDevice,
630 instance,
631 devices[i]->nodes[DRM_NODE_RENDER]);
632 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
633 break;
634 }
635 }
636 drmFreeDevices(devices, max_devices);
637
638 if (result == VK_SUCCESS)
639 instance->physicalDeviceCount = 1;
640
641 return result;
642 }
643
644 static VkResult
645 anv_instance_ensure_physical_device(struct anv_instance *instance)
646 {
647 if (instance->physicalDeviceCount < 0) {
648 VkResult result = anv_enumerate_devices(instance);
649 if (result != VK_SUCCESS &&
650 result != VK_ERROR_INCOMPATIBLE_DRIVER)
651 return result;
652 }
653
654 return VK_SUCCESS;
655 }
656
657 VkResult anv_EnumeratePhysicalDevices(
658 VkInstance _instance,
659 uint32_t* pPhysicalDeviceCount,
660 VkPhysicalDevice* pPhysicalDevices)
661 {
662 ANV_FROM_HANDLE(anv_instance, instance, _instance);
663 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
664
665 VkResult result = anv_instance_ensure_physical_device(instance);
666 if (result != VK_SUCCESS)
667 return result;
668
669 if (instance->physicalDeviceCount == 0)
670 return VK_SUCCESS;
671
672 assert(instance->physicalDeviceCount == 1);
673 vk_outarray_append(&out, i) {
674 *i = anv_physical_device_to_handle(&instance->physicalDevice);
675 }
676
677 return vk_outarray_status(&out);
678 }
679
680 VkResult anv_EnumeratePhysicalDeviceGroups(
681 VkInstance _instance,
682 uint32_t* pPhysicalDeviceGroupCount,
683 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
684 {
685 ANV_FROM_HANDLE(anv_instance, instance, _instance);
686 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
687 pPhysicalDeviceGroupCount);
688
689 VkResult result = anv_instance_ensure_physical_device(instance);
690 if (result != VK_SUCCESS)
691 return result;
692
693 if (instance->physicalDeviceCount == 0)
694 return VK_SUCCESS;
695
696 assert(instance->physicalDeviceCount == 1);
697
698 vk_outarray_append(&out, p) {
699 p->physicalDeviceCount = 1;
700 memset(p->physicalDevices, 0, sizeof(p->physicalDevices));
701 p->physicalDevices[0] =
702 anv_physical_device_to_handle(&instance->physicalDevice);
703 p->subsetAllocation = VK_FALSE;
704
705 vk_foreach_struct(ext, p->pNext)
706 anv_debug_ignored_stype(ext->sType);
707 }
708
709 return vk_outarray_status(&out);
710 }
711
712 void anv_GetPhysicalDeviceFeatures(
713 VkPhysicalDevice physicalDevice,
714 VkPhysicalDeviceFeatures* pFeatures)
715 {
716 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
717
718 *pFeatures = (VkPhysicalDeviceFeatures) {
719 .robustBufferAccess = true,
720 .fullDrawIndexUint32 = true,
721 .imageCubeArray = true,
722 .independentBlend = true,
723 .geometryShader = true,
724 .tessellationShader = true,
725 .sampleRateShading = true,
726 .dualSrcBlend = true,
727 .logicOp = true,
728 .multiDrawIndirect = true,
729 .drawIndirectFirstInstance = true,
730 .depthClamp = true,
731 .depthBiasClamp = true,
732 .fillModeNonSolid = true,
733 .depthBounds = false,
734 .wideLines = true,
735 .largePoints = true,
736 .alphaToOne = true,
737 .multiViewport = true,
738 .samplerAnisotropy = true,
739 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
740 pdevice->info.is_baytrail,
741 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
742 .textureCompressionBC = true,
743 .occlusionQueryPrecise = true,
744 .pipelineStatisticsQuery = true,
745 .fragmentStoresAndAtomics = true,
746 .shaderTessellationAndGeometryPointSize = true,
747 .shaderImageGatherExtended = true,
748 .shaderStorageImageExtendedFormats = true,
749 .shaderStorageImageMultisample = false,
750 .shaderStorageImageReadWithoutFormat = false,
751 .shaderStorageImageWriteWithoutFormat = true,
752 .shaderUniformBufferArrayDynamicIndexing = true,
753 .shaderSampledImageArrayDynamicIndexing = true,
754 .shaderStorageBufferArrayDynamicIndexing = true,
755 .shaderStorageImageArrayDynamicIndexing = true,
756 .shaderClipDistance = true,
757 .shaderCullDistance = true,
758 .shaderFloat64 = pdevice->info.gen >= 8 &&
759 pdevice->info.has_64bit_types,
760 .shaderInt64 = pdevice->info.gen >= 8 &&
761 pdevice->info.has_64bit_types,
762 .shaderInt16 = pdevice->info.gen >= 8,
763 .shaderResourceMinLod = false,
764 .variableMultisampleRate = true,
765 .inheritedQueries = true,
766 };
767
768 /* We can't do image stores in vec4 shaders */
769 pFeatures->vertexPipelineStoresAndAtomics =
770 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
771 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
772 }
773
774 void anv_GetPhysicalDeviceFeatures2(
775 VkPhysicalDevice physicalDevice,
776 VkPhysicalDeviceFeatures2* pFeatures)
777 {
778 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
779
780 vk_foreach_struct(ext, pFeatures->pNext) {
781 switch (ext->sType) {
782 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
783 VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
784 features->protectedMemory = VK_FALSE;
785 break;
786 }
787
788 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
789 VkPhysicalDeviceMultiviewFeatures *features =
790 (VkPhysicalDeviceMultiviewFeatures *)ext;
791 features->multiview = true;
792 features->multiviewGeometryShader = true;
793 features->multiviewTessellationShader = true;
794 break;
795 }
796
797 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES: {
798 VkPhysicalDeviceVariablePointerFeatures *features = (void *)ext;
799 features->variablePointersStorageBuffer = true;
800 features->variablePointers = true;
801 break;
802 }
803
804 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
805 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
806 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
807 features->samplerYcbcrConversion = true;
808 break;
809 }
810
811 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES: {
812 VkPhysicalDeviceShaderDrawParameterFeatures *features = (void *)ext;
813 features->shaderDrawParameters = true;
814 break;
815 }
816
817 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR: {
818 VkPhysicalDevice16BitStorageFeaturesKHR *features =
819 (VkPhysicalDevice16BitStorageFeaturesKHR *)ext;
820 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
821
822 features->storageBuffer16BitAccess = pdevice->info.gen >= 8;
823 features->uniformAndStorageBuffer16BitAccess = pdevice->info.gen >= 8;
824 features->storagePushConstant16 = pdevice->info.gen >= 8;
825 features->storageInputOutput16 = false;
826 break;
827 }
828
829 default:
830 anv_debug_ignored_stype(ext->sType);
831 break;
832 }
833 }
834 }
835
836 void anv_GetPhysicalDeviceProperties(
837 VkPhysicalDevice physicalDevice,
838 VkPhysicalDeviceProperties* pProperties)
839 {
840 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
841 const struct gen_device_info *devinfo = &pdevice->info;
842
843 /* See assertions made when programming the buffer surface state. */
844 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
845 (1ul << 30) : (1ul << 27);
846
847 const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
848 128 : 16;
849
850 VkSampleCountFlags sample_counts =
851 isl_device_get_sample_counts(&pdevice->isl_dev);
852
853 VkPhysicalDeviceLimits limits = {
854 .maxImageDimension1D = (1 << 14),
855 .maxImageDimension2D = (1 << 14),
856 .maxImageDimension3D = (1 << 11),
857 .maxImageDimensionCube = (1 << 14),
858 .maxImageArrayLayers = (1 << 11),
859 .maxTexelBufferElements = 128 * 1024 * 1024,
860 .maxUniformBufferRange = (1ul << 27),
861 .maxStorageBufferRange = max_raw_buffer_sz,
862 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
863 .maxMemoryAllocationCount = UINT32_MAX,
864 .maxSamplerAllocationCount = 64 * 1024,
865 .bufferImageGranularity = 64, /* A cache line */
866 .sparseAddressSpaceSize = 0,
867 .maxBoundDescriptorSets = MAX_SETS,
868 .maxPerStageDescriptorSamplers = max_samplers,
869 .maxPerStageDescriptorUniformBuffers = 64,
870 .maxPerStageDescriptorStorageBuffers = 64,
871 .maxPerStageDescriptorSampledImages = max_samplers,
872 .maxPerStageDescriptorStorageImages = 64,
873 .maxPerStageDescriptorInputAttachments = 64,
874 .maxPerStageResources = 250,
875 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
876 .maxDescriptorSetUniformBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorUniformBuffers */
877 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
878 .maxDescriptorSetStorageBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorStorageBuffers */
879 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
880 .maxDescriptorSetSampledImages = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSampledImages */
881 .maxDescriptorSetStorageImages = 6 * 64, /* number of stages * maxPerStageDescriptorStorageImages */
882 .maxDescriptorSetInputAttachments = 256,
883 .maxVertexInputAttributes = MAX_VBS,
884 .maxVertexInputBindings = MAX_VBS,
885 .maxVertexInputAttributeOffset = 2047,
886 .maxVertexInputBindingStride = 2048,
887 .maxVertexOutputComponents = 128,
888 .maxTessellationGenerationLevel = 64,
889 .maxTessellationPatchSize = 32,
890 .maxTessellationControlPerVertexInputComponents = 128,
891 .maxTessellationControlPerVertexOutputComponents = 128,
892 .maxTessellationControlPerPatchOutputComponents = 128,
893 .maxTessellationControlTotalOutputComponents = 2048,
894 .maxTessellationEvaluationInputComponents = 128,
895 .maxTessellationEvaluationOutputComponents = 128,
896 .maxGeometryShaderInvocations = 32,
897 .maxGeometryInputComponents = 64,
898 .maxGeometryOutputComponents = 128,
899 .maxGeometryOutputVertices = 256,
900 .maxGeometryTotalOutputComponents = 1024,
901 .maxFragmentInputComponents = 128,
902 .maxFragmentOutputAttachments = 8,
903 .maxFragmentDualSrcAttachments = 1,
904 .maxFragmentCombinedOutputResources = 8,
905 .maxComputeSharedMemorySize = 32768,
906 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
907 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
908 .maxComputeWorkGroupSize = {
909 16 * devinfo->max_cs_threads,
910 16 * devinfo->max_cs_threads,
911 16 * devinfo->max_cs_threads,
912 },
913 .subPixelPrecisionBits = 4 /* FIXME */,
914 .subTexelPrecisionBits = 4 /* FIXME */,
915 .mipmapPrecisionBits = 4 /* FIXME */,
916 .maxDrawIndexedIndexValue = UINT32_MAX,
917 .maxDrawIndirectCount = UINT32_MAX,
918 .maxSamplerLodBias = 16,
919 .maxSamplerAnisotropy = 16,
920 .maxViewports = MAX_VIEWPORTS,
921 .maxViewportDimensions = { (1 << 14), (1 << 14) },
922 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
923 .viewportSubPixelBits = 13, /* We take a float? */
924 .minMemoryMapAlignment = 4096, /* A page */
925 .minTexelBufferOffsetAlignment = 1,
926 /* We need 16 for UBO block reads to work and 32 for push UBOs */
927 .minUniformBufferOffsetAlignment = 32,
928 .minStorageBufferOffsetAlignment = 4,
929 .minTexelOffset = -8,
930 .maxTexelOffset = 7,
931 .minTexelGatherOffset = -32,
932 .maxTexelGatherOffset = 31,
933 .minInterpolationOffset = -0.5,
934 .maxInterpolationOffset = 0.4375,
935 .subPixelInterpolationOffsetBits = 4,
936 .maxFramebufferWidth = (1 << 14),
937 .maxFramebufferHeight = (1 << 14),
938 .maxFramebufferLayers = (1 << 11),
939 .framebufferColorSampleCounts = sample_counts,
940 .framebufferDepthSampleCounts = sample_counts,
941 .framebufferStencilSampleCounts = sample_counts,
942 .framebufferNoAttachmentsSampleCounts = sample_counts,
943 .maxColorAttachments = MAX_RTS,
944 .sampledImageColorSampleCounts = sample_counts,
945 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
946 .sampledImageDepthSampleCounts = sample_counts,
947 .sampledImageStencilSampleCounts = sample_counts,
948 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
949 .maxSampleMaskWords = 1,
950 .timestampComputeAndGraphics = false,
951 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
952 .maxClipDistances = 8,
953 .maxCullDistances = 8,
954 .maxCombinedClipAndCullDistances = 8,
955 .discreteQueuePriorities = 1,
956 .pointSizeRange = { 0.125, 255.875 },
957 .lineWidthRange = { 0.0, 7.9921875 },
958 .pointSizeGranularity = (1.0 / 8.0),
959 .lineWidthGranularity = (1.0 / 128.0),
960 .strictLines = false, /* FINISHME */
961 .standardSampleLocations = true,
962 .optimalBufferCopyOffsetAlignment = 128,
963 .optimalBufferCopyRowPitchAlignment = 128,
964 .nonCoherentAtomSize = 64,
965 };
966
967 *pProperties = (VkPhysicalDeviceProperties) {
968 .apiVersion = anv_physical_device_api_version(pdevice),
969 .driverVersion = vk_get_driver_version(),
970 .vendorID = 0x8086,
971 .deviceID = pdevice->chipset_id,
972 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
973 .limits = limits,
974 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
975 };
976
977 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
978 "%s", pdevice->name);
979 memcpy(pProperties->pipelineCacheUUID,
980 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
981 }
982
983 void anv_GetPhysicalDeviceProperties2(
984 VkPhysicalDevice physicalDevice,
985 VkPhysicalDeviceProperties2* pProperties)
986 {
987 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
988
989 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
990
991 vk_foreach_struct(ext, pProperties->pNext) {
992 switch (ext->sType) {
993 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
994 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
995 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
996
997 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
998 break;
999 }
1000
1001 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1002 VkPhysicalDeviceIDProperties *id_props =
1003 (VkPhysicalDeviceIDProperties *)ext;
1004 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1005 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1006 /* The LUID is for Windows. */
1007 id_props->deviceLUIDValid = false;
1008 break;
1009 }
1010
1011 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1012 VkPhysicalDeviceMaintenance3Properties *props =
1013 (VkPhysicalDeviceMaintenance3Properties *)ext;
1014 /* This value doesn't matter for us today as our per-stage
1015 * descriptors are the real limit.
1016 */
1017 props->maxPerSetDescriptors = 1024;
1018 props->maxMemoryAllocationSize = MAX_MEMORY_ALLOCATION_SIZE;
1019 break;
1020 }
1021
1022 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1023 VkPhysicalDeviceMultiviewProperties *properties =
1024 (VkPhysicalDeviceMultiviewProperties *)ext;
1025 properties->maxMultiviewViewCount = 16;
1026 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
1027 break;
1028 }
1029
1030 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1031 VkPhysicalDevicePointClippingProperties *properties =
1032 (VkPhysicalDevicePointClippingProperties *) ext;
1033 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1034 anv_finishme("Implement pop-free point clipping");
1035 break;
1036 }
1037
1038 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1039 VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
1040
1041 properties->subgroupSize = BRW_SUBGROUP_SIZE;
1042
1043 VkShaderStageFlags scalar_stages = 0;
1044 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1045 if (pdevice->compiler->scalar_stage[stage])
1046 scalar_stages |= mesa_to_vk_shader_stage(stage);
1047 }
1048 properties->supportedStages = scalar_stages;
1049
1050 properties->supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1051 VK_SUBGROUP_FEATURE_VOTE_BIT |
1052 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1053 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1054 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1055 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1056 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1057 VK_SUBGROUP_FEATURE_QUAD_BIT;
1058 properties->quadOperationsInAllStages = VK_TRUE;
1059 break;
1060 }
1061
1062 default:
1063 anv_debug_ignored_stype(ext->sType);
1064 break;
1065 }
1066 }
1067 }
1068
1069 /* We support exactly one queue family. */
1070 static const VkQueueFamilyProperties
1071 anv_queue_family_properties = {
1072 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1073 VK_QUEUE_COMPUTE_BIT |
1074 VK_QUEUE_TRANSFER_BIT,
1075 .queueCount = 1,
1076 .timestampValidBits = 36, /* XXX: Real value here */
1077 .minImageTransferGranularity = { 1, 1, 1 },
1078 };
1079
1080 void anv_GetPhysicalDeviceQueueFamilyProperties(
1081 VkPhysicalDevice physicalDevice,
1082 uint32_t* pCount,
1083 VkQueueFamilyProperties* pQueueFamilyProperties)
1084 {
1085 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
1086
1087 vk_outarray_append(&out, p) {
1088 *p = anv_queue_family_properties;
1089 }
1090 }
1091
1092 void anv_GetPhysicalDeviceQueueFamilyProperties2(
1093 VkPhysicalDevice physicalDevice,
1094 uint32_t* pQueueFamilyPropertyCount,
1095 VkQueueFamilyProperties2* pQueueFamilyProperties)
1096 {
1097
1098 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1099
1100 vk_outarray_append(&out, p) {
1101 p->queueFamilyProperties = anv_queue_family_properties;
1102
1103 vk_foreach_struct(s, p->pNext) {
1104 anv_debug_ignored_stype(s->sType);
1105 }
1106 }
1107 }
1108
1109 void anv_GetPhysicalDeviceMemoryProperties(
1110 VkPhysicalDevice physicalDevice,
1111 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1112 {
1113 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1114
1115 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1116 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1117 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1118 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1119 .heapIndex = physical_device->memory.types[i].heapIndex,
1120 };
1121 }
1122
1123 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1124 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1125 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1126 .size = physical_device->memory.heaps[i].size,
1127 .flags = physical_device->memory.heaps[i].flags,
1128 };
1129 }
1130 }
1131
1132 void anv_GetPhysicalDeviceMemoryProperties2(
1133 VkPhysicalDevice physicalDevice,
1134 VkPhysicalDeviceMemoryProperties2* pMemoryProperties)
1135 {
1136 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1137 &pMemoryProperties->memoryProperties);
1138
1139 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1140 switch (ext->sType) {
1141 default:
1142 anv_debug_ignored_stype(ext->sType);
1143 break;
1144 }
1145 }
1146 }
1147
1148 void
1149 anv_GetDeviceGroupPeerMemoryFeatures(
1150 VkDevice device,
1151 uint32_t heapIndex,
1152 uint32_t localDeviceIndex,
1153 uint32_t remoteDeviceIndex,
1154 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
1155 {
1156 assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
1157 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
1158 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
1159 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
1160 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
1161 }
1162
1163 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1164 VkInstance _instance,
1165 const char* pName)
1166 {
1167 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1168
1169 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
1170 * when we have to return valid function pointers, NULL, or it's left
1171 * undefined. See the table for exact details.
1172 */
1173 if (pName == NULL)
1174 return NULL;
1175
1176 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
1177 if (strcmp(pName, "vk" #entrypoint) == 0) \
1178 return (PFN_vkVoidFunction)anv_##entrypoint
1179
1180 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
1181 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
1182 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
1183 LOOKUP_ANV_ENTRYPOINT(CreateInstance);
1184
1185 #undef LOOKUP_ANV_ENTRYPOINT
1186
1187 if (instance == NULL)
1188 return NULL;
1189
1190 int idx = anv_get_entrypoint_index(pName);
1191 if (idx < 0)
1192 return NULL;
1193
1194 return instance->dispatch.entrypoints[idx];
1195 }
1196
1197 /* With version 1+ of the loader interface the ICD should expose
1198 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1199 */
1200 PUBLIC
1201 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1202 VkInstance instance,
1203 const char* pName);
1204
1205 PUBLIC
1206 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1207 VkInstance instance,
1208 const char* pName)
1209 {
1210 return anv_GetInstanceProcAddr(instance, pName);
1211 }
1212
1213 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1214 VkDevice _device,
1215 const char* pName)
1216 {
1217 ANV_FROM_HANDLE(anv_device, device, _device);
1218
1219 if (!device || !pName)
1220 return NULL;
1221
1222 int idx = anv_get_entrypoint_index(pName);
1223 if (idx < 0)
1224 return NULL;
1225
1226 return device->dispatch.entrypoints[idx];
1227 }
1228
1229 VkResult
1230 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
1231 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
1232 const VkAllocationCallbacks* pAllocator,
1233 VkDebugReportCallbackEXT* pCallback)
1234 {
1235 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1236 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
1237 pCreateInfo, pAllocator, &instance->alloc,
1238 pCallback);
1239 }
1240
1241 void
1242 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
1243 VkDebugReportCallbackEXT _callback,
1244 const VkAllocationCallbacks* pAllocator)
1245 {
1246 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1247 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
1248 _callback, pAllocator, &instance->alloc);
1249 }
1250
1251 void
1252 anv_DebugReportMessageEXT(VkInstance _instance,
1253 VkDebugReportFlagsEXT flags,
1254 VkDebugReportObjectTypeEXT objectType,
1255 uint64_t object,
1256 size_t location,
1257 int32_t messageCode,
1258 const char* pLayerPrefix,
1259 const char* pMessage)
1260 {
1261 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1262 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
1263 object, location, messageCode, pLayerPrefix, pMessage);
1264 }
1265
1266 static void
1267 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1268 {
1269 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1270 queue->device = device;
1271 queue->pool = &device->surface_state_pool;
1272 queue->flags = 0;
1273 }
1274
1275 static void
1276 anv_queue_finish(struct anv_queue *queue)
1277 {
1278 }
1279
1280 static struct anv_state
1281 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1282 {
1283 struct anv_state state;
1284
1285 state = anv_state_pool_alloc(pool, size, align);
1286 memcpy(state.map, p, size);
1287
1288 anv_state_flush(pool->block_pool.device, state);
1289
1290 return state;
1291 }
1292
1293 struct gen8_border_color {
1294 union {
1295 float float32[4];
1296 uint32_t uint32[4];
1297 };
1298 /* Pad out to 64 bytes */
1299 uint32_t _pad[12];
1300 };
1301
1302 static void
1303 anv_device_init_border_colors(struct anv_device *device)
1304 {
1305 static const struct gen8_border_color border_colors[] = {
1306 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1307 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1308 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1309 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1310 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1311 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1312 };
1313
1314 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1315 sizeof(border_colors), 64,
1316 border_colors);
1317 }
1318
1319 static void
1320 anv_device_init_trivial_batch(struct anv_device *device)
1321 {
1322 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1323
1324 if (device->instance->physicalDevice.has_exec_async)
1325 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1326
1327 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1328 0, 4096, 0);
1329
1330 struct anv_batch batch = {
1331 .start = map,
1332 .next = map,
1333 .end = map + 4096,
1334 };
1335
1336 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1337 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1338
1339 if (!device->info.has_llc)
1340 gen_clflush_range(map, batch.next - map);
1341
1342 anv_gem_munmap(map, device->trivial_batch_bo.size);
1343 }
1344
1345 VkResult anv_EnumerateDeviceExtensionProperties(
1346 VkPhysicalDevice physicalDevice,
1347 const char* pLayerName,
1348 uint32_t* pPropertyCount,
1349 VkExtensionProperties* pProperties)
1350 {
1351 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
1352 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1353 (void)device;
1354
1355 for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
1356 if (device->supported_extensions.extensions[i]) {
1357 vk_outarray_append(&out, prop) {
1358 *prop = anv_device_extensions[i];
1359 }
1360 }
1361 }
1362
1363 return vk_outarray_status(&out);
1364 }
1365
1366 static void
1367 anv_device_init_dispatch(struct anv_device *device)
1368 {
1369 const struct anv_dispatch_table *genX_table;
1370 switch (device->info.gen) {
1371 case 11:
1372 genX_table = &gen11_dispatch_table;
1373 break;
1374 case 10:
1375 genX_table = &gen10_dispatch_table;
1376 break;
1377 case 9:
1378 genX_table = &gen9_dispatch_table;
1379 break;
1380 case 8:
1381 genX_table = &gen8_dispatch_table;
1382 break;
1383 case 7:
1384 if (device->info.is_haswell)
1385 genX_table = &gen75_dispatch_table;
1386 else
1387 genX_table = &gen7_dispatch_table;
1388 break;
1389 default:
1390 unreachable("unsupported gen\n");
1391 }
1392
1393 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
1394 /* Vulkan requires that entrypoints for extensions which have not been
1395 * enabled must not be advertised.
1396 */
1397 if (!anv_entrypoint_is_enabled(i, device->instance->apiVersion,
1398 &device->instance->enabled_extensions,
1399 &device->enabled_extensions)) {
1400 device->dispatch.entrypoints[i] = NULL;
1401 } else if (genX_table->entrypoints[i]) {
1402 device->dispatch.entrypoints[i] = genX_table->entrypoints[i];
1403 } else {
1404 device->dispatch.entrypoints[i] = anv_dispatch_table.entrypoints[i];
1405 }
1406 }
1407 }
1408
1409 static int
1410 vk_priority_to_gen(int priority)
1411 {
1412 switch (priority) {
1413 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1414 return GEN_CONTEXT_LOW_PRIORITY;
1415 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1416 return GEN_CONTEXT_MEDIUM_PRIORITY;
1417 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1418 return GEN_CONTEXT_HIGH_PRIORITY;
1419 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1420 return GEN_CONTEXT_REALTIME_PRIORITY;
1421 default:
1422 unreachable("Invalid priority");
1423 }
1424 }
1425
1426 static void
1427 anv_device_init_hiz_clear_batch(struct anv_device *device)
1428 {
1429 anv_bo_init_new(&device->hiz_clear_bo, device, 4096);
1430 uint32_t *map = anv_gem_mmap(device, device->hiz_clear_bo.gem_handle,
1431 0, 4096, 0);
1432
1433 union isl_color_value hiz_clear = { .u32 = { 0, } };
1434 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
1435
1436 memcpy(map, hiz_clear.u32, sizeof(hiz_clear.u32));
1437 anv_gem_munmap(map, device->hiz_clear_bo.size);
1438 }
1439
1440 VkResult anv_CreateDevice(
1441 VkPhysicalDevice physicalDevice,
1442 const VkDeviceCreateInfo* pCreateInfo,
1443 const VkAllocationCallbacks* pAllocator,
1444 VkDevice* pDevice)
1445 {
1446 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1447 VkResult result;
1448 struct anv_device *device;
1449
1450 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1451
1452 struct anv_device_extension_table enabled_extensions = { };
1453 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1454 int idx;
1455 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
1456 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1457 anv_device_extensions[idx].extensionName) == 0)
1458 break;
1459 }
1460
1461 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
1462 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1463
1464 if (!physical_device->supported_extensions.extensions[idx])
1465 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1466
1467 enabled_extensions.extensions[idx] = true;
1468 }
1469
1470 /* Check enabled features */
1471 if (pCreateInfo->pEnabledFeatures) {
1472 VkPhysicalDeviceFeatures supported_features;
1473 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1474 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1475 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1476 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1477 for (uint32_t i = 0; i < num_features; i++) {
1478 if (enabled_feature[i] && !supported_feature[i])
1479 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1480 }
1481 }
1482
1483 /* Check requested queues and fail if we are requested to create any
1484 * queues with flags we don't support.
1485 */
1486 assert(pCreateInfo->queueCreateInfoCount > 0);
1487 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1488 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
1489 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
1490 }
1491
1492 /* Check if client specified queue priority. */
1493 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
1494 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
1495 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1496
1497 VkQueueGlobalPriorityEXT priority =
1498 queue_priority ? queue_priority->globalPriority :
1499 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
1500
1501 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1502 sizeof(*device), 8,
1503 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1504 if (!device)
1505 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1506
1507 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1508 device->instance = physical_device->instance;
1509 device->chipset_id = physical_device->chipset_id;
1510 device->no_hw = physical_device->no_hw;
1511 device->lost = false;
1512
1513 if (pAllocator)
1514 device->alloc = *pAllocator;
1515 else
1516 device->alloc = physical_device->instance->alloc;
1517
1518 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1519 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1520 if (device->fd == -1) {
1521 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1522 goto fail_device;
1523 }
1524
1525 device->context_id = anv_gem_create_context(device);
1526 if (device->context_id == -1) {
1527 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1528 goto fail_fd;
1529 }
1530
1531 /* As per spec, the driver implementation may deny requests to acquire
1532 * a priority above the default priority (MEDIUM) if the caller does not
1533 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
1534 * is returned.
1535 */
1536 if (physical_device->has_context_priority) {
1537 int err = anv_gem_set_context_param(device->fd, device->context_id,
1538 I915_CONTEXT_PARAM_PRIORITY,
1539 vk_priority_to_gen(priority));
1540 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
1541 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
1542 goto fail_fd;
1543 }
1544 }
1545
1546 device->info = physical_device->info;
1547 device->isl_dev = physical_device->isl_dev;
1548
1549 /* On Broadwell and later, we can use batch chaining to more efficiently
1550 * implement growing command buffers. Prior to Haswell, the kernel
1551 * command parser gets in the way and we have to fall back to growing
1552 * the batch.
1553 */
1554 device->can_chain_batches = device->info.gen >= 8;
1555
1556 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1557 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1558 device->enabled_extensions = enabled_extensions;
1559
1560 anv_device_init_dispatch(device);
1561
1562 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1563 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1564 goto fail_context_id;
1565 }
1566
1567 pthread_condattr_t condattr;
1568 if (pthread_condattr_init(&condattr) != 0) {
1569 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1570 goto fail_mutex;
1571 }
1572 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1573 pthread_condattr_destroy(&condattr);
1574 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1575 goto fail_mutex;
1576 }
1577 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1578 pthread_condattr_destroy(&condattr);
1579 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1580 goto fail_mutex;
1581 }
1582 pthread_condattr_destroy(&condattr);
1583
1584 uint64_t bo_flags =
1585 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
1586 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1587 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0);
1588
1589 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
1590
1591 result = anv_bo_cache_init(&device->bo_cache);
1592 if (result != VK_SUCCESS)
1593 goto fail_batch_bo_pool;
1594
1595 /* For the state pools we explicitly disable 48bit. */
1596 bo_flags = (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1597 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0);
1598
1599 result = anv_state_pool_init(&device->dynamic_state_pool, device, 16384,
1600 bo_flags);
1601 if (result != VK_SUCCESS)
1602 goto fail_bo_cache;
1603
1604 result = anv_state_pool_init(&device->instruction_state_pool, device, 16384,
1605 bo_flags);
1606 if (result != VK_SUCCESS)
1607 goto fail_dynamic_state_pool;
1608
1609 result = anv_state_pool_init(&device->surface_state_pool, device, 4096,
1610 bo_flags);
1611 if (result != VK_SUCCESS)
1612 goto fail_instruction_state_pool;
1613
1614 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1615 if (result != VK_SUCCESS)
1616 goto fail_surface_state_pool;
1617
1618 anv_device_init_trivial_batch(device);
1619
1620 if (device->info.gen >= 10)
1621 anv_device_init_hiz_clear_batch(device);
1622
1623 anv_scratch_pool_init(device, &device->scratch_pool);
1624
1625 anv_queue_init(device, &device->queue);
1626
1627 switch (device->info.gen) {
1628 case 7:
1629 if (!device->info.is_haswell)
1630 result = gen7_init_device_state(device);
1631 else
1632 result = gen75_init_device_state(device);
1633 break;
1634 case 8:
1635 result = gen8_init_device_state(device);
1636 break;
1637 case 9:
1638 result = gen9_init_device_state(device);
1639 break;
1640 case 10:
1641 result = gen10_init_device_state(device);
1642 break;
1643 case 11:
1644 result = gen11_init_device_state(device);
1645 break;
1646 default:
1647 /* Shouldn't get here as we don't create physical devices for any other
1648 * gens. */
1649 unreachable("unhandled gen");
1650 }
1651 if (result != VK_SUCCESS)
1652 goto fail_workaround_bo;
1653
1654 anv_device_init_blorp(device);
1655
1656 anv_device_init_border_colors(device);
1657
1658 *pDevice = anv_device_to_handle(device);
1659
1660 return VK_SUCCESS;
1661
1662 fail_workaround_bo:
1663 anv_queue_finish(&device->queue);
1664 anv_scratch_pool_finish(device, &device->scratch_pool);
1665 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1666 anv_gem_close(device, device->workaround_bo.gem_handle);
1667 fail_surface_state_pool:
1668 anv_state_pool_finish(&device->surface_state_pool);
1669 fail_instruction_state_pool:
1670 anv_state_pool_finish(&device->instruction_state_pool);
1671 fail_dynamic_state_pool:
1672 anv_state_pool_finish(&device->dynamic_state_pool);
1673 fail_bo_cache:
1674 anv_bo_cache_finish(&device->bo_cache);
1675 fail_batch_bo_pool:
1676 anv_bo_pool_finish(&device->batch_bo_pool);
1677 pthread_cond_destroy(&device->queue_submit);
1678 fail_mutex:
1679 pthread_mutex_destroy(&device->mutex);
1680 fail_context_id:
1681 anv_gem_destroy_context(device, device->context_id);
1682 fail_fd:
1683 close(device->fd);
1684 fail_device:
1685 vk_free(&device->alloc, device);
1686
1687 return result;
1688 }
1689
1690 void anv_DestroyDevice(
1691 VkDevice _device,
1692 const VkAllocationCallbacks* pAllocator)
1693 {
1694 ANV_FROM_HANDLE(anv_device, device, _device);
1695
1696 if (!device)
1697 return;
1698
1699 anv_device_finish_blorp(device);
1700
1701 anv_queue_finish(&device->queue);
1702
1703 #ifdef HAVE_VALGRIND
1704 /* We only need to free these to prevent valgrind errors. The backing
1705 * BO will go away in a couple of lines so we don't actually leak.
1706 */
1707 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1708 #endif
1709
1710 anv_scratch_pool_finish(device, &device->scratch_pool);
1711
1712 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1713 anv_gem_close(device, device->workaround_bo.gem_handle);
1714
1715 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
1716 if (device->info.gen >= 10)
1717 anv_gem_close(device, device->hiz_clear_bo.gem_handle);
1718
1719 anv_state_pool_finish(&device->surface_state_pool);
1720 anv_state_pool_finish(&device->instruction_state_pool);
1721 anv_state_pool_finish(&device->dynamic_state_pool);
1722
1723 anv_bo_cache_finish(&device->bo_cache);
1724
1725 anv_bo_pool_finish(&device->batch_bo_pool);
1726
1727 pthread_cond_destroy(&device->queue_submit);
1728 pthread_mutex_destroy(&device->mutex);
1729
1730 anv_gem_destroy_context(device, device->context_id);
1731
1732 close(device->fd);
1733
1734 vk_free(&device->alloc, device);
1735 }
1736
1737 VkResult anv_EnumerateInstanceLayerProperties(
1738 uint32_t* pPropertyCount,
1739 VkLayerProperties* pProperties)
1740 {
1741 if (pProperties == NULL) {
1742 *pPropertyCount = 0;
1743 return VK_SUCCESS;
1744 }
1745
1746 /* None supported at this time */
1747 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1748 }
1749
1750 VkResult anv_EnumerateDeviceLayerProperties(
1751 VkPhysicalDevice physicalDevice,
1752 uint32_t* pPropertyCount,
1753 VkLayerProperties* pProperties)
1754 {
1755 if (pProperties == NULL) {
1756 *pPropertyCount = 0;
1757 return VK_SUCCESS;
1758 }
1759
1760 /* None supported at this time */
1761 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1762 }
1763
1764 void anv_GetDeviceQueue(
1765 VkDevice _device,
1766 uint32_t queueNodeIndex,
1767 uint32_t queueIndex,
1768 VkQueue* pQueue)
1769 {
1770 ANV_FROM_HANDLE(anv_device, device, _device);
1771
1772 assert(queueIndex == 0);
1773
1774 *pQueue = anv_queue_to_handle(&device->queue);
1775 }
1776
1777 void anv_GetDeviceQueue2(
1778 VkDevice _device,
1779 const VkDeviceQueueInfo2* pQueueInfo,
1780 VkQueue* pQueue)
1781 {
1782 ANV_FROM_HANDLE(anv_device, device, _device);
1783
1784 assert(pQueueInfo->queueIndex == 0);
1785
1786 if (pQueueInfo->flags == device->queue.flags)
1787 *pQueue = anv_queue_to_handle(&device->queue);
1788 else
1789 *pQueue = NULL;
1790 }
1791
1792 VkResult
1793 anv_device_query_status(struct anv_device *device)
1794 {
1795 /* This isn't likely as most of the callers of this function already check
1796 * for it. However, it doesn't hurt to check and it potentially lets us
1797 * avoid an ioctl.
1798 */
1799 if (unlikely(device->lost))
1800 return VK_ERROR_DEVICE_LOST;
1801
1802 uint32_t active, pending;
1803 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
1804 if (ret == -1) {
1805 /* We don't know the real error. */
1806 device->lost = true;
1807 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1808 "get_reset_stats failed: %m");
1809 }
1810
1811 if (active) {
1812 device->lost = true;
1813 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1814 "GPU hung on one of our command buffers");
1815 } else if (pending) {
1816 device->lost = true;
1817 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1818 "GPU hung with commands in-flight");
1819 }
1820
1821 return VK_SUCCESS;
1822 }
1823
1824 VkResult
1825 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
1826 {
1827 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
1828 * Other usages of the BO (such as on different hardware) will not be
1829 * flagged as "busy" by this ioctl. Use with care.
1830 */
1831 int ret = anv_gem_busy(device, bo->gem_handle);
1832 if (ret == 1) {
1833 return VK_NOT_READY;
1834 } else if (ret == -1) {
1835 /* We don't know the real error. */
1836 device->lost = true;
1837 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1838 "gem wait failed: %m");
1839 }
1840
1841 /* Query for device status after the busy call. If the BO we're checking
1842 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
1843 * client because it clearly doesn't have valid data. Yes, this most
1844 * likely means an ioctl, but we just did an ioctl to query the busy status
1845 * so it's no great loss.
1846 */
1847 return anv_device_query_status(device);
1848 }
1849
1850 VkResult
1851 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1852 int64_t timeout)
1853 {
1854 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
1855 if (ret == -1 && errno == ETIME) {
1856 return VK_TIMEOUT;
1857 } else if (ret == -1) {
1858 /* We don't know the real error. */
1859 device->lost = true;
1860 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1861 "gem wait failed: %m");
1862 }
1863
1864 /* Query for device status after the wait. If the BO we're waiting on got
1865 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
1866 * because it clearly doesn't have valid data. Yes, this most likely means
1867 * an ioctl, but we just did an ioctl to wait so it's no great loss.
1868 */
1869 return anv_device_query_status(device);
1870 }
1871
1872 VkResult anv_DeviceWaitIdle(
1873 VkDevice _device)
1874 {
1875 ANV_FROM_HANDLE(anv_device, device, _device);
1876 if (unlikely(device->lost))
1877 return VK_ERROR_DEVICE_LOST;
1878
1879 struct anv_batch batch;
1880
1881 uint32_t cmds[8];
1882 batch.start = batch.next = cmds;
1883 batch.end = (void *) cmds + sizeof(cmds);
1884
1885 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1886 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1887
1888 return anv_device_submit_simple_batch(device, &batch);
1889 }
1890
1891 VkResult
1892 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1893 {
1894 uint32_t gem_handle = anv_gem_create(device, size);
1895 if (!gem_handle)
1896 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1897
1898 anv_bo_init(bo, gem_handle, size);
1899
1900 return VK_SUCCESS;
1901 }
1902
1903 VkResult anv_AllocateMemory(
1904 VkDevice _device,
1905 const VkMemoryAllocateInfo* pAllocateInfo,
1906 const VkAllocationCallbacks* pAllocator,
1907 VkDeviceMemory* pMem)
1908 {
1909 ANV_FROM_HANDLE(anv_device, device, _device);
1910 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1911 struct anv_device_memory *mem;
1912 VkResult result = VK_SUCCESS;
1913
1914 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1915
1916 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1917 assert(pAllocateInfo->allocationSize > 0);
1918
1919 if (pAllocateInfo->allocationSize > MAX_MEMORY_ALLOCATION_SIZE)
1920 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1921
1922 /* FINISHME: Fail if allocation request exceeds heap size. */
1923
1924 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1925 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1926 if (mem == NULL)
1927 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1928
1929 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
1930 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
1931 mem->map = NULL;
1932 mem->map_size = 0;
1933
1934 const VkImportMemoryFdInfoKHR *fd_info =
1935 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
1936
1937 /* The Vulkan spec permits handleType to be 0, in which case the struct is
1938 * ignored.
1939 */
1940 if (fd_info && fd_info->handleType) {
1941 /* At the moment, we support only the below handle types. */
1942 assert(fd_info->handleType ==
1943 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
1944 fd_info->handleType ==
1945 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1946
1947 result = anv_bo_cache_import(device, &device->bo_cache,
1948 fd_info->fd, &mem->bo);
1949 if (result != VK_SUCCESS)
1950 goto fail;
1951
1952 VkDeviceSize aligned_alloc_size =
1953 align_u64(pAllocateInfo->allocationSize, 4096);
1954
1955 /* For security purposes, we reject importing the bo if it's smaller
1956 * than the requested allocation size. This prevents a malicious client
1957 * from passing a buffer to a trusted client, lying about the size, and
1958 * telling the trusted client to try and texture from an image that goes
1959 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
1960 * in the trusted client. The trusted client can protect itself against
1961 * this sort of attack but only if it can trust the buffer size.
1962 */
1963 if (mem->bo->size < aligned_alloc_size) {
1964 result = vk_errorf(device->instance, device,
1965 VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR,
1966 "aligned allocationSize too large for "
1967 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR: "
1968 "%"PRIu64"B > %"PRIu64"B",
1969 aligned_alloc_size, mem->bo->size);
1970 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1971 goto fail;
1972 }
1973
1974 /* From the Vulkan spec:
1975 *
1976 * "Importing memory from a file descriptor transfers ownership of
1977 * the file descriptor from the application to the Vulkan
1978 * implementation. The application must not perform any operations on
1979 * the file descriptor after a successful import."
1980 *
1981 * If the import fails, we leave the file descriptor open.
1982 */
1983 close(fd_info->fd);
1984 } else {
1985 result = anv_bo_cache_alloc(device, &device->bo_cache,
1986 pAllocateInfo->allocationSize,
1987 &mem->bo);
1988 if (result != VK_SUCCESS)
1989 goto fail;
1990
1991 const VkMemoryDedicatedAllocateInfoKHR *dedicated_info =
1992 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
1993 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
1994 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
1995
1996 /* Some legacy (non-modifiers) consumers need the tiling to be set on
1997 * the BO. In this case, we have a dedicated allocation.
1998 */
1999 if (image->needs_set_tiling) {
2000 const uint32_t i915_tiling =
2001 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
2002 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
2003 image->planes[0].surface.isl.row_pitch,
2004 i915_tiling);
2005 if (ret) {
2006 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2007 return vk_errorf(device->instance, NULL,
2008 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2009 "failed to set BO tiling: %m");
2010 }
2011 }
2012 }
2013 }
2014
2015 assert(mem->type->heapIndex < pdevice->memory.heap_count);
2016 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
2017 mem->bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2018
2019 const struct wsi_memory_allocate_info *wsi_info =
2020 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
2021 if (wsi_info && wsi_info->implicit_sync) {
2022 /* We need to set the WRITE flag on window system buffers so that GEM
2023 * will know we're writing to them and synchronize uses on other rings
2024 * (eg if the display server uses the blitter ring).
2025 */
2026 mem->bo->flags |= EXEC_OBJECT_WRITE;
2027 } else if (pdevice->has_exec_async) {
2028 mem->bo->flags |= EXEC_OBJECT_ASYNC;
2029 }
2030
2031 *pMem = anv_device_memory_to_handle(mem);
2032
2033 return VK_SUCCESS;
2034
2035 fail:
2036 vk_free2(&device->alloc, pAllocator, mem);
2037
2038 return result;
2039 }
2040
2041 VkResult anv_GetMemoryFdKHR(
2042 VkDevice device_h,
2043 const VkMemoryGetFdInfoKHR* pGetFdInfo,
2044 int* pFd)
2045 {
2046 ANV_FROM_HANDLE(anv_device, dev, device_h);
2047 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
2048
2049 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2050
2051 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2052 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2053
2054 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
2055 }
2056
2057 VkResult anv_GetMemoryFdPropertiesKHR(
2058 VkDevice _device,
2059 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
2060 int fd,
2061 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
2062 {
2063 ANV_FROM_HANDLE(anv_device, device, _device);
2064 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2065
2066 switch (handleType) {
2067 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
2068 /* dma-buf can be imported as any memory type */
2069 pMemoryFdProperties->memoryTypeBits =
2070 (1 << pdevice->memory.type_count) - 1;
2071 return VK_SUCCESS;
2072
2073 default:
2074 /* The valid usage section for this function says:
2075 *
2076 * "handleType must not be one of the handle types defined as
2077 * opaque."
2078 *
2079 * So opaque handle types fall into the default "unsupported" case.
2080 */
2081 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2082 }
2083 }
2084
2085 void anv_FreeMemory(
2086 VkDevice _device,
2087 VkDeviceMemory _mem,
2088 const VkAllocationCallbacks* pAllocator)
2089 {
2090 ANV_FROM_HANDLE(anv_device, device, _device);
2091 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
2092
2093 if (mem == NULL)
2094 return;
2095
2096 if (mem->map)
2097 anv_UnmapMemory(_device, _mem);
2098
2099 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2100
2101 vk_free2(&device->alloc, pAllocator, mem);
2102 }
2103
2104 VkResult anv_MapMemory(
2105 VkDevice _device,
2106 VkDeviceMemory _memory,
2107 VkDeviceSize offset,
2108 VkDeviceSize size,
2109 VkMemoryMapFlags flags,
2110 void** ppData)
2111 {
2112 ANV_FROM_HANDLE(anv_device, device, _device);
2113 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2114
2115 if (mem == NULL) {
2116 *ppData = NULL;
2117 return VK_SUCCESS;
2118 }
2119
2120 if (size == VK_WHOLE_SIZE)
2121 size = mem->bo->size - offset;
2122
2123 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
2124 *
2125 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
2126 * assert(size != 0);
2127 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
2128 * equal to the size of the memory minus offset
2129 */
2130 assert(size > 0);
2131 assert(offset + size <= mem->bo->size);
2132
2133 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
2134 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
2135 * at a time is valid. We could just mmap up front and return an offset
2136 * pointer here, but that may exhaust virtual memory on 32 bit
2137 * userspace. */
2138
2139 uint32_t gem_flags = 0;
2140
2141 if (!device->info.has_llc &&
2142 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
2143 gem_flags |= I915_MMAP_WC;
2144
2145 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
2146 uint64_t map_offset = offset & ~4095ull;
2147 assert(offset >= map_offset);
2148 uint64_t map_size = (offset + size) - map_offset;
2149
2150 /* Let's map whole pages */
2151 map_size = align_u64(map_size, 4096);
2152
2153 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
2154 map_offset, map_size, gem_flags);
2155 if (map == MAP_FAILED)
2156 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
2157
2158 mem->map = map;
2159 mem->map_size = map_size;
2160
2161 *ppData = mem->map + (offset - map_offset);
2162
2163 return VK_SUCCESS;
2164 }
2165
2166 void anv_UnmapMemory(
2167 VkDevice _device,
2168 VkDeviceMemory _memory)
2169 {
2170 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2171
2172 if (mem == NULL)
2173 return;
2174
2175 anv_gem_munmap(mem->map, mem->map_size);
2176
2177 mem->map = NULL;
2178 mem->map_size = 0;
2179 }
2180
2181 static void
2182 clflush_mapped_ranges(struct anv_device *device,
2183 uint32_t count,
2184 const VkMappedMemoryRange *ranges)
2185 {
2186 for (uint32_t i = 0; i < count; i++) {
2187 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
2188 if (ranges[i].offset >= mem->map_size)
2189 continue;
2190
2191 gen_clflush_range(mem->map + ranges[i].offset,
2192 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
2193 }
2194 }
2195
2196 VkResult anv_FlushMappedMemoryRanges(
2197 VkDevice _device,
2198 uint32_t memoryRangeCount,
2199 const VkMappedMemoryRange* pMemoryRanges)
2200 {
2201 ANV_FROM_HANDLE(anv_device, device, _device);
2202
2203 if (device->info.has_llc)
2204 return VK_SUCCESS;
2205
2206 /* Make sure the writes we're flushing have landed. */
2207 __builtin_ia32_mfence();
2208
2209 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2210
2211 return VK_SUCCESS;
2212 }
2213
2214 VkResult anv_InvalidateMappedMemoryRanges(
2215 VkDevice _device,
2216 uint32_t memoryRangeCount,
2217 const VkMappedMemoryRange* pMemoryRanges)
2218 {
2219 ANV_FROM_HANDLE(anv_device, device, _device);
2220
2221 if (device->info.has_llc)
2222 return VK_SUCCESS;
2223
2224 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2225
2226 /* Make sure no reads get moved up above the invalidate. */
2227 __builtin_ia32_mfence();
2228
2229 return VK_SUCCESS;
2230 }
2231
2232 void anv_GetBufferMemoryRequirements(
2233 VkDevice _device,
2234 VkBuffer _buffer,
2235 VkMemoryRequirements* pMemoryRequirements)
2236 {
2237 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2238 ANV_FROM_HANDLE(anv_device, device, _device);
2239 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2240
2241 /* The Vulkan spec (git aaed022) says:
2242 *
2243 * memoryTypeBits is a bitfield and contains one bit set for every
2244 * supported memory type for the resource. The bit `1<<i` is set if and
2245 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2246 * structure for the physical device is supported.
2247 */
2248 uint32_t memory_types = 0;
2249 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
2250 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
2251 if ((valid_usage & buffer->usage) == buffer->usage)
2252 memory_types |= (1u << i);
2253 }
2254
2255 /* Base alignment requirement of a cache line */
2256 uint32_t alignment = 16;
2257
2258 /* We need an alignment of 32 for pushing UBOs */
2259 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
2260 alignment = MAX2(alignment, 32);
2261
2262 pMemoryRequirements->size = buffer->size;
2263 pMemoryRequirements->alignment = alignment;
2264
2265 /* Storage and Uniform buffers should have their size aligned to
2266 * 32-bits to avoid boundary checks when last DWord is not complete.
2267 * This would ensure that not internal padding would be needed for
2268 * 16-bit types.
2269 */
2270 if (device->robust_buffer_access &&
2271 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
2272 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
2273 pMemoryRequirements->size = align_u64(buffer->size, 4);
2274
2275 pMemoryRequirements->memoryTypeBits = memory_types;
2276 }
2277
2278 void anv_GetBufferMemoryRequirements2(
2279 VkDevice _device,
2280 const VkBufferMemoryRequirementsInfo2* pInfo,
2281 VkMemoryRequirements2* pMemoryRequirements)
2282 {
2283 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
2284 &pMemoryRequirements->memoryRequirements);
2285
2286 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2287 switch (ext->sType) {
2288 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2289 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2290 requirements->prefersDedicatedAllocation = VK_FALSE;
2291 requirements->requiresDedicatedAllocation = VK_FALSE;
2292 break;
2293 }
2294
2295 default:
2296 anv_debug_ignored_stype(ext->sType);
2297 break;
2298 }
2299 }
2300 }
2301
2302 void anv_GetImageMemoryRequirements(
2303 VkDevice _device,
2304 VkImage _image,
2305 VkMemoryRequirements* pMemoryRequirements)
2306 {
2307 ANV_FROM_HANDLE(anv_image, image, _image);
2308 ANV_FROM_HANDLE(anv_device, device, _device);
2309 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2310
2311 /* The Vulkan spec (git aaed022) says:
2312 *
2313 * memoryTypeBits is a bitfield and contains one bit set for every
2314 * supported memory type for the resource. The bit `1<<i` is set if and
2315 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2316 * structure for the physical device is supported.
2317 *
2318 * All types are currently supported for images.
2319 */
2320 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
2321
2322 pMemoryRequirements->size = image->size;
2323 pMemoryRequirements->alignment = image->alignment;
2324 pMemoryRequirements->memoryTypeBits = memory_types;
2325 }
2326
2327 void anv_GetImageMemoryRequirements2(
2328 VkDevice _device,
2329 const VkImageMemoryRequirementsInfo2* pInfo,
2330 VkMemoryRequirements2* pMemoryRequirements)
2331 {
2332 ANV_FROM_HANDLE(anv_device, device, _device);
2333 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
2334
2335 anv_GetImageMemoryRequirements(_device, pInfo->image,
2336 &pMemoryRequirements->memoryRequirements);
2337
2338 vk_foreach_struct_const(ext, pInfo->pNext) {
2339 switch (ext->sType) {
2340 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
2341 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2342 const VkImagePlaneMemoryRequirementsInfoKHR *plane_reqs =
2343 (const VkImagePlaneMemoryRequirementsInfoKHR *) ext;
2344 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
2345 plane_reqs->planeAspect);
2346
2347 assert(image->planes[plane].offset == 0);
2348
2349 /* The Vulkan spec (git aaed022) says:
2350 *
2351 * memoryTypeBits is a bitfield and contains one bit set for every
2352 * supported memory type for the resource. The bit `1<<i` is set
2353 * if and only if the memory type `i` in the
2354 * VkPhysicalDeviceMemoryProperties structure for the physical
2355 * device is supported.
2356 *
2357 * All types are currently supported for images.
2358 */
2359 pMemoryRequirements->memoryRequirements.memoryTypeBits =
2360 (1ull << pdevice->memory.type_count) - 1;
2361
2362 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
2363 pMemoryRequirements->memoryRequirements.alignment =
2364 image->planes[plane].alignment;
2365 break;
2366 }
2367
2368 default:
2369 anv_debug_ignored_stype(ext->sType);
2370 break;
2371 }
2372 }
2373
2374 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2375 switch (ext->sType) {
2376 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2377 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2378 if (image->needs_set_tiling) {
2379 /* If we need to set the tiling for external consumers, we need a
2380 * dedicated allocation.
2381 *
2382 * See also anv_AllocateMemory.
2383 */
2384 requirements->prefersDedicatedAllocation = VK_TRUE;
2385 requirements->requiresDedicatedAllocation = VK_TRUE;
2386 } else {
2387 requirements->prefersDedicatedAllocation = VK_FALSE;
2388 requirements->requiresDedicatedAllocation = VK_FALSE;
2389 }
2390 break;
2391 }
2392
2393 default:
2394 anv_debug_ignored_stype(ext->sType);
2395 break;
2396 }
2397 }
2398 }
2399
2400 void anv_GetImageSparseMemoryRequirements(
2401 VkDevice device,
2402 VkImage image,
2403 uint32_t* pSparseMemoryRequirementCount,
2404 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2405 {
2406 *pSparseMemoryRequirementCount = 0;
2407 }
2408
2409 void anv_GetImageSparseMemoryRequirements2(
2410 VkDevice device,
2411 const VkImageSparseMemoryRequirementsInfo2* pInfo,
2412 uint32_t* pSparseMemoryRequirementCount,
2413 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
2414 {
2415 *pSparseMemoryRequirementCount = 0;
2416 }
2417
2418 void anv_GetDeviceMemoryCommitment(
2419 VkDevice device,
2420 VkDeviceMemory memory,
2421 VkDeviceSize* pCommittedMemoryInBytes)
2422 {
2423 *pCommittedMemoryInBytes = 0;
2424 }
2425
2426 static void
2427 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
2428 {
2429 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
2430 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
2431
2432 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
2433
2434 if (mem) {
2435 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
2436 buffer->bo = mem->bo;
2437 buffer->offset = pBindInfo->memoryOffset;
2438 } else {
2439 buffer->bo = NULL;
2440 buffer->offset = 0;
2441 }
2442 }
2443
2444 VkResult anv_BindBufferMemory(
2445 VkDevice device,
2446 VkBuffer buffer,
2447 VkDeviceMemory memory,
2448 VkDeviceSize memoryOffset)
2449 {
2450 anv_bind_buffer_memory(
2451 &(VkBindBufferMemoryInfo) {
2452 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
2453 .buffer = buffer,
2454 .memory = memory,
2455 .memoryOffset = memoryOffset,
2456 });
2457
2458 return VK_SUCCESS;
2459 }
2460
2461 VkResult anv_BindBufferMemory2(
2462 VkDevice device,
2463 uint32_t bindInfoCount,
2464 const VkBindBufferMemoryInfo* pBindInfos)
2465 {
2466 for (uint32_t i = 0; i < bindInfoCount; i++)
2467 anv_bind_buffer_memory(&pBindInfos[i]);
2468
2469 return VK_SUCCESS;
2470 }
2471
2472 VkResult anv_QueueBindSparse(
2473 VkQueue _queue,
2474 uint32_t bindInfoCount,
2475 const VkBindSparseInfo* pBindInfo,
2476 VkFence fence)
2477 {
2478 ANV_FROM_HANDLE(anv_queue, queue, _queue);
2479 if (unlikely(queue->device->lost))
2480 return VK_ERROR_DEVICE_LOST;
2481
2482 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2483 }
2484
2485 // Event functions
2486
2487 VkResult anv_CreateEvent(
2488 VkDevice _device,
2489 const VkEventCreateInfo* pCreateInfo,
2490 const VkAllocationCallbacks* pAllocator,
2491 VkEvent* pEvent)
2492 {
2493 ANV_FROM_HANDLE(anv_device, device, _device);
2494 struct anv_state state;
2495 struct anv_event *event;
2496
2497 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2498
2499 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2500 sizeof(*event), 8);
2501 event = state.map;
2502 event->state = state;
2503 event->semaphore = VK_EVENT_RESET;
2504
2505 if (!device->info.has_llc) {
2506 /* Make sure the writes we're flushing have landed. */
2507 __builtin_ia32_mfence();
2508 __builtin_ia32_clflush(event);
2509 }
2510
2511 *pEvent = anv_event_to_handle(event);
2512
2513 return VK_SUCCESS;
2514 }
2515
2516 void anv_DestroyEvent(
2517 VkDevice _device,
2518 VkEvent _event,
2519 const VkAllocationCallbacks* pAllocator)
2520 {
2521 ANV_FROM_HANDLE(anv_device, device, _device);
2522 ANV_FROM_HANDLE(anv_event, event, _event);
2523
2524 if (!event)
2525 return;
2526
2527 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2528 }
2529
2530 VkResult anv_GetEventStatus(
2531 VkDevice _device,
2532 VkEvent _event)
2533 {
2534 ANV_FROM_HANDLE(anv_device, device, _device);
2535 ANV_FROM_HANDLE(anv_event, event, _event);
2536
2537 if (unlikely(device->lost))
2538 return VK_ERROR_DEVICE_LOST;
2539
2540 if (!device->info.has_llc) {
2541 /* Invalidate read cache before reading event written by GPU. */
2542 __builtin_ia32_clflush(event);
2543 __builtin_ia32_mfence();
2544
2545 }
2546
2547 return event->semaphore;
2548 }
2549
2550 VkResult anv_SetEvent(
2551 VkDevice _device,
2552 VkEvent _event)
2553 {
2554 ANV_FROM_HANDLE(anv_device, device, _device);
2555 ANV_FROM_HANDLE(anv_event, event, _event);
2556
2557 event->semaphore = VK_EVENT_SET;
2558
2559 if (!device->info.has_llc) {
2560 /* Make sure the writes we're flushing have landed. */
2561 __builtin_ia32_mfence();
2562 __builtin_ia32_clflush(event);
2563 }
2564
2565 return VK_SUCCESS;
2566 }
2567
2568 VkResult anv_ResetEvent(
2569 VkDevice _device,
2570 VkEvent _event)
2571 {
2572 ANV_FROM_HANDLE(anv_device, device, _device);
2573 ANV_FROM_HANDLE(anv_event, event, _event);
2574
2575 event->semaphore = VK_EVENT_RESET;
2576
2577 if (!device->info.has_llc) {
2578 /* Make sure the writes we're flushing have landed. */
2579 __builtin_ia32_mfence();
2580 __builtin_ia32_clflush(event);
2581 }
2582
2583 return VK_SUCCESS;
2584 }
2585
2586 // Buffer functions
2587
2588 VkResult anv_CreateBuffer(
2589 VkDevice _device,
2590 const VkBufferCreateInfo* pCreateInfo,
2591 const VkAllocationCallbacks* pAllocator,
2592 VkBuffer* pBuffer)
2593 {
2594 ANV_FROM_HANDLE(anv_device, device, _device);
2595 struct anv_buffer *buffer;
2596
2597 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2598
2599 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2600 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2601 if (buffer == NULL)
2602 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2603
2604 buffer->size = pCreateInfo->size;
2605 buffer->usage = pCreateInfo->usage;
2606 buffer->bo = NULL;
2607 buffer->offset = 0;
2608
2609 *pBuffer = anv_buffer_to_handle(buffer);
2610
2611 return VK_SUCCESS;
2612 }
2613
2614 void anv_DestroyBuffer(
2615 VkDevice _device,
2616 VkBuffer _buffer,
2617 const VkAllocationCallbacks* pAllocator)
2618 {
2619 ANV_FROM_HANDLE(anv_device, device, _device);
2620 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2621
2622 if (!buffer)
2623 return;
2624
2625 vk_free2(&device->alloc, pAllocator, buffer);
2626 }
2627
2628 void
2629 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2630 enum isl_format format,
2631 uint32_t offset, uint32_t range, uint32_t stride)
2632 {
2633 isl_buffer_fill_state(&device->isl_dev, state.map,
2634 .address = offset,
2635 .mocs = device->default_mocs,
2636 .size = range,
2637 .format = format,
2638 .stride = stride);
2639
2640 anv_state_flush(device, state);
2641 }
2642
2643 void anv_DestroySampler(
2644 VkDevice _device,
2645 VkSampler _sampler,
2646 const VkAllocationCallbacks* pAllocator)
2647 {
2648 ANV_FROM_HANDLE(anv_device, device, _device);
2649 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2650
2651 if (!sampler)
2652 return;
2653
2654 vk_free2(&device->alloc, pAllocator, sampler);
2655 }
2656
2657 VkResult anv_CreateFramebuffer(
2658 VkDevice _device,
2659 const VkFramebufferCreateInfo* pCreateInfo,
2660 const VkAllocationCallbacks* pAllocator,
2661 VkFramebuffer* pFramebuffer)
2662 {
2663 ANV_FROM_HANDLE(anv_device, device, _device);
2664 struct anv_framebuffer *framebuffer;
2665
2666 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2667
2668 size_t size = sizeof(*framebuffer) +
2669 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2670 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2671 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2672 if (framebuffer == NULL)
2673 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2674
2675 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2676 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2677 VkImageView _iview = pCreateInfo->pAttachments[i];
2678 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2679 }
2680
2681 framebuffer->width = pCreateInfo->width;
2682 framebuffer->height = pCreateInfo->height;
2683 framebuffer->layers = pCreateInfo->layers;
2684
2685 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2686
2687 return VK_SUCCESS;
2688 }
2689
2690 void anv_DestroyFramebuffer(
2691 VkDevice _device,
2692 VkFramebuffer _fb,
2693 const VkAllocationCallbacks* pAllocator)
2694 {
2695 ANV_FROM_HANDLE(anv_device, device, _device);
2696 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2697
2698 if (!fb)
2699 return;
2700
2701 vk_free2(&device->alloc, pAllocator, fb);
2702 }
2703
2704 /* vk_icd.h does not declare this function, so we declare it here to
2705 * suppress Wmissing-prototypes.
2706 */
2707 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2708 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2709
2710 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2711 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2712 {
2713 /* For the full details on loader interface versioning, see
2714 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2715 * What follows is a condensed summary, to help you navigate the large and
2716 * confusing official doc.
2717 *
2718 * - Loader interface v0 is incompatible with later versions. We don't
2719 * support it.
2720 *
2721 * - In loader interface v1:
2722 * - The first ICD entrypoint called by the loader is
2723 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2724 * entrypoint.
2725 * - The ICD must statically expose no other Vulkan symbol unless it is
2726 * linked with -Bsymbolic.
2727 * - Each dispatchable Vulkan handle created by the ICD must be
2728 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2729 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2730 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2731 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2732 * such loader-managed surfaces.
2733 *
2734 * - Loader interface v2 differs from v1 in:
2735 * - The first ICD entrypoint called by the loader is
2736 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2737 * statically expose this entrypoint.
2738 *
2739 * - Loader interface v3 differs from v2 in:
2740 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2741 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2742 * because the loader no longer does so.
2743 */
2744 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2745 return VK_SUCCESS;
2746 }