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