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 <unistd.h>
29 #include <fcntl.h>
30 #include "drm-uapi/drm_fourcc.h"
31 #include "drm-uapi/drm.h"
32 #include <xf86drm.h>
33 
34 #include "anv_private.h"
35 #include "util/debug.h"
36 #include "util/build_id.h"
37 #include "util/disk_cache.h"
38 #include "util/mesa-sha1.h"
39 #include "util/os_file.h"
40 #include "util/os_misc.h"
41 #include "util/u_atomic.h"
42 #include "util/u_string.h"
43 #include "util/driconf.h"
44 #include "git_sha1.h"
45 #include "vk_util.h"
46 #include "common/gen_aux_map.h"
47 #include "common/gen_defines.h"
48 #include "common/gen_uuid.h"
49 #include "compiler/glsl_types.h"
50 
51 #include "genxml/gen7_pack.h"
52 
53 static const driOptionDescription anv_dri_options[] = {
54    DRI_CONF_SECTION_PERFORMANCE
55       DRI_CONF_VK_X11_OVERRIDE_MIN_IMAGE_COUNT(0)
56       DRI_CONF_VK_X11_STRICT_IMAGE_COUNT(false)
57    DRI_CONF_SECTION_END
58 
59    DRI_CONF_SECTION_DEBUG
60       DRI_CONF_ALWAYS_FLUSH_CACHE(false)
61       DRI_CONF_VK_WSI_FORCE_BGRA8_UNORM_FIRST(false)
62    DRI_CONF_SECTION_END
63 };
64 
65 /* This is probably far to big but it reflects the max size used for messages
66  * in OpenGLs KHR_debug.
67  */
68 #define MAX_DEBUG_MESSAGE_LENGTH    4096
69 
70 /* Render engine timestamp register */
71 #define TIMESTAMP 0x2358
72 
73 /* The "RAW" clocks on Linux are called "FAST" on FreeBSD */
74 #if !defined(CLOCK_MONOTONIC_RAW) && defined(CLOCK_MONOTONIC_FAST)
75 #define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC_FAST
76 #endif
77 
78 static void
compiler_debug_log(void * data,const char * fmt,...)79 compiler_debug_log(void *data, const char *fmt, ...)
80 {
81    char str[MAX_DEBUG_MESSAGE_LENGTH];
82    struct anv_device *device = (struct anv_device *)data;
83    struct anv_instance *instance = device->physical->instance;
84 
85    if (list_is_empty(&instance->debug_report_callbacks.callbacks))
86       return;
87 
88    va_list args;
89    va_start(args, fmt);
90    (void) vsnprintf(str, MAX_DEBUG_MESSAGE_LENGTH, fmt, args);
91    va_end(args);
92 
93    vk_debug_report(&instance->debug_report_callbacks,
94                    VK_DEBUG_REPORT_DEBUG_BIT_EXT,
95                    VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
96                    0, 0, 0, "anv", str);
97 }
98 
99 static void
compiler_perf_log(void * data,const char * fmt,...)100 compiler_perf_log(void *data, const char *fmt, ...)
101 {
102    va_list args;
103    va_start(args, fmt);
104 
105    if (INTEL_DEBUG & DEBUG_PERF)
106       mesa_logd_v(fmt, args);
107 
108    va_end(args);
109 }
110 
111 static uint64_t
anv_compute_heap_size(int fd,uint64_t gtt_size)112 anv_compute_heap_size(int fd, uint64_t gtt_size)
113 {
114    /* Query the total ram from the system */
115    uint64_t total_ram;
116    if (!os_get_total_physical_memory(&total_ram))
117       return 0;
118 
119    /* We don't want to burn too much ram with the GPU.  If the user has 4GiB
120     * or less, we use at most half.  If they have more than 4GiB, we use 3/4.
121     */
122    uint64_t available_ram;
123    if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
124       available_ram = total_ram / 2;
125    else
126       available_ram = total_ram * 3 / 4;
127 
128    /* We also want to leave some padding for things we allocate in the driver,
129     * so don't go over 3/4 of the GTT either.
130     */
131    uint64_t available_gtt = gtt_size * 3 / 4;
132 
133    return MIN2(available_ram, available_gtt);
134 }
135 
136 static VkResult
anv_physical_device_init_heaps(struct anv_physical_device * device,int fd)137 anv_physical_device_init_heaps(struct anv_physical_device *device, int fd)
138 {
139    if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
140                                  &device->gtt_size) == -1) {
141       /* If, for whatever reason, we can't actually get the GTT size from the
142        * kernel (too old?) fall back to the aperture size.
143        */
144       anv_perf_warn(NULL, NULL,
145                     "Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
146 
147       if (gen_get_aperture_size(fd, &device->gtt_size) == -1) {
148          return vk_errorfi(device->instance, NULL,
149                            VK_ERROR_INITIALIZATION_FAILED,
150                            "failed to get aperture size: %m");
151       }
152    }
153 
154    /* We only allow 48-bit addresses with softpin because knowing the actual
155     * address is required for the vertex cache flush workaround.
156     */
157    device->supports_48bit_addresses = (device->info.gen >= 8) &&
158                                       device->has_softpin &&
159                                       device->gtt_size > (4ULL << 30 /* GiB */);
160 
161    uint64_t heap_size = anv_compute_heap_size(fd, device->gtt_size);
162 
163    if (heap_size > (2ull << 30) && !device->supports_48bit_addresses) {
164       /* When running with an overridden PCI ID, we may get a GTT size from
165        * the kernel that is greater than 2 GiB but the execbuf check for 48bit
166        * address support can still fail.  Just clamp the address space size to
167        * 2 GiB if we don't have 48-bit support.
168        */
169       mesa_logw("%s:%d: The kernel reported a GTT size larger than 2 GiB but "
170                         "not support for 48-bit addresses",
171                         __FILE__, __LINE__);
172       heap_size = 2ull << 30;
173    }
174 
175    device->memory.heap_count = 1;
176    device->memory.heaps[0] = (struct anv_memory_heap) {
177       .size = heap_size,
178       .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
179    };
180 
181    uint32_t type_count = 0;
182    for (uint32_t heap = 0; heap < device->memory.heap_count; heap++) {
183       if (device->info.has_llc) {
184          /* Big core GPUs share LLC with the CPU and thus one memory type can be
185           * both cached and coherent at the same time.
186           */
187          device->memory.types[type_count++] = (struct anv_memory_type) {
188             .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
189                              VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
190                              VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
191                              VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
192             .heapIndex = heap,
193          };
194       } else {
195          /* The spec requires that we expose a host-visible, coherent memory
196           * type, but Atom GPUs don't share LLC. Thus we offer two memory types
197           * to give the application a choice between cached, but not coherent and
198           * coherent but uncached (WC though).
199           */
200          device->memory.types[type_count++] = (struct anv_memory_type) {
201             .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
202                              VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
203                              VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
204             .heapIndex = heap,
205          };
206          device->memory.types[type_count++] = (struct anv_memory_type) {
207             .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
208                              VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
209                              VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
210             .heapIndex = heap,
211          };
212       }
213    }
214    device->memory.type_count = type_count;
215 
216    return VK_SUCCESS;
217 }
218 
219 static VkResult
anv_physical_device_init_uuids(struct anv_physical_device * device)220 anv_physical_device_init_uuids(struct anv_physical_device *device)
221 {
222    const struct build_id_note *note =
223       build_id_find_nhdr_for_addr(anv_physical_device_init_uuids);
224    if (!note) {
225       return vk_errorfi(device->instance, NULL,
226                         VK_ERROR_INITIALIZATION_FAILED,
227                         "Failed to find build-id");
228    }
229 
230    unsigned build_id_len = build_id_length(note);
231    if (build_id_len < 20) {
232       return vk_errorfi(device->instance, NULL,
233                         VK_ERROR_INITIALIZATION_FAILED,
234                         "build-id too short.  It needs to be a SHA");
235    }
236 
237    memcpy(device->driver_build_sha1, build_id_data(note), 20);
238 
239    struct mesa_sha1 sha1_ctx;
240    uint8_t sha1[20];
241    STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
242 
243    /* The pipeline cache UUID is used for determining when a pipeline cache is
244     * invalid.  It needs both a driver build and the PCI ID of the device.
245     */
246    _mesa_sha1_init(&sha1_ctx);
247    _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
248    _mesa_sha1_update(&sha1_ctx, &device->info.chipset_id,
249                      sizeof(device->info.chipset_id));
250    _mesa_sha1_update(&sha1_ctx, &device->always_use_bindless,
251                      sizeof(device->always_use_bindless));
252    _mesa_sha1_update(&sha1_ctx, &device->has_a64_buffer_access,
253                      sizeof(device->has_a64_buffer_access));
254    _mesa_sha1_update(&sha1_ctx, &device->has_bindless_images,
255                      sizeof(device->has_bindless_images));
256    _mesa_sha1_update(&sha1_ctx, &device->has_bindless_samplers,
257                      sizeof(device->has_bindless_samplers));
258    _mesa_sha1_final(&sha1_ctx, sha1);
259    memcpy(device->pipeline_cache_uuid, sha1, VK_UUID_SIZE);
260 
261    gen_uuid_compute_driver_id(device->driver_uuid, &device->info, VK_UUID_SIZE);
262    gen_uuid_compute_device_id(device->device_uuid, &device->isl_dev, VK_UUID_SIZE);
263 
264    return VK_SUCCESS;
265 }
266 
267 static void
anv_physical_device_init_disk_cache(struct anv_physical_device * device)268 anv_physical_device_init_disk_cache(struct anv_physical_device *device)
269 {
270 #ifdef ENABLE_SHADER_CACHE
271    char renderer[10];
272    ASSERTED int len = snprintf(renderer, sizeof(renderer), "anv_%04x",
273                                device->info.chipset_id);
274    assert(len == sizeof(renderer) - 2);
275 
276    char timestamp[41];
277    _mesa_sha1_format(timestamp, device->driver_build_sha1);
278 
279    const uint64_t driver_flags =
280       brw_get_compiler_config_value(device->compiler);
281    device->disk_cache = disk_cache_create(renderer, timestamp, driver_flags);
282 #else
283    device->disk_cache = NULL;
284 #endif
285 }
286 
287 static void
anv_physical_device_free_disk_cache(struct anv_physical_device * device)288 anv_physical_device_free_disk_cache(struct anv_physical_device *device)
289 {
290 #ifdef ENABLE_SHADER_CACHE
291    if (device->disk_cache)
292       disk_cache_destroy(device->disk_cache);
293 #else
294    assert(device->disk_cache == NULL);
295 #endif
296 }
297 
298 static VkResult
anv_physical_device_try_create(struct anv_instance * instance,drmDevicePtr drm_device,struct anv_physical_device ** device_out)299 anv_physical_device_try_create(struct anv_instance *instance,
300                                drmDevicePtr drm_device,
301                                struct anv_physical_device **device_out)
302 {
303    const char *primary_path = drm_device->nodes[DRM_NODE_PRIMARY];
304    const char *path = drm_device->nodes[DRM_NODE_RENDER];
305    VkResult result;
306    int fd;
307    int master_fd = -1;
308 
309    brw_process_intel_debug_variable();
310 
311    fd = open(path, O_RDWR | O_CLOEXEC);
312    if (fd < 0) {
313       if (errno == ENOMEM) {
314          return vk_errorfi(instance, NULL, VK_ERROR_OUT_OF_HOST_MEMORY,
315                         "Unable to open device %s: out of memory", path);
316       }
317       return vk_errorfi(instance, NULL, VK_ERROR_INCOMPATIBLE_DRIVER,
318                         "Unable to open device %s: %m", path);
319    }
320 
321    struct gen_device_info devinfo;
322    if (!gen_get_device_info_from_fd(fd, &devinfo)) {
323       result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
324       goto fail_fd;
325    }
326 
327    const char *device_name = gen_get_device_name(devinfo.chipset_id);
328 
329    if (devinfo.is_haswell) {
330       mesa_logw("Haswell Vulkan support is incomplete");
331    } else if (devinfo.gen == 7 && !devinfo.is_baytrail) {
332       mesa_logw("Ivy Bridge Vulkan support is incomplete");
333    } else if (devinfo.gen == 7 && devinfo.is_baytrail) {
334       mesa_logw("Bay Trail Vulkan support is incomplete");
335    } else if (devinfo.gen >= 8 && devinfo.gen <= 12) {
336       /* Gen8-12 fully supported */
337    } else {
338       result = vk_errorfi(instance, NULL, VK_ERROR_INCOMPATIBLE_DRIVER,
339                           "Vulkan not yet supported on %s", device_name);
340       goto fail_fd;
341    }
342 
343    struct anv_physical_device *device =
344       vk_alloc(&instance->alloc, sizeof(*device), 8,
345                VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
346    if (device == NULL) {
347       result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
348       goto fail_fd;
349    }
350 
351    vk_object_base_init(NULL, &device->base, VK_OBJECT_TYPE_PHYSICAL_DEVICE);
352    device->instance = instance;
353 
354    assert(strlen(path) < ARRAY_SIZE(device->path));
355    snprintf(device->path, ARRAY_SIZE(device->path), "%s", path);
356 
357    device->info = devinfo;
358    device->name = device_name;
359 
360    device->no_hw = device->info.no_hw;
361    if (getenv("INTEL_NO_HW") != NULL)
362       device->no_hw = true;
363 
364    device->pci_info.domain = drm_device->businfo.pci->domain;
365    device->pci_info.bus = drm_device->businfo.pci->bus;
366    device->pci_info.device = drm_device->businfo.pci->dev;
367    device->pci_info.function = drm_device->businfo.pci->func;
368 
369    device->cmd_parser_version = -1;
370    if (device->info.gen == 7) {
371       device->cmd_parser_version =
372          anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
373       if (device->cmd_parser_version == -1) {
374          result = vk_errorfi(device->instance, NULL,
375                              VK_ERROR_INITIALIZATION_FAILED,
376                              "failed to get command parser version");
377          goto fail_alloc;
378       }
379    }
380 
381    if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
382       result = vk_errorfi(device->instance, NULL,
383                           VK_ERROR_INITIALIZATION_FAILED,
384                           "kernel missing gem wait");
385       goto fail_alloc;
386    }
387 
388    if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
389       result = vk_errorfi(device->instance, NULL,
390                           VK_ERROR_INITIALIZATION_FAILED,
391                           "kernel missing execbuf2");
392       goto fail_alloc;
393    }
394 
395    if (!device->info.has_llc &&
396        anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
397       result = vk_errorfi(device->instance, NULL,
398                           VK_ERROR_INITIALIZATION_FAILED,
399                           "kernel missing wc mmap");
400       goto fail_alloc;
401    }
402 
403    device->has_softpin = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_SOFTPIN);
404    device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
405    device->has_exec_capture = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_CAPTURE);
406    device->has_exec_fence = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE);
407    device->has_syncobj = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE_ARRAY);
408    device->has_syncobj_wait = device->has_syncobj &&
409                               anv_gem_supports_syncobj_wait(fd);
410    device->has_syncobj_wait_available =
411       anv_gem_get_drm_cap(fd, DRM_CAP_SYNCOBJ_TIMELINE) != 0;
412 
413    device->has_context_priority = anv_gem_has_context_priority(fd);
414 
415    result = anv_physical_device_init_heaps(device, fd);
416    if (result != VK_SUCCESS)
417       goto fail_alloc;
418 
419    device->use_softpin = device->has_softpin &&
420                          device->supports_48bit_addresses;
421 
422    device->has_context_isolation =
423       anv_gem_get_param(fd, I915_PARAM_HAS_CONTEXT_ISOLATION);
424 
425    device->has_exec_timeline =
426       anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_TIMELINE_FENCES);
427    if (env_var_as_boolean("ANV_QUEUE_THREAD_DISABLE", false))
428       device->has_exec_timeline = false;
429 
430    device->has_thread_submit =
431       device->has_syncobj_wait_available && device->has_exec_timeline;
432 
433    device->always_use_bindless =
434       env_var_as_boolean("ANV_ALWAYS_BINDLESS", false);
435 
436    device->use_call_secondary =
437       device->use_softpin &&
438       !env_var_as_boolean("ANV_DISABLE_SECONDARY_CMD_BUFFER_CALLS", false);
439 
440    /* We first got the A64 messages on broadwell and we can only use them if
441     * we can pass addresses directly into the shader which requires softpin.
442     */
443    device->has_a64_buffer_access = device->info.gen >= 8 &&
444                                    device->use_softpin;
445 
446    /* We first get bindless image access on Skylake and we can only really do
447     * it if we don't have any relocations so we need softpin.
448     */
449    device->has_bindless_images = device->info.gen >= 9 &&
450                                  device->use_softpin;
451 
452    /* We've had bindless samplers since Ivy Bridge (forever in Vulkan terms)
453     * because it's just a matter of setting the sampler address in the sample
454     * message header.  However, we've not bothered to wire it up for vec4 so
455     * we leave it disabled on gen7.
456     */
457    device->has_bindless_samplers = device->info.gen >= 8;
458 
459    device->has_implicit_ccs = device->info.has_aux_map;
460 
461    /* Check if we can read the GPU timestamp register from the CPU */
462    uint64_t u64_ignore;
463    device->has_reg_timestamp = anv_gem_reg_read(fd, TIMESTAMP | I915_REG_READ_8B_WA,
464                                                 &u64_ignore) == 0;
465 
466    uint64_t avail_mem;
467    device->has_mem_available = os_get_available_system_memory(&avail_mem);
468 
469    device->always_flush_cache =
470       driQueryOptionb(&instance->dri_options, "always_flush_cache");
471 
472    device->has_mmap_offset =
473       anv_gem_get_param(fd, I915_PARAM_MMAP_GTT_VERSION) >= 4;
474 
475    /* GENs prior to 8 do not support EU/Subslice info */
476    if (device->info.gen >= 8) {
477       device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
478       device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
479 
480       /* Without this information, we cannot get the right Braswell
481        * brandstrings, and we have to use conservative numbers for GPGPU on
482        * many platforms, but otherwise, things will just work.
483        */
484       if (device->subslice_total < 1 || device->eu_total < 1) {
485          mesa_logw("Kernel 4.1 required to properly query GPU properties");
486       }
487    } else if (device->info.gen == 7) {
488       device->subslice_total = 1 << (device->info.gt - 1);
489    }
490 
491    if (device->info.is_cherryview &&
492        device->subslice_total > 0 && device->eu_total > 0) {
493       /* Logical CS threads = EUs per subslice * num threads per EU */
494       uint32_t max_cs_threads =
495          device->eu_total / device->subslice_total * device->info.num_thread_per_eu;
496 
497       /* Fuse configurations may give more threads than expected, never less. */
498       if (max_cs_threads > device->info.max_cs_threads)
499          device->info.max_cs_threads = max_cs_threads;
500    }
501 
502    device->compiler = brw_compiler_create(NULL, &device->info);
503    if (device->compiler == NULL) {
504       result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
505       goto fail_alloc;
506    }
507    device->compiler->shader_debug_log = compiler_debug_log;
508    device->compiler->shader_perf_log = compiler_perf_log;
509    device->compiler->supports_pull_constants = false;
510    device->compiler->constant_buffer_0_is_relative =
511       device->info.gen < 8 || !device->has_context_isolation;
512    device->compiler->supports_shader_constants = true;
513    device->compiler->compact_params = false;
514    device->compiler->indirect_ubos_use_sampler = device->info.gen < 12;
515 
516    /* Broadwell PRM says:
517     *
518     *   "Before Gen8, there was a historical configuration control field to
519     *    swizzle address bit[6] for in X/Y tiling modes. This was set in three
520     *    different places: TILECTL[1:0], ARB_MODE[5:4], and
521     *    DISP_ARB_CTL[14:13].
522     *
523     *    For Gen8 and subsequent generations, the swizzle fields are all
524     *    reserved, and the CPU's memory controller performs all address
525     *    swizzling modifications."
526     */
527    bool swizzled =
528       device->info.gen < 8 && anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
529 
530    isl_device_init(&device->isl_dev, &device->info, swizzled);
531 
532    result = anv_physical_device_init_uuids(device);
533    if (result != VK_SUCCESS)
534       goto fail_compiler;
535 
536    anv_physical_device_init_disk_cache(device);
537 
538    if (instance->enabled_extensions.KHR_display) {
539       master_fd = open(primary_path, O_RDWR | O_CLOEXEC);
540       if (master_fd >= 0) {
541          /* prod the device with a GETPARAM call which will fail if
542           * we don't have permission to even render on this device
543           */
544          if (anv_gem_get_param(master_fd, I915_PARAM_CHIPSET_ID) == 0) {
545             close(master_fd);
546             master_fd = -1;
547          }
548       }
549    }
550    device->master_fd = master_fd;
551 
552    result = anv_init_wsi(device);
553    if (result != VK_SUCCESS)
554       goto fail_disk_cache;
555 
556    device->perf = anv_get_perf(&device->info, fd);
557 
558    anv_physical_device_get_supported_extensions(device,
559                                                 &device->supported_extensions);
560 
561 
562    device->local_fd = fd;
563 
564    *device_out = device;
565 
566    return VK_SUCCESS;
567 
568 fail_disk_cache:
569    anv_physical_device_free_disk_cache(device);
570 fail_compiler:
571    ralloc_free(device->compiler);
572 fail_alloc:
573    vk_free(&instance->alloc, device);
574 fail_fd:
575    close(fd);
576    if (master_fd != -1)
577       close(master_fd);
578    return result;
579 }
580 
581 static void
anv_physical_device_destroy(struct anv_physical_device * device)582 anv_physical_device_destroy(struct anv_physical_device *device)
583 {
584    anv_finish_wsi(device);
585    anv_physical_device_free_disk_cache(device);
586    ralloc_free(device->compiler);
587    ralloc_free(device->perf);
588    close(device->local_fd);
589    if (device->master_fd >= 0)
590       close(device->master_fd);
591    vk_object_base_finish(&device->base);
592    vk_free(&device->instance->alloc, device);
593 }
594 
595 static void *
default_alloc_func(void * pUserData,size_t size,size_t align,VkSystemAllocationScope allocationScope)596 default_alloc_func(void *pUserData, size_t size, size_t align,
597                    VkSystemAllocationScope allocationScope)
598 {
599    return malloc(size);
600 }
601 
602 static void *
default_realloc_func(void * pUserData,void * pOriginal,size_t size,size_t align,VkSystemAllocationScope allocationScope)603 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
604                      size_t align, VkSystemAllocationScope allocationScope)
605 {
606    return realloc(pOriginal, size);
607 }
608 
609 static void
default_free_func(void * pUserData,void * pMemory)610 default_free_func(void *pUserData, void *pMemory)
611 {
612    free(pMemory);
613 }
614 
615 static const VkAllocationCallbacks default_alloc = {
616    .pUserData = NULL,
617    .pfnAllocation = default_alloc_func,
618    .pfnReallocation = default_realloc_func,
619    .pfnFree = default_free_func,
620 };
621 
anv_EnumerateInstanceExtensionProperties(const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)622 VkResult anv_EnumerateInstanceExtensionProperties(
623     const char*                                 pLayerName,
624     uint32_t*                                   pPropertyCount,
625     VkExtensionProperties*                      pProperties)
626 {
627    VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
628 
629    for (int i = 0; i < ANV_INSTANCE_EXTENSION_COUNT; i++) {
630       if (anv_instance_extensions_supported.extensions[i]) {
631          vk_outarray_append(&out, prop) {
632             *prop = anv_instance_extensions[i];
633          }
634       }
635    }
636 
637    return vk_outarray_status(&out);
638 }
639 
640 static void
anv_init_dri_options(struct anv_instance * instance)641 anv_init_dri_options(struct anv_instance *instance)
642 {
643    driParseOptionInfo(&instance->available_dri_options, anv_dri_options,
644                       ARRAY_SIZE(anv_dri_options));
645    driParseConfigFiles(&instance->dri_options,
646                        &instance->available_dri_options, 0, "anv", NULL,
647                        instance->app_info.app_name,
648                        instance->app_info.app_version,
649                        instance->app_info.engine_name,
650                        instance->app_info.engine_version);
651 }
652 
anv_CreateInstance(const VkInstanceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkInstance * pInstance)653 VkResult anv_CreateInstance(
654     const VkInstanceCreateInfo*                 pCreateInfo,
655     const VkAllocationCallbacks*                pAllocator,
656     VkInstance*                                 pInstance)
657 {
658    struct anv_instance *instance;
659    VkResult result;
660 
661    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
662 
663    struct anv_instance_extension_table enabled_extensions = {};
664    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
665       int idx;
666       for (idx = 0; idx < ANV_INSTANCE_EXTENSION_COUNT; idx++) {
667          if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
668                     anv_instance_extensions[idx].extensionName) == 0)
669             break;
670       }
671 
672       if (idx >= ANV_INSTANCE_EXTENSION_COUNT)
673          return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
674 
675       if (!anv_instance_extensions_supported.extensions[idx])
676          return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
677 
678       enabled_extensions.extensions[idx] = true;
679    }
680 
681    instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
682                          VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
683    if (!instance)
684       return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
685 
686    vk_object_base_init(NULL, &instance->base, VK_OBJECT_TYPE_INSTANCE);
687 
688    if (pAllocator)
689       instance->alloc = *pAllocator;
690    else
691       instance->alloc = default_alloc;
692 
693    instance->app_info = (struct anv_app_info) { .api_version = 0 };
694    if (pCreateInfo->pApplicationInfo) {
695       const VkApplicationInfo *app = pCreateInfo->pApplicationInfo;
696 
697       instance->app_info.app_name =
698          vk_strdup(&instance->alloc, app->pApplicationName,
699                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
700       instance->app_info.app_version = app->applicationVersion;
701 
702       instance->app_info.engine_name =
703          vk_strdup(&instance->alloc, app->pEngineName,
704                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
705       instance->app_info.engine_version = app->engineVersion;
706 
707       instance->app_info.api_version = app->apiVersion;
708    }
709 
710    if (instance->app_info.api_version == 0)
711       instance->app_info.api_version = VK_API_VERSION_1_0;
712 
713    instance->enabled_extensions = enabled_extensions;
714 
715    for (unsigned i = 0; i < ARRAY_SIZE(instance->dispatch.entrypoints); i++) {
716       /* Vulkan requires that entrypoints for extensions which have not been
717        * enabled must not be advertised.
718        */
719       if (!anv_instance_entrypoint_is_enabled(i, instance->app_info.api_version,
720                                               &instance->enabled_extensions)) {
721          instance->dispatch.entrypoints[i] = NULL;
722       } else {
723          instance->dispatch.entrypoints[i] =
724             anv_instance_dispatch_table.entrypoints[i];
725       }
726    }
727 
728    for (unsigned i = 0; i < ARRAY_SIZE(instance->physical_device_dispatch.entrypoints); i++) {
729       /* Vulkan requires that entrypoints for extensions which have not been
730        * enabled must not be advertised.
731        */
732       if (!anv_physical_device_entrypoint_is_enabled(i, instance->app_info.api_version,
733                                                      &instance->enabled_extensions)) {
734          instance->physical_device_dispatch.entrypoints[i] = NULL;
735       } else {
736          instance->physical_device_dispatch.entrypoints[i] =
737             anv_physical_device_dispatch_table.entrypoints[i];
738       }
739    }
740 
741    for (unsigned i = 0; i < ARRAY_SIZE(instance->device_dispatch.entrypoints); i++) {
742       /* Vulkan requires that entrypoints for extensions which have not been
743        * enabled must not be advertised.
744        */
745       if (!anv_device_entrypoint_is_enabled(i, instance->app_info.api_version,
746                                             &instance->enabled_extensions, NULL)) {
747          instance->device_dispatch.entrypoints[i] = NULL;
748       } else {
749          instance->device_dispatch.entrypoints[i] =
750             anv_device_dispatch_table.entrypoints[i];
751       }
752    }
753 
754    instance->physical_devices_enumerated = false;
755    list_inithead(&instance->physical_devices);
756 
757    result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
758    if (result != VK_SUCCESS) {
759       vk_free2(&default_alloc, pAllocator, instance);
760       return vk_error(result);
761    }
762 
763    instance->pipeline_cache_enabled =
764       env_var_as_boolean("ANV_ENABLE_PIPELINE_CACHE", true);
765 
766    glsl_type_singleton_init_or_ref();
767 
768    VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
769 
770    anv_init_dri_options(instance);
771 
772    *pInstance = anv_instance_to_handle(instance);
773 
774    return VK_SUCCESS;
775 }
776 
anv_DestroyInstance(VkInstance _instance,const VkAllocationCallbacks * pAllocator)777 void anv_DestroyInstance(
778     VkInstance                                  _instance,
779     const VkAllocationCallbacks*                pAllocator)
780 {
781    ANV_FROM_HANDLE(anv_instance, instance, _instance);
782 
783    if (!instance)
784       return;
785 
786    list_for_each_entry_safe(struct anv_physical_device, pdevice,
787                             &instance->physical_devices, link)
788       anv_physical_device_destroy(pdevice);
789 
790    vk_free(&instance->alloc, (char *)instance->app_info.app_name);
791    vk_free(&instance->alloc, (char *)instance->app_info.engine_name);
792 
793    VG(VALGRIND_DESTROY_MEMPOOL(instance));
794 
795    vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
796 
797    glsl_type_singleton_decref();
798 
799    driDestroyOptionCache(&instance->dri_options);
800    driDestroyOptionInfo(&instance->available_dri_options);
801 
802    vk_object_base_finish(&instance->base);
803    vk_free(&instance->alloc, instance);
804 }
805 
806 static VkResult
anv_enumerate_physical_devices(struct anv_instance * instance)807 anv_enumerate_physical_devices(struct anv_instance *instance)
808 {
809    if (instance->physical_devices_enumerated)
810       return VK_SUCCESS;
811 
812    instance->physical_devices_enumerated = true;
813 
814    /* TODO: Check for more devices ? */
815    drmDevicePtr devices[8];
816    int max_devices;
817 
818    max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
819    if (max_devices < 1)
820       return VK_SUCCESS;
821 
822    VkResult result = VK_SUCCESS;
823    for (unsigned i = 0; i < (unsigned)max_devices; i++) {
824       if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
825           devices[i]->bustype == DRM_BUS_PCI &&
826           devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
827 
828          struct anv_physical_device *pdevice;
829          result = anv_physical_device_try_create(instance, devices[i],
830                                                  &pdevice);
831          /* Incompatible DRM device, skip. */
832          if (result == VK_ERROR_INCOMPATIBLE_DRIVER) {
833             result = VK_SUCCESS;
834             continue;
835          }
836 
837          /* Error creating the physical device, report the error. */
838          if (result != VK_SUCCESS)
839             break;
840 
841          list_addtail(&pdevice->link, &instance->physical_devices);
842       }
843    }
844    drmFreeDevices(devices, max_devices);
845 
846    /* If we successfully enumerated any devices, call it success */
847    return result;
848 }
849 
anv_EnumeratePhysicalDevices(VkInstance _instance,uint32_t * pPhysicalDeviceCount,VkPhysicalDevice * pPhysicalDevices)850 VkResult anv_EnumeratePhysicalDevices(
851     VkInstance                                  _instance,
852     uint32_t*                                   pPhysicalDeviceCount,
853     VkPhysicalDevice*                           pPhysicalDevices)
854 {
855    ANV_FROM_HANDLE(anv_instance, instance, _instance);
856    VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
857 
858    VkResult result = anv_enumerate_physical_devices(instance);
859    if (result != VK_SUCCESS)
860       return result;
861 
862    list_for_each_entry(struct anv_physical_device, pdevice,
863                        &instance->physical_devices, link) {
864       vk_outarray_append(&out, i) {
865          *i = anv_physical_device_to_handle(pdevice);
866       }
867    }
868 
869    return vk_outarray_status(&out);
870 }
871 
anv_EnumeratePhysicalDeviceGroups(VkInstance _instance,uint32_t * pPhysicalDeviceGroupCount,VkPhysicalDeviceGroupProperties * pPhysicalDeviceGroupProperties)872 VkResult anv_EnumeratePhysicalDeviceGroups(
873     VkInstance                                  _instance,
874     uint32_t*                                   pPhysicalDeviceGroupCount,
875     VkPhysicalDeviceGroupProperties*            pPhysicalDeviceGroupProperties)
876 {
877    ANV_FROM_HANDLE(anv_instance, instance, _instance);
878    VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
879                          pPhysicalDeviceGroupCount);
880 
881    VkResult result = anv_enumerate_physical_devices(instance);
882    if (result != VK_SUCCESS)
883       return result;
884 
885    list_for_each_entry(struct anv_physical_device, pdevice,
886                        &instance->physical_devices, link) {
887       vk_outarray_append(&out, p) {
888          p->physicalDeviceCount = 1;
889          memset(p->physicalDevices, 0, sizeof(p->physicalDevices));
890          p->physicalDevices[0] = anv_physical_device_to_handle(pdevice);
891          p->subsetAllocation = false;
892 
893          vk_foreach_struct(ext, p->pNext)
894             anv_debug_ignored_stype(ext->sType);
895       }
896    }
897 
898    return vk_outarray_status(&out);
899 }
900 
anv_GetPhysicalDeviceFeatures(VkPhysicalDevice physicalDevice,VkPhysicalDeviceFeatures * pFeatures)901 void anv_GetPhysicalDeviceFeatures(
902     VkPhysicalDevice                            physicalDevice,
903     VkPhysicalDeviceFeatures*                   pFeatures)
904 {
905    ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
906 
907    *pFeatures = (VkPhysicalDeviceFeatures) {
908       .robustBufferAccess                       = true,
909       .fullDrawIndexUint32                      = true,
910       .imageCubeArray                           = true,
911       .independentBlend                         = true,
912       .geometryShader                           = true,
913       .tessellationShader                       = true,
914       .sampleRateShading                        = true,
915       .dualSrcBlend                             = true,
916       .logicOp                                  = true,
917       .multiDrawIndirect                        = true,
918       .drawIndirectFirstInstance                = true,
919       .depthClamp                               = true,
920       .depthBiasClamp                           = true,
921       .fillModeNonSolid                         = true,
922       .depthBounds                              = pdevice->info.gen >= 12,
923       .wideLines                                = true,
924       .largePoints                              = true,
925       .alphaToOne                               = true,
926       .multiViewport                            = true,
927       .samplerAnisotropy                        = true,
928       .textureCompressionETC2                   = pdevice->info.gen >= 8 ||
929                                                   pdevice->info.is_baytrail,
930       .textureCompressionASTC_LDR               = pdevice->info.gen >= 9, /* FINISHME CHV */
931       .textureCompressionBC                     = true,
932       .occlusionQueryPrecise                    = true,
933       .pipelineStatisticsQuery                  = true,
934       .fragmentStoresAndAtomics                 = true,
935       .shaderTessellationAndGeometryPointSize   = true,
936       .shaderImageGatherExtended                = true,
937       .shaderStorageImageExtendedFormats        = true,
938       .shaderStorageImageMultisample            = false,
939       .shaderStorageImageReadWithoutFormat      = false,
940       .shaderStorageImageWriteWithoutFormat     = true,
941       .shaderUniformBufferArrayDynamicIndexing  = true,
942       .shaderSampledImageArrayDynamicIndexing   = true,
943       .shaderStorageBufferArrayDynamicIndexing  = true,
944       .shaderStorageImageArrayDynamicIndexing   = true,
945       .shaderClipDistance                       = true,
946       .shaderCullDistance                       = true,
947       .shaderFloat64                            = pdevice->info.gen >= 8 &&
948                                                   pdevice->info.has_64bit_float,
949       .shaderInt64                              = pdevice->info.gen >= 8 &&
950                                                   pdevice->info.has_64bit_int,
951       .shaderInt16                              = pdevice->info.gen >= 8,
952       .shaderResourceMinLod                     = pdevice->info.gen >= 9,
953       .variableMultisampleRate                  = true,
954       .inheritedQueries                         = true,
955    };
956 
957    /* We can't do image stores in vec4 shaders */
958    pFeatures->vertexPipelineStoresAndAtomics =
959       pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
960       pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
961 
962    struct anv_app_info *app_info = &pdevice->instance->app_info;
963 
964    /* The new DOOM and Wolfenstein games require depthBounds without
965     * checking for it.  They seem to run fine without it so just claim it's
966     * there and accept the consequences.
967     */
968    if (app_info->engine_name && strcmp(app_info->engine_name, "idTech") == 0)
969       pFeatures->depthBounds = true;
970 }
971 
972 static void
anv_get_physical_device_features_1_1(struct anv_physical_device * pdevice,VkPhysicalDeviceVulkan11Features * f)973 anv_get_physical_device_features_1_1(struct anv_physical_device *pdevice,
974                                      VkPhysicalDeviceVulkan11Features *f)
975 {
976    assert(f->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
977 
978    f->storageBuffer16BitAccess            = pdevice->info.gen >= 8;
979    f->uniformAndStorageBuffer16BitAccess  = pdevice->info.gen >= 8;
980    f->storagePushConstant16               = pdevice->info.gen >= 8;
981    f->storageInputOutput16                = false;
982    f->multiview                           = true;
983    f->multiviewGeometryShader             = true;
984    f->multiviewTessellationShader         = true;
985    f->variablePointersStorageBuffer       = true;
986    f->variablePointers                    = true;
987    f->protectedMemory                     = false;
988    f->samplerYcbcrConversion              = true;
989    f->shaderDrawParameters                = true;
990 }
991 
992 static void
anv_get_physical_device_features_1_2(struct anv_physical_device * pdevice,VkPhysicalDeviceVulkan12Features * f)993 anv_get_physical_device_features_1_2(struct anv_physical_device *pdevice,
994                                      VkPhysicalDeviceVulkan12Features *f)
995 {
996    assert(f->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES);
997 
998    f->samplerMirrorClampToEdge            = true;
999    f->drawIndirectCount                   = true;
1000    f->storageBuffer8BitAccess             = pdevice->info.gen >= 8;
1001    f->uniformAndStorageBuffer8BitAccess   = pdevice->info.gen >= 8;
1002    f->storagePushConstant8                = pdevice->info.gen >= 8;
1003    f->shaderBufferInt64Atomics            = pdevice->info.gen >= 9 &&
1004                                             pdevice->use_softpin;
1005    f->shaderSharedInt64Atomics            = false;
1006    f->shaderFloat16                       = pdevice->info.gen >= 8;
1007    f->shaderInt8                          = pdevice->info.gen >= 8;
1008 
1009    bool descIndexing = pdevice->has_a64_buffer_access &&
1010                        pdevice->has_bindless_images;
1011    f->descriptorIndexing                                 = descIndexing;
1012    f->shaderInputAttachmentArrayDynamicIndexing          = false;
1013    f->shaderUniformTexelBufferArrayDynamicIndexing       = descIndexing;
1014    f->shaderStorageTexelBufferArrayDynamicIndexing       = descIndexing;
1015    f->shaderUniformBufferArrayNonUniformIndexing         = false;
1016    f->shaderSampledImageArrayNonUniformIndexing          = descIndexing;
1017    f->shaderStorageBufferArrayNonUniformIndexing         = descIndexing;
1018    f->shaderStorageImageArrayNonUniformIndexing          = descIndexing;
1019    f->shaderInputAttachmentArrayNonUniformIndexing       = false;
1020    f->shaderUniformTexelBufferArrayNonUniformIndexing    = descIndexing;
1021    f->shaderStorageTexelBufferArrayNonUniformIndexing    = descIndexing;
1022    f->descriptorBindingUniformBufferUpdateAfterBind      = false;
1023    f->descriptorBindingSampledImageUpdateAfterBind       = descIndexing;
1024    f->descriptorBindingStorageImageUpdateAfterBind       = descIndexing;
1025    f->descriptorBindingStorageBufferUpdateAfterBind      = descIndexing;
1026    f->descriptorBindingUniformTexelBufferUpdateAfterBind = descIndexing;
1027    f->descriptorBindingStorageTexelBufferUpdateAfterBind = descIndexing;
1028    f->descriptorBindingUpdateUnusedWhilePending          = descIndexing;
1029    f->descriptorBindingPartiallyBound                    = descIndexing;
1030    f->descriptorBindingVariableDescriptorCount           = descIndexing;
1031    f->runtimeDescriptorArray                             = descIndexing;
1032 
1033    f->samplerFilterMinmax                 = pdevice->info.gen >= 9;
1034    f->scalarBlockLayout                   = true;
1035    f->imagelessFramebuffer                = true;
1036    f->uniformBufferStandardLayout         = true;
1037    f->shaderSubgroupExtendedTypes         = true;
1038    f->separateDepthStencilLayouts         = true;
1039    f->hostQueryReset                      = true;
1040    f->timelineSemaphore                   = true;
1041    f->bufferDeviceAddress                 = pdevice->has_a64_buffer_access;
1042    f->bufferDeviceAddressCaptureReplay    = pdevice->has_a64_buffer_access;
1043    f->bufferDeviceAddressMultiDevice      = false;
1044    f->vulkanMemoryModel                   = true;
1045    f->vulkanMemoryModelDeviceScope        = true;
1046    f->vulkanMemoryModelAvailabilityVisibilityChains = true;
1047    f->shaderOutputViewportIndex           = true;
1048    f->shaderOutputLayer                   = true;
1049    f->subgroupBroadcastDynamicId          = true;
1050 }
1051 
anv_GetPhysicalDeviceFeatures2(VkPhysicalDevice physicalDevice,VkPhysicalDeviceFeatures2 * pFeatures)1052 void anv_GetPhysicalDeviceFeatures2(
1053     VkPhysicalDevice                            physicalDevice,
1054     VkPhysicalDeviceFeatures2*                  pFeatures)
1055 {
1056    ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1057    anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
1058 
1059    VkPhysicalDeviceVulkan11Features core_1_1 = {
1060       .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
1061    };
1062    anv_get_physical_device_features_1_1(pdevice, &core_1_1);
1063 
1064    VkPhysicalDeviceVulkan12Features core_1_2 = {
1065       .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
1066    };
1067    anv_get_physical_device_features_1_2(pdevice, &core_1_2);
1068 
1069 #define CORE_FEATURE(major, minor, feature) \
1070    features->feature = core_##major##_##minor.feature
1071 
1072 
1073    vk_foreach_struct(ext, pFeatures->pNext) {
1074       switch (ext->sType) {
1075       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_4444_FORMATS_FEATURES_EXT: {
1076          VkPhysicalDevice4444FormatsFeaturesEXT *features =
1077             (VkPhysicalDevice4444FormatsFeaturesEXT *)ext;
1078          features->formatA4R4G4B4 = true;
1079          features->formatA4B4G4R4 = false;
1080          break;
1081       }
1082 
1083       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
1084          VkPhysicalDevice8BitStorageFeaturesKHR *features =
1085             (VkPhysicalDevice8BitStorageFeaturesKHR *)ext;
1086          CORE_FEATURE(1, 2, storageBuffer8BitAccess);
1087          CORE_FEATURE(1, 2, uniformAndStorageBuffer8BitAccess);
1088          CORE_FEATURE(1, 2, storagePushConstant8);
1089          break;
1090       }
1091 
1092       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
1093          VkPhysicalDevice16BitStorageFeatures *features =
1094             (VkPhysicalDevice16BitStorageFeatures *)ext;
1095          CORE_FEATURE(1, 1, storageBuffer16BitAccess);
1096          CORE_FEATURE(1, 1, uniformAndStorageBuffer16BitAccess);
1097          CORE_FEATURE(1, 1, storagePushConstant16);
1098          CORE_FEATURE(1, 1, storageInputOutput16);
1099          break;
1100       }
1101 
1102       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT: {
1103          VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *features = (void *)ext;
1104          features->bufferDeviceAddress = pdevice->has_a64_buffer_access;
1105          features->bufferDeviceAddressCaptureReplay = false;
1106          features->bufferDeviceAddressMultiDevice = false;
1107          break;
1108       }
1109 
1110       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_KHR: {
1111          VkPhysicalDeviceBufferDeviceAddressFeaturesKHR *features = (void *)ext;
1112          CORE_FEATURE(1, 2, bufferDeviceAddress);
1113          CORE_FEATURE(1, 2, bufferDeviceAddressCaptureReplay);
1114          CORE_FEATURE(1, 2, bufferDeviceAddressMultiDevice);
1115          break;
1116       }
1117 
1118       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV: {
1119          VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *features =
1120             (VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *)ext;
1121          features->computeDerivativeGroupQuads = true;
1122          features->computeDerivativeGroupLinear = true;
1123          break;
1124       }
1125 
1126       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
1127          VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
1128             (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
1129          features->conditionalRendering = pdevice->info.gen >= 8 ||
1130                                           pdevice->info.is_haswell;
1131          features->inheritedConditionalRendering = pdevice->info.gen >= 8 ||
1132                                                    pdevice->info.is_haswell;
1133          break;
1134       }
1135 
1136       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT: {
1137          VkPhysicalDeviceCustomBorderColorFeaturesEXT *features =
1138             (VkPhysicalDeviceCustomBorderColorFeaturesEXT *)ext;
1139          features->customBorderColors = pdevice->info.gen >= 8;
1140          features->customBorderColorWithoutFormat = pdevice->info.gen >= 8;
1141          break;
1142       }
1143 
1144       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
1145          VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
1146             (VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
1147          features->depthClipEnable = true;
1148          break;
1149       }
1150 
1151       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR: {
1152          VkPhysicalDeviceFloat16Int8FeaturesKHR *features = (void *)ext;
1153          CORE_FEATURE(1, 2, shaderFloat16);
1154          CORE_FEATURE(1, 2, shaderInt8);
1155          break;
1156       }
1157 
1158       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT: {
1159          VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT *features =
1160             (VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT *)ext;
1161          features->fragmentShaderSampleInterlock = pdevice->info.gen >= 9;
1162          features->fragmentShaderPixelInterlock = pdevice->info.gen >= 9;
1163          features->fragmentShaderShadingRateInterlock = false;
1164          break;
1165       }
1166 
1167       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT: {
1168          VkPhysicalDeviceHostQueryResetFeaturesEXT *features =
1169             (VkPhysicalDeviceHostQueryResetFeaturesEXT *)ext;
1170          CORE_FEATURE(1, 2, hostQueryReset);
1171          break;
1172       }
1173 
1174       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
1175          VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
1176             (VkPhysicalDeviceDescriptorIndexingFeaturesEXT *)ext;
1177          CORE_FEATURE(1, 2, shaderInputAttachmentArrayDynamicIndexing);
1178          CORE_FEATURE(1, 2, shaderUniformTexelBufferArrayDynamicIndexing);
1179          CORE_FEATURE(1, 2, shaderStorageTexelBufferArrayDynamicIndexing);
1180          CORE_FEATURE(1, 2, shaderUniformBufferArrayNonUniformIndexing);
1181          CORE_FEATURE(1, 2, shaderSampledImageArrayNonUniformIndexing);
1182          CORE_FEATURE(1, 2, shaderStorageBufferArrayNonUniformIndexing);
1183          CORE_FEATURE(1, 2, shaderStorageImageArrayNonUniformIndexing);
1184          CORE_FEATURE(1, 2, shaderInputAttachmentArrayNonUniformIndexing);
1185          CORE_FEATURE(1, 2, shaderUniformTexelBufferArrayNonUniformIndexing);
1186          CORE_FEATURE(1, 2, shaderStorageTexelBufferArrayNonUniformIndexing);
1187          CORE_FEATURE(1, 2, descriptorBindingUniformBufferUpdateAfterBind);
1188          CORE_FEATURE(1, 2, descriptorBindingSampledImageUpdateAfterBind);
1189          CORE_FEATURE(1, 2, descriptorBindingStorageImageUpdateAfterBind);
1190          CORE_FEATURE(1, 2, descriptorBindingStorageBufferUpdateAfterBind);
1191          CORE_FEATURE(1, 2, descriptorBindingUniformTexelBufferUpdateAfterBind);
1192          CORE_FEATURE(1, 2, descriptorBindingStorageTexelBufferUpdateAfterBind);
1193          CORE_FEATURE(1, 2, descriptorBindingUpdateUnusedWhilePending);
1194          CORE_FEATURE(1, 2, descriptorBindingPartiallyBound);
1195          CORE_FEATURE(1, 2, descriptorBindingVariableDescriptorCount);
1196          CORE_FEATURE(1, 2, runtimeDescriptorArray);
1197          break;
1198       }
1199 
1200       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES_EXT: {
1201          VkPhysicalDeviceImageRobustnessFeaturesEXT *features =
1202             (VkPhysicalDeviceImageRobustnessFeaturesEXT *)ext;
1203          features->robustImageAccess = true;
1204          break;
1205       }
1206 
1207       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT: {
1208          VkPhysicalDeviceIndexTypeUint8FeaturesEXT *features =
1209             (VkPhysicalDeviceIndexTypeUint8FeaturesEXT *)ext;
1210          features->indexTypeUint8 = true;
1211          break;
1212       }
1213 
1214       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
1215          VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
1216             (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
1217          features->inlineUniformBlock = true;
1218          features->descriptorBindingInlineUniformBlockUpdateAfterBind = true;
1219          break;
1220       }
1221 
1222       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_FEATURES_EXT: {
1223          VkPhysicalDeviceLineRasterizationFeaturesEXT *features =
1224             (VkPhysicalDeviceLineRasterizationFeaturesEXT *)ext;
1225          features->rectangularLines = true;
1226          features->bresenhamLines = true;
1227          /* Support for Smooth lines with MSAA was removed on gen11.  From the
1228           * BSpec section "Multisample ModesState" table for "AA Line Support
1229           * Requirements":
1230           *
1231           *    GEN10:BUG:######## 	NUM_MULTISAMPLES == 1
1232           *
1233           * Fortunately, this isn't a case most people care about.
1234           */
1235          features->smoothLines = pdevice->info.gen < 10;
1236          features->stippledRectangularLines = false;
1237          features->stippledBresenhamLines = true;
1238          features->stippledSmoothLines = false;
1239          break;
1240       }
1241 
1242       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
1243          VkPhysicalDeviceMultiviewFeatures *features =
1244             (VkPhysicalDeviceMultiviewFeatures *)ext;
1245          CORE_FEATURE(1, 1, multiview);
1246          CORE_FEATURE(1, 1, multiviewGeometryShader);
1247          CORE_FEATURE(1, 1, multiviewTessellationShader);
1248          break;
1249       }
1250 
1251       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES_KHR: {
1252          VkPhysicalDeviceImagelessFramebufferFeaturesKHR *features =
1253             (VkPhysicalDeviceImagelessFramebufferFeaturesKHR *)ext;
1254          CORE_FEATURE(1, 2, imagelessFramebuffer);
1255          break;
1256       }
1257 
1258       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PERFORMANCE_QUERY_FEATURES_KHR: {
1259          VkPhysicalDevicePerformanceQueryFeaturesKHR *feature =
1260             (VkPhysicalDevicePerformanceQueryFeaturesKHR *)ext;
1261          feature->performanceCounterQueryPools = true;
1262          /* HW only supports a single configuration at a time. */
1263          feature->performanceCounterMultipleQueryPools = false;
1264          break;
1265       }
1266 
1267       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT: {
1268          VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT *features =
1269             (VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT *)ext;
1270          features->pipelineCreationCacheControl = true;
1271          break;
1272       }
1273 
1274       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR: {
1275          VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *features =
1276             (VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *)ext;
1277          features->pipelineExecutableInfo = true;
1278          break;
1279       }
1280 
1281       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIVATE_DATA_FEATURES_EXT: {
1282          VkPhysicalDevicePrivateDataFeaturesEXT *features = (void *)ext;
1283          features->privateData = true;
1284          break;
1285       }
1286 
1287       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
1288          VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
1289          CORE_FEATURE(1, 1, protectedMemory);
1290          break;
1291       }
1292 
1293       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT: {
1294          VkPhysicalDeviceRobustness2FeaturesEXT *features = (void *)ext;
1295          features->robustBufferAccess2 = true;
1296          features->robustImageAccess2 = true;
1297          features->nullDescriptor = true;
1298          break;
1299       }
1300 
1301       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
1302          VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
1303             (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
1304          CORE_FEATURE(1, 1, samplerYcbcrConversion);
1305          break;
1306       }
1307 
1308       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
1309          VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
1310             (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
1311          CORE_FEATURE(1, 2, scalarBlockLayout);
1312          break;
1313       }
1314 
1315       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SEPARATE_DEPTH_STENCIL_LAYOUTS_FEATURES_KHR: {
1316          VkPhysicalDeviceSeparateDepthStencilLayoutsFeaturesKHR *features =
1317             (VkPhysicalDeviceSeparateDepthStencilLayoutsFeaturesKHR *)ext;
1318          CORE_FEATURE(1, 2, separateDepthStencilLayouts);
1319          break;
1320       }
1321 
1322       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT: {
1323          VkPhysicalDeviceShaderAtomicFloatFeaturesEXT *features = (void *)ext;
1324          features->shaderBufferFloat32Atomics =    true;
1325          features->shaderBufferFloat32AtomicAdd =  false;
1326          features->shaderBufferFloat64Atomics =    false;
1327          features->shaderBufferFloat64AtomicAdd =  false;
1328          features->shaderSharedFloat32Atomics =    true;
1329          features->shaderSharedFloat32AtomicAdd =  false;
1330          features->shaderSharedFloat64Atomics =    false;
1331          features->shaderSharedFloat64AtomicAdd =  false;
1332          features->shaderImageFloat32Atomics =     true;
1333          features->shaderImageFloat32AtomicAdd =   false;
1334          features->sparseImageFloat32Atomics =     false;
1335          features->sparseImageFloat32AtomicAdd =   false;
1336          break;
1337       }
1338 
1339       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR: {
1340          VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *features = (void *)ext;
1341          CORE_FEATURE(1, 2, shaderBufferInt64Atomics);
1342          CORE_FEATURE(1, 2, shaderSharedInt64Atomics);
1343          break;
1344       }
1345 
1346       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT: {
1347          VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT *features = (void *)ext;
1348          features->shaderDemoteToHelperInvocation = true;
1349          break;
1350       }
1351 
1352       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR: {
1353          VkPhysicalDeviceShaderClockFeaturesKHR *features =
1354             (VkPhysicalDeviceShaderClockFeaturesKHR *)ext;
1355          features->shaderSubgroupClock = true;
1356          features->shaderDeviceClock = false;
1357          break;
1358       }
1359 
1360       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
1361          VkPhysicalDeviceShaderDrawParametersFeatures *features = (void *)ext;
1362          CORE_FEATURE(1, 1, shaderDrawParameters);
1363          break;
1364       }
1365 
1366       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_FUNCTIONS_2_FEATURES_INTEL: {
1367          VkPhysicalDeviceShaderIntegerFunctions2FeaturesINTEL *features =
1368             (VkPhysicalDeviceShaderIntegerFunctions2FeaturesINTEL *)ext;
1369          features->shaderIntegerFunctions2 = true;
1370          break;
1371       }
1372 
1373       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES_KHR: {
1374          VkPhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR *features =
1375             (VkPhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR *)ext;
1376          CORE_FEATURE(1, 2, shaderSubgroupExtendedTypes);
1377          break;
1378       }
1379 
1380       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_TERMINATE_INVOCATION_FEATURES_KHR: {
1381          VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR *features =
1382             (VkPhysicalDeviceShaderTerminateInvocationFeaturesKHR *)ext;
1383          features->shaderTerminateInvocation = true;
1384          break;
1385       }
1386 
1387       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT: {
1388          VkPhysicalDeviceSubgroupSizeControlFeaturesEXT *features =
1389             (VkPhysicalDeviceSubgroupSizeControlFeaturesEXT *)ext;
1390          features->subgroupSizeControl = true;
1391          features->computeFullSubgroups = true;
1392          break;
1393       }
1394 
1395       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_FEATURES_EXT: {
1396          VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *features =
1397             (VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *)ext;
1398          features->texelBufferAlignment = true;
1399          break;
1400       }
1401 
1402       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR: {
1403          VkPhysicalDeviceTimelineSemaphoreFeaturesKHR *features =
1404             (VkPhysicalDeviceTimelineSemaphoreFeaturesKHR *) ext;
1405          CORE_FEATURE(1, 2, timelineSemaphore);
1406          break;
1407       }
1408 
1409       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
1410          VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
1411          CORE_FEATURE(1, 1, variablePointersStorageBuffer);
1412          CORE_FEATURE(1, 1, variablePointers);
1413          break;
1414       }
1415 
1416       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
1417          VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
1418             (VkPhysicalDeviceTransformFeedbackFeaturesEXT *)ext;
1419          features->transformFeedback = true;
1420          features->geometryStreams = true;
1421          break;
1422       }
1423 
1424       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR: {
1425          VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *features =
1426             (VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *)ext;
1427          CORE_FEATURE(1, 2, uniformBufferStandardLayout);
1428          break;
1429       }
1430 
1431       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
1432          VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
1433             (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
1434          features->vertexAttributeInstanceRateDivisor = true;
1435          features->vertexAttributeInstanceRateZeroDivisor = true;
1436          break;
1437       }
1438 
1439       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES:
1440          anv_get_physical_device_features_1_1(pdevice, (void *)ext);
1441          break;
1442 
1443       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES:
1444          anv_get_physical_device_features_1_2(pdevice, (void *)ext);
1445          break;
1446 
1447       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES_KHR: {
1448          VkPhysicalDeviceVulkanMemoryModelFeaturesKHR *features = (void *)ext;
1449          CORE_FEATURE(1, 2, vulkanMemoryModel);
1450          CORE_FEATURE(1, 2, vulkanMemoryModelDeviceScope);
1451          CORE_FEATURE(1, 2, vulkanMemoryModelAvailabilityVisibilityChains);
1452          break;
1453       }
1454 
1455       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
1456          VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
1457             (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *)ext;
1458          features->ycbcrImageArrays = true;
1459          break;
1460       }
1461 
1462       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT: {
1463          VkPhysicalDeviceExtendedDynamicStateFeaturesEXT *features =
1464             (VkPhysicalDeviceExtendedDynamicStateFeaturesEXT *)ext;
1465          features->extendedDynamicState = true;
1466          break;
1467       }
1468 
1469       default:
1470          anv_debug_ignored_stype(ext->sType);
1471          break;
1472       }
1473    }
1474 
1475 #undef CORE_FEATURE
1476 }
1477 
1478 #define MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS   64
1479 
1480 #define MAX_PER_STAGE_DESCRIPTOR_INPUT_ATTACHMENTS 64
1481 #define MAX_DESCRIPTOR_SET_INPUT_ATTACHMENTS       256
1482 
1483 #define MAX_CUSTOM_BORDER_COLORS                   4096
1484 
anv_GetPhysicalDeviceProperties(VkPhysicalDevice physicalDevice,VkPhysicalDeviceProperties * pProperties)1485 void anv_GetPhysicalDeviceProperties(
1486     VkPhysicalDevice                            physicalDevice,
1487     VkPhysicalDeviceProperties*                 pProperties)
1488 {
1489    ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1490    const struct gen_device_info *devinfo = &pdevice->info;
1491 
1492    /* See assertions made when programming the buffer surface state. */
1493    const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
1494                                       (1ul << 30) : (1ul << 27);
1495 
1496    const uint32_t max_ssbos = pdevice->has_a64_buffer_access ? UINT16_MAX : 64;
1497    const uint32_t max_textures =
1498       pdevice->has_bindless_images ? UINT16_MAX : 128;
1499    const uint32_t max_samplers =
1500       pdevice->has_bindless_samplers ? UINT16_MAX :
1501       (devinfo->gen >= 8 || devinfo->is_haswell) ? 128 : 16;
1502    const uint32_t max_images =
1503       pdevice->has_bindless_images ? UINT16_MAX : MAX_IMAGES;
1504 
1505    /* If we can use bindless for everything, claim a high per-stage limit,
1506     * otherwise use the binding table size, minus the slots reserved for
1507     * render targets and one slot for the descriptor buffer. */
1508    const uint32_t max_per_stage =
1509       pdevice->has_bindless_images && pdevice->has_a64_buffer_access
1510       ? UINT32_MAX : MAX_BINDING_TABLE_SIZE - MAX_RTS - 1;
1511 
1512    /* Limit max_threads to 64 for the GPGPU_WALKER command */
1513    const uint32_t max_workgroup_size = 32 * MIN2(64, devinfo->max_cs_threads);
1514 
1515    VkSampleCountFlags sample_counts =
1516       isl_device_get_sample_counts(&pdevice->isl_dev);
1517 
1518 
1519    VkPhysicalDeviceLimits limits = {
1520       .maxImageDimension1D                      = (1 << 14),
1521       .maxImageDimension2D                      = (1 << 14),
1522       .maxImageDimension3D                      = (1 << 11),
1523       .maxImageDimensionCube                    = (1 << 14),
1524       .maxImageArrayLayers                      = (1 << 11),
1525       .maxTexelBufferElements                   = 128 * 1024 * 1024,
1526       .maxUniformBufferRange                    = (1ul << 27),
1527       .maxStorageBufferRange                    = max_raw_buffer_sz,
1528       .maxPushConstantsSize                     = MAX_PUSH_CONSTANTS_SIZE,
1529       .maxMemoryAllocationCount                 = UINT32_MAX,
1530       .maxSamplerAllocationCount                = 64 * 1024,
1531       .bufferImageGranularity                   = 64, /* A cache line */
1532       .sparseAddressSpaceSize                   = 0,
1533       .maxBoundDescriptorSets                   = MAX_SETS,
1534       .maxPerStageDescriptorSamplers            = max_samplers,
1535       .maxPerStageDescriptorUniformBuffers      = MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS,
1536       .maxPerStageDescriptorStorageBuffers      = max_ssbos,
1537       .maxPerStageDescriptorSampledImages       = max_textures,
1538       .maxPerStageDescriptorStorageImages       = max_images,
1539       .maxPerStageDescriptorInputAttachments    = MAX_PER_STAGE_DESCRIPTOR_INPUT_ATTACHMENTS,
1540       .maxPerStageResources                     = max_per_stage,
1541       .maxDescriptorSetSamplers                 = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
1542       .maxDescriptorSetUniformBuffers           = 6 * MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS,           /* number of stages * maxPerStageDescriptorUniformBuffers */
1543       .maxDescriptorSetUniformBuffersDynamic    = MAX_DYNAMIC_BUFFERS / 2,
1544       .maxDescriptorSetStorageBuffers           = 6 * max_ssbos,    /* number of stages * maxPerStageDescriptorStorageBuffers */
1545       .maxDescriptorSetStorageBuffersDynamic    = MAX_DYNAMIC_BUFFERS / 2,
1546       .maxDescriptorSetSampledImages            = 6 * max_textures, /* number of stages * maxPerStageDescriptorSampledImages */
1547       .maxDescriptorSetStorageImages            = 6 * max_images,   /* number of stages * maxPerStageDescriptorStorageImages */
1548       .maxDescriptorSetInputAttachments         = MAX_DESCRIPTOR_SET_INPUT_ATTACHMENTS,
1549       .maxVertexInputAttributes                 = MAX_VBS,
1550       .maxVertexInputBindings                   = MAX_VBS,
1551       .maxVertexInputAttributeOffset            = 2047,
1552       .maxVertexInputBindingStride              = 2048,
1553       .maxVertexOutputComponents                = 128,
1554       .maxTessellationGenerationLevel           = 64,
1555       .maxTessellationPatchSize                 = 32,
1556       .maxTessellationControlPerVertexInputComponents = 128,
1557       .maxTessellationControlPerVertexOutputComponents = 128,
1558       .maxTessellationControlPerPatchOutputComponents = 128,
1559       .maxTessellationControlTotalOutputComponents = 2048,
1560       .maxTessellationEvaluationInputComponents = 128,
1561       .maxTessellationEvaluationOutputComponents = 128,
1562       .maxGeometryShaderInvocations             = 32,
1563       .maxGeometryInputComponents               = 64,
1564       .maxGeometryOutputComponents              = 128,
1565       .maxGeometryOutputVertices                = 256,
1566       .maxGeometryTotalOutputComponents         = 1024,
1567       .maxFragmentInputComponents               = 116, /* 128 components - (PSIZ, CLIP_DIST0, CLIP_DIST1) */
1568       .maxFragmentOutputAttachments             = 8,
1569       .maxFragmentDualSrcAttachments            = 1,
1570       .maxFragmentCombinedOutputResources       = 8,
1571       .maxComputeSharedMemorySize               = 64 * 1024,
1572       .maxComputeWorkGroupCount                 = { 65535, 65535, 65535 },
1573       .maxComputeWorkGroupInvocations           = max_workgroup_size,
1574       .maxComputeWorkGroupSize = {
1575          max_workgroup_size,
1576          max_workgroup_size,
1577          max_workgroup_size,
1578       },
1579       .subPixelPrecisionBits                    = 8,
1580       .subTexelPrecisionBits                    = 8,
1581       .mipmapPrecisionBits                      = 8,
1582       .maxDrawIndexedIndexValue                 = UINT32_MAX,
1583       .maxDrawIndirectCount                     = UINT32_MAX,
1584       .maxSamplerLodBias                        = 16,
1585       .maxSamplerAnisotropy                     = 16,
1586       .maxViewports                             = MAX_VIEWPORTS,
1587       .maxViewportDimensions                    = { (1 << 14), (1 << 14) },
1588       .viewportBoundsRange                      = { INT16_MIN, INT16_MAX },
1589       .viewportSubPixelBits                     = 13, /* We take a float? */
1590       .minMemoryMapAlignment                    = 4096, /* A page */
1591       /* The dataport requires texel alignment so we need to assume a worst
1592        * case of R32G32B32A32 which is 16 bytes.
1593        */
1594       .minTexelBufferOffsetAlignment            = 16,
1595       .minUniformBufferOffsetAlignment          = ANV_UBO_ALIGNMENT,
1596       .minStorageBufferOffsetAlignment          = ANV_SSBO_ALIGNMENT,
1597       .minTexelOffset                           = -8,
1598       .maxTexelOffset                           = 7,
1599       .minTexelGatherOffset                     = -32,
1600       .maxTexelGatherOffset                     = 31,
1601       .minInterpolationOffset                   = -0.5,
1602       .maxInterpolationOffset                   = 0.4375,
1603       .subPixelInterpolationOffsetBits          = 4,
1604       .maxFramebufferWidth                      = (1 << 14),
1605       .maxFramebufferHeight                     = (1 << 14),
1606       .maxFramebufferLayers                     = (1 << 11),
1607       .framebufferColorSampleCounts             = sample_counts,
1608       .framebufferDepthSampleCounts             = sample_counts,
1609       .framebufferStencilSampleCounts           = sample_counts,
1610       .framebufferNoAttachmentsSampleCounts     = sample_counts,
1611       .maxColorAttachments                      = MAX_RTS,
1612       .sampledImageColorSampleCounts            = sample_counts,
1613       .sampledImageIntegerSampleCounts          = sample_counts,
1614       .sampledImageDepthSampleCounts            = sample_counts,
1615       .sampledImageStencilSampleCounts          = sample_counts,
1616       .storageImageSampleCounts                 = VK_SAMPLE_COUNT_1_BIT,
1617       .maxSampleMaskWords                       = 1,
1618       .timestampComputeAndGraphics              = true,
1619       .timestampPeriod                          = 1000000000.0 / devinfo->timestamp_frequency,
1620       .maxClipDistances                         = 8,
1621       .maxCullDistances                         = 8,
1622       .maxCombinedClipAndCullDistances          = 8,
1623       .discreteQueuePriorities                  = 2,
1624       .pointSizeRange                           = { 0.125, 255.875 },
1625       .lineWidthRange                           = {
1626          0.0,
1627          (devinfo->gen >= 9 || devinfo->is_cherryview) ?
1628             2047.9921875 : 7.9921875,
1629       },
1630       .pointSizeGranularity                     = (1.0 / 8.0),
1631       .lineWidthGranularity                     = (1.0 / 128.0),
1632       .strictLines                              = false,
1633       .standardSampleLocations                  = true,
1634       .optimalBufferCopyOffsetAlignment         = 128,
1635       .optimalBufferCopyRowPitchAlignment       = 128,
1636       .nonCoherentAtomSize                      = 64,
1637    };
1638 
1639    *pProperties = (VkPhysicalDeviceProperties) {
1640       .apiVersion = anv_physical_device_api_version(pdevice),
1641       .driverVersion = vk_get_driver_version(),
1642       .vendorID = 0x8086,
1643       .deviceID = pdevice->info.chipset_id,
1644       .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1645       .limits = limits,
1646       .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
1647    };
1648 
1649    snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
1650             "%s", pdevice->name);
1651    memcpy(pProperties->pipelineCacheUUID,
1652           pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
1653 }
1654 
1655 static void
anv_get_physical_device_properties_1_1(struct anv_physical_device * pdevice,VkPhysicalDeviceVulkan11Properties * p)1656 anv_get_physical_device_properties_1_1(struct anv_physical_device *pdevice,
1657                                        VkPhysicalDeviceVulkan11Properties *p)
1658 {
1659    assert(p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES);
1660 
1661    memcpy(p->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1662    memcpy(p->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1663    memset(p->deviceLUID, 0, VK_LUID_SIZE);
1664    p->deviceNodeMask = 0;
1665    p->deviceLUIDValid = false;
1666 
1667    p->subgroupSize = BRW_SUBGROUP_SIZE;
1668    VkShaderStageFlags scalar_stages = 0;
1669    for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1670       if (pdevice->compiler->scalar_stage[stage])
1671          scalar_stages |= mesa_to_vk_shader_stage(stage);
1672    }
1673    p->subgroupSupportedStages = scalar_stages;
1674    p->subgroupSupportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1675                                     VK_SUBGROUP_FEATURE_VOTE_BIT |
1676                                     VK_SUBGROUP_FEATURE_BALLOT_BIT |
1677                                     VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1678                                     VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1679                                     VK_SUBGROUP_FEATURE_QUAD_BIT;
1680    if (pdevice->info.gen >= 8) {
1681       /* TODO: There's no technical reason why these can't be made to
1682        * work on gen7 but they don't at the moment so it's best to leave
1683        * the feature disabled than enabled and broken.
1684        */
1685       p->subgroupSupportedOperations |= VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1686                                         VK_SUBGROUP_FEATURE_CLUSTERED_BIT;
1687    }
1688    p->subgroupQuadOperationsInAllStages = pdevice->info.gen >= 8;
1689 
1690    p->pointClippingBehavior      = VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY;
1691    p->maxMultiviewViewCount      = 16;
1692    p->maxMultiviewInstanceIndex  = UINT32_MAX / 16;
1693    p->protectedNoFault           = false;
1694    /* This value doesn't matter for us today as our per-stage descriptors are
1695     * the real limit.
1696     */
1697    p->maxPerSetDescriptors       = 1024;
1698    p->maxMemoryAllocationSize    = MAX_MEMORY_ALLOCATION_SIZE;
1699 }
1700 
1701 static void
anv_get_physical_device_properties_1_2(struct anv_physical_device * pdevice,VkPhysicalDeviceVulkan12Properties * p)1702 anv_get_physical_device_properties_1_2(struct anv_physical_device *pdevice,
1703                                        VkPhysicalDeviceVulkan12Properties *p)
1704 {
1705    assert(p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES);
1706 
1707    p->driverID = VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA_KHR;
1708    memset(p->driverName, 0, sizeof(p->driverName));
1709    snprintf(p->driverName, VK_MAX_DRIVER_NAME_SIZE_KHR,
1710             "Intel open-source Mesa driver");
1711    memset(p->driverInfo, 0, sizeof(p->driverInfo));
1712    snprintf(p->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1713             "Mesa " PACKAGE_VERSION MESA_GIT_SHA1);
1714    p->conformanceVersion = (VkConformanceVersionKHR) {
1715       .major = 1,
1716       .minor = 2,
1717       .subminor = 0,
1718       .patch = 0,
1719    };
1720 
1721    p->denormBehaviorIndependence =
1722       VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR;
1723    p->roundingModeIndependence =
1724       VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR;
1725 
1726    /* Broadwell does not support HF denorms and there are restrictions
1727     * other gens. According to Kabylake's PRM:
1728     *
1729     * "math - Extended Math Function
1730     * [...]
1731     * Restriction : Half-float denorms are always retained."
1732     */
1733    p->shaderDenormFlushToZeroFloat16         = false;
1734    p->shaderDenormPreserveFloat16            = pdevice->info.gen > 8;
1735    p->shaderRoundingModeRTEFloat16           = true;
1736    p->shaderRoundingModeRTZFloat16           = true;
1737    p->shaderSignedZeroInfNanPreserveFloat16  = true;
1738 
1739    p->shaderDenormFlushToZeroFloat32         = true;
1740    p->shaderDenormPreserveFloat32            = true;
1741    p->shaderRoundingModeRTEFloat32           = true;
1742    p->shaderRoundingModeRTZFloat32           = true;
1743    p->shaderSignedZeroInfNanPreserveFloat32  = true;
1744 
1745    p->shaderDenormFlushToZeroFloat64         = true;
1746    p->shaderDenormPreserveFloat64            = true;
1747    p->shaderRoundingModeRTEFloat64           = true;
1748    p->shaderRoundingModeRTZFloat64           = true;
1749    p->shaderSignedZeroInfNanPreserveFloat64  = true;
1750 
1751    /* It's a bit hard to exactly map our implementation to the limits
1752     * described by Vulkan.  The bindless surface handle in the extended
1753     * message descriptors is 20 bits and it's an index into the table of
1754     * RENDER_SURFACE_STATE structs that starts at bindless surface base
1755     * address.  This means that we can have at must 1M surface states
1756     * allocated at any given time.  Since most image views take two
1757     * descriptors, this means we have a limit of about 500K image views.
1758     *
1759     * However, since we allocate surface states at vkCreateImageView time,
1760     * this means our limit is actually something on the order of 500K image
1761     * views allocated at any time.  The actual limit describe by Vulkan, on
1762     * the other hand, is a limit of how many you can have in a descriptor set.
1763     * Assuming anyone using 1M descriptors will be using the same image view
1764     * twice a bunch of times (or a bunch of null descriptors), we can safely
1765     * advertise a larger limit here.
1766     */
1767    const unsigned max_bindless_views = 1 << 20;
1768    p->maxUpdateAfterBindDescriptorsInAllPools            = max_bindless_views;
1769    p->shaderUniformBufferArrayNonUniformIndexingNative   = false;
1770    p->shaderSampledImageArrayNonUniformIndexingNative    = false;
1771    p->shaderStorageBufferArrayNonUniformIndexingNative   = true;
1772    p->shaderStorageImageArrayNonUniformIndexingNative    = false;
1773    p->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1774    p->robustBufferAccessUpdateAfterBind                  = true;
1775    p->quadDivergentImplicitLod                           = false;
1776    p->maxPerStageDescriptorUpdateAfterBindSamplers       = max_bindless_views;
1777    p->maxPerStageDescriptorUpdateAfterBindUniformBuffers = MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS;
1778    p->maxPerStageDescriptorUpdateAfterBindStorageBuffers = UINT32_MAX;
1779    p->maxPerStageDescriptorUpdateAfterBindSampledImages  = max_bindless_views;
1780    p->maxPerStageDescriptorUpdateAfterBindStorageImages  = max_bindless_views;
1781    p->maxPerStageDescriptorUpdateAfterBindInputAttachments = MAX_PER_STAGE_DESCRIPTOR_INPUT_ATTACHMENTS;
1782    p->maxPerStageUpdateAfterBindResources                = UINT32_MAX;
1783    p->maxDescriptorSetUpdateAfterBindSamplers            = max_bindless_views;
1784    p->maxDescriptorSetUpdateAfterBindUniformBuffers      = 6 * MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS;
1785    p->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2;
1786    p->maxDescriptorSetUpdateAfterBindStorageBuffers      = UINT32_MAX;
1787    p->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2;
1788    p->maxDescriptorSetUpdateAfterBindSampledImages       = max_bindless_views;
1789    p->maxDescriptorSetUpdateAfterBindStorageImages       = max_bindless_views;
1790    p->maxDescriptorSetUpdateAfterBindInputAttachments    = MAX_DESCRIPTOR_SET_INPUT_ATTACHMENTS;
1791 
1792    /* We support all of the depth resolve modes */
1793    p->supportedDepthResolveModes    = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1794                                       VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1795                                       VK_RESOLVE_MODE_MIN_BIT_KHR |
1796                                       VK_RESOLVE_MODE_MAX_BIT_KHR;
1797    /* Average doesn't make sense for stencil so we don't support that */
1798    p->supportedStencilResolveModes  = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR;
1799    if (pdevice->info.gen >= 8) {
1800       /* The advanced stencil resolve modes currently require stencil
1801        * sampling be supported by the hardware.
1802        */
1803       p->supportedStencilResolveModes |= VK_RESOLVE_MODE_MIN_BIT_KHR |
1804                                          VK_RESOLVE_MODE_MAX_BIT_KHR;
1805    }
1806    p->independentResolveNone  = true;
1807    p->independentResolve      = true;
1808 
1809    p->filterMinmaxSingleComponentFormats  = pdevice->info.gen >= 9;
1810    p->filterMinmaxImageComponentMapping   = pdevice->info.gen >= 9;
1811 
1812    p->maxTimelineSemaphoreValueDifference = UINT64_MAX;
1813 
1814    p->framebufferIntegerColorSampleCounts =
1815       isl_device_get_sample_counts(&pdevice->isl_dev);
1816 }
1817 
anv_GetPhysicalDeviceProperties2(VkPhysicalDevice physicalDevice,VkPhysicalDeviceProperties2 * pProperties)1818 void anv_GetPhysicalDeviceProperties2(
1819     VkPhysicalDevice                            physicalDevice,
1820     VkPhysicalDeviceProperties2*                pProperties)
1821 {
1822    ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1823 
1824    anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1825 
1826    VkPhysicalDeviceVulkan11Properties core_1_1 = {
1827       .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES,
1828    };
1829    anv_get_physical_device_properties_1_1(pdevice, &core_1_1);
1830 
1831    VkPhysicalDeviceVulkan12Properties core_1_2 = {
1832       .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES,
1833    };
1834    anv_get_physical_device_properties_1_2(pdevice, &core_1_2);
1835 
1836 #define CORE_RENAMED_PROPERTY(major, minor, ext_property, core_property) \
1837    memcpy(&properties->ext_property, &core_##major##_##minor.core_property, \
1838           sizeof(core_##major##_##minor.core_property))
1839 
1840 #define CORE_PROPERTY(major, minor, property) \
1841    CORE_RENAMED_PROPERTY(major, minor, property, property)
1842 
1843    vk_foreach_struct(ext, pProperties->pNext) {
1844       switch (ext->sType) {
1845       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_PROPERTIES_EXT: {
1846          VkPhysicalDeviceCustomBorderColorPropertiesEXT *properties =
1847             (VkPhysicalDeviceCustomBorderColorPropertiesEXT *)ext;
1848          properties->maxCustomBorderColorSamplers = MAX_CUSTOM_BORDER_COLORS;
1849          break;
1850       }
1851 
1852       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR: {
1853          VkPhysicalDeviceDepthStencilResolvePropertiesKHR *properties =
1854             (VkPhysicalDeviceDepthStencilResolvePropertiesKHR *)ext;
1855          CORE_PROPERTY(1, 2, supportedDepthResolveModes);
1856          CORE_PROPERTY(1, 2, supportedStencilResolveModes);
1857          CORE_PROPERTY(1, 2, independentResolveNone);
1858          CORE_PROPERTY(1, 2, independentResolve);
1859          break;
1860       }
1861 
1862       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
1863          VkPhysicalDeviceDescriptorIndexingPropertiesEXT *properties =
1864             (VkPhysicalDeviceDescriptorIndexingPropertiesEXT *)ext;
1865          CORE_PROPERTY(1, 2, maxUpdateAfterBindDescriptorsInAllPools);
1866          CORE_PROPERTY(1, 2, shaderUniformBufferArrayNonUniformIndexingNative);
1867          CORE_PROPERTY(1, 2, shaderSampledImageArrayNonUniformIndexingNative);
1868          CORE_PROPERTY(1, 2, shaderStorageBufferArrayNonUniformIndexingNative);
1869          CORE_PROPERTY(1, 2, shaderStorageImageArrayNonUniformIndexingNative);
1870          CORE_PROPERTY(1, 2, shaderInputAttachmentArrayNonUniformIndexingNative);
1871          CORE_PROPERTY(1, 2, robustBufferAccessUpdateAfterBind);
1872          CORE_PROPERTY(1, 2, quadDivergentImplicitLod);
1873          CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindSamplers);
1874          CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindUniformBuffers);
1875          CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindStorageBuffers);
1876          CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindSampledImages);
1877          CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindStorageImages);
1878          CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindInputAttachments);
1879          CORE_PROPERTY(1, 2, maxPerStageUpdateAfterBindResources);
1880          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindSamplers);
1881          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindUniformBuffers);
1882          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
1883          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageBuffers);
1884          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
1885          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindSampledImages);
1886          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageImages);
1887          CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindInputAttachments);
1888          break;
1889       }
1890 
1891       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1892          VkPhysicalDeviceDriverPropertiesKHR *properties =
1893             (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1894          CORE_PROPERTY(1, 2, driverID);
1895          CORE_PROPERTY(1, 2, driverName);
1896          CORE_PROPERTY(1, 2, driverInfo);
1897          CORE_PROPERTY(1, 2, conformanceVersion);
1898          break;
1899       }
1900 
1901       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1902          VkPhysicalDeviceExternalMemoryHostPropertiesEXT *props =
1903             (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1904          /* Userptr needs page aligned memory. */
1905          props->minImportedHostPointerAlignment = 4096;
1906          break;
1907       }
1908 
1909       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1910          VkPhysicalDeviceIDProperties *properties =
1911             (VkPhysicalDeviceIDProperties *)ext;
1912          CORE_PROPERTY(1, 1, deviceUUID);
1913          CORE_PROPERTY(1, 1, driverUUID);
1914          CORE_PROPERTY(1, 1, deviceLUID);
1915          CORE_PROPERTY(1, 1, deviceLUIDValid);
1916          break;
1917       }
1918 
1919       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1920          VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1921             (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1922          props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1923          props->maxPerStageDescriptorInlineUniformBlocks =
1924             MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1925          props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks =
1926             MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1927          props->maxDescriptorSetInlineUniformBlocks =
1928             MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1929          props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks =
1930             MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1931          break;
1932       }
1933 
1934       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_PROPERTIES_EXT: {
1935          VkPhysicalDeviceLineRasterizationPropertiesEXT *props =
1936             (VkPhysicalDeviceLineRasterizationPropertiesEXT *)ext;
1937          /* In the Skylake PRM Vol. 7, subsection titled "GIQ (Diamond)
1938           * Sampling Rules - Legacy Mode", it says the following:
1939           *
1940           *    "Note that the device divides a pixel into a 16x16 array of
1941           *    subpixels, referenced by their upper left corners."
1942           *
1943           * This is the only known reference in the PRMs to the subpixel
1944           * precision of line rasterization and a "16x16 array of subpixels"
1945           * implies 4 subpixel precision bits.  Empirical testing has shown
1946           * that 4 subpixel precision bits applies to all line rasterization
1947           * types.
1948           */
1949          props->lineSubPixelPrecisionBits = 4;
1950          break;
1951       }
1952 
1953       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1954          VkPhysicalDeviceMaintenance3Properties *properties =
1955             (VkPhysicalDeviceMaintenance3Properties *)ext;
1956          /* This value doesn't matter for us today as our per-stage
1957           * descriptors are the real limit.
1958           */
1959          CORE_PROPERTY(1, 1, maxPerSetDescriptors);
1960          CORE_PROPERTY(1, 1, maxMemoryAllocationSize);
1961          break;
1962       }
1963 
1964       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1965          VkPhysicalDeviceMultiviewProperties *properties =
1966             (VkPhysicalDeviceMultiviewProperties *)ext;
1967          CORE_PROPERTY(1, 1, maxMultiviewViewCount);
1968          CORE_PROPERTY(1, 1, maxMultiviewInstanceIndex);
1969          break;
1970       }
1971 
1972       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1973          VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1974             (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1975          properties->pciDomain = pdevice->pci_info.domain;
1976          properties->pciBus = pdevice->pci_info.bus;
1977          properties->pciDevice = pdevice->pci_info.device;
1978          properties->pciFunction = pdevice->pci_info.function;
1979          break;
1980       }
1981 
1982       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PERFORMANCE_QUERY_PROPERTIES_KHR: {
1983          VkPhysicalDevicePerformanceQueryPropertiesKHR *properties =
1984             (VkPhysicalDevicePerformanceQueryPropertiesKHR *)ext;
1985          /* We could support this by spawning a shader to do the equation
1986           * normalization.
1987           */
1988          properties->allowCommandBufferQueryCopies = false;
1989          break;
1990       }
1991 
1992       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1993          VkPhysicalDevicePointClippingProperties *properties =
1994             (VkPhysicalDevicePointClippingProperties *) ext;
1995          CORE_PROPERTY(1, 1, pointClippingBehavior);
1996          break;
1997       }
1998 
1999 #pragma GCC diagnostic push
2000 #pragma GCC diagnostic ignored "-Wswitch"
2001       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENTATION_PROPERTIES_ANDROID: {
2002          VkPhysicalDevicePresentationPropertiesANDROID *props =
2003             (VkPhysicalDevicePresentationPropertiesANDROID *)ext;
2004          props->sharedImage = VK_FALSE;
2005          break;
2006       }
2007 #pragma GCC diagnostic pop
2008 
2009       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
2010          VkPhysicalDeviceProtectedMemoryProperties *properties =
2011             (VkPhysicalDeviceProtectedMemoryProperties *)ext;
2012          CORE_PROPERTY(1, 1, protectedNoFault);
2013          break;
2014       }
2015 
2016       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
2017          VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
2018             (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
2019          properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
2020          break;
2021       }
2022 
2023       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_PROPERTIES_EXT: {
2024          VkPhysicalDeviceRobustness2PropertiesEXT *properties = (void *)ext;
2025          properties->robustStorageBufferAccessSizeAlignment =
2026             ANV_SSBO_BOUNDS_CHECK_ALIGNMENT;
2027          properties->robustUniformBufferAccessSizeAlignment =
2028             ANV_UBO_ALIGNMENT;
2029          break;
2030       }
2031 
2032       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
2033          VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
2034             (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
2035          CORE_PROPERTY(1, 2, filterMinmaxImageComponentMapping);
2036          CORE_PROPERTY(1, 2, filterMinmaxSingleComponentFormats);
2037          break;
2038       }
2039 
2040       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
2041          VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
2042          CORE_PROPERTY(1, 1, subgroupSize);
2043          CORE_RENAMED_PROPERTY(1, 1, supportedStages,
2044                                      subgroupSupportedStages);
2045          CORE_RENAMED_PROPERTY(1, 1, supportedOperations,
2046                                      subgroupSupportedOperations);
2047          CORE_RENAMED_PROPERTY(1, 1, quadOperationsInAllStages,
2048                                      subgroupQuadOperationsInAllStages);
2049          break;
2050       }
2051 
2052       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES_EXT: {
2053          VkPhysicalDeviceSubgroupSizeControlPropertiesEXT *props =
2054             (VkPhysicalDeviceSubgroupSizeControlPropertiesEXT *)ext;
2055          STATIC_ASSERT(8 <= BRW_SUBGROUP_SIZE && BRW_SUBGROUP_SIZE <= 32);
2056          props->minSubgroupSize = 8;
2057          props->maxSubgroupSize = 32;
2058          /* Limit max_threads to 64 for the GPGPU_WALKER command. */
2059          props->maxComputeWorkgroupSubgroups = MIN2(64, pdevice->info.max_cs_threads);
2060          props->requiredSubgroupSizeStages = VK_SHADER_STAGE_COMPUTE_BIT;
2061          break;
2062       }
2063       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES_KHR : {
2064          VkPhysicalDeviceFloatControlsPropertiesKHR *properties = (void *)ext;
2065          CORE_PROPERTY(1, 2, denormBehaviorIndependence);
2066          CORE_PROPERTY(1, 2, roundingModeIndependence);
2067          CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat16);
2068          CORE_PROPERTY(1, 2, shaderDenormPreserveFloat16);
2069          CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat16);
2070          CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat16);
2071          CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat16);
2072          CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat32);
2073          CORE_PROPERTY(1, 2, shaderDenormPreserveFloat32);
2074          CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat32);
2075          CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat32);
2076          CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat32);
2077          CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat64);
2078          CORE_PROPERTY(1, 2, shaderDenormPreserveFloat64);
2079          CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat64);
2080          CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat64);
2081          CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat64);
2082          break;
2083       }
2084 
2085       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT: {
2086          VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *props =
2087             (VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *)ext;
2088 
2089          /* From the SKL PRM Vol. 2d, docs for RENDER_SURFACE_STATE::Surface
2090           * Base Address:
2091           *
2092           *    "For SURFTYPE_BUFFER non-rendertarget surfaces, this field
2093           *    specifies the base address of the first element of the surface,
2094           *    computed in software by adding the surface base address to the
2095           *    byte offset of the element in the buffer. The base address must
2096           *    be aligned to element size."
2097           *
2098           * The typed dataport messages require that things be texel aligned.
2099           * Otherwise, we may just load/store the wrong data or, in the worst
2100           * case, there may be hangs.
2101           */
2102          props->storageTexelBufferOffsetAlignmentBytes = 16;
2103          props->storageTexelBufferOffsetSingleTexelAlignment = true;
2104 
2105          /* The sampler, however, is much more forgiving and it can handle
2106           * arbitrary byte alignment for linear and buffer surfaces.  It's
2107           * hard to find a good PRM citation for this but years of empirical
2108           * experience demonstrate that this is true.
2109           */
2110          props->uniformTexelBufferOffsetAlignmentBytes = 1;
2111          props->uniformTexelBufferOffsetSingleTexelAlignment = false;
2112          break;
2113       }
2114 
2115       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_PROPERTIES_KHR: {
2116          VkPhysicalDeviceTimelineSemaphorePropertiesKHR *properties =
2117             (VkPhysicalDeviceTimelineSemaphorePropertiesKHR *) ext;
2118          CORE_PROPERTY(1, 2, maxTimelineSemaphoreValueDifference);
2119          break;
2120       }
2121 
2122       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
2123          VkPhysicalDeviceTransformFeedbackPropertiesEXT *props =
2124             (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
2125 
2126          props->maxTransformFeedbackStreams = MAX_XFB_STREAMS;
2127          props->maxTransformFeedbackBuffers = MAX_XFB_BUFFERS;
2128          props->maxTransformFeedbackBufferSize = (1ull << 32);
2129          props->maxTransformFeedbackStreamDataSize = 128 * 4;
2130          props->maxTransformFeedbackBufferDataSize = 128 * 4;
2131          props->maxTransformFeedbackBufferDataStride = 2048;
2132          props->transformFeedbackQueries = true;
2133          props->transformFeedbackStreamsLinesTriangles = false;
2134          props->transformFeedbackRasterizationStreamSelect = false;
2135          /* This requires MI_MATH */
2136          props->transformFeedbackDraw = pdevice->info.is_haswell ||
2137                                         pdevice->info.gen >= 8;
2138          break;
2139       }
2140 
2141       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
2142          VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
2143             (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
2144          /* We have to restrict this a bit for multiview */
2145          props->maxVertexAttribDivisor = UINT32_MAX / 16;
2146          break;
2147       }
2148 
2149       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES:
2150          anv_get_physical_device_properties_1_1(pdevice, (void *)ext);
2151          break;
2152 
2153       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES:
2154          anv_get_physical_device_properties_1_2(pdevice, (void *)ext);
2155          break;
2156 
2157       default:
2158          anv_debug_ignored_stype(ext->sType);
2159          break;
2160       }
2161    }
2162 
2163 #undef CORE_RENAMED_PROPERTY
2164 #undef CORE_PROPERTY
2165 }
2166 
2167 /* We support exactly one queue family. */
2168 static const VkQueueFamilyProperties
2169 anv_queue_family_properties = {
2170    .queueFlags = VK_QUEUE_GRAPHICS_BIT |
2171                  VK_QUEUE_COMPUTE_BIT |
2172                  VK_QUEUE_TRANSFER_BIT,
2173    .queueCount = 1,
2174    .timestampValidBits = 36, /* XXX: Real value here */
2175    .minImageTransferGranularity = { 1, 1, 1 },
2176 };
2177 
anv_GetPhysicalDeviceQueueFamilyProperties(VkPhysicalDevice physicalDevice,uint32_t * pCount,VkQueueFamilyProperties * pQueueFamilyProperties)2178 void anv_GetPhysicalDeviceQueueFamilyProperties(
2179     VkPhysicalDevice                            physicalDevice,
2180     uint32_t*                                   pCount,
2181     VkQueueFamilyProperties*                    pQueueFamilyProperties)
2182 {
2183    VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
2184 
2185    vk_outarray_append(&out, p) {
2186       *p = anv_queue_family_properties;
2187    }
2188 }
2189 
anv_GetPhysicalDeviceQueueFamilyProperties2(VkPhysicalDevice physicalDevice,uint32_t * pQueueFamilyPropertyCount,VkQueueFamilyProperties2 * pQueueFamilyProperties)2190 void anv_GetPhysicalDeviceQueueFamilyProperties2(
2191     VkPhysicalDevice                            physicalDevice,
2192     uint32_t*                                   pQueueFamilyPropertyCount,
2193     VkQueueFamilyProperties2*                   pQueueFamilyProperties)
2194 {
2195 
2196    VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
2197 
2198    vk_outarray_append(&out, p) {
2199       p->queueFamilyProperties = anv_queue_family_properties;
2200 
2201       vk_foreach_struct(s, p->pNext) {
2202          anv_debug_ignored_stype(s->sType);
2203       }
2204    }
2205 }
2206 
anv_GetPhysicalDeviceMemoryProperties(VkPhysicalDevice physicalDevice,VkPhysicalDeviceMemoryProperties * pMemoryProperties)2207 void anv_GetPhysicalDeviceMemoryProperties(
2208     VkPhysicalDevice                            physicalDevice,
2209     VkPhysicalDeviceMemoryProperties*           pMemoryProperties)
2210 {
2211    ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
2212 
2213    pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
2214    for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
2215       pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
2216          .propertyFlags = physical_device->memory.types[i].propertyFlags,
2217          .heapIndex     = physical_device->memory.types[i].heapIndex,
2218       };
2219    }
2220 
2221    pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
2222    for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
2223       pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
2224          .size    = physical_device->memory.heaps[i].size,
2225          .flags   = physical_device->memory.heaps[i].flags,
2226       };
2227    }
2228 }
2229 
2230 static void
anv_get_memory_budget(VkPhysicalDevice physicalDevice,VkPhysicalDeviceMemoryBudgetPropertiesEXT * memoryBudget)2231 anv_get_memory_budget(VkPhysicalDevice physicalDevice,
2232                       VkPhysicalDeviceMemoryBudgetPropertiesEXT *memoryBudget)
2233 {
2234    ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
2235    uint64_t sys_available;
2236    ASSERTED bool has_available_memory =
2237       os_get_available_system_memory(&sys_available);
2238    assert(has_available_memory);
2239 
2240    VkDeviceSize total_heaps_size = 0;
2241    for (size_t i = 0; i < device->memory.heap_count; i++)
2242          total_heaps_size += device->memory.heaps[i].size;
2243 
2244    for (size_t i = 0; i < device->memory.heap_count; i++) {
2245       VkDeviceSize heap_size = device->memory.heaps[i].size;
2246       VkDeviceSize heap_used = device->memory.heaps[i].used;
2247       VkDeviceSize heap_budget;
2248 
2249       double heap_proportion = (double) heap_size / total_heaps_size;
2250       VkDeviceSize sys_available_prop = sys_available * heap_proportion;
2251 
2252       /*
2253        * Let's not incite the app to starve the system: report at most 90% of
2254        * available system memory.
2255        */
2256       uint64_t heap_available = sys_available_prop * 9 / 10;
2257       heap_budget = MIN2(heap_size, heap_used + heap_available);
2258 
2259       /*
2260        * Round down to the nearest MB
2261        */
2262       heap_budget &= ~((1ull << 20) - 1);
2263 
2264       /*
2265        * The heapBudget value must be non-zero for array elements less than
2266        * VkPhysicalDeviceMemoryProperties::memoryHeapCount. The heapBudget
2267        * value must be less than or equal to VkMemoryHeap::size for each heap.
2268        */
2269       assert(0 < heap_budget && heap_budget <= heap_size);
2270 
2271       memoryBudget->heapUsage[i] = heap_used;
2272       memoryBudget->heapBudget[i] = heap_budget;
2273    }
2274 
2275    /* The heapBudget and heapUsage values must be zero for array elements
2276     * greater than or equal to VkPhysicalDeviceMemoryProperties::memoryHeapCount
2277     */
2278    for (uint32_t i = device->memory.heap_count; i < VK_MAX_MEMORY_HEAPS; i++) {
2279       memoryBudget->heapBudget[i] = 0;
2280       memoryBudget->heapUsage[i] = 0;
2281    }
2282 }
2283 
anv_GetPhysicalDeviceMemoryProperties2(VkPhysicalDevice physicalDevice,VkPhysicalDeviceMemoryProperties2 * pMemoryProperties)2284 void anv_GetPhysicalDeviceMemoryProperties2(
2285     VkPhysicalDevice                            physicalDevice,
2286     VkPhysicalDeviceMemoryProperties2*          pMemoryProperties)
2287 {
2288    anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
2289                                          &pMemoryProperties->memoryProperties);
2290 
2291    vk_foreach_struct(ext, pMemoryProperties->pNext) {
2292       switch (ext->sType) {
2293       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT:
2294          anv_get_memory_budget(physicalDevice, (void*)ext);
2295          break;
2296       default:
2297          anv_debug_ignored_stype(ext->sType);
2298          break;
2299       }
2300    }
2301 }
2302 
2303 void
anv_GetDeviceGroupPeerMemoryFeatures(VkDevice device,uint32_t heapIndex,uint32_t localDeviceIndex,uint32_t remoteDeviceIndex,VkPeerMemoryFeatureFlags * pPeerMemoryFeatures)2304 anv_GetDeviceGroupPeerMemoryFeatures(
2305     VkDevice                                    device,
2306     uint32_t                                    heapIndex,
2307     uint32_t                                    localDeviceIndex,
2308     uint32_t                                    remoteDeviceIndex,
2309     VkPeerMemoryFeatureFlags*                   pPeerMemoryFeatures)
2310 {
2311    assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
2312    *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
2313                           VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
2314                           VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
2315                           VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
2316 }
2317 
anv_GetInstanceProcAddr(VkInstance _instance,const char * pName)2318 PFN_vkVoidFunction anv_GetInstanceProcAddr(
2319     VkInstance                                  _instance,
2320     const char*                                 pName)
2321 {
2322    ANV_FROM_HANDLE(anv_instance, instance, _instance);
2323 
2324    /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
2325     * when we have to return valid function pointers, NULL, or it's left
2326     * undefined.  See the table for exact details.
2327     */
2328    if (pName == NULL)
2329       return NULL;
2330 
2331 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
2332    if (strcmp(pName, "vk" #entrypoint) == 0) \
2333       return (PFN_vkVoidFunction)anv_##entrypoint
2334 
2335    LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
2336    LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
2337    LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
2338    LOOKUP_ANV_ENTRYPOINT(CreateInstance);
2339 
2340    /* GetInstanceProcAddr() can also be called with a NULL instance.
2341     * See https://gitlab.khronos.org/vulkan/vulkan/issues/2057
2342     */
2343    LOOKUP_ANV_ENTRYPOINT(GetInstanceProcAddr);
2344 
2345 #undef LOOKUP_ANV_ENTRYPOINT
2346 
2347    if (instance == NULL)
2348       return NULL;
2349 
2350    int idx = anv_get_instance_entrypoint_index(pName);
2351    if (idx >= 0)
2352       return instance->dispatch.entrypoints[idx];
2353 
2354    idx = anv_get_physical_device_entrypoint_index(pName);
2355    if (idx >= 0)
2356       return instance->physical_device_dispatch.entrypoints[idx];
2357 
2358    idx = anv_get_device_entrypoint_index(pName);
2359    if (idx >= 0)
2360       return instance->device_dispatch.entrypoints[idx];
2361 
2362    return NULL;
2363 }
2364 
2365 /* With version 1+ of the loader interface the ICD should expose
2366  * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
2367  */
2368 PUBLIC
2369 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
2370     VkInstance                                  instance,
2371     const char*                                 pName);
2372 
2373 PUBLIC
vk_icdGetInstanceProcAddr(VkInstance instance,const char * pName)2374 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
2375     VkInstance                                  instance,
2376     const char*                                 pName)
2377 {
2378    return anv_GetInstanceProcAddr(instance, pName);
2379 }
2380 
anv_GetDeviceProcAddr(VkDevice _device,const char * pName)2381 PFN_vkVoidFunction anv_GetDeviceProcAddr(
2382     VkDevice                                    _device,
2383     const char*                                 pName)
2384 {
2385    ANV_FROM_HANDLE(anv_device, device, _device);
2386 
2387    if (!device || !pName)
2388       return NULL;
2389 
2390    int idx = anv_get_device_entrypoint_index(pName);
2391    if (idx < 0)
2392       return NULL;
2393 
2394    return device->dispatch.entrypoints[idx];
2395 }
2396 
2397 /* With version 4+ of the loader interface the ICD should expose
2398  * vk_icdGetPhysicalDeviceProcAddr()
2399  */
2400 PUBLIC
2401 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
2402     VkInstance  _instance,
2403     const char* pName);
2404 
vk_icdGetPhysicalDeviceProcAddr(VkInstance _instance,const char * pName)2405 PFN_vkVoidFunction vk_icdGetPhysicalDeviceProcAddr(
2406     VkInstance  _instance,
2407     const char* pName)
2408 {
2409    ANV_FROM_HANDLE(anv_instance, instance, _instance);
2410 
2411    if (!pName || !instance)
2412       return NULL;
2413 
2414    int idx = anv_get_physical_device_entrypoint_index(pName);
2415    if (idx < 0)
2416       return NULL;
2417 
2418    return instance->physical_device_dispatch.entrypoints[idx];
2419 }
2420 
2421 
2422 VkResult
anv_CreateDebugReportCallbackEXT(VkInstance _instance,const VkDebugReportCallbackCreateInfoEXT * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkDebugReportCallbackEXT * pCallback)2423 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
2424                                  const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
2425                                  const VkAllocationCallbacks* pAllocator,
2426                                  VkDebugReportCallbackEXT* pCallback)
2427 {
2428    ANV_FROM_HANDLE(anv_instance, instance, _instance);
2429    return vk_create_debug_report_callback(&instance->debug_report_callbacks,
2430                                           pCreateInfo, pAllocator, &instance->alloc,
2431                                           pCallback);
2432 }
2433 
2434 void
anv_DestroyDebugReportCallbackEXT(VkInstance _instance,VkDebugReportCallbackEXT _callback,const VkAllocationCallbacks * pAllocator)2435 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
2436                                   VkDebugReportCallbackEXT _callback,
2437                                   const VkAllocationCallbacks* pAllocator)
2438 {
2439    ANV_FROM_HANDLE(anv_instance, instance, _instance);
2440    vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
2441                                     _callback, pAllocator, &instance->alloc);
2442 }
2443 
2444 void
anv_DebugReportMessageEXT(VkInstance _instance,VkDebugReportFlagsEXT flags,VkDebugReportObjectTypeEXT objectType,uint64_t object,size_t location,int32_t messageCode,const char * pLayerPrefix,const char * pMessage)2445 anv_DebugReportMessageEXT(VkInstance _instance,
2446                           VkDebugReportFlagsEXT flags,
2447                           VkDebugReportObjectTypeEXT objectType,
2448                           uint64_t object,
2449                           size_t location,
2450                           int32_t messageCode,
2451                           const char* pLayerPrefix,
2452                           const char* pMessage)
2453 {
2454    ANV_FROM_HANDLE(anv_instance, instance, _instance);
2455    vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
2456                    object, location, messageCode, pLayerPrefix, pMessage);
2457 }
2458 
2459 static struct anv_state
anv_state_pool_emit_data(struct anv_state_pool * pool,size_t size,size_t align,const void * p)2460 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
2461 {
2462    struct anv_state state;
2463 
2464    state = anv_state_pool_alloc(pool, size, align);
2465    memcpy(state.map, p, size);
2466 
2467    return state;
2468 }
2469 
2470 static void
anv_device_init_border_colors(struct anv_device * device)2471 anv_device_init_border_colors(struct anv_device *device)
2472 {
2473    if (device->info.is_haswell) {
2474       static const struct hsw_border_color border_colors[] = {
2475          [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] =  { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
2476          [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] =       { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
2477          [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] =       { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
2478          [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] =    { .uint32 = { 0, 0, 0, 0 } },
2479          [VK_BORDER_COLOR_INT_OPAQUE_BLACK] =         { .uint32 = { 0, 0, 0, 1 } },
2480          [VK_BORDER_COLOR_INT_OPAQUE_WHITE] =         { .uint32 = { 1, 1, 1, 1 } },
2481       };
2482 
2483       device->border_colors =
2484          anv_state_pool_emit_data(&device->dynamic_state_pool,
2485                                   sizeof(border_colors), 512, border_colors);
2486    } else {
2487       static const struct gen8_border_color border_colors[] = {
2488          [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] =  { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
2489          [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] =       { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
2490          [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] =       { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
2491          [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] =    { .uint32 = { 0, 0, 0, 0 } },
2492          [VK_BORDER_COLOR_INT_OPAQUE_BLACK] =         { .uint32 = { 0, 0, 0, 1 } },
2493          [VK_BORDER_COLOR_INT_OPAQUE_WHITE] =         { .uint32 = { 1, 1, 1, 1 } },
2494       };
2495 
2496       device->border_colors =
2497          anv_state_pool_emit_data(&device->dynamic_state_pool,
2498                                   sizeof(border_colors), 64, border_colors);
2499    }
2500 }
2501 
2502 static VkResult
anv_device_init_trivial_batch(struct anv_device * device)2503 anv_device_init_trivial_batch(struct anv_device *device)
2504 {
2505    VkResult result = anv_device_alloc_bo(device, 4096,
2506                                          ANV_BO_ALLOC_MAPPED,
2507                                          0 /* explicit_address */,
2508                                          &device->trivial_batch_bo);
2509    if (result != VK_SUCCESS)
2510       return result;
2511 
2512    struct anv_batch batch = {
2513       .start = device->trivial_batch_bo->map,
2514       .next = device->trivial_batch_bo->map,
2515       .end = device->trivial_batch_bo->map + 4096,
2516    };
2517 
2518    anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2519    anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2520 
2521    if (!device->info.has_llc)
2522       gen_clflush_range(batch.start, batch.next - batch.start);
2523 
2524    return VK_SUCCESS;
2525 }
2526 
anv_EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)2527 VkResult anv_EnumerateDeviceExtensionProperties(
2528     VkPhysicalDevice                            physicalDevice,
2529     const char*                                 pLayerName,
2530     uint32_t*                                   pPropertyCount,
2531     VkExtensionProperties*                      pProperties)
2532 {
2533    ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
2534    VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
2535 
2536    for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
2537       if (device->supported_extensions.extensions[i]) {
2538          vk_outarray_append(&out, prop) {
2539             *prop = anv_device_extensions[i];
2540          }
2541       }
2542    }
2543 
2544    return vk_outarray_status(&out);
2545 }
2546 
2547 static int
vk_priority_to_gen(int priority)2548 vk_priority_to_gen(int priority)
2549 {
2550    switch (priority) {
2551    case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
2552       return GEN_CONTEXT_LOW_PRIORITY;
2553    case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
2554       return GEN_CONTEXT_MEDIUM_PRIORITY;
2555    case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
2556       return GEN_CONTEXT_HIGH_PRIORITY;
2557    case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
2558       return GEN_CONTEXT_REALTIME_PRIORITY;
2559    default:
2560       unreachable("Invalid priority");
2561    }
2562 }
2563 
2564 static VkResult
anv_device_init_hiz_clear_value_bo(struct anv_device * device)2565 anv_device_init_hiz_clear_value_bo(struct anv_device *device)
2566 {
2567    VkResult result = anv_device_alloc_bo(device, 4096,
2568                                          ANV_BO_ALLOC_MAPPED,
2569                                          0 /* explicit_address */,
2570                                          &device->hiz_clear_bo);
2571    if (result != VK_SUCCESS)
2572       return result;
2573 
2574    union isl_color_value hiz_clear = { .u32 = { 0, } };
2575    hiz_clear.f32[0] = ANV_HZ_FC_VAL;
2576 
2577    memcpy(device->hiz_clear_bo->map, hiz_clear.u32, sizeof(hiz_clear.u32));
2578 
2579    if (!device->info.has_llc)
2580       gen_clflush_range(device->hiz_clear_bo->map, sizeof(hiz_clear.u32));
2581 
2582    return VK_SUCCESS;
2583 }
2584 
2585 static bool
get_bo_from_pool(struct gen_batch_decode_bo * ret,struct anv_block_pool * pool,uint64_t address)2586 get_bo_from_pool(struct gen_batch_decode_bo *ret,
2587                  struct anv_block_pool *pool,
2588                  uint64_t address)
2589 {
2590    anv_block_pool_foreach_bo(bo, pool) {
2591       uint64_t bo_address = gen_48b_address(bo->offset);
2592       if (address >= bo_address && address < (bo_address + bo->size)) {
2593          *ret = (struct gen_batch_decode_bo) {
2594             .addr = bo_address,
2595             .size = bo->size,
2596             .map = bo->map,
2597          };
2598          return true;
2599       }
2600    }
2601    return false;
2602 }
2603 
2604 /* Finding a buffer for batch decoding */
2605 static struct gen_batch_decode_bo
decode_get_bo(void * v_batch,bool ppgtt,uint64_t address)2606 decode_get_bo(void *v_batch, bool ppgtt, uint64_t address)
2607 {
2608    struct anv_device *device = v_batch;
2609    struct gen_batch_decode_bo ret_bo = {};
2610 
2611    assert(ppgtt);
2612 
2613    if (get_bo_from_pool(&ret_bo, &device->dynamic_state_pool.block_pool, address))
2614       return ret_bo;
2615    if (get_bo_from_pool(&ret_bo, &device->instruction_state_pool.block_pool, address))
2616       return ret_bo;
2617    if (get_bo_from_pool(&ret_bo, &device->binding_table_pool.block_pool, address))
2618       return ret_bo;
2619    if (get_bo_from_pool(&ret_bo, &device->surface_state_pool.block_pool, address))
2620       return ret_bo;
2621 
2622    if (!device->cmd_buffer_being_decoded)
2623       return (struct gen_batch_decode_bo) { };
2624 
2625    struct anv_batch_bo **bo;
2626 
2627    u_vector_foreach(bo, &device->cmd_buffer_being_decoded->seen_bbos) {
2628       /* The decoder zeroes out the top 16 bits, so we need to as well */
2629       uint64_t bo_address = (*bo)->bo->offset & (~0ull >> 16);
2630 
2631       if (address >= bo_address && address < bo_address + (*bo)->bo->size) {
2632          return (struct gen_batch_decode_bo) {
2633             .addr = bo_address,
2634             .size = (*bo)->bo->size,
2635             .map = (*bo)->bo->map,
2636          };
2637       }
2638    }
2639 
2640    return (struct gen_batch_decode_bo) { };
2641 }
2642 
2643 struct gen_aux_map_buffer {
2644    struct gen_buffer base;
2645    struct anv_state state;
2646 };
2647 
2648 static struct gen_buffer *
gen_aux_map_buffer_alloc(void * driver_ctx,uint32_t size)2649 gen_aux_map_buffer_alloc(void *driver_ctx, uint32_t size)
2650 {
2651    struct gen_aux_map_buffer *buf = malloc(sizeof(struct gen_aux_map_buffer));
2652    if (!buf)
2653       return NULL;
2654 
2655    struct anv_device *device = (struct anv_device*)driver_ctx;
2656    assert(device->physical->supports_48bit_addresses &&
2657           device->physical->use_softpin);
2658 
2659    struct anv_state_pool *pool = &device->dynamic_state_pool;
2660    buf->state = anv_state_pool_alloc(pool, size, size);
2661 
2662    buf->base.gpu = pool->block_pool.bo->offset + buf->state.offset;
2663    buf->base.gpu_end = buf->base.gpu + buf->state.alloc_size;
2664    buf->base.map = buf->state.map;
2665    buf->base.driver_bo = &buf->state;
2666    return &buf->base;
2667 }
2668 
2669 static void
gen_aux_map_buffer_free(void * driver_ctx,struct gen_buffer * buffer)2670 gen_aux_map_buffer_free(void *driver_ctx, struct gen_buffer *buffer)
2671 {
2672    struct gen_aux_map_buffer *buf = (struct gen_aux_map_buffer*)buffer;
2673    struct anv_device *device = (struct anv_device*)driver_ctx;
2674    struct anv_state_pool *pool = &device->dynamic_state_pool;
2675    anv_state_pool_free(pool, buf->state);
2676    free(buf);
2677 }
2678 
2679 static struct gen_mapped_pinned_buffer_alloc aux_map_allocator = {
2680    .alloc = gen_aux_map_buffer_alloc,
2681    .free = gen_aux_map_buffer_free,
2682 };
2683 
2684 static VkResult
check_physical_device_features(VkPhysicalDevice physicalDevice,const VkPhysicalDeviceFeatures * features)2685 check_physical_device_features(VkPhysicalDevice physicalDevice,
2686                                const VkPhysicalDeviceFeatures *features)
2687 {
2688    VkPhysicalDeviceFeatures supported_features;
2689    anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2690    VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2691    VkBool32 *enabled_feature = (VkBool32 *)features;
2692    unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2693    for (uint32_t i = 0; i < num_features; i++) {
2694       if (enabled_feature[i] && !supported_feature[i])
2695          return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2696    }
2697 
2698    return VK_SUCCESS;
2699 }
2700 
anv_CreateDevice(VkPhysicalDevice physicalDevice,const VkDeviceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkDevice * pDevice)2701 VkResult anv_CreateDevice(
2702     VkPhysicalDevice                            physicalDevice,
2703     const VkDeviceCreateInfo*                   pCreateInfo,
2704     const VkAllocationCallbacks*                pAllocator,
2705     VkDevice*                                   pDevice)
2706 {
2707    ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
2708    VkResult result;
2709    struct anv_device *device;
2710 
2711    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
2712 
2713    struct anv_device_extension_table enabled_extensions = { };
2714    for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
2715       int idx;
2716       for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
2717          if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
2718                     anv_device_extensions[idx].extensionName) == 0)
2719             break;
2720       }
2721 
2722       if (idx >= ANV_DEVICE_EXTENSION_COUNT)
2723          return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
2724 
2725       if (!physical_device->supported_extensions.extensions[idx])
2726          return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
2727 
2728       enabled_extensions.extensions[idx] = true;
2729    }
2730 
2731    /* Check enabled features */
2732    bool robust_buffer_access = false;
2733    if (pCreateInfo->pEnabledFeatures) {
2734       result = check_physical_device_features(physicalDevice,
2735                                               pCreateInfo->pEnabledFeatures);
2736       if (result != VK_SUCCESS)
2737          return result;
2738 
2739       if (pCreateInfo->pEnabledFeatures->robustBufferAccess)
2740          robust_buffer_access = true;
2741    }
2742 
2743    vk_foreach_struct_const(ext, pCreateInfo->pNext) {
2744       switch (ext->sType) {
2745       case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
2746          const VkPhysicalDeviceFeatures2 *features = (const void *)ext;
2747          result = check_physical_device_features(physicalDevice,
2748                                                  &features->features);
2749          if (result != VK_SUCCESS)
2750             return result;
2751 
2752          if (features->features.robustBufferAccess)
2753             robust_buffer_access = true;
2754          break;
2755       }
2756 
2757       default:
2758          /* Don't warn */
2759          break;
2760       }
2761    }
2762 
2763    /* Check requested queues and fail if we are requested to create any
2764     * queues with flags we don't support.
2765     */
2766    assert(pCreateInfo->queueCreateInfoCount > 0);
2767    for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
2768       if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
2769          return vk_error(VK_ERROR_INITIALIZATION_FAILED);
2770    }
2771 
2772    /* Check if client specified queue priority. */
2773    const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
2774       vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
2775                            DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
2776 
2777    VkQueueGlobalPriorityEXT priority =
2778       queue_priority ? queue_priority->globalPriority :
2779          VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
2780 
2781    device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
2782                        sizeof(*device), 8,
2783                        VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2784    if (!device)
2785       return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2786 
2787    vk_device_init(&device->vk, pCreateInfo,
2788                   &physical_device->instance->alloc, pAllocator);
2789 
2790    if (INTEL_DEBUG & DEBUG_BATCH) {
2791       const unsigned decode_flags =
2792          GEN_BATCH_DECODE_FULL |
2793          ((INTEL_DEBUG & DEBUG_COLOR) ? GEN_BATCH_DECODE_IN_COLOR : 0) |
2794          GEN_BATCH_DECODE_OFFSETS |
2795          GEN_BATCH_DECODE_FLOATS;
2796 
2797       gen_batch_decode_ctx_init(&device->decoder_ctx,
2798                                 &physical_device->info,
2799                                 stderr, decode_flags, NULL,
2800                                 decode_get_bo, NULL, device);
2801    }
2802 
2803    device->physical = physical_device;
2804    device->no_hw = physical_device->no_hw;
2805    device->_lost = false;
2806 
2807    /* XXX(chadv): Can we dup() physicalDevice->fd here? */
2808    device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
2809    if (device->fd == -1) {
2810       result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2811       goto fail_device;
2812    }
2813 
2814    device->context_id = anv_gem_create_context(device);
2815    if (device->context_id == -1) {
2816       result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2817       goto fail_fd;
2818    }
2819 
2820    device->has_thread_submit = physical_device->has_thread_submit;
2821 
2822    result = anv_queue_init(device, &device->queue);
2823    if (result != VK_SUCCESS)
2824       goto fail_context_id;
2825 
2826    if (physical_device->use_softpin) {
2827       if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
2828          result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2829          goto fail_queue;
2830       }
2831 
2832       /* keep the page with address zero out of the allocator */
2833       util_vma_heap_init(&device->vma_lo,
2834                          LOW_HEAP_MIN_ADDRESS, LOW_HEAP_SIZE);
2835 
2836       util_vma_heap_init(&device->vma_cva, CLIENT_VISIBLE_HEAP_MIN_ADDRESS,
2837                          CLIENT_VISIBLE_HEAP_SIZE);
2838 
2839       /* Leave the last 4GiB out of the high vma range, so that no state
2840        * base address + size can overflow 48 bits. For more information see
2841        * the comment about Wa32bitGeneralStateOffset in anv_allocator.c
2842        */
2843       util_vma_heap_init(&device->vma_hi, HIGH_HEAP_MIN_ADDRESS,
2844                          physical_device->gtt_size - (1ull << 32) -
2845                          HIGH_HEAP_MIN_ADDRESS);
2846    }
2847 
2848    list_inithead(&device->memory_objects);
2849 
2850    /* As per spec, the driver implementation may deny requests to acquire
2851     * a priority above the default priority (MEDIUM) if the caller does not
2852     * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
2853     * is returned.
2854     */
2855    if (physical_device->has_context_priority) {
2856       int err = anv_gem_set_context_param(device->fd, device->context_id,
2857                                           I915_CONTEXT_PARAM_PRIORITY,
2858                                           vk_priority_to_gen(priority));
2859       if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
2860          result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
2861          goto fail_vmas;
2862       }
2863    }
2864 
2865    device->info = physical_device->info;
2866    device->isl_dev = physical_device->isl_dev;
2867 
2868    /* On Broadwell and later, we can use batch chaining to more efficiently
2869     * implement growing command buffers.  Prior to Haswell, the kernel
2870     * command parser gets in the way and we have to fall back to growing
2871     * the batch.
2872     */
2873    device->can_chain_batches = device->info.gen >= 8;
2874 
2875    device->robust_buffer_access = robust_buffer_access;
2876    device->enabled_extensions = enabled_extensions;
2877 
2878    const struct anv_instance *instance = physical_device->instance;
2879    for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
2880       /* Vulkan requires that entrypoints for extensions which have not been
2881        * enabled must not be advertised.
2882        */
2883       if (!anv_device_entrypoint_is_enabled(i, instance->app_info.api_version,
2884                                             &instance->enabled_extensions,
2885                                             &device->enabled_extensions)) {
2886          device->dispatch.entrypoints[i] = NULL;
2887       } else {
2888          device->dispatch.entrypoints[i] =
2889             anv_resolve_device_entrypoint(&device->info, i);
2890       }
2891    }
2892 
2893    if (pthread_mutex_init(&device->mutex, NULL) != 0) {
2894       result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2895       goto fail_queue;
2896    }
2897 
2898    pthread_condattr_t condattr;
2899    if (pthread_condattr_init(&condattr) != 0) {
2900       result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2901       goto fail_mutex;
2902    }
2903    if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
2904       pthread_condattr_destroy(&condattr);
2905       result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2906       goto fail_mutex;
2907    }
2908    if (pthread_cond_init(&device->queue_submit, &condattr) != 0) {
2909       pthread_condattr_destroy(&condattr);
2910       result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2911       goto fail_mutex;
2912    }
2913    pthread_condattr_destroy(&condattr);
2914 
2915    result = anv_bo_cache_init(&device->bo_cache);
2916    if (result != VK_SUCCESS)
2917       goto fail_queue_cond;
2918 
2919    anv_bo_pool_init(&device->batch_bo_pool, device);
2920 
2921    result = anv_state_pool_init(&device->dynamic_state_pool, device,
2922                                 DYNAMIC_STATE_POOL_MIN_ADDRESS, 0, 16384);
2923    if (result != VK_SUCCESS)
2924       goto fail_batch_bo_pool;
2925 
2926    if (device->info.gen >= 8) {
2927       /* The border color pointer is limited to 24 bits, so we need to make
2928        * sure that any such color used at any point in the program doesn't
2929        * exceed that limit.
2930        * We achieve that by reserving all the custom border colors we support
2931        * right off the bat, so they are close to the base address.
2932        */
2933       anv_state_reserved_pool_init(&device->custom_border_colors,
2934                                    &device->dynamic_state_pool,
2935                                    MAX_CUSTOM_BORDER_COLORS,
2936                                    sizeof(struct gen8_border_color), 64);
2937    }
2938 
2939    result = anv_state_pool_init(&device->instruction_state_pool, device,
2940                                 INSTRUCTION_STATE_POOL_MIN_ADDRESS, 0, 16384);
2941    if (result != VK_SUCCESS)
2942       goto fail_dynamic_state_pool;
2943 
2944    result = anv_state_pool_init(&device->surface_state_pool, device,
2945                                 SURFACE_STATE_POOL_MIN_ADDRESS, 0, 4096);
2946    if (result != VK_SUCCESS)
2947       goto fail_instruction_state_pool;
2948 
2949    if (physical_device->use_softpin) {
2950       int64_t bt_pool_offset = (int64_t)BINDING_TABLE_POOL_MIN_ADDRESS -
2951                                (int64_t)SURFACE_STATE_POOL_MIN_ADDRESS;
2952       assert(INT32_MIN < bt_pool_offset && bt_pool_offset < 0);
2953       result = anv_state_pool_init(&device->binding_table_pool, device,
2954                                    SURFACE_STATE_POOL_MIN_ADDRESS,
2955                                    bt_pool_offset, 4096);
2956       if (result != VK_SUCCESS)
2957          goto fail_surface_state_pool;
2958    }
2959 
2960    if (device->info.has_aux_map) {
2961       device->aux_map_ctx = gen_aux_map_init(device, &aux_map_allocator,
2962                                              &physical_device->info);
2963       if (!device->aux_map_ctx)
2964          goto fail_binding_table_pool;
2965    }
2966 
2967    result = anv_device_alloc_bo(device, 4096,
2968                                 ANV_BO_ALLOC_CAPTURE | ANV_BO_ALLOC_MAPPED /* flags */,
2969                                 0 /* explicit_address */,
2970                                 &device->workaround_bo);
2971    if (result != VK_SUCCESS)
2972       goto fail_surface_aux_map_pool;
2973 
2974    device->workaround_address = (struct anv_address) {
2975       .bo = device->workaround_bo,
2976       .offset = align_u32(
2977          intel_debug_write_identifiers(device->workaround_bo->map,
2978                                        device->workaround_bo->size,
2979                                        "Anv") + 8, 8),
2980    };
2981 
2982    device->debug_frame_desc =
2983       intel_debug_get_identifier_block(device->workaround_bo->map,
2984                                        device->workaround_bo->size,
2985                                        GEN_DEBUG_BLOCK_TYPE_FRAME);
2986 
2987    result = anv_device_init_trivial_batch(device);
2988    if (result != VK_SUCCESS)
2989       goto fail_workaround_bo;
2990 
2991    /* Allocate a null surface state at surface state offset 0.  This makes
2992     * NULL descriptor handling trivial because we can just memset structures
2993     * to zero and they have a valid descriptor.
2994     */
2995    device->null_surface_state =
2996       anv_state_pool_alloc(&device->surface_state_pool,
2997                            device->isl_dev.ss.size,
2998                            device->isl_dev.ss.align);
2999    isl_null_fill_state(&device->isl_dev, device->null_surface_state.map,
3000                        isl_extent3d(1, 1, 1) /* This shouldn't matter */);
3001    assert(device->null_surface_state.offset == 0);
3002 
3003    if (device->info.gen >= 10) {
3004       result = anv_device_init_hiz_clear_value_bo(device);
3005       if (result != VK_SUCCESS)
3006          goto fail_trivial_batch_bo;
3007    }
3008 
3009    anv_scratch_pool_init(device, &device->scratch_pool);
3010 
3011    switch (device->info.gen) {
3012    case 7:
3013       if (!device->info.is_haswell)
3014          result = gen7_init_device_state(device);
3015       else
3016          result = gen75_init_device_state(device);
3017       break;
3018    case 8:
3019       result = gen8_init_device_state(device);
3020       break;
3021    case 9:
3022       result = gen9_init_device_state(device);
3023       break;
3024    case 11:
3025       result = gen11_init_device_state(device);
3026       break;
3027    case 12:
3028       result = gen12_init_device_state(device);
3029       break;
3030    default:
3031       /* Shouldn't get here as we don't create physical devices for any other
3032        * gens. */
3033       unreachable("unhandled gen");
3034    }
3035    if (result != VK_SUCCESS)
3036       goto fail_clear_value_bo;
3037 
3038    anv_pipeline_cache_init(&device->default_pipeline_cache, device,
3039                            true /* cache_enabled */, false /* external_sync */);
3040 
3041    anv_device_init_blorp(device);
3042 
3043    anv_device_init_border_colors(device);
3044 
3045    anv_device_perf_init(device);
3046 
3047    *pDevice = anv_device_to_handle(device);
3048 
3049    return VK_SUCCESS;
3050 
3051  fail_clear_value_bo:
3052    if (device->info.gen >= 10)
3053       anv_device_release_bo(device, device->hiz_clear_bo);
3054    anv_scratch_pool_finish(device, &device->scratch_pool);
3055  fail_trivial_batch_bo:
3056    anv_device_release_bo(device, device->trivial_batch_bo);
3057  fail_workaround_bo:
3058    anv_device_release_bo(device, device->workaround_bo);
3059  fail_surface_aux_map_pool:
3060    if (device->info.has_aux_map) {
3061       gen_aux_map_finish(device->aux_map_ctx);
3062       device->aux_map_ctx = NULL;
3063    }
3064  fail_binding_table_pool:
3065    if (physical_device->use_softpin)
3066       anv_state_pool_finish(&device->binding_table_pool);
3067  fail_surface_state_pool:
3068    anv_state_pool_finish(&device->surface_state_pool);
3069  fail_instruction_state_pool:
3070    anv_state_pool_finish(&device->instruction_state_pool);
3071  fail_dynamic_state_pool:
3072    if (device->info.gen >= 8)
3073       anv_state_reserved_pool_finish(&device->custom_border_colors);
3074    anv_state_pool_finish(&device->dynamic_state_pool);
3075  fail_batch_bo_pool:
3076    anv_bo_pool_finish(&device->batch_bo_pool);
3077    anv_bo_cache_finish(&device->bo_cache);
3078  fail_queue_cond:
3079    pthread_cond_destroy(&device->queue_submit);
3080  fail_mutex:
3081    pthread_mutex_destroy(&device->mutex);
3082  fail_vmas:
3083    if (physical_device->use_softpin) {
3084       util_vma_heap_finish(&device->vma_hi);
3085       util_vma_heap_finish(&device->vma_cva);
3086       util_vma_heap_finish(&device->vma_lo);
3087    }
3088  fail_queue:
3089    anv_queue_finish(&device->queue);
3090  fail_context_id:
3091    anv_gem_destroy_context(device, device->context_id);
3092  fail_fd:
3093    close(device->fd);
3094  fail_device:
3095    vk_free(&device->vk.alloc, device);
3096 
3097    return result;
3098 }
3099 
anv_DestroyDevice(VkDevice _device,const VkAllocationCallbacks * pAllocator)3100 void anv_DestroyDevice(
3101     VkDevice                                    _device,
3102     const VkAllocationCallbacks*                pAllocator)
3103 {
3104    ANV_FROM_HANDLE(anv_device, device, _device);
3105 
3106    if (!device)
3107       return;
3108 
3109    anv_queue_finish(&device->queue);
3110 
3111    anv_device_finish_blorp(device);
3112 
3113    anv_pipeline_cache_finish(&device->default_pipeline_cache);
3114 
3115 #ifdef HAVE_VALGRIND
3116    /* We only need to free these to prevent valgrind errors.  The backing
3117     * BO will go away in a couple of lines so we don't actually leak.
3118     */
3119    if (device->info.gen >= 8)
3120       anv_state_reserved_pool_finish(&device->custom_border_colors);
3121    anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
3122    anv_state_pool_free(&device->dynamic_state_pool, device->slice_hash);
3123 #endif
3124 
3125    anv_scratch_pool_finish(device, &device->scratch_pool);
3126 
3127    anv_device_release_bo(device, device->workaround_bo);
3128    anv_device_release_bo(device, device->trivial_batch_bo);
3129    if (device->info.gen >= 10)
3130       anv_device_release_bo(device, device->hiz_clear_bo);
3131 
3132    if (device->info.has_aux_map) {
3133       gen_aux_map_finish(device->aux_map_ctx);
3134       device->aux_map_ctx = NULL;
3135    }
3136 
3137    if (device->physical->use_softpin)
3138       anv_state_pool_finish(&device->binding_table_pool);
3139    anv_state_pool_finish(&device->surface_state_pool);
3140    anv_state_pool_finish(&device->instruction_state_pool);
3141    anv_state_pool_finish(&device->dynamic_state_pool);
3142 
3143    anv_bo_pool_finish(&device->batch_bo_pool);
3144 
3145    anv_bo_cache_finish(&device->bo_cache);
3146 
3147    if (device->physical->use_softpin) {
3148       util_vma_heap_finish(&device->vma_hi);
3149       util_vma_heap_finish(&device->vma_cva);
3150       util_vma_heap_finish(&device->vma_lo);
3151    }
3152 
3153    pthread_cond_destroy(&device->queue_submit);
3154    pthread_mutex_destroy(&device->mutex);
3155 
3156    anv_gem_destroy_context(device, device->context_id);
3157 
3158    if (INTEL_DEBUG & DEBUG_BATCH)
3159       gen_batch_decode_ctx_finish(&device->decoder_ctx);
3160 
3161    close(device->fd);
3162 
3163    vk_device_finish(&device->vk);
3164    vk_free(&device->vk.alloc, device);
3165 }
3166 
anv_EnumerateInstanceLayerProperties(uint32_t * pPropertyCount,VkLayerProperties * pProperties)3167 VkResult anv_EnumerateInstanceLayerProperties(
3168     uint32_t*                                   pPropertyCount,
3169     VkLayerProperties*                          pProperties)
3170 {
3171    if (pProperties == NULL) {
3172       *pPropertyCount = 0;
3173       return VK_SUCCESS;
3174    }
3175 
3176    /* None supported at this time */
3177    return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
3178 }
3179 
anv_EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,uint32_t * pPropertyCount,VkLayerProperties * pProperties)3180 VkResult anv_EnumerateDeviceLayerProperties(
3181     VkPhysicalDevice                            physicalDevice,
3182     uint32_t*                                   pPropertyCount,
3183     VkLayerProperties*                          pProperties)
3184 {
3185    if (pProperties == NULL) {
3186       *pPropertyCount = 0;
3187       return VK_SUCCESS;
3188    }
3189 
3190    /* None supported at this time */
3191    return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
3192 }
3193 
anv_GetDeviceQueue(VkDevice _device,uint32_t queueNodeIndex,uint32_t queueIndex,VkQueue * pQueue)3194 void anv_GetDeviceQueue(
3195     VkDevice                                    _device,
3196     uint32_t                                    queueNodeIndex,
3197     uint32_t                                    queueIndex,
3198     VkQueue*                                    pQueue)
3199 {
3200    const VkDeviceQueueInfo2 info = {
3201       .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
3202       .pNext = NULL,
3203       .flags = 0,
3204       .queueFamilyIndex = queueNodeIndex,
3205       .queueIndex = queueIndex,
3206    };
3207 
3208    anv_GetDeviceQueue2(_device, &info, pQueue);
3209 }
3210 
anv_GetDeviceQueue2(VkDevice _device,const VkDeviceQueueInfo2 * pQueueInfo,VkQueue * pQueue)3211 void anv_GetDeviceQueue2(
3212     VkDevice                                    _device,
3213     const VkDeviceQueueInfo2*                   pQueueInfo,
3214     VkQueue*                                    pQueue)
3215 {
3216    ANV_FROM_HANDLE(anv_device, device, _device);
3217 
3218    assert(pQueueInfo->queueIndex == 0);
3219 
3220    if (pQueueInfo->flags == device->queue.flags)
3221       *pQueue = anv_queue_to_handle(&device->queue);
3222    else
3223       *pQueue = NULL;
3224 }
3225 
3226 void
_anv_device_report_lost(struct anv_device * device)3227 _anv_device_report_lost(struct anv_device *device)
3228 {
3229    assert(p_atomic_read(&device->_lost) > 0);
3230 
3231    device->lost_reported = true;
3232 
3233    struct anv_queue *queue = &device->queue;
3234 
3235    __vk_errorf(device->physical->instance, device,
3236                VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
3237                VK_ERROR_DEVICE_LOST,
3238                queue->error_file, queue->error_line,
3239                "%s", queue->error_msg);
3240 }
3241 
3242 VkResult
_anv_device_set_lost(struct anv_device * device,const char * file,int line,const char * msg,...)3243 _anv_device_set_lost(struct anv_device *device,
3244                      const char *file, int line,
3245                      const char *msg, ...)
3246 {
3247    VkResult err;
3248    va_list ap;
3249 
3250    if (p_atomic_read(&device->_lost) > 0)
3251       return VK_ERROR_DEVICE_LOST;
3252 
3253    p_atomic_inc(&device->_lost);
3254    device->lost_reported = true;
3255 
3256    va_start(ap, msg);
3257    err = __vk_errorv(device->physical->instance, device,
3258                      VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
3259                      VK_ERROR_DEVICE_LOST, file, line, msg, ap);
3260    va_end(ap);
3261 
3262    if (env_var_as_boolean("ANV_ABORT_ON_DEVICE_LOSS", false))
3263       abort();
3264 
3265    return err;
3266 }
3267 
3268 VkResult
_anv_queue_set_lost(struct anv_queue * queue,const char * file,int line,const char * msg,...)3269 _anv_queue_set_lost(struct anv_queue *queue,
3270                      const char *file, int line,
3271                      const char *msg, ...)
3272 {
3273    va_list ap;
3274 
3275    if (queue->lost)
3276       return VK_ERROR_DEVICE_LOST;
3277 
3278    queue->lost = true;
3279 
3280    queue->error_file = file;
3281    queue->error_line = line;
3282    va_start(ap, msg);
3283    vsnprintf(queue->error_msg, sizeof(queue->error_msg),
3284              msg, ap);
3285    va_end(ap);
3286 
3287    p_atomic_inc(&queue->device->_lost);
3288 
3289    if (env_var_as_boolean("ANV_ABORT_ON_DEVICE_LOSS", false))
3290       abort();
3291 
3292    return VK_ERROR_DEVICE_LOST;
3293 }
3294 
3295 VkResult
anv_device_query_status(struct anv_device * device)3296 anv_device_query_status(struct anv_device *device)
3297 {
3298    /* This isn't likely as most of the callers of this function already check
3299     * for it.  However, it doesn't hurt to check and it potentially lets us
3300     * avoid an ioctl.
3301     */
3302    if (anv_device_is_lost(device))
3303       return VK_ERROR_DEVICE_LOST;
3304 
3305    uint32_t active, pending;
3306    int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
3307    if (ret == -1) {
3308       /* We don't know the real error. */
3309       return anv_device_set_lost(device, "get_reset_stats failed: %m");
3310    }
3311 
3312    if (active) {
3313       return anv_device_set_lost(device, "GPU hung on one of our command buffers");
3314    } else if (pending) {
3315       return anv_device_set_lost(device, "GPU hung with commands in-flight");
3316    }
3317 
3318    return VK_SUCCESS;
3319 }
3320 
3321 VkResult
anv_device_bo_busy(struct anv_device * device,struct anv_bo * bo)3322 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
3323 {
3324    /* Note:  This only returns whether or not the BO is in use by an i915 GPU.
3325     * Other usages of the BO (such as on different hardware) will not be
3326     * flagged as "busy" by this ioctl.  Use with care.
3327     */
3328    int ret = anv_gem_busy(device, bo->gem_handle);
3329    if (ret == 1) {
3330       return VK_NOT_READY;
3331    } else if (ret == -1) {
3332       /* We don't know the real error. */
3333       return anv_device_set_lost(device, "gem wait failed: %m");
3334    }
3335 
3336    /* Query for device status after the busy call.  If the BO we're checking
3337     * got caught in a GPU hang we don't want to return VK_SUCCESS to the
3338     * client because it clearly doesn't have valid data.  Yes, this most
3339     * likely means an ioctl, but we just did an ioctl to query the busy status
3340     * so it's no great loss.
3341     */
3342    return anv_device_query_status(device);
3343 }
3344 
3345 VkResult
anv_device_wait(struct anv_device * device,struct anv_bo * bo,int64_t timeout)3346 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
3347                 int64_t timeout)
3348 {
3349    int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
3350    if (ret == -1 && errno == ETIME) {
3351       return VK_TIMEOUT;
3352    } else if (ret == -1) {
3353       /* We don't know the real error. */
3354       return anv_device_set_lost(device, "gem wait failed: %m");
3355    }
3356 
3357    /* Query for device status after the wait.  If the BO we're waiting on got
3358     * caught in a GPU hang we don't want to return VK_SUCCESS to the client
3359     * because it clearly doesn't have valid data.  Yes, this most likely means
3360     * an ioctl, but we just did an ioctl to wait so it's no great loss.
3361     */
3362    return anv_device_query_status(device);
3363 }
3364 
anv_DeviceWaitIdle(VkDevice _device)3365 VkResult anv_DeviceWaitIdle(
3366     VkDevice                                    _device)
3367 {
3368    ANV_FROM_HANDLE(anv_device, device, _device);
3369 
3370    if (anv_device_is_lost(device))
3371       return VK_ERROR_DEVICE_LOST;
3372 
3373    return anv_queue_submit_simple_batch(&device->queue, NULL);
3374 }
3375 
3376 uint64_t
anv_vma_alloc(struct anv_device * device,uint64_t size,uint64_t align,enum anv_bo_alloc_flags alloc_flags,uint64_t client_address)3377 anv_vma_alloc(struct anv_device *device,
3378               uint64_t size, uint64_t align,
3379               enum anv_bo_alloc_flags alloc_flags,
3380               uint64_t client_address)
3381 {
3382    pthread_mutex_lock(&device->vma_mutex);
3383 
3384    uint64_t addr = 0;
3385 
3386    if (alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) {
3387       if (client_address) {
3388          if (util_vma_heap_alloc_addr(&device->vma_cva,
3389                                       client_address, size)) {
3390             addr = client_address;
3391          }
3392       } else {
3393          addr = util_vma_heap_alloc(&device->vma_cva, size, align);
3394       }
3395       /* We don't want to fall back to other heaps */
3396       goto done;
3397    }
3398 
3399    assert(client_address == 0);
3400 
3401    if (!(alloc_flags & ANV_BO_ALLOC_32BIT_ADDRESS))
3402       addr = util_vma_heap_alloc(&device->vma_hi, size, align);
3403 
3404    if (addr == 0)
3405       addr = util_vma_heap_alloc(&device->vma_lo, size, align);
3406 
3407 done:
3408    pthread_mutex_unlock(&device->vma_mutex);
3409 
3410    assert(addr == gen_48b_address(addr));
3411    return gen_canonical_address(addr);
3412 }
3413 
3414 void
anv_vma_free(struct anv_device * device,uint64_t address,uint64_t size)3415 anv_vma_free(struct anv_device *device,
3416              uint64_t address, uint64_t size)
3417 {
3418    const uint64_t addr_48b = gen_48b_address(address);
3419 
3420    pthread_mutex_lock(&device->vma_mutex);
3421 
3422    if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
3423        addr_48b <= LOW_HEAP_MAX_ADDRESS) {
3424       util_vma_heap_free(&device->vma_lo, addr_48b, size);
3425    } else if (addr_48b >= CLIENT_VISIBLE_HEAP_MIN_ADDRESS &&
3426               addr_48b <= CLIENT_VISIBLE_HEAP_MAX_ADDRESS) {
3427       util_vma_heap_free(&device->vma_cva, addr_48b, size);
3428    } else {
3429       assert(addr_48b >= HIGH_HEAP_MIN_ADDRESS);
3430       util_vma_heap_free(&device->vma_hi, addr_48b, size);
3431    }
3432 
3433    pthread_mutex_unlock(&device->vma_mutex);
3434 }
3435 
anv_AllocateMemory(VkDevice _device,const VkMemoryAllocateInfo * pAllocateInfo,const VkAllocationCallbacks * pAllocator,VkDeviceMemory * pMem)3436 VkResult anv_AllocateMemory(
3437     VkDevice                                    _device,
3438     const VkMemoryAllocateInfo*                 pAllocateInfo,
3439     const VkAllocationCallbacks*                pAllocator,
3440     VkDeviceMemory*                             pMem)
3441 {
3442    ANV_FROM_HANDLE(anv_device, device, _device);
3443    struct anv_physical_device *pdevice = device->physical;
3444    struct anv_device_memory *mem;
3445    VkResult result = VK_SUCCESS;
3446 
3447    assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
3448 
3449    /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
3450    assert(pAllocateInfo->allocationSize > 0);
3451 
3452    VkDeviceSize aligned_alloc_size =
3453       align_u64(pAllocateInfo->allocationSize, 4096);
3454 
3455    if (aligned_alloc_size > MAX_MEMORY_ALLOCATION_SIZE)
3456       return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
3457 
3458    assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
3459    struct anv_memory_type *mem_type =
3460       &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
3461    assert(mem_type->heapIndex < pdevice->memory.heap_count);
3462    struct anv_memory_heap *mem_heap =
3463       &pdevice->memory.heaps[mem_type->heapIndex];
3464 
3465    uint64_t mem_heap_used = p_atomic_read(&mem_heap->used);
3466    if (mem_heap_used + aligned_alloc_size > mem_heap->size)
3467       return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
3468 
3469    mem = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*mem), 8,
3470                     VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3471    if (mem == NULL)
3472       return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3473 
3474    assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
3475    vk_object_base_init(&device->vk, &mem->base, VK_OBJECT_TYPE_DEVICE_MEMORY);
3476    mem->type = mem_type;
3477    mem->map = NULL;
3478    mem->map_size = 0;
3479    mem->ahw = NULL;
3480    mem->host_ptr = NULL;
3481 
3482    enum anv_bo_alloc_flags alloc_flags = 0;
3483 
3484    const VkExportMemoryAllocateInfo *export_info = NULL;
3485    const VkImportAndroidHardwareBufferInfoANDROID *ahw_import_info = NULL;
3486    const VkImportMemoryFdInfoKHR *fd_info = NULL;
3487    const VkImportMemoryHostPointerInfoEXT *host_ptr_info = NULL;
3488    const VkMemoryDedicatedAllocateInfo *dedicated_info = NULL;
3489    VkMemoryAllocateFlags vk_flags = 0;
3490    uint64_t client_address = 0;
3491 
3492    vk_foreach_struct_const(ext, pAllocateInfo->pNext) {
3493       switch (ext->sType) {
3494       case VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO:
3495          export_info = (void *)ext;
3496          break;
3497 
3498       case VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID:
3499          ahw_import_info = (void *)ext;
3500          break;
3501 
3502       case VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR:
3503          fd_info = (void *)ext;
3504          break;
3505 
3506       case VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT:
3507          host_ptr_info = (void *)ext;
3508          break;
3509 
3510       case VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO: {
3511          const VkMemoryAllocateFlagsInfo *flags_info = (void *)ext;
3512          vk_flags = flags_info->flags;
3513          break;
3514       }
3515 
3516       case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO:
3517          dedicated_info = (void *)ext;
3518          break;
3519 
3520       case VK_STRUCTURE_TYPE_MEMORY_OPAQUE_CAPTURE_ADDRESS_ALLOCATE_INFO_KHR: {
3521          const VkMemoryOpaqueCaptureAddressAllocateInfoKHR *addr_info =
3522             (const VkMemoryOpaqueCaptureAddressAllocateInfoKHR *)ext;
3523          client_address = addr_info->opaqueCaptureAddress;
3524          break;
3525       }
3526 
3527       default:
3528          anv_debug_ignored_stype(ext->sType);
3529          break;
3530       }
3531    }
3532 
3533    /* By default, we want all VkDeviceMemory objects to support CCS */
3534    if (device->physical->has_implicit_ccs)
3535       alloc_flags |= ANV_BO_ALLOC_IMPLICIT_CCS;
3536 
3537    if (vk_flags & VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR)
3538       alloc_flags |= ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS;
3539 
3540    if ((export_info && export_info->handleTypes) ||
3541        (fd_info && fd_info->handleType) ||
3542        (host_ptr_info && host_ptr_info->handleType)) {
3543       /* Anything imported or exported is EXTERNAL */
3544       alloc_flags |= ANV_BO_ALLOC_EXTERNAL;
3545 
3546       /* We can't have implicit CCS on external memory with an AUX-table.
3547        * Doing so would require us to sync the aux tables across processes
3548        * which is impractical.
3549        */
3550       if (device->info.has_aux_map)
3551          alloc_flags &= ~ANV_BO_ALLOC_IMPLICIT_CCS;
3552    }
3553 
3554    /* Check if we need to support Android HW buffer export. If so,
3555     * create AHardwareBuffer and import memory from it.
3556     */
3557    bool android_export = false;
3558    if (export_info && export_info->handleTypes &
3559        VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)
3560       android_export = true;
3561 
3562    if (ahw_import_info) {
3563       result = anv_import_ahw_memory(_device, mem, ahw_import_info);
3564       if (result != VK_SUCCESS)
3565          goto fail;
3566 
3567       goto success;
3568    } else if (android_export) {
3569       result = anv_create_ahw_memory(_device, mem, pAllocateInfo);
3570       if (result != VK_SUCCESS)
3571          goto fail;
3572 
3573       const VkImportAndroidHardwareBufferInfoANDROID import_info = {
3574          .buffer = mem->ahw,
3575       };
3576       result = anv_import_ahw_memory(_device, mem, &import_info);
3577       if (result != VK_SUCCESS)
3578          goto fail;
3579 
3580       goto success;
3581    }
3582 
3583    /* The Vulkan spec permits handleType to be 0, in which case the struct is
3584     * ignored.
3585     */
3586    if (fd_info && fd_info->handleType) {
3587       /* At the moment, we support only the below handle types. */
3588       assert(fd_info->handleType ==
3589                VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3590              fd_info->handleType ==
3591                VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3592 
3593       result = anv_device_import_bo(device, fd_info->fd, alloc_flags,
3594                                     client_address, &mem->bo);
3595       if (result != VK_SUCCESS)
3596          goto fail;
3597 
3598       /* For security purposes, we reject importing the bo if it's smaller
3599        * than the requested allocation size.  This prevents a malicious client
3600        * from passing a buffer to a trusted client, lying about the size, and
3601        * telling the trusted client to try and texture from an image that goes
3602        * out-of-bounds.  This sort of thing could lead to GPU hangs or worse
3603        * in the trusted client.  The trusted client can protect itself against
3604        * this sort of attack but only if it can trust the buffer size.
3605        */
3606       if (mem->bo->size < aligned_alloc_size) {
3607          result = vk_errorf(device, device, VK_ERROR_INVALID_EXTERNAL_HANDLE,
3608                             "aligned allocationSize too large for "
3609                             "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT: "
3610                             "%"PRIu64"B > %"PRIu64"B",
3611                             aligned_alloc_size, mem->bo->size);
3612          anv_device_release_bo(device, mem->bo);
3613          goto fail;
3614       }
3615 
3616       /* From the Vulkan spec:
3617        *
3618        *    "Importing memory from a file descriptor transfers ownership of
3619        *    the file descriptor from the application to the Vulkan
3620        *    implementation. The application must not perform any operations on
3621        *    the file descriptor after a successful import."
3622        *
3623        * If the import fails, we leave the file descriptor open.
3624        */
3625       close(fd_info->fd);
3626       goto success;
3627    }
3628 
3629    if (host_ptr_info && host_ptr_info->handleType) {
3630       if (host_ptr_info->handleType ==
3631           VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT) {
3632          result = vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
3633          goto fail;
3634       }
3635 
3636       assert(host_ptr_info->handleType ==
3637              VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
3638 
3639       result = anv_device_import_bo_from_host_ptr(device,
3640                                                   host_ptr_info->pHostPointer,
3641                                                   pAllocateInfo->allocationSize,
3642                                                   alloc_flags,
3643                                                   client_address,
3644                                                   &mem->bo);
3645       if (result != VK_SUCCESS)
3646          goto fail;
3647 
3648       mem->host_ptr = host_ptr_info->pHostPointer;
3649       goto success;
3650    }
3651 
3652    /* Regular allocate (not importing memory). */
3653 
3654    result = anv_device_alloc_bo(device, pAllocateInfo->allocationSize,
3655                                 alloc_flags, client_address, &mem->bo);
3656    if (result != VK_SUCCESS)
3657       goto fail;
3658 
3659    if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
3660       ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
3661 
3662       /* Some legacy (non-modifiers) consumers need the tiling to be set on
3663        * the BO.  In this case, we have a dedicated allocation.
3664        */
3665       if (image->needs_set_tiling) {
3666          const uint32_t i915_tiling =
3667             isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
3668          int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
3669                                       image->planes[0].surface.isl.row_pitch_B,
3670                                       i915_tiling);
3671          if (ret) {
3672             anv_device_release_bo(device, mem->bo);
3673             result = vk_errorf(device, device, VK_ERROR_OUT_OF_DEVICE_MEMORY,
3674                                "failed to set BO tiling: %m");
3675             goto fail;
3676          }
3677       }
3678    }
3679 
3680  success:
3681    mem_heap_used = p_atomic_add_return(&mem_heap->used, mem->bo->size);
3682    if (mem_heap_used > mem_heap->size) {
3683       p_atomic_add(&mem_heap->used, -mem->bo->size);
3684       anv_device_release_bo(device, mem->bo);
3685       result = vk_errorf(device, device, VK_ERROR_OUT_OF_DEVICE_MEMORY,
3686                          "Out of heap memory");
3687       goto fail;
3688    }
3689 
3690    pthread_mutex_lock(&device->mutex);
3691    list_addtail(&mem->link, &device->memory_objects);
3692    pthread_mutex_unlock(&device->mutex);
3693 
3694    *pMem = anv_device_memory_to_handle(mem);
3695 
3696    return VK_SUCCESS;
3697 
3698  fail:
3699    vk_free2(&device->vk.alloc, pAllocator, mem);
3700 
3701    return result;
3702 }
3703 
anv_GetMemoryFdKHR(VkDevice device_h,const VkMemoryGetFdInfoKHR * pGetFdInfo,int * pFd)3704 VkResult anv_GetMemoryFdKHR(
3705     VkDevice                                    device_h,
3706     const VkMemoryGetFdInfoKHR*                 pGetFdInfo,
3707     int*                                        pFd)
3708 {
3709    ANV_FROM_HANDLE(anv_device, dev, device_h);
3710    ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
3711 
3712    assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
3713 
3714    assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3715           pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3716 
3717    return anv_device_export_bo(dev, mem->bo, pFd);
3718 }
3719 
anv_GetMemoryFdPropertiesKHR(VkDevice _device,VkExternalMemoryHandleTypeFlagBits handleType,int fd,VkMemoryFdPropertiesKHR * pMemoryFdProperties)3720 VkResult anv_GetMemoryFdPropertiesKHR(
3721     VkDevice                                    _device,
3722     VkExternalMemoryHandleTypeFlagBits          handleType,
3723     int                                         fd,
3724     VkMemoryFdPropertiesKHR*                    pMemoryFdProperties)
3725 {
3726    ANV_FROM_HANDLE(anv_device, device, _device);
3727 
3728    switch (handleType) {
3729    case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
3730       /* dma-buf can be imported as any memory type */
3731       pMemoryFdProperties->memoryTypeBits =
3732          (1 << device->physical->memory.type_count) - 1;
3733       return VK_SUCCESS;
3734 
3735    default:
3736       /* The valid usage section for this function says:
3737        *
3738        *    "handleType must not be one of the handle types defined as
3739        *    opaque."
3740        *
3741        * So opaque handle types fall into the default "unsupported" case.
3742        */
3743       return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
3744    }
3745 }
3746 
anv_GetMemoryHostPointerPropertiesEXT(VkDevice _device,VkExternalMemoryHandleTypeFlagBits handleType,const void * pHostPointer,VkMemoryHostPointerPropertiesEXT * pMemoryHostPointerProperties)3747 VkResult anv_GetMemoryHostPointerPropertiesEXT(
3748    VkDevice                                    _device,
3749    VkExternalMemoryHandleTypeFlagBits          handleType,
3750    const void*                                 pHostPointer,
3751    VkMemoryHostPointerPropertiesEXT*           pMemoryHostPointerProperties)
3752 {
3753    ANV_FROM_HANDLE(anv_device, device, _device);
3754 
3755    assert(pMemoryHostPointerProperties->sType ==
3756           VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT);
3757 
3758    switch (handleType) {
3759    case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT:
3760       /* Host memory can be imported as any memory type. */
3761       pMemoryHostPointerProperties->memoryTypeBits =
3762          (1ull << device->physical->memory.type_count) - 1;
3763 
3764       return VK_SUCCESS;
3765 
3766    default:
3767       return VK_ERROR_INVALID_EXTERNAL_HANDLE;
3768    }
3769 }
3770 
anv_FreeMemory(VkDevice _device,VkDeviceMemory _mem,const VkAllocationCallbacks * pAllocator)3771 void anv_FreeMemory(
3772     VkDevice                                    _device,
3773     VkDeviceMemory                              _mem,
3774     const VkAllocationCallbacks*                pAllocator)
3775 {
3776    ANV_FROM_HANDLE(anv_device, device, _device);
3777    ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
3778 
3779    if (mem == NULL)
3780       return;
3781 
3782    pthread_mutex_lock(&device->mutex);
3783    list_del(&mem->link);
3784    pthread_mutex_unlock(&device->mutex);
3785 
3786    if (mem->map)
3787       anv_UnmapMemory(_device, _mem);
3788 
3789    p_atomic_add(&device->physical->memory.heaps[mem->type->heapIndex].used,
3790                 -mem->bo->size);
3791 
3792    anv_device_release_bo(device, mem->bo);
3793 
3794 #if defined(ANDROID) && ANDROID_API_LEVEL >= 26
3795    if (mem->ahw)
3796       AHardwareBuffer_release(mem->ahw);
3797 #endif
3798 
3799    vk_object_base_finish(&mem->base);
3800    vk_free2(&device->vk.alloc, pAllocator, mem);
3801 }
3802 
anv_MapMemory(VkDevice _device,VkDeviceMemory _memory,VkDeviceSize offset,VkDeviceSize size,VkMemoryMapFlags flags,void ** ppData)3803 VkResult anv_MapMemory(
3804     VkDevice                                    _device,
3805     VkDeviceMemory                              _memory,
3806     VkDeviceSize                                offset,
3807     VkDeviceSize                                size,
3808     VkMemoryMapFlags                            flags,
3809     void**                                      ppData)
3810 {
3811    ANV_FROM_HANDLE(anv_device, device, _device);
3812    ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
3813 
3814    if (mem == NULL) {
3815       *ppData = NULL;
3816       return VK_SUCCESS;
3817    }
3818 
3819    if (mem->host_ptr) {
3820       *ppData = mem->host_ptr + offset;
3821       return VK_SUCCESS;
3822    }
3823 
3824    if (size == VK_WHOLE_SIZE)
3825       size = mem->bo->size - offset;
3826 
3827    /* From the Vulkan spec version 1.0.32 docs for MapMemory:
3828     *
3829     *  * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
3830     *    assert(size != 0);
3831     *  * If size is not equal to VK_WHOLE_SIZE, size must be less than or
3832     *    equal to the size of the memory minus offset
3833     */
3834    assert(size > 0);
3835    assert(offset + size <= mem->bo->size);
3836 
3837    /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
3838     * takes a VkDeviceMemory pointer, it seems like only one map of the memory
3839     * at a time is valid. We could just mmap up front and return an offset
3840     * pointer here, but that may exhaust virtual memory on 32 bit
3841     * userspace. */
3842 
3843    uint32_t gem_flags = 0;
3844 
3845    if (!device->info.has_llc &&
3846        (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
3847       gem_flags |= I915_MMAP_WC;
3848 
3849    /* GEM will fail to map if the offset isn't 4k-aligned.  Round down. */
3850    uint64_t map_offset;
3851    if (!device->physical->has_mmap_offset)
3852       map_offset = offset & ~4095ull;
3853    else
3854       map_offset = 0;
3855    assert(offset >= map_offset);
3856    uint64_t map_size = (offset + size) - map_offset;
3857 
3858    /* Let's map whole pages */
3859    map_size = align_u64(map_size, 4096);
3860 
3861    void *map = anv_gem_mmap(device, mem->bo->gem_handle,
3862                             map_offset, map_size, gem_flags);
3863    if (map == MAP_FAILED)
3864       return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
3865 
3866    mem->map = map;
3867    mem->map_size = map_size;
3868 
3869    *ppData = mem->map + (offset - map_offset);
3870 
3871    return VK_SUCCESS;
3872 }
3873 
anv_UnmapMemory(VkDevice _device,VkDeviceMemory _memory)3874 void anv_UnmapMemory(
3875     VkDevice                                    _device,
3876     VkDeviceMemory                              _memory)
3877 {
3878    ANV_FROM_HANDLE(anv_device, device, _device);
3879    ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
3880 
3881    if (mem == NULL || mem->host_ptr)
3882       return;
3883 
3884    anv_gem_munmap(device, mem->map, mem->map_size);
3885 
3886    mem->map = NULL;
3887    mem->map_size = 0;
3888 }
3889 
3890 static void
clflush_mapped_ranges(struct anv_device * device,uint32_t count,const VkMappedMemoryRange * ranges)3891 clflush_mapped_ranges(struct anv_device         *device,
3892                       uint32_t                   count,
3893                       const VkMappedMemoryRange *ranges)
3894 {
3895    for (uint32_t i = 0; i < count; i++) {
3896       ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
3897       if (ranges[i].offset >= mem->map_size)
3898          continue;
3899 
3900       gen_clflush_range(mem->map + ranges[i].offset,
3901                         MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
3902    }
3903 }
3904 
anv_FlushMappedMemoryRanges(VkDevice _device,uint32_t memoryRangeCount,const VkMappedMemoryRange * pMemoryRanges)3905 VkResult anv_FlushMappedMemoryRanges(
3906     VkDevice                                    _device,
3907     uint32_t                                    memoryRangeCount,
3908     const VkMappedMemoryRange*                  pMemoryRanges)
3909 {
3910    ANV_FROM_HANDLE(anv_device, device, _device);
3911 
3912    if (device->info.has_llc)
3913       return VK_SUCCESS;
3914 
3915    /* Make sure the writes we're flushing have landed. */
3916    __builtin_ia32_mfence();
3917 
3918    clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
3919 
3920    return VK_SUCCESS;
3921 }
3922 
anv_InvalidateMappedMemoryRanges(VkDevice _device,uint32_t memoryRangeCount,const VkMappedMemoryRange * pMemoryRanges)3923 VkResult anv_InvalidateMappedMemoryRanges(
3924     VkDevice                                    _device,
3925     uint32_t                                    memoryRangeCount,
3926     const VkMappedMemoryRange*                  pMemoryRanges)
3927 {
3928    ANV_FROM_HANDLE(anv_device, device, _device);
3929 
3930    if (device->info.has_llc)
3931       return VK_SUCCESS;
3932 
3933    clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
3934 
3935    /* Make sure no reads get moved up above the invalidate. */
3936    __builtin_ia32_mfence();
3937 
3938    return VK_SUCCESS;
3939 }
3940 
anv_GetBufferMemoryRequirements(VkDevice _device,VkBuffer _buffer,VkMemoryRequirements * pMemoryRequirements)3941 void anv_GetBufferMemoryRequirements(
3942     VkDevice                                    _device,
3943     VkBuffer                                    _buffer,
3944     VkMemoryRequirements*                       pMemoryRequirements)
3945 {
3946    ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3947    ANV_FROM_HANDLE(anv_device, device, _device);
3948 
3949    /* The Vulkan spec (git aaed022) says:
3950     *
3951     *    memoryTypeBits is a bitfield and contains one bit set for every
3952     *    supported memory type for the resource. The bit `1<<i` is set if and
3953     *    only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
3954     *    structure for the physical device is supported.
3955     */
3956    uint32_t memory_types = (1ull << device->physical->memory.type_count) - 1;
3957 
3958    /* Base alignment requirement of a cache line */
3959    uint32_t alignment = 16;
3960 
3961    if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
3962       alignment = MAX2(alignment, ANV_UBO_ALIGNMENT);
3963 
3964    pMemoryRequirements->size = buffer->size;
3965    pMemoryRequirements->alignment = alignment;
3966 
3967    /* Storage and Uniform buffers should have their size aligned to
3968     * 32-bits to avoid boundary checks when last DWord is not complete.
3969     * This would ensure that not internal padding would be needed for
3970     * 16-bit types.
3971     */
3972    if (device->robust_buffer_access &&
3973        (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
3974         buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
3975       pMemoryRequirements->size = align_u64(buffer->size, 4);
3976 
3977    pMemoryRequirements->memoryTypeBits = memory_types;
3978 }
3979 
anv_GetBufferMemoryRequirements2(VkDevice _device,const VkBufferMemoryRequirementsInfo2 * pInfo,VkMemoryRequirements2 * pMemoryRequirements)3980 void anv_GetBufferMemoryRequirements2(
3981     VkDevice                                    _device,
3982     const VkBufferMemoryRequirementsInfo2*      pInfo,
3983     VkMemoryRequirements2*                      pMemoryRequirements)
3984 {
3985    anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
3986                                    &pMemoryRequirements->memoryRequirements);
3987 
3988    vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3989       switch (ext->sType) {
3990       case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3991          VkMemoryDedicatedRequirements *requirements = (void *)ext;
3992          requirements->prefersDedicatedAllocation = false;
3993          requirements->requiresDedicatedAllocation = false;
3994          break;
3995       }
3996 
3997       default:
3998          anv_debug_ignored_stype(ext->sType);
3999          break;
4000       }
4001    }
4002 }
4003 
anv_GetImageMemoryRequirements(VkDevice _device,VkImage _image,VkMemoryRequirements * pMemoryRequirements)4004 void anv_GetImageMemoryRequirements(
4005     VkDevice                                    _device,
4006     VkImage                                     _image,
4007     VkMemoryRequirements*                       pMemoryRequirements)
4008 {
4009    ANV_FROM_HANDLE(anv_image, image, _image);
4010    ANV_FROM_HANDLE(anv_device, device, _device);
4011 
4012    /* The Vulkan spec (git aaed022) says:
4013     *
4014     *    memoryTypeBits is a bitfield and contains one bit set for every
4015     *    supported memory type for the resource. The bit `1<<i` is set if and
4016     *    only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
4017     *    structure for the physical device is supported.
4018     *
4019     * All types are currently supported for images.
4020     */
4021    uint32_t memory_types = (1ull << device->physical->memory.type_count) - 1;
4022 
4023    pMemoryRequirements->size = image->size;
4024    pMemoryRequirements->alignment = image->alignment;
4025    pMemoryRequirements->memoryTypeBits = memory_types;
4026 }
4027 
anv_GetImageMemoryRequirements2(VkDevice _device,const VkImageMemoryRequirementsInfo2 * pInfo,VkMemoryRequirements2 * pMemoryRequirements)4028 void anv_GetImageMemoryRequirements2(
4029     VkDevice                                    _device,
4030     const VkImageMemoryRequirementsInfo2*       pInfo,
4031     VkMemoryRequirements2*                      pMemoryRequirements)
4032 {
4033    ANV_FROM_HANDLE(anv_device, device, _device);
4034    ANV_FROM_HANDLE(anv_image, image, pInfo->image);
4035 
4036    anv_GetImageMemoryRequirements(_device, pInfo->image,
4037                                   &pMemoryRequirements->memoryRequirements);
4038 
4039    vk_foreach_struct_const(ext, pInfo->pNext) {
4040       switch (ext->sType) {
4041       case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
4042          const VkImagePlaneMemoryRequirementsInfo *plane_reqs =
4043             (const VkImagePlaneMemoryRequirementsInfo *) ext;
4044          uint32_t plane = anv_image_aspect_to_plane(image->aspects,
4045                                                     plane_reqs->planeAspect);
4046 
4047          assert(image->planes[plane].offset == 0);
4048 
4049          /* The Vulkan spec (git aaed022) says:
4050           *
4051           *    memoryTypeBits is a bitfield and contains one bit set for every
4052           *    supported memory type for the resource. The bit `1<<i` is set
4053           *    if and only if the memory type `i` in the
4054           *    VkPhysicalDeviceMemoryProperties structure for the physical
4055           *    device is supported.
4056           *
4057           * All types are currently supported for images.
4058           */
4059          pMemoryRequirements->memoryRequirements.memoryTypeBits =
4060                (1ull << device->physical->memory.type_count) - 1;
4061 
4062          pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
4063          pMemoryRequirements->memoryRequirements.alignment =
4064             image->planes[plane].alignment;
4065          break;
4066       }
4067 
4068       default:
4069          anv_debug_ignored_stype(ext->sType);
4070          break;
4071       }
4072    }
4073 
4074    vk_foreach_struct(ext, pMemoryRequirements->pNext) {
4075       switch (ext->sType) {
4076       case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4077          VkMemoryDedicatedRequirements *requirements = (void *)ext;
4078          if (image->needs_set_tiling || image->external_format) {
4079             /* If we need to set the tiling for external consumers, we need a
4080              * dedicated allocation.
4081              *
4082              * See also anv_AllocateMemory.
4083              */
4084             requirements->prefersDedicatedAllocation = true;
4085             requirements->requiresDedicatedAllocation = true;
4086          } else {
4087             requirements->prefersDedicatedAllocation = false;
4088             requirements->requiresDedicatedAllocation = false;
4089          }
4090          break;
4091       }
4092 
4093       default:
4094          anv_debug_ignored_stype(ext->sType);
4095          break;
4096       }
4097    }
4098 }
4099 
anv_GetImageSparseMemoryRequirements(VkDevice device,VkImage image,uint32_t * pSparseMemoryRequirementCount,VkSparseImageMemoryRequirements * pSparseMemoryRequirements)4100 void anv_GetImageSparseMemoryRequirements(
4101     VkDevice                                    device,
4102     VkImage                                     image,
4103     uint32_t*                                   pSparseMemoryRequirementCount,
4104     VkSparseImageMemoryRequirements*            pSparseMemoryRequirements)
4105 {
4106    *pSparseMemoryRequirementCount = 0;
4107 }
4108 
anv_GetImageSparseMemoryRequirements2(VkDevice device,const VkImageSparseMemoryRequirementsInfo2 * pInfo,uint32_t * pSparseMemoryRequirementCount,VkSparseImageMemoryRequirements2 * pSparseMemoryRequirements)4109 void anv_GetImageSparseMemoryRequirements2(
4110     VkDevice                                    device,
4111     const VkImageSparseMemoryRequirementsInfo2* pInfo,
4112     uint32_t*                                   pSparseMemoryRequirementCount,
4113     VkSparseImageMemoryRequirements2*           pSparseMemoryRequirements)
4114 {
4115    *pSparseMemoryRequirementCount = 0;
4116 }
4117 
anv_GetDeviceMemoryCommitment(VkDevice device,VkDeviceMemory memory,VkDeviceSize * pCommittedMemoryInBytes)4118 void anv_GetDeviceMemoryCommitment(
4119     VkDevice                                    device,
4120     VkDeviceMemory                              memory,
4121     VkDeviceSize*                               pCommittedMemoryInBytes)
4122 {
4123    *pCommittedMemoryInBytes = 0;
4124 }
4125 
4126 static void
anv_bind_buffer_memory(const VkBindBufferMemoryInfo * pBindInfo)4127 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
4128 {
4129    ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
4130    ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
4131 
4132    assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
4133 
4134    if (mem) {
4135       buffer->address = (struct anv_address) {
4136          .bo = mem->bo,
4137          .offset = pBindInfo->memoryOffset,
4138       };
4139    } else {
4140       buffer->address = ANV_NULL_ADDRESS;
4141    }
4142 }
4143 
anv_BindBufferMemory(VkDevice device,VkBuffer buffer,VkDeviceMemory memory,VkDeviceSize memoryOffset)4144 VkResult anv_BindBufferMemory(
4145     VkDevice                                    device,
4146     VkBuffer                                    buffer,
4147     VkDeviceMemory                              memory,
4148     VkDeviceSize                                memoryOffset)
4149 {
4150    anv_bind_buffer_memory(
4151       &(VkBindBufferMemoryInfo) {
4152          .sType         = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
4153          .buffer        = buffer,
4154          .memory        = memory,
4155          .memoryOffset  = memoryOffset,
4156       });
4157 
4158    return VK_SUCCESS;
4159 }
4160 
anv_BindBufferMemory2(VkDevice device,uint32_t bindInfoCount,const VkBindBufferMemoryInfo * pBindInfos)4161 VkResult anv_BindBufferMemory2(
4162     VkDevice                                    device,
4163     uint32_t                                    bindInfoCount,
4164     const VkBindBufferMemoryInfo*               pBindInfos)
4165 {
4166    for (uint32_t i = 0; i < bindInfoCount; i++)
4167       anv_bind_buffer_memory(&pBindInfos[i]);
4168 
4169    return VK_SUCCESS;
4170 }
4171 
anv_QueueBindSparse(VkQueue _queue,uint32_t bindInfoCount,const VkBindSparseInfo * pBindInfo,VkFence fence)4172 VkResult anv_QueueBindSparse(
4173     VkQueue                                     _queue,
4174     uint32_t                                    bindInfoCount,
4175     const VkBindSparseInfo*                     pBindInfo,
4176     VkFence                                     fence)
4177 {
4178    ANV_FROM_HANDLE(anv_queue, queue, _queue);
4179    if (anv_device_is_lost(queue->device))
4180       return VK_ERROR_DEVICE_LOST;
4181 
4182    return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
4183 }
4184 
4185 // Event functions
4186 
anv_CreateEvent(VkDevice _device,const VkEventCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkEvent * pEvent)4187 VkResult anv_CreateEvent(
4188     VkDevice                                    _device,
4189     const VkEventCreateInfo*                    pCreateInfo,
4190     const VkAllocationCallbacks*                pAllocator,
4191     VkEvent*                                    pEvent)
4192 {
4193    ANV_FROM_HANDLE(anv_device, device, _device);
4194    struct anv_event *event;
4195 
4196    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
4197 
4198    event = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*event), 8,
4199                      VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4200    if (event == NULL)
4201       return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4202 
4203    vk_object_base_init(&device->vk, &event->base, VK_OBJECT_TYPE_EVENT);
4204    event->state = anv_state_pool_alloc(&device->dynamic_state_pool,
4205                                        sizeof(uint64_t), 8);
4206    *(uint64_t *)event->state.map = VK_EVENT_RESET;
4207 
4208    *pEvent = anv_event_to_handle(event);
4209 
4210    return VK_SUCCESS;
4211 }
4212 
anv_DestroyEvent(VkDevice _device,VkEvent _event,const VkAllocationCallbacks * pAllocator)4213 void anv_DestroyEvent(
4214     VkDevice                                    _device,
4215     VkEvent                                     _event,
4216     const VkAllocationCallbacks*                pAllocator)
4217 {
4218    ANV_FROM_HANDLE(anv_device, device, _device);
4219    ANV_FROM_HANDLE(anv_event, event, _event);
4220 
4221    if (!event)
4222       return;
4223 
4224    anv_state_pool_free(&device->dynamic_state_pool, event->state);
4225 
4226    vk_object_base_finish(&event->base);
4227    vk_free2(&device->vk.alloc, pAllocator, event);
4228 }
4229 
anv_GetEventStatus(VkDevice _device,VkEvent _event)4230 VkResult anv_GetEventStatus(
4231     VkDevice                                    _device,
4232     VkEvent                                     _event)
4233 {
4234    ANV_FROM_HANDLE(anv_device, device, _device);
4235    ANV_FROM_HANDLE(anv_event, event, _event);
4236 
4237    if (anv_device_is_lost(device))
4238       return VK_ERROR_DEVICE_LOST;
4239 
4240    return *(uint64_t *)event->state.map;
4241 }
4242 
anv_SetEvent(VkDevice _device,VkEvent _event)4243 VkResult anv_SetEvent(
4244     VkDevice                                    _device,
4245     VkEvent                                     _event)
4246 {
4247    ANV_FROM_HANDLE(anv_event, event, _event);
4248 
4249    *(uint64_t *)event->state.map = VK_EVENT_SET;
4250 
4251    return VK_SUCCESS;
4252 }
4253 
anv_ResetEvent(VkDevice _device,VkEvent _event)4254 VkResult anv_ResetEvent(
4255     VkDevice                                    _device,
4256     VkEvent                                     _event)
4257 {
4258    ANV_FROM_HANDLE(anv_event, event, _event);
4259 
4260    *(uint64_t *)event->state.map = VK_EVENT_RESET;
4261 
4262    return VK_SUCCESS;
4263 }
4264 
4265 // Buffer functions
4266 
anv_CreateBuffer(VkDevice _device,const VkBufferCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkBuffer * pBuffer)4267 VkResult anv_CreateBuffer(
4268     VkDevice                                    _device,
4269     const VkBufferCreateInfo*                   pCreateInfo,
4270     const VkAllocationCallbacks*                pAllocator,
4271     VkBuffer*                                   pBuffer)
4272 {
4273    ANV_FROM_HANDLE(anv_device, device, _device);
4274    struct anv_buffer *buffer;
4275 
4276    /* Don't allow creating buffers bigger than our address space.  The real
4277     * issue here is that we may align up the buffer size and we don't want
4278     * doing so to cause roll-over.  However, no one has any business
4279     * allocating a buffer larger than our GTT size.
4280     */
4281    if (pCreateInfo->size > device->physical->gtt_size)
4282       return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
4283 
4284    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
4285 
4286    buffer = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*buffer), 8,
4287                        VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4288    if (buffer == NULL)
4289       return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4290 
4291    vk_object_base_init(&device->vk, &buffer->base, VK_OBJECT_TYPE_BUFFER);
4292    buffer->size = pCreateInfo->size;
4293    buffer->usage = pCreateInfo->usage;
4294    buffer->address = ANV_NULL_ADDRESS;
4295 
4296    *pBuffer = anv_buffer_to_handle(buffer);
4297 
4298    return VK_SUCCESS;
4299 }
4300 
anv_DestroyBuffer(VkDevice _device,VkBuffer _buffer,const VkAllocationCallbacks * pAllocator)4301 void anv_DestroyBuffer(
4302     VkDevice                                    _device,
4303     VkBuffer                                    _buffer,
4304     const VkAllocationCallbacks*                pAllocator)
4305 {
4306    ANV_FROM_HANDLE(anv_device, device, _device);
4307    ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
4308 
4309    if (!buffer)
4310       return;
4311 
4312    vk_object_base_finish(&buffer->base);
4313    vk_free2(&device->vk.alloc, pAllocator, buffer);
4314 }
4315 
anv_GetBufferDeviceAddress(VkDevice device,const VkBufferDeviceAddressInfoKHR * pInfo)4316 VkDeviceAddress anv_GetBufferDeviceAddress(
4317     VkDevice                                    device,
4318     const VkBufferDeviceAddressInfoKHR*         pInfo)
4319 {
4320    ANV_FROM_HANDLE(anv_buffer, buffer, pInfo->buffer);
4321 
4322    assert(!anv_address_is_null(buffer->address));
4323    assert(buffer->address.bo->flags & EXEC_OBJECT_PINNED);
4324 
4325    return anv_address_physical(buffer->address);
4326 }
4327 
anv_GetBufferOpaqueCaptureAddress(VkDevice device,const VkBufferDeviceAddressInfoKHR * pInfo)4328 uint64_t anv_GetBufferOpaqueCaptureAddress(
4329     VkDevice                                    device,
4330     const VkBufferDeviceAddressInfoKHR*         pInfo)
4331 {
4332    return 0;
4333 }
4334 
anv_GetDeviceMemoryOpaqueCaptureAddress(VkDevice device,const VkDeviceMemoryOpaqueCaptureAddressInfoKHR * pInfo)4335 uint64_t anv_GetDeviceMemoryOpaqueCaptureAddress(
4336     VkDevice                                    device,
4337     const VkDeviceMemoryOpaqueCaptureAddressInfoKHR* pInfo)
4338 {
4339    ANV_FROM_HANDLE(anv_device_memory, memory, pInfo->memory);
4340 
4341    assert(memory->bo->flags & EXEC_OBJECT_PINNED);
4342    assert(memory->bo->has_client_visible_address);
4343 
4344    return gen_48b_address(memory->bo->offset);
4345 }
4346 
4347 void
anv_fill_buffer_surface_state(struct anv_device * device,struct anv_state state,enum isl_format format,isl_surf_usage_flags_t usage,struct anv_address address,uint32_t range,uint32_t stride)4348 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
4349                               enum isl_format format,
4350                               isl_surf_usage_flags_t usage,
4351                               struct anv_address address,
4352                               uint32_t range, uint32_t stride)
4353 {
4354    isl_buffer_fill_state(&device->isl_dev, state.map,
4355                          .address = anv_address_physical(address),
4356                          .mocs = isl_mocs(&device->isl_dev, usage),
4357                          .size_B = range,
4358                          .format = format,
4359                          .swizzle = ISL_SWIZZLE_IDENTITY,
4360                          .stride_B = stride);
4361 }
4362 
anv_DestroySampler(VkDevice _device,VkSampler _sampler,const VkAllocationCallbacks * pAllocator)4363 void anv_DestroySampler(
4364     VkDevice                                    _device,
4365     VkSampler                                   _sampler,
4366     const VkAllocationCallbacks*                pAllocator)
4367 {
4368    ANV_FROM_HANDLE(anv_device, device, _device);
4369    ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
4370 
4371    if (!sampler)
4372       return;
4373 
4374    if (sampler->bindless_state.map) {
4375       anv_state_pool_free(&device->dynamic_state_pool,
4376                           sampler->bindless_state);
4377    }
4378 
4379    if (sampler->custom_border_color.map) {
4380       anv_state_reserved_pool_free(&device->custom_border_colors,
4381                                    sampler->custom_border_color);
4382    }
4383 
4384    vk_object_base_finish(&sampler->base);
4385    vk_free2(&device->vk.alloc, pAllocator, sampler);
4386 }
4387 
anv_CreateFramebuffer(VkDevice _device,const VkFramebufferCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkFramebuffer * pFramebuffer)4388 VkResult anv_CreateFramebuffer(
4389     VkDevice                                    _device,
4390     const VkFramebufferCreateInfo*              pCreateInfo,
4391     const VkAllocationCallbacks*                pAllocator,
4392     VkFramebuffer*                              pFramebuffer)
4393 {
4394    ANV_FROM_HANDLE(anv_device, device, _device);
4395    struct anv_framebuffer *framebuffer;
4396 
4397    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
4398 
4399    size_t size = sizeof(*framebuffer);
4400 
4401    /* VK_KHR_imageless_framebuffer extension says:
4402     *
4403     *    If flags includes VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR,
4404     *    parameter pAttachments is ignored.
4405     */
4406    if (!(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
4407       size += sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
4408       framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
4409                               VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4410       if (framebuffer == NULL)
4411          return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4412 
4413       for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
4414          ANV_FROM_HANDLE(anv_image_view, iview, pCreateInfo->pAttachments[i]);
4415          framebuffer->attachments[i] = iview;
4416       }
4417       framebuffer->attachment_count = pCreateInfo->attachmentCount;
4418    } else {
4419       framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
4420                               VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4421       if (framebuffer == NULL)
4422          return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4423 
4424       framebuffer->attachment_count = 0;
4425    }
4426 
4427    vk_object_base_init(&device->vk, &framebuffer->base,
4428                        VK_OBJECT_TYPE_FRAMEBUFFER);
4429 
4430    framebuffer->width = pCreateInfo->width;
4431    framebuffer->height = pCreateInfo->height;
4432    framebuffer->layers = pCreateInfo->layers;
4433 
4434    *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
4435 
4436    return VK_SUCCESS;
4437 }
4438 
anv_DestroyFramebuffer(VkDevice _device,VkFramebuffer _fb,const VkAllocationCallbacks * pAllocator)4439 void anv_DestroyFramebuffer(
4440     VkDevice                                    _device,
4441     VkFramebuffer                               _fb,
4442     const VkAllocationCallbacks*                pAllocator)
4443 {
4444    ANV_FROM_HANDLE(anv_device, device, _device);
4445    ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
4446 
4447    if (!fb)
4448       return;
4449 
4450    vk_object_base_finish(&fb->base);
4451    vk_free2(&device->vk.alloc, pAllocator, fb);
4452 }
4453 
4454 static const VkTimeDomainEXT anv_time_domains[] = {
4455    VK_TIME_DOMAIN_DEVICE_EXT,
4456    VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
4457 #ifdef CLOCK_MONOTONIC_RAW
4458    VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
4459 #endif
4460 };
4461 
anv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(VkPhysicalDevice physicalDevice,uint32_t * pTimeDomainCount,VkTimeDomainEXT * pTimeDomains)4462 VkResult anv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
4463    VkPhysicalDevice                             physicalDevice,
4464    uint32_t                                     *pTimeDomainCount,
4465    VkTimeDomainEXT                              *pTimeDomains)
4466 {
4467    int d;
4468    VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
4469 
4470    for (d = 0; d < ARRAY_SIZE(anv_time_domains); d++) {
4471       vk_outarray_append(&out, i) {
4472          *i = anv_time_domains[d];
4473       }
4474    }
4475 
4476    return vk_outarray_status(&out);
4477 }
4478 
4479 static uint64_t
anv_clock_gettime(clockid_t clock_id)4480 anv_clock_gettime(clockid_t clock_id)
4481 {
4482    struct timespec current;
4483    int ret;
4484 
4485    ret = clock_gettime(clock_id, &current);
4486 #ifdef CLOCK_MONOTONIC_RAW
4487    if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
4488       ret = clock_gettime(CLOCK_MONOTONIC, &current);
4489 #endif
4490    if (ret < 0)
4491       return 0;
4492 
4493    return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
4494 }
4495 
anv_GetCalibratedTimestampsEXT(VkDevice _device,uint32_t timestampCount,const VkCalibratedTimestampInfoEXT * pTimestampInfos,uint64_t * pTimestamps,uint64_t * pMaxDeviation)4496 VkResult anv_GetCalibratedTimestampsEXT(
4497    VkDevice                                     _device,
4498    uint32_t                                     timestampCount,
4499    const VkCalibratedTimestampInfoEXT           *pTimestampInfos,
4500    uint64_t                                     *pTimestamps,
4501    uint64_t                                     *pMaxDeviation)
4502 {
4503    ANV_FROM_HANDLE(anv_device, device, _device);
4504    uint64_t timestamp_frequency = device->info.timestamp_frequency;
4505    int  ret;
4506    int d;
4507    uint64_t begin, end;
4508    uint64_t max_clock_period = 0;
4509 
4510 #ifdef CLOCK_MONOTONIC_RAW
4511    begin = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
4512 #else
4513    begin = anv_clock_gettime(CLOCK_MONOTONIC);
4514 #endif
4515 
4516    for (d = 0; d < timestampCount; d++) {
4517       switch (pTimestampInfos[d].timeDomain) {
4518       case VK_TIME_DOMAIN_DEVICE_EXT:
4519          ret = anv_gem_reg_read(device->fd, TIMESTAMP | I915_REG_READ_8B_WA,
4520                                 &pTimestamps[d]);
4521 
4522          if (ret != 0) {
4523             return anv_device_set_lost(device, "Failed to read the TIMESTAMP "
4524                                                "register: %m");
4525          }
4526          uint64_t device_period = DIV_ROUND_UP(1000000000, timestamp_frequency);
4527          max_clock_period = MAX2(max_clock_period, device_period);
4528          break;
4529       case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
4530          pTimestamps[d] = anv_clock_gettime(CLOCK_MONOTONIC);
4531          max_clock_period = MAX2(max_clock_period, 1);
4532          break;
4533 
4534 #ifdef CLOCK_MONOTONIC_RAW
4535       case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
4536          pTimestamps[d] = begin;
4537          break;
4538 #endif
4539       default:
4540          pTimestamps[d] = 0;
4541          break;
4542       }
4543    }
4544 
4545 #ifdef CLOCK_MONOTONIC_RAW
4546    end = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
4547 #else
4548    end = anv_clock_gettime(CLOCK_MONOTONIC);
4549 #endif
4550 
4551     /*
4552      * The maximum deviation is the sum of the interval over which we
4553      * perform the sampling and the maximum period of any sampled
4554      * clock. That's because the maximum skew between any two sampled
4555      * clock edges is when the sampled clock with the largest period is
4556      * sampled at the end of that period but right at the beginning of the
4557      * sampling interval and some other clock is sampled right at the
4558      * begining of its sampling period and right at the end of the
4559      * sampling interval. Let's assume the GPU has the longest clock
4560      * period and that the application is sampling GPU and monotonic:
4561      *
4562      *                               s                 e
4563      *			 w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
4564      *	Raw              -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
4565      *
4566      *                               g
4567      *		  0         1         2         3
4568      *	GPU       -----_____-----_____-----_____-----_____
4569      *
4570      *                                                m
4571      *					    x y z 0 1 2 3 4 5 6 7 8 9 a b c
4572      *	Monotonic                           -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
4573      *
4574      *	Interval                     <----------------->
4575      *	Deviation           <-------------------------->
4576      *
4577      *		s  = read(raw)       2
4578      *		g  = read(GPU)       1
4579      *		m  = read(monotonic) 2
4580      *		e  = read(raw)       b
4581      *
4582      * We round the sample interval up by one tick to cover sampling error
4583      * in the interval clock
4584      */
4585 
4586    uint64_t sample_interval = end - begin + 1;
4587 
4588    *pMaxDeviation = sample_interval + max_clock_period;
4589 
4590    return VK_SUCCESS;
4591 }
4592 
4593 /* vk_icd.h does not declare this function, so we declare it here to
4594  * suppress Wmissing-prototypes.
4595  */
4596 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
4597 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
4598 
4599 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t * pSupportedVersion)4600 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
4601 {
4602    /* For the full details on loader interface versioning, see
4603     * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
4604     * What follows is a condensed summary, to help you navigate the large and
4605     * confusing official doc.
4606     *
4607     *   - Loader interface v0 is incompatible with later versions. We don't
4608     *     support it.
4609     *
4610     *   - In loader interface v1:
4611     *       - The first ICD entrypoint called by the loader is
4612     *         vk_icdGetInstanceProcAddr(). The ICD must statically expose this
4613     *         entrypoint.
4614     *       - The ICD must statically expose no other Vulkan symbol unless it is
4615     *         linked with -Bsymbolic.
4616     *       - Each dispatchable Vulkan handle created by the ICD must be
4617     *         a pointer to a struct whose first member is VK_LOADER_DATA. The
4618     *         ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
4619     *       - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
4620     *         vkDestroySurfaceKHR(). The ICD must be capable of working with
4621     *         such loader-managed surfaces.
4622     *
4623     *    - Loader interface v2 differs from v1 in:
4624     *       - The first ICD entrypoint called by the loader is
4625     *         vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
4626     *         statically expose this entrypoint.
4627     *
4628     *    - Loader interface v3 differs from v2 in:
4629     *        - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
4630     *          vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
4631     *          because the loader no longer does so.
4632     *
4633     *    - Loader interface v4 differs from v3 in:
4634     *        - The ICD must implement vk_icdGetPhysicalDeviceProcAddr().
4635     */
4636    *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
4637    return VK_SUCCESS;
4638 }
4639 
anv_CreatePrivateDataSlotEXT(VkDevice _device,const VkPrivateDataSlotCreateInfoEXT * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkPrivateDataSlotEXT * pPrivateDataSlot)4640 VkResult anv_CreatePrivateDataSlotEXT(
4641     VkDevice                                    _device,
4642     const VkPrivateDataSlotCreateInfoEXT*       pCreateInfo,
4643     const VkAllocationCallbacks*                pAllocator,
4644     VkPrivateDataSlotEXT*                       pPrivateDataSlot)
4645 {
4646    ANV_FROM_HANDLE(anv_device, device, _device);
4647    return vk_private_data_slot_create(&device->vk, pCreateInfo, pAllocator,
4648                                       pPrivateDataSlot);
4649 }
4650 
anv_DestroyPrivateDataSlotEXT(VkDevice _device,VkPrivateDataSlotEXT privateDataSlot,const VkAllocationCallbacks * pAllocator)4651 void anv_DestroyPrivateDataSlotEXT(
4652     VkDevice                                    _device,
4653     VkPrivateDataSlotEXT                        privateDataSlot,
4654     const VkAllocationCallbacks*                pAllocator)
4655 {
4656    ANV_FROM_HANDLE(anv_device, device, _device);
4657    vk_private_data_slot_destroy(&device->vk, privateDataSlot, pAllocator);
4658 }
4659 
anv_SetPrivateDataEXT(VkDevice _device,VkObjectType objectType,uint64_t objectHandle,VkPrivateDataSlotEXT privateDataSlot,uint64_t data)4660 VkResult anv_SetPrivateDataEXT(
4661     VkDevice                                    _device,
4662     VkObjectType                                objectType,
4663     uint64_t                                    objectHandle,
4664     VkPrivateDataSlotEXT                        privateDataSlot,
4665     uint64_t                                    data)
4666 {
4667    ANV_FROM_HANDLE(anv_device, device, _device);
4668    return vk_object_base_set_private_data(&device->vk,
4669                                           objectType, objectHandle,
4670                                           privateDataSlot, data);
4671 }
4672 
anv_GetPrivateDataEXT(VkDevice _device,VkObjectType objectType,uint64_t objectHandle,VkPrivateDataSlotEXT privateDataSlot,uint64_t * pData)4673 void anv_GetPrivateDataEXT(
4674     VkDevice                                    _device,
4675     VkObjectType                                objectType,
4676     uint64_t                                    objectHandle,
4677     VkPrivateDataSlotEXT                        privateDataSlot,
4678     uint64_t*                                   pData)
4679 {
4680    ANV_FROM_HANDLE(anv_device, device, _device);
4681    vk_object_base_get_private_data(&device->vk,
4682                                    objectType, objectHandle,
4683                                    privateDataSlot, pData);
4684 }
4685