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