• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #ifndef ANV_PRIVATE_H
25 #define ANV_PRIVATE_H
26 
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <stdbool.h>
30 #include <pthread.h>
31 #include <assert.h>
32 #include <stdint.h>
33 #include "drm-uapi/i915_drm.h"
34 #include "drm-uapi/drm_fourcc.h"
35 
36 #ifdef HAVE_VALGRIND
37 #include <valgrind.h>
38 #include <memcheck.h>
39 #define VG(x) x
40 #else
41 #define VG(x) ((void)0)
42 #endif
43 
44 #include "common/intel_engine.h"
45 #include "common/intel_gem.h"
46 #include "common/intel_l3_config.h"
47 #include "common/intel_measure.h"
48 #include "common/intel_mem.h"
49 #include "common/intel_sample_positions.h"
50 #include "decoder/intel_decoder.h"
51 #include "dev/intel_device_info.h"
52 #include "blorp/blorp.h"
53 #include "compiler/elk/elk_compiler.h"
54 #include "ds/intel_driver_ds.h"
55 #include "util/bitset.h"
56 #include "util/bitscan.h"
57 #include "util/detect_os.h"
58 #include "util/macros.h"
59 #include "util/hash_table.h"
60 #include "util/list.h"
61 #include "util/perf/u_trace.h"
62 #include "util/set.h"
63 #include "util/sparse_array.h"
64 #include "util/u_atomic.h"
65 #include "util/u_vector.h"
66 #include "util/u_math.h"
67 #include "util/vma.h"
68 #include "util/xmlconfig.h"
69 #include "vk_alloc.h"
70 #include "vk_buffer.h"
71 #include "vk_command_buffer.h"
72 #include "vk_command_pool.h"
73 #include "vk_debug_report.h"
74 #include "vk_descriptor_update_template.h"
75 #include "vk_device.h"
76 #include "vk_drm_syncobj.h"
77 #include "vk_enum_defines.h"
78 #include "vk_format.h"
79 #include "vk_framebuffer.h"
80 #include "vk_graphics_state.h"
81 #include "vk_image.h"
82 #include "vk_instance.h"
83 #include "vk_pipeline_cache.h"
84 #include "vk_physical_device.h"
85 #include "vk_shader_module.h"
86 #include "vk_sync.h"
87 #include "vk_sync_timeline.h"
88 #include "vk_util.h"
89 #include "vk_queue.h"
90 #include "vk_log.h"
91 #include "vk_ycbcr_conversion.h"
92 
93 /* Pre-declarations needed for WSI entrypoints */
94 struct wl_surface;
95 struct wl_display;
96 typedef struct xcb_connection_t xcb_connection_t;
97 typedef uint32_t xcb_visualid_t;
98 typedef uint32_t xcb_window_t;
99 
100 struct anv_batch;
101 struct anv_buffer;
102 struct anv_buffer_view;
103 struct anv_image_view;
104 struct anv_instance;
105 
106 struct intel_perf_config;
107 struct intel_perf_counter_pass;
108 struct intel_perf_query_result;
109 
110 #include <vulkan/vulkan.h>
111 #include <vulkan/vk_icd.h>
112 
113 #include "anv_android.h"
114 #include "anv_entrypoints.h"
115 #include "isl/isl.h"
116 
117 #include "dev/intel_debug.h"
118 #undef MESA_LOG_TAG
119 #define MESA_LOG_TAG "MESA-INTEL"
120 #include "util/log.h"
121 #include "wsi_common.h"
122 
123 #define NSEC_PER_SEC 1000000000ull
124 
125 /* anv Virtual Memory Layout
126  * =========================
127  *
128  * When the anv driver is determining the virtual graphics addresses of memory
129  * objects itself using the softpin mechanism, the following memory ranges
130  * will be used.
131  *
132  * Three special considerations to notice:
133  *
134  * (1) the dynamic state pool is located within the same 4 GiB as the low
135  * heap. This is to work around a VF cache issue described in a comment in
136  * anv_physical_device_init_heaps.
137  *
138  * (2) the binding table pool is located at lower addresses than the surface
139  * state pool, within a 4 GiB range. This allows surface state base addresses
140  * to cover both binding tables (16 bit offsets) and surface states (32 bit
141  * offsets).
142  *
143  * (3) the last 4 GiB of the address space is withheld from the high
144  * heap. Various hardware units will read past the end of an object for
145  * various reasons. This healthy margin prevents reads from wrapping around
146  * 48-bit addresses.
147  */
148 #define GENERAL_STATE_POOL_MIN_ADDRESS     0x000000200000ULL /* 2 MiB */
149 #define GENERAL_STATE_POOL_MAX_ADDRESS     0x00003fffffffULL
150 #define LOW_HEAP_MIN_ADDRESS               0x000040000000ULL /* 1 GiB */
151 #define LOW_HEAP_MAX_ADDRESS               0x00007fffffffULL
152 #define DYNAMIC_STATE_POOL_MIN_ADDRESS     0x0000c0000000ULL /* 3 GiB */
153 #define DYNAMIC_STATE_POOL_MAX_ADDRESS     0x0000ffffffffULL
154 #define BINDING_TABLE_POOL_MIN_ADDRESS     0x000100000000ULL /* 4 GiB */
155 #define BINDING_TABLE_POOL_MAX_ADDRESS     0x00013fffffffULL
156 #define SURFACE_STATE_POOL_MIN_ADDRESS     0x000140000000ULL /* 5 GiB */
157 #define SURFACE_STATE_POOL_MAX_ADDRESS     0x00017fffffffULL
158 #define INSTRUCTION_STATE_POOL_MIN_ADDRESS 0x000180000000ULL /* 6 GiB */
159 #define INSTRUCTION_STATE_POOL_MAX_ADDRESS 0x0001bfffffffULL
160 #define CLIENT_VISIBLE_HEAP_MIN_ADDRESS    0x0001c0000000ULL /* 7 GiB */
161 #define CLIENT_VISIBLE_HEAP_MAX_ADDRESS    0x0002bfffffffULL
162 #define HIGH_HEAP_MIN_ADDRESS              0x0002c0000000ULL /* 11 GiB */
163 
164 #define GENERAL_STATE_POOL_SIZE     \
165    (GENERAL_STATE_POOL_MAX_ADDRESS - GENERAL_STATE_POOL_MIN_ADDRESS + 1)
166 #define LOW_HEAP_SIZE               \
167    (LOW_HEAP_MAX_ADDRESS - LOW_HEAP_MIN_ADDRESS + 1)
168 #define DYNAMIC_STATE_POOL_SIZE     \
169    (DYNAMIC_STATE_POOL_MAX_ADDRESS - DYNAMIC_STATE_POOL_MIN_ADDRESS + 1)
170 #define BINDING_TABLE_POOL_SIZE     \
171    (BINDING_TABLE_POOL_MAX_ADDRESS - BINDING_TABLE_POOL_MIN_ADDRESS + 1)
172 #define BINDING_TABLE_POOL_BLOCK_SIZE (65536)
173 #define SURFACE_STATE_POOL_SIZE     \
174    (SURFACE_STATE_POOL_MAX_ADDRESS - SURFACE_STATE_POOL_MIN_ADDRESS + 1)
175 #define INSTRUCTION_STATE_POOL_SIZE \
176    (INSTRUCTION_STATE_POOL_MAX_ADDRESS - INSTRUCTION_STATE_POOL_MIN_ADDRESS + 1)
177 #define CLIENT_VISIBLE_HEAP_SIZE               \
178    (CLIENT_VISIBLE_HEAP_MAX_ADDRESS - CLIENT_VISIBLE_HEAP_MIN_ADDRESS + 1)
179 
180 /* Allowing different clear colors requires us to perform a depth resolve at
181  * the end of certain render passes. This is because while slow clears store
182  * the clear color in the HiZ buffer, fast clears (without a resolve) don't.
183  * See the PRMs for examples describing when additional resolves would be
184  * necessary. To enable fast clears without requiring extra resolves, we set
185  * the clear value to a globally-defined one. We could allow different values
186  * if the user doesn't expect coherent data during or after a render passes
187  * (VK_ATTACHMENT_STORE_OP_DONT_CARE), but such users (aside from the CTS)
188  * don't seem to exist yet. In almost all Vulkan applications tested thus far,
189  * 1.0f seems to be the only value used. The only application that doesn't set
190  * this value does so through the usage of an seemingly uninitialized clear
191  * value.
192  */
193 #define ANV_HZ_FC_VAL 1.0f
194 
195 /* 3DSTATE_VERTEX_BUFFER supports 33 VBs, we use 2 for base & drawid SGVs */
196 #define MAX_VBS         (33 - 2)
197 
198 /* 3DSTATE_VERTEX_ELEMENTS supports up to 34 VEs, but our backend compiler
199  * only supports the push model of VS inputs, and we only have 128 GRFs,
200  * minus the g0 and g1 payload, which gives us a maximum of 31 VEs.  Plus,
201  * we use two of them for SGVs.
202  */
203 #define MAX_VES         (31 - 2)
204 
205 #define MAX_XFB_BUFFERS  4
206 #define MAX_XFB_STREAMS  4
207 #define MAX_SETS        32
208 #define MAX_RTS          8
209 #define MAX_VIEWPORTS   16
210 #define MAX_SCISSORS    16
211 #define MAX_PUSH_CONSTANTS_SIZE 128
212 #define MAX_DYNAMIC_BUFFERS 16
213 #define MAX_IMAGES 64
214 #define MAX_PUSH_DESCRIPTORS 32 /* Minimum requirement */
215 #define MAX_INLINE_UNIFORM_BLOCK_SIZE 4096
216 #define MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS 32
217 /* We need 16 for UBO block reads to work and 32 for push UBOs. However, we
218  * use 64 here to avoid cache issues. This could most likely bring it back to
219  * 32 if we had different virtual addresses for the different views on a given
220  * GEM object.
221  */
222 #define ANV_UBO_ALIGNMENT 64
223 #define ANV_SSBO_ALIGNMENT 4
224 #define ANV_SSBO_BOUNDS_CHECK_ALIGNMENT 4
225 #define MAX_VIEWS_FOR_PRIMITIVE_REPLICATION 16
226 #define MAX_SAMPLE_LOCATIONS 16
227 
228 /* From the Skylake PRM Vol. 7 "Binding Table Surface State Model":
229  *
230  *    "The surface state model is used when a Binding Table Index (specified
231  *    in the message descriptor) of less than 240 is specified. In this model,
232  *    the Binding Table Index is used to index into the binding table, and the
233  *    binding table entry contains a pointer to the SURFACE_STATE."
234  *
235  * Binding table values above 240 are used for various things in the hardware
236  * such as stateless, stateless with incoherent cache, SLM, and bindless.
237  */
238 #define MAX_BINDING_TABLE_SIZE 240
239 
240 /* The kernel relocation API has a limitation of a 32-bit delta value
241  * applied to the address before it is written which, in spite of it being
242  * unsigned, is treated as signed .  Because of the way that this maps to
243  * the Vulkan API, we cannot handle an offset into a buffer that does not
244  * fit into a signed 32 bits.  The only mechanism we have for dealing with
245  * this at the moment is to limit all VkDeviceMemory objects to a maximum
246  * of 2GB each.  The Vulkan spec allows us to do this:
247  *
248  *    "Some platforms may have a limit on the maximum size of a single
249  *    allocation. For example, certain systems may fail to create
250  *    allocations with a size greater than or equal to 4GB. Such a limit is
251  *    implementation-dependent, and if such a failure occurs then the error
252  *    VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
253  */
254 #define MAX_MEMORY_ALLOCATION_SIZE (1ull << 31)
255 
256 #define ANV_SVGS_VB_INDEX    MAX_VBS
257 #define ANV_DRAWID_VB_INDEX (MAX_VBS + 1)
258 
259 /* We reserve this MI ALU register for the purpose of handling predication.
260  * Other code which uses the MI ALU should leave it alone.
261  */
262 #define ANV_PREDICATE_RESULT_REG 0x2678 /* MI_ALU_REG15 */
263 
264 /* We reserve this MI ALU register to pass around an offset computed from
265  * VkPerformanceQuerySubmitInfoKHR::counterPassIndex VK_KHR_performance_query.
266  * Other code which uses the MI ALU should leave it alone.
267  */
268 #define ANV_PERF_QUERY_OFFSET_REG 0x2670 /* MI_ALU_REG14 */
269 
270 #define ANV_GRAPHICS_SHADER_STAGE_COUNT (MESA_SHADER_MESH + 1)
271 
272 /* For gfx12 we set the streamout buffers using 4 separate commands
273  * (3DSTATE_SO_BUFFER_INDEX_*) instead of 3DSTATE_SO_BUFFER. However the layout
274  * of the 3DSTATE_SO_BUFFER_INDEX_* commands is identical to that of
275  * 3DSTATE_SO_BUFFER apart from the SOBufferIndex field, so for now we use the
276  * 3DSTATE_SO_BUFFER command, but change the 3DCommandSubOpcode.
277  * SO_BUFFER_INDEX_0_CMD is actually the 3DCommandSubOpcode for
278  * 3DSTATE_SO_BUFFER_INDEX_0.
279  */
280 #define SO_BUFFER_INDEX_0_CMD 0x60
281 #define anv_printflike(a, b) __attribute__((__format__(__printf__, a, b)))
282 
283 static inline uint32_t
align_down_npot_u32(uint32_t v,uint32_t a)284 align_down_npot_u32(uint32_t v, uint32_t a)
285 {
286    return v - (v % a);
287 }
288 
289 /** Alignment must be a power of 2. */
290 static inline bool
anv_is_aligned(uintmax_t n,uintmax_t a)291 anv_is_aligned(uintmax_t n, uintmax_t a)
292 {
293    assert(a == (a & -a));
294    return (n & (a - 1)) == 0;
295 }
296 
297 static inline union isl_color_value
vk_to_isl_color(VkClearColorValue color)298 vk_to_isl_color(VkClearColorValue color)
299 {
300    return (union isl_color_value) {
301       .u32 = {
302          color.uint32[0],
303          color.uint32[1],
304          color.uint32[2],
305          color.uint32[3],
306       },
307    };
308 }
309 
310 static inline union isl_color_value
vk_to_isl_color_with_format(VkClearColorValue color,enum isl_format format)311 vk_to_isl_color_with_format(VkClearColorValue color, enum isl_format format)
312 {
313    const struct isl_format_layout *fmtl = isl_format_get_layout(format);
314    union isl_color_value isl_color = { .u32 = {0, } };
315 
316 #define COPY_COLOR_CHANNEL(c, i) \
317    if (fmtl->channels.c.bits) \
318       isl_color.u32[i] = color.uint32[i]
319 
320    COPY_COLOR_CHANNEL(r, 0);
321    COPY_COLOR_CHANNEL(g, 1);
322    COPY_COLOR_CHANNEL(b, 2);
323    COPY_COLOR_CHANNEL(a, 3);
324 
325 #undef COPY_COLOR_CHANNEL
326 
327    return isl_color;
328 }
329 
330 /**
331  * Warn on ignored extension structs.
332  *
333  * The Vulkan spec requires us to ignore unsupported or unknown structs in
334  * a pNext chain.  In debug mode, emitting warnings for ignored structs may
335  * help us discover structs that we should not have ignored.
336  *
337  *
338  * From the Vulkan 1.0.38 spec:
339  *
340  *    Any component of the implementation (the loader, any enabled layers,
341  *    and drivers) must skip over, without processing (other than reading the
342  *    sType and pNext members) any chained structures with sType values not
343  *    defined by extensions supported by that component.
344  */
345 #define anv_debug_ignored_stype(sType) \
346    mesa_logd("%s: ignored VkStructureType %u\n", __func__, (sType))
347 
348 void __anv_perf_warn(struct anv_device *device,
349                      const struct vk_object_base *object,
350                      const char *file, int line, const char *format, ...)
351    anv_printflike(5, 6);
352 
353 /**
354  * Print a FINISHME message, including its source location.
355  */
356 #define anv_finishme(format, ...) \
357    do { \
358       static bool reported = false; \
359       if (!reported) { \
360          mesa_logw("%s:%d: FINISHME: " format, __FILE__, __LINE__, \
361                     ##__VA_ARGS__); \
362          reported = true; \
363       } \
364    } while (0)
365 
366 /**
367  * Print a perf warning message.  Set INTEL_DEBUG=perf to see these.
368  */
369 #define anv_perf_warn(objects_macro, format, ...)   \
370    do { \
371       static bool reported = false; \
372       if (!reported && INTEL_DEBUG(DEBUG_PERF)) { \
373          __vk_log(VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT,      \
374                   VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,      \
375                   objects_macro, __FILE__, __LINE__,                    \
376                   format, ## __VA_ARGS__);                              \
377          reported = true; \
378       } \
379    } while (0)
380 
381 /* A non-fatal assert.  Useful for debugging. */
382 #ifdef DEBUG
383 #define anv_assert(x) ({ \
384    if (unlikely(!(x))) \
385       mesa_loge("%s:%d ASSERT: %s", __FILE__, __LINE__, #x); \
386 })
387 #else
388 #define anv_assert(x)
389 #endif
390 
391 struct anv_bo {
392    const char *name;
393 
394    uint32_t gem_handle;
395 
396    uint32_t refcount;
397 
398    /* Index into the current validation list.  This is used by the
399     * validation list building algorithm to track which buffers are already
400     * in the validation list so that we can ensure uniqueness.
401     */
402    uint32_t exec_obj_index;
403 
404    /* Index for use with util_sparse_array_free_list */
405    uint32_t free_index;
406 
407    /* Last known offset.  This value is provided by the kernel when we
408     * execbuf and is used as the presumed offset for the next bunch of
409     * relocations.
410     */
411    uint64_t offset;
412 
413    /** Size of the buffer not including implicit aux */
414    uint64_t size;
415 
416    /* Map for internally mapped BOs.
417     *
418     * If ANV_BO_ALLOC_MAPPED is set in flags, this is the map for the whole
419     * BO. If ANV_BO_WRAPPER is set in flags, map points to the wrapped BO.
420     */
421    void *map;
422 
423    /** Flags to pass to the kernel through drm_i915_exec_object2::flags */
424    uint32_t flags;
425 
426    /** True if this BO may be shared with other processes */
427    bool is_external:1;
428 
429    /** True if this BO is a wrapper
430     *
431     * When set to true, none of the fields in this BO are meaningful except
432     * for anv_bo::is_wrapper and anv_bo::map which points to the actual BO.
433     * See also anv_bo_unwrap().  Wrapper BOs are not allowed when use_softpin
434     * is set in the physical device.
435     */
436    bool is_wrapper:1;
437 
438    /** See also ANV_BO_ALLOC_FIXED_ADDRESS */
439    bool has_fixed_address:1;
440 
441    /** True if this BO wraps a host pointer */
442    bool from_host_ptr:1;
443 
444    /** See also ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS */
445    bool has_client_visible_address:1;
446 };
447 
448 static inline struct anv_bo *
anv_bo_ref(struct anv_bo * bo)449 anv_bo_ref(struct anv_bo *bo)
450 {
451    p_atomic_inc(&bo->refcount);
452    return bo;
453 }
454 
455 static inline struct anv_bo *
anv_bo_unwrap(struct anv_bo * bo)456 anv_bo_unwrap(struct anv_bo *bo)
457 {
458    while (bo->is_wrapper)
459       bo = bo->map;
460    return bo;
461 }
462 
463 static inline bool
anv_bo_is_pinned(struct anv_bo * bo)464 anv_bo_is_pinned(struct anv_bo *bo)
465 {
466 #if defined(GFX_VERx10) && GFX_VERx10 < 80
467    /* Haswell and earlier never use softpin */
468    assert(!(bo->flags & EXEC_OBJECT_PINNED));
469    assert(!bo->has_fixed_address);
470    return false;
471 #else
472    /* If we don't have a GFX_VERx10 #define, we need to look at the BO.  Also,
473     * for GFX version 8, we need to look at the BO because Broadwell softpins
474     * but Cherryview doesn't.
475     */
476    assert((bo->flags & EXEC_OBJECT_PINNED) || !bo->has_fixed_address);
477    return (bo->flags & EXEC_OBJECT_PINNED) != 0;
478 #endif
479 }
480 
481 struct anv_address {
482    struct anv_bo *bo;
483    int64_t offset;
484 };
485 
486 #define ANV_NULL_ADDRESS ((struct anv_address) { NULL, 0 })
487 
488 static inline struct anv_address
anv_address_from_u64(uint64_t addr_u64)489 anv_address_from_u64(uint64_t addr_u64)
490 {
491    assert(addr_u64 == intel_canonical_address(addr_u64));
492    return (struct anv_address) {
493       .bo = NULL,
494       .offset = addr_u64,
495    };
496 }
497 
498 static inline bool
anv_address_is_null(struct anv_address addr)499 anv_address_is_null(struct anv_address addr)
500 {
501    return addr.bo == NULL && addr.offset == 0;
502 }
503 
504 static inline uint64_t
anv_address_physical(struct anv_address addr)505 anv_address_physical(struct anv_address addr)
506 {
507    if (addr.bo && anv_bo_is_pinned(addr.bo)) {
508       return intel_canonical_address(addr.bo->offset + addr.offset);
509    } else {
510       return intel_canonical_address(addr.offset);
511    }
512 }
513 
514 static inline struct anv_address
anv_address_add(struct anv_address addr,uint64_t offset)515 anv_address_add(struct anv_address addr, uint64_t offset)
516 {
517    addr.offset += offset;
518    return addr;
519 }
520 
521 /* Represents a lock-free linked list of "free" things.  This is used by
522  * both the block pool and the state pools.  Unfortunately, in order to
523  * solve the ABA problem, we can't use a single uint32_t head.
524  */
525 union anv_free_list {
526    struct {
527       uint32_t offset;
528 
529       /* A simple count that is incremented every time the head changes. */
530       uint32_t count;
531    };
532    /* Make sure it's aligned to 64 bits. This will make atomic operations
533     * faster on 32 bit platforms.
534     */
535    alignas(8) uint64_t u64;
536 };
537 
538 #define ANV_FREE_LIST_EMPTY ((union anv_free_list) { { UINT32_MAX, 0 } })
539 
540 struct anv_block_state {
541    union {
542       struct {
543          uint32_t next;
544          uint32_t end;
545       };
546       /* Make sure it's aligned to 64 bits. This will make atomic operations
547        * faster on 32 bit platforms.
548        */
549       alignas(8) uint64_t u64;
550    };
551 };
552 
553 #define anv_block_pool_foreach_bo(bo, pool)  \
554    for (struct anv_bo **_pp_bo = (pool)->bos, *bo; \
555         _pp_bo != &(pool)->bos[(pool)->nbos] && (bo = *_pp_bo, true); \
556         _pp_bo++)
557 
558 #define ANV_MAX_BLOCK_POOL_BOS 20
559 
560 struct anv_block_pool {
561    const char *name;
562 
563    struct anv_device *device;
564    bool use_relocations;
565 
566    /* Wrapper BO for use in relocation lists.  This BO is simply a wrapper
567     * around the actual BO so that we grow the pool after the wrapper BO has
568     * been put in a relocation list.  This is only used in the non-softpin
569     * case.
570     */
571    struct anv_bo wrapper_bo;
572 
573    struct anv_bo *bos[ANV_MAX_BLOCK_POOL_BOS];
574    struct anv_bo *bo;
575    uint32_t nbos;
576 
577    uint64_t size;
578 
579    /* The address where the start of the pool is pinned. The various bos that
580     * are created as the pool grows will have addresses in the range
581     * [start_address, start_address + BLOCK_POOL_MEMFD_SIZE).
582     */
583    uint64_t start_address;
584 
585    /* The offset from the start of the bo to the "center" of the block
586     * pool.  Pointers to allocated blocks are given by
587     * bo.map + center_bo_offset + offsets.
588     */
589    uint32_t center_bo_offset;
590 
591    /* Current memory map of the block pool.  This pointer may or may not
592     * point to the actual beginning of the block pool memory.  If
593     * anv_block_pool_alloc_back has ever been called, then this pointer
594     * will point to the "center" position of the buffer and all offsets
595     * (negative or positive) given out by the block pool alloc functions
596     * will be valid relative to this pointer.
597     *
598     * In particular, map == bo.map + center_offset
599     *
600     * DO NOT access this pointer directly. Use anv_block_pool_map() instead,
601     * since it will handle the softpin case as well, where this points to NULL.
602     */
603    void *map;
604    int fd;
605 
606    /**
607     * Array of mmaps and gem handles owned by the block pool, reclaimed when
608     * the block pool is destroyed.
609     */
610    struct u_vector mmap_cleanups;
611 
612    struct anv_block_state state;
613 
614    struct anv_block_state back_state;
615 };
616 
617 /* Block pools are backed by a fixed-size 1GB memfd */
618 #define BLOCK_POOL_MEMFD_SIZE (1ul << 30)
619 
620 /* The center of the block pool is also the middle of the memfd.  This may
621  * change in the future if we decide differently for some reason.
622  */
623 #define BLOCK_POOL_MEMFD_CENTER (BLOCK_POOL_MEMFD_SIZE / 2)
624 
625 static inline uint32_t
anv_block_pool_size(struct anv_block_pool * pool)626 anv_block_pool_size(struct anv_block_pool *pool)
627 {
628    return pool->state.end + pool->back_state.end;
629 }
630 
631 struct anv_state {
632    int32_t offset;
633    uint32_t alloc_size;
634    void *map;
635    uint32_t idx;
636 };
637 
638 #define ANV_STATE_NULL ((struct anv_state) { .alloc_size = 0 })
639 
640 struct anv_fixed_size_state_pool {
641    union anv_free_list free_list;
642    struct anv_block_state block;
643 };
644 
645 #define ANV_MIN_STATE_SIZE_LOG2 6
646 #define ANV_MAX_STATE_SIZE_LOG2 21
647 
648 #define ANV_STATE_BUCKETS (ANV_MAX_STATE_SIZE_LOG2 - ANV_MIN_STATE_SIZE_LOG2 + 1)
649 
650 struct anv_free_entry {
651    uint32_t next;
652    struct anv_state state;
653 };
654 
655 struct anv_state_table {
656    struct anv_device *device;
657    int fd;
658    struct anv_free_entry *map;
659    uint32_t size;
660    struct anv_block_state state;
661    struct u_vector cleanups;
662 };
663 
664 struct anv_state_pool {
665    struct anv_block_pool block_pool;
666 
667    /* Offset into the relevant state base address where the state pool starts
668     * allocating memory.
669     */
670    int32_t start_offset;
671 
672    struct anv_state_table table;
673 
674    /* The size of blocks which will be allocated from the block pool */
675    uint32_t block_size;
676 
677    /** Free list for "back" allocations */
678    union anv_free_list back_alloc_free_list;
679 
680    struct anv_fixed_size_state_pool buckets[ANV_STATE_BUCKETS];
681 };
682 
683 struct anv_state_reserved_pool {
684    struct anv_state_pool *pool;
685    union anv_free_list reserved_blocks;
686    uint32_t count;
687 };
688 
689 struct anv_state_stream {
690    struct anv_state_pool *state_pool;
691 
692    /* The size of blocks to allocate from the state pool */
693    uint32_t block_size;
694 
695    /* Current block we're allocating from */
696    struct anv_state block;
697 
698    /* Offset into the current block at which to allocate the next state */
699    uint32_t next;
700 
701    /* List of all blocks allocated from this pool */
702    struct util_dynarray all_blocks;
703 };
704 
705 /* The block_pool functions exported for testing only.  The block pool should
706  * only be used via a state pool (see below).
707  */
708 VkResult anv_block_pool_init(struct anv_block_pool *pool,
709                              struct anv_device *device,
710                              const char *name,
711                              uint64_t start_address,
712                              uint32_t initial_size);
713 void anv_block_pool_finish(struct anv_block_pool *pool);
714 int32_t anv_block_pool_alloc(struct anv_block_pool *pool,
715                              uint32_t block_size, uint32_t *padding);
716 int32_t anv_block_pool_alloc_back(struct anv_block_pool *pool,
717                                   uint32_t block_size);
718 void* anv_block_pool_map(struct anv_block_pool *pool, int32_t offset, uint32_t
719 size);
720 
721 VkResult anv_state_pool_init(struct anv_state_pool *pool,
722                              struct anv_device *device,
723                              const char *name,
724                              uint64_t base_address,
725                              int32_t start_offset,
726                              uint32_t block_size);
727 void anv_state_pool_finish(struct anv_state_pool *pool);
728 struct anv_state anv_state_pool_alloc(struct anv_state_pool *pool,
729                                       uint32_t state_size, uint32_t alignment);
730 struct anv_state anv_state_pool_alloc_back(struct anv_state_pool *pool);
731 void anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state);
732 void anv_state_stream_init(struct anv_state_stream *stream,
733                            struct anv_state_pool *state_pool,
734                            uint32_t block_size);
735 void anv_state_stream_finish(struct anv_state_stream *stream);
736 struct anv_state anv_state_stream_alloc(struct anv_state_stream *stream,
737                                         uint32_t size, uint32_t alignment);
738 
739 void anv_state_reserved_pool_init(struct anv_state_reserved_pool *pool,
740                                       struct anv_state_pool *parent,
741                                       uint32_t count, uint32_t size,
742                                       uint32_t alignment);
743 void anv_state_reserved_pool_finish(struct anv_state_reserved_pool *pool);
744 struct anv_state anv_state_reserved_pool_alloc(struct anv_state_reserved_pool *pool);
745 void anv_state_reserved_pool_free(struct anv_state_reserved_pool *pool,
746                                   struct anv_state state);
747 
748 VkResult anv_state_table_init(struct anv_state_table *table,
749                              struct anv_device *device,
750                              uint32_t initial_entries);
751 void anv_state_table_finish(struct anv_state_table *table);
752 VkResult anv_state_table_add(struct anv_state_table *table, uint32_t *idx,
753                              uint32_t count);
754 void anv_free_list_push(union anv_free_list *list,
755                         struct anv_state_table *table,
756                         uint32_t idx, uint32_t count);
757 struct anv_state* anv_free_list_pop(union anv_free_list *list,
758                                     struct anv_state_table *table);
759 
760 
761 static inline struct anv_state *
anv_state_table_get(struct anv_state_table * table,uint32_t idx)762 anv_state_table_get(struct anv_state_table *table, uint32_t idx)
763 {
764    return &table->map[idx].state;
765 }
766 /**
767  * Implements a pool of re-usable BOs.  The interface is identical to that
768  * of block_pool except that each block is its own BO.
769  */
770 struct anv_bo_pool {
771    const char *name;
772 
773    struct anv_device *device;
774 
775    struct util_sparse_array_free_list free_list[16];
776 };
777 
778 void anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
779                       const char *name);
780 void anv_bo_pool_finish(struct anv_bo_pool *pool);
781 VkResult anv_bo_pool_alloc(struct anv_bo_pool *pool, uint32_t size,
782                            struct anv_bo **bo_out);
783 void anv_bo_pool_free(struct anv_bo_pool *pool, struct anv_bo *bo);
784 
785 struct anv_scratch_pool {
786    /* Indexed by Per-Thread Scratch Space number (the hardware value) and stage */
787    struct anv_bo *bos[16][MESA_SHADER_STAGES];
788 };
789 
790 void anv_scratch_pool_init(struct anv_device *device,
791                            struct anv_scratch_pool *pool);
792 void anv_scratch_pool_finish(struct anv_device *device,
793                              struct anv_scratch_pool *pool);
794 struct anv_bo *anv_scratch_pool_alloc(struct anv_device *device,
795                                       struct anv_scratch_pool *pool,
796                                       gl_shader_stage stage,
797                                       unsigned per_thread_scratch);
798 
799 /** Implements a BO cache that ensures a 1-1 mapping of GEM BOs to anv_bos */
800 struct anv_bo_cache {
801    struct util_sparse_array bo_map;
802    pthread_mutex_t mutex;
803 };
804 
805 VkResult anv_bo_cache_init(struct anv_bo_cache *cache,
806                            struct anv_device *device);
807 void anv_bo_cache_finish(struct anv_bo_cache *cache);
808 
809 struct anv_queue_family {
810    /* Standard bits passed on to the client */
811    VkQueueFlags   queueFlags;
812    uint32_t       queueCount;
813 
814    /* Driver internal information */
815    enum intel_engine_class engine_class;
816 };
817 
818 #define ANV_MAX_QUEUE_FAMILIES 3
819 
820 struct anv_memory_type {
821    /* Standard bits passed on to the client */
822    VkMemoryPropertyFlags   propertyFlags;
823    uint32_t                heapIndex;
824 };
825 
826 struct anv_memory_heap {
827    /* Standard bits passed on to the client */
828    VkDeviceSize      size;
829    VkMemoryHeapFlags flags;
830 
831    /** Driver-internal book-keeping.
832     *
833     * Align it to 64 bits to make atomic operations faster on 32 bit platforms.
834     */
835    alignas(8) VkDeviceSize used;
836 };
837 
838 struct anv_memregion {
839    uint64_t size;
840    uint64_t available;
841 };
842 
843 enum anv_timestamp_capture_type {
844     ANV_TIMESTAMP_CAPTURE_TOP_OF_PIPE,
845     ANV_TIMESTAMP_CAPTURE_END_OF_PIPE,
846     ANV_TIMESTAMP_CAPTURE_AT_CS_STALL,
847 };
848 
849 struct anv_physical_device {
850     struct vk_physical_device                   vk;
851 
852     /* Link in anv_instance::physical_devices */
853     struct list_head                            link;
854 
855     struct anv_instance *                       instance;
856     char                                        path[20];
857     struct intel_device_info                      info;
858     bool                                        supports_48bit_addresses;
859     struct elk_compiler *                       compiler;
860     struct isl_device                           isl_dev;
861     struct intel_perf_config *                    perf;
862    /* True if hardware support is incomplete/alpha */
863     bool                                        is_alpha;
864     /*
865      * Number of commands required to implement a performance query begin +
866      * end.
867      */
868     uint32_t                                    n_perf_query_commands;
869     int                                         cmd_parser_version;
870     bool                                        has_exec_async;
871     bool                                        has_exec_capture;
872     int                                         max_context_priority;
873     uint64_t                                    gtt_size;
874 
875     bool                                        use_relocations;
876     bool                                        use_softpin;
877     bool                                        always_use_bindless;
878     bool                                        use_call_secondary;
879 
880     /** True if we can access buffers using A64 messages */
881     bool                                        has_a64_buffer_access;
882     /** True if we can use bindless access for samplers */
883     bool                                        has_bindless_samplers;
884     /** True if we can use timeline semaphores through execbuf */
885     bool                                        has_exec_timeline;
886 
887     /** True if we can read the GPU timestamp register
888      *
889      * When running in a virtual context, the timestamp register is unreadable
890      * on Gfx12+.
891      */
892     bool                                        has_reg_timestamp;
893 
894     bool                                        always_flush_cache;
895 
896     struct {
897       uint32_t                                  family_count;
898       struct anv_queue_family                   families[ANV_MAX_QUEUE_FAMILIES];
899     } queue;
900 
901     struct {
902       uint32_t                                  type_count;
903       struct anv_memory_type                    types[VK_MAX_MEMORY_TYPES];
904       uint32_t                                  heap_count;
905       struct anv_memory_heap                    heaps[VK_MAX_MEMORY_HEAPS];
906       bool                                      need_flush;
907     } memory;
908 
909     struct anv_memregion                        sys;
910     uint8_t                                     driver_build_sha1[20];
911     uint8_t                                     pipeline_cache_uuid[VK_UUID_SIZE];
912     uint8_t                                     driver_uuid[VK_UUID_SIZE];
913     uint8_t                                     device_uuid[VK_UUID_SIZE];
914 
915     struct vk_sync_type                         sync_syncobj_type;
916     struct vk_sync_timeline_type                sync_timeline_type;
917     const struct vk_sync_type *                 sync_types[4];
918 
919     struct wsi_device                       wsi_device;
920     int                                         local_fd;
921     bool                                        has_local;
922     int64_t                                     local_major;
923     int64_t                                     local_minor;
924     int                                         master_fd;
925     bool                                        has_master;
926     int64_t                                     master_major;
927     int64_t                                     master_minor;
928     struct intel_query_engine_info *            engine_info;
929 
930     void (*cmd_emit_timestamp)(struct anv_batch *, struct anv_device *, struct anv_address, enum anv_timestamp_capture_type);
931     struct intel_measure_device                 measure_device;
932 };
933 
934 struct anv_instance {
935     struct vk_instance                          vk;
936 
937     struct driOptionCache                       dri_options;
938     struct driOptionCache                       available_dri_options;
939 
940     /**
941      * Workarounds for game bugs.
942      */
943     uint8_t                                     assume_full_subgroups;
944     bool                                        limit_trig_input_range;
945     bool                                        sample_mask_out_opengl_behaviour;
946     float                                       lower_depth_range_rate;
947     bool                                        report_vk_1_3;
948 
949     /* HW workarounds */
950     bool                                        no_16bit;
951 };
952 
953 VkResult anv_init_wsi(struct anv_physical_device *physical_device);
954 void anv_finish_wsi(struct anv_physical_device *physical_device);
955 
956 struct anv_queue {
957    struct vk_queue                           vk;
958 
959    struct anv_device *                       device;
960 
961    const struct anv_queue_family *           family;
962 
963    uint32_t                                  exec_flags;
964 
965    /** Synchronization object for debug purposes (DEBUG_SYNC) */
966    struct vk_sync                           *sync;
967 
968    struct intel_ds_queue                     ds;
969 };
970 
971 struct nir_xfb_info;
972 struct anv_pipeline_bind_map;
973 
974 extern const struct vk_pipeline_cache_object_ops *const anv_cache_import_ops[2];
975 
976 struct anv_shader_bin *
977 anv_device_search_for_kernel(struct anv_device *device,
978                              struct vk_pipeline_cache *cache,
979                              const void *key_data, uint32_t key_size,
980                              bool *user_cache_bit);
981 
982 struct anv_shader_bin *
983 anv_device_upload_kernel(struct anv_device *device,
984                          struct vk_pipeline_cache *cache,
985                          gl_shader_stage stage,
986                          const void *key_data, uint32_t key_size,
987                          const void *kernel_data, uint32_t kernel_size,
988                          const struct elk_stage_prog_data *prog_data,
989                          uint32_t prog_data_size,
990                          const struct elk_compile_stats *stats,
991                          uint32_t num_stats,
992                          const struct nir_xfb_info *xfb_info,
993                          const struct anv_pipeline_bind_map *bind_map);
994 
995 struct nir_shader;
996 struct nir_shader_compiler_options;
997 
998 struct nir_shader *
999 anv_device_search_for_nir(struct anv_device *device,
1000                           struct vk_pipeline_cache *cache,
1001                           const struct nir_shader_compiler_options *nir_options,
1002                           unsigned char sha1_key[20],
1003                           void *mem_ctx);
1004 
1005 void
1006 anv_device_upload_nir(struct anv_device *device,
1007                       struct vk_pipeline_cache *cache,
1008                       const struct nir_shader *nir,
1009                       unsigned char sha1_key[20]);
1010 
1011 struct anv_device {
1012     struct vk_device                            vk;
1013 
1014     struct anv_physical_device *                physical;
1015     const struct intel_device_info *            info;
1016     struct isl_device                           isl_dev;
1017     uint32_t                                    context_id;
1018     int                                         fd;
1019     bool                                        can_chain_batches;
1020 
1021     pthread_mutex_t                             vma_mutex;
1022     struct util_vma_heap                        vma_lo;
1023     struct util_vma_heap                        vma_cva;
1024     struct util_vma_heap                        vma_hi;
1025 
1026     /** List of all anv_device_memory objects */
1027     struct list_head                            memory_objects;
1028 
1029     struct anv_bo_pool                          batch_bo_pool;
1030     struct anv_bo_pool                          utrace_bo_pool;
1031 
1032     struct anv_bo_cache                         bo_cache;
1033 
1034     struct anv_state_pool                       general_state_pool;
1035     struct anv_state_pool                       dynamic_state_pool;
1036     struct anv_state_pool                       instruction_state_pool;
1037     struct anv_state_pool                       binding_table_pool;
1038     struct anv_state_pool                       surface_state_pool;
1039 
1040     struct anv_state_reserved_pool              custom_border_colors;
1041 
1042     /** BO used for various workarounds
1043      *
1044      * There are a number of workarounds on our hardware which require writing
1045      * data somewhere and it doesn't really matter where.  For that, we use
1046      * this BO and just write to the first dword or so.
1047      *
1048      * We also need to be able to handle NULL buffers bound as pushed UBOs.
1049      * For that, we use the high bytes (>= 1024) of the workaround BO.
1050      */
1051     struct anv_bo *                             workaround_bo;
1052     struct anv_address                          workaround_address;
1053 
1054     /**
1055      * Workarounds for game bugs.
1056      */
1057     struct {
1058        struct set *                             doom64_images;
1059     } workarounds;
1060 
1061     struct anv_bo *                             trivial_batch_bo;
1062     struct anv_state                            null_surface_state;
1063 
1064     struct vk_pipeline_cache *                  default_pipeline_cache;
1065     struct vk_pipeline_cache *                  internal_cache;
1066     struct blorp_context                        blorp;
1067 
1068     struct anv_state                            border_colors;
1069 
1070     struct anv_state                            slice_hash;
1071 
1072     uint32_t                                    queue_count;
1073     struct anv_queue  *                         queues;
1074 
1075     struct anv_scratch_pool                     scratch_pool;
1076 
1077     bool                                        robust_buffer_access;
1078 
1079     pthread_mutex_t                             mutex;
1080     pthread_cond_t                              queue_submit;
1081 
1082     struct intel_batch_decode_ctx               decoder_ctx;
1083     /*
1084      * When decoding a anv_cmd_buffer, we might need to search for BOs through
1085      * the cmd_buffer's list.
1086      */
1087     struct anv_cmd_buffer                      *cmd_buffer_being_decoded;
1088 
1089     int                                         perf_fd; /* -1 if no opened */
1090     uint64_t                                    perf_metric; /* 0 if unset */
1091 
1092     const struct intel_l3_config                *l3_config;
1093 
1094     struct intel_debug_block_frame              *debug_frame_desc;
1095 
1096     struct intel_ds_device                       ds;
1097 };
1098 
1099 static inline bool
anv_use_relocations(const struct anv_physical_device * pdevice)1100 anv_use_relocations(const struct anv_physical_device *pdevice)
1101 {
1102 #if defined(GFX_VERx10) && GFX_VERx10 < 80
1103    /* Haswell and earlier never use softpin */
1104    assert(pdevice->use_relocations);
1105    return true;
1106 #else
1107    /* If we don't have a GFX_VERx10 #define, we need to look at the physical
1108     * device.  Also, for GFX version 8, we need to look at the physical
1109     * device because Broadwell softpins but Cherryview doesn't.
1110     */
1111    return pdevice->use_relocations;
1112 #endif
1113 }
1114 
1115 static inline struct anv_state_pool *
anv_binding_table_pool(struct anv_device * device)1116 anv_binding_table_pool(struct anv_device *device)
1117 {
1118    if (anv_use_relocations(device->physical))
1119       return &device->surface_state_pool;
1120    else
1121       return &device->binding_table_pool;
1122 }
1123 
1124 static inline struct anv_state
anv_binding_table_pool_alloc(struct anv_device * device)1125 anv_binding_table_pool_alloc(struct anv_device *device)
1126 {
1127    if (anv_use_relocations(device->physical))
1128       return anv_state_pool_alloc_back(&device->surface_state_pool);
1129    else
1130       return anv_state_pool_alloc(&device->binding_table_pool,
1131                                   device->binding_table_pool.block_size, 0);
1132 }
1133 
1134 static inline void
anv_binding_table_pool_free(struct anv_device * device,struct anv_state state)1135 anv_binding_table_pool_free(struct anv_device *device, struct anv_state state) {
1136    anv_state_pool_free(anv_binding_table_pool(device), state);
1137 }
1138 
1139 static inline uint32_t
anv_mocs(const struct anv_device * device,const struct anv_bo * bo,isl_surf_usage_flags_t usage)1140 anv_mocs(const struct anv_device *device,
1141          const struct anv_bo *bo,
1142          isl_surf_usage_flags_t usage)
1143 {
1144    return isl_mocs(&device->isl_dev, usage, bo && bo->is_external);
1145 }
1146 
1147 void anv_device_init_blorp(struct anv_device *device);
1148 void anv_device_finish_blorp(struct anv_device *device);
1149 
1150 enum anv_bo_alloc_flags {
1151    /** Specifies that the BO must have a 32-bit address
1152     *
1153     * This is the opposite of EXEC_OBJECT_SUPPORTS_48B_ADDRESS.
1154     */
1155    ANV_BO_ALLOC_32BIT_ADDRESS =  (1 << 0),
1156 
1157    /** Specifies that the BO may be shared externally */
1158    ANV_BO_ALLOC_EXTERNAL =       (1 << 1),
1159 
1160    /** Specifies that the BO should be mapped */
1161    ANV_BO_ALLOC_MAPPED =         (1 << 2),
1162 
1163    /** Specifies that the BO should be snooped so we get coherency */
1164    ANV_BO_ALLOC_SNOOPED =        (1 << 3),
1165 
1166    /** Specifies that the BO should be captured in error states */
1167    ANV_BO_ALLOC_CAPTURE =        (1 << 4),
1168 
1169    /** Specifies that the BO will have an address assigned by the caller
1170     *
1171     * Such BOs do not exist in any VMA heap.
1172     */
1173    ANV_BO_ALLOC_FIXED_ADDRESS = (1 << 5),
1174 
1175    /** Enables implicit synchronization on the BO
1176     *
1177     * This is the opposite of EXEC_OBJECT_ASYNC.
1178     */
1179    ANV_BO_ALLOC_IMPLICIT_SYNC =  (1 << 6),
1180 
1181    /** Enables implicit synchronization on the BO
1182     *
1183     * This is equivalent to EXEC_OBJECT_WRITE.
1184     */
1185    ANV_BO_ALLOC_IMPLICIT_WRITE = (1 << 7),
1186 
1187    /** Has an address which is visible to the client */
1188    ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS = (1 << 8),
1189 };
1190 
1191 VkResult anv_device_alloc_bo(struct anv_device *device,
1192                              const char *name, uint64_t size,
1193                              enum anv_bo_alloc_flags alloc_flags,
1194                              uint64_t explicit_address,
1195                              struct anv_bo **bo);
1196 VkResult anv_device_map_bo(struct anv_device *device,
1197                            struct anv_bo *bo,
1198                            uint64_t offset,
1199                            size_t size,
1200                            uint32_t gem_flags,
1201                            void **map_out);
1202 void anv_device_unmap_bo(struct anv_device *device,
1203                          struct anv_bo *bo,
1204                          void *map, size_t map_size);
1205 VkResult anv_device_import_bo_from_host_ptr(struct anv_device *device,
1206                                             void *host_ptr, uint32_t size,
1207                                             enum anv_bo_alloc_flags alloc_flags,
1208                                             uint64_t client_address,
1209                                             struct anv_bo **bo_out);
1210 VkResult anv_device_import_bo(struct anv_device *device, int fd,
1211                               enum anv_bo_alloc_flags alloc_flags,
1212                               uint64_t client_address,
1213                               struct anv_bo **bo);
1214 VkResult anv_device_export_bo(struct anv_device *device,
1215                               struct anv_bo *bo, int *fd_out);
1216 VkResult anv_device_get_bo_tiling(struct anv_device *device,
1217                                   struct anv_bo *bo,
1218                                   enum isl_tiling *tiling_out);
1219 VkResult anv_device_set_bo_tiling(struct anv_device *device,
1220                                   struct anv_bo *bo,
1221                                   uint32_t row_pitch_B,
1222                                   enum isl_tiling tiling);
1223 void anv_device_release_bo(struct anv_device *device,
1224                            struct anv_bo *bo);
1225 
anv_device_set_physical(struct anv_device * device,struct anv_physical_device * physical_device)1226 static inline void anv_device_set_physical(struct anv_device *device,
1227                                            struct anv_physical_device *physical_device)
1228 {
1229    device->physical = physical_device;
1230    device->info = &physical_device->info;
1231    device->isl_dev = physical_device->isl_dev;
1232 }
1233 
1234 static inline struct anv_bo *
anv_device_lookup_bo(struct anv_device * device,uint32_t gem_handle)1235 anv_device_lookup_bo(struct anv_device *device, uint32_t gem_handle)
1236 {
1237    return util_sparse_array_get(&device->bo_cache.bo_map, gem_handle);
1238 }
1239 
1240 VkResult anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1241                          int64_t timeout);
1242 
1243 VkResult anv_queue_init(struct anv_device *device, struct anv_queue *queue,
1244                         uint32_t exec_flags,
1245                         const VkDeviceQueueCreateInfo *pCreateInfo,
1246                         uint32_t index_in_family);
1247 void anv_queue_finish(struct anv_queue *queue);
1248 
1249 VkResult anv_queue_submit(struct vk_queue *queue,
1250                           struct vk_queue_submit *submit);
1251 VkResult anv_queue_submit_simple_batch(struct anv_queue *queue,
1252                                        struct anv_batch *batch);
1253 
1254 void* anv_gem_mmap(struct anv_device *device,
1255                    uint32_t gem_handle, uint64_t offset, uint64_t size, uint32_t flags);
1256 void anv_gem_munmap(struct anv_device *device, void *p, uint64_t size);
1257 uint32_t anv_gem_create(struct anv_device *device, uint64_t size);
1258 void anv_gem_close(struct anv_device *device, uint32_t gem_handle);
1259 uint32_t anv_gem_userptr(struct anv_device *device, void *mem, size_t size);
1260 int anv_gem_wait(struct anv_device *device, uint32_t gem_handle, int64_t *timeout_ns);
1261 int anv_gem_execbuffer(struct anv_device *device,
1262                        struct drm_i915_gem_execbuffer2 *execbuf);
1263 int anv_gem_set_tiling(struct anv_device *device, uint32_t gem_handle,
1264                        uint32_t stride, uint32_t tiling);
1265 bool anv_gem_has_context_priority(int fd, int priority);
1266 int anv_gem_set_context_param(int fd, uint32_t context, uint32_t param,
1267                               uint64_t value);
1268 int anv_gem_get_tiling(struct anv_device *device, uint32_t gem_handle);
1269 int anv_gem_context_get_reset_stats(int fd, int context,
1270                                     uint32_t *active, uint32_t *pending);
1271 int anv_gem_handle_to_fd(struct anv_device *device, uint32_t gem_handle);
1272 uint32_t anv_gem_fd_to_handle(struct anv_device *device, int fd);
1273 int anv_gem_set_caching(struct anv_device *device, uint32_t gem_handle, uint32_t caching);
1274 
1275 uint64_t anv_vma_alloc(struct anv_device *device,
1276                        uint64_t size, uint64_t align,
1277                        enum anv_bo_alloc_flags alloc_flags,
1278                        uint64_t client_address);
1279 void anv_vma_free(struct anv_device *device,
1280                   uint64_t address, uint64_t size);
1281 
1282 struct anv_reloc_list {
1283    uint32_t                                     num_relocs;
1284    uint32_t                                     array_length;
1285    struct drm_i915_gem_relocation_entry *       relocs;
1286    struct anv_bo **                             reloc_bos;
1287    uint32_t                                     dep_words;
1288    BITSET_WORD *                                deps;
1289 };
1290 
1291 VkResult anv_reloc_list_init(struct anv_reloc_list *list,
1292                              const VkAllocationCallbacks *alloc);
1293 void anv_reloc_list_finish(struct anv_reloc_list *list,
1294                            const VkAllocationCallbacks *alloc);
1295 
1296 VkResult anv_reloc_list_add(struct anv_reloc_list *list,
1297                             const VkAllocationCallbacks *alloc,
1298                             uint32_t offset, struct anv_bo *target_bo,
1299                             uint32_t delta, uint64_t *address_u64_out);
1300 
1301 VkResult anv_reloc_list_add_bo(struct anv_reloc_list *list,
1302                                const VkAllocationCallbacks *alloc,
1303                                struct anv_bo *target_bo);
1304 
1305 struct anv_batch_bo {
1306    /* Link in the anv_cmd_buffer.owned_batch_bos list */
1307    struct list_head                             link;
1308 
1309    struct anv_bo *                              bo;
1310 
1311    /* Bytes actually consumed in this batch BO */
1312    uint32_t                                     length;
1313 
1314    /* When this batch BO is used as part of a primary batch buffer, this
1315     * tracked whether it is chained to another primary batch buffer.
1316     *
1317     * If this is the case, the relocation list's last entry points the
1318     * location of the MI_BATCH_BUFFER_START chaining to the next batch.
1319     */
1320    bool                                         chained;
1321 
1322    struct anv_reloc_list                        relocs;
1323 };
1324 
1325 struct anv_batch {
1326    const VkAllocationCallbacks *                alloc;
1327 
1328    struct anv_address                           start_addr;
1329 
1330    void *                                       start;
1331    void *                                       end;
1332    void *                                       next;
1333 
1334    struct anv_reloc_list *                      relocs;
1335 
1336    /* This callback is called (with the associated user data) in the event
1337     * that the batch runs out of space.
1338     */
1339    VkResult (*extend_cb)(struct anv_batch *, void *);
1340    void *                                       user_data;
1341 
1342    /**
1343     * Current error status of the command buffer. Used to track inconsistent
1344     * or incomplete command buffer states that are the consequence of run-time
1345     * errors such as out of memory scenarios. We want to track this in the
1346     * batch because the command buffer object is not visible to some parts
1347     * of the driver.
1348     */
1349    VkResult                                     status;
1350 };
1351 
1352 void *anv_batch_emit_dwords(struct anv_batch *batch, int num_dwords);
1353 void anv_batch_emit_batch(struct anv_batch *batch, struct anv_batch *other);
1354 struct anv_address anv_batch_address(struct anv_batch *batch, void *batch_location);
1355 
1356 static inline void
anv_batch_set_storage(struct anv_batch * batch,struct anv_address addr,void * map,size_t size)1357 anv_batch_set_storage(struct anv_batch *batch, struct anv_address addr,
1358                       void *map, size_t size)
1359 {
1360    batch->start_addr = addr;
1361    batch->next = batch->start = map;
1362    batch->end = map + size;
1363 }
1364 
1365 static inline VkResult
anv_batch_set_error(struct anv_batch * batch,VkResult error)1366 anv_batch_set_error(struct anv_batch *batch, VkResult error)
1367 {
1368    assert(error != VK_SUCCESS);
1369    if (batch->status == VK_SUCCESS)
1370       batch->status = error;
1371    return batch->status;
1372 }
1373 
1374 static inline bool
anv_batch_has_error(struct anv_batch * batch)1375 anv_batch_has_error(struct anv_batch *batch)
1376 {
1377    return batch->status != VK_SUCCESS;
1378 }
1379 
1380 static inline uint64_t
anv_batch_emit_reloc(struct anv_batch * batch,void * location,struct anv_bo * bo,uint32_t delta)1381 anv_batch_emit_reloc(struct anv_batch *batch,
1382                      void *location, struct anv_bo *bo, uint32_t delta)
1383 {
1384    uint64_t address_u64 = 0;
1385    VkResult result = anv_reloc_list_add(batch->relocs, batch->alloc,
1386                                         location - batch->start, bo, delta,
1387                                         &address_u64);
1388    if (unlikely(result != VK_SUCCESS)) {
1389       anv_batch_set_error(batch, result);
1390       return 0;
1391    }
1392 
1393    return address_u64;
1394 }
1395 
1396 static inline void
write_reloc(const struct anv_device * device,void * p,uint64_t v,bool flush)1397 write_reloc(const struct anv_device *device, void *p, uint64_t v, bool flush)
1398 {
1399    UNUSED unsigned reloc_size = 0;
1400    if (device->info->ver >= 8) {
1401       reloc_size = sizeof(uint64_t);
1402       *(uint64_t *)p = intel_canonical_address(v);
1403    } else {
1404       reloc_size = sizeof(uint32_t);
1405       *(uint32_t *)p = v;
1406    }
1407 
1408 #ifdef SUPPORT_INTEL_INTEGRATED_GPUS
1409    if (flush && device->physical->memory.need_flush)
1410       intel_flush_range(p, reloc_size);
1411 #endif
1412 }
1413 
1414 static inline uint64_t
_anv_combine_address(struct anv_batch * batch,void * location,const struct anv_address address,uint32_t delta)1415 _anv_combine_address(struct anv_batch *batch, void *location,
1416                      const struct anv_address address, uint32_t delta)
1417 {
1418    if (address.bo == NULL) {
1419       return address.offset + delta;
1420    } else if (batch == NULL) {
1421       assert(anv_bo_is_pinned(address.bo));
1422       return anv_address_physical(anv_address_add(address, delta));
1423    } else {
1424       assert(batch->start <= location && location < batch->end);
1425       /* i915 relocations are signed. */
1426       assert(INT32_MIN <= address.offset && address.offset <= INT32_MAX);
1427       return anv_batch_emit_reloc(batch, location, address.bo, address.offset + delta);
1428    }
1429 }
1430 
1431 #define __gen_address_type struct anv_address
1432 #define __gen_user_data struct anv_batch
1433 #define __gen_combine_address _anv_combine_address
1434 
1435 /* Wrapper macros needed to work around preprocessor argument issues.  In
1436  * particular, arguments don't get pre-evaluated if they are concatenated.
1437  * This means that, if you pass GENX(3DSTATE_PS) into the emit macro, the
1438  * GENX macro won't get evaluated if the emit macro contains "cmd ## foo".
1439  * We can work around this easily enough with these helpers.
1440  */
1441 #define __anv_cmd_length(cmd) cmd ## _length
1442 #define __anv_cmd_length_bias(cmd) cmd ## _length_bias
1443 #define __anv_cmd_header(cmd) cmd ## _header
1444 #define __anv_cmd_pack(cmd) cmd ## _pack
1445 #define __anv_reg_num(reg) reg ## _num
1446 
1447 #define anv_pack_struct(dst, struc, ...) do {                              \
1448       struct struc __template = {                                          \
1449          __VA_ARGS__                                                       \
1450       };                                                                   \
1451       __anv_cmd_pack(struc)(NULL, dst, &__template);                       \
1452       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dst, __anv_cmd_length(struc) * 4)); \
1453    } while (0)
1454 
1455 #define anv_batch_emitn(batch, n, cmd, ...) ({             \
1456       void *__dst = anv_batch_emit_dwords(batch, n);       \
1457       if (__dst) {                                         \
1458          struct cmd __template = {                         \
1459             __anv_cmd_header(cmd),                         \
1460            .DWordLength = n - __anv_cmd_length_bias(cmd),  \
1461             __VA_ARGS__                                    \
1462          };                                                \
1463          __anv_cmd_pack(cmd)(batch, __dst, &__template);   \
1464       }                                                    \
1465       __dst;                                               \
1466    })
1467 
1468 #define anv_batch_emit_merge(batch, dwords0, dwords1)                   \
1469    do {                                                                 \
1470       uint32_t *dw;                                                     \
1471                                                                         \
1472       STATIC_ASSERT(ARRAY_SIZE(dwords0) == ARRAY_SIZE(dwords1));        \
1473       dw = anv_batch_emit_dwords((batch), ARRAY_SIZE(dwords0));         \
1474       if (!dw)                                                          \
1475          break;                                                         \
1476       for (uint32_t i = 0; i < ARRAY_SIZE(dwords0); i++)                \
1477          dw[i] = (dwords0)[i] | (dwords1)[i];                           \
1478       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dw, ARRAY_SIZE(dwords0) * 4));\
1479    } while (0)
1480 
1481 #define anv_batch_emit(batch, cmd, name)                            \
1482    for (struct cmd name = { __anv_cmd_header(cmd) },                    \
1483         *_dst = anv_batch_emit_dwords(batch, __anv_cmd_length(cmd));    \
1484         __builtin_expect(_dst != NULL, 1);                              \
1485         ({ __anv_cmd_pack(cmd)(batch, _dst, &name);                     \
1486            VG(VALGRIND_CHECK_MEM_IS_DEFINED(_dst, __anv_cmd_length(cmd) * 4)); \
1487            _dst = NULL;                                                 \
1488          }))
1489 
1490 #define anv_batch_write_reg(batch, reg, name)                           \
1491    for (struct reg name = {}, *_cont = (struct reg *)1; _cont != NULL;  \
1492         ({                                                              \
1493             uint32_t _dw[__anv_cmd_length(reg)];                        \
1494             __anv_cmd_pack(reg)(NULL, _dw, &name);                      \
1495             for (unsigned i = 0; i < __anv_cmd_length(reg); i++) {      \
1496                anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) { \
1497                   lri.RegisterOffset   = __anv_reg_num(reg);            \
1498                   lri.DataDWord        = _dw[i];                        \
1499                }                                                        \
1500             }                                                           \
1501            _cont = NULL;                                                \
1502          }))
1503 
1504 /* #define __gen_get_batch_dwords anv_batch_emit_dwords */
1505 /* #define __gen_get_batch_address anv_batch_address */
1506 /* #define __gen_address_value anv_address_physical */
1507 /* #define __gen_address_offset anv_address_add */
1508 
1509 struct anv_device_memory {
1510    struct vk_object_base                        base;
1511 
1512    struct list_head                             link;
1513 
1514    struct anv_bo *                              bo;
1515    const struct anv_memory_type *               type;
1516 
1517    void *                                       map;
1518    size_t                                       map_size;
1519 
1520    /* The map, from the user PoV is map + map_delta */
1521    uint64_t                                     map_delta;
1522 
1523    /* If set, we are holding reference to AHardwareBuffer
1524     * which we must release when memory is freed.
1525     */
1526    struct AHardwareBuffer *                     ahw;
1527 
1528    /* If set, this memory comes from a host pointer. */
1529    void *                                       host_ptr;
1530 };
1531 
1532 /**
1533  * Header for Vertex URB Entry (VUE)
1534  */
1535 struct anv_vue_header {
1536    uint32_t Reserved;
1537    uint32_t RTAIndex; /* RenderTargetArrayIndex */
1538    uint32_t ViewportIndex;
1539    float PointWidth;
1540 };
1541 
1542 /** Struct representing a sampled image descriptor
1543  *
1544  * This descriptor layout is used for sampled images, bare sampler, and
1545  * combined image/sampler descriptors.
1546  */
1547 struct anv_sampled_image_descriptor {
1548    /** Bindless image handle
1549     *
1550     * This is expected to already be shifted such that the 20-bit
1551     * SURFACE_STATE table index is in the top 20 bits.
1552     */
1553    uint32_t image;
1554 
1555    /** Bindless sampler handle
1556     *
1557     * This is assumed to be a 32B-aligned SAMPLER_STATE pointer relative
1558     * to the dynamic state base address.
1559     */
1560    uint32_t sampler;
1561 };
1562 
1563 struct anv_texture_swizzle_descriptor {
1564    /** Texture swizzle
1565     *
1566     * See also nir_intrinsic_channel_select_intel
1567     */
1568    uint8_t swizzle[4];
1569 
1570    /** Unused padding to ensure the struct is a multiple of 64 bits */
1571    uint32_t _pad;
1572 };
1573 
1574 /** Struct representing a storage image descriptor */
1575 struct anv_storage_image_descriptor {
1576    /** Bindless image handles
1577     *
1578     * These are expected to already be shifted such that the 20-bit
1579     * SURFACE_STATE table index is in the top 20 bits.
1580     */
1581    uint32_t vanilla;
1582    uint32_t lowered;
1583 };
1584 
1585 /** Struct representing a address/range descriptor
1586  *
1587  * The fields of this struct correspond directly to the data layout of
1588  * nir_address_format_64bit_bounded_global addresses.  The last field is the
1589  * offset in the NIR address so it must be zero so that when you load the
1590  * descriptor you get a pointer to the start of the range.
1591  */
1592 struct anv_address_range_descriptor {
1593    uint64_t address;
1594    uint32_t range;
1595    uint32_t zero;
1596 };
1597 
1598 enum anv_descriptor_data {
1599    /** The descriptor contains a BTI reference to a surface state */
1600    ANV_DESCRIPTOR_SURFACE_STATE  = (1 << 0),
1601    /** The descriptor contains a BTI reference to a sampler state */
1602    ANV_DESCRIPTOR_SAMPLER_STATE  = (1 << 1),
1603    /** The descriptor contains an actual buffer view */
1604    ANV_DESCRIPTOR_BUFFER_VIEW    = (1 << 2),
1605    /** The descriptor contains auxiliary image layout data */
1606    ANV_DESCRIPTOR_IMAGE_PARAM    = (1 << 3),
1607    /** The descriptor contains auxiliary image layout data */
1608    ANV_DESCRIPTOR_INLINE_UNIFORM = (1 << 4),
1609    /** anv_address_range_descriptor with a buffer address and range */
1610    ANV_DESCRIPTOR_ADDRESS_RANGE  = (1 << 5),
1611    /** Bindless surface handle */
1612    ANV_DESCRIPTOR_SAMPLED_IMAGE  = (1 << 6),
1613    /** Storage image handles */
1614    ANV_DESCRIPTOR_STORAGE_IMAGE  = (1 << 7),
1615    /** Storage image handles */
1616    ANV_DESCRIPTOR_TEXTURE_SWIZZLE  = (1 << 8),
1617 };
1618 
1619 struct anv_descriptor_set_binding_layout {
1620    /* The type of the descriptors in this binding */
1621    VkDescriptorType type;
1622 
1623    /* Flags provided when this binding was created */
1624    VkDescriptorBindingFlags flags;
1625 
1626    /* Bitfield representing the type of data this descriptor contains */
1627    enum anv_descriptor_data data;
1628 
1629    /* Maximum number of YCbCr texture/sampler planes */
1630    uint8_t max_plane_count;
1631 
1632    /* Number of array elements in this binding (or size in bytes for inline
1633     * uniform data)
1634     */
1635    uint32_t array_size;
1636 
1637    /* Index into the flattened descriptor set */
1638    uint32_t descriptor_index;
1639 
1640    /* Index into the dynamic state array for a dynamic buffer */
1641    int16_t dynamic_offset_index;
1642 
1643    /* Index into the descriptor set buffer views */
1644    int32_t buffer_view_index;
1645 
1646    /* Offset into the descriptor buffer where this descriptor lives */
1647    uint32_t descriptor_offset;
1648 
1649    /* Pre computed stride */
1650    unsigned descriptor_stride;
1651 
1652    /* Immutable samplers (or NULL if no immutable samplers) */
1653    struct anv_sampler **immutable_samplers;
1654 };
1655 
1656 bool anv_descriptor_supports_bindless(const struct anv_physical_device *pdevice,
1657                                       const struct anv_descriptor_set_binding_layout *binding,
1658                                       bool sampler);
1659 
1660 bool anv_descriptor_requires_bindless(const struct anv_physical_device *pdevice,
1661                                       const struct anv_descriptor_set_binding_layout *binding,
1662                                       bool sampler);
1663 
1664 struct anv_descriptor_set_layout {
1665    struct vk_object_base base;
1666 
1667    /* Descriptor set layouts can be destroyed at almost any time */
1668    uint32_t ref_cnt;
1669 
1670    /* Number of bindings in this descriptor set */
1671    uint32_t binding_count;
1672 
1673    /* Total number of descriptors */
1674    uint32_t descriptor_count;
1675 
1676    /* Shader stages affected by this descriptor set */
1677    uint16_t shader_stages;
1678 
1679    /* Number of buffer views in this descriptor set */
1680    uint32_t buffer_view_count;
1681 
1682    /* Number of dynamic offsets used by this descriptor set */
1683    uint16_t dynamic_offset_count;
1684 
1685    /* For each dynamic buffer, which VkShaderStageFlagBits stages are using
1686     * this buffer
1687     */
1688    VkShaderStageFlags dynamic_offset_stages[MAX_DYNAMIC_BUFFERS];
1689 
1690    /* Size of the descriptor buffer for this descriptor set */
1691    uint32_t descriptor_buffer_size;
1692 
1693    /* Bindings in this descriptor set */
1694    struct anv_descriptor_set_binding_layout binding[0];
1695 };
1696 
1697 void anv_descriptor_set_layout_destroy(struct anv_device *device,
1698                                        struct anv_descriptor_set_layout *layout);
1699 
1700 static inline void
anv_descriptor_set_layout_ref(struct anv_descriptor_set_layout * layout)1701 anv_descriptor_set_layout_ref(struct anv_descriptor_set_layout *layout)
1702 {
1703    assert(layout && layout->ref_cnt >= 1);
1704    p_atomic_inc(&layout->ref_cnt);
1705 }
1706 
1707 static inline void
anv_descriptor_set_layout_unref(struct anv_device * device,struct anv_descriptor_set_layout * layout)1708 anv_descriptor_set_layout_unref(struct anv_device *device,
1709                                 struct anv_descriptor_set_layout *layout)
1710 {
1711    assert(layout && layout->ref_cnt >= 1);
1712    if (p_atomic_dec_zero(&layout->ref_cnt))
1713       anv_descriptor_set_layout_destroy(device, layout);
1714 }
1715 
1716 struct anv_descriptor {
1717    VkDescriptorType type;
1718 
1719    union {
1720       struct {
1721          VkImageLayout layout;
1722          struct anv_image_view *image_view;
1723          struct anv_sampler *sampler;
1724       };
1725 
1726       struct {
1727          struct anv_buffer_view *set_buffer_view;
1728          struct anv_buffer *buffer;
1729          uint64_t offset;
1730          uint64_t range;
1731       };
1732 
1733       struct anv_buffer_view *buffer_view;
1734    };
1735 };
1736 
1737 struct anv_descriptor_set {
1738    struct vk_object_base base;
1739 
1740    struct anv_descriptor_pool *pool;
1741    struct anv_descriptor_set_layout *layout;
1742 
1743    /* Amount of space occupied in the the pool by this descriptor set. It can
1744     * be larger than the size of the descriptor set.
1745     */
1746    uint32_t size;
1747 
1748    /* State relative to anv_descriptor_pool::bo */
1749    struct anv_state desc_mem;
1750    /* Surface state for the descriptor buffer */
1751    struct anv_state desc_surface_state;
1752 
1753    /* Descriptor set address. */
1754    struct anv_address desc_addr;
1755 
1756    uint32_t buffer_view_count;
1757    struct anv_buffer_view *buffer_views;
1758 
1759    /* Link to descriptor pool's desc_sets list . */
1760    struct list_head pool_link;
1761 
1762    uint32_t descriptor_count;
1763    struct anv_descriptor descriptors[0];
1764 };
1765 
1766 static inline bool
anv_descriptor_set_is_push(struct anv_descriptor_set * set)1767 anv_descriptor_set_is_push(struct anv_descriptor_set *set)
1768 {
1769    return set->pool == NULL;
1770 }
1771 
1772 struct anv_buffer_view {
1773    struct vk_object_base base;
1774 
1775    uint64_t range; /**< VkBufferViewCreateInfo::range */
1776 
1777    struct anv_address address;
1778 
1779    struct anv_state surface_state;
1780    struct anv_state storage_surface_state;
1781    struct anv_state lowered_storage_surface_state;
1782 
1783    struct isl_image_param lowered_storage_image_param;
1784 };
1785 
1786 struct anv_push_descriptor_set {
1787    struct anv_descriptor_set set;
1788 
1789    /* Put this field right behind anv_descriptor_set so it fills up the
1790     * descriptors[0] field. */
1791    struct anv_descriptor descriptors[MAX_PUSH_DESCRIPTORS];
1792 
1793    /** True if the descriptor set buffer has been referenced by a draw or
1794     * dispatch command.
1795     */
1796    bool set_used_on_gpu;
1797 
1798    struct anv_buffer_view buffer_views[MAX_PUSH_DESCRIPTORS];
1799 };
1800 
1801 static inline struct anv_address
anv_descriptor_set_address(struct anv_descriptor_set * set)1802 anv_descriptor_set_address(struct anv_descriptor_set *set)
1803 {
1804    if (anv_descriptor_set_is_push(set)) {
1805       /* We have to flag push descriptor set as used on the GPU
1806        * so that the next time we push descriptors, we grab a new memory.
1807        */
1808       struct anv_push_descriptor_set *push_set =
1809          (struct anv_push_descriptor_set *)set;
1810       push_set->set_used_on_gpu = true;
1811    }
1812 
1813    return set->desc_addr;
1814 }
1815 
1816 struct anv_descriptor_pool {
1817    struct vk_object_base base;
1818 
1819    uint32_t size;
1820    uint32_t next;
1821    uint32_t free_list;
1822 
1823    struct anv_bo *bo;
1824    struct util_vma_heap bo_heap;
1825 
1826    struct anv_state_stream surface_state_stream;
1827    void *surface_state_free_list;
1828 
1829    struct list_head desc_sets;
1830 
1831    bool host_only;
1832 
1833    char data[0];
1834 };
1835 
1836 size_t
1837 anv_descriptor_set_layout_size(const struct anv_descriptor_set_layout *layout,
1838                                uint32_t var_desc_count);
1839 
1840 uint32_t
1841 anv_descriptor_set_layout_descriptor_buffer_size(const struct anv_descriptor_set_layout *set_layout,
1842                                                  uint32_t var_desc_count);
1843 
1844 void
1845 anv_descriptor_set_write_image_view(struct anv_device *device,
1846                                     struct anv_descriptor_set *set,
1847                                     const VkDescriptorImageInfo * const info,
1848                                     VkDescriptorType type,
1849                                     uint32_t binding,
1850                                     uint32_t element);
1851 
1852 void
1853 anv_descriptor_set_write_buffer_view(struct anv_device *device,
1854                                      struct anv_descriptor_set *set,
1855                                      VkDescriptorType type,
1856                                      struct anv_buffer_view *buffer_view,
1857                                      uint32_t binding,
1858                                      uint32_t element);
1859 
1860 void
1861 anv_descriptor_set_write_buffer(struct anv_device *device,
1862                                 struct anv_descriptor_set *set,
1863                                 struct anv_state_stream *alloc_stream,
1864                                 VkDescriptorType type,
1865                                 struct anv_buffer *buffer,
1866                                 uint32_t binding,
1867                                 uint32_t element,
1868                                 VkDeviceSize offset,
1869                                 VkDeviceSize range);
1870 
1871 void
1872 anv_descriptor_set_write_inline_uniform_data(struct anv_device *device,
1873                                              struct anv_descriptor_set *set,
1874                                              uint32_t binding,
1875                                              const void *data,
1876                                              size_t offset,
1877                                              size_t size);
1878 
1879 void
1880 anv_descriptor_set_write_template(struct anv_device *device,
1881                                   struct anv_descriptor_set *set,
1882                                   struct anv_state_stream *alloc_stream,
1883                                   const struct vk_descriptor_update_template *template,
1884                                   const void *data);
1885 
1886 #define ANV_DESCRIPTOR_SET_NULL             (UINT8_MAX - 5)
1887 #define ANV_DESCRIPTOR_SET_PUSH_CONSTANTS   (UINT8_MAX - 4)
1888 #define ANV_DESCRIPTOR_SET_DESCRIPTORS      (UINT8_MAX - 3)
1889 #define ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS  (UINT8_MAX - 2)
1890 #define ANV_DESCRIPTOR_SET_SHADER_CONSTANTS (UINT8_MAX - 1)
1891 #define ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS UINT8_MAX
1892 
1893 struct anv_pipeline_binding {
1894    /** Index in the descriptor set
1895     *
1896     * This is a flattened index; the descriptor set layout is already taken
1897     * into account.
1898     */
1899    uint32_t index;
1900 
1901    /** The descriptor set this surface corresponds to.
1902     *
1903     * The special ANV_DESCRIPTOR_SET_* values above indicates that this
1904     * binding is not a normal descriptor set but something else.
1905     */
1906    uint8_t set;
1907 
1908    union {
1909       /** Plane in the binding index for images */
1910       uint8_t plane;
1911 
1912       /** Dynamic offset index (for dynamic UBOs and SSBOs) */
1913       uint8_t dynamic_offset_index;
1914    };
1915 
1916    /** For a storage image, whether it requires a lowered surface */
1917    uint8_t lowered_storage_surface;
1918 
1919    /** Pad to 64 bits so that there are no holes and we can safely memcmp
1920     * assuming POD zero-initialization.
1921     */
1922    uint8_t pad;
1923 };
1924 
1925 struct anv_push_range {
1926    /** Index in the descriptor set */
1927    uint32_t index;
1928 
1929    /** Descriptor set index */
1930    uint8_t set;
1931 
1932    /** Dynamic offset index (for dynamic UBOs) */
1933    uint8_t dynamic_offset_index;
1934 
1935    /** Start offset in units of 32B */
1936    uint8_t start;
1937 
1938    /** Range in units of 32B */
1939    uint8_t length;
1940 };
1941 
1942 struct anv_pipeline_layout {
1943    struct vk_object_base base;
1944 
1945    struct {
1946       struct anv_descriptor_set_layout *layout;
1947       uint32_t dynamic_offset_start;
1948    } set[MAX_SETS];
1949 
1950    uint32_t num_sets;
1951 
1952    unsigned char sha1[20];
1953 };
1954 
1955 struct anv_buffer {
1956    struct vk_buffer vk;
1957 
1958    /* Set when bound */
1959    struct anv_address address;
1960 };
1961 
1962 enum anv_cmd_dirty_bits {
1963    ANV_CMD_DIRTY_PIPELINE                            = 1 << 0,
1964    ANV_CMD_DIRTY_INDEX_BUFFER                        = 1 << 1,
1965    ANV_CMD_DIRTY_RENDER_TARGETS                      = 1 << 2,
1966    ANV_CMD_DIRTY_XFB_ENABLE                          = 1 << 3,
1967 };
1968 typedef enum anv_cmd_dirty_bits anv_cmd_dirty_mask_t;
1969 
1970 enum anv_pipe_bits {
1971    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT            = (1 << 0),
1972    ANV_PIPE_STALL_AT_SCOREBOARD_BIT          = (1 << 1),
1973    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT       = (1 << 2),
1974    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT    = (1 << 3),
1975    ANV_PIPE_VF_CACHE_INVALIDATE_BIT          = (1 << 4),
1976    ANV_PIPE_DATA_CACHE_FLUSH_BIT             = (1 << 5),
1977    ANV_PIPE_TILE_CACHE_FLUSH_BIT             = (1 << 6),
1978    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT     = (1 << 10),
1979    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT = (1 << 11),
1980    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT    = (1 << 12),
1981    ANV_PIPE_DEPTH_STALL_BIT                  = (1 << 13),
1982 
1983    /* ANV_PIPE_HDC_PIPELINE_FLUSH_BIT is a precise way to ensure prior data
1984     * cache work has completed.  Available on Gfx12+.  For earlier Gfx we
1985     * must reinterpret this flush as ANV_PIPE_DATA_CACHE_FLUSH_BIT.
1986     */
1987    ANV_PIPE_HDC_PIPELINE_FLUSH_BIT           = (1 << 14),
1988    ANV_PIPE_PSS_STALL_SYNC_BIT               = (1 << 15),
1989 
1990    /*
1991     * This bit flush data-port's Untyped L1 data cache (LSC L1).
1992     */
1993    ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT = (1 << 16),
1994 
1995    ANV_PIPE_CS_STALL_BIT                     = (1 << 20),
1996    ANV_PIPE_END_OF_PIPE_SYNC_BIT             = (1 << 21),
1997 
1998    /* This bit does not exist directly in PIPE_CONTROL.  Instead it means that
1999     * a flush has happened but not a CS stall.  The next time we do any sort
2000     * of invalidation we need to insert a CS stall at that time.  Otherwise,
2001     * we would have to CS stall on every flush which could be bad.
2002     */
2003    ANV_PIPE_NEEDS_END_OF_PIPE_SYNC_BIT       = (1 << 22),
2004 
2005    /* This bit does not exist directly in PIPE_CONTROL. It means that render
2006     * target operations related to transfer commands with VkBuffer as
2007     * destination are ongoing. Some operations like copies on the command
2008     * streamer might need to be aware of this to trigger the appropriate stall
2009     * before they can proceed with the copy.
2010     */
2011    ANV_PIPE_RENDER_TARGET_BUFFER_WRITES      = (1 << 23),
2012 
2013    /* This bit does not exist directly in PIPE_CONTROL. It means that Gfx12
2014     * AUX-TT data has changed and we need to invalidate AUX-TT data.  This is
2015     * done by writing the AUX-TT register.
2016     */
2017    ANV_PIPE_AUX_TABLE_INVALIDATE_BIT         = (1 << 24),
2018 
2019    /* This bit does not exist directly in PIPE_CONTROL. It means that a
2020     * PIPE_CONTROL with a post-sync operation will follow. This is used to
2021     * implement a workaround for Gfx9.
2022     */
2023    ANV_PIPE_POST_SYNC_BIT                    = (1 << 25),
2024 };
2025 
2026 #define ANV_PIPE_FLUSH_BITS ( \
2027    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT | \
2028    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
2029    ANV_PIPE_HDC_PIPELINE_FLUSH_BIT | \
2030    ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT | \
2031    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | \
2032    ANV_PIPE_TILE_CACHE_FLUSH_BIT)
2033 
2034 #define ANV_PIPE_STALL_BITS ( \
2035    ANV_PIPE_STALL_AT_SCOREBOARD_BIT | \
2036    ANV_PIPE_DEPTH_STALL_BIT | \
2037    ANV_PIPE_CS_STALL_BIT)
2038 
2039 #define ANV_PIPE_INVALIDATE_BITS ( \
2040    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT | \
2041    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT | \
2042    ANV_PIPE_VF_CACHE_INVALIDATE_BIT | \
2043    ANV_PIPE_HDC_PIPELINE_FLUSH_BIT | \
2044    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT | \
2045    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT | \
2046    ANV_PIPE_AUX_TABLE_INVALIDATE_BIT)
2047 
2048 enum intel_ds_stall_flag
2049 anv_pipe_flush_bit_to_ds_stall_flag(enum anv_pipe_bits bits);
2050 
2051 static inline enum anv_pipe_bits
anv_pipe_flush_bits_for_access_flags(struct anv_device * device,VkAccessFlags2 flags)2052 anv_pipe_flush_bits_for_access_flags(struct anv_device *device,
2053                                      VkAccessFlags2 flags)
2054 {
2055    enum anv_pipe_bits pipe_bits = 0;
2056 
2057    u_foreach_bit64(b, flags) {
2058       switch ((VkAccessFlags2)BITFIELD64_BIT(b)) {
2059       case VK_ACCESS_2_SHADER_WRITE_BIT:
2060       case VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT:
2061          /* We're transitioning a buffer that was previously used as write
2062           * destination through the data port. To make its content available
2063           * to future operations, flush the hdc pipeline.
2064           */
2065          pipe_bits |= ANV_PIPE_HDC_PIPELINE_FLUSH_BIT;
2066          pipe_bits |= ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT;
2067          break;
2068       case VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT:
2069          /* We're transitioning a buffer that was previously used as render
2070           * target. To make its content available to future operations, flush
2071           * the render target cache.
2072           */
2073          pipe_bits |= ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
2074          break;
2075       case VK_ACCESS_2_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT:
2076          /* We're transitioning a buffer that was previously used as depth
2077           * buffer. To make its content available to future operations, flush
2078           * the depth cache.
2079           */
2080          pipe_bits |= ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
2081          break;
2082       case VK_ACCESS_2_TRANSFER_WRITE_BIT:
2083          /* We're transitioning a buffer that was previously used as a
2084           * transfer write destination. Generic write operations include color
2085           * & depth operations as well as buffer operations like :
2086           *     - vkCmdClearColorImage()
2087           *     - vkCmdClearDepthStencilImage()
2088           *     - vkCmdBlitImage()
2089           *     - vkCmdCopy*(), vkCmdUpdate*(), vkCmdFill*()
2090           *
2091           * Most of these operations are implemented using Blorp which writes
2092           * through the render target, so flush that cache to make it visible
2093           * to future operations. And for depth related operations we also
2094           * need to flush the depth cache.
2095           */
2096          pipe_bits |= ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
2097          pipe_bits |= ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
2098          break;
2099       case VK_ACCESS_2_MEMORY_WRITE_BIT:
2100          /* We're transitioning a buffer for generic write operations. Flush
2101           * all the caches.
2102           */
2103          pipe_bits |= ANV_PIPE_FLUSH_BITS;
2104          break;
2105       case VK_ACCESS_2_HOST_WRITE_BIT:
2106          /* We're transitioning a buffer for access by CPU. Invalidate
2107           * all the caches. Since data and tile caches don't have invalidate,
2108           * we are forced to flush those as well.
2109           */
2110          pipe_bits |= ANV_PIPE_FLUSH_BITS;
2111          pipe_bits |= ANV_PIPE_INVALIDATE_BITS;
2112          break;
2113       case VK_ACCESS_2_TRANSFORM_FEEDBACK_WRITE_BIT_EXT:
2114       case VK_ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT:
2115          /* We're transitioning a buffer written either from VS stage or from
2116           * the command streamer (see CmdEndTransformFeedbackEXT), we just
2117           * need to stall the CS.
2118           */
2119          pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2120          break;
2121       default:
2122          break; /* Nothing to do */
2123       }
2124    }
2125 
2126    return pipe_bits;
2127 }
2128 
2129 static inline enum anv_pipe_bits
anv_pipe_invalidate_bits_for_access_flags(struct anv_device * device,VkAccessFlags2 flags)2130 anv_pipe_invalidate_bits_for_access_flags(struct anv_device *device,
2131                                           VkAccessFlags2 flags)
2132 {
2133    enum anv_pipe_bits pipe_bits = 0;
2134 
2135    u_foreach_bit64(b, flags) {
2136       switch ((VkAccessFlags2)BITFIELD64_BIT(b)) {
2137       case VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT:
2138          /* Indirect draw commands take a buffer as input that we're going to
2139           * read from the command streamer to load some of the HW registers
2140           * (see genX_cmd_buffer.c:load_indirect_parameters). This requires a
2141           * command streamer stall so that all the cache flushes have
2142           * completed before the command streamer loads from memory.
2143           */
2144          pipe_bits |=  ANV_PIPE_CS_STALL_BIT;
2145          /* Indirect draw commands also set gl_BaseVertex & gl_BaseIndex
2146           * through a vertex buffer, so invalidate that cache.
2147           */
2148          pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
2149          /* For CmdDipatchIndirect, we also load gl_NumWorkGroups through a
2150           * UBO from the buffer, so we need to invalidate constant cache.
2151           */
2152          pipe_bits |= ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
2153          pipe_bits |= ANV_PIPE_DATA_CACHE_FLUSH_BIT;
2154          /* Tile cache flush needed For CmdDipatchIndirect since command
2155           * streamer and vertex fetch aren't L3 coherent.
2156           */
2157          pipe_bits |= ANV_PIPE_TILE_CACHE_FLUSH_BIT;
2158          break;
2159       case VK_ACCESS_2_INDEX_READ_BIT:
2160       case VK_ACCESS_2_VERTEX_ATTRIBUTE_READ_BIT:
2161          /* We transitioning a buffer to be used for as input for vkCmdDraw*
2162           * commands, so we invalidate the VF cache to make sure there is no
2163           * stale data when we start rendering.
2164           */
2165          pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
2166          break;
2167       case VK_ACCESS_2_UNIFORM_READ_BIT:
2168          /* We transitioning a buffer to be used as uniform data. Because
2169           * uniform is accessed through the data port & sampler, we need to
2170           * invalidate the texture cache (sampler) & constant cache (data
2171           * port) to avoid stale data.
2172           */
2173          pipe_bits |= ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
2174          if (device->physical->compiler->indirect_ubos_use_sampler) {
2175             pipe_bits |= ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
2176          } else {
2177             pipe_bits |= ANV_PIPE_HDC_PIPELINE_FLUSH_BIT;
2178             pipe_bits |= ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT;
2179          }
2180          break;
2181       case VK_ACCESS_2_INPUT_ATTACHMENT_READ_BIT:
2182       case VK_ACCESS_2_TRANSFER_READ_BIT:
2183       case VK_ACCESS_2_SHADER_SAMPLED_READ_BIT:
2184          /* Transitioning a buffer to be read through the sampler, so
2185           * invalidate the texture cache, we don't want any stale data.
2186           */
2187          pipe_bits |= ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
2188          break;
2189       case VK_ACCESS_2_SHADER_READ_BIT:
2190          /* Same as VK_ACCESS_2_UNIFORM_READ_BIT and
2191           * VK_ACCESS_2_SHADER_SAMPLED_READ_BIT cases above
2192           */
2193          pipe_bits |= ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT |
2194                       ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
2195          if (!device->physical->compiler->indirect_ubos_use_sampler) {
2196             pipe_bits |= ANV_PIPE_HDC_PIPELINE_FLUSH_BIT;
2197             pipe_bits |= ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT;
2198          }
2199          break;
2200       case VK_ACCESS_2_MEMORY_READ_BIT:
2201          /* Transitioning a buffer for generic read, invalidate all the
2202           * caches.
2203           */
2204          pipe_bits |= ANV_PIPE_INVALIDATE_BITS;
2205          break;
2206       case VK_ACCESS_2_MEMORY_WRITE_BIT:
2207          /* Generic write, make sure all previously written things land in
2208           * memory.
2209           */
2210          pipe_bits |= ANV_PIPE_FLUSH_BITS;
2211          break;
2212       case VK_ACCESS_2_CONDITIONAL_RENDERING_READ_BIT_EXT:
2213       case VK_ACCESS_2_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT:
2214          /* Transitioning a buffer for conditional rendering or transform
2215           * feedback. We'll load the content of this buffer into HW registers
2216           * using the command streamer, so we need to stall the command
2217           * streamer , so we need to stall the command streamer to make sure
2218           * any in-flight flush operations have completed.
2219           */
2220          pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2221          pipe_bits |= ANV_PIPE_TILE_CACHE_FLUSH_BIT;
2222          pipe_bits |= ANV_PIPE_DATA_CACHE_FLUSH_BIT;
2223          break;
2224       case VK_ACCESS_2_HOST_READ_BIT:
2225          /* We're transitioning a buffer that was written by CPU.  Flush
2226           * all the caches.
2227           */
2228          pipe_bits |= ANV_PIPE_FLUSH_BITS;
2229          break;
2230       case VK_ACCESS_2_TRANSFORM_FEEDBACK_WRITE_BIT_EXT:
2231          /* We're transitioning a buffer to be written by the streamout fixed
2232           * function. This one is apparently not L3 coherent, so we need a
2233           * tile cache flush to make sure any previous write is not going to
2234           * create WaW hazards.
2235           */
2236          pipe_bits |= ANV_PIPE_TILE_CACHE_FLUSH_BIT;
2237          break;
2238       case VK_ACCESS_2_SHADER_STORAGE_READ_BIT:
2239       default:
2240          break; /* Nothing to do */
2241       }
2242    }
2243 
2244    return pipe_bits;
2245 }
2246 
2247 #define VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV (         \
2248    VK_IMAGE_ASPECT_COLOR_BIT | \
2249    VK_IMAGE_ASPECT_PLANE_0_BIT | \
2250    VK_IMAGE_ASPECT_PLANE_1_BIT | \
2251    VK_IMAGE_ASPECT_PLANE_2_BIT)
2252 #define VK_IMAGE_ASPECT_PLANES_BITS_ANV ( \
2253    VK_IMAGE_ASPECT_PLANE_0_BIT | \
2254    VK_IMAGE_ASPECT_PLANE_1_BIT | \
2255    VK_IMAGE_ASPECT_PLANE_2_BIT)
2256 
2257 struct anv_vertex_binding {
2258    struct anv_buffer *                          buffer;
2259    VkDeviceSize                                 offset;
2260    VkDeviceSize                                 size;
2261 };
2262 
2263 struct anv_xfb_binding {
2264    struct anv_buffer *                          buffer;
2265    VkDeviceSize                                 offset;
2266    VkDeviceSize                                 size;
2267 };
2268 
2269 struct anv_push_constants {
2270    /** Push constant data provided by the client through vkPushConstants */
2271    uint8_t client_data[MAX_PUSH_CONSTANTS_SIZE];
2272 
2273    /** Dynamic offsets for dynamic UBOs and SSBOs */
2274    uint32_t dynamic_offsets[MAX_DYNAMIC_BUFFERS];
2275 
2276    /* Robust access pushed registers. */
2277    uint64_t push_reg_mask[MESA_SHADER_STAGES];
2278 
2279    struct {
2280       /** Base workgroup ID
2281        *
2282        * Used for vkCmdDispatchBase.
2283        */
2284       uint32_t base_work_group_id[3];
2285 
2286       /** Subgroup ID
2287        *
2288        * This is never set by software but is implicitly filled out when
2289        * uploading the push constants for compute shaders.
2290        */
2291       uint32_t subgroup_id;
2292    } cs;
2293 };
2294 
2295 struct anv_surface_state {
2296    struct anv_state state;
2297    /** Address of the surface referred to by this state
2298     *
2299     * This address is relative to the start of the BO.
2300     */
2301    struct anv_address address;
2302    /* Address of the aux surface, if any
2303     *
2304     * This field is ANV_NULL_ADDRESS if and only if no aux surface exists.
2305     *
2306     * With the exception of gfx8, the bottom 12 bits of this address' offset
2307     * include extra aux information.
2308     */
2309    struct anv_address aux_address;
2310    /* Address of the clear color, if any
2311     *
2312     * This address is relative to the start of the BO.
2313     */
2314    struct anv_address clear_address;
2315 };
2316 
2317 struct anv_attachment {
2318    VkFormat vk_format;
2319    const struct anv_image_view *iview;
2320    VkImageLayout layout;
2321    enum isl_aux_usage aux_usage;
2322    struct anv_surface_state surface_state;
2323 
2324    VkResolveModeFlagBits resolve_mode;
2325    const struct anv_image_view *resolve_iview;
2326    VkImageLayout resolve_layout;
2327 };
2328 
2329 /** State tracking for vertex buffer flushes
2330  *
2331  * On Gfx8-9, the VF cache only considers the bottom 32 bits of memory
2332  * addresses.  If you happen to have two vertex buffers which get placed
2333  * exactly 4 GiB apart and use them in back-to-back draw calls, you can get
2334  * collisions.  In order to solve this problem, we track vertex address ranges
2335  * which are live in the cache and invalidate the cache if one ever exceeds 32
2336  * bits.
2337  */
2338 struct anv_vb_cache_range {
2339    /* Virtual address at which the live vertex buffer cache range starts for
2340     * this vertex buffer index.
2341     */
2342    uint64_t start;
2343 
2344    /* Virtual address of the byte after where vertex buffer cache range ends.
2345     * This is exclusive such that end - start is the size of the range.
2346     */
2347    uint64_t end;
2348 };
2349 
2350 static inline void
anv_merge_vb_cache_range(struct anv_vb_cache_range * dirty,const struct anv_vb_cache_range * bound)2351 anv_merge_vb_cache_range(struct anv_vb_cache_range *dirty,
2352                          const struct anv_vb_cache_range *bound)
2353 {
2354    if (dirty->start == dirty->end) {
2355       *dirty = *bound;
2356    } else if (bound->start != bound->end) {
2357       dirty->start = MIN2(dirty->start, bound->start);
2358       dirty->end = MAX2(dirty->end, bound->end);
2359    }
2360 }
2361 
2362 /* Check whether we need to apply the Gfx8-9 vertex buffer workaround*/
2363 static inline bool
anv_gfx8_9_vb_cache_range_needs_workaround(struct anv_vb_cache_range * bound,struct anv_vb_cache_range * dirty,struct anv_address vb_address,uint32_t vb_size)2364 anv_gfx8_9_vb_cache_range_needs_workaround(struct anv_vb_cache_range *bound,
2365                                            struct anv_vb_cache_range *dirty,
2366                                            struct anv_address vb_address,
2367                                            uint32_t vb_size)
2368 {
2369    if (vb_size == 0) {
2370       bound->start = 0;
2371       bound->end = 0;
2372       return false;
2373    }
2374 
2375    assert(vb_address.bo && anv_bo_is_pinned(vb_address.bo));
2376    bound->start = intel_48b_address(anv_address_physical(vb_address));
2377    bound->end = bound->start + vb_size;
2378    assert(bound->end > bound->start); /* No overflow */
2379 
2380    /* Align everything to a cache line */
2381    bound->start &= ~(64ull - 1ull);
2382    bound->end = align64(bound->end, 64);
2383 
2384    anv_merge_vb_cache_range(dirty, bound);
2385 
2386    /* If our range is larger than 32 bits, we have to flush */
2387    assert(bound->end - bound->start <= (1ull << 32));
2388    return (dirty->end - dirty->start) > (1ull << 32);
2389 }
2390 
2391 /** State tracking for particular pipeline bind point
2392  *
2393  * This struct is the base struct for anv_cmd_graphics_state and
2394  * anv_cmd_compute_state.  These are used to track state which is bound to a
2395  * particular type of pipeline.  Generic state that applies per-stage such as
2396  * binding table offsets and push constants is tracked generically with a
2397  * per-stage array in anv_cmd_state.
2398  */
2399 struct anv_cmd_pipeline_state {
2400    struct anv_descriptor_set *descriptors[MAX_SETS];
2401    struct anv_push_descriptor_set *push_descriptors[MAX_SETS];
2402 
2403    struct anv_push_constants push_constants;
2404 
2405    /* Push constant state allocated when flushing push constants. */
2406    struct anv_state          push_constants_state;
2407 };
2408 
2409 /** State tracking for graphics pipeline
2410  *
2411  * This has anv_cmd_pipeline_state as a base struct to track things which get
2412  * bound to a graphics pipeline.  Along with general pipeline bind point state
2413  * which is in the anv_cmd_pipeline_state base struct, it also contains other
2414  * state which is graphics-specific.
2415  */
2416 struct anv_cmd_graphics_state {
2417    struct anv_cmd_pipeline_state base;
2418 
2419    struct anv_graphics_pipeline *pipeline;
2420 
2421    VkRenderingFlags rendering_flags;
2422    VkRect2D render_area;
2423    uint32_t layer_count;
2424    uint32_t samples;
2425    uint32_t view_mask;
2426    uint32_t color_att_count;
2427    struct anv_state att_states;
2428    struct anv_attachment color_att[MAX_RTS];
2429    struct anv_attachment depth_att;
2430    struct anv_attachment stencil_att;
2431    struct anv_state null_surface_state;
2432 
2433    anv_cmd_dirty_mask_t dirty;
2434    uint32_t vb_dirty;
2435 
2436    struct anv_vb_cache_range ib_bound_range;
2437    struct anv_vb_cache_range ib_dirty_range;
2438    struct anv_vb_cache_range vb_bound_ranges[33];
2439    struct anv_vb_cache_range vb_dirty_ranges[33];
2440 
2441    uint32_t restart_index;
2442 
2443    VkShaderStageFlags push_constant_stages;
2444 
2445    uint32_t primitive_topology;
2446 
2447    struct anv_buffer *index_buffer;
2448    uint32_t index_type; /**< 3DSTATE_INDEX_BUFFER.IndexFormat */
2449    uint32_t index_offset;
2450 
2451    struct vk_sample_locations_state sample_locations;
2452 
2453    bool has_uint_rt;
2454 };
2455 
2456 enum anv_depth_reg_mode {
2457    ANV_DEPTH_REG_MODE_UNKNOWN = 0,
2458    ANV_DEPTH_REG_MODE_HW_DEFAULT,
2459    ANV_DEPTH_REG_MODE_D16_1X_MSAA,
2460 };
2461 
2462 /** State tracking for compute pipeline
2463  *
2464  * This has anv_cmd_pipeline_state as a base struct to track things which get
2465  * bound to a compute pipeline.  Along with general pipeline bind point state
2466  * which is in the anv_cmd_pipeline_state base struct, it also contains other
2467  * state which is compute-specific.
2468  */
2469 struct anv_cmd_compute_state {
2470    struct anv_cmd_pipeline_state base;
2471 
2472    struct anv_compute_pipeline *pipeline;
2473 
2474    bool pipeline_dirty;
2475 
2476    struct anv_state push_data;
2477 
2478    struct anv_address num_workgroups;
2479 };
2480 
2481 /** State required while building cmd buffer */
2482 struct anv_cmd_state {
2483    /* PIPELINE_SELECT.PipelineSelection */
2484    uint32_t                                     current_pipeline;
2485    const struct intel_l3_config *               current_l3_config;
2486 
2487    struct anv_cmd_graphics_state                gfx;
2488    struct anv_cmd_compute_state                 compute;
2489 
2490    enum anv_pipe_bits                           pending_pipe_bits;
2491    VkShaderStageFlags                           descriptors_dirty;
2492    VkShaderStageFlags                           push_constants_dirty;
2493 
2494    struct anv_vertex_binding                    vertex_bindings[MAX_VBS];
2495    bool                                         xfb_enabled;
2496    struct anv_xfb_binding                       xfb_bindings[MAX_XFB_BUFFERS];
2497    struct anv_state                             binding_tables[MESA_VULKAN_SHADER_STAGES];
2498    struct anv_state                             samplers[MESA_VULKAN_SHADER_STAGES];
2499 
2500    unsigned char                                sampler_sha1s[MESA_VULKAN_SHADER_STAGES][20];
2501    unsigned char                                surface_sha1s[MESA_VULKAN_SHADER_STAGES][20];
2502    unsigned char                                push_sha1s[MESA_VULKAN_SHADER_STAGES][20];
2503 
2504    /**
2505     * Whether or not the gfx8 PMA fix is enabled.  We ensure that, at the top
2506     * of any command buffer it is disabled by disabling it in EndCommandBuffer
2507     * and before invoking the secondary in ExecuteCommands.
2508     */
2509    bool                                         pma_fix_enabled;
2510 
2511    /**
2512     * Whether or not we know for certain that HiZ is enabled for the current
2513     * subpass.  If, for whatever reason, we are unsure as to whether HiZ is
2514     * enabled or not, this will be false.
2515     */
2516    bool                                         hiz_enabled;
2517 
2518    /* We ensure the registers for the gfx12 D16 fix are initialized at the
2519     * first non-NULL depth stencil packet emission of every command buffer.
2520     * For secondary command buffer execution, we transfer the state from the
2521     * last command buffer to the primary (if known).
2522     */
2523    enum anv_depth_reg_mode                      depth_reg_mode;
2524 
2525    bool                                         conditional_render_enabled;
2526 
2527    /**
2528     * Last rendering scale argument provided to
2529     * genX(cmd_buffer_emit_hashing_mode)().
2530     */
2531    unsigned                                     current_hash_scale;
2532 };
2533 
2534 #define ANV_MIN_CMD_BUFFER_BATCH_SIZE 8192
2535 #define ANV_MAX_CMD_BUFFER_BATCH_SIZE (16 * 1024 * 1024)
2536 
2537 enum anv_cmd_buffer_exec_mode {
2538    ANV_CMD_BUFFER_EXEC_MODE_PRIMARY,
2539    ANV_CMD_BUFFER_EXEC_MODE_EMIT,
2540    ANV_CMD_BUFFER_EXEC_MODE_GROW_AND_EMIT,
2541    ANV_CMD_BUFFER_EXEC_MODE_CHAIN,
2542    ANV_CMD_BUFFER_EXEC_MODE_COPY_AND_CHAIN,
2543    ANV_CMD_BUFFER_EXEC_MODE_CALL_AND_RETURN,
2544 };
2545 
2546 struct anv_measure_batch;
2547 
2548 struct anv_cmd_buffer {
2549    struct vk_command_buffer                     vk;
2550 
2551    struct anv_device *                          device;
2552    struct anv_queue_family *                    queue_family;
2553 
2554    struct anv_batch                             batch;
2555 
2556    /* Pointer to the location in the batch where MI_BATCH_BUFFER_END was
2557     * recorded upon calling vkEndCommandBuffer(). This is useful if we need to
2558     * rewrite the end to chain multiple batch together at vkQueueSubmit().
2559     */
2560    void *                                       batch_end;
2561 
2562    /* Fields required for the actual chain of anv_batch_bo's.
2563     *
2564     * These fields are initialized by anv_cmd_buffer_init_batch_bo_chain().
2565     */
2566    struct list_head                             batch_bos;
2567    enum anv_cmd_buffer_exec_mode                exec_mode;
2568 
2569    /* A vector of anv_batch_bo pointers for every batch or surface buffer
2570     * referenced by this command buffer
2571     *
2572     * initialized by anv_cmd_buffer_init_batch_bo_chain()
2573     */
2574    struct u_vector                            seen_bbos;
2575 
2576    /* A vector of int32_t's for every block of binding tables.
2577     *
2578     * initialized by anv_cmd_buffer_init_batch_bo_chain()
2579     */
2580    struct u_vector                              bt_block_states;
2581    struct anv_state                             bt_next;
2582 
2583    struct anv_reloc_list                        surface_relocs;
2584    /** Last seen surface state block pool center bo offset */
2585    uint32_t                                     last_ss_pool_center;
2586 
2587    /* Serial for tracking buffer completion */
2588    uint32_t                                     serial;
2589 
2590    /* Stream objects for storing temporary data */
2591    struct anv_state_stream                      surface_state_stream;
2592    struct anv_state_stream                      dynamic_state_stream;
2593    struct anv_state_stream                      general_state_stream;
2594 
2595    VkCommandBufferUsageFlags                    usage_flags;
2596 
2597    struct anv_query_pool                       *perf_query_pool;
2598 
2599    struct anv_cmd_state                         state;
2600 
2601    struct anv_address                           return_addr;
2602 
2603    /* Set by SetPerformanceMarkerINTEL, written into queries by CmdBeginQuery */
2604    uint64_t                                     intel_perf_marker;
2605 
2606    struct anv_measure_batch *measure;
2607 
2608    /**
2609     * KHR_performance_query requires self modifying command buffers and this
2610     * array has the location of modifying commands to the query begin and end
2611     * instructions storing performance counters. The array length is
2612     * anv_physical_device::n_perf_query_commands.
2613     */
2614    struct mi_address_token                  *self_mod_locations;
2615 
2616    /**
2617     * Index tracking which of the self_mod_locations items have already been
2618     * used.
2619     */
2620    uint32_t                                      perf_reloc_idx;
2621 
2622    /**
2623     * Sum of all the anv_batch_bo sizes allocated for this command buffer.
2624     * Used to increase allocation size for long command buffers.
2625     */
2626    uint32_t                                     total_batch_size;
2627 
2628    /**
2629     *
2630     */
2631    struct u_trace                               trace;
2632 };
2633 
2634 extern const struct vk_command_buffer_ops anv_cmd_buffer_ops;
2635 
2636 /* Determine whether we can chain a given cmd_buffer to another one. We need
2637  * softpin and we also need to make sure that we can edit the end of the batch
2638  * to point to next one, which requires the command buffer to not be used
2639  * simultaneously.
2640  */
2641 static inline bool
anv_cmd_buffer_is_chainable(struct anv_cmd_buffer * cmd_buffer)2642 anv_cmd_buffer_is_chainable(struct anv_cmd_buffer *cmd_buffer)
2643 {
2644    return !anv_use_relocations(cmd_buffer->device->physical) &&
2645       !(cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT);
2646 }
2647 
2648 VkResult anv_cmd_buffer_init_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
2649 void anv_cmd_buffer_fini_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
2650 void anv_cmd_buffer_reset_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
2651 void anv_cmd_buffer_end_batch_buffer(struct anv_cmd_buffer *cmd_buffer);
2652 void anv_cmd_buffer_add_secondary(struct anv_cmd_buffer *primary,
2653                                   struct anv_cmd_buffer *secondary);
2654 void anv_cmd_buffer_prepare_execbuf(struct anv_cmd_buffer *cmd_buffer);
2655 VkResult anv_cmd_buffer_execbuf(struct anv_queue *queue,
2656                                 struct anv_cmd_buffer *cmd_buffer,
2657                                 const VkSemaphore *in_semaphores,
2658                                 const uint64_t *in_wait_values,
2659                                 uint32_t num_in_semaphores,
2660                                 const VkSemaphore *out_semaphores,
2661                                 const uint64_t *out_signal_values,
2662                                 uint32_t num_out_semaphores,
2663                                 VkFence fence,
2664                                 int perf_query_pass);
2665 
2666 void anv_cmd_buffer_reset(struct vk_command_buffer *vk_cmd_buffer,
2667                           UNUSED VkCommandBufferResetFlags flags);
2668 
2669 struct anv_state anv_cmd_buffer_emit_dynamic(struct anv_cmd_buffer *cmd_buffer,
2670                                              const void *data, uint32_t size, uint32_t alignment);
2671 struct anv_state anv_cmd_buffer_merge_dynamic(struct anv_cmd_buffer *cmd_buffer,
2672                                               uint32_t *a, uint32_t *b,
2673                                               uint32_t dwords, uint32_t alignment);
2674 
2675 struct anv_address
2676 anv_cmd_buffer_surface_base_address(struct anv_cmd_buffer *cmd_buffer);
2677 struct anv_state
2678 anv_cmd_buffer_alloc_binding_table(struct anv_cmd_buffer *cmd_buffer,
2679                                    uint32_t entries, uint32_t *state_offset);
2680 struct anv_state
2681 anv_cmd_buffer_alloc_surface_state(struct anv_cmd_buffer *cmd_buffer);
2682 struct anv_state
2683 anv_cmd_buffer_alloc_dynamic_state(struct anv_cmd_buffer *cmd_buffer,
2684                                    uint32_t size, uint32_t alignment);
2685 
2686 VkResult
2687 anv_cmd_buffer_new_binding_table_block(struct anv_cmd_buffer *cmd_buffer);
2688 
2689 void anv_cmd_buffer_emit_state_base_address(struct anv_cmd_buffer *cmd_buffer);
2690 
2691 struct anv_state
2692 anv_cmd_buffer_gfx_push_constants(struct anv_cmd_buffer *cmd_buffer);
2693 struct anv_state
2694 anv_cmd_buffer_cs_push_constants(struct anv_cmd_buffer *cmd_buffer);
2695 
2696 VkResult
2697 anv_cmd_buffer_alloc_blorp_binding_table(struct anv_cmd_buffer *cmd_buffer,
2698                                          uint32_t num_entries,
2699                                          uint32_t *state_offset,
2700                                          struct anv_state *bt_state);
2701 
2702 void anv_cmd_buffer_dump(struct anv_cmd_buffer *cmd_buffer);
2703 
2704 void anv_cmd_emit_conditional_render_predicate(struct anv_cmd_buffer *cmd_buffer);
2705 
2706 enum anv_bo_sync_state {
2707    /** Indicates that this is a new (or newly reset fence) */
2708    ANV_BO_SYNC_STATE_RESET,
2709 
2710    /** Indicates that this fence has been submitted to the GPU but is still
2711     * (as far as we know) in use by the GPU.
2712     */
2713    ANV_BO_SYNC_STATE_SUBMITTED,
2714 
2715    ANV_BO_SYNC_STATE_SIGNALED,
2716 };
2717 
2718 struct anv_bo_sync {
2719    struct vk_sync sync;
2720 
2721    enum anv_bo_sync_state state;
2722    struct anv_bo *bo;
2723 };
2724 
2725 extern const struct vk_sync_type anv_bo_sync_type;
2726 
2727 static inline bool
vk_sync_is_anv_bo_sync(const struct vk_sync * sync)2728 vk_sync_is_anv_bo_sync(const struct vk_sync *sync)
2729 {
2730    return sync->type == &anv_bo_sync_type;
2731 }
2732 
2733 VkResult anv_create_sync_for_memory(struct vk_device *device,
2734                                     VkDeviceMemory memory,
2735                                     bool signal_memory,
2736                                     struct vk_sync **sync_out);
2737 
2738 struct anv_event {
2739    struct vk_object_base                        base;
2740    uint64_t                                     semaphore;
2741    struct anv_state                             state;
2742 };
2743 
2744 #define ANV_STAGE_MASK ((1 << MESA_VULKAN_SHADER_STAGES) - 1)
2745 
2746 #define anv_foreach_stage(stage, stage_bits)                         \
2747    for (gl_shader_stage stage,                                       \
2748         __tmp = (gl_shader_stage)((stage_bits) & ANV_STAGE_MASK);    \
2749         stage = __builtin_ffs(__tmp) - 1, __tmp;                     \
2750         __tmp &= ~(1 << (stage)))
2751 
2752 struct anv_pipeline_bind_map {
2753    unsigned char                                surface_sha1[20];
2754    unsigned char                                sampler_sha1[20];
2755    unsigned char                                push_sha1[20];
2756 
2757    uint32_t surface_count;
2758    uint32_t sampler_count;
2759 
2760    struct anv_pipeline_binding *                surface_to_descriptor;
2761    struct anv_pipeline_binding *                sampler_to_descriptor;
2762 
2763    struct anv_push_range                        push_ranges[4];
2764 };
2765 
2766 struct anv_shader_bin {
2767    struct vk_pipeline_cache_object base;
2768 
2769    gl_shader_stage stage;
2770 
2771    struct anv_state kernel;
2772    uint32_t kernel_size;
2773 
2774    const struct elk_stage_prog_data *prog_data;
2775    uint32_t prog_data_size;
2776 
2777    struct elk_compile_stats stats[3];
2778    uint32_t num_stats;
2779 
2780    struct nir_xfb_info *xfb_info;
2781 
2782    struct anv_pipeline_bind_map bind_map;
2783 };
2784 
2785 struct anv_shader_bin *
2786 anv_shader_bin_create(struct anv_device *device,
2787                       gl_shader_stage stage,
2788                       const void *key, uint32_t key_size,
2789                       const void *kernel, uint32_t kernel_size,
2790                       const struct elk_stage_prog_data *prog_data,
2791                       uint32_t prog_data_size,
2792                       const struct elk_compile_stats *stats, uint32_t num_stats,
2793                       const struct nir_xfb_info *xfb_info,
2794                       const struct anv_pipeline_bind_map *bind_map);
2795 
2796 static inline void
anv_shader_bin_ref(struct anv_shader_bin * shader)2797 anv_shader_bin_ref(struct anv_shader_bin *shader)
2798 {
2799    vk_pipeline_cache_object_ref(&shader->base);
2800 }
2801 
2802 static inline void
anv_shader_bin_unref(struct anv_device * device,struct anv_shader_bin * shader)2803 anv_shader_bin_unref(struct anv_device *device, struct anv_shader_bin *shader)
2804 {
2805    vk_pipeline_cache_object_unref(&device->vk, &shader->base);
2806 }
2807 
2808 struct anv_pipeline_executable {
2809    gl_shader_stage stage;
2810 
2811    struct elk_compile_stats stats;
2812 
2813    char *nir;
2814    char *disasm;
2815 };
2816 
2817 enum anv_pipeline_type {
2818    ANV_PIPELINE_GRAPHICS,
2819    ANV_PIPELINE_COMPUTE,
2820 };
2821 
2822 struct anv_pipeline {
2823    struct vk_object_base                        base;
2824 
2825    struct anv_device *                          device;
2826 
2827    struct anv_batch                             batch;
2828    struct anv_reloc_list                        batch_relocs;
2829 
2830    void *                                       mem_ctx;
2831 
2832    enum anv_pipeline_type                       type;
2833    VkPipelineCreateFlags                        flags;
2834 
2835    struct util_dynarray                         executables;
2836 
2837    const struct intel_l3_config *               l3_config;
2838 };
2839 
2840 struct anv_graphics_pipeline {
2841    struct anv_pipeline                          base;
2842 
2843    /* Shaders */
2844    struct anv_shader_bin *                      shaders[ANV_GRAPHICS_SHADER_STAGE_COUNT];
2845 
2846    VkShaderStageFlags                           active_stages;
2847 
2848    struct vk_sample_locations_state             sample_locations;
2849    struct vk_dynamic_graphics_state             dynamic_state;
2850 
2851    /* These fields are required with dynamic primitive topology,
2852     * rasterization_samples used only with gen < 8.
2853     */
2854    VkLineRasterizationModeEXT                   line_mode;
2855    VkPolygonMode                                polygon_mode;
2856    uint32_t                                     patch_control_points;
2857    uint32_t                                     rasterization_samples;
2858 
2859    VkColorComponentFlags                        color_comp_writes[MAX_RTS];
2860 
2861    uint32_t                                     view_mask;
2862    uint32_t                                     instance_multiplier;
2863 
2864    bool                                         depth_clamp_enable;
2865    bool                                         depth_clip_enable;
2866    bool                                         kill_pixel;
2867    bool                                         force_fragment_thread_dispatch;
2868    bool                                         negative_one_to_one;
2869 
2870    uint32_t                                     vb_used;
2871    struct anv_pipeline_vertex_binding {
2872       uint32_t                                  stride;
2873       bool                                      instanced;
2874       uint32_t                                  instance_divisor;
2875    } vb[MAX_VBS];
2876 
2877    /* Pre computed CS instructions that can directly be copied into
2878     * anv_cmd_buffer.
2879     */
2880    uint32_t                                     batch_data[512];
2881 
2882    /* Pre packed CS instructions & structures that need to be merged later
2883     * with dynamic state.
2884     */
2885    struct {
2886       uint32_t                                  sf[7];
2887       uint32_t                                  clip[4];
2888       uint32_t                                  xfb_bo_pitch[4];
2889       uint32_t                                  wm[3];
2890       uint32_t                                  blend_state[MAX_RTS * 2];
2891       uint32_t                                  streamout_state[3];
2892    } gfx7;
2893 
2894    struct {
2895       uint32_t                                  sf[4];
2896       uint32_t                                  raster[5];
2897       uint32_t                                  wm[2];
2898       uint32_t                                  ps_blend[2];
2899       uint32_t                                  blend_state[1 + MAX_RTS * 2];
2900       uint32_t                                  streamout_state[5];
2901    } gfx8;
2902 };
2903 
2904 struct anv_compute_pipeline {
2905    struct anv_pipeline                          base;
2906 
2907    struct anv_shader_bin *                      cs;
2908    uint32_t                                     batch_data[9];
2909    uint32_t                                     interface_descriptor_data[8];
2910 };
2911 
2912 #define ANV_DECL_PIPELINE_DOWNCAST(pipe_type, pipe_enum)             \
2913    static inline struct anv_##pipe_type##_pipeline *                 \
2914    anv_pipeline_to_##pipe_type(struct anv_pipeline *pipeline)      \
2915    {                                                                 \
2916       assert(pipeline->type == pipe_enum);                           \
2917       return (struct anv_##pipe_type##_pipeline *) pipeline;         \
2918    }
2919 
ANV_DECL_PIPELINE_DOWNCAST(graphics,ANV_PIPELINE_GRAPHICS)2920 ANV_DECL_PIPELINE_DOWNCAST(graphics, ANV_PIPELINE_GRAPHICS)
2921 ANV_DECL_PIPELINE_DOWNCAST(compute, ANV_PIPELINE_COMPUTE)
2922 
2923 static inline bool
2924 anv_pipeline_has_stage(const struct anv_graphics_pipeline *pipeline,
2925                        gl_shader_stage stage)
2926 {
2927    return (pipeline->active_stages & mesa_to_vk_shader_stage(stage)) != 0;
2928 }
2929 
2930 static inline bool
anv_pipeline_is_primitive(const struct anv_graphics_pipeline * pipeline)2931 anv_pipeline_is_primitive(const struct anv_graphics_pipeline *pipeline)
2932 {
2933    return anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX);
2934 }
2935 
2936 static inline bool
anv_cmd_buffer_all_color_write_masked(const struct anv_cmd_buffer * cmd_buffer)2937 anv_cmd_buffer_all_color_write_masked(const struct anv_cmd_buffer *cmd_buffer)
2938 {
2939    const struct anv_cmd_graphics_state *state = &cmd_buffer->state.gfx;
2940    const struct vk_dynamic_graphics_state *dyn =
2941       &cmd_buffer->vk.dynamic_graphics_state;
2942    uint8_t color_writes = dyn->cb.color_write_enables;
2943 
2944    /* All writes disabled through vkCmdSetColorWriteEnableEXT */
2945    if ((color_writes & ((1u << state->color_att_count) - 1)) == 0)
2946       return true;
2947 
2948    /* Or all write masks are empty */
2949    for (uint32_t i = 0; i < state->color_att_count; i++) {
2950       if (state->pipeline->color_comp_writes[i] != 0)
2951          return false;
2952    }
2953 
2954    return true;
2955 }
2956 
2957 static inline void
anv_cmd_graphic_state_update_has_uint_rt(struct anv_cmd_graphics_state * state)2958 anv_cmd_graphic_state_update_has_uint_rt(struct anv_cmd_graphics_state *state)
2959 {
2960    state->has_uint_rt = false;
2961    for (unsigned a = 0; a < state->color_att_count; a++) {
2962       if (vk_format_is_int(state->color_att[a].vk_format)) {
2963          state->has_uint_rt = true;
2964          break;
2965       }
2966    }
2967 }
2968 
2969 #define ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(prefix, stage)             \
2970 static inline const struct elk_##prefix##_prog_data *                   \
2971 get_##prefix##_prog_data(const struct anv_graphics_pipeline *pipeline)  \
2972 {                                                                       \
2973    if (anv_pipeline_has_stage(pipeline, stage)) {                       \
2974       return (const struct elk_##prefix##_prog_data *)                  \
2975              pipeline->shaders[stage]->prog_data;                       \
2976    } else {                                                             \
2977       return NULL;                                                      \
2978    }                                                                    \
2979 }
2980 
ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(vs,MESA_SHADER_VERTEX)2981 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(vs, MESA_SHADER_VERTEX)
2982 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(tcs, MESA_SHADER_TESS_CTRL)
2983 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(tes, MESA_SHADER_TESS_EVAL)
2984 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(gs, MESA_SHADER_GEOMETRY)
2985 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(wm, MESA_SHADER_FRAGMENT)
2986 
2987 static inline const struct elk_cs_prog_data *
2988 get_cs_prog_data(const struct anv_compute_pipeline *pipeline)
2989 {
2990    assert(pipeline->cs);
2991    return (const struct elk_cs_prog_data *) pipeline->cs->prog_data;
2992 }
2993 
2994 static inline const struct elk_vue_prog_data *
anv_pipeline_get_last_vue_prog_data(const struct anv_graphics_pipeline * pipeline)2995 anv_pipeline_get_last_vue_prog_data(const struct anv_graphics_pipeline *pipeline)
2996 {
2997    if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
2998       return &get_gs_prog_data(pipeline)->base;
2999    else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
3000       return &get_tes_prog_data(pipeline)->base;
3001    else
3002       return &get_vs_prog_data(pipeline)->base;
3003 }
3004 
3005 VkResult
3006 anv_pipeline_init(struct anv_pipeline *pipeline,
3007                   struct anv_device *device,
3008                   enum anv_pipeline_type type,
3009                   VkPipelineCreateFlags flags,
3010                   const VkAllocationCallbacks *pAllocator);
3011 
3012 void
3013 anv_pipeline_finish(struct anv_pipeline *pipeline,
3014                     struct anv_device *device,
3015                     const VkAllocationCallbacks *pAllocator);
3016 
3017 struct anv_format_plane {
3018    enum isl_format isl_format:16;
3019    struct isl_swizzle swizzle;
3020 
3021    /* Whether this plane contains chroma channels */
3022    bool has_chroma;
3023 
3024    /* For downscaling of YUV planes */
3025    uint8_t denominator_scales[2];
3026 
3027    /* How to map sampled ycbcr planes to a single 4 component element. */
3028    struct isl_swizzle ycbcr_swizzle;
3029 
3030    /* What aspect is associated to this plane */
3031    VkImageAspectFlags aspect;
3032 };
3033 
3034 
3035 struct anv_format {
3036    struct anv_format_plane planes[3];
3037    VkFormat vk_format;
3038    uint8_t n_planes;
3039    bool can_ycbcr;
3040 };
3041 
3042 static inline void
anv_assert_valid_aspect_set(VkImageAspectFlags aspects)3043 anv_assert_valid_aspect_set(VkImageAspectFlags aspects)
3044 {
3045    if (util_bitcount(aspects) == 1) {
3046       assert(aspects & (VK_IMAGE_ASPECT_COLOR_BIT |
3047                         VK_IMAGE_ASPECT_DEPTH_BIT |
3048                         VK_IMAGE_ASPECT_STENCIL_BIT |
3049                         VK_IMAGE_ASPECT_PLANE_0_BIT |
3050                         VK_IMAGE_ASPECT_PLANE_1_BIT |
3051                         VK_IMAGE_ASPECT_PLANE_2_BIT));
3052    } else if (aspects & VK_IMAGE_ASPECT_PLANES_BITS_ANV) {
3053       assert(aspects == VK_IMAGE_ASPECT_PLANE_0_BIT ||
3054              aspects == (VK_IMAGE_ASPECT_PLANE_0_BIT |
3055                          VK_IMAGE_ASPECT_PLANE_1_BIT) ||
3056              aspects == (VK_IMAGE_ASPECT_PLANE_0_BIT |
3057                          VK_IMAGE_ASPECT_PLANE_1_BIT |
3058                          VK_IMAGE_ASPECT_PLANE_2_BIT));
3059    } else {
3060       assert(aspects == (VK_IMAGE_ASPECT_DEPTH_BIT |
3061                          VK_IMAGE_ASPECT_STENCIL_BIT));
3062    }
3063 }
3064 
3065 /**
3066  * Return the aspect's plane relative to all_aspects.  For an image, for
3067  * instance, all_aspects would be the set of aspects in the image.  For
3068  * an image view, all_aspects would be the subset of aspects represented
3069  * by that particular view.
3070  */
3071 static inline uint32_t
anv_aspect_to_plane(VkImageAspectFlags all_aspects,VkImageAspectFlagBits aspect)3072 anv_aspect_to_plane(VkImageAspectFlags all_aspects,
3073                     VkImageAspectFlagBits aspect)
3074 {
3075    anv_assert_valid_aspect_set(all_aspects);
3076    assert(util_bitcount(aspect) == 1);
3077    assert(!(aspect & ~all_aspects));
3078 
3079    /* Because we always put image and view planes in aspect-bit-order, the
3080     * plane index is the number of bits in all_aspects before aspect.
3081     */
3082    return util_bitcount(all_aspects & (aspect - 1));
3083 }
3084 
3085 #define anv_foreach_image_aspect_bit(b, image, aspects) \
3086    u_foreach_bit(b, vk_image_expand_aspect_mask(&(image)->vk, aspects))
3087 
3088 const struct anv_format *
3089 anv_get_format(VkFormat format);
3090 
3091 static inline uint32_t
anv_get_format_planes(VkFormat vk_format)3092 anv_get_format_planes(VkFormat vk_format)
3093 {
3094    const struct anv_format *format = anv_get_format(vk_format);
3095 
3096    return format != NULL ? format->n_planes : 0;
3097 }
3098 
3099 struct anv_format_plane
3100 anv_get_format_plane(const struct intel_device_info *devinfo,
3101                      VkFormat vk_format, uint32_t plane,
3102                      VkImageTiling tiling);
3103 
3104 struct anv_format_plane
3105 anv_get_format_aspect(const struct intel_device_info *devinfo,
3106                       VkFormat vk_format,
3107                       VkImageAspectFlagBits aspect, VkImageTiling tiling);
3108 
3109 static inline enum isl_format
anv_get_isl_format(const struct intel_device_info * devinfo,VkFormat vk_format,VkImageAspectFlags aspect,VkImageTiling tiling)3110 anv_get_isl_format(const struct intel_device_info *devinfo, VkFormat vk_format,
3111                    VkImageAspectFlags aspect, VkImageTiling tiling)
3112 {
3113    return anv_get_format_aspect(devinfo, vk_format, aspect, tiling).isl_format;
3114 }
3115 
3116 extern VkFormat
3117 vk_format_from_android(unsigned android_format, unsigned android_usage);
3118 
3119 static inline struct isl_swizzle
anv_swizzle_for_render(struct isl_swizzle swizzle)3120 anv_swizzle_for_render(struct isl_swizzle swizzle)
3121 {
3122    /* Sometimes the swizzle will have alpha map to one.  We do this to fake
3123     * RGB as RGBA for texturing
3124     */
3125    assert(swizzle.a == ISL_CHANNEL_SELECT_ONE ||
3126           swizzle.a == ISL_CHANNEL_SELECT_ALPHA);
3127 
3128    /* But it doesn't matter what we render to that channel */
3129    swizzle.a = ISL_CHANNEL_SELECT_ALPHA;
3130 
3131    return swizzle;
3132 }
3133 
3134 void
3135 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm);
3136 
3137 /**
3138  * Describes how each part of anv_image will be bound to memory.
3139  */
3140 struct anv_image_memory_range {
3141    /**
3142     * Disjoint bindings into which each portion of the image will be bound.
3143     *
3144     * Binding images to memory can be complicated and invold binding different
3145     * portions of the image to different memory objects or regions.  For most
3146     * images, everything lives in the MAIN binding and gets bound by
3147     * vkBindImageMemory.  For disjoint multi-planar images, each plane has
3148     * a unique, disjoint binding and gets bound by vkBindImageMemory2 with
3149     * VkBindImagePlaneMemoryInfo.  There may also exist bits of memory which are
3150     * implicit or driver-managed and live in special-case bindings.
3151     */
3152    enum anv_image_memory_binding {
3153       /**
3154        * Used if and only if image is not multi-planar disjoint. Bound by
3155        * vkBindImageMemory2 without VkBindImagePlaneMemoryInfo.
3156        */
3157       ANV_IMAGE_MEMORY_BINDING_MAIN,
3158 
3159       /**
3160        * Used if and only if image is multi-planar disjoint.  Bound by
3161        * vkBindImageMemory2 with VkBindImagePlaneMemoryInfo.
3162        */
3163       ANV_IMAGE_MEMORY_BINDING_PLANE_0,
3164       ANV_IMAGE_MEMORY_BINDING_PLANE_1,
3165       ANV_IMAGE_MEMORY_BINDING_PLANE_2,
3166 
3167       /**
3168        * Driver-private bo. In special cases we may store the aux surface and/or
3169        * aux state in this binding.
3170        */
3171       ANV_IMAGE_MEMORY_BINDING_PRIVATE,
3172 
3173       /** Sentinel */
3174       ANV_IMAGE_MEMORY_BINDING_END,
3175    } binding;
3176 
3177    /**
3178     * Offset is relative to the start of the binding created by
3179     * vkBindImageMemory, not to the start of the bo.
3180     */
3181    uint64_t offset;
3182 
3183    uint64_t size;
3184    uint32_t alignment;
3185 };
3186 
3187 /**
3188  * Subsurface of an anv_image.
3189  */
3190 struct anv_surface {
3191    struct isl_surf isl;
3192    struct anv_image_memory_range memory_range;
3193 };
3194 
3195 static inline bool MUST_CHECK
anv_surface_is_valid(const struct anv_surface * surface)3196 anv_surface_is_valid(const struct anv_surface *surface)
3197 {
3198    return surface->isl.size_B > 0 && surface->memory_range.size > 0;
3199 }
3200 
3201 struct anv_image {
3202    struct vk_image vk;
3203 
3204    uint32_t n_planes;
3205 
3206    /**
3207     * Image has multi-planar format and was created with
3208     * VK_IMAGE_CREATE_DISJOINT_BIT.
3209     */
3210    bool disjoint;
3211 
3212    /**
3213     * Image is a WSI image
3214     */
3215    bool from_wsi;
3216 
3217    /**
3218     * Image was imported from an struct AHardwareBuffer.  We have to delay
3219     * final image creation until bind time.
3220     */
3221    bool from_ahb;
3222 
3223    /**
3224     * Image was imported from gralloc with VkNativeBufferANDROID. The gralloc bo
3225     * must be released when the image is destroyed.
3226     */
3227    bool from_gralloc;
3228 
3229    /**
3230     * The memory bindings created by vkCreateImage and vkBindImageMemory.
3231     *
3232     * For details on the image's memory layout, see check_memory_bindings().
3233     *
3234     * vkCreateImage constructs the `memory_range` for each
3235     * anv_image_memory_binding.  After vkCreateImage, each binding is valid if
3236     * and only if `memory_range::size > 0`.
3237     *
3238     * vkBindImageMemory binds each valid `memory_range` to an `address`.
3239     * Usually, the app will provide the address via the parameters of
3240     * vkBindImageMemory.  However, special-case bindings may be bound to
3241     * driver-private memory.
3242     */
3243    struct anv_image_binding {
3244       struct anv_image_memory_range memory_range;
3245       struct anv_address address;
3246    } bindings[ANV_IMAGE_MEMORY_BINDING_END];
3247 
3248    /**
3249     * Image subsurfaces
3250     *
3251     * For each foo, anv_image::planes[x].surface is valid if and only if
3252     * anv_image::aspects has a x aspect. Refer to anv_image_aspect_to_plane()
3253     * to figure the number associated with a given aspect.
3254     *
3255     * The hardware requires that the depth buffer and stencil buffer be
3256     * separate surfaces.  From Vulkan's perspective, though, depth and stencil
3257     * reside in the same VkImage.  To satisfy both the hardware and Vulkan, we
3258     * allocate the depth and stencil buffers as separate surfaces in the same
3259     * bo.
3260     */
3261    struct anv_image_plane {
3262       struct anv_surface primary_surface;
3263 
3264       /**
3265        * A surface which shadows the main surface and may have different
3266        * tiling. This is used for sampling using a tiling that isn't supported
3267        * for other operations.
3268        */
3269       struct anv_surface shadow_surface;
3270 
3271       /**
3272        * The base aux usage for this image.  For color images, this can be
3273        * either CCS_E or CCS_D depending on whether or not we can reliably
3274        * leave CCS on all the time.
3275        */
3276       enum isl_aux_usage aux_usage;
3277 
3278       struct anv_surface aux_surface;
3279 
3280       /** Location of the fast clear state.  */
3281       struct anv_image_memory_range fast_clear_memory_range;
3282 
3283       /**
3284        * Whether this image can be fast cleared with non-zero clear colors.
3285        * This can happen with mutable images when formats of different bit
3286        * sizes per components are used.
3287        *
3288        * On Gfx9+, because the clear colors are stored as a 4 components 32bit
3289        * values, we can clear in R16G16_UNORM (store 2 16bit values in the
3290        * components 0 & 1 of the clear color) and then draw in R32_UINT which
3291        * would interpret the clear color as a single component value, using
3292        * only the first 16bit component of the previous written clear color.
3293        *
3294        * On Gfx7/7.5/8, only CC_ZERO/CC_ONE clear colors are supported, this
3295        * boolean will prevent the usage of CC_ONE.
3296        */
3297       bool can_non_zero_fast_clear;
3298    } planes[3];
3299 };
3300 
3301 static inline bool
anv_image_is_externally_shared(const struct anv_image * image)3302 anv_image_is_externally_shared(const struct anv_image *image)
3303 {
3304    return image->vk.drm_format_mod != DRM_FORMAT_MOD_INVALID ||
3305           image->vk.external_handle_types != 0;
3306 }
3307 
3308 static inline bool
anv_image_has_private_binding(const struct anv_image * image)3309 anv_image_has_private_binding(const struct anv_image *image)
3310 {
3311    const struct anv_image_binding private_binding =
3312       image->bindings[ANV_IMAGE_MEMORY_BINDING_PRIVATE];
3313    return private_binding.memory_range.size != 0;
3314 }
3315 
3316 /* The ordering of this enum is important */
3317 enum anv_fast_clear_type {
3318    /** Image does not have/support any fast-clear blocks */
3319    ANV_FAST_CLEAR_NONE = 0,
3320    /** Image has/supports fast-clear but only to the default value */
3321    ANV_FAST_CLEAR_DEFAULT_VALUE = 1,
3322    /** Image has/supports fast-clear with an arbitrary fast-clear value */
3323    ANV_FAST_CLEAR_ANY = 2,
3324 };
3325 
3326 /**
3327  * Return the aspect's _format_ plane, not its _memory_ plane (using the
3328  * vocabulary of VK_EXT_image_drm_format_modifier). As a consequence, \a
3329  * aspect_mask may contain VK_IMAGE_ASPECT_PLANE_*, but must not contain
3330  * VK_IMAGE_ASPECT_MEMORY_PLANE_* .
3331  */
3332 static inline uint32_t
anv_image_aspect_to_plane(const struct anv_image * image,VkImageAspectFlagBits aspect)3333 anv_image_aspect_to_plane(const struct anv_image *image,
3334                           VkImageAspectFlagBits aspect)
3335 {
3336    return anv_aspect_to_plane(image->vk.aspects, aspect);
3337 }
3338 
3339 /* Returns the number of auxiliary buffer levels attached to an image. */
3340 static inline uint8_t
anv_image_aux_levels(const struct anv_image * const image,VkImageAspectFlagBits aspect)3341 anv_image_aux_levels(const struct anv_image * const image,
3342                      VkImageAspectFlagBits aspect)
3343 {
3344    uint32_t plane = anv_image_aspect_to_plane(image, aspect);
3345    if (image->planes[plane].aux_usage == ISL_AUX_USAGE_NONE)
3346       return 0;
3347 
3348    return image->vk.mip_levels;
3349 }
3350 
3351 /* Returns the number of auxiliary buffer layers attached to an image. */
3352 static inline uint32_t
anv_image_aux_layers(const struct anv_image * const image,VkImageAspectFlagBits aspect,const uint8_t miplevel)3353 anv_image_aux_layers(const struct anv_image * const image,
3354                      VkImageAspectFlagBits aspect,
3355                      const uint8_t miplevel)
3356 {
3357    assert(image);
3358 
3359    /* The miplevel must exist in the main buffer. */
3360    assert(miplevel < image->vk.mip_levels);
3361 
3362    if (miplevel >= anv_image_aux_levels(image, aspect)) {
3363       /* There are no layers with auxiliary data because the miplevel has no
3364        * auxiliary data.
3365        */
3366       return 0;
3367    }
3368 
3369    return MAX2(image->vk.array_layers, image->vk.extent.depth >> miplevel);
3370 }
3371 
3372 static inline struct anv_address MUST_CHECK
anv_image_address(const struct anv_image * image,const struct anv_image_memory_range * mem_range)3373 anv_image_address(const struct anv_image *image,
3374                   const struct anv_image_memory_range *mem_range)
3375 {
3376    const struct anv_image_binding *binding = &image->bindings[mem_range->binding];
3377    assert(binding->memory_range.offset == 0);
3378 
3379    if (mem_range->size == 0)
3380       return ANV_NULL_ADDRESS;
3381 
3382    return anv_address_add(binding->address, mem_range->offset);
3383 }
3384 
3385 static inline struct anv_address
anv_image_get_clear_color_addr(UNUSED const struct anv_device * device,const struct anv_image * image,VkImageAspectFlagBits aspect)3386 anv_image_get_clear_color_addr(UNUSED const struct anv_device *device,
3387                                const struct anv_image *image,
3388                                VkImageAspectFlagBits aspect)
3389 {
3390    assert(image->vk.aspects & (VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV |
3391                                VK_IMAGE_ASPECT_DEPTH_BIT));
3392 
3393    uint32_t plane = anv_image_aspect_to_plane(image, aspect);
3394    const struct anv_image_memory_range *mem_range =
3395       &image->planes[plane].fast_clear_memory_range;
3396 
3397    return anv_image_address(image, mem_range);
3398 }
3399 
3400 static inline struct anv_address
anv_image_get_fast_clear_type_addr(const struct anv_device * device,const struct anv_image * image,VkImageAspectFlagBits aspect)3401 anv_image_get_fast_clear_type_addr(const struct anv_device *device,
3402                                    const struct anv_image *image,
3403                                    VkImageAspectFlagBits aspect)
3404 {
3405    struct anv_address addr =
3406       anv_image_get_clear_color_addr(device, image, aspect);
3407 
3408    const unsigned clear_color_state_size = device->info->ver >= 10 ?
3409       device->isl_dev.ss.clear_color_state_size :
3410       device->isl_dev.ss.clear_value_size;
3411    return anv_address_add(addr, clear_color_state_size);
3412 }
3413 
3414 /* Returns true if a HiZ-enabled depth buffer can be sampled from. */
3415 static inline bool
anv_can_sample_with_hiz(const struct intel_device_info * const devinfo,const struct anv_image * image)3416 anv_can_sample_with_hiz(const struct intel_device_info * const devinfo,
3417                         const struct anv_image *image)
3418 {
3419    if (!(image->vk.aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
3420       return false;
3421 
3422    /* For Gfx8-11, there are some restrictions around sampling from HiZ.
3423     * The Skylake PRM docs for RENDER_SURFACE_STATE::AuxiliarySurfaceMode
3424     * say:
3425     *
3426     *    "If this field is set to AUX_HIZ, Number of Multisamples must
3427     *    be MULTISAMPLECOUNT_1, and Surface Type cannot be SURFTYPE_3D."
3428     */
3429    if (image->vk.image_type == VK_IMAGE_TYPE_3D)
3430       return false;
3431 
3432    /* Allow this feature on BDW even though it is disabled in the BDW devinfo
3433     * struct. There's documentation which suggests that this feature actually
3434     * reduces performance on BDW, but it has only been observed to help so
3435     * far. Sampling fast-cleared blocks on BDW must also be handled with care
3436     * (see depth_stencil_attachment_compute_aux_usage() for more info).
3437     */
3438    if (devinfo->ver != 8 && !devinfo->has_sample_with_hiz)
3439       return false;
3440 
3441    return image->vk.samples == 1;
3442 }
3443 
3444 void
3445 anv_cmd_buffer_mark_image_written(struct anv_cmd_buffer *cmd_buffer,
3446                                   const struct anv_image *image,
3447                                   VkImageAspectFlagBits aspect,
3448                                   enum isl_aux_usage aux_usage,
3449                                   uint32_t level,
3450                                   uint32_t base_layer,
3451                                   uint32_t layer_count);
3452 
3453 void
3454 anv_image_clear_color(struct anv_cmd_buffer *cmd_buffer,
3455                       const struct anv_image *image,
3456                       VkImageAspectFlagBits aspect,
3457                       enum isl_aux_usage aux_usage,
3458                       enum isl_format format, struct isl_swizzle swizzle,
3459                       uint32_t level, uint32_t base_layer, uint32_t layer_count,
3460                       VkRect2D area, union isl_color_value clear_color);
3461 void
3462 anv_image_clear_depth_stencil(struct anv_cmd_buffer *cmd_buffer,
3463                               const struct anv_image *image,
3464                               VkImageAspectFlags aspects,
3465                               enum isl_aux_usage depth_aux_usage,
3466                               uint32_t level,
3467                               uint32_t base_layer, uint32_t layer_count,
3468                               VkRect2D area,
3469                               float depth_value, uint8_t stencil_value);
3470 void
3471 anv_image_msaa_resolve(struct anv_cmd_buffer *cmd_buffer,
3472                        const struct anv_image *src_image,
3473                        enum isl_aux_usage src_aux_usage,
3474                        uint32_t src_level, uint32_t src_base_layer,
3475                        const struct anv_image *dst_image,
3476                        enum isl_aux_usage dst_aux_usage,
3477                        uint32_t dst_level, uint32_t dst_base_layer,
3478                        VkImageAspectFlagBits aspect,
3479                        uint32_t src_x, uint32_t src_y,
3480                        uint32_t dst_x, uint32_t dst_y,
3481                        uint32_t width, uint32_t height,
3482                        uint32_t layer_count,
3483                        enum blorp_filter filter);
3484 void
3485 anv_image_hiz_op(struct anv_cmd_buffer *cmd_buffer,
3486                  const struct anv_image *image,
3487                  VkImageAspectFlagBits aspect, uint32_t level,
3488                  uint32_t base_layer, uint32_t layer_count,
3489                  enum isl_aux_op hiz_op);
3490 void
3491 anv_image_hiz_clear(struct anv_cmd_buffer *cmd_buffer,
3492                     const struct anv_image *image,
3493                     VkImageAspectFlags aspects,
3494                     uint32_t level,
3495                     uint32_t base_layer, uint32_t layer_count,
3496                     VkRect2D area, uint8_t stencil_value);
3497 void
3498 anv_image_mcs_op(struct anv_cmd_buffer *cmd_buffer,
3499                  const struct anv_image *image,
3500                  enum isl_format format, struct isl_swizzle swizzle,
3501                  VkImageAspectFlagBits aspect,
3502                  uint32_t base_layer, uint32_t layer_count,
3503                  enum isl_aux_op mcs_op, union isl_color_value *clear_value,
3504                  bool predicate);
3505 void
3506 anv_image_ccs_op(struct anv_cmd_buffer *cmd_buffer,
3507                  const struct anv_image *image,
3508                  enum isl_format format, struct isl_swizzle swizzle,
3509                  VkImageAspectFlagBits aspect, uint32_t level,
3510                  uint32_t base_layer, uint32_t layer_count,
3511                  enum isl_aux_op ccs_op, union isl_color_value *clear_value,
3512                  bool predicate);
3513 
3514 void
3515 anv_image_copy_to_shadow(struct anv_cmd_buffer *cmd_buffer,
3516                          const struct anv_image *image,
3517                          VkImageAspectFlagBits aspect,
3518                          uint32_t base_level, uint32_t level_count,
3519                          uint32_t base_layer, uint32_t layer_count);
3520 
3521 enum isl_aux_state ATTRIBUTE_PURE
3522 anv_layout_to_aux_state(const struct intel_device_info * const devinfo,
3523                         const struct anv_image *image,
3524                         const VkImageAspectFlagBits aspect,
3525                         const VkImageLayout layout);
3526 
3527 enum isl_aux_usage ATTRIBUTE_PURE
3528 anv_layout_to_aux_usage(const struct intel_device_info * const devinfo,
3529                         const struct anv_image *image,
3530                         const VkImageAspectFlagBits aspect,
3531                         const VkImageUsageFlagBits usage,
3532                         const VkImageLayout layout);
3533 
3534 enum anv_fast_clear_type ATTRIBUTE_PURE
3535 anv_layout_to_fast_clear_type(const struct intel_device_info * const devinfo,
3536                               const struct anv_image * const image,
3537                               const VkImageAspectFlagBits aspect,
3538                               const VkImageLayout layout);
3539 
3540 static inline bool
anv_image_aspects_compatible(VkImageAspectFlags aspects1,VkImageAspectFlags aspects2)3541 anv_image_aspects_compatible(VkImageAspectFlags aspects1,
3542                              VkImageAspectFlags aspects2)
3543 {
3544    if (aspects1 == aspects2)
3545       return true;
3546 
3547    /* Only 1 color aspects are compatibles. */
3548    if ((aspects1 & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) != 0 &&
3549        (aspects2 & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) != 0 &&
3550        util_bitcount(aspects1) == util_bitcount(aspects2))
3551       return true;
3552 
3553    return false;
3554 }
3555 
3556 struct anv_image_view {
3557    struct vk_image_view vk;
3558 
3559    const struct anv_image *image; /**< VkImageViewCreateInfo::image */
3560 
3561    unsigned n_planes;
3562    struct {
3563       uint32_t image_plane;
3564 
3565       struct isl_view isl;
3566 
3567       /**
3568        * RENDER_SURFACE_STATE when using image as a sampler surface with an
3569        * image layout of SHADER_READ_ONLY_OPTIMAL or
3570        * DEPTH_STENCIL_READ_ONLY_OPTIMAL.
3571        */
3572       struct anv_surface_state optimal_sampler_surface_state;
3573 
3574       /**
3575        * RENDER_SURFACE_STATE when using image as a sampler surface with an
3576        * image layout of GENERAL.
3577        */
3578       struct anv_surface_state general_sampler_surface_state;
3579 
3580       /**
3581        * RENDER_SURFACE_STATE when using image as a storage image. Separate
3582        * states for vanilla (with the original format) and one which has been
3583        * lowered to a format suitable for reading.  This may be a raw surface
3584        * in extreme cases or simply a surface with a different format where we
3585        * expect some conversion to be done in the shader.
3586        */
3587       struct anv_surface_state storage_surface_state;
3588       struct anv_surface_state lowered_storage_surface_state;
3589 
3590       struct isl_image_param lowered_storage_image_param;
3591    } planes[3];
3592 };
3593 
3594 enum anv_image_view_state_flags {
3595    ANV_IMAGE_VIEW_STATE_STORAGE_LOWERED      = (1 << 0),
3596    ANV_IMAGE_VIEW_STATE_TEXTURE_OPTIMAL      = (1 << 1),
3597 };
3598 
3599 void anv_image_fill_surface_state(struct anv_device *device,
3600                                   const struct anv_image *image,
3601                                   VkImageAspectFlagBits aspect,
3602                                   const struct isl_view *view,
3603                                   isl_surf_usage_flags_t view_usage,
3604                                   enum isl_aux_usage aux_usage,
3605                                   const union isl_color_value *clear_color,
3606                                   enum anv_image_view_state_flags flags,
3607                                   struct anv_surface_state *state_inout,
3608                                   struct isl_image_param *image_param_out);
3609 
3610 struct anv_image_create_info {
3611    const VkImageCreateInfo *vk_info;
3612 
3613    /** An opt-in bitmask which filters an ISL-mapping of the Vulkan tiling. */
3614    isl_tiling_flags_t isl_tiling_flags;
3615 
3616    /** These flags will be added to any derived from VkImageCreateInfo. */
3617    isl_surf_usage_flags_t isl_extra_usage_flags;
3618 };
3619 
3620 VkResult anv_image_init(struct anv_device *device, struct anv_image *image,
3621                         const struct anv_image_create_info *create_info);
3622 
3623 void anv_image_finish(struct anv_image *image);
3624 
3625 void anv_image_get_memory_requirements(struct anv_device *device,
3626                                        struct anv_image *image,
3627                                        VkImageAspectFlags aspects,
3628                                        VkMemoryRequirements2 *pMemoryRequirements);
3629 
3630 enum isl_format
3631 anv_isl_format_for_descriptor_type(const struct anv_device *device,
3632                                    VkDescriptorType type);
3633 
3634 static inline uint32_t
anv_rasterization_aa_mode(VkPolygonMode raster_mode,VkLineRasterizationModeEXT line_mode)3635 anv_rasterization_aa_mode(VkPolygonMode raster_mode,
3636                           VkLineRasterizationModeEXT line_mode)
3637 {
3638    if (raster_mode == VK_POLYGON_MODE_LINE &&
3639        line_mode == VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT)
3640       return true;
3641    return false;
3642 }
3643 
3644 VkFormatFeatureFlags2
3645 anv_get_image_format_features2(const struct intel_device_info *devinfo,
3646                                VkFormat vk_format,
3647                                const struct anv_format *anv_format,
3648                                VkImageTiling vk_tiling,
3649                                const struct isl_drm_modifier_info *isl_mod_info);
3650 
3651 void anv_fill_buffer_surface_state(struct anv_device *device,
3652                                    struct anv_state state,
3653                                    enum isl_format format,
3654                                    struct isl_swizzle swizzle,
3655                                    isl_surf_usage_flags_t usage,
3656                                    struct anv_address address,
3657                                    uint32_t range, uint32_t stride);
3658 
3659 
3660 /* Haswell border color is a bit of a disaster.  Float and unorm formats use a
3661  * straightforward 32-bit float color in the first 64 bytes.  Instead of using
3662  * a nice float/integer union like Gfx8+, Haswell specifies the integer border
3663  * color as a separate entry /after/ the float color.  The layout of this entry
3664  * also depends on the format's bpp (with extra hacks for RG32), and overlaps.
3665  *
3666  * Since we don't know the format/bpp, we can't make any of the border colors
3667  * containing '1' work for all formats, as it would be in the wrong place for
3668  * some of them.  We opt to make 32-bit integers work as this seems like the
3669  * most common option.  Fortunately, transparent black works regardless, as
3670  * all zeroes is the same in every bit-size.
3671  */
3672 struct hsw_border_color {
3673    float float32[4];
3674    uint32_t _pad0[12];
3675    uint32_t uint32[4];
3676    uint32_t _pad1[108];
3677 };
3678 
3679 struct gfx8_border_color {
3680    union {
3681       float float32[4];
3682       uint32_t uint32[4];
3683    };
3684    /* Pad out to 64 bytes */
3685    uint32_t _pad[12];
3686 };
3687 
3688 struct anv_sampler {
3689    struct vk_object_base        base;
3690 
3691    uint32_t                     state[3][4];
3692    uint32_t                     n_planes;
3693    struct vk_ycbcr_conversion  *conversion;
3694 
3695    /* Blob of sampler state data which is guaranteed to be 32-byte aligned
3696     * and with a 32-byte stride for use as bindless samplers.
3697     */
3698    struct anv_state             bindless_state;
3699 
3700    struct anv_state             custom_border_color;
3701 };
3702 
3703 #define ANV_PIPELINE_STATISTICS_MASK 0x000007ff
3704 
3705 struct anv_query_pool {
3706    struct vk_object_base                        base;
3707 
3708    VkQueryType                                  type;
3709    VkQueryPipelineStatisticFlags                pipeline_statistics;
3710    /** Stride between slots, in bytes */
3711    uint32_t                                     stride;
3712    /** Number of slots in this query pool */
3713    uint32_t                                     slots;
3714    struct anv_bo *                              bo;
3715 
3716    /* KHR perf queries : */
3717    uint32_t                                     pass_size;
3718    uint32_t                                     data_offset;
3719    uint32_t                                     snapshot_size;
3720    uint32_t                                     n_counters;
3721    struct intel_perf_counter_pass                *counter_pass;
3722    uint32_t                                     n_passes;
3723    struct intel_perf_query_info                 **pass_query;
3724 };
3725 
khr_perf_query_preamble_offset(const struct anv_query_pool * pool,uint32_t pass)3726 static inline uint32_t khr_perf_query_preamble_offset(const struct anv_query_pool *pool,
3727                                                       uint32_t pass)
3728 {
3729    return pool->pass_size * pass + 8;
3730 }
3731 
3732 void
3733 anv_dump_pipe_bits(enum anv_pipe_bits bits);
3734 
3735 static inline void
anv_add_pending_pipe_bits(struct anv_cmd_buffer * cmd_buffer,enum anv_pipe_bits bits,const char * reason)3736 anv_add_pending_pipe_bits(struct anv_cmd_buffer* cmd_buffer,
3737                           enum anv_pipe_bits bits,
3738                           const char* reason)
3739 {
3740    cmd_buffer->state.pending_pipe_bits |= bits;
3741    if (INTEL_DEBUG(DEBUG_PIPE_CONTROL) && bits)
3742    {
3743       fputs("pc: add ", stderr);
3744       anv_dump_pipe_bits(bits);
3745       fprintf(stderr, "reason: %s\n", reason);
3746    }
3747 }
3748 
3749 struct anv_performance_configuration_intel {
3750    struct vk_object_base      base;
3751 
3752    struct intel_perf_registers *register_config;
3753 
3754    uint64_t                   config_id;
3755 };
3756 
3757 void anv_physical_device_init_perf(struct anv_physical_device *device, int fd);
3758 void anv_device_perf_init(struct anv_device *device);
3759 void anv_perf_write_pass_results(struct intel_perf_config *perf,
3760                                  struct anv_query_pool *pool, uint32_t pass,
3761                                  const struct intel_perf_query_result *accumulated_results,
3762                                  union VkPerformanceCounterResultKHR *results);
3763 
3764 /* Use to emit a series of memcpy operations */
3765 struct anv_memcpy_state {
3766    struct anv_device *device;
3767    struct anv_batch *batch;
3768 
3769    struct anv_vb_cache_range vb_bound;
3770    struct anv_vb_cache_range vb_dirty;
3771 };
3772 
3773 struct anv_utrace_flush_copy {
3774    /* Needs to be the first field */
3775    struct intel_ds_flush_data ds;
3776 
3777    /* Batch stuff to implement of copy of timestamps recorded in another
3778     * buffer.
3779     */
3780    struct anv_reloc_list relocs;
3781    struct anv_batch batch;
3782    struct anv_bo *batch_bo;
3783 
3784    /* Buffer of 64bits timestamps */
3785    struct anv_bo *trace_bo;
3786 
3787    /* Syncobj to be signaled when the batch completes */
3788    struct vk_sync *sync;
3789 
3790    /* Queue on which all the recorded traces are submitted */
3791    struct anv_queue *queue;
3792 
3793    struct anv_memcpy_state memcpy_state;
3794 };
3795 
3796 void anv_device_utrace_init(struct anv_device *device);
3797 void anv_device_utrace_finish(struct anv_device *device);
3798 VkResult
3799 anv_device_utrace_flush_cmd_buffers(struct anv_queue *queue,
3800                                     uint32_t cmd_buffer_count,
3801                                     struct anv_cmd_buffer **cmd_buffers,
3802                                     struct anv_utrace_flush_copy **out_flush_data);
3803 
3804 #ifdef HAVE_PERFETTO
3805 void anv_perfetto_init(void);
3806 uint64_t anv_perfetto_begin_submit(struct anv_queue *queue);
3807 void anv_perfetto_end_submit(struct anv_queue *queue, uint32_t submission_id,
3808                              uint64_t start_ts);
3809 #else
anv_perfetto_init(void)3810 static inline void anv_perfetto_init(void)
3811 {
3812 }
anv_perfetto_begin_submit(struct anv_queue * queue)3813 static inline uint64_t anv_perfetto_begin_submit(struct anv_queue *queue)
3814 {
3815    return 0;
3816 }
anv_perfetto_end_submit(struct anv_queue * queue,uint32_t submission_id,uint64_t start_ts)3817 static inline void anv_perfetto_end_submit(struct anv_queue *queue,
3818                                            uint32_t submission_id,
3819                                            uint64_t start_ts)
3820 {}
3821 #endif
3822 
3823 
3824 #define ANV_FROM_HANDLE(__anv_type, __name, __handle) \
3825    VK_FROM_HANDLE(__anv_type, __name, __handle)
3826 
3827 VK_DEFINE_HANDLE_CASTS(anv_cmd_buffer, vk.base, VkCommandBuffer,
3828                        VK_OBJECT_TYPE_COMMAND_BUFFER)
3829 VK_DEFINE_HANDLE_CASTS(anv_device, vk.base, VkDevice, VK_OBJECT_TYPE_DEVICE)
3830 VK_DEFINE_HANDLE_CASTS(anv_instance, vk.base, VkInstance, VK_OBJECT_TYPE_INSTANCE)
3831 VK_DEFINE_HANDLE_CASTS(anv_physical_device, vk.base, VkPhysicalDevice,
3832                        VK_OBJECT_TYPE_PHYSICAL_DEVICE)
3833 VK_DEFINE_HANDLE_CASTS(anv_queue, vk.base, VkQueue, VK_OBJECT_TYPE_QUEUE)
3834 
3835 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer, vk.base, VkBuffer,
3836                                VK_OBJECT_TYPE_BUFFER)
3837 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer_view, base, VkBufferView,
3838                                VK_OBJECT_TYPE_BUFFER_VIEW)
3839 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_pool, base, VkDescriptorPool,
3840                                VK_OBJECT_TYPE_DESCRIPTOR_POOL)
3841 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set, base, VkDescriptorSet,
3842                                VK_OBJECT_TYPE_DESCRIPTOR_SET)
3843 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set_layout, base,
3844                                VkDescriptorSetLayout,
3845                                VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT)
3846 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_device_memory, base, VkDeviceMemory,
3847                                VK_OBJECT_TYPE_DEVICE_MEMORY)
3848 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_event, base, VkEvent, VK_OBJECT_TYPE_EVENT)
3849 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_image, vk.base, VkImage, VK_OBJECT_TYPE_IMAGE)
3850 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_image_view, vk.base, VkImageView,
3851                                VK_OBJECT_TYPE_IMAGE_VIEW);
3852 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline, base, VkPipeline,
3853                                VK_OBJECT_TYPE_PIPELINE)
3854 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline_layout, base, VkPipelineLayout,
3855                                VK_OBJECT_TYPE_PIPELINE_LAYOUT)
3856 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_query_pool, base, VkQueryPool,
3857                                VK_OBJECT_TYPE_QUERY_POOL)
3858 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_sampler, base, VkSampler,
3859                                VK_OBJECT_TYPE_SAMPLER)
3860 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_performance_configuration_intel, base,
3861                                VkPerformanceConfigurationINTEL,
3862                                VK_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL)
3863 
3864 #define anv_genX(devinfo, thing) ({             \
3865    __typeof(&gfx7_##thing) genX_thing;          \
3866    switch ((devinfo)->verx10) {                 \
3867    case 70:                                     \
3868       genX_thing = &gfx7_##thing;               \
3869       break;                                    \
3870    case 75:                                     \
3871       genX_thing = &gfx75_##thing;              \
3872       break;                                    \
3873    case 80:                                     \
3874       genX_thing = &gfx8_##thing;               \
3875       break;                                    \
3876    default:                                     \
3877       unreachable("Unknown hardware generation"); \
3878    }                                            \
3879    genX_thing;                                  \
3880 })
3881 
3882 /* Gen-specific function declarations */
3883 #ifdef genX
3884 #  include "anv_genX.h"
3885 #else
3886 #  define genX(x) gfx7_##x
3887 #  include "anv_genX.h"
3888 #  undef genX
3889 #  define genX(x) gfx75_##x
3890 #  include "anv_genX.h"
3891 #  undef genX
3892 #  define genX(x) gfx8_##x
3893 #  include "anv_genX.h"
3894 #  undef genX
3895 #endif
3896 
3897 #endif /* ANV_PRIVATE_H */
3898