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