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