OSDN Git Service

Merge remote-tracking branch 'mesa/18.3' into oreo-x86
[android-x86/external-mesa.git] / src / intel / vulkan / anv_private.h
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 #ifndef ANV_PRIVATE_H
25 #define ANV_PRIVATE_H
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <stdbool.h>
30 #include <pthread.h>
31 #include <assert.h>
32 #include <stdint.h>
33 #include <i915_drm.h>
34
35 #ifdef HAVE_VALGRIND
36 #include <valgrind.h>
37 #include <memcheck.h>
38 #define VG(x) x
39 #ifndef NDEBUG
40 #define __gen_validate_value(x) VALGRIND_CHECK_MEM_IS_DEFINED(&(x), sizeof(x))
41 #endif
42 #else
43 #define VG(x)
44 #endif
45
46 #include "common/gen_clflush.h"
47 #include "common/gen_gem.h"
48 #include "dev/gen_device_info.h"
49 #include "blorp/blorp.h"
50 #include "compiler/brw_compiler.h"
51 #include "util/macros.h"
52 #include "util/hash_table.h"
53 #include "util/list.h"
54 #include "util/set.h"
55 #include "util/u_atomic.h"
56 #include "util/u_vector.h"
57 #include "util/u_math.h"
58 #include "util/vma.h"
59 #include "vk_alloc.h"
60 #include "vk_debug_report.h"
61
62 /* Pre-declarations needed for WSI entrypoints */
63 struct wl_surface;
64 struct wl_display;
65 typedef struct xcb_connection_t xcb_connection_t;
66 typedef uint32_t xcb_visualid_t;
67 typedef uint32_t xcb_window_t;
68
69 struct anv_buffer;
70 struct anv_buffer_view;
71 struct anv_image_view;
72 struct anv_instance;
73
74 struct gen_l3_config;
75
76 #include <vulkan/vulkan.h>
77 #include <vulkan/vulkan_intel.h>
78 #include <vulkan/vk_icd.h>
79 #include <vulkan/vk_android_native_buffer.h>
80
81 #include "anv_entrypoints.h"
82 #include "anv_extensions.h"
83 #include "isl/isl.h"
84
85 #include "common/gen_debug.h"
86 #include "common/intel_log.h"
87 #include "wsi_common.h"
88
89 /* anv Virtual Memory Layout
90  * =========================
91  *
92  * When the anv driver is determining the virtual graphics addresses of memory
93  * objects itself using the softpin mechanism, the following memory ranges
94  * will be used.
95  *
96  * Three special considerations to notice:
97  *
98  * (1) the dynamic state pool is located within the same 4 GiB as the low
99  * heap. This is to work around a VF cache issue described in a comment in
100  * anv_physical_device_init_heaps.
101  *
102  * (2) the binding table pool is located at lower addresses than the surface
103  * state pool, within a 4 GiB range. This allows surface state base addresses
104  * to cover both binding tables (16 bit offsets) and surface states (32 bit
105  * offsets).
106  *
107  * (3) the last 4 GiB of the address space is withheld from the high
108  * heap. Various hardware units will read past the end of an object for
109  * various reasons. This healthy margin prevents reads from wrapping around
110  * 48-bit addresses.
111  */
112 #define LOW_HEAP_MIN_ADDRESS               0x000000001000ULL /* 4 KiB */
113 #define LOW_HEAP_MAX_ADDRESS               0x0000bfffffffULL
114 #define DYNAMIC_STATE_POOL_MIN_ADDRESS     0x0000c0000000ULL /* 3 GiB */
115 #define DYNAMIC_STATE_POOL_MAX_ADDRESS     0x0000ffffffffULL
116 #define BINDING_TABLE_POOL_MIN_ADDRESS     0x000100000000ULL /* 4 GiB */
117 #define BINDING_TABLE_POOL_MAX_ADDRESS     0x00013fffffffULL
118 #define SURFACE_STATE_POOL_MIN_ADDRESS     0x000140000000ULL /* 5 GiB */
119 #define SURFACE_STATE_POOL_MAX_ADDRESS     0x00017fffffffULL
120 #define INSTRUCTION_STATE_POOL_MIN_ADDRESS 0x000180000000ULL /* 6 GiB */
121 #define INSTRUCTION_STATE_POOL_MAX_ADDRESS 0x0001bfffffffULL
122 #define HIGH_HEAP_MIN_ADDRESS              0x0001c0000000ULL /* 7 GiB */
123 #define HIGH_HEAP_MAX_ADDRESS              0xfffeffffffffULL
124
125 #define LOW_HEAP_SIZE               \
126    (LOW_HEAP_MAX_ADDRESS - LOW_HEAP_MIN_ADDRESS + 1)
127 #define HIGH_HEAP_SIZE              \
128    (HIGH_HEAP_MAX_ADDRESS - HIGH_HEAP_MIN_ADDRESS + 1)
129 #define DYNAMIC_STATE_POOL_SIZE     \
130    (DYNAMIC_STATE_POOL_MAX_ADDRESS - DYNAMIC_STATE_POOL_MIN_ADDRESS + 1)
131 #define BINDING_TABLE_POOL_SIZE     \
132    (BINDING_TABLE_POOL_MAX_ADDRESS - BINDING_TABLE_POOL_MIN_ADDRESS + 1)
133 #define SURFACE_STATE_POOL_SIZE     \
134    (SURFACE_STATE_POOL_MAX_ADDRESS - SURFACE_STATE_POOL_MIN_ADDRESS + 1)
135 #define INSTRUCTION_STATE_POOL_SIZE \
136    (INSTRUCTION_STATE_POOL_MAX_ADDRESS - INSTRUCTION_STATE_POOL_MIN_ADDRESS + 1)
137
138 /* Allowing different clear colors requires us to perform a depth resolve at
139  * the end of certain render passes. This is because while slow clears store
140  * the clear color in the HiZ buffer, fast clears (without a resolve) don't.
141  * See the PRMs for examples describing when additional resolves would be
142  * necessary. To enable fast clears without requiring extra resolves, we set
143  * the clear value to a globally-defined one. We could allow different values
144  * if the user doesn't expect coherent data during or after a render passes
145  * (VK_ATTACHMENT_STORE_OP_DONT_CARE), but such users (aside from the CTS)
146  * don't seem to exist yet. In almost all Vulkan applications tested thus far,
147  * 1.0f seems to be the only value used. The only application that doesn't set
148  * this value does so through the usage of an seemingly uninitialized clear
149  * value.
150  */
151 #define ANV_HZ_FC_VAL 1.0f
152
153 #define MAX_VBS         28
154 #define MAX_SETS         8
155 #define MAX_RTS          8
156 #define MAX_VIEWPORTS   16
157 #define MAX_SCISSORS    16
158 #define MAX_PUSH_CONSTANTS_SIZE 128
159 #define MAX_DYNAMIC_BUFFERS 16
160 #define MAX_IMAGES 64
161 #define MAX_GEN8_IMAGES 8
162 #define MAX_PUSH_DESCRIPTORS 32 /* Minimum requirement */
163
164 /* The kernel relocation API has a limitation of a 32-bit delta value
165  * applied to the address before it is written which, in spite of it being
166  * unsigned, is treated as signed .  Because of the way that this maps to
167  * the Vulkan API, we cannot handle an offset into a buffer that does not
168  * fit into a signed 32 bits.  The only mechanism we have for dealing with
169  * this at the moment is to limit all VkDeviceMemory objects to a maximum
170  * of 2GB each.  The Vulkan spec allows us to do this:
171  *
172  *    "Some platforms may have a limit on the maximum size of a single
173  *    allocation. For example, certain systems may fail to create
174  *    allocations with a size greater than or equal to 4GB. Such a limit is
175  *    implementation-dependent, and if such a failure occurs then the error
176  *    VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
177  *
178  * We don't use vk_error here because it's not an error so much as an
179  * indication to the application that the allocation is too large.
180  */
181 #define MAX_MEMORY_ALLOCATION_SIZE (1ull << 31)
182
183 #define ANV_SVGS_VB_INDEX    MAX_VBS
184 #define ANV_DRAWID_VB_INDEX (MAX_VBS + 1)
185
186 #define anv_printflike(a, b) __attribute__((__format__(__printf__, a, b)))
187
188 static inline uint32_t
189 align_down_npot_u32(uint32_t v, uint32_t a)
190 {
191    return v - (v % a);
192 }
193
194 static inline uint32_t
195 align_u32(uint32_t v, uint32_t a)
196 {
197    assert(a != 0 && a == (a & -a));
198    return (v + a - 1) & ~(a - 1);
199 }
200
201 static inline uint64_t
202 align_u64(uint64_t v, uint64_t a)
203 {
204    assert(a != 0 && a == (a & -a));
205    return (v + a - 1) & ~(a - 1);
206 }
207
208 static inline int32_t
209 align_i32(int32_t v, int32_t a)
210 {
211    assert(a != 0 && a == (a & -a));
212    return (v + a - 1) & ~(a - 1);
213 }
214
215 /** Alignment must be a power of 2. */
216 static inline bool
217 anv_is_aligned(uintmax_t n, uintmax_t a)
218 {
219    assert(a == (a & -a));
220    return (n & (a - 1)) == 0;
221 }
222
223 static inline uint32_t
224 anv_minify(uint32_t n, uint32_t levels)
225 {
226    if (unlikely(n == 0))
227       return 0;
228    else
229       return MAX2(n >> levels, 1);
230 }
231
232 static inline float
233 anv_clamp_f(float f, float min, float max)
234 {
235    assert(min < max);
236
237    if (f > max)
238       return max;
239    else if (f < min)
240       return min;
241    else
242       return f;
243 }
244
245 static inline bool
246 anv_clear_mask(uint32_t *inout_mask, uint32_t clear_mask)
247 {
248    if (*inout_mask & clear_mask) {
249       *inout_mask &= ~clear_mask;
250       return true;
251    } else {
252       return false;
253    }
254 }
255
256 static inline union isl_color_value
257 vk_to_isl_color(VkClearColorValue color)
258 {
259    return (union isl_color_value) {
260       .u32 = {
261          color.uint32[0],
262          color.uint32[1],
263          color.uint32[2],
264          color.uint32[3],
265       },
266    };
267 }
268
269 #define for_each_bit(b, dword)                          \
270    for (uint32_t __dword = (dword);                     \
271         (b) = __builtin_ffs(__dword) - 1, __dword;      \
272         __dword &= ~(1 << (b)))
273
274 #define typed_memcpy(dest, src, count) ({ \
275    STATIC_ASSERT(sizeof(*src) == sizeof(*dest)); \
276    memcpy((dest), (src), (count) * sizeof(*(src))); \
277 })
278
279 /* Mapping from anv object to VkDebugReportObjectTypeEXT. New types need
280  * to be added here in order to utilize mapping in debug/error/perf macros.
281  */
282 #define REPORT_OBJECT_TYPE(o)                                                      \
283    __builtin_choose_expr (                                                         \
284    __builtin_types_compatible_p (__typeof (o), struct anv_instance*),              \
285    VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT,                                       \
286    __builtin_choose_expr (                                                         \
287    __builtin_types_compatible_p (__typeof (o), struct anv_physical_device*),       \
288    VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT,                                \
289    __builtin_choose_expr (                                                         \
290    __builtin_types_compatible_p (__typeof (o), struct anv_device*),                \
291    VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,                                         \
292    __builtin_choose_expr (                                                         \
293    __builtin_types_compatible_p (__typeof (o), const struct anv_device*),          \
294    VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,                                         \
295    __builtin_choose_expr (                                                         \
296    __builtin_types_compatible_p (__typeof (o), struct anv_queue*),                 \
297    VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT,                                          \
298    __builtin_choose_expr (                                                         \
299    __builtin_types_compatible_p (__typeof (o), struct anv_semaphore*),             \
300    VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT,                                      \
301    __builtin_choose_expr (                                                         \
302    __builtin_types_compatible_p (__typeof (o), struct anv_cmd_buffer*),            \
303    VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT,                                 \
304    __builtin_choose_expr (                                                         \
305    __builtin_types_compatible_p (__typeof (o), struct anv_fence*),                 \
306    VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT,                                          \
307    __builtin_choose_expr (                                                         \
308    __builtin_types_compatible_p (__typeof (o), struct anv_device_memory*),         \
309    VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT,                                  \
310    __builtin_choose_expr (                                                         \
311    __builtin_types_compatible_p (__typeof (o), struct anv_buffer*),                \
312    VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT,                                         \
313    __builtin_choose_expr (                                                         \
314    __builtin_types_compatible_p (__typeof (o), struct anv_image*),                 \
315    VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,                                          \
316    __builtin_choose_expr (                                                         \
317    __builtin_types_compatible_p (__typeof (o), const struct anv_image*),           \
318    VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT,                                          \
319    __builtin_choose_expr (                                                         \
320    __builtin_types_compatible_p (__typeof (o), struct anv_event*),                 \
321    VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT,                                          \
322    __builtin_choose_expr (                                                         \
323    __builtin_types_compatible_p (__typeof (o), struct anv_query_pool*),            \
324    VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT,                                     \
325    __builtin_choose_expr (                                                         \
326    __builtin_types_compatible_p (__typeof (o), struct anv_buffer_view*),           \
327    VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT,                                    \
328    __builtin_choose_expr (                                                         \
329    __builtin_types_compatible_p (__typeof (o), struct anv_image_view*),            \
330    VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT,                                     \
331    __builtin_choose_expr (                                                         \
332    __builtin_types_compatible_p (__typeof (o), struct anv_shader_module*),         \
333    VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,                                  \
334    __builtin_choose_expr (                                                         \
335    __builtin_types_compatible_p (__typeof (o), struct anv_pipeline_cache*),        \
336    VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT,                                 \
337    __builtin_choose_expr (                                                         \
338    __builtin_types_compatible_p (__typeof (o), struct anv_pipeline_layout*),       \
339    VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT,                                \
340    __builtin_choose_expr (                                                         \
341    __builtin_types_compatible_p (__typeof (o), struct anv_render_pass*),           \
342    VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT,                                    \
343    __builtin_choose_expr (                                                         \
344    __builtin_types_compatible_p (__typeof (o), struct anv_pipeline*),              \
345    VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,                                       \
346    __builtin_choose_expr (                                                         \
347    __builtin_types_compatible_p (__typeof (o), struct anv_descriptor_set_layout*), \
348    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT,                          \
349    __builtin_choose_expr (                                                         \
350    __builtin_types_compatible_p (__typeof (o), struct anv_sampler*),               \
351    VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT,                                        \
352    __builtin_choose_expr (                                                         \
353    __builtin_types_compatible_p (__typeof (o), struct anv_descriptor_pool*),       \
354    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,                                \
355    __builtin_choose_expr (                                                         \
356    __builtin_types_compatible_p (__typeof (o), struct anv_descriptor_set*),        \
357    VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,                                 \
358    __builtin_choose_expr (                                                         \
359    __builtin_types_compatible_p (__typeof (o), struct anv_framebuffer*),           \
360    VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT,                                    \
361    __builtin_choose_expr (                                                         \
362    __builtin_types_compatible_p (__typeof (o), struct anv_cmd_pool*),              \
363    VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT,                                   \
364    __builtin_choose_expr (                                                         \
365    __builtin_types_compatible_p (__typeof (o), struct anv_surface*),               \
366    VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT,                                    \
367    __builtin_choose_expr (                                                         \
368    __builtin_types_compatible_p (__typeof (o), struct wsi_swapchain*),             \
369    VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT,                                  \
370    __builtin_choose_expr (                                                         \
371    __builtin_types_compatible_p (__typeof (o), struct vk_debug_callback*),         \
372    VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT_EXT,                      \
373    __builtin_choose_expr (                                                         \
374    __builtin_types_compatible_p (__typeof (o), void*),                             \
375    VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,                                        \
376    /* The void expression results in a compile-time error                          \
377       when assigning the result to something.  */                                  \
378    (void)0)))))))))))))))))))))))))))))))
379
380 /* Whenever we generate an error, pass it through this function. Useful for
381  * debugging, where we can break on it. Only call at error site, not when
382  * propagating errors. Might be useful to plug in a stack trace here.
383  */
384
385 VkResult __vk_errorv(struct anv_instance *instance, const void *object,
386                      VkDebugReportObjectTypeEXT type, VkResult error,
387                      const char *file, int line, const char *format,
388                      va_list args);
389
390 VkResult __vk_errorf(struct anv_instance *instance, const void *object,
391                      VkDebugReportObjectTypeEXT type, VkResult error,
392                      const char *file, int line, const char *format, ...);
393
394 #ifdef DEBUG
395 #define vk_error(error) __vk_errorf(NULL, NULL,\
396                                     VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,\
397                                     error, __FILE__, __LINE__, NULL)
398 #define vk_errorv(instance, obj, error, format, args)\
399     __vk_errorv(instance, obj, REPORT_OBJECT_TYPE(obj), error,\
400                 __FILE__, __LINE__, format, args)
401 #define vk_errorf(instance, obj, error, format, ...)\
402     __vk_errorf(instance, obj, REPORT_OBJECT_TYPE(obj), error,\
403                 __FILE__, __LINE__, format, ## __VA_ARGS__)
404 #else
405 #define vk_error(error) error
406 #define vk_errorf(instance, obj, error, format, ...) error
407 #endif
408
409 /**
410  * Warn on ignored extension structs.
411  *
412  * The Vulkan spec requires us to ignore unsupported or unknown structs in
413  * a pNext chain.  In debug mode, emitting warnings for ignored structs may
414  * help us discover structs that we should not have ignored.
415  *
416  *
417  * From the Vulkan 1.0.38 spec:
418  *
419  *    Any component of the implementation (the loader, any enabled layers,
420  *    and drivers) must skip over, without processing (other than reading the
421  *    sType and pNext members) any chained structures with sType values not
422  *    defined by extensions supported by that component.
423  */
424 #define anv_debug_ignored_stype(sType) \
425    intel_logd("%s: ignored VkStructureType %u\n", __func__, (sType))
426
427 void __anv_perf_warn(struct anv_instance *instance, const void *object,
428                      VkDebugReportObjectTypeEXT type, const char *file,
429                      int line, const char *format, ...)
430    anv_printflike(6, 7);
431 void anv_loge(const char *format, ...) anv_printflike(1, 2);
432 void anv_loge_v(const char *format, va_list va);
433
434 /**
435  * Print a FINISHME message, including its source location.
436  */
437 #define anv_finishme(format, ...) \
438    do { \
439       static bool reported = false; \
440       if (!reported) { \
441          intel_logw("%s:%d: FINISHME: " format, __FILE__, __LINE__, \
442                     ##__VA_ARGS__); \
443          reported = true; \
444       } \
445    } while (0)
446
447 /**
448  * Print a perf warning message.  Set INTEL_DEBUG=perf to see these.
449  */
450 #define anv_perf_warn(instance, obj, format, ...) \
451    do { \
452       static bool reported = false; \
453       if (!reported && unlikely(INTEL_DEBUG & DEBUG_PERF)) { \
454          __anv_perf_warn(instance, obj, REPORT_OBJECT_TYPE(obj), __FILE__, __LINE__,\
455                          format, ##__VA_ARGS__); \
456          reported = true; \
457       } \
458    } while (0)
459
460 /* A non-fatal assert.  Useful for debugging. */
461 #ifdef DEBUG
462 #define anv_assert(x) ({ \
463    if (unlikely(!(x))) \
464       intel_loge("%s:%d ASSERT: %s", __FILE__, __LINE__, #x); \
465 })
466 #else
467 #define anv_assert(x)
468 #endif
469
470 /* A multi-pointer allocator
471  *
472  * When copying data structures from the user (such as a render pass), it's
473  * common to need to allocate data for a bunch of different things.  Instead
474  * of doing several allocations and having to handle all of the error checking
475  * that entails, it can be easier to do a single allocation.  This struct
476  * helps facilitate that.  The intended usage looks like this:
477  *
478  *    ANV_MULTIALLOC(ma)
479  *    anv_multialloc_add(&ma, &main_ptr, 1);
480  *    anv_multialloc_add(&ma, &substruct1, substruct1Count);
481  *    anv_multialloc_add(&ma, &substruct2, substruct2Count);
482  *
483  *    if (!anv_multialloc_alloc(&ma, pAllocator, VK_ALLOCATION_SCOPE_FOO))
484  *       return vk_error(VK_ERROR_OUT_OF_HOST_MEORY);
485  */
486 struct anv_multialloc {
487     size_t size;
488     size_t align;
489
490     uint32_t ptr_count;
491     void **ptrs[8];
492 };
493
494 #define ANV_MULTIALLOC_INIT \
495    ((struct anv_multialloc) { 0, })
496
497 #define ANV_MULTIALLOC(_name) \
498    struct anv_multialloc _name = ANV_MULTIALLOC_INIT
499
500 __attribute__((always_inline))
501 static inline void
502 _anv_multialloc_add(struct anv_multialloc *ma,
503                     void **ptr, size_t size, size_t align)
504 {
505    size_t offset = align_u64(ma->size, align);
506    ma->size = offset + size;
507    ma->align = MAX2(ma->align, align);
508
509    /* Store the offset in the pointer. */
510    *ptr = (void *)(uintptr_t)offset;
511
512    assert(ma->ptr_count < ARRAY_SIZE(ma->ptrs));
513    ma->ptrs[ma->ptr_count++] = ptr;
514 }
515
516 #define anv_multialloc_add_size(_ma, _ptr, _size) \
517    _anv_multialloc_add((_ma), (void **)(_ptr), (_size), __alignof__(**(_ptr)))
518
519 #define anv_multialloc_add(_ma, _ptr, _count) \
520    anv_multialloc_add_size(_ma, _ptr, (_count) * sizeof(**(_ptr)));
521
522 __attribute__((always_inline))
523 static inline void *
524 anv_multialloc_alloc(struct anv_multialloc *ma,
525                      const VkAllocationCallbacks *alloc,
526                      VkSystemAllocationScope scope)
527 {
528    void *ptr = vk_alloc(alloc, ma->size, ma->align, scope);
529    if (!ptr)
530       return NULL;
531
532    /* Fill out each of the pointers with their final value.
533     *
534     *   for (uint32_t i = 0; i < ma->ptr_count; i++)
535     *      *ma->ptrs[i] = ptr + (uintptr_t)*ma->ptrs[i];
536     *
537     * Unfortunately, even though ma->ptr_count is basically guaranteed to be a
538     * constant, GCC is incapable of figuring this out and unrolling the loop
539     * so we have to give it a little help.
540     */
541    STATIC_ASSERT(ARRAY_SIZE(ma->ptrs) == 8);
542 #define _ANV_MULTIALLOC_UPDATE_POINTER(_i) \
543    if ((_i) < ma->ptr_count) \
544       *ma->ptrs[_i] = ptr + (uintptr_t)*ma->ptrs[_i]
545    _ANV_MULTIALLOC_UPDATE_POINTER(0);
546    _ANV_MULTIALLOC_UPDATE_POINTER(1);
547    _ANV_MULTIALLOC_UPDATE_POINTER(2);
548    _ANV_MULTIALLOC_UPDATE_POINTER(3);
549    _ANV_MULTIALLOC_UPDATE_POINTER(4);
550    _ANV_MULTIALLOC_UPDATE_POINTER(5);
551    _ANV_MULTIALLOC_UPDATE_POINTER(6);
552    _ANV_MULTIALLOC_UPDATE_POINTER(7);
553 #undef _ANV_MULTIALLOC_UPDATE_POINTER
554
555    return ptr;
556 }
557
558 __attribute__((always_inline))
559 static inline void *
560 anv_multialloc_alloc2(struct anv_multialloc *ma,
561                       const VkAllocationCallbacks *parent_alloc,
562                       const VkAllocationCallbacks *alloc,
563                       VkSystemAllocationScope scope)
564 {
565    return anv_multialloc_alloc(ma, alloc ? alloc : parent_alloc, scope);
566 }
567
568 /* Extra ANV-defined BO flags which won't be passed to the kernel */
569 #define ANV_BO_EXTERNAL    (1ull << 31)
570 #define ANV_BO_FLAG_MASK   (1ull << 31)
571
572 struct anv_bo {
573    uint32_t gem_handle;
574
575    /* Index into the current validation list.  This is used by the
576     * validation list building alrogithm to track which buffers are already
577     * in the validation list so that we can ensure uniqueness.
578     */
579    uint32_t index;
580
581    /* Last known offset.  This value is provided by the kernel when we
582     * execbuf and is used as the presumed offset for the next bunch of
583     * relocations.
584     */
585    uint64_t offset;
586
587    uint64_t size;
588    void *map;
589
590    /** Flags to pass to the kernel through drm_i915_exec_object2::flags */
591    uint32_t flags;
592 };
593
594 static inline void
595 anv_bo_init(struct anv_bo *bo, uint32_t gem_handle, uint64_t size)
596 {
597    bo->gem_handle = gem_handle;
598    bo->index = 0;
599    bo->offset = -1;
600    bo->size = size;
601    bo->map = NULL;
602    bo->flags = 0;
603 }
604
605 /* Represents a lock-free linked list of "free" things.  This is used by
606  * both the block pool and the state pools.  Unfortunately, in order to
607  * solve the ABA problem, we can't use a single uint32_t head.
608  */
609 union anv_free_list {
610    struct {
611       int32_t offset;
612
613       /* A simple count that is incremented every time the head changes. */
614       uint32_t count;
615    };
616    uint64_t u64;
617 };
618
619 #define ANV_FREE_LIST_EMPTY ((union anv_free_list) { { 1, 0 } })
620
621 struct anv_block_state {
622    union {
623       struct {
624          uint32_t next;
625          uint32_t end;
626       };
627       uint64_t u64;
628    };
629 };
630
631 struct anv_block_pool {
632    struct anv_device *device;
633
634    uint64_t bo_flags;
635
636    struct anv_bo bo;
637
638    /* The address where the start of the pool is pinned. The various bos that
639     * are created as the pool grows will have addresses in the range
640     * [start_address, start_address + BLOCK_POOL_MEMFD_SIZE).
641     */
642    uint64_t start_address;
643
644    /* The offset from the start of the bo to the "center" of the block
645     * pool.  Pointers to allocated blocks are given by
646     * bo.map + center_bo_offset + offsets.
647     */
648    uint32_t center_bo_offset;
649
650    /* Current memory map of the block pool.  This pointer may or may not
651     * point to the actual beginning of the block pool memory.  If
652     * anv_block_pool_alloc_back has ever been called, then this pointer
653     * will point to the "center" position of the buffer and all offsets
654     * (negative or positive) given out by the block pool alloc functions
655     * will be valid relative to this pointer.
656     *
657     * In particular, map == bo.map + center_offset
658     */
659    void *map;
660    int fd;
661
662    /**
663     * Array of mmaps and gem handles owned by the block pool, reclaimed when
664     * the block pool is destroyed.
665     */
666    struct u_vector mmap_cleanups;
667
668    struct anv_block_state state;
669
670    struct anv_block_state back_state;
671 };
672
673 /* Block pools are backed by a fixed-size 1GB memfd */
674 #define BLOCK_POOL_MEMFD_SIZE (1ul << 30)
675
676 /* The center of the block pool is also the middle of the memfd.  This may
677  * change in the future if we decide differently for some reason.
678  */
679 #define BLOCK_POOL_MEMFD_CENTER (BLOCK_POOL_MEMFD_SIZE / 2)
680
681 static inline uint32_t
682 anv_block_pool_size(struct anv_block_pool *pool)
683 {
684    return pool->state.end + pool->back_state.end;
685 }
686
687 struct anv_state {
688    int32_t offset;
689    uint32_t alloc_size;
690    void *map;
691 };
692
693 #define ANV_STATE_NULL ((struct anv_state) { .alloc_size = 0 })
694
695 struct anv_fixed_size_state_pool {
696    union anv_free_list free_list;
697    struct anv_block_state block;
698 };
699
700 #define ANV_MIN_STATE_SIZE_LOG2 6
701 #define ANV_MAX_STATE_SIZE_LOG2 20
702
703 #define ANV_STATE_BUCKETS (ANV_MAX_STATE_SIZE_LOG2 - ANV_MIN_STATE_SIZE_LOG2 + 1)
704
705 struct anv_state_pool {
706    struct anv_block_pool block_pool;
707
708    /* The size of blocks which will be allocated from the block pool */
709    uint32_t block_size;
710
711    /** Free list for "back" allocations */
712    union anv_free_list back_alloc_free_list;
713
714    struct anv_fixed_size_state_pool buckets[ANV_STATE_BUCKETS];
715 };
716
717 struct anv_state_stream_block;
718
719 struct anv_state_stream {
720    struct anv_state_pool *state_pool;
721
722    /* The size of blocks to allocate from the state pool */
723    uint32_t block_size;
724
725    /* Current block we're allocating from */
726    struct anv_state block;
727
728    /* Offset into the current block at which to allocate the next state */
729    uint32_t next;
730
731    /* List of all blocks allocated from this pool */
732    struct anv_state_stream_block *block_list;
733 };
734
735 /* The block_pool functions exported for testing only.  The block pool should
736  * only be used via a state pool (see below).
737  */
738 VkResult anv_block_pool_init(struct anv_block_pool *pool,
739                              struct anv_device *device,
740                              uint64_t start_address,
741                              uint32_t initial_size,
742                              uint64_t bo_flags);
743 void anv_block_pool_finish(struct anv_block_pool *pool);
744 int32_t anv_block_pool_alloc(struct anv_block_pool *pool,
745                              uint32_t block_size);
746 int32_t anv_block_pool_alloc_back(struct anv_block_pool *pool,
747                                   uint32_t block_size);
748
749 VkResult anv_state_pool_init(struct anv_state_pool *pool,
750                              struct anv_device *device,
751                              uint64_t start_address,
752                              uint32_t block_size,
753                              uint64_t bo_flags);
754 void anv_state_pool_finish(struct anv_state_pool *pool);
755 struct anv_state anv_state_pool_alloc(struct anv_state_pool *pool,
756                                       uint32_t state_size, uint32_t alignment);
757 struct anv_state anv_state_pool_alloc_back(struct anv_state_pool *pool);
758 void anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state);
759 void anv_state_stream_init(struct anv_state_stream *stream,
760                            struct anv_state_pool *state_pool,
761                            uint32_t block_size);
762 void anv_state_stream_finish(struct anv_state_stream *stream);
763 struct anv_state anv_state_stream_alloc(struct anv_state_stream *stream,
764                                         uint32_t size, uint32_t alignment);
765
766 /**
767  * Implements a pool of re-usable BOs.  The interface is identical to that
768  * of block_pool except that each block is its own BO.
769  */
770 struct anv_bo_pool {
771    struct anv_device *device;
772
773    uint64_t bo_flags;
774
775    void *free_list[16];
776 };
777
778 void anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
779                       uint64_t bo_flags);
780 void anv_bo_pool_finish(struct anv_bo_pool *pool);
781 VkResult anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo,
782                            uint32_t size);
783 void anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo);
784
785 struct anv_scratch_bo {
786    bool exists;
787    struct anv_bo bo;
788 };
789
790 struct anv_scratch_pool {
791    /* Indexed by Per-Thread Scratch Space number (the hardware value) and stage */
792    struct anv_scratch_bo bos[16][MESA_SHADER_STAGES];
793 };
794
795 void anv_scratch_pool_init(struct anv_device *device,
796                            struct anv_scratch_pool *pool);
797 void anv_scratch_pool_finish(struct anv_device *device,
798                              struct anv_scratch_pool *pool);
799 struct anv_bo *anv_scratch_pool_alloc(struct anv_device *device,
800                                       struct anv_scratch_pool *pool,
801                                       gl_shader_stage stage,
802                                       unsigned per_thread_scratch);
803
804 /** Implements a BO cache that ensures a 1-1 mapping of GEM BOs to anv_bos */
805 struct anv_bo_cache {
806    struct hash_table *bo_map;
807    pthread_mutex_t mutex;
808 };
809
810 VkResult anv_bo_cache_init(struct anv_bo_cache *cache);
811 void anv_bo_cache_finish(struct anv_bo_cache *cache);
812 VkResult anv_bo_cache_alloc(struct anv_device *device,
813                             struct anv_bo_cache *cache,
814                             uint64_t size, uint64_t bo_flags,
815                             struct anv_bo **bo);
816 VkResult anv_bo_cache_import(struct anv_device *device,
817                              struct anv_bo_cache *cache,
818                              int fd, uint64_t bo_flags,
819                              struct anv_bo **bo);
820 VkResult anv_bo_cache_export(struct anv_device *device,
821                              struct anv_bo_cache *cache,
822                              struct anv_bo *bo_in, int *fd_out);
823 void anv_bo_cache_release(struct anv_device *device,
824                           struct anv_bo_cache *cache,
825                           struct anv_bo *bo);
826
827 struct anv_memory_type {
828    /* Standard bits passed on to the client */
829    VkMemoryPropertyFlags   propertyFlags;
830    uint32_t                heapIndex;
831
832    /* Driver-internal book-keeping */
833    VkBufferUsageFlags      valid_buffer_usage;
834 };
835
836 struct anv_memory_heap {
837    /* Standard bits passed on to the client */
838    VkDeviceSize      size;
839    VkMemoryHeapFlags flags;
840
841    /* Driver-internal book-keeping */
842    bool              supports_48bit_addresses;
843 };
844
845 struct anv_physical_device {
846     VK_LOADER_DATA                              _loader_data;
847
848     struct anv_instance *                       instance;
849     uint32_t                                    chipset_id;
850     bool                                        no_hw;
851     char                                        path[20];
852     const char *                                name;
853     struct {
854        uint16_t                                 domain;
855        uint8_t                                  bus;
856        uint8_t                                  device;
857        uint8_t                                  function;
858     }                                           pci_info;
859     struct gen_device_info                      info;
860     /** Amount of "GPU memory" we want to advertise
861      *
862      * Clearly, this value is bogus since Intel is a UMA architecture.  On
863      * gen7 platforms, we are limited by GTT size unless we want to implement
864      * fine-grained tracking and GTT splitting.  On Broadwell and above we are
865      * practically unlimited.  However, we will never report more than 3/4 of
866      * the total system ram to try and avoid running out of RAM.
867      */
868     bool                                        supports_48bit_addresses;
869     struct brw_compiler *                       compiler;
870     struct isl_device                           isl_dev;
871     int                                         cmd_parser_version;
872     bool                                        has_exec_async;
873     bool                                        has_exec_capture;
874     bool                                        has_exec_fence;
875     bool                                        has_syncobj;
876     bool                                        has_syncobj_wait;
877     bool                                        has_context_priority;
878     bool                                        use_softpin;
879     bool                                        has_context_isolation;
880
881     struct anv_device_extension_table           supported_extensions;
882
883     uint32_t                                    eu_total;
884     uint32_t                                    subslice_total;
885
886     struct {
887       uint32_t                                  type_count;
888       struct anv_memory_type                    types[VK_MAX_MEMORY_TYPES];
889       uint32_t                                  heap_count;
890       struct anv_memory_heap                    heaps[VK_MAX_MEMORY_HEAPS];
891     } memory;
892
893     uint8_t                                     driver_build_sha1[20];
894     uint8_t                                     pipeline_cache_uuid[VK_UUID_SIZE];
895     uint8_t                                     driver_uuid[VK_UUID_SIZE];
896     uint8_t                                     device_uuid[VK_UUID_SIZE];
897
898     struct disk_cache *                         disk_cache;
899
900     struct wsi_device                       wsi_device;
901     int                                         local_fd;
902     int                                         master_fd;
903 };
904
905 struct anv_app_info {
906    const char*        app_name;
907    uint32_t           app_version;
908    const char*        engine_name;
909    uint32_t           engine_version;
910    uint32_t           api_version;
911 };
912
913 struct anv_instance {
914     VK_LOADER_DATA                              _loader_data;
915
916     VkAllocationCallbacks                       alloc;
917
918     struct anv_app_info                         app_info;
919
920     struct anv_instance_extension_table         enabled_extensions;
921     struct anv_instance_dispatch_table          dispatch;
922     struct anv_device_dispatch_table            device_dispatch;
923
924     int                                         physicalDeviceCount;
925     struct anv_physical_device                  physicalDevice;
926
927     bool                                        pipeline_cache_enabled;
928
929     struct vk_debug_report_instance             debug_report_callbacks;
930 };
931
932 VkResult anv_init_wsi(struct anv_physical_device *physical_device);
933 void anv_finish_wsi(struct anv_physical_device *physical_device);
934
935 uint32_t anv_physical_device_api_version(struct anv_physical_device *dev);
936 bool anv_physical_device_extension_supported(struct anv_physical_device *dev,
937                                              const char *name);
938
939 struct anv_queue {
940     VK_LOADER_DATA                              _loader_data;
941
942     struct anv_device *                         device;
943
944     VkDeviceQueueCreateFlags                    flags;
945 };
946
947 struct anv_pipeline_cache {
948    struct anv_device *                          device;
949    pthread_mutex_t                              mutex;
950
951    struct hash_table *                          cache;
952 };
953
954 struct anv_pipeline_bind_map;
955
956 void anv_pipeline_cache_init(struct anv_pipeline_cache *cache,
957                              struct anv_device *device,
958                              bool cache_enabled);
959 void anv_pipeline_cache_finish(struct anv_pipeline_cache *cache);
960
961 struct anv_shader_bin *
962 anv_pipeline_cache_search(struct anv_pipeline_cache *cache,
963                           const void *key, uint32_t key_size);
964 struct anv_shader_bin *
965 anv_pipeline_cache_upload_kernel(struct anv_pipeline_cache *cache,
966                                  const void *key_data, uint32_t key_size,
967                                  const void *kernel_data, uint32_t kernel_size,
968                                  const void *constant_data,
969                                  uint32_t constant_data_size,
970                                  const struct brw_stage_prog_data *prog_data,
971                                  uint32_t prog_data_size,
972                                  const struct anv_pipeline_bind_map *bind_map);
973
974 struct anv_shader_bin *
975 anv_device_search_for_kernel(struct anv_device *device,
976                              struct anv_pipeline_cache *cache,
977                              const void *key_data, uint32_t key_size);
978
979 struct anv_shader_bin *
980 anv_device_upload_kernel(struct anv_device *device,
981                          struct anv_pipeline_cache *cache,
982                          const void *key_data, uint32_t key_size,
983                          const void *kernel_data, uint32_t kernel_size,
984                          const void *constant_data,
985                          uint32_t constant_data_size,
986                          const struct brw_stage_prog_data *prog_data,
987                          uint32_t prog_data_size,
988                          const struct anv_pipeline_bind_map *bind_map);
989
990 struct anv_device {
991     VK_LOADER_DATA                              _loader_data;
992
993     VkAllocationCallbacks                       alloc;
994
995     struct anv_instance *                       instance;
996     uint32_t                                    chipset_id;
997     bool                                        no_hw;
998     struct gen_device_info                      info;
999     struct isl_device                           isl_dev;
1000     int                                         context_id;
1001     int                                         fd;
1002     bool                                        can_chain_batches;
1003     bool                                        robust_buffer_access;
1004     struct anv_device_extension_table           enabled_extensions;
1005     struct anv_device_dispatch_table            dispatch;
1006
1007     pthread_mutex_t                             vma_mutex;
1008     struct util_vma_heap                        vma_lo;
1009     struct util_vma_heap                        vma_hi;
1010     uint64_t                                    vma_lo_available;
1011     uint64_t                                    vma_hi_available;
1012
1013     struct anv_bo_pool                          batch_bo_pool;
1014
1015     struct anv_bo_cache                         bo_cache;
1016
1017     struct anv_state_pool                       dynamic_state_pool;
1018     struct anv_state_pool                       instruction_state_pool;
1019     struct anv_state_pool                       binding_table_pool;
1020     struct anv_state_pool                       surface_state_pool;
1021
1022     struct anv_bo                               workaround_bo;
1023     struct anv_bo                               trivial_batch_bo;
1024     struct anv_bo                               hiz_clear_bo;
1025
1026     struct anv_pipeline_cache                   default_pipeline_cache;
1027     struct blorp_context                        blorp;
1028
1029     struct anv_state                            border_colors;
1030
1031     struct anv_queue                            queue;
1032
1033     struct anv_scratch_pool                     scratch_pool;
1034
1035     uint32_t                                    default_mocs;
1036     uint32_t                                    external_mocs;
1037
1038     pthread_mutex_t                             mutex;
1039     pthread_cond_t                              queue_submit;
1040     bool                                        _lost;
1041 };
1042
1043 static inline struct anv_state_pool *
1044 anv_binding_table_pool(struct anv_device *device)
1045 {
1046    if (device->instance->physicalDevice.use_softpin)
1047       return &device->binding_table_pool;
1048    else
1049       return &device->surface_state_pool;
1050 }
1051
1052 static inline struct anv_state
1053 anv_binding_table_pool_alloc(struct anv_device *device) {
1054    if (device->instance->physicalDevice.use_softpin)
1055       return anv_state_pool_alloc(&device->binding_table_pool,
1056                                   device->binding_table_pool.block_size, 0);
1057    else
1058       return anv_state_pool_alloc_back(&device->surface_state_pool);
1059 }
1060
1061 static inline void
1062 anv_binding_table_pool_free(struct anv_device *device, struct anv_state state) {
1063    anv_state_pool_free(anv_binding_table_pool(device), state);
1064 }
1065
1066 static inline uint32_t
1067 anv_mocs_for_bo(const struct anv_device *device, const struct anv_bo *bo)
1068 {
1069    if (bo->flags & ANV_BO_EXTERNAL)
1070       return device->external_mocs;
1071    else
1072       return device->default_mocs;
1073 }
1074
1075 static void inline
1076 anv_state_flush(struct anv_device *device, struct anv_state state)
1077 {
1078    if (device->info.has_llc)
1079       return;
1080
1081    gen_flush_range(state.map, state.alloc_size);
1082 }
1083
1084 void anv_device_init_blorp(struct anv_device *device);
1085 void anv_device_finish_blorp(struct anv_device *device);
1086
1087 VkResult _anv_device_set_lost(struct anv_device *device,
1088                               const char *file, int line,
1089                               const char *msg, ...);
1090 #define anv_device_set_lost(dev, ...) \
1091    _anv_device_set_lost(dev, __FILE__, __LINE__, __VA_ARGS__)
1092
1093 static inline bool
1094 anv_device_is_lost(struct anv_device *device)
1095 {
1096    return unlikely(device->_lost);
1097 }
1098
1099 VkResult anv_device_execbuf(struct anv_device *device,
1100                             struct drm_i915_gem_execbuffer2 *execbuf,
1101                             struct anv_bo **execbuf_bos);
1102 VkResult anv_device_query_status(struct anv_device *device);
1103 VkResult anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo);
1104 VkResult anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1105                          int64_t timeout);
1106
1107 void* anv_gem_mmap(struct anv_device *device,
1108                    uint32_t gem_handle, uint64_t offset, uint64_t size, uint32_t flags);
1109 void anv_gem_munmap(void *p, uint64_t size);
1110 uint32_t anv_gem_create(struct anv_device *device, uint64_t size);
1111 void anv_gem_close(struct anv_device *device, uint32_t gem_handle);
1112 uint32_t anv_gem_userptr(struct anv_device *device, void *mem, size_t size);
1113 int anv_gem_busy(struct anv_device *device, uint32_t gem_handle);
1114 int anv_gem_wait(struct anv_device *device, uint32_t gem_handle, int64_t *timeout_ns);
1115 int anv_gem_execbuffer(struct anv_device *device,
1116                        struct drm_i915_gem_execbuffer2 *execbuf);
1117 int anv_gem_set_tiling(struct anv_device *device, uint32_t gem_handle,
1118                        uint32_t stride, uint32_t tiling);
1119 int anv_gem_create_context(struct anv_device *device);
1120 bool anv_gem_has_context_priority(int fd);
1121 int anv_gem_destroy_context(struct anv_device *device, int context);
1122 int anv_gem_set_context_param(int fd, int context, uint32_t param,
1123                               uint64_t value);
1124 int anv_gem_get_context_param(int fd, int context, uint32_t param,
1125                               uint64_t *value);
1126 int anv_gem_get_param(int fd, uint32_t param);
1127 int anv_gem_get_tiling(struct anv_device *device, uint32_t gem_handle);
1128 bool anv_gem_get_bit6_swizzle(int fd, uint32_t tiling);
1129 int anv_gem_get_aperture(int fd, uint64_t *size);
1130 int anv_gem_gpu_get_reset_stats(struct anv_device *device,
1131                                 uint32_t *active, uint32_t *pending);
1132 int anv_gem_handle_to_fd(struct anv_device *device, uint32_t gem_handle);
1133 int anv_gem_reg_read(struct anv_device *device,
1134                      uint32_t offset, uint64_t *result);
1135 uint32_t anv_gem_fd_to_handle(struct anv_device *device, int fd);
1136 int anv_gem_set_caching(struct anv_device *device, uint32_t gem_handle, uint32_t caching);
1137 int anv_gem_set_domain(struct anv_device *device, uint32_t gem_handle,
1138                        uint32_t read_domains, uint32_t write_domain);
1139 int anv_gem_sync_file_merge(struct anv_device *device, int fd1, int fd2);
1140 uint32_t anv_gem_syncobj_create(struct anv_device *device, uint32_t flags);
1141 void anv_gem_syncobj_destroy(struct anv_device *device, uint32_t handle);
1142 int anv_gem_syncobj_handle_to_fd(struct anv_device *device, uint32_t handle);
1143 uint32_t anv_gem_syncobj_fd_to_handle(struct anv_device *device, int fd);
1144 int anv_gem_syncobj_export_sync_file(struct anv_device *device,
1145                                      uint32_t handle);
1146 int anv_gem_syncobj_import_sync_file(struct anv_device *device,
1147                                      uint32_t handle, int fd);
1148 void anv_gem_syncobj_reset(struct anv_device *device, uint32_t handle);
1149 bool anv_gem_supports_syncobj_wait(int fd);
1150 int anv_gem_syncobj_wait(struct anv_device *device,
1151                          uint32_t *handles, uint32_t num_handles,
1152                          int64_t abs_timeout_ns, bool wait_all);
1153
1154 bool anv_vma_alloc(struct anv_device *device, struct anv_bo *bo);
1155 void anv_vma_free(struct anv_device *device, struct anv_bo *bo);
1156
1157 VkResult anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size);
1158
1159 struct anv_reloc_list {
1160    uint32_t                                     num_relocs;
1161    uint32_t                                     array_length;
1162    struct drm_i915_gem_relocation_entry *       relocs;
1163    struct anv_bo **                             reloc_bos;
1164    struct set *                                 deps;
1165 };
1166
1167 VkResult anv_reloc_list_init(struct anv_reloc_list *list,
1168                              const VkAllocationCallbacks *alloc);
1169 void anv_reloc_list_finish(struct anv_reloc_list *list,
1170                            const VkAllocationCallbacks *alloc);
1171
1172 VkResult anv_reloc_list_add(struct anv_reloc_list *list,
1173                             const VkAllocationCallbacks *alloc,
1174                             uint32_t offset, struct anv_bo *target_bo,
1175                             uint32_t delta);
1176
1177 struct anv_batch_bo {
1178    /* Link in the anv_cmd_buffer.owned_batch_bos list */
1179    struct list_head                             link;
1180
1181    struct anv_bo                                bo;
1182
1183    /* Bytes actually consumed in this batch BO */
1184    uint32_t                                     length;
1185
1186    struct anv_reloc_list                        relocs;
1187 };
1188
1189 struct anv_batch {
1190    const VkAllocationCallbacks *                alloc;
1191
1192    void *                                       start;
1193    void *                                       end;
1194    void *                                       next;
1195
1196    struct anv_reloc_list *                      relocs;
1197
1198    /* This callback is called (with the associated user data) in the event
1199     * that the batch runs out of space.
1200     */
1201    VkResult (*extend_cb)(struct anv_batch *, void *);
1202    void *                                       user_data;
1203
1204    /**
1205     * Current error status of the command buffer. Used to track inconsistent
1206     * or incomplete command buffer states that are the consequence of run-time
1207     * errors such as out of memory scenarios. We want to track this in the
1208     * batch because the command buffer object is not visible to some parts
1209     * of the driver.
1210     */
1211    VkResult                                     status;
1212 };
1213
1214 void *anv_batch_emit_dwords(struct anv_batch *batch, int num_dwords);
1215 void anv_batch_emit_batch(struct anv_batch *batch, struct anv_batch *other);
1216 uint64_t anv_batch_emit_reloc(struct anv_batch *batch,
1217                               void *location, struct anv_bo *bo, uint32_t offset);
1218 VkResult anv_device_submit_simple_batch(struct anv_device *device,
1219                                         struct anv_batch *batch);
1220
1221 static inline VkResult
1222 anv_batch_set_error(struct anv_batch *batch, VkResult error)
1223 {
1224    assert(error != VK_SUCCESS);
1225    if (batch->status == VK_SUCCESS)
1226       batch->status = error;
1227    return batch->status;
1228 }
1229
1230 static inline bool
1231 anv_batch_has_error(struct anv_batch *batch)
1232 {
1233    return batch->status != VK_SUCCESS;
1234 }
1235
1236 struct anv_address {
1237    struct anv_bo *bo;
1238    uint32_t offset;
1239 };
1240
1241 #define ANV_NULL_ADDRESS ((struct anv_address) { NULL, 0 })
1242
1243 static inline bool
1244 anv_address_is_null(struct anv_address addr)
1245 {
1246    return addr.bo == NULL && addr.offset == 0;
1247 }
1248
1249 static inline uint64_t
1250 anv_address_physical(struct anv_address addr)
1251 {
1252    if (addr.bo && (addr.bo->flags & EXEC_OBJECT_PINNED))
1253       return gen_canonical_address(addr.bo->offset + addr.offset);
1254    else
1255       return gen_canonical_address(addr.offset);
1256 }
1257
1258 static inline struct anv_address
1259 anv_address_add(struct anv_address addr, uint64_t offset)
1260 {
1261    addr.offset += offset;
1262    return addr;
1263 }
1264
1265 static inline void
1266 write_reloc(const struct anv_device *device, void *p, uint64_t v, bool flush)
1267 {
1268    unsigned reloc_size = 0;
1269    if (device->info.gen >= 8) {
1270       reloc_size = sizeof(uint64_t);
1271       *(uint64_t *)p = gen_canonical_address(v);
1272    } else {
1273       reloc_size = sizeof(uint32_t);
1274       *(uint32_t *)p = v;
1275    }
1276
1277    if (flush && !device->info.has_llc)
1278       gen_flush_range(p, reloc_size);
1279 }
1280
1281 static inline uint64_t
1282 _anv_combine_address(struct anv_batch *batch, void *location,
1283                      const struct anv_address address, uint32_t delta)
1284 {
1285    if (address.bo == NULL) {
1286       return address.offset + delta;
1287    } else {
1288       assert(batch->start <= location && location < batch->end);
1289
1290       return anv_batch_emit_reloc(batch, location, address.bo, address.offset + delta);
1291    }
1292 }
1293
1294 #define __gen_address_type struct anv_address
1295 #define __gen_user_data struct anv_batch
1296 #define __gen_combine_address _anv_combine_address
1297
1298 /* Wrapper macros needed to work around preprocessor argument issues.  In
1299  * particular, arguments don't get pre-evaluated if they are concatenated.
1300  * This means that, if you pass GENX(3DSTATE_PS) into the emit macro, the
1301  * GENX macro won't get evaluated if the emit macro contains "cmd ## foo".
1302  * We can work around this easily enough with these helpers.
1303  */
1304 #define __anv_cmd_length(cmd) cmd ## _length
1305 #define __anv_cmd_length_bias(cmd) cmd ## _length_bias
1306 #define __anv_cmd_header(cmd) cmd ## _header
1307 #define __anv_cmd_pack(cmd) cmd ## _pack
1308 #define __anv_reg_num(reg) reg ## _num
1309
1310 #define anv_pack_struct(dst, struc, ...) do {                              \
1311       struct struc __template = {                                          \
1312          __VA_ARGS__                                                       \
1313       };                                                                   \
1314       __anv_cmd_pack(struc)(NULL, dst, &__template);                       \
1315       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dst, __anv_cmd_length(struc) * 4)); \
1316    } while (0)
1317
1318 #define anv_batch_emitn(batch, n, cmd, ...) ({             \
1319       void *__dst = anv_batch_emit_dwords(batch, n);       \
1320       if (__dst) {                                         \
1321          struct cmd __template = {                         \
1322             __anv_cmd_header(cmd),                         \
1323            .DWordLength = n - __anv_cmd_length_bias(cmd),  \
1324             __VA_ARGS__                                    \
1325          };                                                \
1326          __anv_cmd_pack(cmd)(batch, __dst, &__template);   \
1327       }                                                    \
1328       __dst;                                               \
1329    })
1330
1331 #define anv_batch_emit_merge(batch, dwords0, dwords1)                   \
1332    do {                                                                 \
1333       uint32_t *dw;                                                     \
1334                                                                         \
1335       STATIC_ASSERT(ARRAY_SIZE(dwords0) == ARRAY_SIZE(dwords1));        \
1336       dw = anv_batch_emit_dwords((batch), ARRAY_SIZE(dwords0));         \
1337       if (!dw)                                                          \
1338          break;                                                         \
1339       for (uint32_t i = 0; i < ARRAY_SIZE(dwords0); i++)                \
1340          dw[i] = (dwords0)[i] | (dwords1)[i];                           \
1341       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dw, ARRAY_SIZE(dwords0) * 4));\
1342    } while (0)
1343
1344 #define anv_batch_emit(batch, cmd, name)                            \
1345    for (struct cmd name = { __anv_cmd_header(cmd) },                    \
1346         *_dst = anv_batch_emit_dwords(batch, __anv_cmd_length(cmd));    \
1347         __builtin_expect(_dst != NULL, 1);                              \
1348         ({ __anv_cmd_pack(cmd)(batch, _dst, &name);                     \
1349            VG(VALGRIND_CHECK_MEM_IS_DEFINED(_dst, __anv_cmd_length(cmd) * 4)); \
1350            _dst = NULL;                                                 \
1351          }))
1352
1353 #define GEN7_MOCS (struct GEN7_MEMORY_OBJECT_CONTROL_STATE) {  \
1354    .GraphicsDataTypeGFDT                        = 0,           \
1355    .LLCCacheabilityControlLLCCC                 = 0,           \
1356    .L3CacheabilityControlL3CC                   = 1,           \
1357 }
1358
1359 #define GEN75_MOCS (struct GEN75_MEMORY_OBJECT_CONTROL_STATE) {  \
1360    .LLCeLLCCacheabilityControlLLCCC             = 0,           \
1361    .L3CacheabilityControlL3CC                   = 1,           \
1362 }
1363
1364 #define GEN8_MOCS (struct GEN8_MEMORY_OBJECT_CONTROL_STATE) {  \
1365       .MemoryTypeLLCeLLCCacheabilityControl = WB,              \
1366       .TargetCache = L3DefertoPATforLLCeLLCselection,          \
1367       .AgeforQUADLRU = 0                                       \
1368    }
1369
1370 #define GEN8_EXTERNAL_MOCS (struct GEN8_MEMORY_OBJECT_CONTROL_STATE) {     \
1371       .MemoryTypeLLCeLLCCacheabilityControl = UCwithFenceifcoherentcycle,  \
1372       .TargetCache = L3DefertoPATforLLCeLLCselection,                      \
1373       .AgeforQUADLRU = 0                                                   \
1374    }
1375
1376 /* Skylake: MOCS is now an index into an array of 62 different caching
1377  * configurations programmed by the kernel.
1378  */
1379
1380 #define GEN9_MOCS (struct GEN9_MEMORY_OBJECT_CONTROL_STATE) {  \
1381       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */              \
1382       .IndextoMOCSTables                           = 2         \
1383    }
1384
1385 #define GEN9_EXTERNAL_MOCS (struct GEN9_MEMORY_OBJECT_CONTROL_STATE) {  \
1386       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */                       \
1387       .IndextoMOCSTables                           = 1                  \
1388    }
1389
1390 /* Cannonlake MOCS defines are duplicates of Skylake MOCS defines. */
1391 #define GEN10_MOCS (struct GEN10_MEMORY_OBJECT_CONTROL_STATE) {  \
1392       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */              \
1393       .IndextoMOCSTables                           = 2         \
1394    }
1395
1396 #define GEN10_EXTERNAL_MOCS (struct GEN10_MEMORY_OBJECT_CONTROL_STATE) {   \
1397       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */                          \
1398       .IndextoMOCSTables                           = 1                     \
1399    }
1400
1401 /* Ice Lake MOCS defines are duplicates of Skylake MOCS defines. */
1402 #define GEN11_MOCS (struct GEN11_MEMORY_OBJECT_CONTROL_STATE) {  \
1403       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */              \
1404       .IndextoMOCSTables                           = 2         \
1405    }
1406
1407 #define GEN11_EXTERNAL_MOCS (struct GEN11_MEMORY_OBJECT_CONTROL_STATE) {   \
1408       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */                          \
1409       .IndextoMOCSTables                           = 1                     \
1410    }
1411
1412 struct anv_device_memory {
1413    struct anv_bo *                              bo;
1414    struct anv_memory_type *                     type;
1415    VkDeviceSize                                 map_size;
1416    void *                                       map;
1417 };
1418
1419 /**
1420  * Header for Vertex URB Entry (VUE)
1421  */
1422 struct anv_vue_header {
1423    uint32_t Reserved;
1424    uint32_t RTAIndex; /* RenderTargetArrayIndex */
1425    uint32_t ViewportIndex;
1426    float PointWidth;
1427 };
1428
1429 struct anv_descriptor_set_binding_layout {
1430 #ifndef NDEBUG
1431    /* The type of the descriptors in this binding */
1432    VkDescriptorType type;
1433 #endif
1434
1435    /* Number of array elements in this binding */
1436    uint16_t array_size;
1437
1438    /* Index into the flattend descriptor set */
1439    uint16_t descriptor_index;
1440
1441    /* Index into the dynamic state array for a dynamic buffer */
1442    int16_t dynamic_offset_index;
1443
1444    /* Index into the descriptor set buffer views */
1445    int16_t buffer_index;
1446
1447    struct {
1448       /* Index into the binding table for the associated surface */
1449       int16_t surface_index;
1450
1451       /* Index into the sampler table for the associated sampler */
1452       int16_t sampler_index;
1453
1454       /* Index into the image table for the associated image */
1455       int16_t image_index;
1456    } stage[MESA_SHADER_STAGES];
1457
1458    /* Immutable samplers (or NULL if no immutable samplers) */
1459    struct anv_sampler **immutable_samplers;
1460 };
1461
1462 struct anv_descriptor_set_layout {
1463    /* Descriptor set layouts can be destroyed at almost any time */
1464    uint32_t ref_cnt;
1465
1466    /* Number of bindings in this descriptor set */
1467    uint16_t binding_count;
1468
1469    /* Total size of the descriptor set with room for all array entries */
1470    uint16_t size;
1471
1472    /* Shader stages affected by this descriptor set */
1473    uint16_t shader_stages;
1474
1475    /* Number of buffers in this descriptor set */
1476    uint16_t buffer_count;
1477
1478    /* Number of dynamic offsets used by this descriptor set */
1479    uint16_t dynamic_offset_count;
1480
1481    /* Bindings in this descriptor set */
1482    struct anv_descriptor_set_binding_layout binding[0];
1483 };
1484
1485 static inline void
1486 anv_descriptor_set_layout_ref(struct anv_descriptor_set_layout *layout)
1487 {
1488    assert(layout && layout->ref_cnt >= 1);
1489    p_atomic_inc(&layout->ref_cnt);
1490 }
1491
1492 static inline void
1493 anv_descriptor_set_layout_unref(struct anv_device *device,
1494                                 struct anv_descriptor_set_layout *layout)
1495 {
1496    assert(layout && layout->ref_cnt >= 1);
1497    if (p_atomic_dec_zero(&layout->ref_cnt))
1498       vk_free(&device->alloc, layout);
1499 }
1500
1501 struct anv_descriptor {
1502    VkDescriptorType type;
1503
1504    union {
1505       struct {
1506          VkImageLayout layout;
1507          struct anv_image_view *image_view;
1508          struct anv_sampler *sampler;
1509       };
1510
1511       struct {
1512          struct anv_buffer *buffer;
1513          uint64_t offset;
1514          uint64_t range;
1515       };
1516
1517       struct anv_buffer_view *buffer_view;
1518    };
1519 };
1520
1521 struct anv_descriptor_set {
1522    struct anv_descriptor_set_layout *layout;
1523    uint32_t size;
1524    uint32_t buffer_count;
1525    struct anv_buffer_view *buffer_views;
1526
1527    /* Link to descriptor pool's desc_sets list . */
1528    struct list_head pool_link;
1529
1530    struct anv_descriptor descriptors[0];
1531 };
1532
1533 struct anv_buffer_view {
1534    enum isl_format format; /**< VkBufferViewCreateInfo::format */
1535    uint64_t range; /**< VkBufferViewCreateInfo::range */
1536
1537    struct anv_address address;
1538
1539    struct anv_state surface_state;
1540    struct anv_state storage_surface_state;
1541    struct anv_state writeonly_storage_surface_state;
1542
1543    struct brw_image_param storage_image_param;
1544 };
1545
1546 struct anv_push_descriptor_set {
1547    struct anv_descriptor_set set;
1548
1549    /* Put this field right behind anv_descriptor_set so it fills up the
1550     * descriptors[0] field. */
1551    struct anv_descriptor descriptors[MAX_PUSH_DESCRIPTORS];
1552    struct anv_buffer_view buffer_views[MAX_PUSH_DESCRIPTORS];
1553 };
1554
1555 struct anv_descriptor_pool {
1556    uint32_t size;
1557    uint32_t next;
1558    uint32_t free_list;
1559
1560    struct anv_state_stream surface_state_stream;
1561    void *surface_state_free_list;
1562
1563    struct list_head desc_sets;
1564
1565    char data[0];
1566 };
1567
1568 enum anv_descriptor_template_entry_type {
1569    ANV_DESCRIPTOR_TEMPLATE_ENTRY_TYPE_IMAGE,
1570    ANV_DESCRIPTOR_TEMPLATE_ENTRY_TYPE_BUFFER,
1571    ANV_DESCRIPTOR_TEMPLATE_ENTRY_TYPE_BUFFER_VIEW
1572 };
1573
1574 struct anv_descriptor_template_entry {
1575    /* The type of descriptor in this entry */
1576    VkDescriptorType type;
1577
1578    /* Binding in the descriptor set */
1579    uint32_t binding;
1580
1581    /* Offset at which to write into the descriptor set binding */
1582    uint32_t array_element;
1583
1584    /* Number of elements to write into the descriptor set binding */
1585    uint32_t array_count;
1586
1587    /* Offset into the user provided data */
1588    size_t offset;
1589
1590    /* Stride between elements into the user provided data */
1591    size_t stride;
1592 };
1593
1594 struct anv_descriptor_update_template {
1595     VkPipelineBindPoint bind_point;
1596
1597    /* The descriptor set this template corresponds to. This value is only
1598     * valid if the template was created with the templateType
1599     * VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET_KHR.
1600     */
1601    uint8_t set;
1602
1603    /* Number of entries in this template */
1604    uint32_t entry_count;
1605
1606    /* Entries of the template */
1607    struct anv_descriptor_template_entry entries[0];
1608 };
1609
1610 size_t
1611 anv_descriptor_set_layout_size(const struct anv_descriptor_set_layout *layout);
1612
1613 void
1614 anv_descriptor_set_write_image_view(struct anv_descriptor_set *set,
1615                                     const struct gen_device_info * const devinfo,
1616                                     const VkDescriptorImageInfo * const info,
1617                                     VkDescriptorType type,
1618                                     uint32_t binding,
1619                                     uint32_t element);
1620
1621 void
1622 anv_descriptor_set_write_buffer_view(struct anv_descriptor_set *set,
1623                                      VkDescriptorType type,
1624                                      struct anv_buffer_view *buffer_view,
1625                                      uint32_t binding,
1626                                      uint32_t element);
1627
1628 void
1629 anv_descriptor_set_write_buffer(struct anv_descriptor_set *set,
1630                                 struct anv_device *device,
1631                                 struct anv_state_stream *alloc_stream,
1632                                 VkDescriptorType type,
1633                                 struct anv_buffer *buffer,
1634                                 uint32_t binding,
1635                                 uint32_t element,
1636                                 VkDeviceSize offset,
1637                                 VkDeviceSize range);
1638
1639 void
1640 anv_descriptor_set_write_template(struct anv_descriptor_set *set,
1641                                   struct anv_device *device,
1642                                   struct anv_state_stream *alloc_stream,
1643                                   const struct anv_descriptor_update_template *template,
1644                                   const void *data);
1645
1646 VkResult
1647 anv_descriptor_set_create(struct anv_device *device,
1648                           struct anv_descriptor_pool *pool,
1649                           struct anv_descriptor_set_layout *layout,
1650                           struct anv_descriptor_set **out_set);
1651
1652 void
1653 anv_descriptor_set_destroy(struct anv_device *device,
1654                            struct anv_descriptor_pool *pool,
1655                            struct anv_descriptor_set *set);
1656
1657 #define ANV_DESCRIPTOR_SET_SHADER_CONSTANTS (UINT8_MAX - 1)
1658 #define ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS UINT8_MAX
1659
1660 struct anv_pipeline_binding {
1661    /* The descriptor set this surface corresponds to.  The special value of
1662     * ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS indicates that the offset refers
1663     * to a color attachment and not a regular descriptor.
1664     */
1665    uint8_t set;
1666
1667    /* Binding in the descriptor set */
1668    uint32_t binding;
1669
1670    /* Index in the binding */
1671    uint32_t index;
1672
1673    /* Plane in the binding index */
1674    uint8_t plane;
1675
1676    /* Input attachment index (relative to the subpass) */
1677    uint8_t input_attachment_index;
1678
1679    /* For a storage image, whether it is write-only */
1680    bool write_only;
1681 };
1682
1683 struct anv_pipeline_layout {
1684    struct {
1685       struct anv_descriptor_set_layout *layout;
1686       uint32_t dynamic_offset_start;
1687    } set[MAX_SETS];
1688
1689    uint32_t num_sets;
1690
1691    struct {
1692       bool has_dynamic_offsets;
1693    } stage[MESA_SHADER_STAGES];
1694
1695    unsigned char sha1[20];
1696 };
1697
1698 struct anv_buffer {
1699    struct anv_device *                          device;
1700    VkDeviceSize                                 size;
1701
1702    VkBufferUsageFlags                           usage;
1703
1704    /* Set when bound */
1705    struct anv_address                           address;
1706 };
1707
1708 static inline uint64_t
1709 anv_buffer_get_range(struct anv_buffer *buffer, uint64_t offset, uint64_t range)
1710 {
1711    assert(offset <= buffer->size);
1712    if (range == VK_WHOLE_SIZE) {
1713       return buffer->size - offset;
1714    } else {
1715       assert(range + offset >= range);
1716       assert(range + offset <= buffer->size);
1717       return range;
1718    }
1719 }
1720
1721 enum anv_cmd_dirty_bits {
1722    ANV_CMD_DIRTY_DYNAMIC_VIEWPORT                  = 1 << 0, /* VK_DYNAMIC_STATE_VIEWPORT */
1723    ANV_CMD_DIRTY_DYNAMIC_SCISSOR                   = 1 << 1, /* VK_DYNAMIC_STATE_SCISSOR */
1724    ANV_CMD_DIRTY_DYNAMIC_LINE_WIDTH                = 1 << 2, /* VK_DYNAMIC_STATE_LINE_WIDTH */
1725    ANV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS                = 1 << 3, /* VK_DYNAMIC_STATE_DEPTH_BIAS */
1726    ANV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS           = 1 << 4, /* VK_DYNAMIC_STATE_BLEND_CONSTANTS */
1727    ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS              = 1 << 5, /* VK_DYNAMIC_STATE_DEPTH_BOUNDS */
1728    ANV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK      = 1 << 6, /* VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK */
1729    ANV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK        = 1 << 7, /* VK_DYNAMIC_STATE_STENCIL_WRITE_MASK */
1730    ANV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE         = 1 << 8, /* VK_DYNAMIC_STATE_STENCIL_REFERENCE */
1731    ANV_CMD_DIRTY_DYNAMIC_ALL                       = (1 << 9) - 1,
1732    ANV_CMD_DIRTY_PIPELINE                          = 1 << 9,
1733    ANV_CMD_DIRTY_INDEX_BUFFER                      = 1 << 10,
1734    ANV_CMD_DIRTY_RENDER_TARGETS                    = 1 << 11,
1735 };
1736 typedef uint32_t anv_cmd_dirty_mask_t;
1737
1738 enum anv_pipe_bits {
1739    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT            = (1 << 0),
1740    ANV_PIPE_STALL_AT_SCOREBOARD_BIT          = (1 << 1),
1741    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT       = (1 << 2),
1742    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT    = (1 << 3),
1743    ANV_PIPE_VF_CACHE_INVALIDATE_BIT          = (1 << 4),
1744    ANV_PIPE_DATA_CACHE_FLUSH_BIT             = (1 << 5),
1745    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT     = (1 << 10),
1746    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT = (1 << 11),
1747    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT    = (1 << 12),
1748    ANV_PIPE_DEPTH_STALL_BIT                  = (1 << 13),
1749    ANV_PIPE_CS_STALL_BIT                     = (1 << 20),
1750
1751    /* This bit does not exist directly in PIPE_CONTROL.  Instead it means that
1752     * a flush has happened but not a CS stall.  The next time we do any sort
1753     * of invalidation we need to insert a CS stall at that time.  Otherwise,
1754     * we would have to CS stall on every flush which could be bad.
1755     */
1756    ANV_PIPE_NEEDS_CS_STALL_BIT               = (1 << 21),
1757
1758    /* This bit does not exist directly in PIPE_CONTROL. It means that render
1759     * target operations are ongoing. Some operations like copies on the
1760     * command streamer might need to be aware of this to trigger the
1761     * appropriate stall before they can proceed with the copy.
1762     */
1763    ANV_PIPE_RENDER_TARGET_WRITES              = (1 << 22),
1764 };
1765
1766 #define ANV_PIPE_FLUSH_BITS ( \
1767    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT | \
1768    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
1769    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
1770
1771 #define ANV_PIPE_STALL_BITS ( \
1772    ANV_PIPE_STALL_AT_SCOREBOARD_BIT | \
1773    ANV_PIPE_DEPTH_STALL_BIT | \
1774    ANV_PIPE_CS_STALL_BIT)
1775
1776 #define ANV_PIPE_INVALIDATE_BITS ( \
1777    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT | \
1778    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT | \
1779    ANV_PIPE_VF_CACHE_INVALIDATE_BIT | \
1780    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
1781    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT | \
1782    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT)
1783
1784 static inline enum anv_pipe_bits
1785 anv_pipe_flush_bits_for_access_flags(VkAccessFlags flags)
1786 {
1787    enum anv_pipe_bits pipe_bits = 0;
1788
1789    unsigned b;
1790    for_each_bit(b, flags) {
1791       switch ((VkAccessFlagBits)(1 << b)) {
1792       case VK_ACCESS_SHADER_WRITE_BIT:
1793          pipe_bits |= ANV_PIPE_DATA_CACHE_FLUSH_BIT;
1794          break;
1795       case VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT:
1796          pipe_bits |= ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1797          break;
1798       case VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT:
1799          pipe_bits |= ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1800          break;
1801       case VK_ACCESS_TRANSFER_WRITE_BIT:
1802          pipe_bits |= ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1803          pipe_bits |= ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1804          break;
1805       case VK_ACCESS_MEMORY_WRITE_BIT:
1806          pipe_bits |= ANV_PIPE_FLUSH_BITS;
1807          break;
1808       default:
1809          break; /* Nothing to do */
1810       }
1811    }
1812
1813    return pipe_bits;
1814 }
1815
1816 static inline enum anv_pipe_bits
1817 anv_pipe_invalidate_bits_for_access_flags(VkAccessFlags flags)
1818 {
1819    enum anv_pipe_bits pipe_bits = 0;
1820
1821    unsigned b;
1822    for_each_bit(b, flags) {
1823       switch ((VkAccessFlagBits)(1 << b)) {
1824       case VK_ACCESS_INDIRECT_COMMAND_READ_BIT:
1825       case VK_ACCESS_INDEX_READ_BIT:
1826       case VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT:
1827          pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1828          break;
1829       case VK_ACCESS_UNIFORM_READ_BIT:
1830          pipe_bits |= ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
1831          pipe_bits |= ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1832          break;
1833       case VK_ACCESS_SHADER_READ_BIT:
1834       case VK_ACCESS_INPUT_ATTACHMENT_READ_BIT:
1835       case VK_ACCESS_TRANSFER_READ_BIT:
1836          pipe_bits |= ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1837          break;
1838       case VK_ACCESS_MEMORY_READ_BIT:
1839          pipe_bits |= ANV_PIPE_INVALIDATE_BITS;
1840          break;
1841       case VK_ACCESS_MEMORY_WRITE_BIT:
1842          pipe_bits |= ANV_PIPE_FLUSH_BITS;
1843          break;
1844       default:
1845          break; /* Nothing to do */
1846       }
1847    }
1848
1849    return pipe_bits;
1850 }
1851
1852 #define VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV (         \
1853    VK_IMAGE_ASPECT_COLOR_BIT | \
1854    VK_IMAGE_ASPECT_PLANE_0_BIT | \
1855    VK_IMAGE_ASPECT_PLANE_1_BIT | \
1856    VK_IMAGE_ASPECT_PLANE_2_BIT)
1857 #define VK_IMAGE_ASPECT_PLANES_BITS_ANV ( \
1858    VK_IMAGE_ASPECT_PLANE_0_BIT | \
1859    VK_IMAGE_ASPECT_PLANE_1_BIT | \
1860    VK_IMAGE_ASPECT_PLANE_2_BIT)
1861
1862 struct anv_vertex_binding {
1863    struct anv_buffer *                          buffer;
1864    VkDeviceSize                                 offset;
1865 };
1866
1867 #define ANV_PARAM_PUSH(offset)         ((1 << 16) | (uint32_t)(offset))
1868 #define ANV_PARAM_PUSH_OFFSET(param)   ((param) & 0xffff)
1869
1870 struct anv_push_constants {
1871    /* Current allocated size of this push constants data structure.
1872     * Because a decent chunk of it may not be used (images on SKL, for
1873     * instance), we won't actually allocate the entire structure up-front.
1874     */
1875    uint32_t size;
1876
1877    /* Push constant data provided by the client through vkPushConstants */
1878    uint8_t client_data[MAX_PUSH_CONSTANTS_SIZE];
1879
1880    /* Used for vkCmdDispatchBase */
1881    uint32_t base_work_group_id[3];
1882
1883    /* Image data for image_load_store on pre-SKL */
1884    struct brw_image_param images[MAX_GEN8_IMAGES];
1885 };
1886
1887 struct anv_dynamic_state {
1888    struct {
1889       uint32_t                                  count;
1890       VkViewport                                viewports[MAX_VIEWPORTS];
1891    } viewport;
1892
1893    struct {
1894       uint32_t                                  count;
1895       VkRect2D                                  scissors[MAX_SCISSORS];
1896    } scissor;
1897
1898    float                                        line_width;
1899
1900    struct {
1901       float                                     bias;
1902       float                                     clamp;
1903       float                                     slope;
1904    } depth_bias;
1905
1906    float                                        blend_constants[4];
1907
1908    struct {
1909       float                                     min;
1910       float                                     max;
1911    } depth_bounds;
1912
1913    struct {
1914       uint32_t                                  front;
1915       uint32_t                                  back;
1916    } stencil_compare_mask;
1917
1918    struct {
1919       uint32_t                                  front;
1920       uint32_t                                  back;
1921    } stencil_write_mask;
1922
1923    struct {
1924       uint32_t                                  front;
1925       uint32_t                                  back;
1926    } stencil_reference;
1927 };
1928
1929 extern const struct anv_dynamic_state default_dynamic_state;
1930
1931 void anv_dynamic_state_copy(struct anv_dynamic_state *dest,
1932                             const struct anv_dynamic_state *src,
1933                             uint32_t copy_mask);
1934
1935 struct anv_surface_state {
1936    struct anv_state state;
1937    /** Address of the surface referred to by this state
1938     *
1939     * This address is relative to the start of the BO.
1940     */
1941    struct anv_address address;
1942    /* Address of the aux surface, if any
1943     *
1944     * This field is ANV_NULL_ADDRESS if and only if no aux surface exists.
1945     *
1946     * With the exception of gen8, the bottom 12 bits of this address' offset
1947     * include extra aux information.
1948     */
1949    struct anv_address aux_address;
1950    /* Address of the clear color, if any
1951     *
1952     * This address is relative to the start of the BO.
1953     */
1954    struct anv_address clear_address;
1955 };
1956
1957 /**
1958  * Attachment state when recording a renderpass instance.
1959  *
1960  * The clear value is valid only if there exists a pending clear.
1961  */
1962 struct anv_attachment_state {
1963    enum isl_aux_usage                           aux_usage;
1964    enum isl_aux_usage                           input_aux_usage;
1965    struct anv_surface_state                     color;
1966    struct anv_surface_state                     input;
1967
1968    VkImageLayout                                current_layout;
1969    VkImageAspectFlags                           pending_clear_aspects;
1970    VkImageAspectFlags                           pending_load_aspects;
1971    bool                                         fast_clear;
1972    VkClearValue                                 clear_value;
1973    bool                                         clear_color_is_zero_one;
1974    bool                                         clear_color_is_zero;
1975
1976    /* When multiview is active, attachments with a renderpass clear
1977     * operation have their respective layers cleared on the first
1978     * subpass that uses them, and only in that subpass. We keep track
1979     * of this using a bitfield to indicate which layers of an attachment
1980     * have not been cleared yet when multiview is active.
1981     */
1982    uint32_t                                     pending_clear_views;
1983 };
1984
1985 /** State tracking for particular pipeline bind point
1986  *
1987  * This struct is the base struct for anv_cmd_graphics_state and
1988  * anv_cmd_compute_state.  These are used to track state which is bound to a
1989  * particular type of pipeline.  Generic state that applies per-stage such as
1990  * binding table offsets and push constants is tracked generically with a
1991  * per-stage array in anv_cmd_state.
1992  */
1993 struct anv_cmd_pipeline_state {
1994    struct anv_pipeline *pipeline;
1995    struct anv_pipeline_layout *layout;
1996
1997    struct anv_descriptor_set *descriptors[MAX_SETS];
1998    uint32_t dynamic_offsets[MAX_DYNAMIC_BUFFERS];
1999
2000    struct anv_push_descriptor_set *push_descriptors[MAX_SETS];
2001 };
2002
2003 /** State tracking for graphics pipeline
2004  *
2005  * This has anv_cmd_pipeline_state as a base struct to track things which get
2006  * bound to a graphics pipeline.  Along with general pipeline bind point state
2007  * which is in the anv_cmd_pipeline_state base struct, it also contains other
2008  * state which is graphics-specific.
2009  */
2010 struct anv_cmd_graphics_state {
2011    struct anv_cmd_pipeline_state base;
2012
2013    anv_cmd_dirty_mask_t dirty;
2014    uint32_t vb_dirty;
2015
2016    struct anv_dynamic_state dynamic;
2017
2018    struct {
2019       struct anv_buffer *index_buffer;
2020       uint32_t index_type; /**< 3DSTATE_INDEX_BUFFER.IndexFormat */
2021       uint32_t index_offset;
2022    } gen7;
2023 };
2024
2025 /** State tracking for compute pipeline
2026  *
2027  * This has anv_cmd_pipeline_state as a base struct to track things which get
2028  * bound to a compute pipeline.  Along with general pipeline bind point state
2029  * which is in the anv_cmd_pipeline_state base struct, it also contains other
2030  * state which is compute-specific.
2031  */
2032 struct anv_cmd_compute_state {
2033    struct anv_cmd_pipeline_state base;
2034
2035    bool pipeline_dirty;
2036
2037    struct anv_address num_workgroups;
2038 };
2039
2040 /** State required while building cmd buffer */
2041 struct anv_cmd_state {
2042    /* PIPELINE_SELECT.PipelineSelection */
2043    uint32_t                                     current_pipeline;
2044    const struct gen_l3_config *                 current_l3_config;
2045
2046    struct anv_cmd_graphics_state                gfx;
2047    struct anv_cmd_compute_state                 compute;
2048
2049    enum anv_pipe_bits                           pending_pipe_bits;
2050    VkShaderStageFlags                           descriptors_dirty;
2051    VkShaderStageFlags                           push_constants_dirty;
2052
2053    struct anv_framebuffer *                     framebuffer;
2054    struct anv_render_pass *                     pass;
2055    struct anv_subpass *                         subpass;
2056    VkRect2D                                     render_area;
2057    uint32_t                                     restart_index;
2058    struct anv_vertex_binding                    vertex_bindings[MAX_VBS];
2059    VkShaderStageFlags                           push_constant_stages;
2060    struct anv_push_constants *                  push_constants[MESA_SHADER_STAGES];
2061    struct anv_state                             binding_tables[MESA_SHADER_STAGES];
2062    struct anv_state                             samplers[MESA_SHADER_STAGES];
2063
2064    /**
2065     * Whether or not the gen8 PMA fix is enabled.  We ensure that, at the top
2066     * of any command buffer it is disabled by disabling it in EndCommandBuffer
2067     * and before invoking the secondary in ExecuteCommands.
2068     */
2069    bool                                         pma_fix_enabled;
2070
2071    /**
2072     * Whether or not we know for certain that HiZ is enabled for the current
2073     * subpass.  If, for whatever reason, we are unsure as to whether HiZ is
2074     * enabled or not, this will be false.
2075     */
2076    bool                                         hiz_enabled;
2077
2078    /**
2079     * Array length is anv_cmd_state::pass::attachment_count. Array content is
2080     * valid only when recording a render pass instance.
2081     */
2082    struct anv_attachment_state *                attachments;
2083
2084    /**
2085     * Surface states for color render targets.  These are stored in a single
2086     * flat array.  For depth-stencil attachments, the surface state is simply
2087     * left blank.
2088     */
2089    struct anv_state                             render_pass_states;
2090
2091    /**
2092     * A null surface state of the right size to match the framebuffer.  This
2093     * is one of the states in render_pass_states.
2094     */
2095    struct anv_state                             null_surface_state;
2096 };
2097
2098 struct anv_cmd_pool {
2099    VkAllocationCallbacks                        alloc;
2100    struct list_head                             cmd_buffers;
2101 };
2102
2103 #define ANV_CMD_BUFFER_BATCH_SIZE 8192
2104
2105 enum anv_cmd_buffer_exec_mode {
2106    ANV_CMD_BUFFER_EXEC_MODE_PRIMARY,
2107    ANV_CMD_BUFFER_EXEC_MODE_EMIT,
2108    ANV_CMD_BUFFER_EXEC_MODE_GROW_AND_EMIT,
2109    ANV_CMD_BUFFER_EXEC_MODE_CHAIN,
2110    ANV_CMD_BUFFER_EXEC_MODE_COPY_AND_CHAIN,
2111 };
2112
2113 struct anv_cmd_buffer {
2114    VK_LOADER_DATA                               _loader_data;
2115
2116    struct anv_device *                          device;
2117
2118    struct anv_cmd_pool *                        pool;
2119    struct list_head                             pool_link;
2120
2121    struct anv_batch                             batch;
2122
2123    /* Fields required for the actual chain of anv_batch_bo's.
2124     *
2125     * These fields are initialized by anv_cmd_buffer_init_batch_bo_chain().
2126     */
2127    struct list_head                             batch_bos;
2128    enum anv_cmd_buffer_exec_mode                exec_mode;
2129
2130    /* A vector of anv_batch_bo pointers for every batch or surface buffer
2131     * referenced by this command buffer
2132     *
2133     * initialized by anv_cmd_buffer_init_batch_bo_chain()
2134     */
2135    struct u_vector                            seen_bbos;
2136
2137    /* A vector of int32_t's for every block of binding tables.
2138     *
2139     * initialized by anv_cmd_buffer_init_batch_bo_chain()
2140     */
2141    struct u_vector                              bt_block_states;
2142    uint32_t                                     bt_next;
2143
2144    struct anv_reloc_list                        surface_relocs;
2145    /** Last seen surface state block pool center bo offset */
2146    uint32_t                                     last_ss_pool_center;
2147
2148    /* Serial for tracking buffer completion */
2149    uint32_t                                     serial;
2150
2151    /* Stream objects for storing temporary data */
2152    struct anv_state_stream                      surface_state_stream;
2153    struct anv_state_stream                      dynamic_state_stream;
2154
2155    VkCommandBufferUsageFlags                    usage_flags;
2156    VkCommandBufferLevel                         level;
2157
2158    struct anv_cmd_state                         state;
2159 };
2160
2161 VkResult anv_cmd_buffer_init_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
2162 void anv_cmd_buffer_fini_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
2163 void anv_cmd_buffer_reset_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
2164 void anv_cmd_buffer_end_batch_buffer(struct anv_cmd_buffer *cmd_buffer);
2165 void anv_cmd_buffer_add_secondary(struct anv_cmd_buffer *primary,
2166                                   struct anv_cmd_buffer *secondary);
2167 void anv_cmd_buffer_prepare_execbuf(struct anv_cmd_buffer *cmd_buffer);
2168 VkResult anv_cmd_buffer_execbuf(struct anv_device *device,
2169                                 struct anv_cmd_buffer *cmd_buffer,
2170                                 const VkSemaphore *in_semaphores,
2171                                 uint32_t num_in_semaphores,
2172                                 const VkSemaphore *out_semaphores,
2173                                 uint32_t num_out_semaphores,
2174                                 VkFence fence);
2175
2176 VkResult anv_cmd_buffer_reset(struct anv_cmd_buffer *cmd_buffer);
2177
2178 VkResult
2179 anv_cmd_buffer_ensure_push_constants_size(struct anv_cmd_buffer *cmd_buffer,
2180                                           gl_shader_stage stage, uint32_t size);
2181 #define anv_cmd_buffer_ensure_push_constant_field(cmd_buffer, stage, field) \
2182    anv_cmd_buffer_ensure_push_constants_size(cmd_buffer, stage, \
2183       (offsetof(struct anv_push_constants, field) + \
2184        sizeof(cmd_buffer->state.push_constants[0]->field)))
2185
2186 struct anv_state anv_cmd_buffer_emit_dynamic(struct anv_cmd_buffer *cmd_buffer,
2187                                              const void *data, uint32_t size, uint32_t alignment);
2188 struct anv_state anv_cmd_buffer_merge_dynamic(struct anv_cmd_buffer *cmd_buffer,
2189                                               uint32_t *a, uint32_t *b,
2190                                               uint32_t dwords, uint32_t alignment);
2191
2192 struct anv_address
2193 anv_cmd_buffer_surface_base_address(struct anv_cmd_buffer *cmd_buffer);
2194 struct anv_state
2195 anv_cmd_buffer_alloc_binding_table(struct anv_cmd_buffer *cmd_buffer,
2196                                    uint32_t entries, uint32_t *state_offset);
2197 struct anv_state
2198 anv_cmd_buffer_alloc_surface_state(struct anv_cmd_buffer *cmd_buffer);
2199 struct anv_state
2200 anv_cmd_buffer_alloc_dynamic_state(struct anv_cmd_buffer *cmd_buffer,
2201                                    uint32_t size, uint32_t alignment);
2202
2203 VkResult
2204 anv_cmd_buffer_new_binding_table_block(struct anv_cmd_buffer *cmd_buffer);
2205
2206 void gen8_cmd_buffer_emit_viewport(struct anv_cmd_buffer *cmd_buffer);
2207 void gen8_cmd_buffer_emit_depth_viewport(struct anv_cmd_buffer *cmd_buffer,
2208                                          bool depth_clamp_enable);
2209 void gen7_cmd_buffer_emit_scissor(struct anv_cmd_buffer *cmd_buffer);
2210
2211 void anv_cmd_buffer_setup_attachments(struct anv_cmd_buffer *cmd_buffer,
2212                                       struct anv_render_pass *pass,
2213                                       struct anv_framebuffer *framebuffer,
2214                                       const VkClearValue *clear_values);
2215
2216 void anv_cmd_buffer_emit_state_base_address(struct anv_cmd_buffer *cmd_buffer);
2217
2218 struct anv_state
2219 anv_cmd_buffer_push_constants(struct anv_cmd_buffer *cmd_buffer,
2220                               gl_shader_stage stage);
2221 struct anv_state
2222 anv_cmd_buffer_cs_push_constants(struct anv_cmd_buffer *cmd_buffer);
2223
2224 void anv_cmd_buffer_resolve_subpass(struct anv_cmd_buffer *cmd_buffer);
2225
2226 const struct anv_image_view *
2227 anv_cmd_buffer_get_depth_stencil_view(const struct anv_cmd_buffer *cmd_buffer);
2228
2229 VkResult
2230 anv_cmd_buffer_alloc_blorp_binding_table(struct anv_cmd_buffer *cmd_buffer,
2231                                          uint32_t num_entries,
2232                                          uint32_t *state_offset,
2233                                          struct anv_state *bt_state);
2234
2235 void anv_cmd_buffer_dump(struct anv_cmd_buffer *cmd_buffer);
2236
2237 enum anv_fence_type {
2238    ANV_FENCE_TYPE_NONE = 0,
2239    ANV_FENCE_TYPE_BO,
2240    ANV_FENCE_TYPE_SYNCOBJ,
2241    ANV_FENCE_TYPE_WSI,
2242 };
2243
2244 enum anv_bo_fence_state {
2245    /** Indicates that this is a new (or newly reset fence) */
2246    ANV_BO_FENCE_STATE_RESET,
2247
2248    /** Indicates that this fence has been submitted to the GPU but is still
2249     * (as far as we know) in use by the GPU.
2250     */
2251    ANV_BO_FENCE_STATE_SUBMITTED,
2252
2253    ANV_BO_FENCE_STATE_SIGNALED,
2254 };
2255
2256 struct anv_fence_impl {
2257    enum anv_fence_type type;
2258
2259    union {
2260       /** Fence implementation for BO fences
2261        *
2262        * These fences use a BO and a set of CPU-tracked state flags.  The BO
2263        * is added to the object list of the last execbuf call in a QueueSubmit
2264        * and is marked EXEC_WRITE.  The state flags track when the BO has been
2265        * submitted to the kernel.  We need to do this because Vulkan lets you
2266        * wait on a fence that has not yet been submitted and I915_GEM_BUSY
2267        * will say it's idle in this case.
2268        */
2269       struct {
2270          struct anv_bo bo;
2271          enum anv_bo_fence_state state;
2272       } bo;
2273
2274       /** DRM syncobj handle for syncobj-based fences */
2275       uint32_t syncobj;
2276
2277       /** WSI fence */
2278       struct wsi_fence *fence_wsi;
2279    };
2280 };
2281
2282 struct anv_fence {
2283    /* Permanent fence state.  Every fence has some form of permanent state
2284     * (type != ANV_SEMAPHORE_TYPE_NONE).  This may be a BO to fence on (for
2285     * cross-process fences) or it could just be a dummy for use internally.
2286     */
2287    struct anv_fence_impl permanent;
2288
2289    /* Temporary fence state.  A fence *may* have temporary state.  That state
2290     * is added to the fence by an import operation and is reset back to
2291     * ANV_SEMAPHORE_TYPE_NONE when the fence is reset.  A fence with temporary
2292     * state cannot be signaled because the fence must already be signaled
2293     * before the temporary state can be exported from the fence in the other
2294     * process and imported here.
2295     */
2296    struct anv_fence_impl temporary;
2297 };
2298
2299 struct anv_event {
2300    uint64_t                                     semaphore;
2301    struct anv_state                             state;
2302 };
2303
2304 enum anv_semaphore_type {
2305    ANV_SEMAPHORE_TYPE_NONE = 0,
2306    ANV_SEMAPHORE_TYPE_DUMMY,
2307    ANV_SEMAPHORE_TYPE_BO,
2308    ANV_SEMAPHORE_TYPE_SYNC_FILE,
2309    ANV_SEMAPHORE_TYPE_DRM_SYNCOBJ,
2310 };
2311
2312 struct anv_semaphore_impl {
2313    enum anv_semaphore_type type;
2314
2315    union {
2316       /* A BO representing this semaphore when type == ANV_SEMAPHORE_TYPE_BO.
2317        * This BO will be added to the object list on any execbuf2 calls for
2318        * which this semaphore is used as a wait or signal fence.  When used as
2319        * a signal fence, the EXEC_OBJECT_WRITE flag will be set.
2320        */
2321       struct anv_bo *bo;
2322
2323       /* The sync file descriptor when type == ANV_SEMAPHORE_TYPE_SYNC_FILE.
2324        * If the semaphore is in the unsignaled state due to either just being
2325        * created or because it has been used for a wait, fd will be -1.
2326        */
2327       int fd;
2328
2329       /* Sync object handle when type == ANV_SEMAPHORE_TYPE_DRM_SYNCOBJ.
2330        * Unlike GEM BOs, DRM sync objects aren't deduplicated by the kernel on
2331        * import so we don't need to bother with a userspace cache.
2332        */
2333       uint32_t syncobj;
2334    };
2335 };
2336
2337 struct anv_semaphore {
2338    /* Permanent semaphore state.  Every semaphore has some form of permanent
2339     * state (type != ANV_SEMAPHORE_TYPE_NONE).  This may be a BO to fence on
2340     * (for cross-process semaphores0 or it could just be a dummy for use
2341     * internally.
2342     */
2343    struct anv_semaphore_impl permanent;
2344
2345    /* Temporary semaphore state.  A semaphore *may* have temporary state.
2346     * That state is added to the semaphore by an import operation and is reset
2347     * back to ANV_SEMAPHORE_TYPE_NONE when the semaphore is waited on.  A
2348     * semaphore with temporary state cannot be signaled because the semaphore
2349     * must already be signaled before the temporary state can be exported from
2350     * the semaphore in the other process and imported here.
2351     */
2352    struct anv_semaphore_impl temporary;
2353 };
2354
2355 void anv_semaphore_reset_temporary(struct anv_device *device,
2356                                    struct anv_semaphore *semaphore);
2357
2358 struct anv_shader_module {
2359    unsigned char                                sha1[20];
2360    uint32_t                                     size;
2361    char                                         data[0];
2362 };
2363
2364 static inline gl_shader_stage
2365 vk_to_mesa_shader_stage(VkShaderStageFlagBits vk_stage)
2366 {
2367    assert(__builtin_popcount(vk_stage) == 1);
2368    return ffs(vk_stage) - 1;
2369 }
2370
2371 static inline VkShaderStageFlagBits
2372 mesa_to_vk_shader_stage(gl_shader_stage mesa_stage)
2373 {
2374    return (1 << mesa_stage);
2375 }
2376
2377 #define ANV_STAGE_MASK ((1 << MESA_SHADER_STAGES) - 1)
2378
2379 #define anv_foreach_stage(stage, stage_bits)                         \
2380    for (gl_shader_stage stage,                                       \
2381         __tmp = (gl_shader_stage)((stage_bits) & ANV_STAGE_MASK);    \
2382         stage = __builtin_ffs(__tmp) - 1, __tmp;                     \
2383         __tmp &= ~(1 << (stage)))
2384
2385 struct anv_pipeline_bind_map {
2386    uint32_t surface_count;
2387    uint32_t sampler_count;
2388    uint32_t image_count;
2389
2390    struct anv_pipeline_binding *                surface_to_descriptor;
2391    struct anv_pipeline_binding *                sampler_to_descriptor;
2392 };
2393
2394 struct anv_shader_bin_key {
2395    uint32_t size;
2396    uint8_t data[0];
2397 };
2398
2399 struct anv_shader_bin {
2400    uint32_t ref_cnt;
2401
2402    const struct anv_shader_bin_key *key;
2403
2404    struct anv_state kernel;
2405    uint32_t kernel_size;
2406
2407    struct anv_state constant_data;
2408    uint32_t constant_data_size;
2409
2410    const struct brw_stage_prog_data *prog_data;
2411    uint32_t prog_data_size;
2412
2413    struct anv_pipeline_bind_map bind_map;
2414 };
2415
2416 struct anv_shader_bin *
2417 anv_shader_bin_create(struct anv_device *device,
2418                       const void *key, uint32_t key_size,
2419                       const void *kernel, uint32_t kernel_size,
2420                       const void *constant_data, uint32_t constant_data_size,
2421                       const struct brw_stage_prog_data *prog_data,
2422                       uint32_t prog_data_size, const void *prog_data_param,
2423                       const struct anv_pipeline_bind_map *bind_map);
2424
2425 void
2426 anv_shader_bin_destroy(struct anv_device *device, struct anv_shader_bin *shader);
2427
2428 static inline void
2429 anv_shader_bin_ref(struct anv_shader_bin *shader)
2430 {
2431    assert(shader && shader->ref_cnt >= 1);
2432    p_atomic_inc(&shader->ref_cnt);
2433 }
2434
2435 static inline void
2436 anv_shader_bin_unref(struct anv_device *device, struct anv_shader_bin *shader)
2437 {
2438    assert(shader && shader->ref_cnt >= 1);
2439    if (p_atomic_dec_zero(&shader->ref_cnt))
2440       anv_shader_bin_destroy(device, shader);
2441 }
2442
2443 struct anv_pipeline {
2444    struct anv_device *                          device;
2445    struct anv_batch                             batch;
2446    uint32_t                                     batch_data[512];
2447    struct anv_reloc_list                        batch_relocs;
2448    uint32_t                                     dynamic_state_mask;
2449    struct anv_dynamic_state                     dynamic_state;
2450
2451    struct anv_subpass *                         subpass;
2452
2453    bool                                         needs_data_cache;
2454
2455    struct anv_shader_bin *                      shaders[MESA_SHADER_STAGES];
2456
2457    struct {
2458       const struct gen_l3_config *              l3_config;
2459       uint32_t                                  total_size;
2460    } urb;
2461
2462    VkShaderStageFlags                           active_stages;
2463    struct anv_state                             blend_state;
2464
2465    uint32_t                                     vb_used;
2466    struct anv_pipeline_vertex_binding {
2467       uint32_t                                  stride;
2468       bool                                      instanced;
2469       uint32_t                                  instance_divisor;
2470    } vb[MAX_VBS];
2471
2472    bool                                         primitive_restart;
2473    uint32_t                                     topology;
2474
2475    uint32_t                                     cs_right_mask;
2476
2477    bool                                         writes_depth;
2478    bool                                         depth_test_enable;
2479    bool                                         writes_stencil;
2480    bool                                         stencil_test_enable;
2481    bool                                         depth_clamp_enable;
2482    bool                                         sample_shading_enable;
2483    bool                                         kill_pixel;
2484
2485    struct {
2486       uint32_t                                  sf[7];
2487       uint32_t                                  depth_stencil_state[3];
2488    } gen7;
2489
2490    struct {
2491       uint32_t                                  sf[4];
2492       uint32_t                                  raster[5];
2493       uint32_t                                  wm_depth_stencil[3];
2494    } gen8;
2495
2496    struct {
2497       uint32_t                                  wm_depth_stencil[4];
2498    } gen9;
2499
2500    uint32_t                                     interface_descriptor_data[8];
2501 };
2502
2503 static inline bool
2504 anv_pipeline_has_stage(const struct anv_pipeline *pipeline,
2505                        gl_shader_stage stage)
2506 {
2507    return (pipeline->active_stages & mesa_to_vk_shader_stage(stage)) != 0;
2508 }
2509
2510 #define ANV_DECL_GET_PROG_DATA_FUNC(prefix, stage)                   \
2511 static inline const struct brw_##prefix##_prog_data *                \
2512 get_##prefix##_prog_data(const struct anv_pipeline *pipeline)        \
2513 {                                                                    \
2514    if (anv_pipeline_has_stage(pipeline, stage)) {                    \
2515       return (const struct brw_##prefix##_prog_data *)               \
2516              pipeline->shaders[stage]->prog_data;                    \
2517    } else {                                                          \
2518       return NULL;                                                   \
2519    }                                                                 \
2520 }
2521
2522 ANV_DECL_GET_PROG_DATA_FUNC(vs, MESA_SHADER_VERTEX)
2523 ANV_DECL_GET_PROG_DATA_FUNC(tcs, MESA_SHADER_TESS_CTRL)
2524 ANV_DECL_GET_PROG_DATA_FUNC(tes, MESA_SHADER_TESS_EVAL)
2525 ANV_DECL_GET_PROG_DATA_FUNC(gs, MESA_SHADER_GEOMETRY)
2526 ANV_DECL_GET_PROG_DATA_FUNC(wm, MESA_SHADER_FRAGMENT)
2527 ANV_DECL_GET_PROG_DATA_FUNC(cs, MESA_SHADER_COMPUTE)
2528
2529 static inline const struct brw_vue_prog_data *
2530 anv_pipeline_get_last_vue_prog_data(const struct anv_pipeline *pipeline)
2531 {
2532    if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
2533       return &get_gs_prog_data(pipeline)->base;
2534    else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
2535       return &get_tes_prog_data(pipeline)->base;
2536    else
2537       return &get_vs_prog_data(pipeline)->base;
2538 }
2539
2540 VkResult
2541 anv_pipeline_init(struct anv_pipeline *pipeline, struct anv_device *device,
2542                   struct anv_pipeline_cache *cache,
2543                   const VkGraphicsPipelineCreateInfo *pCreateInfo,
2544                   const VkAllocationCallbacks *alloc);
2545
2546 VkResult
2547 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
2548                         struct anv_pipeline_cache *cache,
2549                         const VkComputePipelineCreateInfo *info,
2550                         const struct anv_shader_module *module,
2551                         const char *entrypoint,
2552                         const VkSpecializationInfo *spec_info);
2553
2554 struct anv_format_plane {
2555    enum isl_format isl_format:16;
2556    struct isl_swizzle swizzle;
2557
2558    /* Whether this plane contains chroma channels */
2559    bool has_chroma;
2560
2561    /* For downscaling of YUV planes */
2562    uint8_t denominator_scales[2];
2563
2564    /* How to map sampled ycbcr planes to a single 4 component element. */
2565    struct isl_swizzle ycbcr_swizzle;
2566 };
2567
2568
2569 struct anv_format {
2570    struct anv_format_plane planes[3];
2571    uint8_t n_planes;
2572    bool can_ycbcr;
2573 };
2574
2575 static inline uint32_t
2576 anv_image_aspect_to_plane(VkImageAspectFlags image_aspects,
2577                           VkImageAspectFlags aspect_mask)
2578 {
2579    switch (aspect_mask) {
2580    case VK_IMAGE_ASPECT_COLOR_BIT:
2581    case VK_IMAGE_ASPECT_DEPTH_BIT:
2582    case VK_IMAGE_ASPECT_PLANE_0_BIT:
2583       return 0;
2584    case VK_IMAGE_ASPECT_STENCIL_BIT:
2585       if ((image_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) == 0)
2586          return 0;
2587       /* Fall-through */
2588    case VK_IMAGE_ASPECT_PLANE_1_BIT:
2589       return 1;
2590    case VK_IMAGE_ASPECT_PLANE_2_BIT:
2591       return 2;
2592    default:
2593       /* Purposefully assert with depth/stencil aspects. */
2594       unreachable("invalid image aspect");
2595    }
2596 }
2597
2598 static inline uint32_t
2599 anv_image_aspect_get_planes(VkImageAspectFlags aspect_mask)
2600 {
2601    uint32_t planes = 0;
2602
2603    if (aspect_mask & (VK_IMAGE_ASPECT_COLOR_BIT |
2604                       VK_IMAGE_ASPECT_DEPTH_BIT |
2605                       VK_IMAGE_ASPECT_STENCIL_BIT |
2606                       VK_IMAGE_ASPECT_PLANE_0_BIT))
2607       planes++;
2608    if (aspect_mask & VK_IMAGE_ASPECT_PLANE_1_BIT)
2609       planes++;
2610    if (aspect_mask & VK_IMAGE_ASPECT_PLANE_2_BIT)
2611       planes++;
2612
2613    if ((aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) != 0 &&
2614        (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) != 0)
2615       planes++;
2616
2617    return planes;
2618 }
2619
2620 static inline VkImageAspectFlags
2621 anv_plane_to_aspect(VkImageAspectFlags image_aspects,
2622                     uint32_t plane)
2623 {
2624    if (image_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
2625       if (util_bitcount(image_aspects) > 1)
2626          return VK_IMAGE_ASPECT_PLANE_0_BIT << plane;
2627       return VK_IMAGE_ASPECT_COLOR_BIT;
2628    }
2629    if (image_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)
2630       return VK_IMAGE_ASPECT_DEPTH_BIT << plane;
2631    assert(image_aspects == VK_IMAGE_ASPECT_STENCIL_BIT);
2632    return VK_IMAGE_ASPECT_STENCIL_BIT;
2633 }
2634
2635 #define anv_foreach_image_aspect_bit(b, image, aspects) \
2636    for_each_bit(b, anv_image_expand_aspects(image, aspects))
2637
2638 const struct anv_format *
2639 anv_get_format(VkFormat format);
2640
2641 static inline uint32_t
2642 anv_get_format_planes(VkFormat vk_format)
2643 {
2644    const struct anv_format *format = anv_get_format(vk_format);
2645
2646    return format != NULL ? format->n_planes : 0;
2647 }
2648
2649 struct anv_format_plane
2650 anv_get_format_plane(const struct gen_device_info *devinfo, VkFormat vk_format,
2651                      VkImageAspectFlagBits aspect, VkImageTiling tiling);
2652
2653 static inline enum isl_format
2654 anv_get_isl_format(const struct gen_device_info *devinfo, VkFormat vk_format,
2655                    VkImageAspectFlags aspect, VkImageTiling tiling)
2656 {
2657    return anv_get_format_plane(devinfo, vk_format, aspect, tiling).isl_format;
2658 }
2659
2660 static inline struct isl_swizzle
2661 anv_swizzle_for_render(struct isl_swizzle swizzle)
2662 {
2663    /* Sometimes the swizzle will have alpha map to one.  We do this to fake
2664     * RGB as RGBA for texturing
2665     */
2666    assert(swizzle.a == ISL_CHANNEL_SELECT_ONE ||
2667           swizzle.a == ISL_CHANNEL_SELECT_ALPHA);
2668
2669    /* But it doesn't matter what we render to that channel */
2670    swizzle.a = ISL_CHANNEL_SELECT_ALPHA;
2671
2672    return swizzle;
2673 }
2674
2675 void
2676 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm);
2677
2678 /**
2679  * Subsurface of an anv_image.
2680  */
2681 struct anv_surface {
2682    /** Valid only if isl_surf::size_B > 0. */
2683    struct isl_surf isl;
2684
2685    /**
2686     * Offset from VkImage's base address, as bound by vkBindImageMemory().
2687     */
2688    uint32_t offset;
2689 };
2690
2691 struct anv_image {
2692    VkImageType type;
2693    /* The original VkFormat provided by the client.  This may not match any
2694     * of the actual surface formats.
2695     */
2696    VkFormat vk_format;
2697    const struct anv_format *format;
2698
2699    VkImageAspectFlags aspects;
2700    VkExtent3D extent;
2701    uint32_t levels;
2702    uint32_t array_size;
2703    uint32_t samples; /**< VkImageCreateInfo::samples */
2704    uint32_t n_planes;
2705    VkImageUsageFlags usage; /**< Superset of VkImageCreateInfo::usage. */
2706    VkImageTiling tiling; /** VkImageCreateInfo::tiling */
2707
2708    /** True if this is needs to be bound to an appropriately tiled BO.
2709     *
2710     * When not using modifiers, consumers such as X11, Wayland, and KMS need
2711     * the tiling passed via I915_GEM_SET_TILING.  When exporting these buffers
2712     * we require a dedicated allocation so that we can know to allocate a
2713     * tiled buffer.
2714     */
2715    bool needs_set_tiling;
2716
2717    /**
2718     * Must be DRM_FORMAT_MOD_INVALID unless tiling is
2719     * VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT.
2720     */
2721    uint64_t drm_format_mod;
2722
2723    VkDeviceSize size;
2724    uint32_t alignment;
2725
2726    /* Whether the image is made of several underlying buffer objects rather a
2727     * single one with different offsets.
2728     */
2729    bool disjoint;
2730
2731    /**
2732     * Image subsurfaces
2733     *
2734     * For each foo, anv_image::planes[x].surface is valid if and only if
2735     * anv_image::aspects has a x aspect. Refer to anv_image_aspect_to_plane()
2736     * to figure the number associated with a given aspect.
2737     *
2738     * The hardware requires that the depth buffer and stencil buffer be
2739     * separate surfaces.  From Vulkan's perspective, though, depth and stencil
2740     * reside in the same VkImage.  To satisfy both the hardware and Vulkan, we
2741     * allocate the depth and stencil buffers as separate surfaces in the same
2742     * bo.
2743     *
2744     * Memory layout :
2745     *
2746     * -----------------------
2747     * |     surface0        |   /|\
2748     * -----------------------    |
2749     * |   shadow surface0   |    |
2750     * -----------------------    | Plane 0
2751     * |    aux surface0     |    |
2752     * -----------------------    |
2753     * | fast clear colors0  |   \|/
2754     * -----------------------
2755     * |     surface1        |   /|\
2756     * -----------------------    |
2757     * |   shadow surface1   |    |
2758     * -----------------------    | Plane 1
2759     * |    aux surface1     |    |
2760     * -----------------------    |
2761     * | fast clear colors1  |   \|/
2762     * -----------------------
2763     * |        ...          |
2764     * |                     |
2765     * -----------------------
2766     */
2767    struct {
2768       /**
2769        * Offset of the entire plane (whenever the image is disjoint this is
2770        * set to 0).
2771        */
2772       uint32_t offset;
2773
2774       VkDeviceSize size;
2775       uint32_t alignment;
2776
2777       struct anv_surface surface;
2778
2779       /**
2780        * A surface which shadows the main surface and may have different
2781        * tiling. This is used for sampling using a tiling that isn't supported
2782        * for other operations.
2783        */
2784       struct anv_surface shadow_surface;
2785
2786       /**
2787        * For color images, this is the aux usage for this image when not used
2788        * as a color attachment.
2789        *
2790        * For depth/stencil images, this is set to ISL_AUX_USAGE_HIZ if the
2791        * image has a HiZ buffer.
2792        */
2793       enum isl_aux_usage aux_usage;
2794
2795       struct anv_surface aux_surface;
2796
2797       /**
2798        * Offset of the fast clear state (used to compute the
2799        * fast_clear_state_offset of the following planes).
2800        */
2801       uint32_t fast_clear_state_offset;
2802
2803       /**
2804        * BO associated with this plane, set when bound.
2805        */
2806       struct anv_address address;
2807
2808       /**
2809        * When destroying the image, also free the bo.
2810        * */
2811       bool bo_is_owned;
2812    } planes[3];
2813 };
2814
2815 /* The ordering of this enum is important */
2816 enum anv_fast_clear_type {
2817    /** Image does not have/support any fast-clear blocks */
2818    ANV_FAST_CLEAR_NONE = 0,
2819    /** Image has/supports fast-clear but only to the default value */
2820    ANV_FAST_CLEAR_DEFAULT_VALUE = 1,
2821    /** Image has/supports fast-clear with an arbitrary fast-clear value */
2822    ANV_FAST_CLEAR_ANY = 2,
2823 };
2824
2825 /* Returns the number of auxiliary buffer levels attached to an image. */
2826 static inline uint8_t
2827 anv_image_aux_levels(const struct anv_image * const image,
2828                      VkImageAspectFlagBits aspect)
2829 {
2830    uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
2831    return image->planes[plane].aux_surface.isl.size_B > 0 ?
2832           image->planes[plane].aux_surface.isl.levels : 0;
2833 }
2834
2835 /* Returns the number of auxiliary buffer layers attached to an image. */
2836 static inline uint32_t
2837 anv_image_aux_layers(const struct anv_image * const image,
2838                      VkImageAspectFlagBits aspect,
2839                      const uint8_t miplevel)
2840 {
2841    assert(image);
2842
2843    /* The miplevel must exist in the main buffer. */
2844    assert(miplevel < image->levels);
2845
2846    if (miplevel >= anv_image_aux_levels(image, aspect)) {
2847       /* There are no layers with auxiliary data because the miplevel has no
2848        * auxiliary data.
2849        */
2850       return 0;
2851    } else {
2852       uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
2853       return MAX2(image->planes[plane].aux_surface.isl.logical_level0_px.array_len,
2854                   image->planes[plane].aux_surface.isl.logical_level0_px.depth >> miplevel);
2855    }
2856 }
2857
2858 static inline struct anv_address
2859 anv_image_get_clear_color_addr(const struct anv_device *device,
2860                                const struct anv_image *image,
2861                                VkImageAspectFlagBits aspect)
2862 {
2863    assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
2864
2865    uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
2866    return anv_address_add(image->planes[plane].address,
2867                           image->planes[plane].fast_clear_state_offset);
2868 }
2869
2870 static inline struct anv_address
2871 anv_image_get_fast_clear_type_addr(const struct anv_device *device,
2872                                    const struct anv_image *image,
2873                                    VkImageAspectFlagBits aspect)
2874 {
2875    struct anv_address addr =
2876       anv_image_get_clear_color_addr(device, image, aspect);
2877
2878    const unsigned clear_color_state_size = device->info.gen >= 10 ?
2879       device->isl_dev.ss.clear_color_state_size :
2880       device->isl_dev.ss.clear_value_size;
2881    addr.offset += clear_color_state_size;
2882    return addr;
2883 }
2884
2885 static inline struct anv_address
2886 anv_image_get_compression_state_addr(const struct anv_device *device,
2887                                      const struct anv_image *image,
2888                                      VkImageAspectFlagBits aspect,
2889                                      uint32_t level, uint32_t array_layer)
2890 {
2891    assert(level < anv_image_aux_levels(image, aspect));
2892    assert(array_layer < anv_image_aux_layers(image, aspect, level));
2893    UNUSED uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
2894    assert(image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_E);
2895
2896    struct anv_address addr =
2897       anv_image_get_fast_clear_type_addr(device, image, aspect);
2898    addr.offset += 4; /* Go past the fast clear type */
2899
2900    if (image->type == VK_IMAGE_TYPE_3D) {
2901       for (uint32_t l = 0; l < level; l++)
2902          addr.offset += anv_minify(image->extent.depth, l) * 4;
2903    } else {
2904       addr.offset += level * image->array_size * 4;
2905    }
2906    addr.offset += array_layer * 4;
2907
2908    return addr;
2909 }
2910
2911 /* Returns true if a HiZ-enabled depth buffer can be sampled from. */
2912 static inline bool
2913 anv_can_sample_with_hiz(const struct gen_device_info * const devinfo,
2914                         const struct anv_image *image)
2915 {
2916    if (!(image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
2917       return false;
2918
2919    if (devinfo->gen < 8)
2920       return false;
2921
2922    return image->samples == 1;
2923 }
2924
2925 void
2926 anv_cmd_buffer_mark_image_written(struct anv_cmd_buffer *cmd_buffer,
2927                                   const struct anv_image *image,
2928                                   VkImageAspectFlagBits aspect,
2929                                   enum isl_aux_usage aux_usage,
2930                                   uint32_t level,
2931                                   uint32_t base_layer,
2932                                   uint32_t layer_count);
2933
2934 void
2935 anv_image_clear_color(struct anv_cmd_buffer *cmd_buffer,
2936                       const struct anv_image *image,
2937                       VkImageAspectFlagBits aspect,
2938                       enum isl_aux_usage aux_usage,
2939                       enum isl_format format, struct isl_swizzle swizzle,
2940                       uint32_t level, uint32_t base_layer, uint32_t layer_count,
2941                       VkRect2D area, union isl_color_value clear_color);
2942 void
2943 anv_image_clear_depth_stencil(struct anv_cmd_buffer *cmd_buffer,
2944                               const struct anv_image *image,
2945                               VkImageAspectFlags aspects,
2946                               enum isl_aux_usage depth_aux_usage,
2947                               uint32_t level,
2948                               uint32_t base_layer, uint32_t layer_count,
2949                               VkRect2D area,
2950                               float depth_value, uint8_t stencil_value);
2951 void
2952 anv_image_hiz_op(struct anv_cmd_buffer *cmd_buffer,
2953                  const struct anv_image *image,
2954                  VkImageAspectFlagBits aspect, uint32_t level,
2955                  uint32_t base_layer, uint32_t layer_count,
2956                  enum isl_aux_op hiz_op);
2957 void
2958 anv_image_hiz_clear(struct anv_cmd_buffer *cmd_buffer,
2959                     const struct anv_image *image,
2960                     VkImageAspectFlags aspects,
2961                     uint32_t level,
2962                     uint32_t base_layer, uint32_t layer_count,
2963                     VkRect2D area, uint8_t stencil_value);
2964 void
2965 anv_image_mcs_op(struct anv_cmd_buffer *cmd_buffer,
2966                  const struct anv_image *image,
2967                  enum isl_format format,
2968                  VkImageAspectFlagBits aspect,
2969                  uint32_t base_layer, uint32_t layer_count,
2970                  enum isl_aux_op mcs_op, union isl_color_value *clear_value,
2971                  bool predicate);
2972 void
2973 anv_image_ccs_op(struct anv_cmd_buffer *cmd_buffer,
2974                  const struct anv_image *image,
2975                  enum isl_format format,
2976                  VkImageAspectFlagBits aspect, uint32_t level,
2977                  uint32_t base_layer, uint32_t layer_count,
2978                  enum isl_aux_op ccs_op, union isl_color_value *clear_value,
2979                  bool predicate);
2980
2981 void
2982 anv_image_copy_to_shadow(struct anv_cmd_buffer *cmd_buffer,
2983                          const struct anv_image *image,
2984                          uint32_t base_level, uint32_t level_count,
2985                          uint32_t base_layer, uint32_t layer_count);
2986
2987 enum isl_aux_usage
2988 anv_layout_to_aux_usage(const struct gen_device_info * const devinfo,
2989                         const struct anv_image *image,
2990                         const VkImageAspectFlagBits aspect,
2991                         const VkImageLayout layout);
2992
2993 enum anv_fast_clear_type
2994 anv_layout_to_fast_clear_type(const struct gen_device_info * const devinfo,
2995                               const struct anv_image * const image,
2996                               const VkImageAspectFlagBits aspect,
2997                               const VkImageLayout layout);
2998
2999 /* This is defined as a macro so that it works for both
3000  * VkImageSubresourceRange and VkImageSubresourceLayers
3001  */
3002 #define anv_get_layerCount(_image, _range) \
3003    ((_range)->layerCount == VK_REMAINING_ARRAY_LAYERS ? \
3004     (_image)->array_size - (_range)->baseArrayLayer : (_range)->layerCount)
3005
3006 static inline uint32_t
3007 anv_get_levelCount(const struct anv_image *image,
3008                    const VkImageSubresourceRange *range)
3009 {
3010    return range->levelCount == VK_REMAINING_MIP_LEVELS ?
3011           image->levels - range->baseMipLevel : range->levelCount;
3012 }
3013
3014 static inline VkImageAspectFlags
3015 anv_image_expand_aspects(const struct anv_image *image,
3016                          VkImageAspectFlags aspects)
3017 {
3018    /* If the underlying image has color plane aspects and
3019     * VK_IMAGE_ASPECT_COLOR_BIT has been requested, then return the aspects of
3020     * the underlying image. */
3021    if ((image->aspects & VK_IMAGE_ASPECT_PLANES_BITS_ANV) != 0 &&
3022        aspects == VK_IMAGE_ASPECT_COLOR_BIT)
3023       return image->aspects;
3024
3025    return aspects;
3026 }
3027
3028 static inline bool
3029 anv_image_aspects_compatible(VkImageAspectFlags aspects1,
3030                              VkImageAspectFlags aspects2)
3031 {
3032    if (aspects1 == aspects2)
3033       return true;
3034
3035    /* Only 1 color aspects are compatibles. */
3036    if ((aspects1 & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) != 0 &&
3037        (aspects2 & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) != 0 &&
3038        util_bitcount(aspects1) == util_bitcount(aspects2))
3039       return true;
3040
3041    return false;
3042 }
3043
3044 struct anv_image_view {
3045    const struct anv_image *image; /**< VkImageViewCreateInfo::image */
3046
3047    VkImageAspectFlags aspect_mask;
3048    VkFormat vk_format;
3049    VkExtent3D extent; /**< Extent of VkImageViewCreateInfo::baseMipLevel. */
3050
3051    unsigned n_planes;
3052    struct {
3053       uint32_t image_plane;
3054
3055       struct isl_view isl;
3056
3057       /**
3058        * RENDER_SURFACE_STATE when using image as a sampler surface with an
3059        * image layout of SHADER_READ_ONLY_OPTIMAL or
3060        * DEPTH_STENCIL_READ_ONLY_OPTIMAL.
3061        */
3062       struct anv_surface_state optimal_sampler_surface_state;
3063
3064       /**
3065        * RENDER_SURFACE_STATE when using image as a sampler surface with an
3066        * image layout of GENERAL.
3067        */
3068       struct anv_surface_state general_sampler_surface_state;
3069
3070       /**
3071        * RENDER_SURFACE_STATE when using image as a storage image. Separate
3072        * states for write-only and readable, using the real format for
3073        * write-only and the lowered format for readable.
3074        */
3075       struct anv_surface_state storage_surface_state;
3076       struct anv_surface_state writeonly_storage_surface_state;
3077
3078       struct brw_image_param storage_image_param;
3079    } planes[3];
3080 };
3081
3082 enum anv_image_view_state_flags {
3083    ANV_IMAGE_VIEW_STATE_STORAGE_WRITE_ONLY   = (1 << 0),
3084    ANV_IMAGE_VIEW_STATE_TEXTURE_OPTIMAL      = (1 << 1),
3085 };
3086
3087 void anv_image_fill_surface_state(struct anv_device *device,
3088                                   const struct anv_image *image,
3089                                   VkImageAspectFlagBits aspect,
3090                                   const struct isl_view *view,
3091                                   isl_surf_usage_flags_t view_usage,
3092                                   enum isl_aux_usage aux_usage,
3093                                   const union isl_color_value *clear_color,
3094                                   enum anv_image_view_state_flags flags,
3095                                   struct anv_surface_state *state_inout,
3096                                   struct brw_image_param *image_param_out);
3097
3098 struct anv_image_create_info {
3099    const VkImageCreateInfo *vk_info;
3100
3101    /** An opt-in bitmask which filters an ISL-mapping of the Vulkan tiling. */
3102    isl_tiling_flags_t isl_tiling_flags;
3103
3104    /** These flags will be added to any derived from VkImageCreateInfo. */
3105    isl_surf_usage_flags_t isl_extra_usage_flags;
3106
3107    uint32_t stride;
3108 };
3109
3110 VkResult anv_image_create(VkDevice _device,
3111                           const struct anv_image_create_info *info,
3112                           const VkAllocationCallbacks* alloc,
3113                           VkImage *pImage);
3114
3115 #ifdef ANDROID
3116 VkResult anv_image_from_gralloc(VkDevice device_h,
3117                                 const VkImageCreateInfo *base_info,
3118                                 const VkNativeBufferANDROID *gralloc_info,
3119                                 const VkAllocationCallbacks *alloc,
3120                                 VkImage *pImage);
3121 #endif
3122
3123 const struct anv_surface *
3124 anv_image_get_surface_for_aspect_mask(const struct anv_image *image,
3125                                       VkImageAspectFlags aspect_mask);
3126
3127 enum isl_format
3128 anv_isl_format_for_descriptor_type(VkDescriptorType type);
3129
3130 static inline struct VkExtent3D
3131 anv_sanitize_image_extent(const VkImageType imageType,
3132                           const struct VkExtent3D imageExtent)
3133 {
3134    switch (imageType) {
3135    case VK_IMAGE_TYPE_1D:
3136       return (VkExtent3D) { imageExtent.width, 1, 1 };
3137    case VK_IMAGE_TYPE_2D:
3138       return (VkExtent3D) { imageExtent.width, imageExtent.height, 1 };
3139    case VK_IMAGE_TYPE_3D:
3140       return imageExtent;
3141    default:
3142       unreachable("invalid image type");
3143    }
3144 }
3145
3146 static inline struct VkOffset3D
3147 anv_sanitize_image_offset(const VkImageType imageType,
3148                           const struct VkOffset3D imageOffset)
3149 {
3150    switch (imageType) {
3151    case VK_IMAGE_TYPE_1D:
3152       return (VkOffset3D) { imageOffset.x, 0, 0 };
3153    case VK_IMAGE_TYPE_2D:
3154       return (VkOffset3D) { imageOffset.x, imageOffset.y, 0 };
3155    case VK_IMAGE_TYPE_3D:
3156       return imageOffset;
3157    default:
3158       unreachable("invalid image type");
3159    }
3160 }
3161
3162
3163 void anv_fill_buffer_surface_state(struct anv_device *device,
3164                                    struct anv_state state,
3165                                    enum isl_format format,
3166                                    struct anv_address address,
3167                                    uint32_t range, uint32_t stride);
3168
3169 static inline void
3170 anv_clear_color_from_att_state(union isl_color_value *clear_color,
3171                                const struct anv_attachment_state *att_state,
3172                                const struct anv_image_view *iview)
3173 {
3174    const struct isl_format_layout *view_fmtl =
3175       isl_format_get_layout(iview->planes[0].isl.format);
3176
3177 #define COPY_CLEAR_COLOR_CHANNEL(c, i) \
3178    if (view_fmtl->channels.c.bits) \
3179       clear_color->u32[i] = att_state->clear_value.color.uint32[i]
3180
3181    COPY_CLEAR_COLOR_CHANNEL(r, 0);
3182    COPY_CLEAR_COLOR_CHANNEL(g, 1);
3183    COPY_CLEAR_COLOR_CHANNEL(b, 2);
3184    COPY_CLEAR_COLOR_CHANNEL(a, 3);
3185
3186 #undef COPY_CLEAR_COLOR_CHANNEL
3187 }
3188
3189
3190 struct anv_ycbcr_conversion {
3191    const struct anv_format *        format;
3192    VkSamplerYcbcrModelConversion    ycbcr_model;
3193    VkSamplerYcbcrRange              ycbcr_range;
3194    VkComponentSwizzle               mapping[4];
3195    VkChromaLocation                 chroma_offsets[2];
3196    VkFilter                         chroma_filter;
3197    bool                             chroma_reconstruction;
3198 };
3199
3200 struct anv_sampler {
3201    uint32_t                     state[3][4];
3202    uint32_t                     n_planes;
3203    struct anv_ycbcr_conversion *conversion;
3204 };
3205
3206 struct anv_framebuffer {
3207    uint32_t                                     width;
3208    uint32_t                                     height;
3209    uint32_t                                     layers;
3210
3211    uint32_t                                     attachment_count;
3212    struct anv_image_view *                      attachments[0];
3213 };
3214
3215 struct anv_subpass_attachment {
3216    VkImageUsageFlagBits usage;
3217    uint32_t attachment;
3218    VkImageLayout layout;
3219 };
3220
3221 struct anv_subpass {
3222    uint32_t                                     attachment_count;
3223
3224    /**
3225     * A pointer to all attachment references used in this subpass.
3226     * Only valid if ::attachment_count > 0.
3227     */
3228    struct anv_subpass_attachment *              attachments;
3229    uint32_t                                     input_count;
3230    struct anv_subpass_attachment *              input_attachments;
3231    uint32_t                                     color_count;
3232    struct anv_subpass_attachment *              color_attachments;
3233    struct anv_subpass_attachment *              resolve_attachments;
3234
3235    struct anv_subpass_attachment *              depth_stencil_attachment;
3236
3237    uint32_t                                     view_mask;
3238
3239    /** Subpass has a depth/stencil self-dependency */
3240    bool                                         has_ds_self_dep;
3241
3242    /** Subpass has at least one resolve attachment */
3243    bool                                         has_resolve;
3244 };
3245
3246 static inline unsigned
3247 anv_subpass_view_count(const struct anv_subpass *subpass)
3248 {
3249    return MAX2(1, util_bitcount(subpass->view_mask));
3250 }
3251
3252 struct anv_render_pass_attachment {
3253    /* TODO: Consider using VkAttachmentDescription instead of storing each of
3254     * its members individually.
3255     */
3256    VkFormat                                     format;
3257    uint32_t                                     samples;
3258    VkImageUsageFlags                            usage;
3259    VkAttachmentLoadOp                           load_op;
3260    VkAttachmentStoreOp                          store_op;
3261    VkAttachmentLoadOp                           stencil_load_op;
3262    VkImageLayout                                initial_layout;
3263    VkImageLayout                                final_layout;
3264    VkImageLayout                                first_subpass_layout;
3265
3266    /* The subpass id in which the attachment will be used last. */
3267    uint32_t                                     last_subpass_idx;
3268 };
3269
3270 struct anv_render_pass {
3271    uint32_t                                     attachment_count;
3272    uint32_t                                     subpass_count;
3273    /* An array of subpass_count+1 flushes, one per subpass boundary */
3274    enum anv_pipe_bits *                         subpass_flushes;
3275    struct anv_render_pass_attachment *          attachments;
3276    struct anv_subpass                           subpasses[0];
3277 };
3278
3279 #define ANV_PIPELINE_STATISTICS_MASK 0x000007ff
3280
3281 struct anv_query_pool {
3282    VkQueryType                                  type;
3283    VkQueryPipelineStatisticFlags                pipeline_statistics;
3284    /** Stride between slots, in bytes */
3285    uint32_t                                     stride;
3286    /** Number of slots in this query pool */
3287    uint32_t                                     slots;
3288    struct anv_bo                                bo;
3289 };
3290
3291 int anv_get_instance_entrypoint_index(const char *name);
3292 int anv_get_device_entrypoint_index(const char *name);
3293
3294 bool
3295 anv_instance_entrypoint_is_enabled(int index, uint32_t core_version,
3296                                    const struct anv_instance_extension_table *instance);
3297
3298 bool
3299 anv_device_entrypoint_is_enabled(int index, uint32_t core_version,
3300                                  const struct anv_instance_extension_table *instance,
3301                                  const struct anv_device_extension_table *device);
3302
3303 void *anv_lookup_entrypoint(const struct gen_device_info *devinfo,
3304                             const char *name);
3305
3306 void anv_dump_image_to_ppm(struct anv_device *device,
3307                            struct anv_image *image, unsigned miplevel,
3308                            unsigned array_layer, VkImageAspectFlagBits aspect,
3309                            const char *filename);
3310
3311 enum anv_dump_action {
3312    ANV_DUMP_FRAMEBUFFERS_BIT = 0x1,
3313 };
3314
3315 void anv_dump_start(struct anv_device *device, enum anv_dump_action actions);
3316 void anv_dump_finish(void);
3317
3318 void anv_dump_add_framebuffer(struct anv_cmd_buffer *cmd_buffer,
3319                               struct anv_framebuffer *fb);
3320
3321 static inline uint32_t
3322 anv_get_subpass_id(const struct anv_cmd_state * const cmd_state)
3323 {
3324    /* This function must be called from within a subpass. */
3325    assert(cmd_state->pass && cmd_state->subpass);
3326
3327    const uint32_t subpass_id = cmd_state->subpass - cmd_state->pass->subpasses;
3328
3329    /* The id of this subpass shouldn't exceed the number of subpasses in this
3330     * render pass minus 1.
3331     */
3332    assert(subpass_id < cmd_state->pass->subpass_count);
3333    return subpass_id;
3334 }
3335
3336 #define ANV_DEFINE_HANDLE_CASTS(__anv_type, __VkType)                      \
3337                                                                            \
3338    static inline struct __anv_type *                                       \
3339    __anv_type ## _from_handle(__VkType _handle)                            \
3340    {                                                                       \
3341       return (struct __anv_type *) _handle;                                \
3342    }                                                                       \
3343                                                                            \
3344    static inline __VkType                                                  \
3345    __anv_type ## _to_handle(struct __anv_type *_obj)                       \
3346    {                                                                       \
3347       return (__VkType) _obj;                                              \
3348    }
3349
3350 #define ANV_DEFINE_NONDISP_HANDLE_CASTS(__anv_type, __VkType)              \
3351                                                                            \
3352    static inline struct __anv_type *                                       \
3353    __anv_type ## _from_handle(__VkType _handle)                            \
3354    {                                                                       \
3355       return (struct __anv_type *)(uintptr_t) _handle;                     \
3356    }                                                                       \
3357                                                                            \
3358    static inline __VkType                                                  \
3359    __anv_type ## _to_handle(struct __anv_type *_obj)                       \
3360    {                                                                       \
3361       return (__VkType)(uintptr_t) _obj;                                   \
3362    }
3363
3364 #define ANV_FROM_HANDLE(__anv_type, __name, __handle) \
3365    struct __anv_type *__name = __anv_type ## _from_handle(__handle)
3366
3367 ANV_DEFINE_HANDLE_CASTS(anv_cmd_buffer, VkCommandBuffer)
3368 ANV_DEFINE_HANDLE_CASTS(anv_device, VkDevice)
3369 ANV_DEFINE_HANDLE_CASTS(anv_instance, VkInstance)
3370 ANV_DEFINE_HANDLE_CASTS(anv_physical_device, VkPhysicalDevice)
3371 ANV_DEFINE_HANDLE_CASTS(anv_queue, VkQueue)
3372
3373 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_cmd_pool, VkCommandPool)
3374 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer, VkBuffer)
3375 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer_view, VkBufferView)
3376 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_pool, VkDescriptorPool)
3377 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set, VkDescriptorSet)
3378 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set_layout, VkDescriptorSetLayout)
3379 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_update_template, VkDescriptorUpdateTemplateKHR)
3380 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_device_memory, VkDeviceMemory)
3381 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_fence, VkFence)
3382 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_event, VkEvent)
3383 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_framebuffer, VkFramebuffer)
3384 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_image, VkImage)
3385 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_image_view, VkImageView);
3386 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline_cache, VkPipelineCache)
3387 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline, VkPipeline)
3388 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline_layout, VkPipelineLayout)
3389 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_query_pool, VkQueryPool)
3390 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_render_pass, VkRenderPass)
3391 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_sampler, VkSampler)
3392 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_semaphore, VkSemaphore)
3393 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_shader_module, VkShaderModule)
3394 ANV_DEFINE_NONDISP_HANDLE_CASTS(vk_debug_report_callback, VkDebugReportCallbackEXT)
3395 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_ycbcr_conversion, VkSamplerYcbcrConversion)
3396
3397 /* Gen-specific function declarations */
3398 #ifdef genX
3399 #  include "anv_genX.h"
3400 #else
3401 #  define genX(x) gen7_##x
3402 #  include "anv_genX.h"
3403 #  undef genX
3404 #  define genX(x) gen75_##x
3405 #  include "anv_genX.h"
3406 #  undef genX
3407 #  define genX(x) gen8_##x
3408 #  include "anv_genX.h"
3409 #  undef genX
3410 #  define genX(x) gen9_##x
3411 #  include "anv_genX.h"
3412 #  undef genX
3413 #  define genX(x) gen10_##x
3414 #  include "anv_genX.h"
3415 #  undef genX
3416 #  define genX(x) gen11_##x
3417 #  include "anv_genX.h"
3418 #  undef genX
3419 #endif
3420
3421 #endif /* ANV_PRIVATE_H */