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