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