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