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