anv: Add a per-instance table of enabled extensions
[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 struct anv_instance_extension_table enabled_extensions = {};
543 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
544 int idx;
545 for (idx = 0; idx < ANV_INSTANCE_EXTENSION_COUNT; idx++) {
546 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
547 anv_instance_extensions[idx].extensionName) == 0)
548 break;
549 }
550
551 if (idx >= ANV_INSTANCE_EXTENSION_COUNT)
552 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
553
554 if (!anv_instance_extensions_supported.extensions[idx])
555 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
556
557 enabled_extensions.extensions[idx] = true;
558 }
559
560 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
561 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
562 if (!instance)
563 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
564
565 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
566
567 if (pAllocator)
568 instance->alloc = *pAllocator;
569 else
570 instance->alloc = default_alloc;
571
572 instance->apiVersion = client_version;
573 instance->enabled_extensions = enabled_extensions;
574 instance->physicalDeviceCount = -1;
575
576 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
577 if (result != VK_SUCCESS) {
578 vk_free2(&default_alloc, pAllocator, instance);
579 return vk_error(result);
580 }
581
582 _mesa_locale_init();
583
584 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
585
586 *pInstance = anv_instance_to_handle(instance);
587
588 return VK_SUCCESS;
589 }
590
591 void anv_DestroyInstance(
592 VkInstance _instance,
593 const VkAllocationCallbacks* pAllocator)
594 {
595 ANV_FROM_HANDLE(anv_instance, instance, _instance);
596
597 if (!instance)
598 return;
599
600 if (instance->physicalDeviceCount > 0) {
601 /* We support at most one physical device. */
602 assert(instance->physicalDeviceCount == 1);
603 anv_physical_device_finish(&instance->physicalDevice);
604 }
605
606 VG(VALGRIND_DESTROY_MEMPOOL(instance));
607
608 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
609
610 _mesa_locale_fini();
611
612 vk_free(&instance->alloc, instance);
613 }
614
615 static VkResult
616 anv_enumerate_devices(struct anv_instance *instance)
617 {
618 /* TODO: Check for more devices ? */
619 drmDevicePtr devices[8];
620 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
621 int max_devices;
622
623 instance->physicalDeviceCount = 0;
624
625 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
626 if (max_devices < 1)
627 return VK_ERROR_INCOMPATIBLE_DRIVER;
628
629 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
630 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
631 devices[i]->bustype == DRM_BUS_PCI &&
632 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
633
634 result = anv_physical_device_init(&instance->physicalDevice,
635 instance,
636 devices[i]->nodes[DRM_NODE_RENDER]);
637 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
638 break;
639 }
640 }
641 drmFreeDevices(devices, max_devices);
642
643 if (result == VK_SUCCESS)
644 instance->physicalDeviceCount = 1;
645
646 return result;
647 }
648
649
650 VkResult anv_EnumeratePhysicalDevices(
651 VkInstance _instance,
652 uint32_t* pPhysicalDeviceCount,
653 VkPhysicalDevice* pPhysicalDevices)
654 {
655 ANV_FROM_HANDLE(anv_instance, instance, _instance);
656 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
657 VkResult result;
658
659 if (instance->physicalDeviceCount < 0) {
660 result = anv_enumerate_devices(instance);
661 if (result != VK_SUCCESS &&
662 result != VK_ERROR_INCOMPATIBLE_DRIVER)
663 return result;
664 }
665
666 if (instance->physicalDeviceCount > 0) {
667 assert(instance->physicalDeviceCount == 1);
668 vk_outarray_append(&out, i) {
669 *i = anv_physical_device_to_handle(&instance->physicalDevice);
670 }
671 }
672
673 return vk_outarray_status(&out);
674 }
675
676 void anv_GetPhysicalDeviceFeatures(
677 VkPhysicalDevice physicalDevice,
678 VkPhysicalDeviceFeatures* pFeatures)
679 {
680 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
681
682 *pFeatures = (VkPhysicalDeviceFeatures) {
683 .robustBufferAccess = true,
684 .fullDrawIndexUint32 = true,
685 .imageCubeArray = true,
686 .independentBlend = true,
687 .geometryShader = true,
688 .tessellationShader = true,
689 .sampleRateShading = true,
690 .dualSrcBlend = true,
691 .logicOp = true,
692 .multiDrawIndirect = true,
693 .drawIndirectFirstInstance = true,
694 .depthClamp = true,
695 .depthBiasClamp = true,
696 .fillModeNonSolid = true,
697 .depthBounds = false,
698 .wideLines = true,
699 .largePoints = true,
700 .alphaToOne = true,
701 .multiViewport = true,
702 .samplerAnisotropy = true,
703 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
704 pdevice->info.is_baytrail,
705 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
706 .textureCompressionBC = true,
707 .occlusionQueryPrecise = true,
708 .pipelineStatisticsQuery = true,
709 .fragmentStoresAndAtomics = true,
710 .shaderTessellationAndGeometryPointSize = true,
711 .shaderImageGatherExtended = true,
712 .shaderStorageImageExtendedFormats = true,
713 .shaderStorageImageMultisample = false,
714 .shaderStorageImageReadWithoutFormat = false,
715 .shaderStorageImageWriteWithoutFormat = true,
716 .shaderUniformBufferArrayDynamicIndexing = true,
717 .shaderSampledImageArrayDynamicIndexing = true,
718 .shaderStorageBufferArrayDynamicIndexing = true,
719 .shaderStorageImageArrayDynamicIndexing = true,
720 .shaderClipDistance = true,
721 .shaderCullDistance = true,
722 .shaderFloat64 = pdevice->info.gen >= 8,
723 .shaderInt64 = pdevice->info.gen >= 8,
724 .shaderInt16 = false,
725 .shaderResourceMinLod = false,
726 .variableMultisampleRate = false,
727 .inheritedQueries = true,
728 };
729
730 /* We can't do image stores in vec4 shaders */
731 pFeatures->vertexPipelineStoresAndAtomics =
732 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
733 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
734 }
735
736 void anv_GetPhysicalDeviceFeatures2KHR(
737 VkPhysicalDevice physicalDevice,
738 VkPhysicalDeviceFeatures2KHR* pFeatures)
739 {
740 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
741
742 vk_foreach_struct(ext, pFeatures->pNext) {
743 switch (ext->sType) {
744 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX: {
745 VkPhysicalDeviceMultiviewFeaturesKHX *features =
746 (VkPhysicalDeviceMultiviewFeaturesKHX *)ext;
747 features->multiview = true;
748 features->multiviewGeometryShader = true;
749 features->multiviewTessellationShader = true;
750 break;
751 }
752
753 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR: {
754 VkPhysicalDeviceVariablePointerFeaturesKHR *features = (void *)ext;
755 features->variablePointersStorageBuffer = true;
756 features->variablePointers = true;
757 break;
758 }
759
760 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR: {
761 VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR *features =
762 (VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR *) ext;
763 features->samplerYcbcrConversion = true;
764 break;
765 }
766
767 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR: {
768 VkPhysicalDevice16BitStorageFeaturesKHR *features =
769 (VkPhysicalDevice16BitStorageFeaturesKHR *)ext;
770
771 features->storageBuffer16BitAccess = false;
772 features->uniformAndStorageBuffer16BitAccess = false;
773 features->storagePushConstant16 = false;
774 features->storageInputOutput16 = false;
775 break;
776 }
777
778 default:
779 anv_debug_ignored_stype(ext->sType);
780 break;
781 }
782 }
783 }
784
785 void anv_GetPhysicalDeviceProperties(
786 VkPhysicalDevice physicalDevice,
787 VkPhysicalDeviceProperties* pProperties)
788 {
789 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
790 const struct gen_device_info *devinfo = &pdevice->info;
791
792 /* See assertions made when programming the buffer surface state. */
793 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
794 (1ul << 30) : (1ul << 27);
795
796 const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
797 128 : 16;
798
799 VkSampleCountFlags sample_counts =
800 isl_device_get_sample_counts(&pdevice->isl_dev);
801
802 VkPhysicalDeviceLimits limits = {
803 .maxImageDimension1D = (1 << 14),
804 .maxImageDimension2D = (1 << 14),
805 .maxImageDimension3D = (1 << 11),
806 .maxImageDimensionCube = (1 << 14),
807 .maxImageArrayLayers = (1 << 11),
808 .maxTexelBufferElements = 128 * 1024 * 1024,
809 .maxUniformBufferRange = (1ul << 27),
810 .maxStorageBufferRange = max_raw_buffer_sz,
811 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
812 .maxMemoryAllocationCount = UINT32_MAX,
813 .maxSamplerAllocationCount = 64 * 1024,
814 .bufferImageGranularity = 64, /* A cache line */
815 .sparseAddressSpaceSize = 0,
816 .maxBoundDescriptorSets = MAX_SETS,
817 .maxPerStageDescriptorSamplers = max_samplers,
818 .maxPerStageDescriptorUniformBuffers = 64,
819 .maxPerStageDescriptorStorageBuffers = 64,
820 .maxPerStageDescriptorSampledImages = max_samplers,
821 .maxPerStageDescriptorStorageImages = 64,
822 .maxPerStageDescriptorInputAttachments = 64,
823 .maxPerStageResources = 250,
824 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
825 .maxDescriptorSetUniformBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorUniformBuffers */
826 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
827 .maxDescriptorSetStorageBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorStorageBuffers */
828 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
829 .maxDescriptorSetSampledImages = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSampledImages */
830 .maxDescriptorSetStorageImages = 6 * 64, /* number of stages * maxPerStageDescriptorStorageImages */
831 .maxDescriptorSetInputAttachments = 256,
832 .maxVertexInputAttributes = MAX_VBS,
833 .maxVertexInputBindings = MAX_VBS,
834 .maxVertexInputAttributeOffset = 2047,
835 .maxVertexInputBindingStride = 2048,
836 .maxVertexOutputComponents = 128,
837 .maxTessellationGenerationLevel = 64,
838 .maxTessellationPatchSize = 32,
839 .maxTessellationControlPerVertexInputComponents = 128,
840 .maxTessellationControlPerVertexOutputComponents = 128,
841 .maxTessellationControlPerPatchOutputComponents = 128,
842 .maxTessellationControlTotalOutputComponents = 2048,
843 .maxTessellationEvaluationInputComponents = 128,
844 .maxTessellationEvaluationOutputComponents = 128,
845 .maxGeometryShaderInvocations = 32,
846 .maxGeometryInputComponents = 64,
847 .maxGeometryOutputComponents = 128,
848 .maxGeometryOutputVertices = 256,
849 .maxGeometryTotalOutputComponents = 1024,
850 .maxFragmentInputComponents = 128,
851 .maxFragmentOutputAttachments = 8,
852 .maxFragmentDualSrcAttachments = 1,
853 .maxFragmentCombinedOutputResources = 8,
854 .maxComputeSharedMemorySize = 32768,
855 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
856 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
857 .maxComputeWorkGroupSize = {
858 16 * devinfo->max_cs_threads,
859 16 * devinfo->max_cs_threads,
860 16 * devinfo->max_cs_threads,
861 },
862 .subPixelPrecisionBits = 4 /* FIXME */,
863 .subTexelPrecisionBits = 4 /* FIXME */,
864 .mipmapPrecisionBits = 4 /* FIXME */,
865 .maxDrawIndexedIndexValue = UINT32_MAX,
866 .maxDrawIndirectCount = UINT32_MAX,
867 .maxSamplerLodBias = 16,
868 .maxSamplerAnisotropy = 16,
869 .maxViewports = MAX_VIEWPORTS,
870 .maxViewportDimensions = { (1 << 14), (1 << 14) },
871 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
872 .viewportSubPixelBits = 13, /* We take a float? */
873 .minMemoryMapAlignment = 4096, /* A page */
874 .minTexelBufferOffsetAlignment = 1,
875 /* We need 16 for UBO block reads to work and 32 for push UBOs */
876 .minUniformBufferOffsetAlignment = 32,
877 .minStorageBufferOffsetAlignment = 4,
878 .minTexelOffset = -8,
879 .maxTexelOffset = 7,
880 .minTexelGatherOffset = -32,
881 .maxTexelGatherOffset = 31,
882 .minInterpolationOffset = -0.5,
883 .maxInterpolationOffset = 0.4375,
884 .subPixelInterpolationOffsetBits = 4,
885 .maxFramebufferWidth = (1 << 14),
886 .maxFramebufferHeight = (1 << 14),
887 .maxFramebufferLayers = (1 << 11),
888 .framebufferColorSampleCounts = sample_counts,
889 .framebufferDepthSampleCounts = sample_counts,
890 .framebufferStencilSampleCounts = sample_counts,
891 .framebufferNoAttachmentsSampleCounts = sample_counts,
892 .maxColorAttachments = MAX_RTS,
893 .sampledImageColorSampleCounts = sample_counts,
894 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
895 .sampledImageDepthSampleCounts = sample_counts,
896 .sampledImageStencilSampleCounts = sample_counts,
897 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
898 .maxSampleMaskWords = 1,
899 .timestampComputeAndGraphics = false,
900 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
901 .maxClipDistances = 8,
902 .maxCullDistances = 8,
903 .maxCombinedClipAndCullDistances = 8,
904 .discreteQueuePriorities = 1,
905 .pointSizeRange = { 0.125, 255.875 },
906 .lineWidthRange = { 0.0, 7.9921875 },
907 .pointSizeGranularity = (1.0 / 8.0),
908 .lineWidthGranularity = (1.0 / 128.0),
909 .strictLines = false, /* FINISHME */
910 .standardSampleLocations = true,
911 .optimalBufferCopyOffsetAlignment = 128,
912 .optimalBufferCopyRowPitchAlignment = 128,
913 .nonCoherentAtomSize = 64,
914 };
915
916 *pProperties = (VkPhysicalDeviceProperties) {
917 .apiVersion = anv_physical_device_api_version(pdevice),
918 .driverVersion = vk_get_driver_version(),
919 .vendorID = 0x8086,
920 .deviceID = pdevice->chipset_id,
921 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
922 .limits = limits,
923 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
924 };
925
926 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
927 "%s", pdevice->name);
928 memcpy(pProperties->pipelineCacheUUID,
929 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
930 }
931
932 void anv_GetPhysicalDeviceProperties2KHR(
933 VkPhysicalDevice physicalDevice,
934 VkPhysicalDeviceProperties2KHR* pProperties)
935 {
936 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
937
938 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
939
940 vk_foreach_struct(ext, pProperties->pNext) {
941 switch (ext->sType) {
942 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
943 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
944 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
945
946 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
947 break;
948 }
949
950 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR: {
951 VkPhysicalDeviceIDPropertiesKHR *id_props =
952 (VkPhysicalDeviceIDPropertiesKHR *)ext;
953 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
954 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
955 /* The LUID is for Windows. */
956 id_props->deviceLUIDValid = false;
957 break;
958 }
959
960 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX: {
961 VkPhysicalDeviceMultiviewPropertiesKHX *properties =
962 (VkPhysicalDeviceMultiviewPropertiesKHX *)ext;
963 properties->maxMultiviewViewCount = 16;
964 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
965 break;
966 }
967
968 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KHR: {
969 VkPhysicalDevicePointClippingPropertiesKHR *properties =
970 (VkPhysicalDevicePointClippingPropertiesKHR *) ext;
971 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES_KHR;
972 anv_finishme("Implement pop-free point clipping");
973 break;
974 }
975
976 default:
977 anv_debug_ignored_stype(ext->sType);
978 break;
979 }
980 }
981 }
982
983 /* We support exactly one queue family. */
984 static const VkQueueFamilyProperties
985 anv_queue_family_properties = {
986 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
987 VK_QUEUE_COMPUTE_BIT |
988 VK_QUEUE_TRANSFER_BIT,
989 .queueCount = 1,
990 .timestampValidBits = 36, /* XXX: Real value here */
991 .minImageTransferGranularity = { 1, 1, 1 },
992 };
993
994 void anv_GetPhysicalDeviceQueueFamilyProperties(
995 VkPhysicalDevice physicalDevice,
996 uint32_t* pCount,
997 VkQueueFamilyProperties* pQueueFamilyProperties)
998 {
999 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
1000
1001 vk_outarray_append(&out, p) {
1002 *p = anv_queue_family_properties;
1003 }
1004 }
1005
1006 void anv_GetPhysicalDeviceQueueFamilyProperties2KHR(
1007 VkPhysicalDevice physicalDevice,
1008 uint32_t* pQueueFamilyPropertyCount,
1009 VkQueueFamilyProperties2KHR* pQueueFamilyProperties)
1010 {
1011
1012 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1013
1014 vk_outarray_append(&out, p) {
1015 p->queueFamilyProperties = anv_queue_family_properties;
1016
1017 vk_foreach_struct(s, p->pNext) {
1018 anv_debug_ignored_stype(s->sType);
1019 }
1020 }
1021 }
1022
1023 void anv_GetPhysicalDeviceMemoryProperties(
1024 VkPhysicalDevice physicalDevice,
1025 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1026 {
1027 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1028
1029 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1030 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1031 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1032 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1033 .heapIndex = physical_device->memory.types[i].heapIndex,
1034 };
1035 }
1036
1037 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1038 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1039 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1040 .size = physical_device->memory.heaps[i].size,
1041 .flags = physical_device->memory.heaps[i].flags,
1042 };
1043 }
1044 }
1045
1046 void anv_GetPhysicalDeviceMemoryProperties2KHR(
1047 VkPhysicalDevice physicalDevice,
1048 VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties)
1049 {
1050 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1051 &pMemoryProperties->memoryProperties);
1052
1053 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1054 switch (ext->sType) {
1055 default:
1056 anv_debug_ignored_stype(ext->sType);
1057 break;
1058 }
1059 }
1060 }
1061
1062 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1063 VkInstance instance,
1064 const char* pName)
1065 {
1066 return anv_lookup_entrypoint(NULL, pName);
1067 }
1068
1069 /* With version 1+ of the loader interface the ICD should expose
1070 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1071 */
1072 PUBLIC
1073 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1074 VkInstance instance,
1075 const char* pName);
1076
1077 PUBLIC
1078 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1079 VkInstance instance,
1080 const char* pName)
1081 {
1082 return anv_GetInstanceProcAddr(instance, pName);
1083 }
1084
1085 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1086 VkDevice _device,
1087 const char* pName)
1088 {
1089 ANV_FROM_HANDLE(anv_device, device, _device);
1090 return anv_lookup_entrypoint(&device->info, pName);
1091 }
1092
1093 VkResult
1094 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
1095 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
1096 const VkAllocationCallbacks* pAllocator,
1097 VkDebugReportCallbackEXT* pCallback)
1098 {
1099 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1100 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
1101 pCreateInfo, pAllocator, &instance->alloc,
1102 pCallback);
1103 }
1104
1105 void
1106 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
1107 VkDebugReportCallbackEXT _callback,
1108 const VkAllocationCallbacks* pAllocator)
1109 {
1110 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1111 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
1112 _callback, pAllocator, &instance->alloc);
1113 }
1114
1115 void
1116 anv_DebugReportMessageEXT(VkInstance _instance,
1117 VkDebugReportFlagsEXT flags,
1118 VkDebugReportObjectTypeEXT objectType,
1119 uint64_t object,
1120 size_t location,
1121 int32_t messageCode,
1122 const char* pLayerPrefix,
1123 const char* pMessage)
1124 {
1125 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1126 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
1127 object, location, messageCode, pLayerPrefix, pMessage);
1128 }
1129
1130 static void
1131 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1132 {
1133 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1134 queue->device = device;
1135 queue->pool = &device->surface_state_pool;
1136 }
1137
1138 static void
1139 anv_queue_finish(struct anv_queue *queue)
1140 {
1141 }
1142
1143 static struct anv_state
1144 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1145 {
1146 struct anv_state state;
1147
1148 state = anv_state_pool_alloc(pool, size, align);
1149 memcpy(state.map, p, size);
1150
1151 anv_state_flush(pool->block_pool.device, state);
1152
1153 return state;
1154 }
1155
1156 struct gen8_border_color {
1157 union {
1158 float float32[4];
1159 uint32_t uint32[4];
1160 };
1161 /* Pad out to 64 bytes */
1162 uint32_t _pad[12];
1163 };
1164
1165 static void
1166 anv_device_init_border_colors(struct anv_device *device)
1167 {
1168 static const struct gen8_border_color border_colors[] = {
1169 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1170 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1171 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1172 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1173 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1174 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1175 };
1176
1177 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1178 sizeof(border_colors), 64,
1179 border_colors);
1180 }
1181
1182 static void
1183 anv_device_init_trivial_batch(struct anv_device *device)
1184 {
1185 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1186
1187 if (device->instance->physicalDevice.has_exec_async)
1188 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1189
1190 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1191 0, 4096, 0);
1192
1193 struct anv_batch batch = {
1194 .start = map,
1195 .next = map,
1196 .end = map + 4096,
1197 };
1198
1199 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1200 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1201
1202 if (!device->info.has_llc)
1203 gen_clflush_range(map, batch.next - map);
1204
1205 anv_gem_munmap(map, device->trivial_batch_bo.size);
1206 }
1207
1208 VkResult anv_CreateDevice(
1209 VkPhysicalDevice physicalDevice,
1210 const VkDeviceCreateInfo* pCreateInfo,
1211 const VkAllocationCallbacks* pAllocator,
1212 VkDevice* pDevice)
1213 {
1214 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1215 VkResult result;
1216 struct anv_device *device;
1217
1218 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1219
1220 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1221 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
1222 if (!anv_physical_device_extension_supported(physical_device, ext_name))
1223 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1224 }
1225
1226 /* Check enabled features */
1227 if (pCreateInfo->pEnabledFeatures) {
1228 VkPhysicalDeviceFeatures supported_features;
1229 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1230 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1231 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1232 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1233 for (uint32_t i = 0; i < num_features; i++) {
1234 if (enabled_feature[i] && !supported_feature[i])
1235 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1236 }
1237 }
1238
1239 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1240 sizeof(*device), 8,
1241 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1242 if (!device)
1243 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1244
1245 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1246 device->instance = physical_device->instance;
1247 device->chipset_id = physical_device->chipset_id;
1248 device->lost = false;
1249
1250 if (pAllocator)
1251 device->alloc = *pAllocator;
1252 else
1253 device->alloc = physical_device->instance->alloc;
1254
1255 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1256 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1257 if (device->fd == -1) {
1258 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1259 goto fail_device;
1260 }
1261
1262 device->context_id = anv_gem_create_context(device);
1263 if (device->context_id == -1) {
1264 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1265 goto fail_fd;
1266 }
1267
1268 device->info = physical_device->info;
1269 device->isl_dev = physical_device->isl_dev;
1270
1271 /* On Broadwell and later, we can use batch chaining to more efficiently
1272 * implement growing command buffers. Prior to Haswell, the kernel
1273 * command parser gets in the way and we have to fall back to growing
1274 * the batch.
1275 */
1276 device->can_chain_batches = device->info.gen >= 8;
1277
1278 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1279 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1280
1281 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1282 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1283 goto fail_context_id;
1284 }
1285
1286 pthread_condattr_t condattr;
1287 if (pthread_condattr_init(&condattr) != 0) {
1288 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1289 goto fail_mutex;
1290 }
1291 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1292 pthread_condattr_destroy(&condattr);
1293 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1294 goto fail_mutex;
1295 }
1296 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1297 pthread_condattr_destroy(&condattr);
1298 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1299 goto fail_mutex;
1300 }
1301 pthread_condattr_destroy(&condattr);
1302
1303 uint64_t bo_flags =
1304 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
1305 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1306 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0);
1307
1308 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
1309
1310 result = anv_bo_cache_init(&device->bo_cache);
1311 if (result != VK_SUCCESS)
1312 goto fail_batch_bo_pool;
1313
1314 /* For the state pools we explicitly disable 48bit. */
1315 bo_flags = (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1316 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0);
1317
1318 result = anv_state_pool_init(&device->dynamic_state_pool, device, 16384,
1319 bo_flags);
1320 if (result != VK_SUCCESS)
1321 goto fail_bo_cache;
1322
1323 result = anv_state_pool_init(&device->instruction_state_pool, device, 16384,
1324 bo_flags);
1325 if (result != VK_SUCCESS)
1326 goto fail_dynamic_state_pool;
1327
1328 result = anv_state_pool_init(&device->surface_state_pool, device, 4096,
1329 bo_flags);
1330 if (result != VK_SUCCESS)
1331 goto fail_instruction_state_pool;
1332
1333 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1334 if (result != VK_SUCCESS)
1335 goto fail_surface_state_pool;
1336
1337 anv_device_init_trivial_batch(device);
1338
1339 anv_scratch_pool_init(device, &device->scratch_pool);
1340
1341 anv_queue_init(device, &device->queue);
1342
1343 switch (device->info.gen) {
1344 case 7:
1345 if (!device->info.is_haswell)
1346 result = gen7_init_device_state(device);
1347 else
1348 result = gen75_init_device_state(device);
1349 break;
1350 case 8:
1351 result = gen8_init_device_state(device);
1352 break;
1353 case 9:
1354 result = gen9_init_device_state(device);
1355 break;
1356 case 10:
1357 result = gen10_init_device_state(device);
1358 break;
1359 default:
1360 /* Shouldn't get here as we don't create physical devices for any other
1361 * gens. */
1362 unreachable("unhandled gen");
1363 }
1364 if (result != VK_SUCCESS)
1365 goto fail_workaround_bo;
1366
1367 anv_device_init_blorp(device);
1368
1369 anv_device_init_border_colors(device);
1370
1371 *pDevice = anv_device_to_handle(device);
1372
1373 return VK_SUCCESS;
1374
1375 fail_workaround_bo:
1376 anv_queue_finish(&device->queue);
1377 anv_scratch_pool_finish(device, &device->scratch_pool);
1378 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1379 anv_gem_close(device, device->workaround_bo.gem_handle);
1380 fail_surface_state_pool:
1381 anv_state_pool_finish(&device->surface_state_pool);
1382 fail_instruction_state_pool:
1383 anv_state_pool_finish(&device->instruction_state_pool);
1384 fail_dynamic_state_pool:
1385 anv_state_pool_finish(&device->dynamic_state_pool);
1386 fail_bo_cache:
1387 anv_bo_cache_finish(&device->bo_cache);
1388 fail_batch_bo_pool:
1389 anv_bo_pool_finish(&device->batch_bo_pool);
1390 pthread_cond_destroy(&device->queue_submit);
1391 fail_mutex:
1392 pthread_mutex_destroy(&device->mutex);
1393 fail_context_id:
1394 anv_gem_destroy_context(device, device->context_id);
1395 fail_fd:
1396 close(device->fd);
1397 fail_device:
1398 vk_free(&device->alloc, device);
1399
1400 return result;
1401 }
1402
1403 void anv_DestroyDevice(
1404 VkDevice _device,
1405 const VkAllocationCallbacks* pAllocator)
1406 {
1407 ANV_FROM_HANDLE(anv_device, device, _device);
1408
1409 if (!device)
1410 return;
1411
1412 anv_device_finish_blorp(device);
1413
1414 anv_queue_finish(&device->queue);
1415
1416 #ifdef HAVE_VALGRIND
1417 /* We only need to free these to prevent valgrind errors. The backing
1418 * BO will go away in a couple of lines so we don't actually leak.
1419 */
1420 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1421 #endif
1422
1423 anv_scratch_pool_finish(device, &device->scratch_pool);
1424
1425 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1426 anv_gem_close(device, device->workaround_bo.gem_handle);
1427
1428 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
1429
1430 anv_state_pool_finish(&device->surface_state_pool);
1431 anv_state_pool_finish(&device->instruction_state_pool);
1432 anv_state_pool_finish(&device->dynamic_state_pool);
1433
1434 anv_bo_cache_finish(&device->bo_cache);
1435
1436 anv_bo_pool_finish(&device->batch_bo_pool);
1437
1438 pthread_cond_destroy(&device->queue_submit);
1439 pthread_mutex_destroy(&device->mutex);
1440
1441 anv_gem_destroy_context(device, device->context_id);
1442
1443 close(device->fd);
1444
1445 vk_free(&device->alloc, device);
1446 }
1447
1448 VkResult anv_EnumerateInstanceLayerProperties(
1449 uint32_t* pPropertyCount,
1450 VkLayerProperties* pProperties)
1451 {
1452 if (pProperties == NULL) {
1453 *pPropertyCount = 0;
1454 return VK_SUCCESS;
1455 }
1456
1457 /* None supported at this time */
1458 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1459 }
1460
1461 VkResult anv_EnumerateDeviceLayerProperties(
1462 VkPhysicalDevice physicalDevice,
1463 uint32_t* pPropertyCount,
1464 VkLayerProperties* pProperties)
1465 {
1466 if (pProperties == NULL) {
1467 *pPropertyCount = 0;
1468 return VK_SUCCESS;
1469 }
1470
1471 /* None supported at this time */
1472 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1473 }
1474
1475 void anv_GetDeviceQueue(
1476 VkDevice _device,
1477 uint32_t queueNodeIndex,
1478 uint32_t queueIndex,
1479 VkQueue* pQueue)
1480 {
1481 ANV_FROM_HANDLE(anv_device, device, _device);
1482
1483 assert(queueIndex == 0);
1484
1485 *pQueue = anv_queue_to_handle(&device->queue);
1486 }
1487
1488 VkResult
1489 anv_device_query_status(struct anv_device *device)
1490 {
1491 /* This isn't likely as most of the callers of this function already check
1492 * for it. However, it doesn't hurt to check and it potentially lets us
1493 * avoid an ioctl.
1494 */
1495 if (unlikely(device->lost))
1496 return VK_ERROR_DEVICE_LOST;
1497
1498 uint32_t active, pending;
1499 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
1500 if (ret == -1) {
1501 /* We don't know the real error. */
1502 device->lost = true;
1503 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1504 "get_reset_stats failed: %m");
1505 }
1506
1507 if (active) {
1508 device->lost = true;
1509 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1510 "GPU hung on one of our command buffers");
1511 } else if (pending) {
1512 device->lost = true;
1513 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1514 "GPU hung with commands in-flight");
1515 }
1516
1517 return VK_SUCCESS;
1518 }
1519
1520 VkResult
1521 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
1522 {
1523 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
1524 * Other usages of the BO (such as on different hardware) will not be
1525 * flagged as "busy" by this ioctl. Use with care.
1526 */
1527 int ret = anv_gem_busy(device, bo->gem_handle);
1528 if (ret == 1) {
1529 return VK_NOT_READY;
1530 } else if (ret == -1) {
1531 /* We don't know the real error. */
1532 device->lost = true;
1533 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1534 "gem wait failed: %m");
1535 }
1536
1537 /* Query for device status after the busy call. If the BO we're checking
1538 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
1539 * client because it clearly doesn't have valid data. Yes, this most
1540 * likely means an ioctl, but we just did an ioctl to query the busy status
1541 * so it's no great loss.
1542 */
1543 return anv_device_query_status(device);
1544 }
1545
1546 VkResult
1547 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1548 int64_t timeout)
1549 {
1550 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
1551 if (ret == -1 && errno == ETIME) {
1552 return VK_TIMEOUT;
1553 } else if (ret == -1) {
1554 /* We don't know the real error. */
1555 device->lost = true;
1556 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1557 "gem wait failed: %m");
1558 }
1559
1560 /* Query for device status after the wait. If the BO we're waiting on got
1561 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
1562 * because it clearly doesn't have valid data. Yes, this most likely means
1563 * an ioctl, but we just did an ioctl to wait so it's no great loss.
1564 */
1565 return anv_device_query_status(device);
1566 }
1567
1568 VkResult anv_DeviceWaitIdle(
1569 VkDevice _device)
1570 {
1571 ANV_FROM_HANDLE(anv_device, device, _device);
1572 if (unlikely(device->lost))
1573 return VK_ERROR_DEVICE_LOST;
1574
1575 struct anv_batch batch;
1576
1577 uint32_t cmds[8];
1578 batch.start = batch.next = cmds;
1579 batch.end = (void *) cmds + sizeof(cmds);
1580
1581 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1582 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1583
1584 return anv_device_submit_simple_batch(device, &batch);
1585 }
1586
1587 VkResult
1588 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1589 {
1590 uint32_t gem_handle = anv_gem_create(device, size);
1591 if (!gem_handle)
1592 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1593
1594 anv_bo_init(bo, gem_handle, size);
1595
1596 return VK_SUCCESS;
1597 }
1598
1599 VkResult anv_AllocateMemory(
1600 VkDevice _device,
1601 const VkMemoryAllocateInfo* pAllocateInfo,
1602 const VkAllocationCallbacks* pAllocator,
1603 VkDeviceMemory* pMem)
1604 {
1605 ANV_FROM_HANDLE(anv_device, device, _device);
1606 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1607 struct anv_device_memory *mem;
1608 VkResult result = VK_SUCCESS;
1609
1610 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1611
1612 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1613 assert(pAllocateInfo->allocationSize > 0);
1614
1615 /* The kernel relocation API has a limitation of a 32-bit delta value
1616 * applied to the address before it is written which, in spite of it being
1617 * unsigned, is treated as signed . Because of the way that this maps to
1618 * the Vulkan API, we cannot handle an offset into a buffer that does not
1619 * fit into a signed 32 bits. The only mechanism we have for dealing with
1620 * this at the moment is to limit all VkDeviceMemory objects to a maximum
1621 * of 2GB each. The Vulkan spec allows us to do this:
1622 *
1623 * "Some platforms may have a limit on the maximum size of a single
1624 * allocation. For example, certain systems may fail to create
1625 * allocations with a size greater than or equal to 4GB. Such a limit is
1626 * implementation-dependent, and if such a failure occurs then the error
1627 * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
1628 *
1629 * We don't use vk_error here because it's not an error so much as an
1630 * indication to the application that the allocation is too large.
1631 */
1632 if (pAllocateInfo->allocationSize > (1ull << 31))
1633 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1634
1635 /* FINISHME: Fail if allocation request exceeds heap size. */
1636
1637 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1638 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1639 if (mem == NULL)
1640 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1641
1642 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
1643 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
1644 mem->map = NULL;
1645 mem->map_size = 0;
1646
1647 const VkImportMemoryFdInfoKHR *fd_info =
1648 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
1649
1650 /* The Vulkan spec permits handleType to be 0, in which case the struct is
1651 * ignored.
1652 */
1653 if (fd_info && fd_info->handleType) {
1654 /* At the moment, we support only the below handle types. */
1655 assert(fd_info->handleType ==
1656 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR ||
1657 fd_info->handleType ==
1658 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1659
1660 result = anv_bo_cache_import(device, &device->bo_cache,
1661 fd_info->fd, &mem->bo);
1662 if (result != VK_SUCCESS)
1663 goto fail;
1664
1665 VkDeviceSize aligned_alloc_size =
1666 align_u64(pAllocateInfo->allocationSize, 4096);
1667
1668 /* For security purposes, we reject importing the bo if it's smaller
1669 * than the requested allocation size. This prevents a malicious client
1670 * from passing a buffer to a trusted client, lying about the size, and
1671 * telling the trusted client to try and texture from an image that goes
1672 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
1673 * in the trusted client. The trusted client can protect itself against
1674 * this sort of attack but only if it can trust the buffer size.
1675 */
1676 if (mem->bo->size < aligned_alloc_size) {
1677 result = vk_errorf(device->instance, device,
1678 VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR,
1679 "aligned allocationSize too large for "
1680 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR: "
1681 "%"PRIu64"B > %"PRIu64"B",
1682 aligned_alloc_size, mem->bo->size);
1683 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1684 goto fail;
1685 }
1686
1687 /* From the Vulkan spec:
1688 *
1689 * "Importing memory from a file descriptor transfers ownership of
1690 * the file descriptor from the application to the Vulkan
1691 * implementation. The application must not perform any operations on
1692 * the file descriptor after a successful import."
1693 *
1694 * If the import fails, we leave the file descriptor open.
1695 */
1696 close(fd_info->fd);
1697 } else {
1698 result = anv_bo_cache_alloc(device, &device->bo_cache,
1699 pAllocateInfo->allocationSize,
1700 &mem->bo);
1701 if (result != VK_SUCCESS)
1702 goto fail;
1703
1704 const VkMemoryDedicatedAllocateInfoKHR *dedicated_info =
1705 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
1706 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
1707 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
1708
1709 /* For images using modifiers, we require a dedicated allocation
1710 * and we set the BO tiling to match the tiling of the underlying
1711 * modifier. This is a bit unfortunate as this is completely
1712 * pointless for Vulkan. However, GL needs to be able to map things
1713 * so it needs the tiling to be set. The only way to do this in a
1714 * non-racy way is to set the tiling in the creator of the BO so that
1715 * makes it our job.
1716 *
1717 * One of these days, once the GL driver learns to not map things
1718 * through the GTT in random places, we can drop this and start
1719 * allowing multiple modified images in the same BO.
1720 */
1721 if (image->drm_format_mod != DRM_FORMAT_MOD_INVALID) {
1722 assert(isl_drm_modifier_get_info(image->drm_format_mod)->tiling ==
1723 image->planes[0].surface.isl.tiling);
1724 const uint32_t i915_tiling =
1725 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
1726 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
1727 image->planes[0].surface.isl.row_pitch,
1728 i915_tiling);
1729 if (ret) {
1730 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1731 return vk_errorf(device->instance, NULL,
1732 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1733 "failed to set BO tiling: %m");
1734 }
1735 }
1736 }
1737 }
1738
1739 assert(mem->type->heapIndex < pdevice->memory.heap_count);
1740 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
1741 mem->bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1742
1743 const struct wsi_memory_allocate_info *wsi_info =
1744 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
1745 if (wsi_info && wsi_info->implicit_sync) {
1746 /* We need to set the WRITE flag on window system buffers so that GEM
1747 * will know we're writing to them and synchronize uses on other rings
1748 * (eg if the display server uses the blitter ring).
1749 */
1750 mem->bo->flags |= EXEC_OBJECT_WRITE;
1751 } else if (pdevice->has_exec_async) {
1752 mem->bo->flags |= EXEC_OBJECT_ASYNC;
1753 }
1754
1755 *pMem = anv_device_memory_to_handle(mem);
1756
1757 return VK_SUCCESS;
1758
1759 fail:
1760 vk_free2(&device->alloc, pAllocator, mem);
1761
1762 return result;
1763 }
1764
1765 VkResult anv_GetMemoryFdKHR(
1766 VkDevice device_h,
1767 const VkMemoryGetFdInfoKHR* pGetFdInfo,
1768 int* pFd)
1769 {
1770 ANV_FROM_HANDLE(anv_device, dev, device_h);
1771 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
1772
1773 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
1774
1775 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR ||
1776 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1777
1778 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
1779 }
1780
1781 VkResult anv_GetMemoryFdPropertiesKHR(
1782 VkDevice _device,
1783 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
1784 int fd,
1785 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
1786 {
1787 ANV_FROM_HANDLE(anv_device, device, _device);
1788 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1789
1790 switch (handleType) {
1791 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
1792 /* dma-buf can be imported as any memory type */
1793 pMemoryFdProperties->memoryTypeBits =
1794 (1 << pdevice->memory.type_count) - 1;
1795 return VK_SUCCESS;
1796
1797 default:
1798 /* The valid usage section for this function says:
1799 *
1800 * "handleType must not be one of the handle types defined as
1801 * opaque."
1802 *
1803 * So opaque handle types fall into the default "unsupported" case.
1804 */
1805 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR);
1806 }
1807 }
1808
1809 void anv_FreeMemory(
1810 VkDevice _device,
1811 VkDeviceMemory _mem,
1812 const VkAllocationCallbacks* pAllocator)
1813 {
1814 ANV_FROM_HANDLE(anv_device, device, _device);
1815 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1816
1817 if (mem == NULL)
1818 return;
1819
1820 if (mem->map)
1821 anv_UnmapMemory(_device, _mem);
1822
1823 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1824
1825 vk_free2(&device->alloc, pAllocator, mem);
1826 }
1827
1828 VkResult anv_MapMemory(
1829 VkDevice _device,
1830 VkDeviceMemory _memory,
1831 VkDeviceSize offset,
1832 VkDeviceSize size,
1833 VkMemoryMapFlags flags,
1834 void** ppData)
1835 {
1836 ANV_FROM_HANDLE(anv_device, device, _device);
1837 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1838
1839 if (mem == NULL) {
1840 *ppData = NULL;
1841 return VK_SUCCESS;
1842 }
1843
1844 if (size == VK_WHOLE_SIZE)
1845 size = mem->bo->size - offset;
1846
1847 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1848 *
1849 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1850 * assert(size != 0);
1851 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1852 * equal to the size of the memory minus offset
1853 */
1854 assert(size > 0);
1855 assert(offset + size <= mem->bo->size);
1856
1857 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1858 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1859 * at a time is valid. We could just mmap up front and return an offset
1860 * pointer here, but that may exhaust virtual memory on 32 bit
1861 * userspace. */
1862
1863 uint32_t gem_flags = 0;
1864
1865 if (!device->info.has_llc &&
1866 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
1867 gem_flags |= I915_MMAP_WC;
1868
1869 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1870 uint64_t map_offset = offset & ~4095ull;
1871 assert(offset >= map_offset);
1872 uint64_t map_size = (offset + size) - map_offset;
1873
1874 /* Let's map whole pages */
1875 map_size = align_u64(map_size, 4096);
1876
1877 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
1878 map_offset, map_size, gem_flags);
1879 if (map == MAP_FAILED)
1880 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1881
1882 mem->map = map;
1883 mem->map_size = map_size;
1884
1885 *ppData = mem->map + (offset - map_offset);
1886
1887 return VK_SUCCESS;
1888 }
1889
1890 void anv_UnmapMemory(
1891 VkDevice _device,
1892 VkDeviceMemory _memory)
1893 {
1894 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1895
1896 if (mem == NULL)
1897 return;
1898
1899 anv_gem_munmap(mem->map, mem->map_size);
1900
1901 mem->map = NULL;
1902 mem->map_size = 0;
1903 }
1904
1905 static void
1906 clflush_mapped_ranges(struct anv_device *device,
1907 uint32_t count,
1908 const VkMappedMemoryRange *ranges)
1909 {
1910 for (uint32_t i = 0; i < count; i++) {
1911 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1912 if (ranges[i].offset >= mem->map_size)
1913 continue;
1914
1915 gen_clflush_range(mem->map + ranges[i].offset,
1916 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
1917 }
1918 }
1919
1920 VkResult anv_FlushMappedMemoryRanges(
1921 VkDevice _device,
1922 uint32_t memoryRangeCount,
1923 const VkMappedMemoryRange* pMemoryRanges)
1924 {
1925 ANV_FROM_HANDLE(anv_device, device, _device);
1926
1927 if (device->info.has_llc)
1928 return VK_SUCCESS;
1929
1930 /* Make sure the writes we're flushing have landed. */
1931 __builtin_ia32_mfence();
1932
1933 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1934
1935 return VK_SUCCESS;
1936 }
1937
1938 VkResult anv_InvalidateMappedMemoryRanges(
1939 VkDevice _device,
1940 uint32_t memoryRangeCount,
1941 const VkMappedMemoryRange* pMemoryRanges)
1942 {
1943 ANV_FROM_HANDLE(anv_device, device, _device);
1944
1945 if (device->info.has_llc)
1946 return VK_SUCCESS;
1947
1948 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1949
1950 /* Make sure no reads get moved up above the invalidate. */
1951 __builtin_ia32_mfence();
1952
1953 return VK_SUCCESS;
1954 }
1955
1956 void anv_GetBufferMemoryRequirements(
1957 VkDevice _device,
1958 VkBuffer _buffer,
1959 VkMemoryRequirements* pMemoryRequirements)
1960 {
1961 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1962 ANV_FROM_HANDLE(anv_device, device, _device);
1963 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1964
1965 /* The Vulkan spec (git aaed022) says:
1966 *
1967 * memoryTypeBits is a bitfield and contains one bit set for every
1968 * supported memory type for the resource. The bit `1<<i` is set if and
1969 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1970 * structure for the physical device is supported.
1971 */
1972 uint32_t memory_types = 0;
1973 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
1974 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
1975 if ((valid_usage & buffer->usage) == buffer->usage)
1976 memory_types |= (1u << i);
1977 }
1978
1979 /* Base alignment requirement of a cache line */
1980 uint32_t alignment = 16;
1981
1982 /* We need an alignment of 32 for pushing UBOs */
1983 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
1984 alignment = MAX2(alignment, 32);
1985
1986 pMemoryRequirements->size = buffer->size;
1987 pMemoryRequirements->alignment = alignment;
1988 pMemoryRequirements->memoryTypeBits = memory_types;
1989 }
1990
1991 void anv_GetBufferMemoryRequirements2KHR(
1992 VkDevice _device,
1993 const VkBufferMemoryRequirementsInfo2KHR* pInfo,
1994 VkMemoryRequirements2KHR* pMemoryRequirements)
1995 {
1996 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
1997 &pMemoryRequirements->memoryRequirements);
1998
1999 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2000 switch (ext->sType) {
2001 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
2002 VkMemoryDedicatedRequirementsKHR *requirements = (void *)ext;
2003 requirements->prefersDedicatedAllocation = VK_FALSE;
2004 requirements->requiresDedicatedAllocation = VK_FALSE;
2005 break;
2006 }
2007
2008 default:
2009 anv_debug_ignored_stype(ext->sType);
2010 break;
2011 }
2012 }
2013 }
2014
2015 void anv_GetImageMemoryRequirements(
2016 VkDevice _device,
2017 VkImage _image,
2018 VkMemoryRequirements* pMemoryRequirements)
2019 {
2020 ANV_FROM_HANDLE(anv_image, image, _image);
2021 ANV_FROM_HANDLE(anv_device, device, _device);
2022 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2023
2024 /* The Vulkan spec (git aaed022) says:
2025 *
2026 * memoryTypeBits is a bitfield and contains one bit set for every
2027 * supported memory type for the resource. The bit `1<<i` is set if and
2028 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2029 * structure for the physical device is supported.
2030 *
2031 * All types are currently supported for images.
2032 */
2033 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
2034
2035 pMemoryRequirements->size = image->size;
2036 pMemoryRequirements->alignment = image->alignment;
2037 pMemoryRequirements->memoryTypeBits = memory_types;
2038 }
2039
2040 void anv_GetImageMemoryRequirements2KHR(
2041 VkDevice _device,
2042 const VkImageMemoryRequirementsInfo2KHR* pInfo,
2043 VkMemoryRequirements2KHR* pMemoryRequirements)
2044 {
2045 ANV_FROM_HANDLE(anv_device, device, _device);
2046 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
2047
2048 anv_GetImageMemoryRequirements(_device, pInfo->image,
2049 &pMemoryRequirements->memoryRequirements);
2050
2051 vk_foreach_struct_const(ext, pInfo->pNext) {
2052 switch (ext->sType) {
2053 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO_KHR: {
2054 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2055 const VkImagePlaneMemoryRequirementsInfoKHR *plane_reqs =
2056 (const VkImagePlaneMemoryRequirementsInfoKHR *) ext;
2057 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
2058 plane_reqs->planeAspect);
2059
2060 assert(image->planes[plane].offset == 0);
2061
2062 /* The Vulkan spec (git aaed022) says:
2063 *
2064 * memoryTypeBits is a bitfield and contains one bit set for every
2065 * supported memory type for the resource. The bit `1<<i` is set
2066 * if and only if the memory type `i` in the
2067 * VkPhysicalDeviceMemoryProperties structure for the physical
2068 * device is supported.
2069 *
2070 * All types are currently supported for images.
2071 */
2072 pMemoryRequirements->memoryRequirements.memoryTypeBits =
2073 (1ull << pdevice->memory.type_count) - 1;
2074
2075 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
2076 pMemoryRequirements->memoryRequirements.alignment =
2077 image->planes[plane].alignment;
2078 break;
2079 }
2080
2081 default:
2082 anv_debug_ignored_stype(ext->sType);
2083 break;
2084 }
2085 }
2086
2087 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2088 switch (ext->sType) {
2089 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
2090 VkMemoryDedicatedRequirementsKHR *requirements = (void *)ext;
2091 if (image->drm_format_mod != DRM_FORMAT_MOD_INVALID) {
2092 /* Require a dedicated allocation for images with modifiers.
2093 *
2094 * See also anv_AllocateMemory.
2095 */
2096 requirements->prefersDedicatedAllocation = VK_TRUE;
2097 requirements->requiresDedicatedAllocation = VK_TRUE;
2098 } else {
2099 requirements->prefersDedicatedAllocation = VK_FALSE;
2100 requirements->requiresDedicatedAllocation = VK_FALSE;
2101 }
2102 break;
2103 }
2104
2105 default:
2106 anv_debug_ignored_stype(ext->sType);
2107 break;
2108 }
2109 }
2110 }
2111
2112 void anv_GetImageSparseMemoryRequirements(
2113 VkDevice device,
2114 VkImage image,
2115 uint32_t* pSparseMemoryRequirementCount,
2116 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2117 {
2118 *pSparseMemoryRequirementCount = 0;
2119 }
2120
2121 void anv_GetImageSparseMemoryRequirements2KHR(
2122 VkDevice device,
2123 const VkImageSparseMemoryRequirementsInfo2KHR* pInfo,
2124 uint32_t* pSparseMemoryRequirementCount,
2125 VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements)
2126 {
2127 *pSparseMemoryRequirementCount = 0;
2128 }
2129
2130 void anv_GetDeviceMemoryCommitment(
2131 VkDevice device,
2132 VkDeviceMemory memory,
2133 VkDeviceSize* pCommittedMemoryInBytes)
2134 {
2135 *pCommittedMemoryInBytes = 0;
2136 }
2137
2138 static void
2139 anv_bind_buffer_memory(const VkBindBufferMemoryInfoKHR *pBindInfo)
2140 {
2141 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
2142 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
2143
2144 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR);
2145
2146 if (mem) {
2147 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
2148 buffer->bo = mem->bo;
2149 buffer->offset = pBindInfo->memoryOffset;
2150 } else {
2151 buffer->bo = NULL;
2152 buffer->offset = 0;
2153 }
2154 }
2155
2156 VkResult anv_BindBufferMemory(
2157 VkDevice device,
2158 VkBuffer buffer,
2159 VkDeviceMemory memory,
2160 VkDeviceSize memoryOffset)
2161 {
2162 anv_bind_buffer_memory(
2163 &(VkBindBufferMemoryInfoKHR) {
2164 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR,
2165 .buffer = buffer,
2166 .memory = memory,
2167 .memoryOffset = memoryOffset,
2168 });
2169
2170 return VK_SUCCESS;
2171 }
2172
2173 VkResult anv_BindBufferMemory2KHR(
2174 VkDevice device,
2175 uint32_t bindInfoCount,
2176 const VkBindBufferMemoryInfoKHR* pBindInfos)
2177 {
2178 for (uint32_t i = 0; i < bindInfoCount; i++)
2179 anv_bind_buffer_memory(&pBindInfos[i]);
2180
2181 return VK_SUCCESS;
2182 }
2183
2184 VkResult anv_QueueBindSparse(
2185 VkQueue _queue,
2186 uint32_t bindInfoCount,
2187 const VkBindSparseInfo* pBindInfo,
2188 VkFence fence)
2189 {
2190 ANV_FROM_HANDLE(anv_queue, queue, _queue);
2191 if (unlikely(queue->device->lost))
2192 return VK_ERROR_DEVICE_LOST;
2193
2194 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2195 }
2196
2197 // Event functions
2198
2199 VkResult anv_CreateEvent(
2200 VkDevice _device,
2201 const VkEventCreateInfo* pCreateInfo,
2202 const VkAllocationCallbacks* pAllocator,
2203 VkEvent* pEvent)
2204 {
2205 ANV_FROM_HANDLE(anv_device, device, _device);
2206 struct anv_state state;
2207 struct anv_event *event;
2208
2209 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2210
2211 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2212 sizeof(*event), 8);
2213 event = state.map;
2214 event->state = state;
2215 event->semaphore = VK_EVENT_RESET;
2216
2217 if (!device->info.has_llc) {
2218 /* Make sure the writes we're flushing have landed. */
2219 __builtin_ia32_mfence();
2220 __builtin_ia32_clflush(event);
2221 }
2222
2223 *pEvent = anv_event_to_handle(event);
2224
2225 return VK_SUCCESS;
2226 }
2227
2228 void anv_DestroyEvent(
2229 VkDevice _device,
2230 VkEvent _event,
2231 const VkAllocationCallbacks* pAllocator)
2232 {
2233 ANV_FROM_HANDLE(anv_device, device, _device);
2234 ANV_FROM_HANDLE(anv_event, event, _event);
2235
2236 if (!event)
2237 return;
2238
2239 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2240 }
2241
2242 VkResult anv_GetEventStatus(
2243 VkDevice _device,
2244 VkEvent _event)
2245 {
2246 ANV_FROM_HANDLE(anv_device, device, _device);
2247 ANV_FROM_HANDLE(anv_event, event, _event);
2248
2249 if (unlikely(device->lost))
2250 return VK_ERROR_DEVICE_LOST;
2251
2252 if (!device->info.has_llc) {
2253 /* Invalidate read cache before reading event written by GPU. */
2254 __builtin_ia32_clflush(event);
2255 __builtin_ia32_mfence();
2256
2257 }
2258
2259 return event->semaphore;
2260 }
2261
2262 VkResult anv_SetEvent(
2263 VkDevice _device,
2264 VkEvent _event)
2265 {
2266 ANV_FROM_HANDLE(anv_device, device, _device);
2267 ANV_FROM_HANDLE(anv_event, event, _event);
2268
2269 event->semaphore = VK_EVENT_SET;
2270
2271 if (!device->info.has_llc) {
2272 /* Make sure the writes we're flushing have landed. */
2273 __builtin_ia32_mfence();
2274 __builtin_ia32_clflush(event);
2275 }
2276
2277 return VK_SUCCESS;
2278 }
2279
2280 VkResult anv_ResetEvent(
2281 VkDevice _device,
2282 VkEvent _event)
2283 {
2284 ANV_FROM_HANDLE(anv_device, device, _device);
2285 ANV_FROM_HANDLE(anv_event, event, _event);
2286
2287 event->semaphore = VK_EVENT_RESET;
2288
2289 if (!device->info.has_llc) {
2290 /* Make sure the writes we're flushing have landed. */
2291 __builtin_ia32_mfence();
2292 __builtin_ia32_clflush(event);
2293 }
2294
2295 return VK_SUCCESS;
2296 }
2297
2298 // Buffer functions
2299
2300 VkResult anv_CreateBuffer(
2301 VkDevice _device,
2302 const VkBufferCreateInfo* pCreateInfo,
2303 const VkAllocationCallbacks* pAllocator,
2304 VkBuffer* pBuffer)
2305 {
2306 ANV_FROM_HANDLE(anv_device, device, _device);
2307 struct anv_buffer *buffer;
2308
2309 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2310
2311 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2312 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2313 if (buffer == NULL)
2314 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2315
2316 buffer->size = pCreateInfo->size;
2317 buffer->usage = pCreateInfo->usage;
2318 buffer->bo = NULL;
2319 buffer->offset = 0;
2320
2321 *pBuffer = anv_buffer_to_handle(buffer);
2322
2323 return VK_SUCCESS;
2324 }
2325
2326 void anv_DestroyBuffer(
2327 VkDevice _device,
2328 VkBuffer _buffer,
2329 const VkAllocationCallbacks* pAllocator)
2330 {
2331 ANV_FROM_HANDLE(anv_device, device, _device);
2332 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2333
2334 if (!buffer)
2335 return;
2336
2337 vk_free2(&device->alloc, pAllocator, buffer);
2338 }
2339
2340 void
2341 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2342 enum isl_format format,
2343 uint32_t offset, uint32_t range, uint32_t stride)
2344 {
2345 isl_buffer_fill_state(&device->isl_dev, state.map,
2346 .address = offset,
2347 .mocs = device->default_mocs,
2348 .size = range,
2349 .format = format,
2350 .stride = stride);
2351
2352 anv_state_flush(device, state);
2353 }
2354
2355 void anv_DestroySampler(
2356 VkDevice _device,
2357 VkSampler _sampler,
2358 const VkAllocationCallbacks* pAllocator)
2359 {
2360 ANV_FROM_HANDLE(anv_device, device, _device);
2361 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2362
2363 if (!sampler)
2364 return;
2365
2366 vk_free2(&device->alloc, pAllocator, sampler);
2367 }
2368
2369 VkResult anv_CreateFramebuffer(
2370 VkDevice _device,
2371 const VkFramebufferCreateInfo* pCreateInfo,
2372 const VkAllocationCallbacks* pAllocator,
2373 VkFramebuffer* pFramebuffer)
2374 {
2375 ANV_FROM_HANDLE(anv_device, device, _device);
2376 struct anv_framebuffer *framebuffer;
2377
2378 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2379
2380 size_t size = sizeof(*framebuffer) +
2381 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2382 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2383 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2384 if (framebuffer == NULL)
2385 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2386
2387 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2388 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2389 VkImageView _iview = pCreateInfo->pAttachments[i];
2390 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2391 }
2392
2393 framebuffer->width = pCreateInfo->width;
2394 framebuffer->height = pCreateInfo->height;
2395 framebuffer->layers = pCreateInfo->layers;
2396
2397 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2398
2399 return VK_SUCCESS;
2400 }
2401
2402 void anv_DestroyFramebuffer(
2403 VkDevice _device,
2404 VkFramebuffer _fb,
2405 const VkAllocationCallbacks* pAllocator)
2406 {
2407 ANV_FROM_HANDLE(anv_device, device, _device);
2408 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2409
2410 if (!fb)
2411 return;
2412
2413 vk_free2(&device->alloc, pAllocator, fb);
2414 }
2415
2416 /* vk_icd.h does not declare this function, so we declare it here to
2417 * suppress Wmissing-prototypes.
2418 */
2419 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2420 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2421
2422 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2423 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2424 {
2425 /* For the full details on loader interface versioning, see
2426 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2427 * What follows is a condensed summary, to help you navigate the large and
2428 * confusing official doc.
2429 *
2430 * - Loader interface v0 is incompatible with later versions. We don't
2431 * support it.
2432 *
2433 * - In loader interface v1:
2434 * - The first ICD entrypoint called by the loader is
2435 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2436 * entrypoint.
2437 * - The ICD must statically expose no other Vulkan symbol unless it is
2438 * linked with -Bsymbolic.
2439 * - Each dispatchable Vulkan handle created by the ICD must be
2440 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2441 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2442 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2443 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2444 * such loader-managed surfaces.
2445 *
2446 * - Loader interface v2 differs from v1 in:
2447 * - The first ICD entrypoint called by the loader is
2448 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2449 * statically expose this entrypoint.
2450 *
2451 * - Loader interface v3 differs from v2 in:
2452 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2453 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2454 * because the loader no longer does so.
2455 */
2456 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2457 return VK_SUCCESS;
2458 }