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