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