OSDN Git Service

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