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