anv: If softpin is supported, use it with the hiz clear value bo
[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 vk_free(&instance->alloc, (char *)instance->app_info.app_name);
686 vk_free(&instance->alloc, (char *)instance->app_info.engine_name);
687
688 VG(VALGRIND_DESTROY_MEMPOOL(instance));
689
690 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
691
692 _mesa_locale_fini();
693
694 vk_free(&instance->alloc, instance);
695 }
696
697 static VkResult
698 anv_enumerate_devices(struct anv_instance *instance)
699 {
700 /* TODO: Check for more devices ? */
701 drmDevicePtr devices[8];
702 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
703 int max_devices;
704
705 instance->physicalDeviceCount = 0;
706
707 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
708 if (max_devices < 1)
709 return VK_ERROR_INCOMPATIBLE_DRIVER;
710
711 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
712 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
713 devices[i]->bustype == DRM_BUS_PCI &&
714 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
715
716 result = anv_physical_device_init(&instance->physicalDevice,
717 instance,
718 devices[i]->nodes[DRM_NODE_PRIMARY],
719 devices[i]->nodes[DRM_NODE_RENDER]);
720 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
721 break;
722 }
723 }
724 drmFreeDevices(devices, max_devices);
725
726 if (result == VK_SUCCESS)
727 instance->physicalDeviceCount = 1;
728
729 return result;
730 }
731
732 static VkResult
733 anv_instance_ensure_physical_device(struct anv_instance *instance)
734 {
735 if (instance->physicalDeviceCount < 0) {
736 VkResult result = anv_enumerate_devices(instance);
737 if (result != VK_SUCCESS &&
738 result != VK_ERROR_INCOMPATIBLE_DRIVER)
739 return result;
740 }
741
742 return VK_SUCCESS;
743 }
744
745 VkResult anv_EnumeratePhysicalDevices(
746 VkInstance _instance,
747 uint32_t* pPhysicalDeviceCount,
748 VkPhysicalDevice* pPhysicalDevices)
749 {
750 ANV_FROM_HANDLE(anv_instance, instance, _instance);
751 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
752
753 VkResult result = anv_instance_ensure_physical_device(instance);
754 if (result != VK_SUCCESS)
755 return result;
756
757 if (instance->physicalDeviceCount == 0)
758 return VK_SUCCESS;
759
760 assert(instance->physicalDeviceCount == 1);
761 vk_outarray_append(&out, i) {
762 *i = anv_physical_device_to_handle(&instance->physicalDevice);
763 }
764
765 return vk_outarray_status(&out);
766 }
767
768 VkResult anv_EnumeratePhysicalDeviceGroups(
769 VkInstance _instance,
770 uint32_t* pPhysicalDeviceGroupCount,
771 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
772 {
773 ANV_FROM_HANDLE(anv_instance, instance, _instance);
774 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
775 pPhysicalDeviceGroupCount);
776
777 VkResult result = anv_instance_ensure_physical_device(instance);
778 if (result != VK_SUCCESS)
779 return result;
780
781 if (instance->physicalDeviceCount == 0)
782 return VK_SUCCESS;
783
784 assert(instance->physicalDeviceCount == 1);
785
786 vk_outarray_append(&out, p) {
787 p->physicalDeviceCount = 1;
788 memset(p->physicalDevices, 0, sizeof(p->physicalDevices));
789 p->physicalDevices[0] =
790 anv_physical_device_to_handle(&instance->physicalDevice);
791 p->subsetAllocation = VK_FALSE;
792
793 vk_foreach_struct(ext, p->pNext)
794 anv_debug_ignored_stype(ext->sType);
795 }
796
797 return vk_outarray_status(&out);
798 }
799
800 void anv_GetPhysicalDeviceFeatures(
801 VkPhysicalDevice physicalDevice,
802 VkPhysicalDeviceFeatures* pFeatures)
803 {
804 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
805
806 *pFeatures = (VkPhysicalDeviceFeatures) {
807 .robustBufferAccess = true,
808 .fullDrawIndexUint32 = true,
809 .imageCubeArray = true,
810 .independentBlend = true,
811 .geometryShader = true,
812 .tessellationShader = true,
813 .sampleRateShading = true,
814 .dualSrcBlend = true,
815 .logicOp = true,
816 .multiDrawIndirect = true,
817 .drawIndirectFirstInstance = true,
818 .depthClamp = true,
819 .depthBiasClamp = true,
820 .fillModeNonSolid = true,
821 .depthBounds = false,
822 .wideLines = true,
823 .largePoints = true,
824 .alphaToOne = true,
825 .multiViewport = true,
826 .samplerAnisotropy = true,
827 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
828 pdevice->info.is_baytrail,
829 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
830 .textureCompressionBC = true,
831 .occlusionQueryPrecise = true,
832 .pipelineStatisticsQuery = true,
833 .fragmentStoresAndAtomics = true,
834 .shaderTessellationAndGeometryPointSize = true,
835 .shaderImageGatherExtended = true,
836 .shaderStorageImageExtendedFormats = true,
837 .shaderStorageImageMultisample = false,
838 .shaderStorageImageReadWithoutFormat = false,
839 .shaderStorageImageWriteWithoutFormat = true,
840 .shaderUniformBufferArrayDynamicIndexing = true,
841 .shaderSampledImageArrayDynamicIndexing = true,
842 .shaderStorageBufferArrayDynamicIndexing = true,
843 .shaderStorageImageArrayDynamicIndexing = true,
844 .shaderClipDistance = true,
845 .shaderCullDistance = true,
846 .shaderFloat64 = pdevice->info.gen >= 8 &&
847 pdevice->info.has_64bit_types,
848 .shaderInt64 = pdevice->info.gen >= 8 &&
849 pdevice->info.has_64bit_types,
850 .shaderInt16 = pdevice->info.gen >= 8,
851 .shaderResourceMinLod = false,
852 .variableMultisampleRate = true,
853 .inheritedQueries = true,
854 };
855
856 /* We can't do image stores in vec4 shaders */
857 pFeatures->vertexPipelineStoresAndAtomics =
858 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
859 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
860
861 struct anv_app_info *app_info = &pdevice->instance->app_info;
862
863 /* The new DOOM and Wolfenstein games require depthBounds without
864 * checking for it. They seem to run fine without it so just claim it's
865 * there and accept the consequences.
866 */
867 if (app_info->engine_name && strcmp(app_info->engine_name, "idTech") == 0)
868 pFeatures->depthBounds = true;
869 }
870
871 void anv_GetPhysicalDeviceFeatures2(
872 VkPhysicalDevice physicalDevice,
873 VkPhysicalDeviceFeatures2* pFeatures)
874 {
875 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
876
877 vk_foreach_struct(ext, pFeatures->pNext) {
878 switch (ext->sType) {
879 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
880 VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
881 features->protectedMemory = VK_FALSE;
882 break;
883 }
884
885 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
886 VkPhysicalDeviceMultiviewFeatures *features =
887 (VkPhysicalDeviceMultiviewFeatures *)ext;
888 features->multiview = true;
889 features->multiviewGeometryShader = true;
890 features->multiviewTessellationShader = true;
891 break;
892 }
893
894 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES: {
895 VkPhysicalDeviceVariablePointerFeatures *features = (void *)ext;
896 features->variablePointersStorageBuffer = true;
897 features->variablePointers = true;
898 break;
899 }
900
901 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
902 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
903 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
904 features->samplerYcbcrConversion = true;
905 break;
906 }
907
908 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES: {
909 VkPhysicalDeviceShaderDrawParameterFeatures *features = (void *)ext;
910 features->shaderDrawParameters = true;
911 break;
912 }
913
914 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR: {
915 VkPhysicalDevice16BitStorageFeaturesKHR *features =
916 (VkPhysicalDevice16BitStorageFeaturesKHR *)ext;
917 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
918
919 features->storageBuffer16BitAccess = pdevice->info.gen >= 8;
920 features->uniformAndStorageBuffer16BitAccess = pdevice->info.gen >= 8;
921 features->storagePushConstant16 = pdevice->info.gen >= 8;
922 features->storageInputOutput16 = false;
923 break;
924 }
925
926 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
927 VkPhysicalDevice8BitStorageFeaturesKHR *features =
928 (VkPhysicalDevice8BitStorageFeaturesKHR *)ext;
929 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
930
931 features->storageBuffer8BitAccess = pdevice->info.gen >= 8;
932 features->uniformAndStorageBuffer8BitAccess = pdevice->info.gen >= 8;
933 features->storagePushConstant8 = pdevice->info.gen >= 8;
934 break;
935 }
936
937 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
938 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
939 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
940 features->vertexAttributeInstanceRateDivisor = VK_TRUE;
941 features->vertexAttributeInstanceRateZeroDivisor = VK_TRUE;
942 break;
943 }
944
945 default:
946 anv_debug_ignored_stype(ext->sType);
947 break;
948 }
949 }
950 }
951
952 void anv_GetPhysicalDeviceProperties(
953 VkPhysicalDevice physicalDevice,
954 VkPhysicalDeviceProperties* pProperties)
955 {
956 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
957 const struct gen_device_info *devinfo = &pdevice->info;
958
959 /* See assertions made when programming the buffer surface state. */
960 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
961 (1ul << 30) : (1ul << 27);
962
963 const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
964 128 : 16;
965
966 VkSampleCountFlags sample_counts =
967 isl_device_get_sample_counts(&pdevice->isl_dev);
968
969 VkPhysicalDeviceLimits limits = {
970 .maxImageDimension1D = (1 << 14),
971 .maxImageDimension2D = (1 << 14),
972 .maxImageDimension3D = (1 << 11),
973 .maxImageDimensionCube = (1 << 14),
974 .maxImageArrayLayers = (1 << 11),
975 .maxTexelBufferElements = 128 * 1024 * 1024,
976 .maxUniformBufferRange = (1ul << 27),
977 .maxStorageBufferRange = max_raw_buffer_sz,
978 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
979 .maxMemoryAllocationCount = UINT32_MAX,
980 .maxSamplerAllocationCount = 64 * 1024,
981 .bufferImageGranularity = 64, /* A cache line */
982 .sparseAddressSpaceSize = 0,
983 .maxBoundDescriptorSets = MAX_SETS,
984 .maxPerStageDescriptorSamplers = max_samplers,
985 .maxPerStageDescriptorUniformBuffers = 64,
986 .maxPerStageDescriptorStorageBuffers = 64,
987 .maxPerStageDescriptorSampledImages = max_samplers,
988 .maxPerStageDescriptorStorageImages = 64,
989 .maxPerStageDescriptorInputAttachments = 64,
990 .maxPerStageResources = 250,
991 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
992 .maxDescriptorSetUniformBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorUniformBuffers */
993 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
994 .maxDescriptorSetStorageBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorStorageBuffers */
995 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
996 .maxDescriptorSetSampledImages = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSampledImages */
997 .maxDescriptorSetStorageImages = 6 * 64, /* number of stages * maxPerStageDescriptorStorageImages */
998 .maxDescriptorSetInputAttachments = 256,
999 .maxVertexInputAttributes = MAX_VBS,
1000 .maxVertexInputBindings = MAX_VBS,
1001 .maxVertexInputAttributeOffset = 2047,
1002 .maxVertexInputBindingStride = 2048,
1003 .maxVertexOutputComponents = 128,
1004 .maxTessellationGenerationLevel = 64,
1005 .maxTessellationPatchSize = 32,
1006 .maxTessellationControlPerVertexInputComponents = 128,
1007 .maxTessellationControlPerVertexOutputComponents = 128,
1008 .maxTessellationControlPerPatchOutputComponents = 128,
1009 .maxTessellationControlTotalOutputComponents = 2048,
1010 .maxTessellationEvaluationInputComponents = 128,
1011 .maxTessellationEvaluationOutputComponents = 128,
1012 .maxGeometryShaderInvocations = 32,
1013 .maxGeometryInputComponents = 64,
1014 .maxGeometryOutputComponents = 128,
1015 .maxGeometryOutputVertices = 256,
1016 .maxGeometryTotalOutputComponents = 1024,
1017 .maxFragmentInputComponents = 112, /* 128 components - (POS, PSIZ, CLIP_DIST0, CLIP_DIST1) */
1018 .maxFragmentOutputAttachments = 8,
1019 .maxFragmentDualSrcAttachments = 1,
1020 .maxFragmentCombinedOutputResources = 8,
1021 .maxComputeSharedMemorySize = 32768,
1022 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1023 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
1024 .maxComputeWorkGroupSize = {
1025 16 * devinfo->max_cs_threads,
1026 16 * devinfo->max_cs_threads,
1027 16 * devinfo->max_cs_threads,
1028 },
1029 .subPixelPrecisionBits = 4 /* FIXME */,
1030 .subTexelPrecisionBits = 4 /* FIXME */,
1031 .mipmapPrecisionBits = 4 /* FIXME */,
1032 .maxDrawIndexedIndexValue = UINT32_MAX,
1033 .maxDrawIndirectCount = UINT32_MAX,
1034 .maxSamplerLodBias = 16,
1035 .maxSamplerAnisotropy = 16,
1036 .maxViewports = MAX_VIEWPORTS,
1037 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1038 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1039 .viewportSubPixelBits = 13, /* We take a float? */
1040 .minMemoryMapAlignment = 4096, /* A page */
1041 .minTexelBufferOffsetAlignment = 1,
1042 /* We need 16 for UBO block reads to work and 32 for push UBOs */
1043 .minUniformBufferOffsetAlignment = 32,
1044 .minStorageBufferOffsetAlignment = 4,
1045 .minTexelOffset = -8,
1046 .maxTexelOffset = 7,
1047 .minTexelGatherOffset = -32,
1048 .maxTexelGatherOffset = 31,
1049 .minInterpolationOffset = -0.5,
1050 .maxInterpolationOffset = 0.4375,
1051 .subPixelInterpolationOffsetBits = 4,
1052 .maxFramebufferWidth = (1 << 14),
1053 .maxFramebufferHeight = (1 << 14),
1054 .maxFramebufferLayers = (1 << 11),
1055 .framebufferColorSampleCounts = sample_counts,
1056 .framebufferDepthSampleCounts = sample_counts,
1057 .framebufferStencilSampleCounts = sample_counts,
1058 .framebufferNoAttachmentsSampleCounts = sample_counts,
1059 .maxColorAttachments = MAX_RTS,
1060 .sampledImageColorSampleCounts = sample_counts,
1061 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1062 .sampledImageDepthSampleCounts = sample_counts,
1063 .sampledImageStencilSampleCounts = sample_counts,
1064 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1065 .maxSampleMaskWords = 1,
1066 .timestampComputeAndGraphics = false,
1067 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
1068 .maxClipDistances = 8,
1069 .maxCullDistances = 8,
1070 .maxCombinedClipAndCullDistances = 8,
1071 .discreteQueuePriorities = 1,
1072 .pointSizeRange = { 0.125, 255.875 },
1073 .lineWidthRange = { 0.0, 7.9921875 },
1074 .pointSizeGranularity = (1.0 / 8.0),
1075 .lineWidthGranularity = (1.0 / 128.0),
1076 .strictLines = false, /* FINISHME */
1077 .standardSampleLocations = true,
1078 .optimalBufferCopyOffsetAlignment = 128,
1079 .optimalBufferCopyRowPitchAlignment = 128,
1080 .nonCoherentAtomSize = 64,
1081 };
1082
1083 *pProperties = (VkPhysicalDeviceProperties) {
1084 .apiVersion = anv_physical_device_api_version(pdevice),
1085 .driverVersion = vk_get_driver_version(),
1086 .vendorID = 0x8086,
1087 .deviceID = pdevice->chipset_id,
1088 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1089 .limits = limits,
1090 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
1091 };
1092
1093 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
1094 "%s", pdevice->name);
1095 memcpy(pProperties->pipelineCacheUUID,
1096 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
1097 }
1098
1099 void anv_GetPhysicalDeviceProperties2(
1100 VkPhysicalDevice physicalDevice,
1101 VkPhysicalDeviceProperties2* pProperties)
1102 {
1103 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1104
1105 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1106
1107 vk_foreach_struct(ext, pProperties->pNext) {
1108 switch (ext->sType) {
1109 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1110 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1111 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1112
1113 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1114 break;
1115 }
1116
1117 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1118 VkPhysicalDeviceIDProperties *id_props =
1119 (VkPhysicalDeviceIDProperties *)ext;
1120 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1121 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1122 /* The LUID is for Windows. */
1123 id_props->deviceLUIDValid = false;
1124 break;
1125 }
1126
1127 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1128 VkPhysicalDeviceMaintenance3Properties *props =
1129 (VkPhysicalDeviceMaintenance3Properties *)ext;
1130 /* This value doesn't matter for us today as our per-stage
1131 * descriptors are the real limit.
1132 */
1133 props->maxPerSetDescriptors = 1024;
1134 props->maxMemoryAllocationSize = MAX_MEMORY_ALLOCATION_SIZE;
1135 break;
1136 }
1137
1138 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1139 VkPhysicalDeviceMultiviewProperties *properties =
1140 (VkPhysicalDeviceMultiviewProperties *)ext;
1141 properties->maxMultiviewViewCount = 16;
1142 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
1143 break;
1144 }
1145
1146 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1147 VkPhysicalDevicePointClippingProperties *properties =
1148 (VkPhysicalDevicePointClippingProperties *) ext;
1149 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1150 anv_finishme("Implement pop-free point clipping");
1151 break;
1152 }
1153
1154 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
1155 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
1156 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
1157 properties->filterMinmaxImageComponentMapping = pdevice->info.gen >= 9;
1158 properties->filterMinmaxSingleComponentFormats = true;
1159 break;
1160 }
1161
1162 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1163 VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
1164
1165 properties->subgroupSize = BRW_SUBGROUP_SIZE;
1166
1167 VkShaderStageFlags scalar_stages = 0;
1168 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1169 if (pdevice->compiler->scalar_stage[stage])
1170 scalar_stages |= mesa_to_vk_shader_stage(stage);
1171 }
1172 properties->supportedStages = scalar_stages;
1173
1174 properties->supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1175 VK_SUBGROUP_FEATURE_VOTE_BIT |
1176 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1177 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1178 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1179 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1180 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1181 VK_SUBGROUP_FEATURE_QUAD_BIT;
1182 properties->quadOperationsInAllStages = VK_TRUE;
1183 break;
1184 }
1185
1186 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1187 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
1188 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1189 /* We have to restrict this a bit for multiview */
1190 props->maxVertexAttribDivisor = UINT32_MAX / 16;
1191 break;
1192 }
1193
1194 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1195 VkPhysicalDeviceProtectedMemoryProperties *props =
1196 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1197 props->protectedNoFault = false;
1198 break;
1199 }
1200
1201 default:
1202 anv_debug_ignored_stype(ext->sType);
1203 break;
1204 }
1205 }
1206 }
1207
1208 /* We support exactly one queue family. */
1209 static const VkQueueFamilyProperties
1210 anv_queue_family_properties = {
1211 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1212 VK_QUEUE_COMPUTE_BIT |
1213 VK_QUEUE_TRANSFER_BIT,
1214 .queueCount = 1,
1215 .timestampValidBits = 36, /* XXX: Real value here */
1216 .minImageTransferGranularity = { 1, 1, 1 },
1217 };
1218
1219 void anv_GetPhysicalDeviceQueueFamilyProperties(
1220 VkPhysicalDevice physicalDevice,
1221 uint32_t* pCount,
1222 VkQueueFamilyProperties* pQueueFamilyProperties)
1223 {
1224 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
1225
1226 vk_outarray_append(&out, p) {
1227 *p = anv_queue_family_properties;
1228 }
1229 }
1230
1231 void anv_GetPhysicalDeviceQueueFamilyProperties2(
1232 VkPhysicalDevice physicalDevice,
1233 uint32_t* pQueueFamilyPropertyCount,
1234 VkQueueFamilyProperties2* pQueueFamilyProperties)
1235 {
1236
1237 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1238
1239 vk_outarray_append(&out, p) {
1240 p->queueFamilyProperties = anv_queue_family_properties;
1241
1242 vk_foreach_struct(s, p->pNext) {
1243 anv_debug_ignored_stype(s->sType);
1244 }
1245 }
1246 }
1247
1248 void anv_GetPhysicalDeviceMemoryProperties(
1249 VkPhysicalDevice physicalDevice,
1250 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1251 {
1252 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1253
1254 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1255 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1256 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1257 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1258 .heapIndex = physical_device->memory.types[i].heapIndex,
1259 };
1260 }
1261
1262 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1263 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1264 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1265 .size = physical_device->memory.heaps[i].size,
1266 .flags = physical_device->memory.heaps[i].flags,
1267 };
1268 }
1269 }
1270
1271 void anv_GetPhysicalDeviceMemoryProperties2(
1272 VkPhysicalDevice physicalDevice,
1273 VkPhysicalDeviceMemoryProperties2* pMemoryProperties)
1274 {
1275 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1276 &pMemoryProperties->memoryProperties);
1277
1278 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1279 switch (ext->sType) {
1280 default:
1281 anv_debug_ignored_stype(ext->sType);
1282 break;
1283 }
1284 }
1285 }
1286
1287 void
1288 anv_GetDeviceGroupPeerMemoryFeatures(
1289 VkDevice device,
1290 uint32_t heapIndex,
1291 uint32_t localDeviceIndex,
1292 uint32_t remoteDeviceIndex,
1293 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
1294 {
1295 assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
1296 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
1297 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
1298 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
1299 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
1300 }
1301
1302 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1303 VkInstance _instance,
1304 const char* pName)
1305 {
1306 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1307
1308 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
1309 * when we have to return valid function pointers, NULL, or it's left
1310 * undefined. See the table for exact details.
1311 */
1312 if (pName == NULL)
1313 return NULL;
1314
1315 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
1316 if (strcmp(pName, "vk" #entrypoint) == 0) \
1317 return (PFN_vkVoidFunction)anv_##entrypoint
1318
1319 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
1320 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
1321 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
1322 LOOKUP_ANV_ENTRYPOINT(CreateInstance);
1323
1324 #undef LOOKUP_ANV_ENTRYPOINT
1325
1326 if (instance == NULL)
1327 return NULL;
1328
1329 int idx = anv_get_entrypoint_index(pName);
1330 if (idx < 0)
1331 return NULL;
1332
1333 return instance->dispatch.entrypoints[idx];
1334 }
1335
1336 /* With version 1+ of the loader interface the ICD should expose
1337 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1338 */
1339 PUBLIC
1340 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1341 VkInstance instance,
1342 const char* pName);
1343
1344 PUBLIC
1345 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1346 VkInstance instance,
1347 const char* pName)
1348 {
1349 return anv_GetInstanceProcAddr(instance, pName);
1350 }
1351
1352 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1353 VkDevice _device,
1354 const char* pName)
1355 {
1356 ANV_FROM_HANDLE(anv_device, device, _device);
1357
1358 if (!device || !pName)
1359 return NULL;
1360
1361 int idx = anv_get_entrypoint_index(pName);
1362 if (idx < 0)
1363 return NULL;
1364
1365 return device->dispatch.entrypoints[idx];
1366 }
1367
1368 VkResult
1369 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
1370 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
1371 const VkAllocationCallbacks* pAllocator,
1372 VkDebugReportCallbackEXT* pCallback)
1373 {
1374 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1375 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
1376 pCreateInfo, pAllocator, &instance->alloc,
1377 pCallback);
1378 }
1379
1380 void
1381 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
1382 VkDebugReportCallbackEXT _callback,
1383 const VkAllocationCallbacks* pAllocator)
1384 {
1385 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1386 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
1387 _callback, pAllocator, &instance->alloc);
1388 }
1389
1390 void
1391 anv_DebugReportMessageEXT(VkInstance _instance,
1392 VkDebugReportFlagsEXT flags,
1393 VkDebugReportObjectTypeEXT objectType,
1394 uint64_t object,
1395 size_t location,
1396 int32_t messageCode,
1397 const char* pLayerPrefix,
1398 const char* pMessage)
1399 {
1400 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1401 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
1402 object, location, messageCode, pLayerPrefix, pMessage);
1403 }
1404
1405 static void
1406 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1407 {
1408 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1409 queue->device = device;
1410 queue->flags = 0;
1411 }
1412
1413 static void
1414 anv_queue_finish(struct anv_queue *queue)
1415 {
1416 }
1417
1418 static struct anv_state
1419 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1420 {
1421 struct anv_state state;
1422
1423 state = anv_state_pool_alloc(pool, size, align);
1424 memcpy(state.map, p, size);
1425
1426 anv_state_flush(pool->block_pool.device, state);
1427
1428 return state;
1429 }
1430
1431 struct gen8_border_color {
1432 union {
1433 float float32[4];
1434 uint32_t uint32[4];
1435 };
1436 /* Pad out to 64 bytes */
1437 uint32_t _pad[12];
1438 };
1439
1440 static void
1441 anv_device_init_border_colors(struct anv_device *device)
1442 {
1443 static const struct gen8_border_color border_colors[] = {
1444 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1445 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1446 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1447 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1448 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1449 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1450 };
1451
1452 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1453 sizeof(border_colors), 64,
1454 border_colors);
1455 }
1456
1457 static void
1458 anv_device_init_trivial_batch(struct anv_device *device)
1459 {
1460 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1461
1462 if (device->instance->physicalDevice.has_exec_async)
1463 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1464
1465 if (device->instance->physicalDevice.use_softpin)
1466 device->trivial_batch_bo.flags |= EXEC_OBJECT_PINNED;
1467
1468 anv_vma_alloc(device, &device->trivial_batch_bo);
1469
1470 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1471 0, 4096, 0);
1472
1473 struct anv_batch batch = {
1474 .start = map,
1475 .next = map,
1476 .end = map + 4096,
1477 };
1478
1479 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1480 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1481
1482 if (!device->info.has_llc)
1483 gen_clflush_range(map, batch.next - map);
1484
1485 anv_gem_munmap(map, device->trivial_batch_bo.size);
1486 }
1487
1488 VkResult anv_EnumerateDeviceExtensionProperties(
1489 VkPhysicalDevice physicalDevice,
1490 const char* pLayerName,
1491 uint32_t* pPropertyCount,
1492 VkExtensionProperties* pProperties)
1493 {
1494 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
1495 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1496
1497 for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
1498 if (device->supported_extensions.extensions[i]) {
1499 vk_outarray_append(&out, prop) {
1500 *prop = anv_device_extensions[i];
1501 }
1502 }
1503 }
1504
1505 return vk_outarray_status(&out);
1506 }
1507
1508 static void
1509 anv_device_init_dispatch(struct anv_device *device)
1510 {
1511 const struct anv_dispatch_table *genX_table;
1512 switch (device->info.gen) {
1513 case 11:
1514 genX_table = &gen11_dispatch_table;
1515 break;
1516 case 10:
1517 genX_table = &gen10_dispatch_table;
1518 break;
1519 case 9:
1520 genX_table = &gen9_dispatch_table;
1521 break;
1522 case 8:
1523 genX_table = &gen8_dispatch_table;
1524 break;
1525 case 7:
1526 if (device->info.is_haswell)
1527 genX_table = &gen75_dispatch_table;
1528 else
1529 genX_table = &gen7_dispatch_table;
1530 break;
1531 default:
1532 unreachable("unsupported gen\n");
1533 }
1534
1535 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
1536 /* Vulkan requires that entrypoints for extensions which have not been
1537 * enabled must not be advertised.
1538 */
1539 if (!anv_entrypoint_is_enabled(i, device->instance->app_info.api_version,
1540 &device->instance->enabled_extensions,
1541 &device->enabled_extensions)) {
1542 device->dispatch.entrypoints[i] = NULL;
1543 } else if (genX_table->entrypoints[i]) {
1544 device->dispatch.entrypoints[i] = genX_table->entrypoints[i];
1545 } else {
1546 device->dispatch.entrypoints[i] = anv_dispatch_table.entrypoints[i];
1547 }
1548 }
1549 }
1550
1551 static int
1552 vk_priority_to_gen(int priority)
1553 {
1554 switch (priority) {
1555 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1556 return GEN_CONTEXT_LOW_PRIORITY;
1557 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1558 return GEN_CONTEXT_MEDIUM_PRIORITY;
1559 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1560 return GEN_CONTEXT_HIGH_PRIORITY;
1561 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1562 return GEN_CONTEXT_REALTIME_PRIORITY;
1563 default:
1564 unreachable("Invalid priority");
1565 }
1566 }
1567
1568 static void
1569 anv_device_init_hiz_clear_value_bo(struct anv_device *device)
1570 {
1571 anv_bo_init_new(&device->hiz_clear_bo, device, 4096);
1572
1573 if (device->instance->physicalDevice.has_exec_async)
1574 device->hiz_clear_bo.flags |= EXEC_OBJECT_ASYNC;
1575
1576 if (device->instance->physicalDevice.use_softpin)
1577 device->hiz_clear_bo.flags |= EXEC_OBJECT_PINNED;
1578
1579 anv_vma_alloc(device, &device->hiz_clear_bo);
1580
1581 uint32_t *map = anv_gem_mmap(device, device->hiz_clear_bo.gem_handle,
1582 0, 4096, 0);
1583
1584 union isl_color_value hiz_clear = { .u32 = { 0, } };
1585 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
1586
1587 memcpy(map, hiz_clear.u32, sizeof(hiz_clear.u32));
1588 anv_gem_munmap(map, device->hiz_clear_bo.size);
1589 }
1590
1591 VkResult anv_CreateDevice(
1592 VkPhysicalDevice physicalDevice,
1593 const VkDeviceCreateInfo* pCreateInfo,
1594 const VkAllocationCallbacks* pAllocator,
1595 VkDevice* pDevice)
1596 {
1597 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1598 VkResult result;
1599 struct anv_device *device;
1600
1601 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1602
1603 struct anv_device_extension_table enabled_extensions = { };
1604 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1605 int idx;
1606 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
1607 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1608 anv_device_extensions[idx].extensionName) == 0)
1609 break;
1610 }
1611
1612 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
1613 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1614
1615 if (!physical_device->supported_extensions.extensions[idx])
1616 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1617
1618 enabled_extensions.extensions[idx] = true;
1619 }
1620
1621 /* Check enabled features */
1622 if (pCreateInfo->pEnabledFeatures) {
1623 VkPhysicalDeviceFeatures supported_features;
1624 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1625 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1626 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1627 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1628 for (uint32_t i = 0; i < num_features; i++) {
1629 if (enabled_feature[i] && !supported_feature[i])
1630 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1631 }
1632 }
1633
1634 /* Check requested queues and fail if we are requested to create any
1635 * queues with flags we don't support.
1636 */
1637 assert(pCreateInfo->queueCreateInfoCount > 0);
1638 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1639 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
1640 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
1641 }
1642
1643 /* Check if client specified queue priority. */
1644 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
1645 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
1646 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1647
1648 VkQueueGlobalPriorityEXT priority =
1649 queue_priority ? queue_priority->globalPriority :
1650 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
1651
1652 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1653 sizeof(*device), 8,
1654 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1655 if (!device)
1656 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1657
1658 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1659 device->instance = physical_device->instance;
1660 device->chipset_id = physical_device->chipset_id;
1661 device->no_hw = physical_device->no_hw;
1662 device->lost = false;
1663
1664 if (pAllocator)
1665 device->alloc = *pAllocator;
1666 else
1667 device->alloc = physical_device->instance->alloc;
1668
1669 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1670 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1671 if (device->fd == -1) {
1672 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1673 goto fail_device;
1674 }
1675
1676 device->context_id = anv_gem_create_context(device);
1677 if (device->context_id == -1) {
1678 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1679 goto fail_fd;
1680 }
1681
1682 if (physical_device->use_softpin) {
1683 if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
1684 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1685 goto fail_fd;
1686 }
1687
1688 /* keep the page with address zero out of the allocator */
1689 util_vma_heap_init(&device->vma_lo, LOW_HEAP_MIN_ADDRESS, LOW_HEAP_SIZE);
1690 device->vma_lo_available =
1691 physical_device->memory.heaps[physical_device->memory.heap_count - 1].size;
1692
1693 /* Leave the last 4GiB out of the high vma range, so that no state base
1694 * address + size can overflow 48 bits. For more information see the
1695 * comment about Wa32bitGeneralStateOffset in anv_allocator.c
1696 */
1697 util_vma_heap_init(&device->vma_hi, HIGH_HEAP_MIN_ADDRESS,
1698 HIGH_HEAP_SIZE);
1699 device->vma_hi_available = physical_device->memory.heap_count == 1 ? 0 :
1700 physical_device->memory.heaps[0].size;
1701 }
1702
1703 /* As per spec, the driver implementation may deny requests to acquire
1704 * a priority above the default priority (MEDIUM) if the caller does not
1705 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
1706 * is returned.
1707 */
1708 if (physical_device->has_context_priority) {
1709 int err = anv_gem_set_context_param(device->fd, device->context_id,
1710 I915_CONTEXT_PARAM_PRIORITY,
1711 vk_priority_to_gen(priority));
1712 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
1713 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
1714 goto fail_fd;
1715 }
1716 }
1717
1718 device->info = physical_device->info;
1719 device->isl_dev = physical_device->isl_dev;
1720
1721 /* On Broadwell and later, we can use batch chaining to more efficiently
1722 * implement growing command buffers. Prior to Haswell, the kernel
1723 * command parser gets in the way and we have to fall back to growing
1724 * the batch.
1725 */
1726 device->can_chain_batches = device->info.gen >= 8;
1727
1728 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1729 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1730 device->enabled_extensions = enabled_extensions;
1731
1732 anv_device_init_dispatch(device);
1733
1734 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1735 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1736 goto fail_context_id;
1737 }
1738
1739 pthread_condattr_t condattr;
1740 if (pthread_condattr_init(&condattr) != 0) {
1741 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1742 goto fail_mutex;
1743 }
1744 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1745 pthread_condattr_destroy(&condattr);
1746 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1747 goto fail_mutex;
1748 }
1749 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1750 pthread_condattr_destroy(&condattr);
1751 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1752 goto fail_mutex;
1753 }
1754 pthread_condattr_destroy(&condattr);
1755
1756 uint64_t bo_flags =
1757 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
1758 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1759 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0) |
1760 (physical_device->use_softpin ? EXEC_OBJECT_PINNED : 0);
1761
1762 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
1763
1764 result = anv_bo_cache_init(&device->bo_cache);
1765 if (result != VK_SUCCESS)
1766 goto fail_batch_bo_pool;
1767
1768 if (!physical_device->use_softpin)
1769 bo_flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1770
1771 result = anv_state_pool_init(&device->dynamic_state_pool, device,
1772 DYNAMIC_STATE_POOL_MIN_ADDRESS,
1773 16384,
1774 bo_flags);
1775 if (result != VK_SUCCESS)
1776 goto fail_bo_cache;
1777
1778 result = anv_state_pool_init(&device->instruction_state_pool, device,
1779 INSTRUCTION_STATE_POOL_MIN_ADDRESS,
1780 16384,
1781 bo_flags);
1782 if (result != VK_SUCCESS)
1783 goto fail_dynamic_state_pool;
1784
1785 result = anv_state_pool_init(&device->surface_state_pool, device,
1786 SURFACE_STATE_POOL_MIN_ADDRESS,
1787 4096,
1788 bo_flags);
1789 if (result != VK_SUCCESS)
1790 goto fail_instruction_state_pool;
1791
1792 if (physical_device->use_softpin) {
1793 result = anv_state_pool_init(&device->binding_table_pool, device,
1794 BINDING_TABLE_POOL_MIN_ADDRESS,
1795 4096,
1796 bo_flags);
1797 if (result != VK_SUCCESS)
1798 goto fail_surface_state_pool;
1799 }
1800
1801 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1802 if (result != VK_SUCCESS)
1803 goto fail_binding_table_pool;
1804
1805 if (physical_device->use_softpin)
1806 device->workaround_bo.flags |= EXEC_OBJECT_PINNED;
1807
1808 if (!anv_vma_alloc(device, &device->workaround_bo))
1809 goto fail_workaround_bo;
1810
1811 anv_device_init_trivial_batch(device);
1812
1813 if (device->info.gen >= 10)
1814 anv_device_init_hiz_clear_value_bo(device);
1815
1816 anv_scratch_pool_init(device, &device->scratch_pool);
1817
1818 anv_queue_init(device, &device->queue);
1819
1820 switch (device->info.gen) {
1821 case 7:
1822 if (!device->info.is_haswell)
1823 result = gen7_init_device_state(device);
1824 else
1825 result = gen75_init_device_state(device);
1826 break;
1827 case 8:
1828 result = gen8_init_device_state(device);
1829 break;
1830 case 9:
1831 result = gen9_init_device_state(device);
1832 break;
1833 case 10:
1834 result = gen10_init_device_state(device);
1835 break;
1836 case 11:
1837 result = gen11_init_device_state(device);
1838 break;
1839 default:
1840 /* Shouldn't get here as we don't create physical devices for any other
1841 * gens. */
1842 unreachable("unhandled gen");
1843 }
1844 if (result != VK_SUCCESS)
1845 goto fail_workaround_bo;
1846
1847 anv_pipeline_cache_init(&device->default_pipeline_cache, device, true);
1848
1849 anv_device_init_blorp(device);
1850
1851 anv_device_init_border_colors(device);
1852
1853 *pDevice = anv_device_to_handle(device);
1854
1855 return VK_SUCCESS;
1856
1857 fail_workaround_bo:
1858 anv_queue_finish(&device->queue);
1859 anv_scratch_pool_finish(device, &device->scratch_pool);
1860 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1861 anv_gem_close(device, device->workaround_bo.gem_handle);
1862 fail_binding_table_pool:
1863 if (physical_device->use_softpin)
1864 anv_state_pool_finish(&device->binding_table_pool);
1865 fail_surface_state_pool:
1866 anv_state_pool_finish(&device->surface_state_pool);
1867 fail_instruction_state_pool:
1868 anv_state_pool_finish(&device->instruction_state_pool);
1869 fail_dynamic_state_pool:
1870 anv_state_pool_finish(&device->dynamic_state_pool);
1871 fail_bo_cache:
1872 anv_bo_cache_finish(&device->bo_cache);
1873 fail_batch_bo_pool:
1874 anv_bo_pool_finish(&device->batch_bo_pool);
1875 pthread_cond_destroy(&device->queue_submit);
1876 fail_mutex:
1877 pthread_mutex_destroy(&device->mutex);
1878 fail_context_id:
1879 anv_gem_destroy_context(device, device->context_id);
1880 fail_fd:
1881 close(device->fd);
1882 fail_device:
1883 vk_free(&device->alloc, device);
1884
1885 return result;
1886 }
1887
1888 void anv_DestroyDevice(
1889 VkDevice _device,
1890 const VkAllocationCallbacks* pAllocator)
1891 {
1892 ANV_FROM_HANDLE(anv_device, device, _device);
1893 struct anv_physical_device *physical_device;
1894
1895 if (!device)
1896 return;
1897
1898 physical_device = &device->instance->physicalDevice;
1899
1900 anv_device_finish_blorp(device);
1901
1902 anv_pipeline_cache_finish(&device->default_pipeline_cache);
1903
1904 anv_queue_finish(&device->queue);
1905
1906 #ifdef HAVE_VALGRIND
1907 /* We only need to free these to prevent valgrind errors. The backing
1908 * BO will go away in a couple of lines so we don't actually leak.
1909 */
1910 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1911 #endif
1912
1913 anv_scratch_pool_finish(device, &device->scratch_pool);
1914
1915 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1916 anv_vma_free(device, &device->workaround_bo);
1917 anv_gem_close(device, device->workaround_bo.gem_handle);
1918
1919 anv_vma_free(device, &device->trivial_batch_bo);
1920 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
1921 if (device->info.gen >= 10)
1922 anv_gem_close(device, device->hiz_clear_bo.gem_handle);
1923
1924 if (physical_device->use_softpin)
1925 anv_state_pool_finish(&device->binding_table_pool);
1926 anv_state_pool_finish(&device->surface_state_pool);
1927 anv_state_pool_finish(&device->instruction_state_pool);
1928 anv_state_pool_finish(&device->dynamic_state_pool);
1929
1930 anv_bo_cache_finish(&device->bo_cache);
1931
1932 anv_bo_pool_finish(&device->batch_bo_pool);
1933
1934 pthread_cond_destroy(&device->queue_submit);
1935 pthread_mutex_destroy(&device->mutex);
1936
1937 anv_gem_destroy_context(device, device->context_id);
1938
1939 close(device->fd);
1940
1941 vk_free(&device->alloc, device);
1942 }
1943
1944 VkResult anv_EnumerateInstanceLayerProperties(
1945 uint32_t* pPropertyCount,
1946 VkLayerProperties* pProperties)
1947 {
1948 if (pProperties == NULL) {
1949 *pPropertyCount = 0;
1950 return VK_SUCCESS;
1951 }
1952
1953 /* None supported at this time */
1954 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1955 }
1956
1957 VkResult anv_EnumerateDeviceLayerProperties(
1958 VkPhysicalDevice physicalDevice,
1959 uint32_t* pPropertyCount,
1960 VkLayerProperties* pProperties)
1961 {
1962 if (pProperties == NULL) {
1963 *pPropertyCount = 0;
1964 return VK_SUCCESS;
1965 }
1966
1967 /* None supported at this time */
1968 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1969 }
1970
1971 void anv_GetDeviceQueue(
1972 VkDevice _device,
1973 uint32_t queueNodeIndex,
1974 uint32_t queueIndex,
1975 VkQueue* pQueue)
1976 {
1977 ANV_FROM_HANDLE(anv_device, device, _device);
1978
1979 assert(queueIndex == 0);
1980
1981 *pQueue = anv_queue_to_handle(&device->queue);
1982 }
1983
1984 void anv_GetDeviceQueue2(
1985 VkDevice _device,
1986 const VkDeviceQueueInfo2* pQueueInfo,
1987 VkQueue* pQueue)
1988 {
1989 ANV_FROM_HANDLE(anv_device, device, _device);
1990
1991 assert(pQueueInfo->queueIndex == 0);
1992
1993 if (pQueueInfo->flags == device->queue.flags)
1994 *pQueue = anv_queue_to_handle(&device->queue);
1995 else
1996 *pQueue = NULL;
1997 }
1998
1999 VkResult
2000 anv_device_query_status(struct anv_device *device)
2001 {
2002 /* This isn't likely as most of the callers of this function already check
2003 * for it. However, it doesn't hurt to check and it potentially lets us
2004 * avoid an ioctl.
2005 */
2006 if (unlikely(device->lost))
2007 return VK_ERROR_DEVICE_LOST;
2008
2009 uint32_t active, pending;
2010 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
2011 if (ret == -1) {
2012 /* We don't know the real error. */
2013 device->lost = true;
2014 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2015 "get_reset_stats failed: %m");
2016 }
2017
2018 if (active) {
2019 device->lost = true;
2020 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2021 "GPU hung on one of our command buffers");
2022 } else if (pending) {
2023 device->lost = true;
2024 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2025 "GPU hung with commands in-flight");
2026 }
2027
2028 return VK_SUCCESS;
2029 }
2030
2031 VkResult
2032 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
2033 {
2034 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
2035 * Other usages of the BO (such as on different hardware) will not be
2036 * flagged as "busy" by this ioctl. Use with care.
2037 */
2038 int ret = anv_gem_busy(device, bo->gem_handle);
2039 if (ret == 1) {
2040 return VK_NOT_READY;
2041 } else if (ret == -1) {
2042 /* We don't know the real error. */
2043 device->lost = true;
2044 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2045 "gem wait failed: %m");
2046 }
2047
2048 /* Query for device status after the busy call. If the BO we're checking
2049 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
2050 * client because it clearly doesn't have valid data. Yes, this most
2051 * likely means an ioctl, but we just did an ioctl to query the busy status
2052 * so it's no great loss.
2053 */
2054 return anv_device_query_status(device);
2055 }
2056
2057 VkResult
2058 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
2059 int64_t timeout)
2060 {
2061 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
2062 if (ret == -1 && errno == ETIME) {
2063 return VK_TIMEOUT;
2064 } else if (ret == -1) {
2065 /* We don't know the real error. */
2066 device->lost = true;
2067 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2068 "gem wait failed: %m");
2069 }
2070
2071 /* Query for device status after the wait. If the BO we're waiting on got
2072 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
2073 * because it clearly doesn't have valid data. Yes, this most likely means
2074 * an ioctl, but we just did an ioctl to wait so it's no great loss.
2075 */
2076 return anv_device_query_status(device);
2077 }
2078
2079 VkResult anv_DeviceWaitIdle(
2080 VkDevice _device)
2081 {
2082 ANV_FROM_HANDLE(anv_device, device, _device);
2083 if (unlikely(device->lost))
2084 return VK_ERROR_DEVICE_LOST;
2085
2086 struct anv_batch batch;
2087
2088 uint32_t cmds[8];
2089 batch.start = batch.next = cmds;
2090 batch.end = (void *) cmds + sizeof(cmds);
2091
2092 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2093 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2094
2095 return anv_device_submit_simple_batch(device, &batch);
2096 }
2097
2098 bool
2099 anv_vma_alloc(struct anv_device *device, struct anv_bo *bo)
2100 {
2101 if (!(bo->flags & EXEC_OBJECT_PINNED))
2102 return true;
2103
2104 pthread_mutex_lock(&device->vma_mutex);
2105
2106 bo->offset = 0;
2107
2108 if (bo->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS &&
2109 device->vma_hi_available >= bo->size) {
2110 uint64_t addr = util_vma_heap_alloc(&device->vma_hi, bo->size, 4096);
2111 if (addr) {
2112 bo->offset = gen_canonical_address(addr);
2113 assert(addr == gen_48b_address(bo->offset));
2114 device->vma_hi_available -= bo->size;
2115 }
2116 }
2117
2118 if (bo->offset == 0 && device->vma_lo_available >= bo->size) {
2119 uint64_t addr = util_vma_heap_alloc(&device->vma_lo, bo->size, 4096);
2120 if (addr) {
2121 bo->offset = gen_canonical_address(addr);
2122 assert(addr == gen_48b_address(bo->offset));
2123 device->vma_lo_available -= bo->size;
2124 }
2125 }
2126
2127 pthread_mutex_unlock(&device->vma_mutex);
2128
2129 return bo->offset != 0;
2130 }
2131
2132 void
2133 anv_vma_free(struct anv_device *device, struct anv_bo *bo)
2134 {
2135 if (!(bo->flags & EXEC_OBJECT_PINNED))
2136 return;
2137
2138 const uint64_t addr_48b = gen_48b_address(bo->offset);
2139
2140 pthread_mutex_lock(&device->vma_mutex);
2141
2142 if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
2143 addr_48b <= LOW_HEAP_MAX_ADDRESS) {
2144 util_vma_heap_free(&device->vma_lo, addr_48b, bo->size);
2145 device->vma_lo_available += bo->size;
2146 } else {
2147 assert(addr_48b >= HIGH_HEAP_MIN_ADDRESS &&
2148 addr_48b <= HIGH_HEAP_MAX_ADDRESS);
2149 util_vma_heap_free(&device->vma_hi, addr_48b, bo->size);
2150 device->vma_hi_available += bo->size;
2151 }
2152
2153 pthread_mutex_unlock(&device->vma_mutex);
2154
2155 bo->offset = 0;
2156 }
2157
2158 VkResult
2159 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
2160 {
2161 uint32_t gem_handle = anv_gem_create(device, size);
2162 if (!gem_handle)
2163 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
2164
2165 anv_bo_init(bo, gem_handle, size);
2166
2167 return VK_SUCCESS;
2168 }
2169
2170 VkResult anv_AllocateMemory(
2171 VkDevice _device,
2172 const VkMemoryAllocateInfo* pAllocateInfo,
2173 const VkAllocationCallbacks* pAllocator,
2174 VkDeviceMemory* pMem)
2175 {
2176 ANV_FROM_HANDLE(anv_device, device, _device);
2177 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2178 struct anv_device_memory *mem;
2179 VkResult result = VK_SUCCESS;
2180
2181 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
2182
2183 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
2184 assert(pAllocateInfo->allocationSize > 0);
2185
2186 if (pAllocateInfo->allocationSize > MAX_MEMORY_ALLOCATION_SIZE)
2187 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2188
2189 /* FINISHME: Fail if allocation request exceeds heap size. */
2190
2191 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
2192 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2193 if (mem == NULL)
2194 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2195
2196 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
2197 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
2198 mem->map = NULL;
2199 mem->map_size = 0;
2200
2201 uint64_t bo_flags = 0;
2202
2203 assert(mem->type->heapIndex < pdevice->memory.heap_count);
2204 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
2205 bo_flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2206
2207 const struct wsi_memory_allocate_info *wsi_info =
2208 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
2209 if (wsi_info && wsi_info->implicit_sync) {
2210 /* We need to set the WRITE flag on window system buffers so that GEM
2211 * will know we're writing to them and synchronize uses on other rings
2212 * (eg if the display server uses the blitter ring).
2213 */
2214 bo_flags |= EXEC_OBJECT_WRITE;
2215 } else if (pdevice->has_exec_async) {
2216 bo_flags |= EXEC_OBJECT_ASYNC;
2217 }
2218
2219 if (pdevice->use_softpin)
2220 bo_flags |= EXEC_OBJECT_PINNED;
2221
2222 const VkImportMemoryFdInfoKHR *fd_info =
2223 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
2224
2225 /* The Vulkan spec permits handleType to be 0, in which case the struct is
2226 * ignored.
2227 */
2228 if (fd_info && fd_info->handleType) {
2229 /* At the moment, we support only the below handle types. */
2230 assert(fd_info->handleType ==
2231 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2232 fd_info->handleType ==
2233 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2234
2235 result = anv_bo_cache_import(device, &device->bo_cache,
2236 fd_info->fd, bo_flags, &mem->bo);
2237 if (result != VK_SUCCESS)
2238 goto fail;
2239
2240 VkDeviceSize aligned_alloc_size =
2241 align_u64(pAllocateInfo->allocationSize, 4096);
2242
2243 /* For security purposes, we reject importing the bo if it's smaller
2244 * than the requested allocation size. This prevents a malicious client
2245 * from passing a buffer to a trusted client, lying about the size, and
2246 * telling the trusted client to try and texture from an image that goes
2247 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
2248 * in the trusted client. The trusted client can protect itself against
2249 * this sort of attack but only if it can trust the buffer size.
2250 */
2251 if (mem->bo->size < aligned_alloc_size) {
2252 result = vk_errorf(device->instance, device,
2253 VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR,
2254 "aligned allocationSize too large for "
2255 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR: "
2256 "%"PRIu64"B > %"PRIu64"B",
2257 aligned_alloc_size, mem->bo->size);
2258 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2259 goto fail;
2260 }
2261
2262 /* From the Vulkan spec:
2263 *
2264 * "Importing memory from a file descriptor transfers ownership of
2265 * the file descriptor from the application to the Vulkan
2266 * implementation. The application must not perform any operations on
2267 * the file descriptor after a successful import."
2268 *
2269 * If the import fails, we leave the file descriptor open.
2270 */
2271 close(fd_info->fd);
2272 } else {
2273 result = anv_bo_cache_alloc(device, &device->bo_cache,
2274 pAllocateInfo->allocationSize, bo_flags,
2275 &mem->bo);
2276 if (result != VK_SUCCESS)
2277 goto fail;
2278
2279 const VkMemoryDedicatedAllocateInfoKHR *dedicated_info =
2280 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
2281 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
2282 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
2283
2284 /* Some legacy (non-modifiers) consumers need the tiling to be set on
2285 * the BO. In this case, we have a dedicated allocation.
2286 */
2287 if (image->needs_set_tiling) {
2288 const uint32_t i915_tiling =
2289 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
2290 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
2291 image->planes[0].surface.isl.row_pitch_B,
2292 i915_tiling);
2293 if (ret) {
2294 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2295 return vk_errorf(device->instance, NULL,
2296 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2297 "failed to set BO tiling: %m");
2298 }
2299 }
2300 }
2301 }
2302
2303 *pMem = anv_device_memory_to_handle(mem);
2304
2305 return VK_SUCCESS;
2306
2307 fail:
2308 vk_free2(&device->alloc, pAllocator, mem);
2309
2310 return result;
2311 }
2312
2313 VkResult anv_GetMemoryFdKHR(
2314 VkDevice device_h,
2315 const VkMemoryGetFdInfoKHR* pGetFdInfo,
2316 int* pFd)
2317 {
2318 ANV_FROM_HANDLE(anv_device, dev, device_h);
2319 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
2320
2321 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2322
2323 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2324 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2325
2326 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
2327 }
2328
2329 VkResult anv_GetMemoryFdPropertiesKHR(
2330 VkDevice _device,
2331 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
2332 int fd,
2333 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
2334 {
2335 ANV_FROM_HANDLE(anv_device, device, _device);
2336 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2337
2338 switch (handleType) {
2339 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
2340 /* dma-buf can be imported as any memory type */
2341 pMemoryFdProperties->memoryTypeBits =
2342 (1 << pdevice->memory.type_count) - 1;
2343 return VK_SUCCESS;
2344
2345 default:
2346 /* The valid usage section for this function says:
2347 *
2348 * "handleType must not be one of the handle types defined as
2349 * opaque."
2350 *
2351 * So opaque handle types fall into the default "unsupported" case.
2352 */
2353 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2354 }
2355 }
2356
2357 void anv_FreeMemory(
2358 VkDevice _device,
2359 VkDeviceMemory _mem,
2360 const VkAllocationCallbacks* pAllocator)
2361 {
2362 ANV_FROM_HANDLE(anv_device, device, _device);
2363 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
2364
2365 if (mem == NULL)
2366 return;
2367
2368 if (mem->map)
2369 anv_UnmapMemory(_device, _mem);
2370
2371 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2372
2373 vk_free2(&device->alloc, pAllocator, mem);
2374 }
2375
2376 VkResult anv_MapMemory(
2377 VkDevice _device,
2378 VkDeviceMemory _memory,
2379 VkDeviceSize offset,
2380 VkDeviceSize size,
2381 VkMemoryMapFlags flags,
2382 void** ppData)
2383 {
2384 ANV_FROM_HANDLE(anv_device, device, _device);
2385 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2386
2387 if (mem == NULL) {
2388 *ppData = NULL;
2389 return VK_SUCCESS;
2390 }
2391
2392 if (size == VK_WHOLE_SIZE)
2393 size = mem->bo->size - offset;
2394
2395 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
2396 *
2397 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
2398 * assert(size != 0);
2399 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
2400 * equal to the size of the memory minus offset
2401 */
2402 assert(size > 0);
2403 assert(offset + size <= mem->bo->size);
2404
2405 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
2406 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
2407 * at a time is valid. We could just mmap up front and return an offset
2408 * pointer here, but that may exhaust virtual memory on 32 bit
2409 * userspace. */
2410
2411 uint32_t gem_flags = 0;
2412
2413 if (!device->info.has_llc &&
2414 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
2415 gem_flags |= I915_MMAP_WC;
2416
2417 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
2418 uint64_t map_offset = offset & ~4095ull;
2419 assert(offset >= map_offset);
2420 uint64_t map_size = (offset + size) - map_offset;
2421
2422 /* Let's map whole pages */
2423 map_size = align_u64(map_size, 4096);
2424
2425 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
2426 map_offset, map_size, gem_flags);
2427 if (map == MAP_FAILED)
2428 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
2429
2430 mem->map = map;
2431 mem->map_size = map_size;
2432
2433 *ppData = mem->map + (offset - map_offset);
2434
2435 return VK_SUCCESS;
2436 }
2437
2438 void anv_UnmapMemory(
2439 VkDevice _device,
2440 VkDeviceMemory _memory)
2441 {
2442 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2443
2444 if (mem == NULL)
2445 return;
2446
2447 anv_gem_munmap(mem->map, mem->map_size);
2448
2449 mem->map = NULL;
2450 mem->map_size = 0;
2451 }
2452
2453 static void
2454 clflush_mapped_ranges(struct anv_device *device,
2455 uint32_t count,
2456 const VkMappedMemoryRange *ranges)
2457 {
2458 for (uint32_t i = 0; i < count; i++) {
2459 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
2460 if (ranges[i].offset >= mem->map_size)
2461 continue;
2462
2463 gen_clflush_range(mem->map + ranges[i].offset,
2464 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
2465 }
2466 }
2467
2468 VkResult anv_FlushMappedMemoryRanges(
2469 VkDevice _device,
2470 uint32_t memoryRangeCount,
2471 const VkMappedMemoryRange* pMemoryRanges)
2472 {
2473 ANV_FROM_HANDLE(anv_device, device, _device);
2474
2475 if (device->info.has_llc)
2476 return VK_SUCCESS;
2477
2478 /* Make sure the writes we're flushing have landed. */
2479 __builtin_ia32_mfence();
2480
2481 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2482
2483 return VK_SUCCESS;
2484 }
2485
2486 VkResult anv_InvalidateMappedMemoryRanges(
2487 VkDevice _device,
2488 uint32_t memoryRangeCount,
2489 const VkMappedMemoryRange* pMemoryRanges)
2490 {
2491 ANV_FROM_HANDLE(anv_device, device, _device);
2492
2493 if (device->info.has_llc)
2494 return VK_SUCCESS;
2495
2496 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2497
2498 /* Make sure no reads get moved up above the invalidate. */
2499 __builtin_ia32_mfence();
2500
2501 return VK_SUCCESS;
2502 }
2503
2504 void anv_GetBufferMemoryRequirements(
2505 VkDevice _device,
2506 VkBuffer _buffer,
2507 VkMemoryRequirements* pMemoryRequirements)
2508 {
2509 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2510 ANV_FROM_HANDLE(anv_device, device, _device);
2511 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2512
2513 /* The Vulkan spec (git aaed022) says:
2514 *
2515 * memoryTypeBits is a bitfield and contains one bit set for every
2516 * supported memory type for the resource. The bit `1<<i` is set if and
2517 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2518 * structure for the physical device is supported.
2519 */
2520 uint32_t memory_types = 0;
2521 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
2522 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
2523 if ((valid_usage & buffer->usage) == buffer->usage)
2524 memory_types |= (1u << i);
2525 }
2526
2527 /* Base alignment requirement of a cache line */
2528 uint32_t alignment = 16;
2529
2530 /* We need an alignment of 32 for pushing UBOs */
2531 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
2532 alignment = MAX2(alignment, 32);
2533
2534 pMemoryRequirements->size = buffer->size;
2535 pMemoryRequirements->alignment = alignment;
2536
2537 /* Storage and Uniform buffers should have their size aligned to
2538 * 32-bits to avoid boundary checks when last DWord is not complete.
2539 * This would ensure that not internal padding would be needed for
2540 * 16-bit types.
2541 */
2542 if (device->robust_buffer_access &&
2543 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
2544 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
2545 pMemoryRequirements->size = align_u64(buffer->size, 4);
2546
2547 pMemoryRequirements->memoryTypeBits = memory_types;
2548 }
2549
2550 void anv_GetBufferMemoryRequirements2(
2551 VkDevice _device,
2552 const VkBufferMemoryRequirementsInfo2* pInfo,
2553 VkMemoryRequirements2* pMemoryRequirements)
2554 {
2555 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
2556 &pMemoryRequirements->memoryRequirements);
2557
2558 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2559 switch (ext->sType) {
2560 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2561 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2562 requirements->prefersDedicatedAllocation = VK_FALSE;
2563 requirements->requiresDedicatedAllocation = VK_FALSE;
2564 break;
2565 }
2566
2567 default:
2568 anv_debug_ignored_stype(ext->sType);
2569 break;
2570 }
2571 }
2572 }
2573
2574 void anv_GetImageMemoryRequirements(
2575 VkDevice _device,
2576 VkImage _image,
2577 VkMemoryRequirements* pMemoryRequirements)
2578 {
2579 ANV_FROM_HANDLE(anv_image, image, _image);
2580 ANV_FROM_HANDLE(anv_device, device, _device);
2581 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2582
2583 /* The Vulkan spec (git aaed022) says:
2584 *
2585 * memoryTypeBits is a bitfield and contains one bit set for every
2586 * supported memory type for the resource. The bit `1<<i` is set if and
2587 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2588 * structure for the physical device is supported.
2589 *
2590 * All types are currently supported for images.
2591 */
2592 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
2593
2594 pMemoryRequirements->size = image->size;
2595 pMemoryRequirements->alignment = image->alignment;
2596 pMemoryRequirements->memoryTypeBits = memory_types;
2597 }
2598
2599 void anv_GetImageMemoryRequirements2(
2600 VkDevice _device,
2601 const VkImageMemoryRequirementsInfo2* pInfo,
2602 VkMemoryRequirements2* pMemoryRequirements)
2603 {
2604 ANV_FROM_HANDLE(anv_device, device, _device);
2605 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
2606
2607 anv_GetImageMemoryRequirements(_device, pInfo->image,
2608 &pMemoryRequirements->memoryRequirements);
2609
2610 vk_foreach_struct_const(ext, pInfo->pNext) {
2611 switch (ext->sType) {
2612 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
2613 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2614 const VkImagePlaneMemoryRequirementsInfoKHR *plane_reqs =
2615 (const VkImagePlaneMemoryRequirementsInfoKHR *) ext;
2616 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
2617 plane_reqs->planeAspect);
2618
2619 assert(image->planes[plane].offset == 0);
2620
2621 /* The Vulkan spec (git aaed022) says:
2622 *
2623 * memoryTypeBits is a bitfield and contains one bit set for every
2624 * supported memory type for the resource. The bit `1<<i` is set
2625 * if and only if the memory type `i` in the
2626 * VkPhysicalDeviceMemoryProperties structure for the physical
2627 * device is supported.
2628 *
2629 * All types are currently supported for images.
2630 */
2631 pMemoryRequirements->memoryRequirements.memoryTypeBits =
2632 (1ull << pdevice->memory.type_count) - 1;
2633
2634 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
2635 pMemoryRequirements->memoryRequirements.alignment =
2636 image->planes[plane].alignment;
2637 break;
2638 }
2639
2640 default:
2641 anv_debug_ignored_stype(ext->sType);
2642 break;
2643 }
2644 }
2645
2646 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2647 switch (ext->sType) {
2648 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2649 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2650 if (image->needs_set_tiling) {
2651 /* If we need to set the tiling for external consumers, we need a
2652 * dedicated allocation.
2653 *
2654 * See also anv_AllocateMemory.
2655 */
2656 requirements->prefersDedicatedAllocation = VK_TRUE;
2657 requirements->requiresDedicatedAllocation = VK_TRUE;
2658 } else {
2659 requirements->prefersDedicatedAllocation = VK_FALSE;
2660 requirements->requiresDedicatedAllocation = VK_FALSE;
2661 }
2662 break;
2663 }
2664
2665 default:
2666 anv_debug_ignored_stype(ext->sType);
2667 break;
2668 }
2669 }
2670 }
2671
2672 void anv_GetImageSparseMemoryRequirements(
2673 VkDevice device,
2674 VkImage image,
2675 uint32_t* pSparseMemoryRequirementCount,
2676 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2677 {
2678 *pSparseMemoryRequirementCount = 0;
2679 }
2680
2681 void anv_GetImageSparseMemoryRequirements2(
2682 VkDevice device,
2683 const VkImageSparseMemoryRequirementsInfo2* pInfo,
2684 uint32_t* pSparseMemoryRequirementCount,
2685 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
2686 {
2687 *pSparseMemoryRequirementCount = 0;
2688 }
2689
2690 void anv_GetDeviceMemoryCommitment(
2691 VkDevice device,
2692 VkDeviceMemory memory,
2693 VkDeviceSize* pCommittedMemoryInBytes)
2694 {
2695 *pCommittedMemoryInBytes = 0;
2696 }
2697
2698 static void
2699 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
2700 {
2701 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
2702 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
2703
2704 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
2705
2706 if (mem) {
2707 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
2708 buffer->address = (struct anv_address) {
2709 .bo = mem->bo,
2710 .offset = pBindInfo->memoryOffset,
2711 };
2712 } else {
2713 buffer->address = ANV_NULL_ADDRESS;
2714 }
2715 }
2716
2717 VkResult anv_BindBufferMemory(
2718 VkDevice device,
2719 VkBuffer buffer,
2720 VkDeviceMemory memory,
2721 VkDeviceSize memoryOffset)
2722 {
2723 anv_bind_buffer_memory(
2724 &(VkBindBufferMemoryInfo) {
2725 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
2726 .buffer = buffer,
2727 .memory = memory,
2728 .memoryOffset = memoryOffset,
2729 });
2730
2731 return VK_SUCCESS;
2732 }
2733
2734 VkResult anv_BindBufferMemory2(
2735 VkDevice device,
2736 uint32_t bindInfoCount,
2737 const VkBindBufferMemoryInfo* pBindInfos)
2738 {
2739 for (uint32_t i = 0; i < bindInfoCount; i++)
2740 anv_bind_buffer_memory(&pBindInfos[i]);
2741
2742 return VK_SUCCESS;
2743 }
2744
2745 VkResult anv_QueueBindSparse(
2746 VkQueue _queue,
2747 uint32_t bindInfoCount,
2748 const VkBindSparseInfo* pBindInfo,
2749 VkFence fence)
2750 {
2751 ANV_FROM_HANDLE(anv_queue, queue, _queue);
2752 if (unlikely(queue->device->lost))
2753 return VK_ERROR_DEVICE_LOST;
2754
2755 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2756 }
2757
2758 // Event functions
2759
2760 VkResult anv_CreateEvent(
2761 VkDevice _device,
2762 const VkEventCreateInfo* pCreateInfo,
2763 const VkAllocationCallbacks* pAllocator,
2764 VkEvent* pEvent)
2765 {
2766 ANV_FROM_HANDLE(anv_device, device, _device);
2767 struct anv_state state;
2768 struct anv_event *event;
2769
2770 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2771
2772 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2773 sizeof(*event), 8);
2774 event = state.map;
2775 event->state = state;
2776 event->semaphore = VK_EVENT_RESET;
2777
2778 if (!device->info.has_llc) {
2779 /* Make sure the writes we're flushing have landed. */
2780 __builtin_ia32_mfence();
2781 __builtin_ia32_clflush(event);
2782 }
2783
2784 *pEvent = anv_event_to_handle(event);
2785
2786 return VK_SUCCESS;
2787 }
2788
2789 void anv_DestroyEvent(
2790 VkDevice _device,
2791 VkEvent _event,
2792 const VkAllocationCallbacks* pAllocator)
2793 {
2794 ANV_FROM_HANDLE(anv_device, device, _device);
2795 ANV_FROM_HANDLE(anv_event, event, _event);
2796
2797 if (!event)
2798 return;
2799
2800 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2801 }
2802
2803 VkResult anv_GetEventStatus(
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 if (unlikely(device->lost))
2811 return VK_ERROR_DEVICE_LOST;
2812
2813 if (!device->info.has_llc) {
2814 /* Invalidate read cache before reading event written by GPU. */
2815 __builtin_ia32_clflush(event);
2816 __builtin_ia32_mfence();
2817
2818 }
2819
2820 return event->semaphore;
2821 }
2822
2823 VkResult anv_SetEvent(
2824 VkDevice _device,
2825 VkEvent _event)
2826 {
2827 ANV_FROM_HANDLE(anv_device, device, _device);
2828 ANV_FROM_HANDLE(anv_event, event, _event);
2829
2830 event->semaphore = VK_EVENT_SET;
2831
2832 if (!device->info.has_llc) {
2833 /* Make sure the writes we're flushing have landed. */
2834 __builtin_ia32_mfence();
2835 __builtin_ia32_clflush(event);
2836 }
2837
2838 return VK_SUCCESS;
2839 }
2840
2841 VkResult anv_ResetEvent(
2842 VkDevice _device,
2843 VkEvent _event)
2844 {
2845 ANV_FROM_HANDLE(anv_device, device, _device);
2846 ANV_FROM_HANDLE(anv_event, event, _event);
2847
2848 event->semaphore = VK_EVENT_RESET;
2849
2850 if (!device->info.has_llc) {
2851 /* Make sure the writes we're flushing have landed. */
2852 __builtin_ia32_mfence();
2853 __builtin_ia32_clflush(event);
2854 }
2855
2856 return VK_SUCCESS;
2857 }
2858
2859 // Buffer functions
2860
2861 VkResult anv_CreateBuffer(
2862 VkDevice _device,
2863 const VkBufferCreateInfo* pCreateInfo,
2864 const VkAllocationCallbacks* pAllocator,
2865 VkBuffer* pBuffer)
2866 {
2867 ANV_FROM_HANDLE(anv_device, device, _device);
2868 struct anv_buffer *buffer;
2869
2870 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2871
2872 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2873 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2874 if (buffer == NULL)
2875 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2876
2877 buffer->size = pCreateInfo->size;
2878 buffer->usage = pCreateInfo->usage;
2879 buffer->address = ANV_NULL_ADDRESS;
2880
2881 *pBuffer = anv_buffer_to_handle(buffer);
2882
2883 return VK_SUCCESS;
2884 }
2885
2886 void anv_DestroyBuffer(
2887 VkDevice _device,
2888 VkBuffer _buffer,
2889 const VkAllocationCallbacks* pAllocator)
2890 {
2891 ANV_FROM_HANDLE(anv_device, device, _device);
2892 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2893
2894 if (!buffer)
2895 return;
2896
2897 vk_free2(&device->alloc, pAllocator, buffer);
2898 }
2899
2900 void
2901 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2902 enum isl_format format,
2903 struct anv_address address,
2904 uint32_t range, uint32_t stride)
2905 {
2906 isl_buffer_fill_state(&device->isl_dev, state.map,
2907 .address = anv_address_physical(address),
2908 .mocs = device->default_mocs,
2909 .size_B = range,
2910 .format = format,
2911 .stride_B = stride);
2912
2913 anv_state_flush(device, state);
2914 }
2915
2916 void anv_DestroySampler(
2917 VkDevice _device,
2918 VkSampler _sampler,
2919 const VkAllocationCallbacks* pAllocator)
2920 {
2921 ANV_FROM_HANDLE(anv_device, device, _device);
2922 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2923
2924 if (!sampler)
2925 return;
2926
2927 vk_free2(&device->alloc, pAllocator, sampler);
2928 }
2929
2930 VkResult anv_CreateFramebuffer(
2931 VkDevice _device,
2932 const VkFramebufferCreateInfo* pCreateInfo,
2933 const VkAllocationCallbacks* pAllocator,
2934 VkFramebuffer* pFramebuffer)
2935 {
2936 ANV_FROM_HANDLE(anv_device, device, _device);
2937 struct anv_framebuffer *framebuffer;
2938
2939 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2940
2941 size_t size = sizeof(*framebuffer) +
2942 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2943 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2944 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2945 if (framebuffer == NULL)
2946 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2947
2948 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2949 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2950 VkImageView _iview = pCreateInfo->pAttachments[i];
2951 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2952 }
2953
2954 framebuffer->width = pCreateInfo->width;
2955 framebuffer->height = pCreateInfo->height;
2956 framebuffer->layers = pCreateInfo->layers;
2957
2958 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2959
2960 return VK_SUCCESS;
2961 }
2962
2963 void anv_DestroyFramebuffer(
2964 VkDevice _device,
2965 VkFramebuffer _fb,
2966 const VkAllocationCallbacks* pAllocator)
2967 {
2968 ANV_FROM_HANDLE(anv_device, device, _device);
2969 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2970
2971 if (!fb)
2972 return;
2973
2974 vk_free2(&device->alloc, pAllocator, fb);
2975 }
2976
2977 /* vk_icd.h does not declare this function, so we declare it here to
2978 * suppress Wmissing-prototypes.
2979 */
2980 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2981 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2982
2983 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2984 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2985 {
2986 /* For the full details on loader interface versioning, see
2987 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2988 * What follows is a condensed summary, to help you navigate the large and
2989 * confusing official doc.
2990 *
2991 * - Loader interface v0 is incompatible with later versions. We don't
2992 * support it.
2993 *
2994 * - In loader interface v1:
2995 * - The first ICD entrypoint called by the loader is
2996 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2997 * entrypoint.
2998 * - The ICD must statically expose no other Vulkan symbol unless it is
2999 * linked with -Bsymbolic.
3000 * - Each dispatchable Vulkan handle created by the ICD must be
3001 * a pointer to a struct whose first member is VK_LOADER_DATA. The
3002 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
3003 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
3004 * vkDestroySurfaceKHR(). The ICD must be capable of working with
3005 * such loader-managed surfaces.
3006 *
3007 * - Loader interface v2 differs from v1 in:
3008 * - The first ICD entrypoint called by the loader is
3009 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
3010 * statically expose this entrypoint.
3011 *
3012 * - Loader interface v3 differs from v2 in:
3013 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
3014 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
3015 * because the loader no longer does so.
3016 */
3017 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
3018 return VK_SUCCESS;
3019 }