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