OSDN Git Service

anv: drop pointless struct decl.
[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 #define __gen_validate_value(x) VALGRIND_CHECK_MEM_IS_DEFINED(&(x), sizeof(x))
40 #else
41 #define VG(x)
42 #endif
43
44 #include "common/gen_device_info.h"
45 #include "blorp/blorp.h"
46 #include "brw_compiler.h"
47 #include "util/macros.h"
48 #include "util/list.h"
49 #include "util/u_vector.h"
50 #include "util/vk_alloc.h"
51
52 /* Pre-declarations needed for WSI entrypoints */
53 struct wl_surface;
54 struct wl_display;
55 typedef struct xcb_connection_t xcb_connection_t;
56 typedef uint32_t xcb_visualid_t;
57 typedef uint32_t xcb_window_t;
58
59 struct gen_l3_config;
60
61 #include <vulkan/vulkan.h>
62 #include <vulkan/vulkan_intel.h>
63 #include <vulkan/vk_icd.h>
64
65 #include "anv_entrypoints.h"
66 #include "brw_context.h"
67 #include "isl/isl.h"
68
69 #ifdef __cplusplus
70 extern "C" {
71 #endif
72
73 #define MAX_VBS         32
74 #define MAX_SETS         8
75 #define MAX_RTS          8
76 #define MAX_VIEWPORTS   16
77 #define MAX_SCISSORS    16
78 #define MAX_PUSH_CONSTANTS_SIZE 128
79 #define MAX_DYNAMIC_BUFFERS 16
80 #define MAX_IMAGES 8
81 #define MAX_SAMPLES_LOG2 4 /* SKL supports 16 samples */
82
83 #define anv_noreturn __attribute__((__noreturn__))
84 #define anv_printflike(a, b) __attribute__((__format__(__printf__, a, b)))
85
86 static inline uint32_t
87 align_down_npot_u32(uint32_t v, uint32_t a)
88 {
89    return v - (v % a);
90 }
91
92 static inline uint32_t
93 align_u32(uint32_t v, uint32_t a)
94 {
95    assert(a != 0 && a == (a & -a));
96    return (v + a - 1) & ~(a - 1);
97 }
98
99 static inline uint64_t
100 align_u64(uint64_t v, uint64_t a)
101 {
102    assert(a != 0 && a == (a & -a));
103    return (v + a - 1) & ~(a - 1);
104 }
105
106 static inline int32_t
107 align_i32(int32_t v, int32_t a)
108 {
109    assert(a != 0 && a == (a & -a));
110    return (v + a - 1) & ~(a - 1);
111 }
112
113 /** Alignment must be a power of 2. */
114 static inline bool
115 anv_is_aligned(uintmax_t n, uintmax_t a)
116 {
117    assert(a == (a & -a));
118    return (n & (a - 1)) == 0;
119 }
120
121 static inline uint32_t
122 anv_minify(uint32_t n, uint32_t levels)
123 {
124    if (unlikely(n == 0))
125       return 0;
126    else
127       return MAX2(n >> levels, 1);
128 }
129
130 static inline float
131 anv_clamp_f(float f, float min, float max)
132 {
133    assert(min < max);
134
135    if (f > max)
136       return max;
137    else if (f < min)
138       return min;
139    else
140       return f;
141 }
142
143 static inline bool
144 anv_clear_mask(uint32_t *inout_mask, uint32_t clear_mask)
145 {
146    if (*inout_mask & clear_mask) {
147       *inout_mask &= ~clear_mask;
148       return true;
149    } else {
150       return false;
151    }
152 }
153
154 #define for_each_bit(b, dword)                          \
155    for (uint32_t __dword = (dword);                     \
156         (b) = __builtin_ffs(__dword) - 1, __dword;      \
157         __dword &= ~(1 << (b)))
158
159 #define typed_memcpy(dest, src, count) ({ \
160    static_assert(sizeof(*src) == sizeof(*dest), ""); \
161    memcpy((dest), (src), (count) * sizeof(*(src))); \
162 })
163
164 #define zero(x) (memset(&(x), 0, sizeof(x)))
165
166 /* Define no kernel as 1, since that's an illegal offset for a kernel */
167 #define NO_KERNEL 1
168
169 struct anv_common {
170     VkStructureType                             sType;
171     const void*                                 pNext;
172 };
173
174 /* Whenever we generate an error, pass it through this function. Useful for
175  * debugging, where we can break on it. Only call at error site, not when
176  * propagating errors. Might be useful to plug in a stack trace here.
177  */
178
179 VkResult __vk_errorf(VkResult error, const char *file, int line, const char *format, ...);
180
181 #ifdef DEBUG
182 #define vk_error(error) __vk_errorf(error, __FILE__, __LINE__, NULL);
183 #define vk_errorf(error, format, ...) __vk_errorf(error, __FILE__, __LINE__, format, ## __VA_ARGS__);
184 #else
185 #define vk_error(error) error
186 #define vk_errorf(error, format, ...) error
187 #endif
188
189 void __anv_finishme(const char *file, int line, const char *format, ...)
190    anv_printflike(3, 4);
191 void anv_loge(const char *format, ...) anv_printflike(1, 2);
192 void anv_loge_v(const char *format, va_list va);
193
194 /**
195  * Print a FINISHME message, including its source location.
196  */
197 #define anv_finishme(format, ...) \
198    __anv_finishme(__FILE__, __LINE__, format, ##__VA_ARGS__);
199
200 /* A non-fatal assert.  Useful for debugging. */
201 #ifdef DEBUG
202 #define anv_assert(x) ({ \
203    if (unlikely(!(x))) \
204       fprintf(stderr, "%s:%d ASSERT: %s\n", __FILE__, __LINE__, #x); \
205 })
206 #else
207 #define anv_assert(x)
208 #endif
209
210 /**
211  * If a block of code is annotated with anv_validate, then the block runs only
212  * in debug builds.
213  */
214 #ifdef DEBUG
215 #define anv_validate if (1)
216 #else
217 #define anv_validate if (0)
218 #endif
219
220 void anv_abortf(const char *format, ...) anv_noreturn anv_printflike(1, 2);
221 void anv_abortfv(const char *format, va_list va) anv_noreturn;
222
223 #define stub_return(v) \
224    do { \
225       anv_finishme("stub %s", __func__); \
226       return (v); \
227    } while (0)
228
229 #define stub() \
230    do { \
231       anv_finishme("stub %s", __func__); \
232       return; \
233    } while (0)
234
235 /**
236  * A dynamically growable, circular buffer.  Elements are added at head and
237  * removed from tail. head and tail are free-running uint32_t indices and we
238  * only compute the modulo with size when accessing the array.  This way,
239  * number of bytes in the queue is always head - tail, even in case of
240  * wraparound.
241  */
242
243 struct anv_bo {
244    uint32_t gem_handle;
245
246    /* Index into the current validation list.  This is used by the
247     * validation list building alrogithm to track which buffers are already
248     * in the validation list so that we can ensure uniqueness.
249     */
250    uint32_t index;
251
252    /* Last known offset.  This value is provided by the kernel when we
253     * execbuf and is used as the presumed offset for the next bunch of
254     * relocations.
255     */
256    uint64_t offset;
257
258    uint64_t size;
259    void *map;
260
261    /* We need to set the WRITE flag on winsys bos so GEM will know we're
262     * writing to them and synchronize uses on other rings (eg if the display
263     * server uses the blitter ring).
264     */
265    bool is_winsys_bo;
266 };
267
268 /* Represents a lock-free linked list of "free" things.  This is used by
269  * both the block pool and the state pools.  Unfortunately, in order to
270  * solve the ABA problem, we can't use a single uint32_t head.
271  */
272 union anv_free_list {
273    struct {
274       int32_t offset;
275
276       /* A simple count that is incremented every time the head changes. */
277       uint32_t count;
278    };
279    uint64_t u64;
280 };
281
282 #define ANV_FREE_LIST_EMPTY ((union anv_free_list) { { 1, 0 } })
283
284 struct anv_block_state {
285    union {
286       struct {
287          uint32_t next;
288          uint32_t end;
289       };
290       uint64_t u64;
291    };
292 };
293
294 struct anv_block_pool {
295    struct anv_device *device;
296
297    struct anv_bo bo;
298
299    /* The offset from the start of the bo to the "center" of the block
300     * pool.  Pointers to allocated blocks are given by
301     * bo.map + center_bo_offset + offsets.
302     */
303    uint32_t center_bo_offset;
304
305    /* Current memory map of the block pool.  This pointer may or may not
306     * point to the actual beginning of the block pool memory.  If
307     * anv_block_pool_alloc_back has ever been called, then this pointer
308     * will point to the "center" position of the buffer and all offsets
309     * (negative or positive) given out by the block pool alloc functions
310     * will be valid relative to this pointer.
311     *
312     * In particular, map == bo.map + center_offset
313     */
314    void *map;
315    int fd;
316
317    /**
318     * Array of mmaps and gem handles owned by the block pool, reclaimed when
319     * the block pool is destroyed.
320     */
321    struct u_vector mmap_cleanups;
322
323    uint32_t block_size;
324
325    union anv_free_list free_list;
326    struct anv_block_state state;
327
328    union anv_free_list back_free_list;
329    struct anv_block_state back_state;
330 };
331
332 /* Block pools are backed by a fixed-size 2GB memfd */
333 #define BLOCK_POOL_MEMFD_SIZE (1ull << 32)
334
335 /* The center of the block pool is also the middle of the memfd.  This may
336  * change in the future if we decide differently for some reason.
337  */
338 #define BLOCK_POOL_MEMFD_CENTER (BLOCK_POOL_MEMFD_SIZE / 2)
339
340 static inline uint32_t
341 anv_block_pool_size(struct anv_block_pool *pool)
342 {
343    return pool->state.end + pool->back_state.end;
344 }
345
346 struct anv_state {
347    int32_t offset;
348    uint32_t alloc_size;
349    void *map;
350 };
351
352 struct anv_fixed_size_state_pool {
353    size_t state_size;
354    union anv_free_list free_list;
355    struct anv_block_state block;
356 };
357
358 #define ANV_MIN_STATE_SIZE_LOG2 6
359 #define ANV_MAX_STATE_SIZE_LOG2 17
360
361 #define ANV_STATE_BUCKETS (ANV_MAX_STATE_SIZE_LOG2 - ANV_MIN_STATE_SIZE_LOG2 + 1)
362
363 struct anv_state_pool {
364    struct anv_block_pool *block_pool;
365    struct anv_fixed_size_state_pool buckets[ANV_STATE_BUCKETS];
366 };
367
368 struct anv_state_stream_block;
369
370 struct anv_state_stream {
371    struct anv_block_pool *block_pool;
372
373    /* The current working block */
374    struct anv_state_stream_block *block;
375
376    /* Offset at which the current block starts */
377    uint32_t start;
378    /* Offset at which to allocate the next state */
379    uint32_t next;
380    /* Offset at which the current block ends */
381    uint32_t end;
382 };
383
384 #define CACHELINE_SIZE 64
385 #define CACHELINE_MASK 63
386
387 static inline void
388 anv_clflush_range(void *start, size_t size)
389 {
390    void *p = (void *) (((uintptr_t) start) & ~CACHELINE_MASK);
391    void *end = start + size;
392
393    __builtin_ia32_mfence();
394    while (p < end) {
395       __builtin_ia32_clflush(p);
396       p += CACHELINE_SIZE;
397    }
398 }
399
400 static void inline
401 anv_state_clflush(struct anv_state state)
402 {
403    anv_clflush_range(state.map, state.alloc_size);
404 }
405
406 void anv_block_pool_init(struct anv_block_pool *pool,
407                          struct anv_device *device, uint32_t block_size);
408 void anv_block_pool_finish(struct anv_block_pool *pool);
409 int32_t anv_block_pool_alloc(struct anv_block_pool *pool);
410 int32_t anv_block_pool_alloc_back(struct anv_block_pool *pool);
411 void anv_block_pool_free(struct anv_block_pool *pool, int32_t offset);
412 void anv_state_pool_init(struct anv_state_pool *pool,
413                          struct anv_block_pool *block_pool);
414 void anv_state_pool_finish(struct anv_state_pool *pool);
415 struct anv_state anv_state_pool_alloc(struct anv_state_pool *pool,
416                                       size_t state_size, size_t alignment);
417 void anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state);
418 void anv_state_stream_init(struct anv_state_stream *stream,
419                            struct anv_block_pool *block_pool);
420 void anv_state_stream_finish(struct anv_state_stream *stream);
421 struct anv_state anv_state_stream_alloc(struct anv_state_stream *stream,
422                                         uint32_t size, uint32_t alignment);
423
424 /**
425  * Implements a pool of re-usable BOs.  The interface is identical to that
426  * of block_pool except that each block is its own BO.
427  */
428 struct anv_bo_pool {
429    struct anv_device *device;
430
431    void *free_list[16];
432 };
433
434 void anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device);
435 void anv_bo_pool_finish(struct anv_bo_pool *pool);
436 VkResult anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo,
437                            uint32_t size);
438 void anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo);
439
440 struct anv_scratch_pool {
441    /* Indexed by Per-Thread Scratch Space number (the hardware value) and stage */
442    struct anv_bo bos[16][MESA_SHADER_STAGES];
443 };
444
445 void anv_scratch_pool_init(struct anv_device *device,
446                            struct anv_scratch_pool *pool);
447 void anv_scratch_pool_finish(struct anv_device *device,
448                              struct anv_scratch_pool *pool);
449 struct anv_bo *anv_scratch_pool_alloc(struct anv_device *device,
450                                       struct anv_scratch_pool *pool,
451                                       gl_shader_stage stage,
452                                       unsigned per_thread_scratch);
453
454 extern struct anv_dispatch_table dtable;
455
456 #define VK_ICD_WSI_PLATFORM_MAX 5
457
458 struct anv_physical_device {
459     VK_LOADER_DATA                              _loader_data;
460
461     struct anv_instance *                       instance;
462     uint32_t                                    chipset_id;
463     char                                        path[20];
464     const char *                                name;
465     struct gen_device_info                      info;
466     uint64_t                                    aperture_size;
467     struct brw_compiler *                       compiler;
468     struct isl_device                           isl_dev;
469     int                                         cmd_parser_version;
470
471     uint32_t                                    eu_total;
472     uint32_t                                    subslice_total;
473
474     struct anv_wsi_interface *                  wsi[VK_ICD_WSI_PLATFORM_MAX];
475 };
476
477 struct anv_instance {
478     VK_LOADER_DATA                              _loader_data;
479
480     VkAllocationCallbacks                       alloc;
481
482     uint32_t                                    apiVersion;
483     int                                         physicalDeviceCount;
484     struct anv_physical_device                  physicalDevice;
485 };
486
487 VkResult anv_init_wsi(struct anv_physical_device *physical_device);
488 void anv_finish_wsi(struct anv_physical_device *physical_device);
489
490 struct anv_queue {
491     VK_LOADER_DATA                              _loader_data;
492
493     struct anv_device *                         device;
494
495     struct anv_state_pool *                     pool;
496 };
497
498 struct anv_pipeline_cache {
499    struct anv_device *                          device;
500    pthread_mutex_t                              mutex;
501
502    struct hash_table *                          cache;
503 };
504
505 struct anv_pipeline_bind_map;
506
507 void anv_pipeline_cache_init(struct anv_pipeline_cache *cache,
508                              struct anv_device *device,
509                              bool cache_enabled);
510 void anv_pipeline_cache_finish(struct anv_pipeline_cache *cache);
511
512 struct anv_shader_bin *
513 anv_pipeline_cache_search(struct anv_pipeline_cache *cache,
514                           const void *key, uint32_t key_size);
515 struct anv_shader_bin *
516 anv_pipeline_cache_upload_kernel(struct anv_pipeline_cache *cache,
517                                  const void *key_data, uint32_t key_size,
518                                  const void *kernel_data, uint32_t kernel_size,
519                                  const void *prog_data, uint32_t prog_data_size,
520                                  const struct anv_pipeline_bind_map *bind_map);
521
522 struct anv_device {
523     VK_LOADER_DATA                              _loader_data;
524
525     VkAllocationCallbacks                       alloc;
526
527     struct anv_instance *                       instance;
528     uint32_t                                    chipset_id;
529     struct gen_device_info                      info;
530     struct isl_device                           isl_dev;
531     int                                         context_id;
532     int                                         fd;
533     bool                                        can_chain_batches;
534     bool                                        robust_buffer_access;
535
536     struct anv_bo_pool                          batch_bo_pool;
537
538     struct anv_block_pool                       dynamic_state_block_pool;
539     struct anv_state_pool                       dynamic_state_pool;
540
541     struct anv_block_pool                       instruction_block_pool;
542     struct anv_state_pool                       instruction_state_pool;
543
544     struct anv_block_pool                       surface_state_block_pool;
545     struct anv_state_pool                       surface_state_pool;
546
547     struct anv_bo                               workaround_bo;
548
549     struct anv_pipeline_cache                   blorp_shader_cache;
550     struct blorp_context                        blorp;
551
552     struct anv_state                            border_colors;
553
554     struct anv_queue                            queue;
555
556     struct anv_scratch_pool                     scratch_pool;
557
558     uint32_t                                    default_mocs;
559
560     pthread_mutex_t                             mutex;
561 };
562
563 void anv_device_get_cache_uuid(void *uuid);
564
565 void anv_device_init_blorp(struct anv_device *device);
566 void anv_device_finish_blorp(struct anv_device *device);
567
568 void* anv_gem_mmap(struct anv_device *device,
569                    uint32_t gem_handle, uint64_t offset, uint64_t size, uint32_t flags);
570 void anv_gem_munmap(void *p, uint64_t size);
571 uint32_t anv_gem_create(struct anv_device *device, size_t size);
572 void anv_gem_close(struct anv_device *device, uint32_t gem_handle);
573 uint32_t anv_gem_userptr(struct anv_device *device, void *mem, size_t size);
574 int anv_gem_wait(struct anv_device *device, uint32_t gem_handle, int64_t *timeout_ns);
575 int anv_gem_execbuffer(struct anv_device *device,
576                        struct drm_i915_gem_execbuffer2 *execbuf);
577 int anv_gem_set_tiling(struct anv_device *device, uint32_t gem_handle,
578                        uint32_t stride, uint32_t tiling);
579 int anv_gem_create_context(struct anv_device *device);
580 int anv_gem_destroy_context(struct anv_device *device, int context);
581 int anv_gem_get_param(int fd, uint32_t param);
582 bool anv_gem_get_bit6_swizzle(int fd, uint32_t tiling);
583 int anv_gem_get_aperture(int fd, uint64_t *size);
584 int anv_gem_handle_to_fd(struct anv_device *device, uint32_t gem_handle);
585 uint32_t anv_gem_fd_to_handle(struct anv_device *device, int fd);
586 int anv_gem_set_caching(struct anv_device *device, uint32_t gem_handle, uint32_t caching);
587 int anv_gem_set_domain(struct anv_device *device, uint32_t gem_handle,
588                        uint32_t read_domains, uint32_t write_domain);
589
590 VkResult anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size);
591
592 struct anv_reloc_list {
593    size_t                                       num_relocs;
594    size_t                                       array_length;
595    struct drm_i915_gem_relocation_entry *       relocs;
596    struct anv_bo **                             reloc_bos;
597 };
598
599 VkResult anv_reloc_list_init(struct anv_reloc_list *list,
600                              const VkAllocationCallbacks *alloc);
601 void anv_reloc_list_finish(struct anv_reloc_list *list,
602                            const VkAllocationCallbacks *alloc);
603
604 uint64_t anv_reloc_list_add(struct anv_reloc_list *list,
605                             const VkAllocationCallbacks *alloc,
606                             uint32_t offset, struct anv_bo *target_bo,
607                             uint32_t delta);
608
609 struct anv_batch_bo {
610    /* Link in the anv_cmd_buffer.owned_batch_bos list */
611    struct list_head                             link;
612
613    struct anv_bo                                bo;
614
615    /* Bytes actually consumed in this batch BO */
616    size_t                                       length;
617
618    /* Last seen surface state block pool bo offset */
619    uint32_t                                     last_ss_pool_bo_offset;
620
621    struct anv_reloc_list                        relocs;
622 };
623
624 struct anv_batch {
625    const VkAllocationCallbacks *                alloc;
626
627    void *                                       start;
628    void *                                       end;
629    void *                                       next;
630
631    struct anv_reloc_list *                      relocs;
632
633    /* This callback is called (with the associated user data) in the event
634     * that the batch runs out of space.
635     */
636    VkResult (*extend_cb)(struct anv_batch *, void *);
637    void *                                       user_data;
638 };
639
640 void *anv_batch_emit_dwords(struct anv_batch *batch, int num_dwords);
641 void anv_batch_emit_batch(struct anv_batch *batch, struct anv_batch *other);
642 uint64_t anv_batch_emit_reloc(struct anv_batch *batch,
643                               void *location, struct anv_bo *bo, uint32_t offset);
644 VkResult anv_device_submit_simple_batch(struct anv_device *device,
645                                         struct anv_batch *batch);
646
647 struct anv_address {
648    struct anv_bo *bo;
649    uint32_t offset;
650 };
651
652 static inline uint64_t
653 _anv_combine_address(struct anv_batch *batch, void *location,
654                      const struct anv_address address, uint32_t delta)
655 {
656    if (address.bo == NULL) {
657       return address.offset + delta;
658    } else {
659       assert(batch->start <= location && location < batch->end);
660
661       return anv_batch_emit_reloc(batch, location, address.bo, address.offset + delta);
662    }
663 }
664
665 #define __gen_address_type struct anv_address
666 #define __gen_user_data struct anv_batch
667 #define __gen_combine_address _anv_combine_address
668
669 /* Wrapper macros needed to work around preprocessor argument issues.  In
670  * particular, arguments don't get pre-evaluated if they are concatenated.
671  * This means that, if you pass GENX(3DSTATE_PS) into the emit macro, the
672  * GENX macro won't get evaluated if the emit macro contains "cmd ## foo".
673  * We can work around this easily enough with these helpers.
674  */
675 #define __anv_cmd_length(cmd) cmd ## _length
676 #define __anv_cmd_length_bias(cmd) cmd ## _length_bias
677 #define __anv_cmd_header(cmd) cmd ## _header
678 #define __anv_cmd_pack(cmd) cmd ## _pack
679 #define __anv_reg_num(reg) reg ## _num
680
681 #define anv_pack_struct(dst, struc, ...) do {                              \
682       struct struc __template = {                                          \
683          __VA_ARGS__                                                       \
684       };                                                                   \
685       __anv_cmd_pack(struc)(NULL, dst, &__template);                       \
686       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dst, __anv_cmd_length(struc) * 4)); \
687    } while (0)
688
689 #define anv_batch_emitn(batch, n, cmd, ...) ({          \
690       void *__dst = anv_batch_emit_dwords(batch, n);    \
691       struct cmd __template = {                         \
692          __anv_cmd_header(cmd),                         \
693         .DWordLength = n - __anv_cmd_length_bias(cmd),  \
694          __VA_ARGS__                                    \
695       };                                                \
696       __anv_cmd_pack(cmd)(batch, __dst, &__template);   \
697       __dst;                                            \
698    })
699
700 #define anv_batch_emit_merge(batch, dwords0, dwords1)                   \
701    do {                                                                 \
702       uint32_t *dw;                                                     \
703                                                                         \
704       static_assert(ARRAY_SIZE(dwords0) == ARRAY_SIZE(dwords1), "mismatch merge"); \
705       dw = anv_batch_emit_dwords((batch), ARRAY_SIZE(dwords0));         \
706       for (uint32_t i = 0; i < ARRAY_SIZE(dwords0); i++)                \
707          dw[i] = (dwords0)[i] | (dwords1)[i];                           \
708       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dw, ARRAY_SIZE(dwords0) * 4));\
709    } while (0)
710
711 #define anv_batch_emit(batch, cmd, name)                            \
712    for (struct cmd name = { __anv_cmd_header(cmd) },                    \
713         *_dst = anv_batch_emit_dwords(batch, __anv_cmd_length(cmd));    \
714         __builtin_expect(_dst != NULL, 1);                              \
715         ({ __anv_cmd_pack(cmd)(batch, _dst, &name);                     \
716            VG(VALGRIND_CHECK_MEM_IS_DEFINED(_dst, __anv_cmd_length(cmd) * 4)); \
717            _dst = NULL;                                                 \
718          }))
719
720 #define anv_state_pool_emit(pool, cmd, align, ...) ({                   \
721       const uint32_t __size = __anv_cmd_length(cmd) * 4;                \
722       struct anv_state __state =                                        \
723          anv_state_pool_alloc((pool), __size, align);                   \
724       struct cmd __template = {                                         \
725          __VA_ARGS__                                                    \
726       };                                                                \
727       __anv_cmd_pack(cmd)(NULL, __state.map, &__template);              \
728       VG(VALGRIND_CHECK_MEM_IS_DEFINED(__state.map, __anv_cmd_length(cmd) * 4)); \
729       if (!(pool)->block_pool->device->info.has_llc)                    \
730          anv_state_clflush(__state);                                    \
731       __state;                                                          \
732    })
733
734 #define GEN7_MOCS (struct GEN7_MEMORY_OBJECT_CONTROL_STATE) {  \
735    .GraphicsDataTypeGFDT                        = 0,           \
736    .LLCCacheabilityControlLLCCC                 = 0,           \
737    .L3CacheabilityControlL3CC                   = 1,           \
738 }
739
740 #define GEN75_MOCS (struct GEN75_MEMORY_OBJECT_CONTROL_STATE) {  \
741    .LLCeLLCCacheabilityControlLLCCC             = 0,           \
742    .L3CacheabilityControlL3CC                   = 1,           \
743 }
744
745 #define GEN8_MOCS (struct GEN8_MEMORY_OBJECT_CONTROL_STATE) {  \
746       .MemoryTypeLLCeLLCCacheabilityControl = WB,              \
747       .TargetCache = L3DefertoPATforLLCeLLCselection,          \
748       .AgeforQUADLRU = 0                                       \
749    }
750
751 /* Skylake: MOCS is now an index into an array of 62 different caching
752  * configurations programmed by the kernel.
753  */
754
755 #define GEN9_MOCS (struct GEN9_MEMORY_OBJECT_CONTROL_STATE) {  \
756       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */              \
757       .IndextoMOCSTables                           = 2         \
758    }
759
760 #define GEN9_MOCS_PTE {                                 \
761       /* TC=LLC/eLLC, LeCC=WB, LRUM=3, L3CC=WB */       \
762       .IndextoMOCSTables                           = 1  \
763    }
764
765 struct anv_device_memory {
766    struct anv_bo                                bo;
767    uint32_t                                     type_index;
768    VkDeviceSize                                 map_size;
769    void *                                       map;
770 };
771
772 /**
773  * Header for Vertex URB Entry (VUE)
774  */
775 struct anv_vue_header {
776    uint32_t Reserved;
777    uint32_t RTAIndex; /* RenderTargetArrayIndex */
778    uint32_t ViewportIndex;
779    float PointWidth;
780 };
781
782 struct anv_descriptor_set_binding_layout {
783 #ifndef NDEBUG
784    /* The type of the descriptors in this binding */
785    VkDescriptorType type;
786 #endif
787
788    /* Number of array elements in this binding */
789    uint16_t array_size;
790
791    /* Index into the flattend descriptor set */
792    uint16_t descriptor_index;
793
794    /* Index into the dynamic state array for a dynamic buffer */
795    int16_t dynamic_offset_index;
796
797    /* Index into the descriptor set buffer views */
798    int16_t buffer_index;
799
800    struct {
801       /* Index into the binding table for the associated surface */
802       int16_t surface_index;
803
804       /* Index into the sampler table for the associated sampler */
805       int16_t sampler_index;
806
807       /* Index into the image table for the associated image */
808       int16_t image_index;
809    } stage[MESA_SHADER_STAGES];
810
811    /* Immutable samplers (or NULL if no immutable samplers) */
812    struct anv_sampler **immutable_samplers;
813 };
814
815 struct anv_descriptor_set_layout {
816    /* Number of bindings in this descriptor set */
817    uint16_t binding_count;
818
819    /* Total size of the descriptor set with room for all array entries */
820    uint16_t size;
821
822    /* Shader stages affected by this descriptor set */
823    uint16_t shader_stages;
824
825    /* Number of buffers in this descriptor set */
826    uint16_t buffer_count;
827
828    /* Number of dynamic offsets used by this descriptor set */
829    uint16_t dynamic_offset_count;
830
831    /* Bindings in this descriptor set */
832    struct anv_descriptor_set_binding_layout binding[0];
833 };
834
835 struct anv_descriptor {
836    VkDescriptorType type;
837
838    union {
839       struct {
840          struct anv_image_view *image_view;
841          struct anv_sampler *sampler;
842       };
843
844       struct anv_buffer_view *buffer_view;
845    };
846 };
847
848 struct anv_descriptor_set {
849    const struct anv_descriptor_set_layout *layout;
850    uint32_t size;
851    uint32_t buffer_count;
852    struct anv_buffer_view *buffer_views;
853    struct anv_descriptor descriptors[0];
854 };
855
856 struct anv_descriptor_pool {
857    uint32_t size;
858    uint32_t next;
859    uint32_t free_list;
860
861    struct anv_state_stream surface_state_stream;
862    void *surface_state_free_list;
863
864    char data[0];
865 };
866
867 VkResult
868 anv_descriptor_set_create(struct anv_device *device,
869                           struct anv_descriptor_pool *pool,
870                           const struct anv_descriptor_set_layout *layout,
871                           struct anv_descriptor_set **out_set);
872
873 void
874 anv_descriptor_set_destroy(struct anv_device *device,
875                            struct anv_descriptor_pool *pool,
876                            struct anv_descriptor_set *set);
877
878 #define ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS UINT8_MAX
879
880 struct anv_pipeline_binding {
881    /* The descriptor set this surface corresponds to.  The special value of
882     * ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS indicates that the offset refers
883     * to a color attachment and not a regular descriptor.
884     */
885    uint8_t set;
886
887    /* Binding in the descriptor set */
888    uint8_t binding;
889
890    /* Index in the binding */
891    uint8_t index;
892 };
893
894 struct anv_pipeline_layout {
895    struct {
896       struct anv_descriptor_set_layout *layout;
897       uint32_t dynamic_offset_start;
898    } set[MAX_SETS];
899
900    uint32_t num_sets;
901
902    struct {
903       bool has_dynamic_offsets;
904    } stage[MESA_SHADER_STAGES];
905
906    unsigned char sha1[20];
907 };
908
909 struct anv_buffer {
910    struct anv_device *                          device;
911    VkDeviceSize                                 size;
912
913    VkBufferUsageFlags                           usage;
914
915    /* Set when bound */
916    struct anv_bo *                              bo;
917    VkDeviceSize                                 offset;
918 };
919
920 enum anv_cmd_dirty_bits {
921    ANV_CMD_DIRTY_DYNAMIC_VIEWPORT                  = 1 << 0, /* VK_DYNAMIC_STATE_VIEWPORT */
922    ANV_CMD_DIRTY_DYNAMIC_SCISSOR                   = 1 << 1, /* VK_DYNAMIC_STATE_SCISSOR */
923    ANV_CMD_DIRTY_DYNAMIC_LINE_WIDTH                = 1 << 2, /* VK_DYNAMIC_STATE_LINE_WIDTH */
924    ANV_CMD_DIRTY_DYNAMIC_DEPTH_BIAS                = 1 << 3, /* VK_DYNAMIC_STATE_DEPTH_BIAS */
925    ANV_CMD_DIRTY_DYNAMIC_BLEND_CONSTANTS           = 1 << 4, /* VK_DYNAMIC_STATE_BLEND_CONSTANTS */
926    ANV_CMD_DIRTY_DYNAMIC_DEPTH_BOUNDS              = 1 << 5, /* VK_DYNAMIC_STATE_DEPTH_BOUNDS */
927    ANV_CMD_DIRTY_DYNAMIC_STENCIL_COMPARE_MASK      = 1 << 6, /* VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK */
928    ANV_CMD_DIRTY_DYNAMIC_STENCIL_WRITE_MASK        = 1 << 7, /* VK_DYNAMIC_STATE_STENCIL_WRITE_MASK */
929    ANV_CMD_DIRTY_DYNAMIC_STENCIL_REFERENCE         = 1 << 8, /* VK_DYNAMIC_STATE_STENCIL_REFERENCE */
930    ANV_CMD_DIRTY_DYNAMIC_ALL                       = (1 << 9) - 1,
931    ANV_CMD_DIRTY_PIPELINE                          = 1 << 9,
932    ANV_CMD_DIRTY_INDEX_BUFFER                      = 1 << 10,
933    ANV_CMD_DIRTY_RENDER_TARGETS                    = 1 << 11,
934 };
935 typedef uint32_t anv_cmd_dirty_mask_t;
936
937 enum anv_pipe_bits {
938    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT            = (1 << 0),
939    ANV_PIPE_STALL_AT_SCOREBOARD_BIT          = (1 << 1),
940    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT       = (1 << 2),
941    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT    = (1 << 3),
942    ANV_PIPE_VF_CACHE_INVALIDATE_BIT          = (1 << 4),
943    ANV_PIPE_DATA_CACHE_FLUSH_BIT             = (1 << 5),
944    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT     = (1 << 10),
945    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT = (1 << 11),
946    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT    = (1 << 12),
947    ANV_PIPE_DEPTH_STALL_BIT                  = (1 << 13),
948    ANV_PIPE_CS_STALL_BIT                     = (1 << 20),
949
950    /* This bit does not exist directly in PIPE_CONTROL.  Instead it means that
951     * a flush has happened but not a CS stall.  The next time we do any sort
952     * of invalidation we need to insert a CS stall at that time.  Otherwise,
953     * we would have to CS stall on every flush which could be bad.
954     */
955    ANV_PIPE_NEEDS_CS_STALL_BIT               = (1 << 21),
956 };
957
958 #define ANV_PIPE_FLUSH_BITS ( \
959    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT | \
960    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
961    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
962
963 #define ANV_PIPE_STALL_BITS ( \
964    ANV_PIPE_STALL_AT_SCOREBOARD_BIT | \
965    ANV_PIPE_DEPTH_STALL_BIT | \
966    ANV_PIPE_CS_STALL_BIT)
967
968 #define ANV_PIPE_INVALIDATE_BITS ( \
969    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT | \
970    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT | \
971    ANV_PIPE_VF_CACHE_INVALIDATE_BIT | \
972    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
973    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT | \
974    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT)
975
976 struct anv_vertex_binding {
977    struct anv_buffer *                          buffer;
978    VkDeviceSize                                 offset;
979 };
980
981 struct anv_push_constants {
982    /* Current allocated size of this push constants data structure.
983     * Because a decent chunk of it may not be used (images on SKL, for
984     * instance), we won't actually allocate the entire structure up-front.
985     */
986    uint32_t size;
987
988    /* Push constant data provided by the client through vkPushConstants */
989    uint8_t client_data[MAX_PUSH_CONSTANTS_SIZE];
990
991    /* Our hardware only provides zero-based vertex and instance id so, in
992     * order to satisfy the vulkan requirements, we may have to push one or
993     * both of these into the shader.
994     */
995    uint32_t base_vertex;
996    uint32_t base_instance;
997
998    /* Offsets and ranges for dynamically bound buffers */
999    struct {
1000       uint32_t offset;
1001       uint32_t range;
1002    } dynamic[MAX_DYNAMIC_BUFFERS];
1003
1004    /* Image data for image_load_store on pre-SKL */
1005    struct brw_image_param images[MAX_IMAGES];
1006 };
1007
1008 struct anv_dynamic_state {
1009    struct {
1010       uint32_t                                  count;
1011       VkViewport                                viewports[MAX_VIEWPORTS];
1012    } viewport;
1013
1014    struct {
1015       uint32_t                                  count;
1016       VkRect2D                                  scissors[MAX_SCISSORS];
1017    } scissor;
1018
1019    float                                        line_width;
1020
1021    struct {
1022       float                                     bias;
1023       float                                     clamp;
1024       float                                     slope;
1025    } depth_bias;
1026
1027    float                                        blend_constants[4];
1028
1029    struct {
1030       float                                     min;
1031       float                                     max;
1032    } depth_bounds;
1033
1034    struct {
1035       uint32_t                                  front;
1036       uint32_t                                  back;
1037    } stencil_compare_mask;
1038
1039    struct {
1040       uint32_t                                  front;
1041       uint32_t                                  back;
1042    } stencil_write_mask;
1043
1044    struct {
1045       uint32_t                                  front;
1046       uint32_t                                  back;
1047    } stencil_reference;
1048 };
1049
1050 extern const struct anv_dynamic_state default_dynamic_state;
1051
1052 void anv_dynamic_state_copy(struct anv_dynamic_state *dest,
1053                             const struct anv_dynamic_state *src,
1054                             uint32_t copy_mask);
1055
1056 /**
1057  * Attachment state when recording a renderpass instance.
1058  *
1059  * The clear value is valid only if there exists a pending clear.
1060  */
1061 struct anv_attachment_state {
1062    VkImageAspectFlags                           pending_clear_aspects;
1063    VkClearValue                                 clear_value;
1064 };
1065
1066 /** State required while building cmd buffer */
1067 struct anv_cmd_state {
1068    /* PIPELINE_SELECT.PipelineSelection */
1069    uint32_t                                     current_pipeline;
1070    const struct gen_l3_config *                 current_l3_config;
1071    uint32_t                                     vb_dirty;
1072    anv_cmd_dirty_mask_t                         dirty;
1073    anv_cmd_dirty_mask_t                         compute_dirty;
1074    enum anv_pipe_bits                           pending_pipe_bits;
1075    uint32_t                                     num_workgroups_offset;
1076    struct anv_bo                                *num_workgroups_bo;
1077    VkShaderStageFlags                           descriptors_dirty;
1078    VkShaderStageFlags                           push_constants_dirty;
1079    uint32_t                                     scratch_size;
1080    struct anv_pipeline *                        pipeline;
1081    struct anv_pipeline *                        compute_pipeline;
1082    struct anv_framebuffer *                     framebuffer;
1083    struct anv_render_pass *                     pass;
1084    struct anv_subpass *                         subpass;
1085    VkRect2D                                     render_area;
1086    uint32_t                                     restart_index;
1087    struct anv_vertex_binding                    vertex_bindings[MAX_VBS];
1088    struct anv_descriptor_set *                  descriptors[MAX_SETS];
1089    VkShaderStageFlags                           push_constant_stages;
1090    struct anv_push_constants *                  push_constants[MESA_SHADER_STAGES];
1091    struct anv_state                             binding_tables[MESA_SHADER_STAGES];
1092    struct anv_state                             samplers[MESA_SHADER_STAGES];
1093    struct anv_dynamic_state                     dynamic;
1094    bool                                         need_query_wa;
1095
1096    /**
1097     * Array length is anv_cmd_state::pass::attachment_count. Array content is
1098     * valid only when recording a render pass instance.
1099     */
1100    struct anv_attachment_state *                attachments;
1101
1102    struct {
1103       struct anv_buffer *                       index_buffer;
1104       uint32_t                                  index_type; /**< 3DSTATE_INDEX_BUFFER.IndexFormat */
1105       uint32_t                                  index_offset;
1106    } gen7;
1107 };
1108
1109 struct anv_cmd_pool {
1110    VkAllocationCallbacks                        alloc;
1111    struct list_head                             cmd_buffers;
1112 };
1113
1114 #define ANV_CMD_BUFFER_BATCH_SIZE 8192
1115
1116 enum anv_cmd_buffer_exec_mode {
1117    ANV_CMD_BUFFER_EXEC_MODE_PRIMARY,
1118    ANV_CMD_BUFFER_EXEC_MODE_EMIT,
1119    ANV_CMD_BUFFER_EXEC_MODE_GROW_AND_EMIT,
1120    ANV_CMD_BUFFER_EXEC_MODE_CHAIN,
1121    ANV_CMD_BUFFER_EXEC_MODE_COPY_AND_CHAIN,
1122 };
1123
1124 struct anv_cmd_buffer {
1125    VK_LOADER_DATA                               _loader_data;
1126
1127    struct anv_device *                          device;
1128
1129    struct anv_cmd_pool *                        pool;
1130    struct list_head                             pool_link;
1131
1132    struct anv_batch                             batch;
1133
1134    /* Fields required for the actual chain of anv_batch_bo's.
1135     *
1136     * These fields are initialized by anv_cmd_buffer_init_batch_bo_chain().
1137     */
1138    struct list_head                             batch_bos;
1139    enum anv_cmd_buffer_exec_mode                exec_mode;
1140
1141    /* A vector of anv_batch_bo pointers for every batch or surface buffer
1142     * referenced by this command buffer
1143     *
1144     * initialized by anv_cmd_buffer_init_batch_bo_chain()
1145     */
1146    struct u_vector                            seen_bbos;
1147
1148    /* A vector of int32_t's for every block of binding tables.
1149     *
1150     * initialized by anv_cmd_buffer_init_batch_bo_chain()
1151     */
1152    struct u_vector                            bt_blocks;
1153    uint32_t                                     bt_next;
1154    struct anv_reloc_list                        surface_relocs;
1155
1156    /* Information needed for execbuf
1157     *
1158     * These fields are generated by anv_cmd_buffer_prepare_execbuf().
1159     */
1160    struct {
1161       struct drm_i915_gem_execbuffer2           execbuf;
1162
1163       struct drm_i915_gem_exec_object2 *        objects;
1164       uint32_t                                  bo_count;
1165       struct anv_bo **                          bos;
1166
1167       /* Allocated length of the 'objects' and 'bos' arrays */
1168       uint32_t                                  array_length;
1169
1170       bool                                      need_reloc;
1171    } execbuf2;
1172
1173    /* Serial for tracking buffer completion */
1174    uint32_t                                     serial;
1175
1176    /* Stream objects for storing temporary data */
1177    struct anv_state_stream                      surface_state_stream;
1178    struct anv_state_stream                      dynamic_state_stream;
1179
1180    VkCommandBufferUsageFlags                    usage_flags;
1181    VkCommandBufferLevel                         level;
1182
1183    struct anv_cmd_state                         state;
1184 };
1185
1186 VkResult anv_cmd_buffer_init_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
1187 void anv_cmd_buffer_fini_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
1188 void anv_cmd_buffer_reset_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
1189 void anv_cmd_buffer_end_batch_buffer(struct anv_cmd_buffer *cmd_buffer);
1190 void anv_cmd_buffer_add_secondary(struct anv_cmd_buffer *primary,
1191                                   struct anv_cmd_buffer *secondary);
1192 void anv_cmd_buffer_prepare_execbuf(struct anv_cmd_buffer *cmd_buffer);
1193
1194 VkResult anv_cmd_buffer_reset(struct anv_cmd_buffer *cmd_buffer);
1195
1196 VkResult
1197 anv_cmd_buffer_ensure_push_constants_size(struct anv_cmd_buffer *cmd_buffer,
1198                                           gl_shader_stage stage, uint32_t size);
1199 #define anv_cmd_buffer_ensure_push_constant_field(cmd_buffer, stage, field) \
1200    anv_cmd_buffer_ensure_push_constants_size(cmd_buffer, stage, \
1201       (offsetof(struct anv_push_constants, field) + \
1202        sizeof(cmd_buffer->state.push_constants[0]->field)))
1203
1204 struct anv_state anv_cmd_buffer_emit_dynamic(struct anv_cmd_buffer *cmd_buffer,
1205                                              const void *data, uint32_t size, uint32_t alignment);
1206 struct anv_state anv_cmd_buffer_merge_dynamic(struct anv_cmd_buffer *cmd_buffer,
1207                                               uint32_t *a, uint32_t *b,
1208                                               uint32_t dwords, uint32_t alignment);
1209
1210 struct anv_address
1211 anv_cmd_buffer_surface_base_address(struct anv_cmd_buffer *cmd_buffer);
1212 struct anv_state
1213 anv_cmd_buffer_alloc_binding_table(struct anv_cmd_buffer *cmd_buffer,
1214                                    uint32_t entries, uint32_t *state_offset);
1215 struct anv_state
1216 anv_cmd_buffer_alloc_surface_state(struct anv_cmd_buffer *cmd_buffer);
1217 struct anv_state
1218 anv_cmd_buffer_alloc_dynamic_state(struct anv_cmd_buffer *cmd_buffer,
1219                                    uint32_t size, uint32_t alignment);
1220
1221 VkResult
1222 anv_cmd_buffer_new_binding_table_block(struct anv_cmd_buffer *cmd_buffer);
1223
1224 void gen8_cmd_buffer_emit_viewport(struct anv_cmd_buffer *cmd_buffer);
1225 void gen8_cmd_buffer_emit_depth_viewport(struct anv_cmd_buffer *cmd_buffer,
1226                                          bool depth_clamp_enable);
1227 void gen7_cmd_buffer_emit_scissor(struct anv_cmd_buffer *cmd_buffer);
1228
1229 void anv_cmd_state_setup_attachments(struct anv_cmd_buffer *cmd_buffer,
1230                                      const VkRenderPassBeginInfo *info);
1231
1232 struct anv_state
1233 anv_cmd_buffer_push_constants(struct anv_cmd_buffer *cmd_buffer,
1234                               gl_shader_stage stage);
1235 struct anv_state
1236 anv_cmd_buffer_cs_push_constants(struct anv_cmd_buffer *cmd_buffer);
1237
1238 void anv_cmd_buffer_clear_subpass(struct anv_cmd_buffer *cmd_buffer);
1239 void anv_cmd_buffer_resolve_subpass(struct anv_cmd_buffer *cmd_buffer);
1240
1241 const struct anv_image_view *
1242 anv_cmd_buffer_get_depth_stencil_view(const struct anv_cmd_buffer *cmd_buffer);
1243
1244 void anv_cmd_buffer_dump(struct anv_cmd_buffer *cmd_buffer);
1245
1246 struct anv_fence {
1247    struct anv_bo bo;
1248    struct drm_i915_gem_execbuffer2 execbuf;
1249    struct drm_i915_gem_exec_object2 exec2_objects[1];
1250    bool ready;
1251 };
1252
1253 struct anv_event {
1254    uint64_t                                     semaphore;
1255    struct anv_state                             state;
1256 };
1257
1258 struct anv_shader_module {
1259    unsigned char                                sha1[20];
1260    uint32_t                                     size;
1261    char                                         data[0];
1262 };
1263
1264 void anv_hash_shader(unsigned char *hash, const void *key, size_t key_size,
1265                      struct anv_shader_module *module,
1266                      const char *entrypoint,
1267                      const struct anv_pipeline_layout *pipeline_layout,
1268                      const VkSpecializationInfo *spec_info);
1269
1270 static inline gl_shader_stage
1271 vk_to_mesa_shader_stage(VkShaderStageFlagBits vk_stage)
1272 {
1273    assert(__builtin_popcount(vk_stage) == 1);
1274    return ffs(vk_stage) - 1;
1275 }
1276
1277 static inline VkShaderStageFlagBits
1278 mesa_to_vk_shader_stage(gl_shader_stage mesa_stage)
1279 {
1280    return (1 << mesa_stage);
1281 }
1282
1283 #define ANV_STAGE_MASK ((1 << MESA_SHADER_STAGES) - 1)
1284
1285 #define anv_foreach_stage(stage, stage_bits)                         \
1286    for (gl_shader_stage stage,                                       \
1287         __tmp = (gl_shader_stage)((stage_bits) & ANV_STAGE_MASK);    \
1288         stage = __builtin_ffs(__tmp) - 1, __tmp;                     \
1289         __tmp &= ~(1 << (stage)))
1290
1291 struct anv_pipeline_bind_map {
1292    uint32_t surface_count;
1293    uint32_t sampler_count;
1294    uint32_t image_count;
1295
1296    struct anv_pipeline_binding *                surface_to_descriptor;
1297    struct anv_pipeline_binding *                sampler_to_descriptor;
1298 };
1299
1300 struct anv_shader_bin {
1301    uint32_t ref_cnt;
1302
1303    struct anv_state kernel;
1304    uint32_t kernel_size;
1305
1306    struct anv_pipeline_bind_map bind_map;
1307
1308    uint32_t prog_data_size;
1309
1310    /* Prog data follows, then the key, both aligned to 8-bytes */
1311 };
1312
1313 struct anv_shader_bin *
1314 anv_shader_bin_create(struct anv_device *device,
1315                       const void *key, uint32_t key_size,
1316                       const void *kernel, uint32_t kernel_size,
1317                       const void *prog_data, uint32_t prog_data_size,
1318                       const struct anv_pipeline_bind_map *bind_map);
1319
1320 void
1321 anv_shader_bin_destroy(struct anv_device *device, struct anv_shader_bin *shader);
1322
1323 static inline void
1324 anv_shader_bin_ref(struct anv_shader_bin *shader)
1325 {
1326    assert(shader->ref_cnt >= 1);
1327    __sync_fetch_and_add(&shader->ref_cnt, 1);
1328 }
1329
1330 static inline void
1331 anv_shader_bin_unref(struct anv_device *device, struct anv_shader_bin *shader)
1332 {
1333    assert(shader->ref_cnt >= 1);
1334    if (__sync_fetch_and_add(&shader->ref_cnt, -1) == 1)
1335       anv_shader_bin_destroy(device, shader);
1336 }
1337
1338 static inline const struct brw_stage_prog_data *
1339 anv_shader_bin_get_prog_data(const struct anv_shader_bin *shader)
1340 {
1341    const void *data = shader;
1342    data += align_u32(sizeof(struct anv_shader_bin), 8);
1343    return data;
1344 }
1345
1346 struct anv_pipeline {
1347    struct anv_device *                          device;
1348    struct anv_batch                             batch;
1349    uint32_t                                     batch_data[512];
1350    struct anv_reloc_list                        batch_relocs;
1351    uint32_t                                     dynamic_state_mask;
1352    struct anv_dynamic_state                     dynamic_state;
1353
1354    struct anv_pipeline_layout *                 layout;
1355
1356    bool                                         needs_data_cache;
1357
1358    struct anv_shader_bin *                      shaders[MESA_SHADER_STAGES];
1359
1360    struct {
1361       const struct gen_l3_config *              l3_config;
1362       uint32_t                                  total_size;
1363    } urb;
1364
1365    VkShaderStageFlags                           active_stages;
1366    struct anv_state                             blend_state;
1367    uint32_t                                     vs_simd8;
1368    uint32_t                                     vs_vec4;
1369    uint32_t                                     ps_ksp0;
1370    uint32_t                                     gs_kernel;
1371    uint32_t                                     cs_simd;
1372
1373    uint32_t                                     vb_used;
1374    uint32_t                                     binding_stride[MAX_VBS];
1375    bool                                         instancing_enable[MAX_VBS];
1376    bool                                         primitive_restart;
1377    uint32_t                                     topology;
1378
1379    uint32_t                                     cs_right_mask;
1380
1381    bool                                         depth_clamp_enable;
1382
1383    struct {
1384       uint32_t                                  sf[7];
1385       uint32_t                                  depth_stencil_state[3];
1386    } gen7;
1387
1388    struct {
1389       uint32_t                                  sf[4];
1390       uint32_t                                  raster[5];
1391       uint32_t                                  wm_depth_stencil[3];
1392    } gen8;
1393
1394    struct {
1395       uint32_t                                  wm_depth_stencil[4];
1396    } gen9;
1397 };
1398
1399 static inline bool
1400 anv_pipeline_has_stage(const struct anv_pipeline *pipeline,
1401                        gl_shader_stage stage)
1402 {
1403    return (pipeline->active_stages & mesa_to_vk_shader_stage(stage)) != 0;
1404 }
1405
1406 #define ANV_DECL_GET_PROG_DATA_FUNC(prefix, stage)                   \
1407 static inline const struct brw_##prefix##_prog_data *                \
1408 get_##prefix##_prog_data(struct anv_pipeline *pipeline)              \
1409 {                                                                    \
1410    if (anv_pipeline_has_stage(pipeline, stage)) {                    \
1411       return (const struct brw_##prefix##_prog_data *)               \
1412              anv_shader_bin_get_prog_data(pipeline->shaders[stage]); \
1413    } else {                                                          \
1414       return NULL;                                                   \
1415    }                                                                 \
1416 }
1417
1418 ANV_DECL_GET_PROG_DATA_FUNC(vs, MESA_SHADER_VERTEX)
1419 ANV_DECL_GET_PROG_DATA_FUNC(gs, MESA_SHADER_GEOMETRY)
1420 ANV_DECL_GET_PROG_DATA_FUNC(wm, MESA_SHADER_FRAGMENT)
1421 ANV_DECL_GET_PROG_DATA_FUNC(cs, MESA_SHADER_COMPUTE)
1422
1423 VkResult
1424 anv_pipeline_init(struct anv_pipeline *pipeline, struct anv_device *device,
1425                   struct anv_pipeline_cache *cache,
1426                   const VkGraphicsPipelineCreateInfo *pCreateInfo,
1427                   const VkAllocationCallbacks *alloc);
1428
1429 VkResult
1430 anv_pipeline_compile_cs(struct anv_pipeline *pipeline,
1431                         struct anv_pipeline_cache *cache,
1432                         const VkComputePipelineCreateInfo *info,
1433                         struct anv_shader_module *module,
1434                         const char *entrypoint,
1435                         const VkSpecializationInfo *spec_info);
1436
1437 struct anv_format {
1438    enum isl_format isl_format:16;
1439    struct isl_swizzle swizzle;
1440 };
1441
1442 struct anv_format
1443 anv_get_format(const struct gen_device_info *devinfo, VkFormat format,
1444                VkImageAspectFlags aspect, VkImageTiling tiling);
1445
1446 static inline enum isl_format
1447 anv_get_isl_format(const struct gen_device_info *devinfo, VkFormat vk_format,
1448                    VkImageAspectFlags aspect, VkImageTiling tiling)
1449 {
1450    return anv_get_format(devinfo, vk_format, aspect, tiling).isl_format;
1451 }
1452
1453 void
1454 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm);
1455
1456 /**
1457  * Subsurface of an anv_image.
1458  */
1459 struct anv_surface {
1460    /** Valid only if isl_surf::size > 0. */
1461    struct isl_surf isl;
1462
1463    /**
1464     * Offset from VkImage's base address, as bound by vkBindImageMemory().
1465     */
1466    uint32_t offset;
1467 };
1468
1469 struct anv_image {
1470    VkImageType type;
1471    /* The original VkFormat provided by the client.  This may not match any
1472     * of the actual surface formats.
1473     */
1474    VkFormat vk_format;
1475    VkImageAspectFlags aspects;
1476    VkExtent3D extent;
1477    uint32_t levels;
1478    uint32_t array_size;
1479    uint32_t samples; /**< VkImageCreateInfo::samples */
1480    VkImageUsageFlags usage; /**< Superset of VkImageCreateInfo::usage. */
1481    VkImageTiling tiling; /** VkImageCreateInfo::tiling */
1482
1483    VkDeviceSize size;
1484    uint32_t alignment;
1485
1486    /* Set when bound */
1487    struct anv_bo *bo;
1488    VkDeviceSize offset;
1489
1490    /**
1491     * Image subsurfaces
1492     *
1493     * For each foo, anv_image::foo_surface is valid if and only if
1494     * anv_image::aspects has a foo aspect.
1495     *
1496     * The hardware requires that the depth buffer and stencil buffer be
1497     * separate surfaces.  From Vulkan's perspective, though, depth and stencil
1498     * reside in the same VkImage.  To satisfy both the hardware and Vulkan, we
1499     * allocate the depth and stencil buffers as separate surfaces in the same
1500     * bo.
1501     */
1502    union {
1503       struct anv_surface color_surface;
1504
1505       struct {
1506          struct anv_surface depth_surface;
1507          struct anv_surface hiz_surface;
1508          struct anv_surface stencil_surface;
1509       };
1510    };
1511 };
1512
1513 static inline uint32_t
1514 anv_get_layerCount(const struct anv_image *image,
1515                    const VkImageSubresourceRange *range)
1516 {
1517    return range->layerCount == VK_REMAINING_ARRAY_LAYERS ?
1518           image->array_size - range->baseArrayLayer : range->layerCount;
1519 }
1520
1521 static inline uint32_t
1522 anv_get_levelCount(const struct anv_image *image,
1523                    const VkImageSubresourceRange *range)
1524 {
1525    return range->levelCount == VK_REMAINING_MIP_LEVELS ?
1526           image->levels - range->baseMipLevel : range->levelCount;
1527 }
1528
1529
1530 struct anv_image_view {
1531    const struct anv_image *image; /**< VkImageViewCreateInfo::image */
1532    struct anv_bo *bo;
1533    uint32_t offset; /**< Offset into bo. */
1534
1535    struct isl_view isl;
1536
1537    VkImageAspectFlags aspect_mask;
1538    VkFormat vk_format;
1539    VkExtent3D extent; /**< Extent of VkImageViewCreateInfo::baseMipLevel. */
1540
1541    /** RENDER_SURFACE_STATE when using image as a color render target. */
1542    struct anv_state color_rt_surface_state;
1543
1544    /** RENDER_SURFACE_STATE when using image as a sampler surface. */
1545    struct anv_state sampler_surface_state;
1546
1547    /** RENDER_SURFACE_STATE when using image as a storage image. */
1548    struct anv_state storage_surface_state;
1549
1550    struct brw_image_param storage_image_param;
1551 };
1552
1553 struct anv_image_create_info {
1554    const VkImageCreateInfo *vk_info;
1555
1556    /** An opt-in bitmask which filters an ISL-mapping of the Vulkan tiling. */
1557    isl_tiling_flags_t isl_tiling_flags;
1558
1559    uint32_t stride;
1560 };
1561
1562 VkResult anv_image_create(VkDevice _device,
1563                           const struct anv_image_create_info *info,
1564                           const VkAllocationCallbacks* alloc,
1565                           VkImage *pImage);
1566
1567 const struct anv_surface *
1568 anv_image_get_surface_for_aspect_mask(const struct anv_image *image,
1569                                       VkImageAspectFlags aspect_mask);
1570
1571 static inline bool
1572 anv_image_has_hiz(const struct anv_image *image)
1573 {
1574    /* We must check the aspect because anv_image::hiz_surface belongs to
1575     * a union.
1576     */
1577    return (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
1578           image->hiz_surface.isl.size > 0;
1579 }
1580
1581 struct anv_buffer_view {
1582    enum isl_format format; /**< VkBufferViewCreateInfo::format */
1583    struct anv_bo *bo;
1584    uint32_t offset; /**< Offset into bo. */
1585    uint64_t range; /**< VkBufferViewCreateInfo::range */
1586
1587    struct anv_state surface_state;
1588    struct anv_state storage_surface_state;
1589
1590    struct brw_image_param storage_image_param;
1591 };
1592
1593 enum isl_format
1594 anv_isl_format_for_descriptor_type(VkDescriptorType type);
1595
1596 static inline struct VkExtent3D
1597 anv_sanitize_image_extent(const VkImageType imageType,
1598                           const struct VkExtent3D imageExtent)
1599 {
1600    switch (imageType) {
1601    case VK_IMAGE_TYPE_1D:
1602       return (VkExtent3D) { imageExtent.width, 1, 1 };
1603    case VK_IMAGE_TYPE_2D:
1604       return (VkExtent3D) { imageExtent.width, imageExtent.height, 1 };
1605    case VK_IMAGE_TYPE_3D:
1606       return imageExtent;
1607    default:
1608       unreachable("invalid image type");
1609    }
1610 }
1611
1612 static inline struct VkOffset3D
1613 anv_sanitize_image_offset(const VkImageType imageType,
1614                           const struct VkOffset3D imageOffset)
1615 {
1616    switch (imageType) {
1617    case VK_IMAGE_TYPE_1D:
1618       return (VkOffset3D) { imageOffset.x, 0, 0 };
1619    case VK_IMAGE_TYPE_2D:
1620       return (VkOffset3D) { imageOffset.x, imageOffset.y, 0 };
1621    case VK_IMAGE_TYPE_3D:
1622       return imageOffset;
1623    default:
1624       unreachable("invalid image type");
1625    }
1626 }
1627
1628
1629 void anv_fill_buffer_surface_state(struct anv_device *device,
1630                                    struct anv_state state,
1631                                    enum isl_format format,
1632                                    uint32_t offset, uint32_t range,
1633                                    uint32_t stride);
1634
1635 void anv_image_view_fill_image_param(struct anv_device *device,
1636                                      struct anv_image_view *view,
1637                                      struct brw_image_param *param);
1638 void anv_buffer_view_fill_image_param(struct anv_device *device,
1639                                       struct anv_buffer_view *view,
1640                                       struct brw_image_param *param);
1641
1642 struct anv_sampler {
1643    uint32_t state[4];
1644 };
1645
1646 struct anv_framebuffer {
1647    uint32_t                                     width;
1648    uint32_t                                     height;
1649    uint32_t                                     layers;
1650
1651    uint32_t                                     attachment_count;
1652    struct anv_image_view *                      attachments[0];
1653 };
1654
1655 struct anv_subpass {
1656    uint32_t                                     input_count;
1657    uint32_t *                                   input_attachments;
1658    uint32_t                                     color_count;
1659    uint32_t *                                   color_attachments;
1660    uint32_t *                                   resolve_attachments;
1661    uint32_t                                     depth_stencil_attachment;
1662
1663    /** Subpass has at least one resolve attachment */
1664    bool                                         has_resolve;
1665 };
1666
1667 struct anv_render_pass_attachment {
1668    VkFormat                                     format;
1669    uint32_t                                     samples;
1670    VkAttachmentLoadOp                           load_op;
1671    VkAttachmentStoreOp                          store_op;
1672    VkAttachmentLoadOp                           stencil_load_op;
1673 };
1674
1675 struct anv_render_pass {
1676    uint32_t                                     attachment_count;
1677    uint32_t                                     subpass_count;
1678    uint32_t *                                   subpass_attachments;
1679    struct anv_render_pass_attachment *          attachments;
1680    struct anv_subpass                           subpasses[0];
1681 };
1682
1683 struct anv_query_pool_slot {
1684    uint64_t begin;
1685    uint64_t end;
1686    uint64_t available;
1687 };
1688
1689 struct anv_query_pool {
1690    VkQueryType                                  type;
1691    uint32_t                                     slots;
1692    struct anv_bo                                bo;
1693 };
1694
1695 void *anv_lookup_entrypoint(const struct gen_device_info *devinfo,
1696                             const char *name);
1697
1698 void anv_dump_image_to_ppm(struct anv_device *device,
1699                            struct anv_image *image, unsigned miplevel,
1700                            unsigned array_layer, VkImageAspectFlagBits aspect,
1701                            const char *filename);
1702
1703 enum anv_dump_action {
1704    ANV_DUMP_FRAMEBUFFERS_BIT = 0x1,
1705 };
1706
1707 void anv_dump_start(struct anv_device *device, enum anv_dump_action actions);
1708 void anv_dump_finish(void);
1709
1710 void anv_dump_add_framebuffer(struct anv_cmd_buffer *cmd_buffer,
1711                               struct anv_framebuffer *fb);
1712
1713 #define ANV_DEFINE_HANDLE_CASTS(__anv_type, __VkType)                      \
1714                                                                            \
1715    static inline struct __anv_type *                                       \
1716    __anv_type ## _from_handle(__VkType _handle)                            \
1717    {                                                                       \
1718       return (struct __anv_type *) _handle;                                \
1719    }                                                                       \
1720                                                                            \
1721    static inline __VkType                                                  \
1722    __anv_type ## _to_handle(struct __anv_type *_obj)                       \
1723    {                                                                       \
1724       return (__VkType) _obj;                                              \
1725    }
1726
1727 #define ANV_DEFINE_NONDISP_HANDLE_CASTS(__anv_type, __VkType)              \
1728                                                                            \
1729    static inline struct __anv_type *                                       \
1730    __anv_type ## _from_handle(__VkType _handle)                            \
1731    {                                                                       \
1732       return (struct __anv_type *)(uintptr_t) _handle;                     \
1733    }                                                                       \
1734                                                                            \
1735    static inline __VkType                                                  \
1736    __anv_type ## _to_handle(struct __anv_type *_obj)                       \
1737    {                                                                       \
1738       return (__VkType)(uintptr_t) _obj;                                   \
1739    }
1740
1741 #define ANV_FROM_HANDLE(__anv_type, __name, __handle) \
1742    struct __anv_type *__name = __anv_type ## _from_handle(__handle)
1743
1744 ANV_DEFINE_HANDLE_CASTS(anv_cmd_buffer, VkCommandBuffer)
1745 ANV_DEFINE_HANDLE_CASTS(anv_device, VkDevice)
1746 ANV_DEFINE_HANDLE_CASTS(anv_instance, VkInstance)
1747 ANV_DEFINE_HANDLE_CASTS(anv_physical_device, VkPhysicalDevice)
1748 ANV_DEFINE_HANDLE_CASTS(anv_queue, VkQueue)
1749
1750 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_cmd_pool, VkCommandPool)
1751 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer, VkBuffer)
1752 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer_view, VkBufferView)
1753 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_pool, VkDescriptorPool)
1754 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set, VkDescriptorSet)
1755 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set_layout, VkDescriptorSetLayout)
1756 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_device_memory, VkDeviceMemory)
1757 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_fence, VkFence)
1758 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_event, VkEvent)
1759 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_framebuffer, VkFramebuffer)
1760 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_image, VkImage)
1761 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_image_view, VkImageView);
1762 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline_cache, VkPipelineCache)
1763 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline, VkPipeline)
1764 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline_layout, VkPipelineLayout)
1765 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_query_pool, VkQueryPool)
1766 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_render_pass, VkRenderPass)
1767 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_sampler, VkSampler)
1768 ANV_DEFINE_NONDISP_HANDLE_CASTS(anv_shader_module, VkShaderModule)
1769
1770 #define ANV_DEFINE_STRUCT_CASTS(__anv_type, __VkType) \
1771    \
1772    static inline const __VkType * \
1773    __anv_type ## _to_ ## __VkType(const struct __anv_type *__anv_obj) \
1774    { \
1775       return (const __VkType *) __anv_obj; \
1776    }
1777
1778 #define ANV_COMMON_TO_STRUCT(__VkType, __vk_name, __common_name) \
1779    const __VkType *__vk_name = anv_common_to_ ## __VkType(__common_name)
1780
1781 ANV_DEFINE_STRUCT_CASTS(anv_common, VkMemoryBarrier)
1782 ANV_DEFINE_STRUCT_CASTS(anv_common, VkBufferMemoryBarrier)
1783 ANV_DEFINE_STRUCT_CASTS(anv_common, VkImageMemoryBarrier)
1784
1785 /* Gen-specific function declarations */
1786 #ifdef genX
1787 #  include "anv_genX.h"
1788 #else
1789 #  define genX(x) gen7_##x
1790 #  include "anv_genX.h"
1791 #  undef genX
1792 #  define genX(x) gen75_##x
1793 #  include "anv_genX.h"
1794 #  undef genX
1795 #  define genX(x) gen8_##x
1796 #  include "anv_genX.h"
1797 #  undef genX
1798 #  define genX(x) gen9_##x
1799 #  include "anv_genX.h"
1800 #  undef genX
1801 #endif
1802
1803 #ifdef __cplusplus
1804 }
1805 #endif
1806
1807 #endif /* ANV_PRIVATE_H */