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