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