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