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