intel/isl: Add a unit suffixes to some struct fields and variables
[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_batch(struct anv_device *device)
1570 {
1571 anv_bo_init_new(&device->hiz_clear_bo, device, 4096);
1572 uint32_t *map = anv_gem_mmap(device, device->hiz_clear_bo.gem_handle,
1573 0, 4096, 0);
1574
1575 union isl_color_value hiz_clear = { .u32 = { 0, } };
1576 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
1577
1578 memcpy(map, hiz_clear.u32, sizeof(hiz_clear.u32));
1579 anv_gem_munmap(map, device->hiz_clear_bo.size);
1580 }
1581
1582 VkResult anv_CreateDevice(
1583 VkPhysicalDevice physicalDevice,
1584 const VkDeviceCreateInfo* pCreateInfo,
1585 const VkAllocationCallbacks* pAllocator,
1586 VkDevice* pDevice)
1587 {
1588 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1589 VkResult result;
1590 struct anv_device *device;
1591
1592 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1593
1594 struct anv_device_extension_table enabled_extensions = { };
1595 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1596 int idx;
1597 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
1598 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1599 anv_device_extensions[idx].extensionName) == 0)
1600 break;
1601 }
1602
1603 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
1604 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1605
1606 if (!physical_device->supported_extensions.extensions[idx])
1607 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1608
1609 enabled_extensions.extensions[idx] = true;
1610 }
1611
1612 /* Check enabled features */
1613 if (pCreateInfo->pEnabledFeatures) {
1614 VkPhysicalDeviceFeatures supported_features;
1615 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1616 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1617 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1618 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1619 for (uint32_t i = 0; i < num_features; i++) {
1620 if (enabled_feature[i] && !supported_feature[i])
1621 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1622 }
1623 }
1624
1625 /* Check requested queues and fail if we are requested to create any
1626 * queues with flags we don't support.
1627 */
1628 assert(pCreateInfo->queueCreateInfoCount > 0);
1629 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1630 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
1631 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
1632 }
1633
1634 /* Check if client specified queue priority. */
1635 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
1636 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
1637 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1638
1639 VkQueueGlobalPriorityEXT priority =
1640 queue_priority ? queue_priority->globalPriority :
1641 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
1642
1643 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1644 sizeof(*device), 8,
1645 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1646 if (!device)
1647 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1648
1649 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1650 device->instance = physical_device->instance;
1651 device->chipset_id = physical_device->chipset_id;
1652 device->no_hw = physical_device->no_hw;
1653 device->lost = false;
1654
1655 if (pAllocator)
1656 device->alloc = *pAllocator;
1657 else
1658 device->alloc = physical_device->instance->alloc;
1659
1660 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1661 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1662 if (device->fd == -1) {
1663 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1664 goto fail_device;
1665 }
1666
1667 device->context_id = anv_gem_create_context(device);
1668 if (device->context_id == -1) {
1669 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1670 goto fail_fd;
1671 }
1672
1673 if (physical_device->use_softpin) {
1674 if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
1675 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1676 goto fail_fd;
1677 }
1678
1679 /* keep the page with address zero out of the allocator */
1680 util_vma_heap_init(&device->vma_lo, LOW_HEAP_MIN_ADDRESS, LOW_HEAP_SIZE);
1681 device->vma_lo_available =
1682 physical_device->memory.heaps[physical_device->memory.heap_count - 1].size;
1683
1684 /* Leave the last 4GiB out of the high vma range, so that no state base
1685 * address + size can overflow 48 bits. For more information see the
1686 * comment about Wa32bitGeneralStateOffset in anv_allocator.c
1687 */
1688 util_vma_heap_init(&device->vma_hi, HIGH_HEAP_MIN_ADDRESS,
1689 HIGH_HEAP_SIZE);
1690 device->vma_hi_available = physical_device->memory.heap_count == 1 ? 0 :
1691 physical_device->memory.heaps[0].size;
1692 }
1693
1694 /* As per spec, the driver implementation may deny requests to acquire
1695 * a priority above the default priority (MEDIUM) if the caller does not
1696 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
1697 * is returned.
1698 */
1699 if (physical_device->has_context_priority) {
1700 int err = anv_gem_set_context_param(device->fd, device->context_id,
1701 I915_CONTEXT_PARAM_PRIORITY,
1702 vk_priority_to_gen(priority));
1703 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
1704 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
1705 goto fail_fd;
1706 }
1707 }
1708
1709 device->info = physical_device->info;
1710 device->isl_dev = physical_device->isl_dev;
1711
1712 /* On Broadwell and later, we can use batch chaining to more efficiently
1713 * implement growing command buffers. Prior to Haswell, the kernel
1714 * command parser gets in the way and we have to fall back to growing
1715 * the batch.
1716 */
1717 device->can_chain_batches = device->info.gen >= 8;
1718
1719 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1720 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1721 device->enabled_extensions = enabled_extensions;
1722
1723 anv_device_init_dispatch(device);
1724
1725 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1726 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1727 goto fail_context_id;
1728 }
1729
1730 pthread_condattr_t condattr;
1731 if (pthread_condattr_init(&condattr) != 0) {
1732 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1733 goto fail_mutex;
1734 }
1735 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1736 pthread_condattr_destroy(&condattr);
1737 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1738 goto fail_mutex;
1739 }
1740 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1741 pthread_condattr_destroy(&condattr);
1742 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1743 goto fail_mutex;
1744 }
1745 pthread_condattr_destroy(&condattr);
1746
1747 uint64_t bo_flags =
1748 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
1749 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1750 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0) |
1751 (physical_device->use_softpin ? EXEC_OBJECT_PINNED : 0);
1752
1753 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
1754
1755 result = anv_bo_cache_init(&device->bo_cache);
1756 if (result != VK_SUCCESS)
1757 goto fail_batch_bo_pool;
1758
1759 if (!physical_device->use_softpin)
1760 bo_flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1761
1762 result = anv_state_pool_init(&device->dynamic_state_pool, device,
1763 DYNAMIC_STATE_POOL_MIN_ADDRESS,
1764 16384,
1765 bo_flags);
1766 if (result != VK_SUCCESS)
1767 goto fail_bo_cache;
1768
1769 result = anv_state_pool_init(&device->instruction_state_pool, device,
1770 INSTRUCTION_STATE_POOL_MIN_ADDRESS,
1771 16384,
1772 bo_flags);
1773 if (result != VK_SUCCESS)
1774 goto fail_dynamic_state_pool;
1775
1776 result = anv_state_pool_init(&device->surface_state_pool, device,
1777 SURFACE_STATE_POOL_MIN_ADDRESS,
1778 4096,
1779 bo_flags);
1780 if (result != VK_SUCCESS)
1781 goto fail_instruction_state_pool;
1782
1783 if (physical_device->use_softpin) {
1784 result = anv_state_pool_init(&device->binding_table_pool, device,
1785 BINDING_TABLE_POOL_MIN_ADDRESS,
1786 4096,
1787 bo_flags);
1788 if (result != VK_SUCCESS)
1789 goto fail_surface_state_pool;
1790 }
1791
1792 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1793 if (result != VK_SUCCESS)
1794 goto fail_binding_table_pool;
1795
1796 if (physical_device->use_softpin)
1797 device->workaround_bo.flags |= EXEC_OBJECT_PINNED;
1798
1799 if (!anv_vma_alloc(device, &device->workaround_bo))
1800 goto fail_workaround_bo;
1801
1802 anv_device_init_trivial_batch(device);
1803
1804 if (device->info.gen >= 10)
1805 anv_device_init_hiz_clear_batch(device);
1806
1807 anv_scratch_pool_init(device, &device->scratch_pool);
1808
1809 anv_queue_init(device, &device->queue);
1810
1811 switch (device->info.gen) {
1812 case 7:
1813 if (!device->info.is_haswell)
1814 result = gen7_init_device_state(device);
1815 else
1816 result = gen75_init_device_state(device);
1817 break;
1818 case 8:
1819 result = gen8_init_device_state(device);
1820 break;
1821 case 9:
1822 result = gen9_init_device_state(device);
1823 break;
1824 case 10:
1825 result = gen10_init_device_state(device);
1826 break;
1827 case 11:
1828 result = gen11_init_device_state(device);
1829 break;
1830 default:
1831 /* Shouldn't get here as we don't create physical devices for any other
1832 * gens. */
1833 unreachable("unhandled gen");
1834 }
1835 if (result != VK_SUCCESS)
1836 goto fail_workaround_bo;
1837
1838 anv_pipeline_cache_init(&device->default_pipeline_cache, device, true);
1839
1840 anv_device_init_blorp(device);
1841
1842 anv_device_init_border_colors(device);
1843
1844 *pDevice = anv_device_to_handle(device);
1845
1846 return VK_SUCCESS;
1847
1848 fail_workaround_bo:
1849 anv_queue_finish(&device->queue);
1850 anv_scratch_pool_finish(device, &device->scratch_pool);
1851 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1852 anv_gem_close(device, device->workaround_bo.gem_handle);
1853 fail_binding_table_pool:
1854 if (physical_device->use_softpin)
1855 anv_state_pool_finish(&device->binding_table_pool);
1856 fail_surface_state_pool:
1857 anv_state_pool_finish(&device->surface_state_pool);
1858 fail_instruction_state_pool:
1859 anv_state_pool_finish(&device->instruction_state_pool);
1860 fail_dynamic_state_pool:
1861 anv_state_pool_finish(&device->dynamic_state_pool);
1862 fail_bo_cache:
1863 anv_bo_cache_finish(&device->bo_cache);
1864 fail_batch_bo_pool:
1865 anv_bo_pool_finish(&device->batch_bo_pool);
1866 pthread_cond_destroy(&device->queue_submit);
1867 fail_mutex:
1868 pthread_mutex_destroy(&device->mutex);
1869 fail_context_id:
1870 anv_gem_destroy_context(device, device->context_id);
1871 fail_fd:
1872 close(device->fd);
1873 fail_device:
1874 vk_free(&device->alloc, device);
1875
1876 return result;
1877 }
1878
1879 void anv_DestroyDevice(
1880 VkDevice _device,
1881 const VkAllocationCallbacks* pAllocator)
1882 {
1883 ANV_FROM_HANDLE(anv_device, device, _device);
1884 struct anv_physical_device *physical_device;
1885
1886 if (!device)
1887 return;
1888
1889 physical_device = &device->instance->physicalDevice;
1890
1891 anv_device_finish_blorp(device);
1892
1893 anv_pipeline_cache_finish(&device->default_pipeline_cache);
1894
1895 anv_queue_finish(&device->queue);
1896
1897 #ifdef HAVE_VALGRIND
1898 /* We only need to free these to prevent valgrind errors. The backing
1899 * BO will go away in a couple of lines so we don't actually leak.
1900 */
1901 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1902 #endif
1903
1904 anv_scratch_pool_finish(device, &device->scratch_pool);
1905
1906 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1907 anv_vma_free(device, &device->workaround_bo);
1908 anv_gem_close(device, device->workaround_bo.gem_handle);
1909
1910 anv_vma_free(device, &device->trivial_batch_bo);
1911 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
1912 if (device->info.gen >= 10)
1913 anv_gem_close(device, device->hiz_clear_bo.gem_handle);
1914
1915 if (physical_device->use_softpin)
1916 anv_state_pool_finish(&device->binding_table_pool);
1917 anv_state_pool_finish(&device->surface_state_pool);
1918 anv_state_pool_finish(&device->instruction_state_pool);
1919 anv_state_pool_finish(&device->dynamic_state_pool);
1920
1921 anv_bo_cache_finish(&device->bo_cache);
1922
1923 anv_bo_pool_finish(&device->batch_bo_pool);
1924
1925 pthread_cond_destroy(&device->queue_submit);
1926 pthread_mutex_destroy(&device->mutex);
1927
1928 anv_gem_destroy_context(device, device->context_id);
1929
1930 close(device->fd);
1931
1932 vk_free(&device->alloc, device);
1933 }
1934
1935 VkResult anv_EnumerateInstanceLayerProperties(
1936 uint32_t* pPropertyCount,
1937 VkLayerProperties* pProperties)
1938 {
1939 if (pProperties == NULL) {
1940 *pPropertyCount = 0;
1941 return VK_SUCCESS;
1942 }
1943
1944 /* None supported at this time */
1945 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1946 }
1947
1948 VkResult anv_EnumerateDeviceLayerProperties(
1949 VkPhysicalDevice physicalDevice,
1950 uint32_t* pPropertyCount,
1951 VkLayerProperties* pProperties)
1952 {
1953 if (pProperties == NULL) {
1954 *pPropertyCount = 0;
1955 return VK_SUCCESS;
1956 }
1957
1958 /* None supported at this time */
1959 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1960 }
1961
1962 void anv_GetDeviceQueue(
1963 VkDevice _device,
1964 uint32_t queueNodeIndex,
1965 uint32_t queueIndex,
1966 VkQueue* pQueue)
1967 {
1968 ANV_FROM_HANDLE(anv_device, device, _device);
1969
1970 assert(queueIndex == 0);
1971
1972 *pQueue = anv_queue_to_handle(&device->queue);
1973 }
1974
1975 void anv_GetDeviceQueue2(
1976 VkDevice _device,
1977 const VkDeviceQueueInfo2* pQueueInfo,
1978 VkQueue* pQueue)
1979 {
1980 ANV_FROM_HANDLE(anv_device, device, _device);
1981
1982 assert(pQueueInfo->queueIndex == 0);
1983
1984 if (pQueueInfo->flags == device->queue.flags)
1985 *pQueue = anv_queue_to_handle(&device->queue);
1986 else
1987 *pQueue = NULL;
1988 }
1989
1990 VkResult
1991 anv_device_query_status(struct anv_device *device)
1992 {
1993 /* This isn't likely as most of the callers of this function already check
1994 * for it. However, it doesn't hurt to check and it potentially lets us
1995 * avoid an ioctl.
1996 */
1997 if (unlikely(device->lost))
1998 return VK_ERROR_DEVICE_LOST;
1999
2000 uint32_t active, pending;
2001 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
2002 if (ret == -1) {
2003 /* We don't know the real error. */
2004 device->lost = true;
2005 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2006 "get_reset_stats failed: %m");
2007 }
2008
2009 if (active) {
2010 device->lost = true;
2011 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2012 "GPU hung on one of our command buffers");
2013 } else if (pending) {
2014 device->lost = true;
2015 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2016 "GPU hung with commands in-flight");
2017 }
2018
2019 return VK_SUCCESS;
2020 }
2021
2022 VkResult
2023 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
2024 {
2025 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
2026 * Other usages of the BO (such as on different hardware) will not be
2027 * flagged as "busy" by this ioctl. Use with care.
2028 */
2029 int ret = anv_gem_busy(device, bo->gem_handle);
2030 if (ret == 1) {
2031 return VK_NOT_READY;
2032 } else if (ret == -1) {
2033 /* We don't know the real error. */
2034 device->lost = true;
2035 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2036 "gem wait failed: %m");
2037 }
2038
2039 /* Query for device status after the busy call. If the BO we're checking
2040 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
2041 * client because it clearly doesn't have valid data. Yes, this most
2042 * likely means an ioctl, but we just did an ioctl to query the busy status
2043 * so it's no great loss.
2044 */
2045 return anv_device_query_status(device);
2046 }
2047
2048 VkResult
2049 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
2050 int64_t timeout)
2051 {
2052 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
2053 if (ret == -1 && errno == ETIME) {
2054 return VK_TIMEOUT;
2055 } else if (ret == -1) {
2056 /* We don't know the real error. */
2057 device->lost = true;
2058 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2059 "gem wait failed: %m");
2060 }
2061
2062 /* Query for device status after the wait. If the BO we're waiting on got
2063 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
2064 * because it clearly doesn't have valid data. Yes, this most likely means
2065 * an ioctl, but we just did an ioctl to wait so it's no great loss.
2066 */
2067 return anv_device_query_status(device);
2068 }
2069
2070 VkResult anv_DeviceWaitIdle(
2071 VkDevice _device)
2072 {
2073 ANV_FROM_HANDLE(anv_device, device, _device);
2074 if (unlikely(device->lost))
2075 return VK_ERROR_DEVICE_LOST;
2076
2077 struct anv_batch batch;
2078
2079 uint32_t cmds[8];
2080 batch.start = batch.next = cmds;
2081 batch.end = (void *) cmds + sizeof(cmds);
2082
2083 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2084 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2085
2086 return anv_device_submit_simple_batch(device, &batch);
2087 }
2088
2089 bool
2090 anv_vma_alloc(struct anv_device *device, struct anv_bo *bo)
2091 {
2092 if (!(bo->flags & EXEC_OBJECT_PINNED))
2093 return true;
2094
2095 pthread_mutex_lock(&device->vma_mutex);
2096
2097 bo->offset = 0;
2098
2099 if (bo->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS &&
2100 device->vma_hi_available >= bo->size) {
2101 uint64_t addr = util_vma_heap_alloc(&device->vma_hi, bo->size, 4096);
2102 if (addr) {
2103 bo->offset = gen_canonical_address(addr);
2104 assert(addr == gen_48b_address(bo->offset));
2105 device->vma_hi_available -= bo->size;
2106 }
2107 }
2108
2109 if (bo->offset == 0 && device->vma_lo_available >= bo->size) {
2110 uint64_t addr = util_vma_heap_alloc(&device->vma_lo, bo->size, 4096);
2111 if (addr) {
2112 bo->offset = gen_canonical_address(addr);
2113 assert(addr == gen_48b_address(bo->offset));
2114 device->vma_lo_available -= bo->size;
2115 }
2116 }
2117
2118 pthread_mutex_unlock(&device->vma_mutex);
2119
2120 return bo->offset != 0;
2121 }
2122
2123 void
2124 anv_vma_free(struct anv_device *device, struct anv_bo *bo)
2125 {
2126 if (!(bo->flags & EXEC_OBJECT_PINNED))
2127 return;
2128
2129 const uint64_t addr_48b = gen_48b_address(bo->offset);
2130
2131 pthread_mutex_lock(&device->vma_mutex);
2132
2133 if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
2134 addr_48b <= LOW_HEAP_MAX_ADDRESS) {
2135 util_vma_heap_free(&device->vma_lo, addr_48b, bo->size);
2136 device->vma_lo_available += bo->size;
2137 } else {
2138 assert(addr_48b >= HIGH_HEAP_MIN_ADDRESS &&
2139 addr_48b <= HIGH_HEAP_MAX_ADDRESS);
2140 util_vma_heap_free(&device->vma_hi, addr_48b, bo->size);
2141 device->vma_hi_available += bo->size;
2142 }
2143
2144 pthread_mutex_unlock(&device->vma_mutex);
2145
2146 bo->offset = 0;
2147 }
2148
2149 VkResult
2150 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
2151 {
2152 uint32_t gem_handle = anv_gem_create(device, size);
2153 if (!gem_handle)
2154 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
2155
2156 anv_bo_init(bo, gem_handle, size);
2157
2158 return VK_SUCCESS;
2159 }
2160
2161 VkResult anv_AllocateMemory(
2162 VkDevice _device,
2163 const VkMemoryAllocateInfo* pAllocateInfo,
2164 const VkAllocationCallbacks* pAllocator,
2165 VkDeviceMemory* pMem)
2166 {
2167 ANV_FROM_HANDLE(anv_device, device, _device);
2168 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2169 struct anv_device_memory *mem;
2170 VkResult result = VK_SUCCESS;
2171
2172 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
2173
2174 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
2175 assert(pAllocateInfo->allocationSize > 0);
2176
2177 if (pAllocateInfo->allocationSize > MAX_MEMORY_ALLOCATION_SIZE)
2178 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2179
2180 /* FINISHME: Fail if allocation request exceeds heap size. */
2181
2182 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
2183 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2184 if (mem == NULL)
2185 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2186
2187 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
2188 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
2189 mem->map = NULL;
2190 mem->map_size = 0;
2191
2192 uint64_t bo_flags = 0;
2193
2194 assert(mem->type->heapIndex < pdevice->memory.heap_count);
2195 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
2196 bo_flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2197
2198 const struct wsi_memory_allocate_info *wsi_info =
2199 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
2200 if (wsi_info && wsi_info->implicit_sync) {
2201 /* We need to set the WRITE flag on window system buffers so that GEM
2202 * will know we're writing to them and synchronize uses on other rings
2203 * (eg if the display server uses the blitter ring).
2204 */
2205 bo_flags |= EXEC_OBJECT_WRITE;
2206 } else if (pdevice->has_exec_async) {
2207 bo_flags |= EXEC_OBJECT_ASYNC;
2208 }
2209
2210 if (pdevice->use_softpin)
2211 bo_flags |= EXEC_OBJECT_PINNED;
2212
2213 const VkImportMemoryFdInfoKHR *fd_info =
2214 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
2215
2216 /* The Vulkan spec permits handleType to be 0, in which case the struct is
2217 * ignored.
2218 */
2219 if (fd_info && fd_info->handleType) {
2220 /* At the moment, we support only the below handle types. */
2221 assert(fd_info->handleType ==
2222 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2223 fd_info->handleType ==
2224 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2225
2226 result = anv_bo_cache_import(device, &device->bo_cache,
2227 fd_info->fd, bo_flags, &mem->bo);
2228 if (result != VK_SUCCESS)
2229 goto fail;
2230
2231 VkDeviceSize aligned_alloc_size =
2232 align_u64(pAllocateInfo->allocationSize, 4096);
2233
2234 /* For security purposes, we reject importing the bo if it's smaller
2235 * than the requested allocation size. This prevents a malicious client
2236 * from passing a buffer to a trusted client, lying about the size, and
2237 * telling the trusted client to try and texture from an image that goes
2238 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
2239 * in the trusted client. The trusted client can protect itself against
2240 * this sort of attack but only if it can trust the buffer size.
2241 */
2242 if (mem->bo->size < aligned_alloc_size) {
2243 result = vk_errorf(device->instance, device,
2244 VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR,
2245 "aligned allocationSize too large for "
2246 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR: "
2247 "%"PRIu64"B > %"PRIu64"B",
2248 aligned_alloc_size, mem->bo->size);
2249 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2250 goto fail;
2251 }
2252
2253 /* From the Vulkan spec:
2254 *
2255 * "Importing memory from a file descriptor transfers ownership of
2256 * the file descriptor from the application to the Vulkan
2257 * implementation. The application must not perform any operations on
2258 * the file descriptor after a successful import."
2259 *
2260 * If the import fails, we leave the file descriptor open.
2261 */
2262 close(fd_info->fd);
2263 } else {
2264 result = anv_bo_cache_alloc(device, &device->bo_cache,
2265 pAllocateInfo->allocationSize, bo_flags,
2266 &mem->bo);
2267 if (result != VK_SUCCESS)
2268 goto fail;
2269
2270 const VkMemoryDedicatedAllocateInfoKHR *dedicated_info =
2271 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
2272 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
2273 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
2274
2275 /* Some legacy (non-modifiers) consumers need the tiling to be set on
2276 * the BO. In this case, we have a dedicated allocation.
2277 */
2278 if (image->needs_set_tiling) {
2279 const uint32_t i915_tiling =
2280 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
2281 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
2282 image->planes[0].surface.isl.row_pitch_B,
2283 i915_tiling);
2284 if (ret) {
2285 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2286 return vk_errorf(device->instance, NULL,
2287 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2288 "failed to set BO tiling: %m");
2289 }
2290 }
2291 }
2292 }
2293
2294 *pMem = anv_device_memory_to_handle(mem);
2295
2296 return VK_SUCCESS;
2297
2298 fail:
2299 vk_free2(&device->alloc, pAllocator, mem);
2300
2301 return result;
2302 }
2303
2304 VkResult anv_GetMemoryFdKHR(
2305 VkDevice device_h,
2306 const VkMemoryGetFdInfoKHR* pGetFdInfo,
2307 int* pFd)
2308 {
2309 ANV_FROM_HANDLE(anv_device, dev, device_h);
2310 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
2311
2312 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2313
2314 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2315 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2316
2317 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
2318 }
2319
2320 VkResult anv_GetMemoryFdPropertiesKHR(
2321 VkDevice _device,
2322 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
2323 int fd,
2324 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
2325 {
2326 ANV_FROM_HANDLE(anv_device, device, _device);
2327 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2328
2329 switch (handleType) {
2330 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
2331 /* dma-buf can be imported as any memory type */
2332 pMemoryFdProperties->memoryTypeBits =
2333 (1 << pdevice->memory.type_count) - 1;
2334 return VK_SUCCESS;
2335
2336 default:
2337 /* The valid usage section for this function says:
2338 *
2339 * "handleType must not be one of the handle types defined as
2340 * opaque."
2341 *
2342 * So opaque handle types fall into the default "unsupported" case.
2343 */
2344 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2345 }
2346 }
2347
2348 void anv_FreeMemory(
2349 VkDevice _device,
2350 VkDeviceMemory _mem,
2351 const VkAllocationCallbacks* pAllocator)
2352 {
2353 ANV_FROM_HANDLE(anv_device, device, _device);
2354 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
2355
2356 if (mem == NULL)
2357 return;
2358
2359 if (mem->map)
2360 anv_UnmapMemory(_device, _mem);
2361
2362 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2363
2364 vk_free2(&device->alloc, pAllocator, mem);
2365 }
2366
2367 VkResult anv_MapMemory(
2368 VkDevice _device,
2369 VkDeviceMemory _memory,
2370 VkDeviceSize offset,
2371 VkDeviceSize size,
2372 VkMemoryMapFlags flags,
2373 void** ppData)
2374 {
2375 ANV_FROM_HANDLE(anv_device, device, _device);
2376 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2377
2378 if (mem == NULL) {
2379 *ppData = NULL;
2380 return VK_SUCCESS;
2381 }
2382
2383 if (size == VK_WHOLE_SIZE)
2384 size = mem->bo->size - offset;
2385
2386 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
2387 *
2388 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
2389 * assert(size != 0);
2390 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
2391 * equal to the size of the memory minus offset
2392 */
2393 assert(size > 0);
2394 assert(offset + size <= mem->bo->size);
2395
2396 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
2397 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
2398 * at a time is valid. We could just mmap up front and return an offset
2399 * pointer here, but that may exhaust virtual memory on 32 bit
2400 * userspace. */
2401
2402 uint32_t gem_flags = 0;
2403
2404 if (!device->info.has_llc &&
2405 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
2406 gem_flags |= I915_MMAP_WC;
2407
2408 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
2409 uint64_t map_offset = offset & ~4095ull;
2410 assert(offset >= map_offset);
2411 uint64_t map_size = (offset + size) - map_offset;
2412
2413 /* Let's map whole pages */
2414 map_size = align_u64(map_size, 4096);
2415
2416 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
2417 map_offset, map_size, gem_flags);
2418 if (map == MAP_FAILED)
2419 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
2420
2421 mem->map = map;
2422 mem->map_size = map_size;
2423
2424 *ppData = mem->map + (offset - map_offset);
2425
2426 return VK_SUCCESS;
2427 }
2428
2429 void anv_UnmapMemory(
2430 VkDevice _device,
2431 VkDeviceMemory _memory)
2432 {
2433 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2434
2435 if (mem == NULL)
2436 return;
2437
2438 anv_gem_munmap(mem->map, mem->map_size);
2439
2440 mem->map = NULL;
2441 mem->map_size = 0;
2442 }
2443
2444 static void
2445 clflush_mapped_ranges(struct anv_device *device,
2446 uint32_t count,
2447 const VkMappedMemoryRange *ranges)
2448 {
2449 for (uint32_t i = 0; i < count; i++) {
2450 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
2451 if (ranges[i].offset >= mem->map_size)
2452 continue;
2453
2454 gen_clflush_range(mem->map + ranges[i].offset,
2455 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
2456 }
2457 }
2458
2459 VkResult anv_FlushMappedMemoryRanges(
2460 VkDevice _device,
2461 uint32_t memoryRangeCount,
2462 const VkMappedMemoryRange* pMemoryRanges)
2463 {
2464 ANV_FROM_HANDLE(anv_device, device, _device);
2465
2466 if (device->info.has_llc)
2467 return VK_SUCCESS;
2468
2469 /* Make sure the writes we're flushing have landed. */
2470 __builtin_ia32_mfence();
2471
2472 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2473
2474 return VK_SUCCESS;
2475 }
2476
2477 VkResult anv_InvalidateMappedMemoryRanges(
2478 VkDevice _device,
2479 uint32_t memoryRangeCount,
2480 const VkMappedMemoryRange* pMemoryRanges)
2481 {
2482 ANV_FROM_HANDLE(anv_device, device, _device);
2483
2484 if (device->info.has_llc)
2485 return VK_SUCCESS;
2486
2487 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2488
2489 /* Make sure no reads get moved up above the invalidate. */
2490 __builtin_ia32_mfence();
2491
2492 return VK_SUCCESS;
2493 }
2494
2495 void anv_GetBufferMemoryRequirements(
2496 VkDevice _device,
2497 VkBuffer _buffer,
2498 VkMemoryRequirements* pMemoryRequirements)
2499 {
2500 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2501 ANV_FROM_HANDLE(anv_device, device, _device);
2502 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2503
2504 /* The Vulkan spec (git aaed022) says:
2505 *
2506 * memoryTypeBits is a bitfield and contains one bit set for every
2507 * supported memory type for the resource. The bit `1<<i` is set if and
2508 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2509 * structure for the physical device is supported.
2510 */
2511 uint32_t memory_types = 0;
2512 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
2513 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
2514 if ((valid_usage & buffer->usage) == buffer->usage)
2515 memory_types |= (1u << i);
2516 }
2517
2518 /* Base alignment requirement of a cache line */
2519 uint32_t alignment = 16;
2520
2521 /* We need an alignment of 32 for pushing UBOs */
2522 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
2523 alignment = MAX2(alignment, 32);
2524
2525 pMemoryRequirements->size = buffer->size;
2526 pMemoryRequirements->alignment = alignment;
2527
2528 /* Storage and Uniform buffers should have their size aligned to
2529 * 32-bits to avoid boundary checks when last DWord is not complete.
2530 * This would ensure that not internal padding would be needed for
2531 * 16-bit types.
2532 */
2533 if (device->robust_buffer_access &&
2534 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
2535 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
2536 pMemoryRequirements->size = align_u64(buffer->size, 4);
2537
2538 pMemoryRequirements->memoryTypeBits = memory_types;
2539 }
2540
2541 void anv_GetBufferMemoryRequirements2(
2542 VkDevice _device,
2543 const VkBufferMemoryRequirementsInfo2* pInfo,
2544 VkMemoryRequirements2* pMemoryRequirements)
2545 {
2546 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
2547 &pMemoryRequirements->memoryRequirements);
2548
2549 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2550 switch (ext->sType) {
2551 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2552 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2553 requirements->prefersDedicatedAllocation = VK_FALSE;
2554 requirements->requiresDedicatedAllocation = VK_FALSE;
2555 break;
2556 }
2557
2558 default:
2559 anv_debug_ignored_stype(ext->sType);
2560 break;
2561 }
2562 }
2563 }
2564
2565 void anv_GetImageMemoryRequirements(
2566 VkDevice _device,
2567 VkImage _image,
2568 VkMemoryRequirements* pMemoryRequirements)
2569 {
2570 ANV_FROM_HANDLE(anv_image, image, _image);
2571 ANV_FROM_HANDLE(anv_device, device, _device);
2572 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2573
2574 /* The Vulkan spec (git aaed022) says:
2575 *
2576 * memoryTypeBits is a bitfield and contains one bit set for every
2577 * supported memory type for the resource. The bit `1<<i` is set if and
2578 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2579 * structure for the physical device is supported.
2580 *
2581 * All types are currently supported for images.
2582 */
2583 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
2584
2585 pMemoryRequirements->size = image->size;
2586 pMemoryRequirements->alignment = image->alignment;
2587 pMemoryRequirements->memoryTypeBits = memory_types;
2588 }
2589
2590 void anv_GetImageMemoryRequirements2(
2591 VkDevice _device,
2592 const VkImageMemoryRequirementsInfo2* pInfo,
2593 VkMemoryRequirements2* pMemoryRequirements)
2594 {
2595 ANV_FROM_HANDLE(anv_device, device, _device);
2596 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
2597
2598 anv_GetImageMemoryRequirements(_device, pInfo->image,
2599 &pMemoryRequirements->memoryRequirements);
2600
2601 vk_foreach_struct_const(ext, pInfo->pNext) {
2602 switch (ext->sType) {
2603 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
2604 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2605 const VkImagePlaneMemoryRequirementsInfoKHR *plane_reqs =
2606 (const VkImagePlaneMemoryRequirementsInfoKHR *) ext;
2607 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
2608 plane_reqs->planeAspect);
2609
2610 assert(image->planes[plane].offset == 0);
2611
2612 /* The Vulkan spec (git aaed022) says:
2613 *
2614 * memoryTypeBits is a bitfield and contains one bit set for every
2615 * supported memory type for the resource. The bit `1<<i` is set
2616 * if and only if the memory type `i` in the
2617 * VkPhysicalDeviceMemoryProperties structure for the physical
2618 * device is supported.
2619 *
2620 * All types are currently supported for images.
2621 */
2622 pMemoryRequirements->memoryRequirements.memoryTypeBits =
2623 (1ull << pdevice->memory.type_count) - 1;
2624
2625 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
2626 pMemoryRequirements->memoryRequirements.alignment =
2627 image->planes[plane].alignment;
2628 break;
2629 }
2630
2631 default:
2632 anv_debug_ignored_stype(ext->sType);
2633 break;
2634 }
2635 }
2636
2637 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2638 switch (ext->sType) {
2639 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2640 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2641 if (image->needs_set_tiling) {
2642 /* If we need to set the tiling for external consumers, we need a
2643 * dedicated allocation.
2644 *
2645 * See also anv_AllocateMemory.
2646 */
2647 requirements->prefersDedicatedAllocation = VK_TRUE;
2648 requirements->requiresDedicatedAllocation = VK_TRUE;
2649 } else {
2650 requirements->prefersDedicatedAllocation = VK_FALSE;
2651 requirements->requiresDedicatedAllocation = VK_FALSE;
2652 }
2653 break;
2654 }
2655
2656 default:
2657 anv_debug_ignored_stype(ext->sType);
2658 break;
2659 }
2660 }
2661 }
2662
2663 void anv_GetImageSparseMemoryRequirements(
2664 VkDevice device,
2665 VkImage image,
2666 uint32_t* pSparseMemoryRequirementCount,
2667 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2668 {
2669 *pSparseMemoryRequirementCount = 0;
2670 }
2671
2672 void anv_GetImageSparseMemoryRequirements2(
2673 VkDevice device,
2674 const VkImageSparseMemoryRequirementsInfo2* pInfo,
2675 uint32_t* pSparseMemoryRequirementCount,
2676 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
2677 {
2678 *pSparseMemoryRequirementCount = 0;
2679 }
2680
2681 void anv_GetDeviceMemoryCommitment(
2682 VkDevice device,
2683 VkDeviceMemory memory,
2684 VkDeviceSize* pCommittedMemoryInBytes)
2685 {
2686 *pCommittedMemoryInBytes = 0;
2687 }
2688
2689 static void
2690 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
2691 {
2692 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
2693 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
2694
2695 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
2696
2697 if (mem) {
2698 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
2699 buffer->address = (struct anv_address) {
2700 .bo = mem->bo,
2701 .offset = pBindInfo->memoryOffset,
2702 };
2703 } else {
2704 buffer->address = ANV_NULL_ADDRESS;
2705 }
2706 }
2707
2708 VkResult anv_BindBufferMemory(
2709 VkDevice device,
2710 VkBuffer buffer,
2711 VkDeviceMemory memory,
2712 VkDeviceSize memoryOffset)
2713 {
2714 anv_bind_buffer_memory(
2715 &(VkBindBufferMemoryInfo) {
2716 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
2717 .buffer = buffer,
2718 .memory = memory,
2719 .memoryOffset = memoryOffset,
2720 });
2721
2722 return VK_SUCCESS;
2723 }
2724
2725 VkResult anv_BindBufferMemory2(
2726 VkDevice device,
2727 uint32_t bindInfoCount,
2728 const VkBindBufferMemoryInfo* pBindInfos)
2729 {
2730 for (uint32_t i = 0; i < bindInfoCount; i++)
2731 anv_bind_buffer_memory(&pBindInfos[i]);
2732
2733 return VK_SUCCESS;
2734 }
2735
2736 VkResult anv_QueueBindSparse(
2737 VkQueue _queue,
2738 uint32_t bindInfoCount,
2739 const VkBindSparseInfo* pBindInfo,
2740 VkFence fence)
2741 {
2742 ANV_FROM_HANDLE(anv_queue, queue, _queue);
2743 if (unlikely(queue->device->lost))
2744 return VK_ERROR_DEVICE_LOST;
2745
2746 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2747 }
2748
2749 // Event functions
2750
2751 VkResult anv_CreateEvent(
2752 VkDevice _device,
2753 const VkEventCreateInfo* pCreateInfo,
2754 const VkAllocationCallbacks* pAllocator,
2755 VkEvent* pEvent)
2756 {
2757 ANV_FROM_HANDLE(anv_device, device, _device);
2758 struct anv_state state;
2759 struct anv_event *event;
2760
2761 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2762
2763 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2764 sizeof(*event), 8);
2765 event = state.map;
2766 event->state = state;
2767 event->semaphore = VK_EVENT_RESET;
2768
2769 if (!device->info.has_llc) {
2770 /* Make sure the writes we're flushing have landed. */
2771 __builtin_ia32_mfence();
2772 __builtin_ia32_clflush(event);
2773 }
2774
2775 *pEvent = anv_event_to_handle(event);
2776
2777 return VK_SUCCESS;
2778 }
2779
2780 void anv_DestroyEvent(
2781 VkDevice _device,
2782 VkEvent _event,
2783 const VkAllocationCallbacks* pAllocator)
2784 {
2785 ANV_FROM_HANDLE(anv_device, device, _device);
2786 ANV_FROM_HANDLE(anv_event, event, _event);
2787
2788 if (!event)
2789 return;
2790
2791 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2792 }
2793
2794 VkResult anv_GetEventStatus(
2795 VkDevice _device,
2796 VkEvent _event)
2797 {
2798 ANV_FROM_HANDLE(anv_device, device, _device);
2799 ANV_FROM_HANDLE(anv_event, event, _event);
2800
2801 if (unlikely(device->lost))
2802 return VK_ERROR_DEVICE_LOST;
2803
2804 if (!device->info.has_llc) {
2805 /* Invalidate read cache before reading event written by GPU. */
2806 __builtin_ia32_clflush(event);
2807 __builtin_ia32_mfence();
2808
2809 }
2810
2811 return event->semaphore;
2812 }
2813
2814 VkResult anv_SetEvent(
2815 VkDevice _device,
2816 VkEvent _event)
2817 {
2818 ANV_FROM_HANDLE(anv_device, device, _device);
2819 ANV_FROM_HANDLE(anv_event, event, _event);
2820
2821 event->semaphore = VK_EVENT_SET;
2822
2823 if (!device->info.has_llc) {
2824 /* Make sure the writes we're flushing have landed. */
2825 __builtin_ia32_mfence();
2826 __builtin_ia32_clflush(event);
2827 }
2828
2829 return VK_SUCCESS;
2830 }
2831
2832 VkResult anv_ResetEvent(
2833 VkDevice _device,
2834 VkEvent _event)
2835 {
2836 ANV_FROM_HANDLE(anv_device, device, _device);
2837 ANV_FROM_HANDLE(anv_event, event, _event);
2838
2839 event->semaphore = VK_EVENT_RESET;
2840
2841 if (!device->info.has_llc) {
2842 /* Make sure the writes we're flushing have landed. */
2843 __builtin_ia32_mfence();
2844 __builtin_ia32_clflush(event);
2845 }
2846
2847 return VK_SUCCESS;
2848 }
2849
2850 // Buffer functions
2851
2852 VkResult anv_CreateBuffer(
2853 VkDevice _device,
2854 const VkBufferCreateInfo* pCreateInfo,
2855 const VkAllocationCallbacks* pAllocator,
2856 VkBuffer* pBuffer)
2857 {
2858 ANV_FROM_HANDLE(anv_device, device, _device);
2859 struct anv_buffer *buffer;
2860
2861 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2862
2863 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2864 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2865 if (buffer == NULL)
2866 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2867
2868 buffer->size = pCreateInfo->size;
2869 buffer->usage = pCreateInfo->usage;
2870 buffer->address = ANV_NULL_ADDRESS;
2871
2872 *pBuffer = anv_buffer_to_handle(buffer);
2873
2874 return VK_SUCCESS;
2875 }
2876
2877 void anv_DestroyBuffer(
2878 VkDevice _device,
2879 VkBuffer _buffer,
2880 const VkAllocationCallbacks* pAllocator)
2881 {
2882 ANV_FROM_HANDLE(anv_device, device, _device);
2883 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2884
2885 if (!buffer)
2886 return;
2887
2888 vk_free2(&device->alloc, pAllocator, buffer);
2889 }
2890
2891 void
2892 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2893 enum isl_format format,
2894 struct anv_address address,
2895 uint32_t range, uint32_t stride)
2896 {
2897 isl_buffer_fill_state(&device->isl_dev, state.map,
2898 .address = anv_address_physical(address),
2899 .mocs = device->default_mocs,
2900 .size_B = range,
2901 .format = format,
2902 .stride_B = stride);
2903
2904 anv_state_flush(device, state);
2905 }
2906
2907 void anv_DestroySampler(
2908 VkDevice _device,
2909 VkSampler _sampler,
2910 const VkAllocationCallbacks* pAllocator)
2911 {
2912 ANV_FROM_HANDLE(anv_device, device, _device);
2913 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2914
2915 if (!sampler)
2916 return;
2917
2918 vk_free2(&device->alloc, pAllocator, sampler);
2919 }
2920
2921 VkResult anv_CreateFramebuffer(
2922 VkDevice _device,
2923 const VkFramebufferCreateInfo* pCreateInfo,
2924 const VkAllocationCallbacks* pAllocator,
2925 VkFramebuffer* pFramebuffer)
2926 {
2927 ANV_FROM_HANDLE(anv_device, device, _device);
2928 struct anv_framebuffer *framebuffer;
2929
2930 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2931
2932 size_t size = sizeof(*framebuffer) +
2933 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2934 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2935 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2936 if (framebuffer == NULL)
2937 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2938
2939 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2940 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2941 VkImageView _iview = pCreateInfo->pAttachments[i];
2942 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2943 }
2944
2945 framebuffer->width = pCreateInfo->width;
2946 framebuffer->height = pCreateInfo->height;
2947 framebuffer->layers = pCreateInfo->layers;
2948
2949 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2950
2951 return VK_SUCCESS;
2952 }
2953
2954 void anv_DestroyFramebuffer(
2955 VkDevice _device,
2956 VkFramebuffer _fb,
2957 const VkAllocationCallbacks* pAllocator)
2958 {
2959 ANV_FROM_HANDLE(anv_device, device, _device);
2960 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2961
2962 if (!fb)
2963 return;
2964
2965 vk_free2(&device->alloc, pAllocator, fb);
2966 }
2967
2968 /* vk_icd.h does not declare this function, so we declare it here to
2969 * suppress Wmissing-prototypes.
2970 */
2971 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2972 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2973
2974 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2975 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2976 {
2977 /* For the full details on loader interface versioning, see
2978 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2979 * What follows is a condensed summary, to help you navigate the large and
2980 * confusing official doc.
2981 *
2982 * - Loader interface v0 is incompatible with later versions. We don't
2983 * support it.
2984 *
2985 * - In loader interface v1:
2986 * - The first ICD entrypoint called by the loader is
2987 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2988 * entrypoint.
2989 * - The ICD must statically expose no other Vulkan symbol unless it is
2990 * linked with -Bsymbolic.
2991 * - Each dispatchable Vulkan handle created by the ICD must be
2992 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2993 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2994 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2995 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2996 * such loader-managed surfaces.
2997 *
2998 * - Loader interface v2 differs from v1 in:
2999 * - The first ICD entrypoint called by the loader is
3000 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
3001 * statically expose this entrypoint.
3002 *
3003 * - Loader interface v3 differs from v2 in:
3004 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
3005 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
3006 * because the loader no longer does so.
3007 */
3008 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
3009 return VK_SUCCESS;
3010 }