OSDN Git Service

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