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