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