OSDN Git Service

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