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