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