• 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/drm_fourcc.h"
34 
35 #ifdef HAVE_VALGRIND
36 #include <valgrind.h>
37 #include <memcheck.h>
38 #define VG(x) x
39 #else
40 #define VG(x) ((void)0)
41 #endif
42 
43 #include "common/intel_aux_map.h"
44 #include "common/intel_bind_timeline.h"
45 #include "common/intel_engine.h"
46 #include "common/intel_gem.h"
47 #include "common/intel_l3_config.h"
48 #include "common/intel_measure.h"
49 #include "common/intel_mem.h"
50 #include "common/intel_sample_positions.h"
51 #include "decoder/intel_decoder.h"
52 #include "dev/intel_device_info.h"
53 #include "blorp/blorp.h"
54 #include "compiler/brw_compiler.h"
55 #include "compiler/brw_kernel.h"
56 #include "compiler/brw_rt.h"
57 #include "ds/intel_driver_ds.h"
58 #include "util/bitset.h"
59 #include "util/bitscan.h"
60 #include "util/detect_os.h"
61 #include "util/macros.h"
62 #include "util/hash_table.h"
63 #include "util/list.h"
64 #include "util/perf/u_trace.h"
65 #include "util/set.h"
66 #include "util/sparse_array.h"
67 #include "util/u_atomic.h"
68 #if DETECT_OS_ANDROID
69 #include "util/u_gralloc/u_gralloc.h"
70 #endif
71 #include "util/u_vector.h"
72 #include "util/u_math.h"
73 #include "util/vma.h"
74 #include "util/xmlconfig.h"
75 #include "vk_acceleration_structure.h"
76 #include "vk_alloc.h"
77 #include "vk_buffer.h"
78 #include "vk_buffer_view.h"
79 #include "vk_command_buffer.h"
80 #include "vk_command_pool.h"
81 #include "vk_debug_report.h"
82 #include "vk_descriptor_update_template.h"
83 #include "vk_device.h"
84 #include "vk_device_memory.h"
85 #include "vk_drm_syncobj.h"
86 #include "vk_enum_defines.h"
87 #include "vk_format.h"
88 #include "vk_framebuffer.h"
89 #include "vk_graphics_state.h"
90 #include "vk_image.h"
91 #include "vk_instance.h"
92 #include "vk_pipeline_cache.h"
93 #include "vk_physical_device.h"
94 #include "vk_sampler.h"
95 #include "vk_shader_module.h"
96 #include "vk_sync.h"
97 #include "vk_sync_timeline.h"
98 #include "vk_texcompress_astc.h"
99 #include "vk_util.h"
100 #include "vk_query_pool.h"
101 #include "vk_queue.h"
102 #include "vk_log.h"
103 #include "vk_ycbcr_conversion.h"
104 #include "vk_video.h"
105 #include "vk_meta.h"
106 
107 #ifdef __cplusplus
108 extern "C" {
109 #endif
110 
111 /* Pre-declarations needed for WSI entrypoints */
112 struct wl_surface;
113 struct wl_display;
114 typedef struct xcb_connection_t xcb_connection_t;
115 typedef uint32_t xcb_visualid_t;
116 typedef uint32_t xcb_window_t;
117 
118 struct anv_batch;
119 struct anv_buffer;
120 struct anv_buffer_view;
121 struct anv_image_view;
122 struct anv_instance;
123 
124 struct intel_aux_map_context;
125 struct intel_perf_config;
126 struct intel_perf_counter_pass;
127 struct intel_perf_query_result;
128 
129 #include <vulkan/vulkan.h>
130 #include <vulkan/vk_icd.h>
131 
132 #include "anv_android.h"
133 #include "anv_entrypoints.h"
134 #include "anv_kmd_backend.h"
135 #include "anv_rmv.h"
136 #include "isl/isl.h"
137 
138 #include "dev/intel_debug.h"
139 #undef MESA_LOG_TAG
140 #define MESA_LOG_TAG "MESA-INTEL"
141 #include "util/log.h"
142 #include "wsi_common.h"
143 
144 /* The "RAW" clocks on Linux are called "FAST" on FreeBSD */
145 #if !defined(CLOCK_MONOTONIC_RAW) && defined(CLOCK_MONOTONIC_FAST)
146 #define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC_FAST
147 #endif
148 
149 #define NSEC_PER_SEC 1000000000ull
150 
151 #define BINDING_TABLE_POOL_BLOCK_SIZE (65536)
152 
153 /* 3DSTATE_VERTEX_BUFFER supports 33 VBs, we use 2 for base & drawid SGVs */
154 #define MAX_VBS         (33 - 2)
155 
156 /* 3DSTATE_VERTEX_ELEMENTS supports up to 34 VEs, but our backend compiler
157  * only supports the push model of VS inputs, and we only have 128 GRFs,
158  * minus the g0 and g1 payload, which gives us a maximum of 31 VEs.  Plus,
159  * we use two of them for SGVs.
160  */
161 #define MAX_VES         (31 - 2)
162 
163 #define MAX_XFB_BUFFERS  4
164 #define MAX_XFB_STREAMS  4
165 #define MAX_SETS         8
166 #define MAX_RTS          8
167 #define MAX_VIEWPORTS   16
168 #define MAX_SCISSORS    16
169 #define MAX_PUSH_CONSTANTS_SIZE 256  /* Minimum requirement as of Vulkan 1.4 */
170 #define MAX_DYNAMIC_BUFFERS 16
171 #define MAX_PUSH_DESCRIPTORS 32 /* Minimum requirement */
172 #define MAX_INLINE_UNIFORM_BLOCK_SIZE 4096
173 #define MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS 32
174 #define MAX_EMBEDDED_SAMPLERS 2048
175 #define MAX_CUSTOM_BORDER_COLORS 4096
176 /* We need 16 for UBO block reads to work and 32 for push UBOs. However, we
177  * use 64 here to avoid cache issues. This could most likely bring it back to
178  * 32 if we had different virtual addresses for the different views on a given
179  * GEM object.
180  */
181 #define ANV_UBO_ALIGNMENT 64
182 #define ANV_SSBO_ALIGNMENT 4
183 #define ANV_SSBO_BOUNDS_CHECK_ALIGNMENT 4
184 #define MAX_VIEWS_FOR_PRIMITIVE_REPLICATION 16
185 #define MAX_SAMPLE_LOCATIONS 16
186 
187 /* RENDER_SURFACE_STATE is a bit smaller (48b) but since it is aligned to 64
188  * and we can't put anything else there we use 64b.
189  */
190 #define ANV_SURFACE_STATE_SIZE (64)
191 
192 /* From the Skylake PRM Vol. 7 "Binding Table Surface State Model":
193  *
194  *    "The surface state model is used when a Binding Table Index (specified
195  *    in the message descriptor) of less than 240 is specified. In this model,
196  *    the Binding Table Index is used to index into the binding table, and the
197  *    binding table entry contains a pointer to the SURFACE_STATE."
198  *
199  * Binding table values above 240 are used for various things in the hardware
200  * such as stateless, stateless with incoherent cache, SLM, and bindless.
201  */
202 #define MAX_BINDING_TABLE_SIZE 240
203 
204 #define ANV_SVGS_VB_INDEX    MAX_VBS
205 #define ANV_DRAWID_VB_INDEX (MAX_VBS + 1)
206 
207 /* We reserve this MI ALU register for the purpose of handling predication.
208  * Other code which uses the MI ALU should leave it alone.
209  */
210 #define ANV_PREDICATE_RESULT_REG 0x2678 /* MI_ALU_REG15 */
211 
212 /* We reserve this MI ALU register to pass around an offset computed from
213  * VkPerformanceQuerySubmitInfoKHR::counterPassIndex VK_KHR_performance_query.
214  * Other code which uses the MI ALU should leave it alone.
215  */
216 #define ANV_PERF_QUERY_OFFSET_REG 0x2670 /* MI_ALU_REG14 */
217 
218 /* We reserve this MI ALU register to hold the last programmed bindless
219  * surface state base address so that we can predicate STATE_BASE_ADDRESS
220  * emissions if the address doesn't change.
221  */
222 #define ANV_BINDLESS_SURFACE_BASE_ADDR_REG 0x2668 /* MI_ALU_REG13 */
223 
224 #define ANV_GRAPHICS_SHADER_STAGE_COUNT (MESA_SHADER_MESH + 1)
225 
226 #define ANV_INLINE_PARAM_NUM_WORKGROUPS_OFFSET (8)
227 
228 /* RENDER_SURFACE_STATE is a bit smaller (48b) but since it is aligned to 64
229  * and we can't put anything else there we use 64b.
230  */
231 #define ANV_SURFACE_STATE_SIZE (64)
232 #define ANV_SAMPLER_STATE_SIZE (32)
233 
234 /* For gfx12 we set the streamout buffers using 4 separate commands
235  * (3DSTATE_SO_BUFFER_INDEX_*) instead of 3DSTATE_SO_BUFFER. However the layout
236  * of the 3DSTATE_SO_BUFFER_INDEX_* commands is identical to that of
237  * 3DSTATE_SO_BUFFER apart from the SOBufferIndex field, so for now we use the
238  * 3DSTATE_SO_BUFFER command, but change the 3DCommandSubOpcode.
239  * SO_BUFFER_INDEX_0_CMD is actually the 3DCommandSubOpcode for
240  * 3DSTATE_SO_BUFFER_INDEX_0.
241  */
242 #define SO_BUFFER_INDEX_0_CMD 0x60
243 #define anv_printflike(a, b) __attribute__((__format__(__printf__, a, b)))
244 
245 /* The TR-TT L1 page table entries may contain these values instead of actual
246  * pointers to indicate the regions are either NULL or invalid. We program
247  * these values to TR-TT registers, so we could change them, but it's super
248  * convenient to have the NULL value be 0 because everything is
249  * zero-initialized when allocated.
250  *
251  * Since we reserve these values for NULL/INVALID, then we can't use them as
252  * destinations for TR-TT address translation. Both values are shifted by 16
253  * bits, wich results in graphic addresses 0 and 64k. On Anv the first vma
254  * starts at 2MB, so we already don't use 0 and 64k for anything, so there's
255  * nothing really to reserve. We could instead just reserve random 64kb
256  * ranges from any of the non-TR-TT vmas and use their addresses.
257  */
258 #define ANV_TRTT_L1_NULL_TILE_VAL 0
259 #define ANV_TRTT_L1_INVALID_TILE_VAL 1
260 
261 #define ANV_COLOR_OUTPUT_DISABLED (0xff)
262 #define ANV_COLOR_OUTPUT_UNUSED   (0xfe)
263 
264 static inline uint32_t
align_down_npot_u32(uint32_t v,uint32_t a)265 align_down_npot_u32(uint32_t v, uint32_t a)
266 {
267    return v - (v % a);
268 }
269 
270 /** Alignment must be a power of 2. */
271 static inline bool
anv_is_aligned(uintmax_t n,uintmax_t a)272 anv_is_aligned(uintmax_t n, uintmax_t a)
273 {
274    assert(a == (a & -a));
275    return (n & (a - 1)) == 0;
276 }
277 
278 static inline union isl_color_value
vk_to_isl_color(VkClearColorValue color)279 vk_to_isl_color(VkClearColorValue color)
280 {
281    return (union isl_color_value) {
282       .u32 = {
283          color.uint32[0],
284          color.uint32[1],
285          color.uint32[2],
286          color.uint32[3],
287       },
288    };
289 }
290 
291 static inline union isl_color_value
vk_to_isl_color_with_format(VkClearColorValue color,enum isl_format format)292 vk_to_isl_color_with_format(VkClearColorValue color, enum isl_format format)
293 {
294    const struct isl_format_layout *fmtl = isl_format_get_layout(format);
295    union isl_color_value isl_color = { .u32 = {0, } };
296 
297 #define COPY_COLOR_CHANNEL(c, i) \
298    if (fmtl->channels.c.bits) \
299       isl_color.u32[i] = color.uint32[i]
300 
301    COPY_COLOR_CHANNEL(r, 0);
302    COPY_COLOR_CHANNEL(g, 1);
303    COPY_COLOR_CHANNEL(b, 2);
304    COPY_COLOR_CHANNEL(a, 3);
305 
306 #undef COPY_COLOR_CHANNEL
307 
308    return isl_color;
309 }
310 
311 void __anv_perf_warn(struct anv_device *device,
312                      const struct vk_object_base *object,
313                      const char *file, int line, const char *format, ...)
314    anv_printflike(5, 6);
315 
316 /**
317  * Print a FINISHME message, including its source location.
318  */
319 #define anv_finishme(format, ...) \
320    do { \
321       static bool reported = false; \
322       if (!reported) { \
323          mesa_logw("%s:%d: FINISHME: " format, __FILE__, __LINE__, \
324                     ##__VA_ARGS__); \
325          reported = true; \
326       } \
327    } while (0)
328 
329 /**
330  * Print a perf warning message.  Set INTEL_DEBUG=perf to see these.
331  */
332 #define anv_perf_warn(objects_macro, format, ...)   \
333    do { \
334       static bool reported = false; \
335       if (!reported && INTEL_DEBUG(DEBUG_PERF)) { \
336          __vk_log(VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT,      \
337                   VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,      \
338                   objects_macro, __FILE__, __LINE__,                    \
339                   format, ## __VA_ARGS__);                              \
340          reported = true; \
341       } \
342    } while (0)
343 
344 /* A non-fatal assert.  Useful for debugging. */
345 #if MESA_DEBUG
346 #define anv_assert(x) ({ \
347    if (unlikely(!(x))) \
348       mesa_loge("%s:%d ASSERT: %s", __FILE__, __LINE__, #x); \
349 })
350 #else
351 #define anv_assert(x)
352 #endif
353 
354 enum anv_bo_alloc_flags {
355    /** Specifies that the BO must have a 32-bit address
356     *
357     * This is the opposite of EXEC_OBJECT_SUPPORTS_48B_ADDRESS.
358     */
359    ANV_BO_ALLOC_32BIT_ADDRESS =           (1 << 0),
360 
361    /** Specifies that the BO may be shared externally */
362    ANV_BO_ALLOC_EXTERNAL =                (1 << 1),
363 
364    /** Specifies that the BO should be mapped */
365    ANV_BO_ALLOC_MAPPED =                  (1 << 2),
366 
367    /** Specifies that the BO should be coherent.
368     *
369     * Note: In platforms with LLC where HOST_CACHED + HOST_COHERENT is free,
370     * bo can get upgraded to HOST_CACHED_COHERENT
371     */
372    ANV_BO_ALLOC_HOST_COHERENT =           (1 << 3),
373 
374    /** Specifies that the BO should be captured in error states */
375    ANV_BO_ALLOC_CAPTURE =                 (1 << 4),
376 
377    /** Specifies that the BO will have an address assigned by the caller
378     *
379     * Such BOs do not exist in any VMA heap.
380     */
381    ANV_BO_ALLOC_FIXED_ADDRESS =           (1 << 5),
382 
383    /** Enables implicit synchronization on the BO
384     *
385     * This is the opposite of EXEC_OBJECT_ASYNC.
386     */
387    ANV_BO_ALLOC_IMPLICIT_SYNC =           (1 << 6),
388 
389    /** Enables implicit synchronization on the BO
390     *
391     * This is equivalent to EXEC_OBJECT_WRITE.
392     */
393    ANV_BO_ALLOC_IMPLICIT_WRITE =          (1 << 7),
394 
395    /** Has an address which is visible to the client */
396    ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS =  (1 << 8),
397 
398    /** Align the BO's virtual address to match AUX-TT requirements */
399    ANV_BO_ALLOC_AUX_TT_ALIGNED =          (1 << 9),
400 
401    /** This buffer is allocated from local memory and should be cpu visible */
402    ANV_BO_ALLOC_LOCAL_MEM_CPU_VISIBLE =   (1 << 10),
403 
404    /** For non device local allocations */
405    ANV_BO_ALLOC_NO_LOCAL_MEM =            (1 << 11),
406 
407    /** This buffer will be scanout to display */
408    ANV_BO_ALLOC_SCANOUT =                 (1 << 12),
409 
410    /** For descriptor pools */
411    ANV_BO_ALLOC_DESCRIPTOR_POOL =         (1 << 13),
412 
413    /** For buffers that will be bound using TR-TT.
414     *
415     * Not for buffers used as the TR-TT page tables.
416     */
417    ANV_BO_ALLOC_TRTT =                    (1 << 14),
418 
419    /** Protected buffer */
420    ANV_BO_ALLOC_PROTECTED =               (1 << 15),
421 
422    /** Specifies that the BO should be cached and incoherent. */
423    ANV_BO_ALLOC_HOST_CACHED =             (1 << 16),
424 
425    /** For buffer addressable from the dynamic state heap */
426    ANV_BO_ALLOC_DYNAMIC_VISIBLE_POOL =    (1 << 17),
427 
428    /** Specifies that the BO is imported.
429     *
430     * Imported BOs must also be marked as ANV_BO_ALLOC_EXTERNAL
431     */
432    ANV_BO_ALLOC_IMPORTED =                (1 << 18),
433 
434    /** Specify whether this BO is internal to the driver */
435    ANV_BO_ALLOC_INTERNAL =                (1 << 19),
436 
437    /** Allocate with CCS AUX requirements
438     *
439     * This pads the BO include CCS data mapppable through the AUX-TT and
440     * aligned to the AUX-TT requirements.
441     */
442    ANV_BO_ALLOC_AUX_CCS =                 (1 << 20),
443 
444    /** Compressed buffer, only supported in Xe2+ */
445    ANV_BO_ALLOC_COMPRESSED =              (1 << 21),
446 };
447 
448 /** Specifies that the BO should be cached and coherent. */
449 #define ANV_BO_ALLOC_HOST_CACHED_COHERENT (ANV_BO_ALLOC_HOST_COHERENT | \
450                                            ANV_BO_ALLOC_HOST_CACHED)
451 
452 
453 struct anv_bo {
454    const char *name;
455 
456    /* The VMA heap in anv_device from which this BO takes its offset.
457     *
458     * This can only be NULL when has_fixed_address is true.
459     */
460    struct util_vma_heap *vma_heap;
461 
462    /* All userptr bos in Xe KMD has gem_handle set to workaround_bo->gem_handle */
463    uint32_t gem_handle;
464 
465    uint32_t refcount;
466 
467    /* Index into the current validation list.  This is used by the
468     * validation list building algorithm to track which buffers are already
469     * in the validation list so that we can ensure uniqueness.
470     */
471    uint32_t exec_obj_index;
472 
473    /* Index for use with util_sparse_array_free_list */
474    uint32_t free_index;
475 
476    /* Last known offset.  This value is provided by the kernel when we
477     * execbuf and is used as the presumed offset for the next bunch of
478     * relocations, in canonical address format.
479     */
480    uint64_t offset;
481 
482    /** Size of the buffer */
483    uint64_t size;
484 
485    /** Offset at which the CCS data is stored */
486    uint64_t ccs_offset;
487 
488    /* Map for internally mapped BOs.
489     *
490     * If ANV_BO_ALLOC_MAPPED is set in flags, this is the map for the whole
491     * BO.
492     */
493    void *map;
494 
495    /* The actual size of bo allocated by kmd, basically:
496     * align(size, mem_alignment)
497     */
498    uint64_t actual_size;
499 
500    /** Flags to pass to the kernel through drm_i915_exec_object2::flags */
501    uint32_t flags;
502 
503    enum anv_bo_alloc_flags alloc_flags;
504 
505    /** True if this BO wraps a host pointer */
506    bool from_host_ptr:1;
507 
508    /** True if this BO is mapped in the GTT (only used for RMV) */
509    bool gtt_mapped:1;
510 };
511 
512 static inline bool
anv_bo_is_external(const struct anv_bo * bo)513 anv_bo_is_external(const struct anv_bo *bo)
514 {
515    return bo->alloc_flags & ANV_BO_ALLOC_EXTERNAL;
516 }
517 
518 static inline bool
anv_bo_is_vram_only(const struct anv_bo * bo)519 anv_bo_is_vram_only(const struct anv_bo *bo)
520 {
521    return !(bo->alloc_flags & (ANV_BO_ALLOC_NO_LOCAL_MEM |
522                                ANV_BO_ALLOC_MAPPED |
523                                ANV_BO_ALLOC_LOCAL_MEM_CPU_VISIBLE |
524                                ANV_BO_ALLOC_IMPORTED));
525 }
526 
527 static inline struct anv_bo *
anv_bo_ref(struct anv_bo * bo)528 anv_bo_ref(struct anv_bo *bo)
529 {
530    p_atomic_inc(&bo->refcount);
531    return bo;
532 }
533 
534 enum intel_device_info_mmap_mode
535 anv_bo_get_mmap_mode(struct anv_device *device, struct anv_bo *bo);
536 
537 static inline bool
anv_bo_needs_host_cache_flush(enum anv_bo_alloc_flags alloc_flags)538 anv_bo_needs_host_cache_flush(enum anv_bo_alloc_flags alloc_flags)
539 {
540    return (alloc_flags & (ANV_BO_ALLOC_HOST_CACHED | ANV_BO_ALLOC_HOST_COHERENT)) ==
541           ANV_BO_ALLOC_HOST_CACHED;
542 }
543 
544 struct anv_address {
545    struct anv_bo *bo;
546    int64_t offset;
547 };
548 
549 #define ANV_NULL_ADDRESS ((struct anv_address) { NULL, 0 })
550 
551 static inline struct anv_address
anv_address_from_u64(uint64_t addr_u64)552 anv_address_from_u64(uint64_t addr_u64)
553 {
554    assert(addr_u64 == intel_canonical_address(addr_u64));
555    return (struct anv_address) {
556       .bo = NULL,
557       .offset = addr_u64,
558    };
559 }
560 
561 static inline bool
anv_address_is_null(struct anv_address addr)562 anv_address_is_null(struct anv_address addr)
563 {
564    return addr.bo == NULL && addr.offset == 0;
565 }
566 
567 static inline uint64_t
anv_address_physical(struct anv_address addr)568 anv_address_physical(struct anv_address addr)
569 {
570    uint64_t address = (addr.bo ? addr.bo->offset : 0ull) + addr.offset;
571    return intel_canonical_address(address);
572 }
573 
574 static inline struct u_trace_address
anv_address_utrace(struct anv_address addr)575 anv_address_utrace(struct anv_address addr)
576 {
577    return (struct u_trace_address) {
578       .bo = addr.bo,
579       .offset = addr.offset,
580    };
581 }
582 
583 static inline struct anv_address
anv_address_add(struct anv_address addr,uint64_t offset)584 anv_address_add(struct anv_address addr, uint64_t offset)
585 {
586    addr.offset += offset;
587    return addr;
588 }
589 
590 static inline struct anv_address
anv_address_add_aligned(struct anv_address addr,uint64_t offset,uint32_t alignment)591 anv_address_add_aligned(struct anv_address addr, uint64_t offset, uint32_t alignment)
592 {
593    addr.offset = align(addr.offset + offset, alignment);
594    return addr;
595 }
596 
597 static inline void *
anv_address_map(struct anv_address addr)598 anv_address_map(struct anv_address addr)
599 {
600    if (addr.bo == NULL)
601       return NULL;
602 
603    if (addr.bo->map == NULL)
604       return NULL;
605 
606    return addr.bo->map + addr.offset;
607 }
608 
609 /* Represent a virtual address range */
610 struct anv_va_range {
611    uint64_t addr;
612    uint64_t size;
613 };
614 
615 /* Represents a lock-free linked list of "free" things.  This is used by
616  * both the block pool and the state pools.  Unfortunately, in order to
617  * solve the ABA problem, we can't use a single uint32_t head.
618  */
619 union anv_free_list {
620    struct {
621       uint32_t offset;
622 
623       /* A simple count that is incremented every time the head changes. */
624       uint32_t count;
625    };
626    /* Make sure it's aligned to 64 bits. This will make atomic operations
627     * faster on 32 bit platforms.
628     */
629    alignas(8) uint64_t u64;
630 };
631 
632 #define ANV_FREE_LIST_EMPTY ((union anv_free_list) { { UINT32_MAX, 0 } })
633 
634 struct anv_block_state {
635    union {
636       struct {
637          uint32_t next;
638          uint32_t end;
639       };
640       /* Make sure it's aligned to 64 bits. This will make atomic operations
641        * faster on 32 bit platforms.
642        */
643       alignas(8) uint64_t u64;
644    };
645 };
646 
647 #define anv_block_pool_foreach_bo(bo, pool)  \
648    for (struct anv_bo **_pp_bo = (pool)->bos, *bo; \
649         _pp_bo != &(pool)->bos[(pool)->nbos] && (bo = *_pp_bo, true); \
650         _pp_bo++)
651 
652 #define ANV_MAX_BLOCK_POOL_BOS 20
653 
654 struct anv_block_pool {
655    const char *name;
656 
657    struct anv_device *device;
658 
659    struct anv_bo *bos[ANV_MAX_BLOCK_POOL_BOS];
660    struct anv_bo *bo;
661    uint32_t nbos;
662 
663    /* Maximum size of the pool */
664    uint64_t max_size;
665 
666    /* Current size of the pool */
667    uint64_t size;
668 
669    /* The canonical address where the start of the pool is pinned. The various bos that
670     * are created as the pool grows will have addresses in the range
671     * [start_address, start_address + BLOCK_POOL_MEMFD_SIZE).
672     */
673    uint64_t start_address;
674 
675    /* The offset from the start of the bo to the "center" of the block
676     * pool.  Pointers to allocated blocks are given by
677     * bo.map + center_bo_offset + offsets.
678     */
679    uint32_t center_bo_offset;
680 
681    struct anv_block_state state;
682 
683    enum anv_bo_alloc_flags bo_alloc_flags;
684 };
685 
686 /* Block pools are backed by a fixed-size 1GB memfd */
687 #define BLOCK_POOL_MEMFD_SIZE (1ul << 30)
688 
689 /* The center of the block pool is also the middle of the memfd.  This may
690  * change in the future if we decide differently for some reason.
691  */
692 #define BLOCK_POOL_MEMFD_CENTER (BLOCK_POOL_MEMFD_SIZE / 2)
693 
694 static inline uint32_t
anv_block_pool_size(struct anv_block_pool * pool)695 anv_block_pool_size(struct anv_block_pool *pool)
696 {
697    return pool->state.end;
698 }
699 
700 struct anv_state {
701    int64_t offset;
702    uint32_t alloc_size;
703    uint32_t idx;
704    void *map;
705 };
706 
707 #define ANV_STATE_NULL ((struct anv_state) { .alloc_size = 0 })
708 
709 struct anv_fixed_size_state_pool {
710    union anv_free_list free_list;
711    struct anv_block_state block;
712 };
713 
714 #define ANV_MIN_STATE_SIZE_LOG2 6
715 #define ANV_MAX_STATE_SIZE_LOG2 24
716 
717 #define ANV_STATE_BUCKETS (ANV_MAX_STATE_SIZE_LOG2 - ANV_MIN_STATE_SIZE_LOG2 + 1)
718 
719 struct anv_free_entry {
720    uint32_t next;
721    struct anv_state state;
722 };
723 
724 struct anv_state_table {
725    struct anv_device *device;
726    int fd;
727    struct anv_free_entry *map;
728    uint32_t size;
729    uint64_t max_size;
730    struct anv_block_state state;
731    struct u_vector cleanups;
732 };
733 
734 struct anv_state_pool {
735    struct anv_block_pool block_pool;
736 
737    /* Offset into the relevant state base address where the state pool starts
738     * allocating memory.
739     */
740    int64_t start_offset;
741 
742    struct anv_state_table table;
743 
744    /* The size of blocks which will be allocated from the block pool */
745    uint32_t block_size;
746 
747    struct anv_fixed_size_state_pool buckets[ANV_STATE_BUCKETS];
748 };
749 
750 struct anv_state_reserved_pool {
751    struct anv_state_pool *pool;
752    union anv_free_list reserved_blocks;
753    uint32_t count;
754 };
755 
756 struct anv_state_reserved_array_pool {
757    struct anv_state_pool *pool;
758    simple_mtx_t mutex;
759    /* Bitfield of usable elements */
760    BITSET_WORD *states;
761    /* Backing store */
762    struct anv_state state;
763    /* Number of elements */
764    uint32_t count;
765    /* Stride between each element */
766    uint32_t stride;
767    /* Size of each element */
768    uint32_t size;
769 };
770 
771 struct anv_state_stream {
772    struct anv_state_pool *state_pool;
773 
774    /* The size of blocks to allocate from the state pool */
775    uint32_t block_size;
776 
777    /* Current block we're allocating from */
778    struct anv_state block;
779 
780    /* Offset into the current block at which to allocate the next state */
781    uint32_t next;
782 
783    /* Sum of all the blocks in all_blocks */
784    uint32_t total_size;
785 
786    /* List of all blocks allocated from this pool */
787    struct util_dynarray all_blocks;
788 };
789 
790 /* The block_pool functions exported for testing only.  The block pool should
791  * only be used via a state pool (see below).
792  */
793 VkResult anv_block_pool_init(struct anv_block_pool *pool,
794                              struct anv_device *device,
795                              const char *name,
796                              uint64_t start_address,
797                              uint32_t initial_size,
798                              uint32_t max_size);
799 void anv_block_pool_finish(struct anv_block_pool *pool);
800 VkResult anv_block_pool_alloc(struct anv_block_pool *pool,
801                               uint32_t block_size,
802                               int64_t *offset,
803                               uint32_t *padding);
804 void* anv_block_pool_map(struct anv_block_pool *pool, int32_t offset, uint32_t
805 size);
806 
807 struct anv_state_pool_params {
808    const char *name;
809    uint64_t    base_address;
810    int64_t     start_offset;
811    uint32_t    block_size;
812    uint32_t    max_size;
813 };
814 
815 VkResult anv_state_pool_init(struct anv_state_pool *pool,
816                              struct anv_device *device,
817                              const struct anv_state_pool_params *params);
818 void anv_state_pool_finish(struct anv_state_pool *pool);
819 struct anv_state anv_state_pool_alloc(struct anv_state_pool *pool,
820                                       uint32_t state_size, uint32_t alignment);
821 void anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state);
822 
823 static inline struct anv_address
anv_state_pool_state_address(struct anv_state_pool * pool,struct anv_state state)824 anv_state_pool_state_address(struct anv_state_pool *pool, struct anv_state state)
825 {
826    return (struct anv_address) {
827       .bo = pool->block_pool.bo,
828       .offset = state.offset - pool->start_offset,
829    };
830 }
831 
832 static inline struct anv_state
anv_state_pool_emit_data(struct anv_state_pool * pool,size_t size,size_t align,const void * p)833 anv_state_pool_emit_data(struct anv_state_pool *pool,
834                          size_t size, size_t align,
835                          const void *p)
836 {
837    struct anv_state state;
838 
839    state = anv_state_pool_alloc(pool, size, align);
840    memcpy(state.map, p, size);
841 
842    return state;
843 }
844 
845 void anv_state_stream_init(struct anv_state_stream *stream,
846                            struct anv_state_pool *state_pool,
847                            uint32_t block_size);
848 void anv_state_stream_finish(struct anv_state_stream *stream);
849 struct anv_state anv_state_stream_alloc(struct anv_state_stream *stream,
850                                         uint32_t size, uint32_t alignment);
851 
852 void anv_state_reserved_pool_init(struct anv_state_reserved_pool *pool,
853                                       struct anv_state_pool *parent,
854                                       uint32_t count, uint32_t size,
855                                       uint32_t alignment);
856 void anv_state_reserved_pool_finish(struct anv_state_reserved_pool *pool);
857 struct anv_state anv_state_reserved_pool_alloc(struct anv_state_reserved_pool *pool);
858 void anv_state_reserved_pool_free(struct anv_state_reserved_pool *pool,
859                                   struct anv_state state);
860 
861 VkResult anv_state_reserved_array_pool_init(struct anv_state_reserved_array_pool *pool,
862                                             struct anv_state_pool *parent,
863                                             uint32_t count, uint32_t size,
864                                             uint32_t alignment);
865 void anv_state_reserved_array_pool_finish(struct anv_state_reserved_array_pool *pool);
866 struct anv_state anv_state_reserved_array_pool_alloc(struct anv_state_reserved_array_pool *pool,
867                                                      bool alloc_back);
868 struct anv_state anv_state_reserved_array_pool_alloc_index(struct anv_state_reserved_array_pool *pool,
869                                                            unsigned idx);
870 uint32_t anv_state_reserved_array_pool_state_index(struct anv_state_reserved_array_pool *pool,
871                                                    struct anv_state state);
872 void anv_state_reserved_array_pool_free(struct anv_state_reserved_array_pool *pool,
873                                         struct anv_state state);
874 
875 VkResult anv_state_table_init(struct anv_state_table *table,
876                              struct anv_device *device,
877                              uint32_t initial_entries);
878 void anv_state_table_finish(struct anv_state_table *table);
879 VkResult anv_state_table_add(struct anv_state_table *table, uint32_t *idx,
880                              uint32_t count);
881 void anv_free_list_push(union anv_free_list *list,
882                         struct anv_state_table *table,
883                         uint32_t idx, uint32_t count);
884 struct anv_state* anv_free_list_pop(union anv_free_list *list,
885                                     struct anv_state_table *table);
886 
887 
888 static inline struct anv_state *
anv_state_table_get(struct anv_state_table * table,uint32_t idx)889 anv_state_table_get(struct anv_state_table *table, uint32_t idx)
890 {
891    return &table->map[idx].state;
892 }
893 /**
894  * Implements a pool of re-usable BOs.  The interface is identical to that
895  * of block_pool except that each block is its own BO.
896  */
897 struct anv_bo_pool {
898    const char *name;
899 
900    struct anv_device *device;
901 
902    enum anv_bo_alloc_flags bo_alloc_flags;
903 
904    struct util_sparse_array_free_list free_list[16];
905 };
906 
907 void anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
908                       const char *name, enum anv_bo_alloc_flags alloc_flags);
909 void anv_bo_pool_finish(struct anv_bo_pool *pool);
910 VkResult anv_bo_pool_alloc(struct anv_bo_pool *pool, uint32_t size,
911                            struct anv_bo **bo_out);
912 void anv_bo_pool_free(struct anv_bo_pool *pool, struct anv_bo *bo);
913 
914 struct anv_scratch_pool {
915    enum anv_bo_alloc_flags alloc_flags;
916    /* Indexed by Per-Thread Scratch Space number (the hardware value) and stage */
917    struct anv_bo *bos[16][MESA_SHADER_STAGES];
918    uint32_t surfs[16];
919    struct anv_state surf_states[16];
920 };
921 
922 void anv_scratch_pool_init(struct anv_device *device,
923                            struct anv_scratch_pool *pool,
924                            bool protected);
925 void anv_scratch_pool_finish(struct anv_device *device,
926                              struct anv_scratch_pool *pool);
927 struct anv_bo *anv_scratch_pool_alloc(struct anv_device *device,
928                                       struct anv_scratch_pool *pool,
929                                       gl_shader_stage stage,
930                                       unsigned per_thread_scratch);
931 uint32_t anv_scratch_pool_get_surf(struct anv_device *device,
932                                    struct anv_scratch_pool *pool,
933                                    unsigned per_thread_scratch);
934 
935 /* Note that on Gfx12HP we pass a scratch space surface state offset
936  * shifted by 2 relative to the value specified on the BSpec, since
937  * that allows the compiler to save a shift instruction while
938  * constructing the extended descriptor for SS addressing.  That
939  * worked because we limit the scratch surface state pool to 8 MB and
940  * because we relied on the legacy (ExBSO=0) encoding of the extended
941  * descriptor in order to save the shift, which is no longer supported
942  * for the UGM shared function on Xe2 platforms, so we no longer
943  * attempt to do that trick.
944  */
945 #define ANV_SCRATCH_SPACE_SHIFT(ver) ((ver) >= 20 ? 6 : 4)
946 
947 /** Implements a BO cache that ensures a 1-1 mapping of GEM BOs to anv_bos */
948 struct anv_bo_cache {
949    struct util_sparse_array bo_map;
950    pthread_mutex_t mutex;
951 };
952 
953 VkResult anv_bo_cache_init(struct anv_bo_cache *cache,
954                            struct anv_device *device);
955 void anv_bo_cache_finish(struct anv_bo_cache *cache);
956 
957 struct anv_queue_family {
958    /* Standard bits passed on to the client */
959    VkQueueFlags   queueFlags;
960    uint32_t       queueCount;
961 
962    enum intel_engine_class engine_class;
963    bool supports_perf;
964 };
965 
966 #define ANV_MAX_QUEUE_FAMILIES 5
967 
968 struct anv_memory_type {
969    /* Standard bits passed on to the client */
970    VkMemoryPropertyFlags   propertyFlags;
971    uint32_t                heapIndex;
972    /* Whether this is the dynamic visible memory type */
973    bool                    dynamic_visible;
974    bool                    compressed;
975 };
976 
977 struct anv_memory_heap {
978    /* Standard bits passed on to the client */
979    VkDeviceSize      size;
980    VkMemoryHeapFlags flags;
981 
982    /** Driver-internal book-keeping.
983     *
984     * Align it to 64 bits to make atomic operations faster on 32 bit platforms.
985     */
986    alignas(8) VkDeviceSize used;
987 
988    bool              is_local_mem;
989 };
990 
991 struct anv_memregion {
992    const struct intel_memory_class_instance *region;
993    uint64_t size;
994    uint64_t available;
995 };
996 
997 enum anv_timestamp_capture_type {
998     ANV_TIMESTAMP_CAPTURE_TOP_OF_PIPE,
999     ANV_TIMESTAMP_CAPTURE_END_OF_PIPE,
1000     ANV_TIMESTAMP_CAPTURE_AT_CS_STALL,
1001     ANV_TIMESTAMP_REWRITE_COMPUTE_WALKER,
1002     ANV_TIMESTAMP_REWRITE_INDIRECT_DISPATCH,
1003 };
1004 
1005 struct anv_physical_device {
1006     struct vk_physical_device                   vk;
1007 
1008     /* Link in anv_instance::physical_devices */
1009     struct list_head                            link;
1010 
1011     struct anv_instance *                       instance;
1012     char                                        path[20];
1013     struct intel_device_info                      info;
1014 
1015     bool                                        video_decode_enabled;
1016     bool                                        video_encode_enabled;
1017 
1018     struct brw_compiler *                       compiler;
1019     struct isl_device                           isl_dev;
1020     struct intel_perf_config *                    perf;
1021     /*
1022      * Number of commands required to implement a performance query begin +
1023      * end.
1024      */
1025     uint32_t                                    n_perf_query_commands;
1026     bool                                        has_exec_async;
1027     bool                                        has_exec_capture;
1028     VkQueueGlobalPriorityKHR                    max_context_priority;
1029     uint64_t                                    gtt_size;
1030 
1031     bool                                        always_use_bindless;
1032     bool                                        use_call_secondary;
1033 
1034     /** True if we can use timeline semaphores through execbuf */
1035     bool                                        has_exec_timeline;
1036 
1037     /** True if we can read the GPU timestamp register
1038      *
1039      * When running in a virtual context, the timestamp register is unreadable
1040      * on Gfx12+.
1041      */
1042     bool                                        has_reg_timestamp;
1043 
1044     /** True if we can create protected contexts. */
1045     bool                                        has_protected_contexts;
1046 
1047     /** Whether KMD has the ability to create VM objects */
1048     bool                                        has_vm_control;
1049 
1050     /** Whether the device is not able map all the device local memory on the
1051      * host
1052      */
1053     bool                                        has_small_bar;
1054 
1055     /** True if we have the means to do sparse binding (e.g., a Kernel driver
1056      * a vm_bind ioctl).
1057      */
1058     enum anv_sparse_type {
1059       ANV_SPARSE_TYPE_NOT_SUPPORTED = 0,
1060       ANV_SPARSE_TYPE_VM_BIND,
1061       ANV_SPARSE_TYPE_TRTT,
1062       ANV_SPARSE_TYPE_FAKE,
1063     } sparse_type;
1064 
1065     /** True if HW supports ASTC LDR */
1066     bool                                        has_astc_ldr;
1067     /** True if denorms in void extents should be flushed to zero */
1068     bool                                        flush_astc_ldr_void_extent_denorms;
1069     /** True if ASTC LDR is supported via emulation */
1070     bool                                        emu_astc_ldr;
1071     /* true if FCV optimization should be disabled. */
1072     bool                                        disable_fcv;
1073     /**/
1074     bool                                        uses_ex_bso;
1075 
1076     bool                                        always_flush_cache;
1077 
1078     /** True if application memory is allocated with extra AUX memory
1079      *
1080      * Applications quite often pool image allocations together in a single
1081      * VkDeviceMemory object. On platforms like MTL, the alignment of images
1082      * with compression mapped through the AUX translation tables is large :
1083      * 1MB. This can create a lot of wasted space in the application memory
1084      * objects.
1085      *
1086      * To workaround this problem, we allocate CCS data at the end of
1087      * VkDeviceMemory objects. This would not work well for TGL-like platforms
1088      * because the AUX translation tables also contain the format of the
1089      * images, but on MTL the HW ignore those values. So we can share the AUX
1090      * TT entries between different images without problem.
1091      *
1092      * This should be only true for platforms with AUX TT.
1093      */
1094     bool                                         alloc_aux_tt_mem;
1095 
1096     /**
1097      * True if the descriptors buffers are holding one of the following :
1098      *    - anv_sampled_image_descriptor
1099      *    - anv_storage_image_descriptor
1100      *    - anv_address_range_descriptor
1101      *
1102      * Accessing the descriptors in a bindless fashion from the shader
1103      * requires an indirection in the shader, first fetch one of the structure
1104      * listed above from the descriptor buffer, then emit the send message to
1105      * the fixed function (sampler, dataport, etc...) with the handle fetched
1106      * above.
1107      *
1108      * We need to do things this way prior to DG2 because the bindless surface
1109      * state space is limited to 64Mb and some application will allocate more
1110      * than what HW can support. On DG2+ we get 4Gb of bindless surface state
1111      * and so we can reference directly RENDER_SURFACE_STATE/SAMPLER_STATE
1112      * structures instead.
1113      */
1114     bool                                        indirect_descriptors;
1115 
1116     bool                                        uses_relocs;
1117 
1118     /** Can the platform support cooperative matrices and is it enabled? */
1119     bool                                        has_cooperative_matrix;
1120 
1121     struct {
1122       uint32_t                                  family_count;
1123       struct anv_queue_family                   families[ANV_MAX_QUEUE_FAMILIES];
1124     } queue;
1125 
1126     struct {
1127       uint32_t                                  type_count;
1128       struct anv_memory_type                    types[VK_MAX_MEMORY_TYPES];
1129       uint32_t                                  heap_count;
1130       struct anv_memory_heap                    heaps[VK_MAX_MEMORY_HEAPS];
1131 #ifdef SUPPORT_INTEL_INTEGRATED_GPUS
1132       bool                                      need_flush;
1133 #endif
1134       /** Mask of memory types of normal allocations */
1135       uint32_t                                  default_buffer_mem_types;
1136       /** Mask of memory types of data indexable from the dynamic heap */
1137       uint32_t                                  dynamic_visible_mem_types;
1138       /** Mask of memory types of protected buffers/images */
1139       uint32_t                                  protected_mem_types;
1140       /**
1141        * Mask of memory types of compressed buffers/images. This is generally
1142        * a win for images, but a loss for buffers.
1143        */
1144       uint32_t                                  compressed_mem_types;
1145     } memory;
1146 
1147     struct {
1148        /**
1149         * General state pool
1150         */
1151        struct anv_va_range                      general_state_pool;
1152        /**
1153         * Low 32bit heap
1154         */
1155        struct anv_va_range                      low_heap;
1156        /**
1157         * Binding table pool
1158         */
1159        struct anv_va_range                      binding_table_pool;
1160        /**
1161         * Internal surface states for blorp & push descriptors.
1162         */
1163        struct anv_va_range                      internal_surface_state_pool;
1164        /**
1165         * Scratch surfaces (overlaps with internal_surface_state_pool).
1166         */
1167        struct anv_va_range                      scratch_surface_state_pool;
1168        /**
1169         * Bindless surface states (indirectly referred to by indirect
1170         * descriptors or for direct descriptors)
1171         */
1172        struct anv_va_range                      bindless_surface_state_pool;
1173        /**
1174         * Dynamic state pool
1175         */
1176        struct anv_va_range                      dynamic_state_pool;
1177        /**
1178         * Buffer pool that can be index from the dynamic state heap
1179         */
1180        struct anv_va_range                      dynamic_visible_pool;
1181        /**
1182         * Indirect descriptor pool
1183         */
1184        struct anv_va_range                      indirect_descriptor_pool;
1185        /**
1186         * Indirect push descriptor pool
1187         */
1188        struct anv_va_range                      indirect_push_descriptor_pool;
1189        /**
1190         * Instruction state pool
1191         */
1192        struct anv_va_range                      instruction_state_pool;
1193        /**
1194         * Push descriptor with descriptor buffers
1195         */
1196        struct anv_va_range                      push_descriptor_buffer_pool;
1197        /**
1198         * AUX-TT
1199         */
1200        struct anv_va_range                      aux_tt_pool;
1201        /**
1202         * Client heap
1203         */
1204        struct anv_va_range                      high_heap;
1205        struct anv_va_range                      trtt;
1206     } va;
1207 
1208     /* Either we have a single vram region and it's all mappable, or we have
1209      * both mappable & non-mappable parts. System memory is always available.
1210      */
1211     struct anv_memregion                        vram_mappable;
1212     struct anv_memregion                        vram_non_mappable;
1213     struct anv_memregion                        sys;
1214     uint8_t                                     driver_build_sha1[20];
1215     uint8_t                                     pipeline_cache_uuid[VK_UUID_SIZE];
1216     uint8_t                                     driver_uuid[VK_UUID_SIZE];
1217     uint8_t                                     device_uuid[VK_UUID_SIZE];
1218     uint8_t                                     rt_uuid[VK_UUID_SIZE];
1219 
1220     /* Maximum amount of scratch space used by all the GRL kernels */
1221     uint32_t                                    max_grl_scratch_size;
1222 
1223     struct vk_sync_type                         sync_syncobj_type;
1224     struct vk_sync_timeline_type                sync_timeline_type;
1225     const struct vk_sync_type *                 sync_types[4];
1226 
1227     struct wsi_device                       wsi_device;
1228     int                                         local_fd;
1229     bool                                        has_local;
1230     int64_t                                     local_major;
1231     int64_t                                     local_minor;
1232     int                                         master_fd;
1233     bool                                        has_master;
1234     int64_t                                     master_major;
1235     int64_t                                     master_minor;
1236     struct intel_query_engine_info *            engine_info;
1237 
1238     void (*cmd_emit_timestamp)(struct anv_batch *, struct anv_device *, struct anv_address,
1239                                enum anv_timestamp_capture_type, void *);
1240     void (*cmd_capture_data)(struct anv_batch *, struct anv_device *,
1241                              struct anv_address, struct anv_address,
1242                              uint32_t);
1243     struct intel_measure_device                 measure_device;
1244 
1245     /* Value of PIPELINE_SELECT::PipelineSelection == GPGPU */
1246     uint32_t                                    gpgpu_pipeline_value;
1247 
1248     /** A pre packed VERTEX_ELEMENT_STATE feeding 0s to the VS stage
1249      *
1250      * For use when a pipeline has no VS input
1251      */
1252     uint32_t                                    empty_vs_input[2];
1253 };
1254 
1255 VkResult anv_physical_device_try_create(struct vk_instance *vk_instance,
1256                                         struct _drmDevice *drm_device,
1257                                         struct vk_physical_device **out);
1258 
1259 void anv_physical_device_destroy(struct vk_physical_device *vk_device);
1260 
1261 static inline uint32_t
anv_physical_device_bindless_heap_size(const struct anv_physical_device * device,bool descriptor_buffer)1262 anv_physical_device_bindless_heap_size(const struct anv_physical_device *device,
1263                                        bool descriptor_buffer)
1264 {
1265    /* Pre-Gfx12.5, the HW bindless surface heap is only 64MB. After it's 4GB,
1266     * but we have some workarounds that require 2 heaps to overlap, so the
1267     * size is dictated by our VA allocation.
1268     */
1269    return device->uses_ex_bso ?
1270       (descriptor_buffer ?
1271        device->va.dynamic_visible_pool.size :
1272        device->va.bindless_surface_state_pool.size) :
1273       64 * 1024 * 1024 /* 64 MiB */;
1274 }
1275 
1276 static inline bool
anv_physical_device_has_vram(const struct anv_physical_device * device)1277 anv_physical_device_has_vram(const struct anv_physical_device *device)
1278 {
1279    return device->vram_mappable.size > 0;
1280 }
1281 
1282 struct anv_instance {
1283     struct vk_instance                          vk;
1284 
1285     struct driOptionCache                       dri_options;
1286     struct driOptionCache                       available_dri_options;
1287 
1288     int                                         mesh_conv_prim_attrs_to_vert_attrs;
1289     bool                                        enable_tbimr;
1290     bool                                        external_memory_implicit_sync;
1291     bool                                        force_guc_low_latency;
1292 
1293     /**
1294      * Workarounds for game bugs.
1295      */
1296     uint8_t                                     assume_full_subgroups;
1297     bool                                        assume_full_subgroups_with_barrier;
1298     bool                                        limit_trig_input_range;
1299     bool                                        sample_mask_out_opengl_behaviour;
1300     bool                                        force_filter_addr_rounding;
1301     bool                                        fp64_workaround_enabled;
1302     float                                       lower_depth_range_rate;
1303     unsigned                                    generated_indirect_threshold;
1304     unsigned                                    generated_indirect_ring_threshold;
1305     unsigned                                    query_clear_with_blorp_threshold;
1306     unsigned                                    query_copy_with_shader_threshold;
1307     unsigned                                    force_vk_vendor;
1308     bool                                        has_fake_sparse;
1309     bool                                        disable_fcv;
1310     bool                                        enable_buffer_comp;
1311     bool                                        compression_control_enabled;
1312     bool                                        anv_fake_nonlocal_memory;
1313     bool                                        anv_upper_bound_descriptor_pool_sampler;
1314     bool                                        custom_border_colors_without_format;
1315 
1316     /* HW workarounds */
1317     bool                                        no_16bit;
1318     bool                                        intel_enable_wa_14018912822;
1319 
1320     /**
1321      * Ray tracing configuration.
1322      */
1323     unsigned                                    stack_ids;
1324 };
1325 
1326 VkResult anv_init_wsi(struct anv_physical_device *physical_device);
1327 void anv_finish_wsi(struct anv_physical_device *physical_device);
1328 
1329 struct anv_queue {
1330    struct vk_queue                           vk;
1331 
1332    struct anv_device *                       device;
1333 
1334    const struct anv_queue_family *           family;
1335 
1336    struct intel_batch_decode_ctx *           decoder;
1337 
1338    union {
1339       uint32_t                               exec_flags; /* i915 */
1340       uint32_t                               context_id; /* i915 */
1341       uint32_t                               exec_queue_id; /* Xe */
1342    };
1343 
1344    uint32_t                                  bind_queue_id; /* Xe */
1345 
1346    /** Context/Engine id which executes companion RCS command buffer */
1347    uint32_t                                  companion_rcs_id;
1348 
1349    /** Synchronization object for debug purposes (DEBUG_SYNC) */
1350    struct vk_sync                           *sync;
1351 
1352    /** Companion synchronization object
1353     *
1354     * Vulkan command buffers can be destroyed as soon as their lifecycle moved
1355     * from the Pending state to the Invalid/Executable state. This transition
1356     * happens when the VkFence/VkSemaphore associated with the completion of
1357     * the command buffer work is signaled.
1358     *
1359     * When we're using a companion command buffer to execute part of another
1360     * command buffer, we need to tie the 2 work submissions together to ensure
1361     * when the associated VkFence/VkSemaphore is signaled, both command
1362     * buffers are actually unused by the HW. To do this, we run an empty batch
1363     * buffer that we use to signal after both submissions :
1364     *
1365     *   CCS -->    main   ---> empty_batch (with wait on companion) --> signal
1366     *   RCS --> companion -|
1367     *
1368     * When companion batch completes, it signals companion_sync and allow
1369     * empty_batch to execute. Since empty_batch is running on the main engine,
1370     * we're guaranteed that upon completion both main & companion command
1371     * buffers are not used by HW anymore.
1372     */
1373    struct vk_sync                           *companion_sync;
1374 
1375    struct intel_ds_queue                     ds;
1376 
1377    struct anv_async_submit                  *init_submit;
1378    struct anv_async_submit                  *init_companion_submit;
1379 };
1380 
1381 struct nir_xfb_info;
1382 struct anv_pipeline_bind_map;
1383 struct anv_pipeline_sets_layout;
1384 struct anv_push_descriptor_info;
1385 enum anv_dynamic_push_bits;
1386 
1387 void anv_device_init_embedded_samplers(struct anv_device *device);
1388 void anv_device_finish_embedded_samplers(struct anv_device *device);
1389 
1390 extern const struct vk_pipeline_cache_object_ops *const anv_cache_import_ops[2];
1391 
1392 struct anv_shader_bin *
1393 anv_device_search_for_kernel(struct anv_device *device,
1394                              struct vk_pipeline_cache *cache,
1395                              const void *key_data, uint32_t key_size,
1396                              bool *user_cache_bit);
1397 
1398 struct anv_shader_upload_params;
1399 
1400 struct anv_shader_bin *
1401 anv_device_upload_kernel(struct anv_device *device,
1402                          struct vk_pipeline_cache *cache,
1403                          const struct anv_shader_upload_params *params);
1404 
1405 struct nir_shader;
1406 struct nir_shader_compiler_options;
1407 
1408 struct nir_shader *
1409 anv_device_search_for_nir(struct anv_device *device,
1410                           struct vk_pipeline_cache *cache,
1411                           const struct nir_shader_compiler_options *nir_options,
1412                           unsigned char sha1_key[20],
1413                           void *mem_ctx);
1414 
1415 void
1416 anv_device_upload_nir(struct anv_device *device,
1417                       struct vk_pipeline_cache *cache,
1418                       const struct nir_shader *nir,
1419                       unsigned char sha1_key[20]);
1420 
1421 void
1422 anv_load_fp64_shader(struct anv_device *device);
1423 
1424 /**
1425  * This enum tracks the various HW instructions that hold graphics state
1426  * needing to be reprogrammed. Some instructions are grouped together as they
1427  * pretty much need to be emitted together (like 3DSTATE_URB_*).
1428  *
1429  * Not all bits apply to all platforms. We build a dirty state based on
1430  * enabled extensions & generation on anv_device.
1431  */
1432 enum anv_gfx_state_bits {
1433    /* Pipeline states */
1434    ANV_GFX_STATE_URB, /* All legacy stages, including mesh */
1435    ANV_GFX_STATE_VF_STATISTICS,
1436    ANV_GFX_STATE_VF_SGVS,
1437    ANV_GFX_STATE_VF_SGVS_2,
1438    ANV_GFX_STATE_VF_SGVS_VI, /* 3DSTATE_VERTEX_ELEMENTS for sgvs elements */
1439    ANV_GFX_STATE_VF_SGVS_INSTANCING, /* 3DSTATE_VF_INSTANCING for sgvs elements */
1440    ANV_GFX_STATE_PRIMITIVE_REPLICATION,
1441    ANV_GFX_STATE_SBE,
1442    ANV_GFX_STATE_SBE_SWIZ,
1443    ANV_GFX_STATE_SO_DECL_LIST,
1444    ANV_GFX_STATE_VS,
1445    ANV_GFX_STATE_HS,
1446    ANV_GFX_STATE_DS,
1447    ANV_GFX_STATE_GS,
1448    ANV_GFX_STATE_PS,
1449    ANV_GFX_STATE_SBE_MESH,
1450    ANV_GFX_STATE_CLIP_MESH,
1451    ANV_GFX_STATE_MESH_CONTROL,
1452    ANV_GFX_STATE_MESH_SHADER,
1453    ANV_GFX_STATE_MESH_DISTRIB,
1454    ANV_GFX_STATE_TASK_CONTROL,
1455    ANV_GFX_STATE_TASK_SHADER,
1456    ANV_GFX_STATE_TASK_REDISTRIB,
1457    /* Dynamic states */
1458    ANV_GFX_STATE_BLEND_STATE, /* Just the dynamic state structure */
1459    ANV_GFX_STATE_BLEND_STATE_PTR, /* The pointer to the dynamic state */
1460    ANV_GFX_STATE_CLIP,
1461    ANV_GFX_STATE_CC_STATE,
1462    ANV_GFX_STATE_CC_STATE_PTR,
1463    ANV_GFX_STATE_COARSE_PIXEL,
1464    ANV_GFX_STATE_CPS,
1465    ANV_GFX_STATE_DEPTH_BOUNDS,
1466    ANV_GFX_STATE_INDEX_BUFFER,
1467    ANV_GFX_STATE_LINE_STIPPLE,
1468    ANV_GFX_STATE_MULTISAMPLE,
1469    ANV_GFX_STATE_PS_BLEND,
1470    ANV_GFX_STATE_RASTER,
1471    ANV_GFX_STATE_SAMPLE_MASK,
1472    ANV_GFX_STATE_SAMPLE_PATTERN,
1473    ANV_GFX_STATE_SCISSOR,
1474    ANV_GFX_STATE_SF,
1475    ANV_GFX_STATE_STREAMOUT,
1476    ANV_GFX_STATE_TE,
1477    ANV_GFX_STATE_VERTEX_INPUT,
1478    ANV_GFX_STATE_VF,
1479    ANV_GFX_STATE_VF_TOPOLOGY,
1480    ANV_GFX_STATE_VFG,
1481    ANV_GFX_STATE_VIEWPORT_CC,
1482    ANV_GFX_STATE_VIEWPORT_CC_PTR,
1483    ANV_GFX_STATE_VIEWPORT_SF_CLIP,
1484    ANV_GFX_STATE_WM,
1485    ANV_GFX_STATE_WM_DEPTH_STENCIL,
1486    ANV_GFX_STATE_PS_EXTRA,
1487    ANV_GFX_STATE_PMA_FIX, /* Fake state to implement workaround */
1488    ANV_GFX_STATE_WA_18019816803, /* Fake state to implement workaround */
1489    ANV_GFX_STATE_WA_14018283232, /* Fake state to implement workaround */
1490    ANV_GFX_STATE_TBIMR_TILE_PASS_INFO,
1491    ANV_GFX_STATE_FS_MSAA_FLAGS,
1492    ANV_GFX_STATE_TCS_INPUT_VERTICES,
1493    ANV_GFX_STATE_COARSE_STATE,
1494 
1495    ANV_GFX_STATE_MAX,
1496 };
1497 
1498 const char *anv_gfx_state_bit_to_str(enum anv_gfx_state_bits state);
1499 
1500 enum anv_coarse_pixel_state {
1501    ANV_COARSE_PIXEL_STATE_UNKNOWN,
1502    ANV_COARSE_PIXEL_STATE_DISABLED,
1503    ANV_COARSE_PIXEL_STATE_ENABLED,
1504 };
1505 
1506 /* This structure tracks the values to program in HW instructions for
1507  * corresponding to dynamic states of the Vulkan API. Only fields that need to
1508  * be reemitted outside of the VkPipeline object are tracked here.
1509  */
1510 struct anv_gfx_dynamic_state {
1511    /* 3DSTATE_BLEND_STATE_POINTERS */
1512    struct {
1513       bool AlphaToCoverageEnable;
1514       bool AlphaToOneEnable;
1515       bool IndependentAlphaBlendEnable;
1516       bool ColorDitherEnable;
1517       struct {
1518          bool     WriteDisableAlpha;
1519          bool     WriteDisableRed;
1520          bool     WriteDisableGreen;
1521          bool     WriteDisableBlue;
1522 
1523          uint32_t LogicOpFunction;
1524          bool     LogicOpEnable;
1525 
1526          bool     ColorBufferBlendEnable;
1527          uint32_t ColorClampRange;
1528          bool     PreBlendColorClampEnable;
1529          bool     PostBlendColorClampEnable;
1530          uint32_t SourceBlendFactor;
1531          uint32_t DestinationBlendFactor;
1532          uint32_t ColorBlendFunction;
1533          uint32_t SourceAlphaBlendFactor;
1534          uint32_t DestinationAlphaBlendFactor;
1535          uint32_t AlphaBlendFunction;
1536       } rts[MAX_RTS];
1537 
1538       struct anv_state state;
1539    } blend;
1540 
1541    /* 3DSTATE_CC_STATE_POINTERS */
1542    struct {
1543       float BlendConstantColorRed;
1544       float BlendConstantColorGreen;
1545       float BlendConstantColorBlue;
1546       float BlendConstantColorAlpha;
1547 
1548       struct anv_state state;
1549    } cc;
1550 
1551    /* 3DSTATE_CLIP */
1552    struct {
1553       uint32_t APIMode;
1554       uint32_t ViewportXYClipTestEnable;
1555       uint32_t MaximumVPIndex;
1556       uint32_t TriangleStripListProvokingVertexSelect;
1557       uint32_t LineStripListProvokingVertexSelect;
1558       uint32_t TriangleFanProvokingVertexSelect;
1559    } clip;
1560 
1561    /* 3DSTATE_COARSE_PIXEL */
1562    struct {
1563       uint32_t    CPSizeX;
1564       uint32_t    CPSizeY;
1565       uint32_t    CPSizeCombiner0Opcode;
1566       uint32_t    CPSizeCombiner1Opcode;
1567       bool        DisableCPSPointers;
1568    } coarse_pixel;
1569 
1570    /* 3DSTATE_CPS/3DSTATE_CPS_POINTERS */
1571    struct {
1572       /* Gfx11 */
1573       uint32_t CoarsePixelShadingMode;
1574       float    MinCPSizeX;
1575       float    MinCPSizeY;
1576       /* Gfx12+ */
1577       uint32_t CoarsePixelShadingStateArrayPointer;
1578    } cps;
1579 
1580    /* 3DSTATE_DEPTH_BOUNDS */
1581    struct {
1582       bool     DepthBoundsTestEnable;
1583       float    DepthBoundsTestMinValue;
1584       float    DepthBoundsTestMaxValue;
1585    } db;
1586 
1587    /* 3DSTATE_GS */
1588    struct {
1589       uint32_t ReorderMode;
1590    } gs;
1591 
1592    /* 3DSTATE_LINE_STIPPLE */
1593    struct {
1594       uint32_t LineStipplePattern;
1595       float    LineStippleInverseRepeatCount;
1596       uint32_t LineStippleRepeatCount;
1597    } ls;
1598 
1599    /* 3DSTATE_MULTISAMPLE */
1600    struct {
1601       uint32_t NumberofMultisamples;
1602    } ms;
1603 
1604    /* 3DSTATE_PS */
1605    struct {
1606       uint32_t PositionXYOffsetSelect;
1607 
1608       uint32_t KernelStartPointer0;
1609       uint32_t KernelStartPointer1;
1610       uint32_t KernelStartPointer2;
1611 
1612       uint32_t DispatchGRFStartRegisterForConstantSetupData0;
1613       uint32_t DispatchGRFStartRegisterForConstantSetupData1;
1614       uint32_t DispatchGRFStartRegisterForConstantSetupData2;
1615 
1616       /* Pre-Gfx20 only */
1617       bool     _8PixelDispatchEnable;
1618       bool     _16PixelDispatchEnable;
1619       bool     _32PixelDispatchEnable;
1620 
1621       /* Gfx20+ only */
1622       bool     Kernel0Enable;
1623       bool     Kernel1Enable;
1624       uint32_t Kernel0SIMDWidth;
1625       uint32_t Kernel1SIMDWidth;
1626       uint32_t Kernel0PolyPackingPolicy;
1627       uint32_t Kernel0MaximumPolysperThread;
1628    } ps;
1629 
1630    /* 3DSTATE_PS_EXTRA */
1631    struct {
1632       bool PixelShaderHasUAV;
1633       bool PixelShaderIsPerSample;
1634       bool PixelShaderKillsPixel;
1635       bool PixelShaderIsPerCoarsePixel;
1636       bool EnablePSDependencyOnCPsizeChange;
1637    } ps_extra;
1638 
1639    /* 3DSTATE_PS_BLEND */
1640    struct {
1641       bool     HasWriteableRT;
1642       bool     ColorBufferBlendEnable;
1643       uint32_t SourceAlphaBlendFactor;
1644       uint32_t DestinationAlphaBlendFactor;
1645       uint32_t SourceBlendFactor;
1646       uint32_t DestinationBlendFactor;
1647       bool     AlphaTestEnable;
1648       bool     IndependentAlphaBlendEnable;
1649       bool     AlphaToCoverageEnable;
1650    } ps_blend;
1651 
1652    /* 3DSTATE_RASTER */
1653    struct {
1654       uint32_t APIMode;
1655       bool     DXMultisampleRasterizationEnable;
1656       bool     AntialiasingEnable;
1657       uint32_t CullMode;
1658       uint32_t FrontWinding;
1659       bool     GlobalDepthOffsetEnableSolid;
1660       bool     GlobalDepthOffsetEnableWireframe;
1661       bool     GlobalDepthOffsetEnablePoint;
1662       float    GlobalDepthOffsetConstant;
1663       float    GlobalDepthOffsetScale;
1664       float    GlobalDepthOffsetClamp;
1665       uint32_t FrontFaceFillMode;
1666       uint32_t BackFaceFillMode;
1667       bool     ViewportZFarClipTestEnable;
1668       bool     ViewportZNearClipTestEnable;
1669       bool     ConservativeRasterizationEnable;
1670    } raster;
1671 
1672    /* 3DSTATE_SCISSOR_STATE_POINTERS */
1673    struct {
1674       uint32_t count;
1675       struct {
1676          uint32_t ScissorRectangleYMin;
1677          uint32_t ScissorRectangleXMin;
1678          uint32_t ScissorRectangleYMax;
1679          uint32_t ScissorRectangleXMax;
1680       } elem[MAX_SCISSORS];
1681    } scissor;
1682 
1683    /* 3DSTATE_SF */
1684    struct {
1685       float    LineWidth;
1686       uint32_t TriangleStripListProvokingVertexSelect;
1687       uint32_t LineStripListProvokingVertexSelect;
1688       uint32_t TriangleFanProvokingVertexSelect;
1689       bool     LegacyGlobalDepthBiasEnable;
1690    } sf;
1691 
1692    /* 3DSTATE_STREAMOUT */
1693    struct {
1694       bool     RenderingDisable;
1695       uint32_t RenderStreamSelect;
1696       uint32_t ReorderMode;
1697       uint32_t ForceRendering;
1698    } so;
1699 
1700    /* 3DSTATE_SAMPLE_MASK */
1701    struct {
1702       uint32_t SampleMask;
1703    } sm;
1704 
1705    /* 3DSTATE_TE */
1706    struct {
1707       uint32_t OutputTopology;
1708    } te;
1709 
1710    /* 3DSTATE_VF */
1711    struct {
1712       bool     IndexedDrawCutIndexEnable;
1713       uint32_t CutIndex;
1714    } vf;
1715 
1716    /* 3DSTATE_VFG */
1717    struct {
1718       uint32_t DistributionMode;
1719       bool     ListCutIndexEnable;
1720    } vfg;
1721 
1722    /* 3DSTATE_VF_TOPOLOGY */
1723    struct {
1724       uint32_t PrimitiveTopologyType;
1725    } vft;
1726 
1727    /* 3DSTATE_VIEWPORT_STATE_POINTERS_CC */
1728    struct {
1729       uint32_t count;
1730       struct {
1731          float MinimumDepth;
1732          float MaximumDepth;
1733       } elem[MAX_VIEWPORTS];
1734 
1735       struct anv_state state;
1736    } vp_cc;
1737 
1738    /* 3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP */
1739    struct {
1740       uint32_t count;
1741       struct {
1742          float ViewportMatrixElementm00;
1743          float ViewportMatrixElementm11;
1744          float ViewportMatrixElementm22;
1745          float ViewportMatrixElementm30;
1746          float ViewportMatrixElementm31;
1747          float ViewportMatrixElementm32;
1748          float XMinClipGuardband;
1749          float XMaxClipGuardband;
1750          float YMinClipGuardband;
1751          float YMaxClipGuardband;
1752          float XMinViewPort;
1753          float XMaxViewPort;
1754          float YMinViewPort;
1755          float YMaxViewPort;
1756       } elem[MAX_VIEWPORTS];
1757    } vp_sf_clip;
1758 
1759    /* 3DSTATE_WM */
1760    struct {
1761       bool     LineStippleEnable;
1762       uint32_t BarycentricInterpolationMode;
1763    } wm;
1764 
1765    /* 3DSTATE_WM_DEPTH_STENCIL */
1766    struct {
1767       bool     DoubleSidedStencilEnable;
1768       uint32_t StencilTestMask;
1769       uint32_t StencilWriteMask;
1770       uint32_t BackfaceStencilTestMask;
1771       uint32_t BackfaceStencilWriteMask;
1772       uint32_t StencilReferenceValue;
1773       uint32_t BackfaceStencilReferenceValue;
1774       bool     DepthTestEnable;
1775       bool     DepthBufferWriteEnable;
1776       uint32_t DepthTestFunction;
1777       bool     StencilTestEnable;
1778       bool     StencilBufferWriteEnable;
1779       uint32_t StencilFailOp;
1780       uint32_t StencilPassDepthPassOp;
1781       uint32_t StencilPassDepthFailOp;
1782       uint32_t StencilTestFunction;
1783       uint32_t BackfaceStencilFailOp;
1784       uint32_t BackfaceStencilPassDepthPassOp;
1785       uint32_t BackfaceStencilPassDepthFailOp;
1786       uint32_t BackfaceStencilTestFunction;
1787    } ds;
1788 
1789    /* 3DSTATE_TBIMR_TILE_PASS_INFO */
1790    struct {
1791       unsigned TileRectangleHeight;
1792       unsigned TileRectangleWidth;
1793       unsigned VerticalTileCount;
1794       unsigned HorizontalTileCount;
1795       unsigned TBIMRBatchSize;
1796       unsigned TileBoxCheck;
1797    } tbimr;
1798    bool use_tbimr;
1799 
1800    /**
1801     * Dynamic msaa flags, this value can be different from
1802     * anv_push_constants::gfx::fs_msaa_flags, as the push constant value only
1803     * needs to be updated for fragment shaders dynamically checking the value.
1804     */
1805    enum intel_msaa_flags fs_msaa_flags;
1806 
1807    /**
1808     * Dynamic TCS input vertices, this value can be different from
1809     * anv_driver_constants::gfx::tcs_input_vertices, as the push constant
1810     * value only needs to be updated for tesselation control shaders
1811     * dynamically checking the value.
1812     */
1813    uint32_t tcs_input_vertices;
1814 
1815    bool pma_fix;
1816 
1817    /**
1818     * DEPTH and STENCIL attachment write state for Wa_18019816803.
1819     */
1820    bool ds_write_state;
1821 
1822    /**
1823     * Toggle tracking for Wa_14018283232.
1824     */
1825    bool wa_14018283232_toggle;
1826 
1827    /**
1828     * Coarse state tracking for Wa_18038825448.
1829     */
1830    enum anv_coarse_pixel_state coarse_state;
1831 
1832    BITSET_DECLARE(dirty, ANV_GFX_STATE_MAX);
1833 };
1834 
1835 enum anv_internal_kernel_name {
1836    ANV_INTERNAL_KERNEL_GENERATED_DRAWS,
1837    ANV_INTERNAL_KERNEL_COPY_QUERY_RESULTS_COMPUTE,
1838    ANV_INTERNAL_KERNEL_COPY_QUERY_RESULTS_FRAGMENT,
1839    ANV_INTERNAL_KERNEL_MEMCPY_COMPUTE,
1840 
1841    ANV_INTERNAL_KERNEL_COUNT,
1842 };
1843 
1844 enum anv_rt_bvh_build_method {
1845    ANV_BVH_BUILD_METHOD_TRIVIAL,
1846    ANV_BVH_BUILD_METHOD_NEW_SAH,
1847 };
1848 
1849 /* If serialization-breaking or algorithm-breaking changes are made,
1850  * increment the digits at the end
1851  */
1852 #define ANV_RT_UUID_MACRO             "ANV_RT_BVH_0001"
1853 
1854 enum bvh_dump_type {
1855    BVH_ANV,
1856    BVH_IR_HDR,
1857    BVH_IR_AS
1858 };
1859 
1860 struct anv_bvh_dump {
1861    struct anv_bo *bo;
1862    uint32_t bvh_id;
1863    uint64_t dump_size;
1864    VkGeometryTypeKHR geometry_type;
1865    enum bvh_dump_type dump_type;
1866 
1867    /* Link in the anv_device.bvh_dumps list */
1868    struct list_head link;
1869 };
1870 
1871 struct anv_device_astc_emu {
1872     struct vk_texcompress_astc_state           *texcompress;
1873 
1874     /* for flush_astc_ldr_void_extent_denorms */
1875     simple_mtx_t mutex;
1876     VkDescriptorSetLayout ds_layout;
1877     VkPipelineLayout pipeline_layout;
1878     VkPipeline pipeline;
1879 };
1880 
1881 struct anv_device {
1882     struct vk_device                            vk;
1883 
1884     struct anv_physical_device *                physical;
1885     const struct intel_device_info *            info;
1886     const struct anv_kmd_backend *              kmd_backend;
1887     struct isl_device                           isl_dev;
1888     union {
1889        uint32_t                                 context_id; /* i915 */
1890        uint32_t                                 vm_id; /* Xe */
1891     };
1892     int                                         fd;
1893 
1894     pthread_mutex_t                             vma_mutex;
1895     struct util_vma_heap                        vma_lo;
1896     struct util_vma_heap                        vma_hi;
1897     struct util_vma_heap                        vma_desc;
1898     struct util_vma_heap                        vma_dynamic_visible;
1899     struct util_vma_heap                        vma_trtt;
1900 
1901     /** List of all anv_device_memory objects */
1902     struct list_head                            memory_objects;
1903 
1904     /** List of anv_image objects with a private binding for implicit CCS */
1905     struct list_head                            image_private_objects;
1906 
1907     /** List of anv_bvh_dump objects that get dumped on cmd buf completion */
1908     struct list_head                            bvh_dumps;
1909 
1910     /** Memory pool for batch buffers */
1911     struct anv_bo_pool                          batch_bo_pool;
1912     /** Memory pool for utrace timestamp buffers */
1913     struct anv_bo_pool                          utrace_bo_pool;
1914     /**
1915      * Size of the timestamp captured for utrace.
1916      */
1917     uint32_t                                     utrace_timestamp_size;
1918     /** Memory pool for BVH build buffers */
1919     struct anv_bo_pool                          bvh_bo_pool;
1920 
1921     struct anv_bo_cache                         bo_cache;
1922 
1923     struct anv_state_pool                       general_state_pool;
1924     struct anv_state_pool                       aux_tt_pool;
1925     struct anv_state_pool                       dynamic_state_pool;
1926     struct anv_state_pool                       instruction_state_pool;
1927     struct anv_state_pool                       binding_table_pool;
1928     struct anv_state_pool                       scratch_surface_state_pool;
1929     struct anv_state_pool                       internal_surface_state_pool;
1930     struct anv_state_pool                       bindless_surface_state_pool;
1931     struct anv_state_pool                       indirect_push_descriptor_pool;
1932     struct anv_state_pool                       push_descriptor_buffer_pool;
1933 
1934     struct anv_state_reserved_array_pool        custom_border_colors;
1935 
1936     /** BO used for various workarounds
1937      *
1938      * There are a number of workarounds on our hardware which require writing
1939      * data somewhere and it doesn't really matter where.  For that, we use
1940      * this BO and just write to the first dword or so.
1941      *
1942      * We also need to be able to handle NULL buffers bound as pushed UBOs.
1943      * For that, we use the high bytes (>= 1024) of the workaround BO.
1944      */
1945     struct anv_bo *                             workaround_bo;
1946     struct anv_address                          workaround_address;
1947 
1948     struct anv_bo *                             dummy_aux_bo;
1949     struct anv_bo *                             mem_fence_bo;
1950 
1951     /**
1952      * Workarounds for game bugs.
1953      */
1954     struct {
1955        struct set *                             doom64_images;
1956     } workarounds;
1957 
1958     struct anv_bo *                             trivial_batch_bo;
1959     struct anv_state                            null_surface_state;
1960 
1961     /**
1962      * NULL surface state copy stored in host memory for use as a fast
1963      * memcpy() source.
1964      */
1965     char                                        host_null_surface_state[ANV_SURFACE_STATE_SIZE];
1966 
1967     struct vk_pipeline_cache *                  internal_cache;
1968 
1969     struct {
1970        struct blorp_context                     context;
1971        struct anv_state                         dynamic_states[BLORP_DYNAMIC_STATE_COUNT];
1972     }                                           blorp;
1973 
1974     struct anv_state                            border_colors;
1975 
1976     struct anv_state                            slice_hash;
1977 
1978     /** An array of CPS_STATE structures grouped by MAX_VIEWPORTS elements
1979      *
1980      * We need to emit CPS_STATE structures for each viewport accessible by a
1981      * pipeline. So rather than write many identical CPS_STATE structures
1982      * dynamically, we can enumerate all possible combinaisons and then just
1983      * emit a 3DSTATE_CPS_POINTERS instruction with the right offset into this
1984      * array.
1985      */
1986     struct anv_state                            cps_states;
1987 
1988     uint32_t                                    queue_count;
1989     struct anv_queue  *                         queues;
1990 
1991     struct anv_scratch_pool                     scratch_pool;
1992     struct anv_scratch_pool                     protected_scratch_pool;
1993     struct anv_bo                              *rt_scratch_bos[16];
1994     struct anv_bo                              *btd_fifo_bo;
1995     struct anv_address                          rt_uuid_addr;
1996 
1997     bool                                        robust_buffer_access;
1998 
1999     uint32_t                                    protected_session_id;
2000 
2001     /** Shadow ray query BO
2002      *
2003      * The ray_query_bo only holds the current ray being traced. When using
2004      * more than 1 ray query per thread, we cannot fit all the queries in
2005      * there, so we need a another buffer to hold query data that is not
2006      * currently being used by the HW for tracing, similar to a scratch space.
2007      *
2008      * The size of the shadow buffer depends on the number of queries per
2009      * shader.
2010      *
2011      * We might need a buffer per queue family due to Wa_14022863161.
2012      */
2013     struct anv_bo                              *ray_query_shadow_bos[2][16];
2014     /** Ray query buffer used to communicated with HW unit.
2015      */
2016     struct anv_bo                              *ray_query_bo[2];
2017 
2018     struct anv_shader_bin                      *rt_trampoline;
2019     struct anv_shader_bin                      *rt_trivial_return;
2020 
2021     enum anv_rt_bvh_build_method                bvh_build_method;
2022 
2023     /** Draw generation shader
2024      *
2025      * Generates direct draw calls out of indirect parameters. Used to
2026      * workaround slowness with indirect draw calls.
2027      */
2028     struct anv_shader_bin                      *internal_kernels[ANV_INTERNAL_KERNEL_COUNT];
2029     const struct intel_l3_config               *internal_kernels_l3_config;
2030 
2031     pthread_mutex_t                             mutex;
2032     pthread_cond_t                              queue_submit;
2033 
2034     struct intel_batch_decode_ctx               decoder[ANV_MAX_QUEUE_FAMILIES];
2035     /*
2036      * When decoding a anv_cmd_buffer, we might need to search for BOs through
2037      * the cmd_buffer's list.
2038      */
2039     struct anv_cmd_buffer                      *cmd_buffer_being_decoded;
2040 
2041     int                                         perf_fd; /* -1 if no opened */
2042     struct anv_queue                            *perf_queue;
2043     struct intel_bind_timeline                  perf_timeline;
2044 
2045     struct intel_aux_map_context                *aux_map_ctx;
2046 
2047     const struct intel_l3_config                *l3_config;
2048 
2049     struct intel_debug_block_frame              *debug_frame_desc;
2050 
2051     struct intel_ds_device                       ds;
2052 
2053     nir_shader                                  *fp64_nir;
2054 
2055     uint32_t                                    draw_call_count;
2056     struct anv_state                            breakpoint;
2057 #if DETECT_OS_ANDROID
2058     struct u_gralloc                            *u_gralloc;
2059 #endif
2060 
2061     /** Precompute all dirty graphics bits
2062      *
2063      * Depending on platforms, some of the dirty bits don't apply (for example
2064      * 3DSTATE_PRIMITIVE_REPLICATION is only Gfx12.0+). Disabling some
2065      * extensions like Mesh shaders also allow us to avoid emitting any
2066      * mesh/task related instructions (we only initialize them once at device
2067      * initialization).
2068      */
2069     BITSET_DECLARE(gfx_dirty_state, ANV_GFX_STATE_MAX);
2070 
2071     /*
2072      * Command pool for companion RCS command buffer.
2073      */
2074     VkCommandPool                               companion_rcs_cmd_pool;
2075 
2076     struct anv_trtt {
2077        simple_mtx_t mutex;
2078 
2079        /* Sometimes we need to run batches from places where we don't have a
2080         * queue coming from the API, so we use this.
2081         */
2082        struct anv_queue *queue;
2083 
2084        /* There's only one L3 table, so if l3_addr is zero that means we
2085         * didn't initialize the TR-TT context yet (i.e., we're not using TR-TT
2086         * yet in this context).
2087         */
2088        uint64_t l3_addr;
2089 
2090        /* We don't want to access the page tables from the CPU, so just
2091         * maintain a mirror that we can use.
2092         */
2093        uint64_t *l3_mirror;
2094        uint64_t *l2_mirror;
2095 
2096        /* We keep a dynamic list of page table bos, and each bo can store
2097         * multiple page tables.
2098         */
2099        struct anv_bo **page_table_bos;
2100        int num_page_table_bos;
2101        int page_table_bos_capacity;
2102 
2103        /* These are used to keep track of space available for more page tables
2104         * within a bo.
2105         */
2106        struct anv_bo *cur_page_table_bo;
2107        uint64_t next_page_table_bo_offset;
2108 
2109        struct vk_sync *timeline;
2110        uint64_t timeline_val;
2111 
2112        /* List of struct anv_trtt_submission that are in flight and can be
2113         * freed once their vk_sync gets signaled.
2114         */
2115        struct list_head in_flight_batches;
2116     } trtt;
2117 
2118     /* Number of sparse resources that currently exist. This is used for a
2119      * workaround that makes every memoryBarrier flush more things than it
2120      * should. Some workloads create and then immediately destroy sparse
2121      * resources when they start, so just counting if a sparse resource was
2122      * ever created is not enough.
2123      */
2124     uint32_t num_sparse_resources;
2125 
2126     struct anv_device_astc_emu                   astc_emu;
2127 
2128     struct intel_bind_timeline bind_timeline; /* Xe only */
2129 
2130     struct {
2131        simple_mtx_t                              mutex;
2132        struct hash_table                        *map;
2133     }                                            embedded_samplers;
2134 
2135     struct {
2136        /**
2137         * Mutex for the printfs array
2138         */
2139        simple_mtx_t                              mutex;
2140        /**
2141         * Buffer in which the shader printfs are stored
2142         */
2143        struct anv_bo                            *bo;
2144        /**
2145         * Array of pointers to u_printf_info
2146         */
2147        struct util_dynarray                      prints;
2148     } printf;
2149 
2150     struct {
2151        simple_mtx_t  mutex;
2152        struct radix_sort_vk *radix_sort;
2153        struct vk_acceleration_structure_build_args build_args;
2154    } accel_struct_build;
2155 
2156    struct vk_meta_device meta_device;
2157 };
2158 
2159 static inline uint32_t
anv_printf_buffer_size(void)2160 anv_printf_buffer_size(void)
2161 {
2162    return debug_get_num_option("ANV_PRINTF_BUFFER_SIZE", 1024 * 1024);
2163 }
2164 
2165 static inline uint32_t
anv_get_first_render_queue_index(struct anv_physical_device * pdevice)2166 anv_get_first_render_queue_index(struct anv_physical_device *pdevice)
2167 {
2168    assert(pdevice != NULL);
2169 
2170    for (uint32_t i = 0; i < pdevice->queue.family_count; i++) {
2171       if (pdevice->queue.families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
2172          return i;
2173       }
2174    }
2175 
2176    unreachable("Graphics capable queue family not found");
2177 }
2178 
2179 static inline struct anv_state
anv_binding_table_pool_alloc(struct anv_device * device)2180 anv_binding_table_pool_alloc(struct anv_device *device)
2181 {
2182    return anv_state_pool_alloc(&device->binding_table_pool,
2183                                device->binding_table_pool.block_size, 0);
2184 }
2185 
2186 static inline void
anv_binding_table_pool_free(struct anv_device * device,struct anv_state state)2187 anv_binding_table_pool_free(struct anv_device *device, struct anv_state state)
2188 {
2189    anv_state_pool_free(&device->binding_table_pool, state);
2190 }
2191 
2192 static inline struct anv_state
anv_null_surface_state_for_binding_table(struct anv_device * device)2193 anv_null_surface_state_for_binding_table(struct anv_device *device)
2194 {
2195    struct anv_state state = device->null_surface_state;
2196    if (device->physical->indirect_descriptors) {
2197       state.offset += device->physical->va.bindless_surface_state_pool.addr -
2198                       device->physical->va.internal_surface_state_pool.addr;
2199    }
2200    return state;
2201 }
2202 
2203 static inline struct anv_state
anv_bindless_state_for_binding_table(struct anv_device * device,struct anv_state state)2204 anv_bindless_state_for_binding_table(struct anv_device *device,
2205                                      struct anv_state state)
2206 {
2207    state.offset += device->physical->va.bindless_surface_state_pool.addr -
2208                    device->physical->va.internal_surface_state_pool.addr;
2209    return state;
2210 }
2211 
2212 static inline struct anv_state
anv_device_maybe_alloc_surface_state(struct anv_device * device,struct anv_state_stream * surface_state_stream)2213 anv_device_maybe_alloc_surface_state(struct anv_device *device,
2214                                      struct anv_state_stream *surface_state_stream)
2215 {
2216    if (device->physical->indirect_descriptors) {
2217       if (surface_state_stream)
2218          return anv_state_stream_alloc(surface_state_stream, 64, 64);
2219       return anv_state_pool_alloc(&device->bindless_surface_state_pool, 64, 64);
2220    } else {
2221       return ANV_STATE_NULL;
2222    }
2223 }
2224 
2225 static inline uint32_t
anv_mocs(const struct anv_device * device,const struct anv_bo * bo,isl_surf_usage_flags_t usage)2226 anv_mocs(const struct anv_device *device,
2227          const struct anv_bo *bo,
2228          isl_surf_usage_flags_t usage)
2229 {
2230    return isl_mocs(&device->isl_dev, usage, bo && anv_bo_is_external(bo));
2231 }
2232 
2233 static inline uint32_t
anv_mocs_for_address(const struct anv_device * device,const struct anv_address * addr)2234 anv_mocs_for_address(const struct anv_device *device,
2235                      const struct anv_address *addr)
2236 {
2237    return anv_mocs(device, addr->bo, 0);
2238 }
2239 
2240 void anv_device_init_blorp(struct anv_device *device);
2241 void anv_device_finish_blorp(struct anv_device *device);
2242 
2243 static inline void
anv_sanitize_map_params(struct anv_device * device,uint64_t in_offset,uint64_t in_size,uint64_t * out_offset,uint64_t * out_size)2244 anv_sanitize_map_params(struct anv_device *device,
2245                         uint64_t in_offset,
2246                         uint64_t in_size,
2247                         uint64_t *out_offset,
2248                         uint64_t *out_size)
2249 {
2250    /* GEM will fail to map if the offset isn't 4k-aligned.  Round down. */
2251    if (!device->physical->info.has_mmap_offset)
2252       *out_offset = in_offset & ~4095ull;
2253    else
2254       *out_offset = 0;
2255    assert(in_offset >= *out_offset);
2256    *out_size = (in_offset + in_size) - *out_offset;
2257 
2258    /* Let's map whole pages */
2259    *out_size = align64(*out_size, 4096);
2260 }
2261 
2262 
2263 VkResult anv_device_alloc_bo(struct anv_device *device,
2264                              const char *name, uint64_t size,
2265                              enum anv_bo_alloc_flags alloc_flags,
2266                              uint64_t explicit_address,
2267                              struct anv_bo **bo);
2268 VkResult anv_device_map_bo(struct anv_device *device,
2269                            struct anv_bo *bo,
2270                            uint64_t offset,
2271                            size_t size,
2272                            void *placed_addr,
2273                            void **map_out);
2274 VkResult anv_device_unmap_bo(struct anv_device *device,
2275                              struct anv_bo *bo,
2276                              void *map, size_t map_size,
2277                              bool replace);
2278 VkResult anv_device_import_bo_from_host_ptr(struct anv_device *device,
2279                                             void *host_ptr, uint32_t size,
2280                                             enum anv_bo_alloc_flags alloc_flags,
2281                                             uint64_t client_address,
2282                                             struct anv_bo **bo_out);
2283 VkResult anv_device_import_bo(struct anv_device *device, int fd,
2284                               enum anv_bo_alloc_flags alloc_flags,
2285                               uint64_t client_address,
2286                               struct anv_bo **bo);
2287 VkResult anv_device_export_bo(struct anv_device *device,
2288                               struct anv_bo *bo, int *fd_out);
2289 VkResult anv_device_get_bo_tiling(struct anv_device *device,
2290                                   struct anv_bo *bo,
2291                                   enum isl_tiling *tiling_out);
2292 VkResult anv_device_set_bo_tiling(struct anv_device *device,
2293                                   struct anv_bo *bo,
2294                                   uint32_t row_pitch_B,
2295                                   enum isl_tiling tiling);
2296 void anv_device_release_bo(struct anv_device *device,
2297                            struct anv_bo *bo);
2298 
anv_device_set_physical(struct anv_device * device,struct anv_physical_device * physical_device)2299 static inline void anv_device_set_physical(struct anv_device *device,
2300                                            struct anv_physical_device *physical_device)
2301 {
2302    device->physical = physical_device;
2303    device->info = &physical_device->info;
2304    device->isl_dev = physical_device->isl_dev;
2305 }
2306 
2307 static inline struct anv_bo *
anv_device_lookup_bo(struct anv_device * device,uint32_t gem_handle)2308 anv_device_lookup_bo(struct anv_device *device, uint32_t gem_handle)
2309 {
2310    return util_sparse_array_get(&device->bo_cache.bo_map, gem_handle);
2311 }
2312 
2313 VkResult anv_device_wait(struct anv_device *device, struct anv_bo *bo,
2314                          int64_t timeout);
2315 
2316 VkResult anv_device_print_init(struct anv_device *device);
2317 void anv_device_print_fini(struct anv_device *device);
2318 void anv_device_print_shader_prints(struct anv_device *device);
2319 
2320 void anv_dump_bvh_to_files(struct anv_device *device);
2321 
2322 VkResult anv_queue_init(struct anv_device *device, struct anv_queue *queue,
2323                         const VkDeviceQueueCreateInfo *pCreateInfo,
2324                         uint32_t index_in_family);
2325 void anv_queue_finish(struct anv_queue *queue);
2326 
2327 VkResult anv_queue_submit(struct vk_queue *queue,
2328                           struct vk_queue_submit *submit);
2329 
2330 void anv_queue_trace(struct anv_queue *queue, const char *label,
2331                      bool frame, bool begin);
2332 
2333 static inline VkResult
anv_queue_post_submit(struct anv_queue * queue,VkResult submit_result)2334 anv_queue_post_submit(struct anv_queue *queue, VkResult submit_result)
2335 {
2336    if (submit_result != VK_SUCCESS)
2337       return submit_result;
2338 
2339    VkResult result = VK_SUCCESS;
2340    if (queue->sync) {
2341       result = vk_sync_wait(&queue->device->vk, queue->sync, 0,
2342                             VK_SYNC_WAIT_COMPLETE, UINT64_MAX);
2343       if (result != VK_SUCCESS)
2344          result = vk_queue_set_lost(&queue->vk, "sync wait failed");
2345    }
2346 
2347    if (INTEL_DEBUG(DEBUG_SHADER_PRINT))
2348       anv_device_print_shader_prints(queue->device);
2349 
2350 #if ANV_SUPPORT_RT && !ANV_SUPPORT_RT_GRL
2351    /* The recorded bvh is dumped to files upon command buffer completion */
2352    if (INTEL_DEBUG(DEBUG_BVH_ANY))
2353       anv_dump_bvh_to_files(queue->device);
2354 #endif
2355 
2356    return result;
2357 }
2358 
2359 int anv_gem_wait(struct anv_device *device, uint32_t gem_handle, int64_t *timeout_ns);
2360 int anv_gem_set_tiling(struct anv_device *device, uint32_t gem_handle,
2361                        uint32_t stride, uint32_t tiling);
2362 int anv_gem_get_tiling(struct anv_device *device, uint32_t gem_handle);
2363 int anv_gem_handle_to_fd(struct anv_device *device, uint32_t gem_handle);
2364 uint32_t anv_gem_fd_to_handle(struct anv_device *device, int fd);
2365 int anv_gem_set_context_param(int fd, uint32_t context, uint32_t param,
2366                               uint64_t value);
2367 VkResult
2368 anv_gem_import_bo_alloc_flags_to_bo_flags(struct anv_device *device,
2369                                           struct anv_bo *bo,
2370                                           enum anv_bo_alloc_flags alloc_flags,
2371                                           uint32_t *bo_flags);
2372 const struct intel_device_info_pat_entry *
2373 anv_device_get_pat_entry(struct anv_device *device,
2374                          enum anv_bo_alloc_flags alloc_flags);
2375 
2376 uint64_t anv_vma_alloc(struct anv_device *device,
2377                        uint64_t size, uint64_t align,
2378                        enum anv_bo_alloc_flags alloc_flags,
2379                        uint64_t client_address,
2380                        struct util_vma_heap **out_vma_heap);
2381 void anv_vma_free(struct anv_device *device,
2382                   struct util_vma_heap *vma_heap,
2383                   uint64_t address, uint64_t size);
2384 
2385 struct anv_reloc_list {
2386    bool                                         uses_relocs;
2387    uint32_t                                     dep_words;
2388    BITSET_WORD *                                deps;
2389    const VkAllocationCallbacks                  *alloc;
2390 };
2391 
2392 VkResult anv_reloc_list_init(struct anv_reloc_list *list,
2393                              const VkAllocationCallbacks *alloc,
2394                              bool uses_relocs);
2395 void anv_reloc_list_finish(struct anv_reloc_list *list);
2396 
2397 VkResult
2398 anv_reloc_list_add_bo_impl(struct anv_reloc_list *list, struct anv_bo *target_bo);
2399 
2400 static inline VkResult
anv_reloc_list_add_bo(struct anv_reloc_list * list,struct anv_bo * target_bo)2401 anv_reloc_list_add_bo(struct anv_reloc_list *list, struct anv_bo *target_bo)
2402 {
2403    return list->uses_relocs ? anv_reloc_list_add_bo_impl(list, target_bo) : VK_SUCCESS;
2404 }
2405 
2406 VkResult anv_reloc_list_append(struct anv_reloc_list *list,
2407                                struct anv_reloc_list *other);
2408 
2409 struct anv_batch_bo {
2410    /* Link in the anv_cmd_buffer.owned_batch_bos list */
2411    struct list_head                             link;
2412 
2413    struct anv_bo *                              bo;
2414 
2415    /* Bytes actually consumed in this batch BO */
2416    uint32_t                                     length;
2417 
2418    /* When this batch BO is used as part of a primary batch buffer, this
2419     * tracked whether it is chained to another primary batch buffer.
2420     *
2421     * If this is the case, the relocation list's last entry points the
2422     * location of the MI_BATCH_BUFFER_START chaining to the next batch.
2423     */
2424    bool                                         chained;
2425 
2426    struct anv_reloc_list                        relocs;
2427 };
2428 
2429 struct anv_batch {
2430    const VkAllocationCallbacks *                alloc;
2431 
2432    /**
2433     * Sum of all the anv_batch_bo sizes allocated for this command buffer.
2434     * Used to increase allocation size for long command buffers.
2435     */
2436    size_t                                       allocated_batch_size;
2437 
2438    struct anv_address                           start_addr;
2439 
2440    void *                                       start;
2441    void *                                       end;
2442    void *                                       next;
2443 
2444    struct anv_reloc_list *                      relocs;
2445 
2446    /* This callback is called (with the associated user data) in the event
2447     * that the batch runs out of space.
2448     */
2449    VkResult (*extend_cb)(struct anv_batch *, uint32_t, void *);
2450    void *                                       user_data;
2451 
2452    /**
2453     * Current error status of the command buffer. Used to track inconsistent
2454     * or incomplete command buffer states that are the consequence of run-time
2455     * errors such as out of memory scenarios. We want to track this in the
2456     * batch because the command buffer object is not visible to some parts
2457     * of the driver.
2458     */
2459    VkResult                                     status;
2460 
2461    enum intel_engine_class                      engine_class;
2462 
2463    /**
2464     * Write fencing status for mi_builder.
2465     */
2466    bool write_fence_status;
2467 
2468    /**
2469     * Number of 3DPRIMITIVE's emitted for WA 16014538804
2470     */
2471    uint8_t num_3d_primitives_emitted;
2472 
2473    struct u_trace * trace;
2474    const char * pc_reasons[4];
2475    uint32_t pc_reasons_count;
2476 
2477 };
2478 
2479 void *anv_batch_emit_dwords(struct anv_batch *batch, int num_dwords);
2480 VkResult anv_batch_emit_ensure_space(struct anv_batch *batch, uint32_t size);
2481 void anv_batch_advance(struct anv_batch *batch, uint32_t size);
2482 void anv_batch_emit_batch(struct anv_batch *batch, struct anv_batch *other);
2483 struct anv_address anv_batch_address(struct anv_batch *batch, void *batch_location);
2484 
2485 static inline struct anv_address
anv_batch_current_address(struct anv_batch * batch)2486 anv_batch_current_address(struct anv_batch *batch)
2487 {
2488    return anv_batch_address(batch, batch->next);
2489 }
2490 
2491 static inline void
anv_batch_set_storage(struct anv_batch * batch,struct anv_address addr,void * map,size_t size)2492 anv_batch_set_storage(struct anv_batch *batch, struct anv_address addr,
2493                       void *map, size_t size)
2494 {
2495    batch->start_addr = addr;
2496    batch->next = batch->start = map;
2497    batch->end = map + size;
2498 }
2499 
2500 static inline VkResult
anv_batch_set_error(struct anv_batch * batch,VkResult error)2501 anv_batch_set_error(struct anv_batch *batch, VkResult error)
2502 {
2503    assert(error != VK_SUCCESS);
2504    if (batch->status == VK_SUCCESS)
2505       batch->status = error;
2506    return batch->status;
2507 }
2508 
2509 static inline bool
anv_batch_has_error(struct anv_batch * batch)2510 anv_batch_has_error(struct anv_batch *batch)
2511 {
2512    return batch->status != VK_SUCCESS;
2513 }
2514 
2515 static inline uint64_t
_anv_combine_address(struct anv_batch * batch,void * location,const struct anv_address address,uint32_t delta)2516 _anv_combine_address(struct anv_batch *batch, void *location,
2517                      const struct anv_address address, uint32_t delta)
2518 {
2519    if (address.bo == NULL)
2520       return address.offset + delta;
2521 
2522    if (batch)
2523       anv_reloc_list_add_bo(batch->relocs, address.bo);
2524 
2525    return anv_address_physical(anv_address_add(address, delta));
2526 }
2527 
2528 #define __gen_address_type struct anv_address
2529 #define __gen_user_data struct anv_batch
2530 #define __gen_combine_address _anv_combine_address
2531 
2532 /* Wrapper macros needed to work around preprocessor argument issues.  In
2533  * particular, arguments don't get pre-evaluated if they are concatenated.
2534  * This means that, if you pass GENX(3DSTATE_PS) into the emit macro, the
2535  * GENX macro won't get evaluated if the emit macro contains "cmd ## foo".
2536  * We can work around this easily enough with these helpers.
2537  */
2538 #define __anv_cmd_length(cmd) cmd ## _length
2539 #define __anv_cmd_length_bias(cmd) cmd ## _length_bias
2540 #define __anv_cmd_header(cmd) cmd ## _header
2541 #define __anv_cmd_pack(cmd) cmd ## _pack
2542 #define __anv_reg_num(reg) reg ## _num
2543 
2544 #define anv_pack_struct(dst, struc, ...) do {                              \
2545       struct struc __template = {                                          \
2546          __VA_ARGS__                                                       \
2547       };                                                                   \
2548       __anv_cmd_pack(struc)(NULL, dst, &__template);                       \
2549       VG(VALGRIND_CHECK_MEM_IS_DEFINED(dst, __anv_cmd_length(struc) * 4)); \
2550    } while (0)
2551 
2552 #define anv_batch_emitn(batch, n, cmd, ...) ({             \
2553       void *__dst = anv_batch_emit_dwords(batch, n);       \
2554       if (__dst) {                                         \
2555          struct cmd __template = {                         \
2556             __anv_cmd_header(cmd),                         \
2557            .DWordLength = n - __anv_cmd_length_bias(cmd),  \
2558             __VA_ARGS__                                    \
2559          };                                                \
2560          __anv_cmd_pack(cmd)(batch, __dst, &__template);   \
2561       }                                                    \
2562       __dst;                                               \
2563    })
2564 
2565 #define anv_batch_emit_merge(batch, cmd, pipeline, state, name)         \
2566    for (struct cmd name = { 0 },                                        \
2567         *_dst = anv_batch_emit_dwords(batch, __anv_cmd_length(cmd));    \
2568         __builtin_expect(_dst != NULL, 1);                              \
2569         ({ uint32_t _partial[__anv_cmd_length(cmd)];                    \
2570            assert((pipeline)->state.len == __anv_cmd_length(cmd));      \
2571            __anv_cmd_pack(cmd)(batch, _partial, &name);                 \
2572            for (uint32_t i = 0; i < __anv_cmd_length(cmd); i++) {       \
2573               assert((_partial[i] &                                     \
2574                       (pipeline)->batch_data[                           \
2575                          (pipeline)->state.offset + i]) == 0);          \
2576               ((uint32_t *)_dst)[i] = _partial[i] |                     \
2577                  (pipeline)->batch_data[(pipeline)->state.offset + i];  \
2578            }                                                            \
2579            VG(VALGRIND_CHECK_MEM_IS_DEFINED(_dst, __anv_cmd_length(cmd) * 4)); \
2580            _dst = NULL;                                                 \
2581          }))
2582 
2583 #define anv_batch_emit_merge_protected(batch, cmd, pipeline, state,     \
2584                                        name, protected)                 \
2585    for (struct cmd name = { 0 },                                        \
2586         *_dst = anv_batch_emit_dwords(batch, __anv_cmd_length(cmd));    \
2587         __builtin_expect(_dst != NULL, 1);                              \
2588         ({ struct anv_gfx_state_ptr *_cmd_state = protected ?           \
2589               &(pipeline)->state##_protected :                          \
2590               &(pipeline)->state;                                       \
2591            uint32_t _partial[__anv_cmd_length(cmd)];                    \
2592            assert(_cmd_state->len == __anv_cmd_length(cmd));            \
2593            __anv_cmd_pack(cmd)(batch, _partial, &name);                 \
2594            for (uint32_t i = 0; i < __anv_cmd_length(cmd); i++) {       \
2595               assert((_partial[i] &                                     \
2596                       (pipeline)->batch_data[                           \
2597                          (pipeline)->state.offset + i]) == 0);          \
2598               ((uint32_t *)_dst)[i] = _partial[i] |                     \
2599                  (pipeline)->batch_data[_cmd_state->offset + i];        \
2600            }                                                            \
2601            VG(VALGRIND_CHECK_MEM_IS_DEFINED(_dst, __anv_cmd_length(cmd) * 4)); \
2602            _dst = NULL;                                                 \
2603          }))
2604 
2605 #define anv_batch_emit(batch, cmd, name)                            \
2606    for (struct cmd name = { __anv_cmd_header(cmd) },                    \
2607         *_dst = anv_batch_emit_dwords(batch, __anv_cmd_length(cmd));    \
2608         __builtin_expect(_dst != NULL, 1);                              \
2609         ({ __anv_cmd_pack(cmd)(batch, _dst, &name);                     \
2610            VG(VALGRIND_CHECK_MEM_IS_DEFINED(_dst, __anv_cmd_length(cmd) * 4)); \
2611            _dst = NULL;                                                 \
2612          }))
2613 
2614 #define anv_batch_write_reg(batch, reg, name)                           \
2615    for (struct reg name = {}, *_cont = (struct reg *)1; _cont != NULL;  \
2616         ({                                                              \
2617             uint32_t _dw[__anv_cmd_length(reg)];                        \
2618             __anv_cmd_pack(reg)(NULL, _dw, &name);                      \
2619             for (unsigned i = 0; i < __anv_cmd_length(reg); i++) {      \
2620                anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) { \
2621                   lri.RegisterOffset   = __anv_reg_num(reg);            \
2622                   lri.DataDWord        = _dw[i];                        \
2623                }                                                        \
2624             }                                                           \
2625            _cont = NULL;                                                \
2626          }))
2627 
2628 /* #define __gen_get_batch_dwords anv_batch_emit_dwords */
2629 /* #define __gen_get_batch_address anv_batch_address */
2630 /* #define __gen_address_value anv_address_physical */
2631 /* #define __gen_address_offset anv_address_add */
2632 
2633 /* Base structure used to track a submission that needs some clean operations
2634  * upon completion. Should be embedded into a larger structure.
2635  */
2636 struct anv_async_submit {
2637    struct anv_queue *queue;
2638 
2639    struct anv_bo_pool *bo_pool;
2640 
2641    bool use_companion_rcs;
2642 
2643    bool owns_sync;
2644    struct vk_sync_signal signal;
2645 
2646    struct anv_reloc_list relocs;
2647    struct anv_batch batch;
2648    struct util_dynarray batch_bos;
2649 };
2650 
2651 VkResult
2652 anv_async_submit_init(struct anv_async_submit *submit,
2653                       struct anv_queue *queue,
2654                       struct anv_bo_pool *bo_pool,
2655                       bool use_companion_rcs,
2656                       bool create_signal_sync);
2657 
2658 void
2659 anv_async_submit_fini(struct anv_async_submit *submit);
2660 
2661 VkResult
2662 anv_async_submit_create(struct anv_queue *queue,
2663                         struct anv_bo_pool *bo_pool,
2664                         bool use_companion_rcs,
2665                         bool create_signal_sync,
2666                         struct anv_async_submit **out_submit);
2667 
2668 void
2669 anv_async_submit_destroy(struct anv_async_submit *submit);
2670 
2671 bool
2672 anv_async_submit_done(struct anv_async_submit *submit);
2673 
2674 bool
2675 anv_async_submit_wait(struct anv_async_submit *submit);
2676 
2677 struct anv_sparse_submission {
2678    struct anv_queue *queue;
2679 
2680    struct anv_vm_bind *binds;
2681    int binds_len;
2682    int binds_capacity;
2683 
2684    uint32_t wait_count;
2685    uint32_t signal_count;
2686 
2687    struct vk_sync_wait *waits;
2688    struct vk_sync_signal *signals;
2689 };
2690 
2691 struct anv_trtt_bind {
2692    uint64_t pte_addr;
2693    uint64_t entry_addr;
2694 };
2695 
2696 struct anv_trtt_submission {
2697    struct anv_async_submit base;
2698 
2699    struct anv_sparse_submission *sparse;
2700 
2701    struct list_head link;
2702 };
2703 
2704 struct anv_device_memory {
2705    struct vk_device_memory                      vk;
2706 
2707    struct list_head                             link;
2708 
2709    struct anv_bo *                              bo;
2710    const struct anv_memory_type *               type;
2711 
2712    void *                                       map;
2713    size_t                                       map_size;
2714 
2715    /* The map, from the user PoV is map + map_delta */
2716    uint64_t                                     map_delta;
2717 };
2718 
2719 /**
2720  * Header for Vertex URB Entry (VUE)
2721  */
2722 struct anv_vue_header {
2723    uint32_t Reserved;
2724    uint32_t RTAIndex; /* RenderTargetArrayIndex */
2725    uint32_t ViewportIndex;
2726    float PointWidth;
2727 };
2728 
2729 /** Struct representing a sampled image descriptor
2730  *
2731  * This descriptor layout is used for sampled images, bare sampler, and
2732  * combined image/sampler descriptors.
2733  */
2734 struct anv_sampled_image_descriptor {
2735    /** Bindless image handle
2736     *
2737     * This is expected to already be shifted such that the 20-bit
2738     * SURFACE_STATE table index is in the top 20 bits.
2739     */
2740    uint32_t image;
2741 
2742    /** Bindless sampler handle
2743     *
2744     * This is assumed to be a 32B-aligned SAMPLER_STATE pointer relative
2745     * to the dynamic state base address.
2746     */
2747    uint32_t sampler;
2748 };
2749 
2750 /** Struct representing a storage image descriptor */
2751 struct anv_storage_image_descriptor {
2752    /** Bindless image handles
2753     *
2754     * These are expected to already be shifted such that the 20-bit
2755     * SURFACE_STATE table index is in the top 20 bits.
2756     */
2757    uint32_t vanilla;
2758 
2759    /** Image depth
2760     *
2761     * By default the HW RESINFO message allows us to query the depth of an image :
2762     *
2763     * From the Kaby Lake docs for the RESINFO message:
2764     *
2765     *    "Surface Type | ... | Blue
2766     *    --------------+-----+----------------
2767     *    SURFTYPE_3D  | ... | (Depth+1)»LOD"
2768     *
2769     * With VK_EXT_sliced_view_of_3d, we have to support a slice of a 3D image,
2770     * meaning at a depth offset with a new depth value potentially reduced
2771     * from the original image. Unfortunately if we change the Depth value of
2772     * the image, we then run into issues with Yf/Ys tilings where the HW fetch
2773     * data at incorrect locations.
2774     *
2775     * To solve this, we put the slice depth in the descriptor and recompose
2776     * the vec3 (width, height, depth) using this field for z and xy using the
2777     * RESINFO result.
2778     */
2779    uint32_t image_depth;
2780 };
2781 
2782 /** Struct representing a address/range descriptor
2783  *
2784  * The fields of this struct correspond directly to the data layout of
2785  * nir_address_format_64bit_bounded_global addresses.  The last field is the
2786  * offset in the NIR address so it must be zero so that when you load the
2787  * descriptor you get a pointer to the start of the range.
2788  */
2789 struct anv_address_range_descriptor {
2790    uint64_t address;
2791    uint32_t range;
2792    uint32_t zero;
2793 };
2794 
2795 enum anv_descriptor_data {
2796    /** The descriptor contains a BTI reference to a surface state */
2797    ANV_DESCRIPTOR_BTI_SURFACE_STATE       = BITFIELD_BIT(0),
2798    /** The descriptor contains a BTI reference to a sampler state */
2799    ANV_DESCRIPTOR_BTI_SAMPLER_STATE       = BITFIELD_BIT(1),
2800    /** The descriptor contains an actual buffer view */
2801    ANV_DESCRIPTOR_BUFFER_VIEW             = BITFIELD_BIT(2),
2802    /** The descriptor contains inline uniform data */
2803    ANV_DESCRIPTOR_INLINE_UNIFORM          = BITFIELD_BIT(3),
2804    /** anv_address_range_descriptor with a buffer address and range */
2805    ANV_DESCRIPTOR_INDIRECT_ADDRESS_RANGE  = BITFIELD_BIT(4),
2806    /** Bindless surface handle (through anv_sampled_image_descriptor) */
2807    ANV_DESCRIPTOR_INDIRECT_SAMPLED_IMAGE  = BITFIELD_BIT(5),
2808    /** Storage image handles (through anv_storage_image_descriptor) */
2809    ANV_DESCRIPTOR_INDIRECT_STORAGE_IMAGE  = BITFIELD_BIT(6),
2810    /** The descriptor contains a single RENDER_SURFACE_STATE */
2811    ANV_DESCRIPTOR_SURFACE                 = BITFIELD_BIT(7),
2812    /** The descriptor contains a SAMPLER_STATE */
2813    ANV_DESCRIPTOR_SAMPLER                 = BITFIELD_BIT(8),
2814    /** A tuple of RENDER_SURFACE_STATE & SAMPLER_STATE */
2815    ANV_DESCRIPTOR_SURFACE_SAMPLER         = BITFIELD_BIT(9),
2816 };
2817 
2818 struct anv_descriptor_set_binding_layout {
2819    /* The type of the descriptors in this binding */
2820    VkDescriptorType type;
2821 
2822    /* Flags provided when this binding was created */
2823    VkDescriptorBindingFlags flags;
2824 
2825    /* Bitfield representing the type of data this descriptor contains */
2826    enum anv_descriptor_data data;
2827 
2828    /* Maximum number of YCbCr texture/sampler planes */
2829    uint8_t max_plane_count;
2830 
2831    /* Number of array elements in this binding (or size in bytes for inline
2832     * uniform data)
2833     */
2834    uint32_t array_size;
2835 
2836    /* Index into the flattened descriptor set */
2837    uint32_t descriptor_index;
2838 
2839    /* Index into the dynamic state array for a dynamic buffer, relative to the
2840     * set.
2841     */
2842    int16_t dynamic_offset_index;
2843 
2844    /* Computed surface size from data (for one plane) */
2845    uint16_t descriptor_data_surface_size;
2846 
2847    /* Computed sampler size from data (for one plane) */
2848    uint16_t descriptor_data_sampler_size;
2849 
2850    /* Index into the descriptor set buffer views */
2851    int32_t buffer_view_index;
2852 
2853    /* Offset into the descriptor buffer where the surface descriptor lives */
2854    uint32_t descriptor_surface_offset;
2855 
2856    /* Offset into the descriptor buffer where the sampler descriptor lives */
2857    uint16_t descriptor_sampler_offset;
2858 
2859    /* Pre computed surface stride (with multiplane descriptor, the descriptor
2860     * includes all the planes)
2861     */
2862    uint16_t descriptor_surface_stride;
2863 
2864    /* Pre computed sampler stride (with multiplane descriptor, the descriptor
2865     * includes all the planes)
2866     */
2867    uint16_t descriptor_sampler_stride;
2868 
2869    /* Immutable samplers (or NULL if no immutable samplers) */
2870    struct anv_sampler **immutable_samplers;
2871 };
2872 
2873 enum anv_descriptor_set_layout_type {
2874    ANV_PIPELINE_DESCRIPTOR_SET_LAYOUT_TYPE_UNKNOWN,
2875    ANV_PIPELINE_DESCRIPTOR_SET_LAYOUT_TYPE_INDIRECT,
2876    ANV_PIPELINE_DESCRIPTOR_SET_LAYOUT_TYPE_DIRECT,
2877    ANV_PIPELINE_DESCRIPTOR_SET_LAYOUT_TYPE_BUFFER,
2878 };
2879 
2880 struct anv_descriptor_set_layout {
2881    struct vk_object_base base;
2882 
2883    VkDescriptorSetLayoutCreateFlags flags;
2884 
2885    /* Type of descriptor set layout */
2886    enum anv_descriptor_set_layout_type type;
2887 
2888    /* Descriptor set layouts can be destroyed at almost any time */
2889    uint32_t ref_cnt;
2890 
2891    /* Number of bindings in this descriptor set */
2892    uint32_t binding_count;
2893 
2894    /* Total number of descriptors */
2895    uint32_t descriptor_count;
2896 
2897    /* Shader stages affected by this descriptor set */
2898    uint16_t shader_stages;
2899 
2900    /* Number of buffer views in this descriptor set */
2901    uint32_t buffer_view_count;
2902 
2903    /* Number of dynamic offsets used by this descriptor set */
2904    uint16_t dynamic_offset_count;
2905 
2906    /* For each dynamic buffer, which VkShaderStageFlagBits stages are using
2907     * this buffer
2908     */
2909    VkShaderStageFlags dynamic_offset_stages[MAX_DYNAMIC_BUFFERS];
2910 
2911    /* Size of the descriptor buffer dedicated to surface states for this
2912     * descriptor set
2913     */
2914    uint32_t descriptor_buffer_surface_size;
2915 
2916    /* Size of the descriptor buffer dedicated to sampler states for this
2917     * descriptor set
2918     */
2919    uint32_t descriptor_buffer_sampler_size;
2920 
2921    /* Number of embedded sampler count */
2922    uint32_t embedded_sampler_count;
2923 
2924    /* Bindings in this descriptor set */
2925    struct anv_descriptor_set_binding_layout binding[0];
2926 };
2927 
2928 bool anv_descriptor_supports_bindless(const struct anv_physical_device *pdevice,
2929                                       const struct anv_descriptor_set_layout *set,
2930                                       const struct anv_descriptor_set_binding_layout *binding);
2931 
2932 bool anv_descriptor_requires_bindless(const struct anv_physical_device *pdevice,
2933                                       const struct anv_descriptor_set_layout *set,
2934                                       const struct anv_descriptor_set_binding_layout *binding);
2935 
2936 void anv_descriptor_set_layout_destroy(struct anv_device *device,
2937                                        struct anv_descriptor_set_layout *layout);
2938 
2939 void anv_descriptor_set_layout_print(const struct anv_descriptor_set_layout *layout);
2940 
2941 static inline struct anv_descriptor_set_layout *
anv_descriptor_set_layout_ref(struct anv_descriptor_set_layout * layout)2942 anv_descriptor_set_layout_ref(struct anv_descriptor_set_layout *layout)
2943 {
2944    assert(layout && layout->ref_cnt >= 1);
2945    p_atomic_inc(&layout->ref_cnt);
2946 
2947    return layout;
2948 }
2949 
2950 static inline void
anv_descriptor_set_layout_unref(struct anv_device * device,struct anv_descriptor_set_layout * layout)2951 anv_descriptor_set_layout_unref(struct anv_device *device,
2952                                 struct anv_descriptor_set_layout *layout)
2953 {
2954    assert(layout && layout->ref_cnt >= 1);
2955    if (p_atomic_dec_zero(&layout->ref_cnt))
2956       anv_descriptor_set_layout_destroy(device, layout);
2957 }
2958 
2959 struct anv_descriptor {
2960    VkDescriptorType type;
2961 
2962    union {
2963       struct {
2964          VkImageLayout layout;
2965          struct anv_image_view *image_view;
2966          struct anv_sampler *sampler;
2967       };
2968 
2969       struct {
2970          struct anv_buffer_view *set_buffer_view;
2971          struct anv_buffer *buffer;
2972          uint64_t offset;
2973          uint64_t range;
2974          uint64_t bind_range;
2975       };
2976 
2977       struct anv_buffer_view *buffer_view;
2978 
2979       struct vk_acceleration_structure *accel_struct;
2980    };
2981 };
2982 
2983 struct anv_descriptor_set {
2984    struct vk_object_base base;
2985 
2986    struct anv_descriptor_pool *pool;
2987    struct anv_descriptor_set_layout *layout;
2988 
2989    /* Amount of space occupied in the the pool by this descriptor set. It can
2990     * be larger than the size of the descriptor set.
2991     */
2992    uint32_t size;
2993 
2994    /* Is this descriptor set a push descriptor */
2995    bool is_push;
2996 
2997    /* Bitfield of descriptors for which we need to generate surface states.
2998     * Only valid for push descriptors
2999     */
3000    uint32_t generate_surface_states;
3001 
3002    /* State relative to anv_descriptor_pool::surface_bo */
3003    struct anv_state desc_surface_mem;
3004    /* State relative to anv_descriptor_pool::sampler_bo */
3005    struct anv_state desc_sampler_mem;
3006    /* Surface state for the descriptor buffer */
3007    struct anv_state desc_surface_state;
3008 
3009    /* Descriptor set address pointing to desc_surface_mem (we don't need one
3010     * for sampler because they're never accessed other than by the HW through
3011     * the shader sampler handle).
3012     */
3013    struct anv_address desc_surface_addr;
3014 
3015    struct anv_address desc_sampler_addr;
3016 
3017    /* Descriptor offset from the
3018     * device->va.internal_surface_state_pool.addr
3019     *
3020     * It just needs to be added to the binding table offset to be put into the
3021     * HW BTI entry.
3022     */
3023    uint32_t desc_offset;
3024 
3025    uint32_t buffer_view_count;
3026    struct anv_buffer_view *buffer_views;
3027 
3028    /* Link to descriptor pool's desc_sets list . */
3029    struct list_head pool_link;
3030 
3031    uint32_t descriptor_count;
3032    struct anv_descriptor descriptors[0];
3033 };
3034 
3035 static inline bool
anv_descriptor_set_is_push(struct anv_descriptor_set * set)3036 anv_descriptor_set_is_push(struct anv_descriptor_set *set)
3037 {
3038    return set->pool == NULL;
3039 }
3040 
3041 struct anv_surface_state_data {
3042    uint8_t data[ANV_SURFACE_STATE_SIZE];
3043 };
3044 
3045 struct anv_buffer_state {
3046    /** Surface state allocated from the bindless heap
3047     *
3048     * Only valid if anv_physical_device::indirect_descriptors is true
3049     */
3050    struct anv_state state;
3051 
3052    /** Surface state after genxml packing
3053     *
3054     * Only valid if anv_physical_device::indirect_descriptors is false
3055     */
3056    struct anv_surface_state_data state_data;
3057 };
3058 
3059 struct anv_buffer_view {
3060    struct vk_buffer_view vk;
3061 
3062    struct anv_address address;
3063 
3064    struct anv_buffer_state general;
3065    struct anv_buffer_state storage;
3066 };
3067 
3068 struct anv_push_descriptor_set {
3069    struct anv_descriptor_set set;
3070 
3071    /* Put this field right behind anv_descriptor_set so it fills up the
3072     * descriptors[0] field. */
3073    struct anv_descriptor descriptors[MAX_PUSH_DESCRIPTORS];
3074 
3075    /** True if the descriptor set buffer has been referenced by a draw or
3076     * dispatch command.
3077     */
3078    bool set_used_on_gpu;
3079 
3080    struct anv_buffer_view buffer_views[MAX_PUSH_DESCRIPTORS];
3081 };
3082 
3083 static inline struct anv_address
anv_descriptor_set_address(struct anv_descriptor_set * set)3084 anv_descriptor_set_address(struct anv_descriptor_set *set)
3085 {
3086    if (anv_descriptor_set_is_push(set)) {
3087       /* We have to flag push descriptor set as used on the GPU
3088        * so that the next time we push descriptors, we grab a new memory.
3089        */
3090       struct anv_push_descriptor_set *push_set =
3091          (struct anv_push_descriptor_set *)set;
3092       push_set->set_used_on_gpu = true;
3093    }
3094 
3095    return set->desc_surface_addr;
3096 }
3097 
3098 struct anv_descriptor_pool_heap {
3099    /* BO allocated to back the pool (unused for host pools) */
3100    struct anv_bo        *bo;
3101 
3102    /* Host memory allocated to back a host pool */
3103    void                 *host_mem;
3104 
3105    /* Heap tracking allocations in bo/host_mem */
3106    struct util_vma_heap  heap;
3107 
3108    /* Size of the heap */
3109    uint32_t              size;
3110 
3111    /* Allocated size in the heap */
3112    uint32_t              alloc_size;
3113 };
3114 
3115 struct anv_descriptor_pool {
3116    struct vk_object_base base;
3117 
3118    struct anv_descriptor_pool_heap surfaces;
3119    struct anv_descriptor_pool_heap samplers;
3120 
3121    struct anv_state_stream surface_state_stream;
3122    void *surface_state_free_list;
3123 
3124    /** List of anv_descriptor_set. */
3125    struct list_head desc_sets;
3126 
3127    /** Heap over host_mem */
3128    struct util_vma_heap host_heap;
3129 
3130    /** Allocated size of host_mem */
3131    uint32_t host_mem_size;
3132 
3133    /**
3134     * VK_DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_EXT. If set, then
3135     * surface_state_stream is unused.
3136     */
3137    bool host_only;
3138 
3139    alignas(8) char host_mem[0];
3140 };
3141 
3142 bool
3143 anv_push_descriptor_set_init(struct anv_cmd_buffer *cmd_buffer,
3144                              struct anv_push_descriptor_set *push_set,
3145                              struct anv_descriptor_set_layout *layout);
3146 
3147 void
3148 anv_push_descriptor_set_finish(struct anv_push_descriptor_set *push_set);
3149 
3150 void
3151 anv_descriptor_set_write_image_view(struct anv_device *device,
3152                                     struct anv_descriptor_set *set,
3153                                     const VkDescriptorImageInfo * const info,
3154                                     VkDescriptorType type,
3155                                     uint32_t binding,
3156                                     uint32_t element);
3157 
3158 void
3159 anv_descriptor_set_write_buffer_view(struct anv_device *device,
3160                                      struct anv_descriptor_set *set,
3161                                      VkDescriptorType type,
3162                                      struct anv_buffer_view *buffer_view,
3163                                      uint32_t binding,
3164                                      uint32_t element);
3165 
3166 void
3167 anv_descriptor_set_write_buffer(struct anv_device *device,
3168                                 struct anv_descriptor_set *set,
3169                                 VkDescriptorType type,
3170                                 struct anv_buffer *buffer,
3171                                 uint32_t binding,
3172                                 uint32_t element,
3173                                 VkDeviceSize offset,
3174                                 VkDeviceSize range);
3175 
3176 void
3177 anv_descriptor_write_surface_state(struct anv_device *device,
3178                                    struct anv_descriptor *desc,
3179                                    struct anv_state surface_state);
3180 
3181 void
3182 anv_descriptor_set_write_acceleration_structure(struct anv_device *device,
3183                                                 struct anv_descriptor_set *set,
3184                                                 struct vk_acceleration_structure *accel,
3185                                                 uint32_t binding,
3186                                                 uint32_t element);
3187 
3188 void
3189 anv_descriptor_set_write_inline_uniform_data(struct anv_device *device,
3190                                              struct anv_descriptor_set *set,
3191                                              uint32_t binding,
3192                                              const void *data,
3193                                              size_t offset,
3194                                              size_t size);
3195 
3196 void
3197 anv_descriptor_set_write(struct anv_device *device,
3198                          struct anv_descriptor_set *set_override,
3199                          uint32_t write_count,
3200                          const VkWriteDescriptorSet *writes);
3201 
3202 void
3203 anv_descriptor_set_write_template(struct anv_device *device,
3204                                   struct anv_descriptor_set *set,
3205                                   const struct vk_descriptor_update_template *template,
3206                                   const void *data);
3207 
3208 #define ANV_DESCRIPTOR_SET_DESCRIPTORS_BUFFER (UINT8_MAX - 4)
3209 #define ANV_DESCRIPTOR_SET_NULL               (UINT8_MAX - 3)
3210 #define ANV_DESCRIPTOR_SET_PUSH_CONSTANTS     (UINT8_MAX - 2)
3211 #define ANV_DESCRIPTOR_SET_DESCRIPTORS        (UINT8_MAX - 1)
3212 #define ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS   UINT8_MAX
3213 
3214 struct anv_pipeline_binding {
3215    /** Index in the descriptor set
3216     *
3217     * This is a flattened index; the descriptor set layout is already taken
3218     * into account.
3219     */
3220    uint32_t index;
3221 
3222    /** Binding in the descriptor set. Not valid for any of the
3223     * ANV_DESCRIPTOR_SET_*
3224     */
3225    uint32_t binding;
3226 
3227    /** Offset in the descriptor buffer
3228     *
3229     * Relative to anv_descriptor_set::desc_addr. This is useful for
3230     * ANV_PIPELINE_DESCRIPTOR_SET_LAYOUT_TYPE_DIRECT, to generate the binding
3231     * table entry.
3232     */
3233    uint32_t set_offset;
3234 
3235    /** The descriptor set this surface corresponds to.
3236     *
3237     * The special ANV_DESCRIPTOR_SET_* values above indicates that this
3238     * binding is not a normal descriptor set but something else.
3239     */
3240    uint8_t set;
3241 
3242    union {
3243       /** Plane in the binding index for images */
3244       uint8_t plane;
3245 
3246       /** Input attachment index (relative to the subpass) */
3247       uint8_t input_attachment_index;
3248 
3249       /** Dynamic offset index
3250        *
3251        * For dynamic UBOs and SSBOs, relative to set.
3252        */
3253       uint8_t dynamic_offset_index;
3254    };
3255 };
3256 
3257 struct anv_embedded_sampler_key {
3258    /** No need to track binding elements for embedded samplers as :
3259     *
3260     *    VUID-VkDescriptorSetLayoutBinding-flags-08006:
3261     *
3262     *       "If VkDescriptorSetLayoutCreateInfo:flags contains
3263     *        VK_DESCRIPTOR_SET_LAYOUT_CREATE_EMBEDDED_IMMUTABLE_SAMPLERS_BIT_EXT,
3264     *        descriptorCount must: less than or equal to 1"
3265     *
3266     * The following struct can be safely hash as it doesn't include in
3267     * address/offset.
3268     */
3269    uint32_t sampler[4];
3270    uint32_t color[4];
3271 };
3272 
3273 struct anv_pipeline_embedded_sampler_binding {
3274    /** The descriptor set this sampler belongs to */
3275    uint8_t set;
3276 
3277    /** The binding in the set this sampler belongs to */
3278    uint32_t binding;
3279 
3280    /** The data configuring the sampler */
3281    struct anv_embedded_sampler_key key;
3282 };
3283 
3284 struct anv_push_range {
3285    /** Index in the descriptor set */
3286    uint32_t index;
3287 
3288    /** Descriptor set index */
3289    uint8_t set;
3290 
3291    /** Dynamic offset index (for dynamic UBOs), relative to set. */
3292    uint8_t dynamic_offset_index;
3293 
3294    /** Start offset in units of 32B */
3295    uint8_t start;
3296 
3297    /** Range in units of 32B */
3298    uint8_t length;
3299 };
3300 
3301 struct anv_pipeline_sets_layout {
3302    struct anv_device *device;
3303 
3304    struct {
3305       struct anv_descriptor_set_layout *layout;
3306       uint32_t dynamic_offset_start;
3307    } set[MAX_SETS];
3308 
3309    enum anv_descriptor_set_layout_type type;
3310 
3311    uint32_t num_sets;
3312    uint32_t num_dynamic_buffers;
3313    int push_descriptor_set_index;
3314 
3315    bool independent_sets;
3316 
3317    unsigned char sha1[20];
3318 };
3319 
3320 void anv_pipeline_sets_layout_init(struct anv_pipeline_sets_layout *layout,
3321                                    struct anv_device *device,
3322                                    bool independent_sets);
3323 
3324 void anv_pipeline_sets_layout_fini(struct anv_pipeline_sets_layout *layout);
3325 
3326 void anv_pipeline_sets_layout_add(struct anv_pipeline_sets_layout *layout,
3327                                   uint32_t set_idx,
3328                                   struct anv_descriptor_set_layout *set_layout);
3329 
3330 uint32_t
3331 anv_pipeline_sets_layout_embedded_sampler_count(const struct anv_pipeline_sets_layout *layout);
3332 
3333 void anv_pipeline_sets_layout_hash(struct anv_pipeline_sets_layout *layout);
3334 
3335 void anv_pipeline_sets_layout_print(const struct anv_pipeline_sets_layout *layout);
3336 
3337 struct anv_pipeline_layout {
3338    struct vk_object_base base;
3339 
3340    struct anv_pipeline_sets_layout sets_layout;
3341 };
3342 
3343 const struct anv_descriptor_set_layout *
3344 anv_pipeline_layout_get_push_set(const struct anv_pipeline_sets_layout *layout,
3345                                  uint8_t *desc_idx);
3346 
3347 struct anv_sparse_binding_data {
3348    uint64_t address;
3349    uint64_t size;
3350 
3351    /* This is kept only because it's given to us by vma_alloc() and need to be
3352     * passed back to vma_free(), we have no other particular use for it
3353     */
3354    struct util_vma_heap *vma_heap;
3355 };
3356 
3357 #define ANV_SPARSE_BLOCK_SIZE (64 * 1024)
3358 
3359 static inline bool
anv_sparse_binding_is_enabled(struct anv_device * device)3360 anv_sparse_binding_is_enabled(struct anv_device *device)
3361 {
3362    return device->vk.enabled_features.sparseBinding;
3363 }
3364 
3365 static inline bool
anv_sparse_residency_is_enabled(struct anv_device * device)3366 anv_sparse_residency_is_enabled(struct anv_device *device)
3367 {
3368    return device->vk.enabled_features.sparseResidencyBuffer ||
3369           device->vk.enabled_features.sparseResidencyImage2D ||
3370           device->vk.enabled_features.sparseResidencyImage3D ||
3371           device->vk.enabled_features.sparseResidency2Samples ||
3372           device->vk.enabled_features.sparseResidency4Samples ||
3373           device->vk.enabled_features.sparseResidency8Samples ||
3374           device->vk.enabled_features.sparseResidency16Samples ||
3375           device->vk.enabled_features.sparseResidencyAliased;
3376 }
3377 
3378 VkResult anv_init_sparse_bindings(struct anv_device *device,
3379                                   uint64_t size,
3380                                   struct anv_sparse_binding_data *sparse,
3381                                   enum anv_bo_alloc_flags alloc_flags,
3382                                   uint64_t client_address,
3383                                   struct anv_address *out_address);
3384 void anv_free_sparse_bindings(struct anv_device *device,
3385                               struct anv_sparse_binding_data *sparse);
3386 VkResult anv_sparse_bind_buffer(struct anv_device *device,
3387                                 struct anv_buffer *buffer,
3388                                 const VkSparseMemoryBind *vk_bind,
3389                                 struct anv_sparse_submission *submit);
3390 VkResult anv_sparse_bind_image_opaque(struct anv_device *device,
3391                                       struct anv_image *image,
3392                                       const VkSparseMemoryBind *vk_bind,
3393                                       struct anv_sparse_submission *submit);
3394 VkResult anv_sparse_bind_image_memory(struct anv_queue *queue,
3395                                       struct anv_image *image,
3396                                       const VkSparseImageMemoryBind *bind,
3397                                       struct anv_sparse_submission *submit);
3398 VkResult anv_sparse_bind(struct anv_device *device,
3399                          struct anv_sparse_submission *sparse_submit);
3400 
3401 VkResult anv_sparse_trtt_garbage_collect_batches(struct anv_device *device,
3402                                                  bool wait_completion);
3403 
3404 VkSparseImageFormatProperties
3405 anv_sparse_calc_image_format_properties(struct anv_physical_device *pdevice,
3406                                         VkImageAspectFlags aspect,
3407                                         VkImageType vk_image_type,
3408                                         VkSampleCountFlagBits vk_samples,
3409                                         struct isl_surf *surf);
3410 void anv_sparse_calc_miptail_properties(struct anv_device *device,
3411                                         struct anv_image *image,
3412                                         VkImageAspectFlags vk_aspect,
3413                                         uint32_t *imageMipTailFirstLod,
3414                                         VkDeviceSize *imageMipTailSize,
3415                                         VkDeviceSize *imageMipTailOffset,
3416                                         VkDeviceSize *imageMipTailStride);
3417 VkResult anv_sparse_image_check_support(struct anv_physical_device *pdevice,
3418                                         VkImageCreateFlags flags,
3419                                         VkImageTiling tiling,
3420                                         VkSampleCountFlagBits samples,
3421                                         VkImageType type,
3422                                         VkFormat format);
3423 
3424 struct anv_buffer {
3425    struct vk_buffer vk;
3426 
3427    /* Set when bound */
3428    struct anv_address address;
3429 
3430    struct anv_sparse_binding_data sparse_data;
3431 };
3432 
3433 static inline bool
anv_buffer_is_protected(const struct anv_buffer * buffer)3434 anv_buffer_is_protected(const struct anv_buffer *buffer)
3435 {
3436    return buffer->vk.create_flags & VK_BUFFER_CREATE_PROTECTED_BIT;
3437 }
3438 
3439 static inline bool
anv_buffer_is_sparse(const struct anv_buffer * buffer)3440 anv_buffer_is_sparse(const struct anv_buffer *buffer)
3441 {
3442    return buffer->vk.create_flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT;
3443 }
3444 
3445 enum anv_cmd_dirty_bits {
3446    ANV_CMD_DIRTY_PIPELINE                            = 1 << 0,
3447    ANV_CMD_DIRTY_INDEX_BUFFER                        = 1 << 1,
3448    ANV_CMD_DIRTY_RENDER_AREA                         = 1 << 2,
3449    ANV_CMD_DIRTY_RENDER_TARGETS                      = 1 << 3,
3450    ANV_CMD_DIRTY_XFB_ENABLE                          = 1 << 4,
3451    ANV_CMD_DIRTY_RESTART_INDEX                       = 1 << 5,
3452    ANV_CMD_DIRTY_OCCLUSION_QUERY_ACTIVE              = 1 << 6,
3453    ANV_CMD_DIRTY_INDIRECT_DATA_STRIDE                = 1 << 7,
3454 };
3455 typedef enum anv_cmd_dirty_bits anv_cmd_dirty_mask_t;
3456 
3457 enum anv_pipe_bits {
3458    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT            = (1 << 0),
3459    ANV_PIPE_STALL_AT_SCOREBOARD_BIT          = (1 << 1),
3460    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT       = (1 << 2),
3461    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT    = (1 << 3),
3462    ANV_PIPE_VF_CACHE_INVALIDATE_BIT          = (1 << 4),
3463    ANV_PIPE_DATA_CACHE_FLUSH_BIT             = (1 << 5),
3464    ANV_PIPE_TILE_CACHE_FLUSH_BIT             = (1 << 6),
3465    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT     = (1 << 10),
3466    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT = (1 << 11),
3467    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT    = (1 << 12),
3468    ANV_PIPE_DEPTH_STALL_BIT                  = (1 << 13),
3469 
3470    /* ANV_PIPE_HDC_PIPELINE_FLUSH_BIT is a precise way to ensure prior data
3471     * cache work has completed.  Available on Gfx12+.  For earlier Gfx we
3472     * must reinterpret this flush as ANV_PIPE_DATA_CACHE_FLUSH_BIT.
3473     */
3474    ANV_PIPE_HDC_PIPELINE_FLUSH_BIT           = (1 << 14),
3475    ANV_PIPE_PSS_STALL_SYNC_BIT               = (1 << 15),
3476 
3477    /*
3478     * This bit flush data-port's Untyped L1 data cache (LSC L1).
3479     */
3480    ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT = (1 << 16),
3481 
3482    /* This bit controls the flushing of the engine (Render, Compute) specific
3483     * entries from the compression cache.
3484     */
3485    ANV_PIPE_CCS_CACHE_FLUSH_BIT              = (1 << 17),
3486 
3487    ANV_PIPE_TLB_INVALIDATE_BIT               = (1 << 18),
3488 
3489    /* L3 Fabric Flush */
3490    ANV_PIPE_L3_FABRIC_FLUSH_BIT              = (1 << 19),
3491 
3492    ANV_PIPE_CS_STALL_BIT                     = (1 << 20),
3493    ANV_PIPE_END_OF_PIPE_SYNC_BIT             = (1 << 21),
3494 
3495    /* This bit does not exist directly in PIPE_CONTROL.  Instead it means that
3496     * a flush has happened but not a CS stall.  The next time we do any sort
3497     * of invalidation we need to insert a CS stall at that time.  Otherwise,
3498     * we would have to CS stall on every flush which could be bad.
3499     */
3500    ANV_PIPE_NEEDS_END_OF_PIPE_SYNC_BIT       = (1 << 22),
3501 
3502    /* This bit does not exist directly in PIPE_CONTROL. It means that Gfx12
3503     * AUX-TT data has changed and we need to invalidate AUX-TT data.  This is
3504     * done by writing the AUX-TT register.
3505     */
3506    ANV_PIPE_AUX_TABLE_INVALIDATE_BIT         = (1 << 23),
3507 
3508    /* This bit does not exist directly in PIPE_CONTROL. It means that a
3509     * PIPE_CONTROL with a post-sync operation will follow. This is used to
3510     * implement a workaround for Gfx9.
3511     */
3512    ANV_PIPE_POST_SYNC_BIT                    = (1 << 24),
3513 
3514 };
3515 
3516 /* These bits track the state of buffer writes for queries. They get cleared
3517  * based on PIPE_CONTROL emissions.
3518  */
3519 enum anv_query_bits {
3520    ANV_QUERY_WRITES_RT_FLUSH      = (1 << 0),
3521 
3522    ANV_QUERY_WRITES_TILE_FLUSH    = (1 << 1),
3523 
3524    ANV_QUERY_WRITES_CS_STALL      = (1 << 2),
3525 
3526    ANV_QUERY_WRITES_DATA_FLUSH    = (1 << 3),
3527 };
3528 
3529 /* It's not clear why DG2 doesn't have issues with L3/CS coherency. But it's
3530  * likely related to performance workaround 14015868140.
3531  *
3532  * For now we enable this only on DG2 and platform prior to Gfx12 where there
3533  * is no tile cache.
3534  */
3535 #define ANV_DEVINFO_HAS_COHERENT_L3_CS(devinfo) \
3536    (intel_device_info_is_dg2(devinfo))
3537 
3538 /* Things we need to flush before accessing query data using the command
3539  * streamer.
3540  *
3541  * Prior to DG2 experiments show that the command streamer is not coherent
3542  * with the tile cache so we need to flush it to make any data visible to CS.
3543  *
3544  * Otherwise we want to flush the RT cache which is where blorp writes, either
3545  * for clearing the query buffer or for clearing the destination buffer in
3546  * vkCopyQueryPoolResults().
3547  */
3548 #define ANV_QUERY_RENDER_TARGET_WRITES_PENDING_BITS(devinfo) \
3549    (((!ANV_DEVINFO_HAS_COHERENT_L3_CS(devinfo) && \
3550       (devinfo)->ver >= 12) ? \
3551      ANV_QUERY_WRITES_TILE_FLUSH : 0) | \
3552     ANV_QUERY_WRITES_RT_FLUSH | \
3553     ANV_QUERY_WRITES_CS_STALL)
3554 #define ANV_QUERY_COMPUTE_WRITES_PENDING_BITS \
3555    (ANV_QUERY_WRITES_DATA_FLUSH | \
3556     ANV_QUERY_WRITES_CS_STALL)
3557 
3558 #define ANV_PIPE_QUERY_BITS(pending_query_bits) ( \
3559    ((pending_query_bits & ANV_QUERY_WRITES_RT_FLUSH) ?   \
3560     ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT : 0) | \
3561    ((pending_query_bits & ANV_QUERY_WRITES_TILE_FLUSH) ?   \
3562     ANV_PIPE_TILE_CACHE_FLUSH_BIT : 0) | \
3563    ((pending_query_bits & ANV_QUERY_WRITES_CS_STALL) ?   \
3564     ANV_PIPE_CS_STALL_BIT : 0) | \
3565    ((pending_query_bits & ANV_QUERY_WRITES_DATA_FLUSH) ?  \
3566     (ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
3567      ANV_PIPE_HDC_PIPELINE_FLUSH_BIT | \
3568      ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT) : 0))
3569 
3570 #define ANV_PIPE_FLUSH_BITS ( \
3571    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT | \
3572    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
3573    ANV_PIPE_HDC_PIPELINE_FLUSH_BIT | \
3574    ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT | \
3575    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | \
3576    ANV_PIPE_TILE_CACHE_FLUSH_BIT | \
3577    ANV_PIPE_L3_FABRIC_FLUSH_BIT)
3578 
3579 #define ANV_PIPE_BARRIER_FLUSH_BITS ( \
3580    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT | \
3581    ANV_PIPE_DATA_CACHE_FLUSH_BIT | \
3582    ANV_PIPE_HDC_PIPELINE_FLUSH_BIT | \
3583    ANV_PIPE_UNTYPED_DATAPORT_CACHE_FLUSH_BIT | \
3584    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | \
3585    ANV_PIPE_TILE_CACHE_FLUSH_BIT)
3586 
3587 #define ANV_PIPE_STALL_BITS ( \
3588    ANV_PIPE_STALL_AT_SCOREBOARD_BIT | \
3589    ANV_PIPE_DEPTH_STALL_BIT | \
3590    ANV_PIPE_CS_STALL_BIT | \
3591    ANV_PIPE_PSS_STALL_SYNC_BIT)
3592 
3593 #define ANV_PIPE_INVALIDATE_BITS ( \
3594    ANV_PIPE_STATE_CACHE_INVALIDATE_BIT | \
3595    ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT | \
3596    ANV_PIPE_VF_CACHE_INVALIDATE_BIT | \
3597    ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT | \
3598    ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT | \
3599    ANV_PIPE_AUX_TABLE_INVALIDATE_BIT)
3600 
3601 /* PIPE_CONTROL bits that should be set only in 3D RCS mode.
3602  * For more details see genX(emit_apply_pipe_flushes).
3603  */
3604 #define ANV_PIPE_GFX_BITS ( \
3605    ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | \
3606    ANV_PIPE_DEPTH_CACHE_FLUSH_BIT | \
3607    ANV_PIPE_TILE_CACHE_FLUSH_BIT | \
3608    ANV_PIPE_DEPTH_STALL_BIT | \
3609    ANV_PIPE_STALL_AT_SCOREBOARD_BIT | \
3610    (GFX_VERx10 >= 125 ? ANV_PIPE_PSS_STALL_SYNC_BIT : 0) | \
3611    ANV_PIPE_VF_CACHE_INVALIDATE_BIT)
3612 
3613 /* PIPE_CONTROL bits that should be set only in Media/GPGPU RCS mode.
3614  * For more details see genX(emit_apply_pipe_flushes).
3615  *
3616  * Documentation says that untyped L1 dataport cache flush is controlled by
3617  * HDC pipeline flush in 3D mode according to HDC_CHICKEN0 register:
3618  *
3619  * BSpec 47112: PIPE_CONTROL::HDC Pipeline Flush:
3620  *
3621  *    "When the "Pipeline Select" mode in PIPELINE_SELECT command is set to
3622  *     "3D", HDC Pipeline Flush can also flush/invalidate the LSC Untyped L1
3623  *     cache based on the programming of HDC_Chicken0 register bits 13:11."
3624  *
3625  *    "When the 'Pipeline Select' mode is set to 'GPGPU', the LSC Untyped L1
3626  *     cache flush is controlled by 'Untyped Data-Port Cache Flush' bit in the
3627  *     PIPE_CONTROL command."
3628  *
3629  *    As part of Wa_22010960976 & Wa_14013347512, i915 is programming
3630  *    HDC_CHICKEN0[11:13] = 0 ("Untyped L1 is flushed, for both 3D Pipecontrol
3631  *    Dataport flush, and UAV coherency barrier event"). So there is no need
3632  *    to set "Untyped Data-Port Cache" in 3D mode.
3633  *
3634  * On MTL the HDC_CHICKEN0 default values changed to match what was programmed
3635  * by Wa_22010960976 & Wa_14013347512 on DG2, but experiments show that the
3636  * change runs a bit deeper. Even manually writing to the HDC_CHICKEN0
3637  * register to force L1 untyped flush with HDC pipeline flush has no effect on
3638  * MTL.
3639  *
3640  * It seems like the HW change completely disconnected L1 untyped flush from
3641  * HDC pipeline flush with no way to bring that behavior back. So leave the L1
3642  * untyped flush active in 3D mode on all platforms since it doesn't seems to
3643  * cause issues there too.
3644  *
3645  * Maybe we'll have some GPGPU only bits here at some point.
3646  */
3647 #define ANV_PIPE_GPGPU_BITS (0)
3648 
3649 enum intel_ds_stall_flag
3650 anv_pipe_flush_bit_to_ds_stall_flag(enum anv_pipe_bits bits);
3651 
3652 #define VK_IMAGE_ASPECT_PLANES_BITS_ANV ( \
3653    VK_IMAGE_ASPECT_PLANE_0_BIT | \
3654    VK_IMAGE_ASPECT_PLANE_1_BIT | \
3655    VK_IMAGE_ASPECT_PLANE_2_BIT)
3656 
3657 #define VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV (         \
3658    VK_IMAGE_ASPECT_COLOR_BIT | \
3659    VK_IMAGE_ASPECT_PLANES_BITS_ANV)
3660 
3661 struct anv_vertex_binding {
3662    struct anv_buffer *                          buffer;
3663    VkDeviceSize                                 offset;
3664    VkDeviceSize                                 size;
3665 };
3666 
3667 struct anv_xfb_binding {
3668    struct anv_buffer *                          buffer;
3669    VkDeviceSize                                 offset;
3670    VkDeviceSize                                 size;
3671 };
3672 
3673 struct anv_push_constants {
3674    /** Push constant data provided by the client through vkPushConstants */
3675    uint8_t client_data[MAX_PUSH_CONSTANTS_SIZE];
3676 
3677 #define ANV_DESCRIPTOR_SET_DYNAMIC_INDEX_MASK ((uint32_t)ANV_UBO_ALIGNMENT - 1)
3678 #define ANV_DESCRIPTOR_SET_OFFSET_MASK        (~(uint32_t)(ANV_UBO_ALIGNMENT - 1))
3679 
3680    /**
3681     * Base offsets for descriptor sets from
3682     *
3683     * The offset has different meaning depending on a number of factors :
3684     *
3685     *    - with descriptor sets (direct or indirect), this relative
3686     *      pdevice->va.descriptor_pool
3687     *
3688     *    - with descriptor buffers on DG2+, relative
3689     *      device->va.descriptor_buffer_pool
3690     *
3691     *    - with descriptor buffers prior to DG2, relative the programmed value
3692     *      in STATE_BASE_ADDRESS::BindlessSurfaceStateBaseAddress
3693     */
3694    uint32_t desc_surface_offsets[MAX_SETS];
3695 
3696    /**
3697     * Base offsets for descriptor sets from
3698     */
3699    uint32_t desc_sampler_offsets[MAX_SETS];
3700 
3701    /** Dynamic offsets for dynamic UBOs and SSBOs */
3702    uint32_t dynamic_offsets[MAX_DYNAMIC_BUFFERS];
3703 
3704    /** Surface buffer base offset
3705     *
3706     * Only used prior to DG2 with descriptor buffers.
3707     *
3708     * (surfaces_base_offset + desc_offsets[set_index]) is relative to
3709     * device->va.descriptor_buffer_pool and can be used to compute a 64bit
3710     * address to the descriptor buffer (using load_desc_set_address_intel).
3711     */
3712    uint32_t surfaces_base_offset;
3713 
3714    /* Robust access pushed registers. */
3715    uint64_t push_reg_mask[MESA_SHADER_STAGES];
3716 
3717    /** Ray query globals (RT_DISPATCH_GLOBALS) */
3718    uint64_t ray_query_globals;
3719 
3720    union {
3721       struct {
3722          /** Dynamic MSAA value */
3723          uint32_t fs_msaa_flags;
3724 
3725          /** Dynamic TCS input vertices */
3726          uint32_t tcs_input_vertices;
3727       } gfx;
3728 
3729       struct {
3730          /** Base workgroup ID
3731           *
3732           * Used for vkCmdDispatchBase.
3733           */
3734          uint32_t base_work_group_id[3];
3735 
3736          /** gl_NumWorkgroups */
3737          uint32_t num_work_groups[3];
3738 
3739          /** Subgroup ID
3740           *
3741           * This is never set by software but is implicitly filled out when
3742           * uploading the push constants for compute shaders.
3743           *
3744           * This *MUST* be the last field of the anv_push_constants structure.
3745           */
3746          uint32_t subgroup_id;
3747       } cs;
3748    };
3749 };
3750 
3751 struct anv_surface_state {
3752    /** Surface state allocated from the bindless heap
3753     *
3754     * Can be NULL if unused.
3755     */
3756    struct anv_state state;
3757 
3758    /** Surface state after genxml packing
3759     *
3760     * Same data as in state.
3761     */
3762    struct anv_surface_state_data state_data;
3763 
3764    /** Address of the surface referred to by this state
3765     *
3766     * This address is relative to the start of the BO.
3767     */
3768    struct anv_address address;
3769    /* Address of the aux surface, if any
3770     *
3771     * This field is ANV_NULL_ADDRESS if and only if no aux surface exists.
3772     *
3773     * With the exception of gfx8, the bottom 12 bits of this address' offset
3774     * include extra aux information.
3775     */
3776    struct anv_address aux_address;
3777    /* Address of the clear color, if any
3778     *
3779     * This address is relative to the start of the BO.
3780     */
3781    struct anv_address clear_address;
3782 };
3783 
3784 struct anv_attachment {
3785    VkFormat vk_format;
3786    const struct anv_image_view *iview;
3787    VkImageLayout layout;
3788    enum isl_aux_usage aux_usage;
3789    struct anv_surface_state surface_state;
3790 
3791    VkResolveModeFlagBits resolve_mode;
3792    const struct anv_image_view *resolve_iview;
3793    VkImageLayout resolve_layout;
3794 };
3795 
3796 /** State tracking for vertex buffer flushes
3797  *
3798  * On Gfx8-9, the VF cache only considers the bottom 32 bits of memory
3799  * addresses.  If you happen to have two vertex buffers which get placed
3800  * exactly 4 GiB apart and use them in back-to-back draw calls, you can get
3801  * collisions.  In order to solve this problem, we track vertex address ranges
3802  * which are live in the cache and invalidate the cache if one ever exceeds 32
3803  * bits.
3804  */
3805 struct anv_vb_cache_range {
3806    /* Virtual address at which the live vertex buffer cache range starts for
3807     * this vertex buffer index.
3808     */
3809    uint64_t start;
3810 
3811    /* Virtual address of the byte after where vertex buffer cache range ends.
3812     * This is exclusive such that end - start is the size of the range.
3813     */
3814    uint64_t end;
3815 };
3816 
3817 static inline void
anv_merge_vb_cache_range(struct anv_vb_cache_range * dirty,const struct anv_vb_cache_range * bound)3818 anv_merge_vb_cache_range(struct anv_vb_cache_range *dirty,
3819                          const struct anv_vb_cache_range *bound)
3820 {
3821    if (dirty->start == dirty->end) {
3822       *dirty = *bound;
3823    } else if (bound->start != bound->end) {
3824       dirty->start = MIN2(dirty->start, bound->start);
3825       dirty->end = MAX2(dirty->end, bound->end);
3826    }
3827 }
3828 
3829 /* Check whether we need to apply the Gfx8-9 vertex buffer workaround*/
3830 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)3831 anv_gfx8_9_vb_cache_range_needs_workaround(struct anv_vb_cache_range *bound,
3832                                            struct anv_vb_cache_range *dirty,
3833                                            struct anv_address vb_address,
3834                                            uint32_t vb_size)
3835 {
3836    if (vb_size == 0) {
3837       bound->start = 0;
3838       bound->end = 0;
3839       return false;
3840    }
3841 
3842    bound->start = intel_48b_address(anv_address_physical(vb_address));
3843    bound->end = bound->start + vb_size;
3844    assert(bound->end > bound->start); /* No overflow */
3845 
3846    /* Align everything to a cache line */
3847    bound->start &= ~(64ull - 1ull);
3848    bound->end = align64(bound->end, 64);
3849 
3850    anv_merge_vb_cache_range(dirty, bound);
3851 
3852    /* If our range is larger than 32 bits, we have to flush */
3853    assert(bound->end - bound->start <= (1ull << 32));
3854    return (dirty->end - dirty->start) > (1ull << 32);
3855 }
3856 
3857 /**
3858  * State tracking for simple internal shaders
3859  */
3860 struct anv_simple_shader {
3861    /* The device associated with this emission */
3862    struct anv_device *device;
3863    /* The command buffer associated with this emission (can be NULL) */
3864    struct anv_cmd_buffer *cmd_buffer;
3865    /* State stream used for various internal allocations */
3866    struct anv_state_stream *dynamic_state_stream;
3867    struct anv_state_stream *general_state_stream;
3868    /* Where to emit the commands (can be different from cmd_buffer->batch) */
3869    struct anv_batch *batch;
3870    /* Shader to use */
3871    struct anv_shader_bin *kernel;
3872    /* L3 config used by the shader */
3873    const struct intel_l3_config *l3_config;
3874    /* Current URB config */
3875    const struct intel_urb_config *urb_cfg;
3876 
3877    /* Managed by the simpler shader helper*/
3878    struct anv_state bt_state;
3879 };
3880 
3881 /** State tracking for particular pipeline bind point
3882  *
3883  * This struct is the base struct for anv_cmd_graphics_state and
3884  * anv_cmd_compute_state.  These are used to track state which is bound to a
3885  * particular type of pipeline.  Generic state that applies per-stage such as
3886  * binding table offsets and push constants is tracked generically with a
3887  * per-stage array in anv_cmd_state.
3888  */
3889 struct anv_cmd_pipeline_state {
3890    struct anv_descriptor_set *descriptors[MAX_SETS];
3891    struct {
3892       bool             bound;
3893       /**
3894        * Buffer index used by this descriptor set.
3895        */
3896       int32_t          buffer_index; /* -1 means push descriptor */
3897       /**
3898        * Offset of the descriptor set in the descriptor buffer.
3899        */
3900       uint32_t         buffer_offset;
3901       /**
3902        * Final computed address to be emitted in the descriptor set surface
3903        * state.
3904        */
3905       uint64_t         address;
3906       /**
3907        * The descriptor set surface state.
3908        */
3909       struct anv_state state;
3910    } descriptor_buffers[MAX_SETS];
3911    struct anv_push_descriptor_set push_descriptor;
3912 
3913    struct anv_push_constants push_constants;
3914 
3915    /** Amount of data written to anv_push_constants::client_data */
3916    uint16_t push_constants_client_size;
3917 
3918    /** Tracks whether the push constant data has changed and need to be reemitted */
3919    bool                                         push_constants_data_dirty;
3920 
3921    /* Push constant state allocated when flushing push constants. */
3922    struct anv_state          push_constants_state;
3923 
3924    /**
3925     * Dynamic buffer offsets.
3926     *
3927     * We have a maximum of MAX_DYNAMIC_BUFFERS per pipeline, but with
3928     * independent sets we cannot know which how much in total is going to be
3929     * used. As a result we need to store the maximum possible number per set.
3930     *
3931     * Those values are written into anv_push_constants::dynamic_offsets at
3932     * flush time when have the pipeline with the final
3933     * anv_pipeline_sets_layout.
3934     */
3935    struct {
3936       uint32_t                                  offsets[MAX_DYNAMIC_BUFFERS];
3937    }                                            dynamic_offsets[MAX_SETS];
3938 
3939    /**
3940     * The current bound pipeline.
3941     */
3942    struct anv_pipeline      *pipeline;
3943 };
3944 
3945 enum anv_depth_reg_mode {
3946    ANV_DEPTH_REG_MODE_UNKNOWN = 0,
3947    ANV_DEPTH_REG_MODE_HW_DEFAULT,
3948    ANV_DEPTH_REG_MODE_D16_1X_MSAA,
3949 };
3950 
3951 /** State tracking for graphics pipeline
3952  *
3953  * This has anv_cmd_pipeline_state as a base struct to track things which get
3954  * bound to a graphics pipeline.  Along with general pipeline bind point state
3955  * which is in the anv_cmd_pipeline_state base struct, it also contains other
3956  * state which is graphics-specific.
3957  */
3958 struct anv_cmd_graphics_state {
3959    struct anv_cmd_pipeline_state base;
3960 
3961    VkRenderingFlags rendering_flags;
3962    VkRect2D render_area;
3963    uint32_t layer_count;
3964    uint32_t samples;
3965    uint32_t view_mask;
3966    uint32_t color_att_count;
3967    struct anv_state att_states;
3968    struct anv_attachment color_att[MAX_RTS];
3969    struct anv_attachment depth_att;
3970    struct anv_attachment stencil_att;
3971    struct anv_state null_surface_state;
3972 
3973    /* Map of color output from the last dispatched fragment shader to color
3974     * attachments in the render pass.
3975     */
3976    uint8_t color_output_mapping[MAX_RTS];
3977 
3978    anv_cmd_dirty_mask_t dirty;
3979    uint32_t vb_dirty;
3980 
3981    struct anv_vb_cache_range ib_bound_range;
3982    struct anv_vb_cache_range ib_dirty_range;
3983    struct anv_vb_cache_range vb_bound_ranges[33];
3984    struct anv_vb_cache_range vb_dirty_ranges[33];
3985 
3986    uint32_t restart_index;
3987 
3988    VkShaderStageFlags push_constant_stages;
3989 
3990    bool used_task_shader;
3991 
3992    struct anv_buffer *index_buffer;
3993    uint32_t index_type; /**< 3DSTATE_INDEX_BUFFER.IndexFormat */
3994    uint32_t index_offset;
3995    uint32_t index_size;
3996 
3997    uint32_t indirect_data_stride;
3998    bool indirect_data_stride_aligned;
3999 
4000    struct vk_vertex_input_state vertex_input;
4001    struct vk_sample_locations_state sample_locations;
4002 
4003    bool object_preemption;
4004    bool has_uint_rt;
4005 
4006    /* State tracking for Wa_14018912822. */
4007    bool color_blend_zero;
4008    bool alpha_blend_zero;
4009 
4010    /**
4011     * State tracking for Wa_18020335297.
4012     */
4013    bool                                         viewport_set;
4014 
4015    struct intel_urb_config urb_cfg;
4016 
4017    uint32_t n_occlusion_queries;
4018 
4019    /**
4020     * Whether or not the gfx8 PMA fix is enabled.  We ensure that, at the top
4021     * of any command buffer it is disabled by disabling it in EndCommandBuffer
4022     * and before invoking the secondary in ExecuteCommands.
4023     */
4024    bool                                         pma_fix_enabled;
4025 
4026    /**
4027     * Whether or not we know for certain that HiZ is enabled for the current
4028     * subpass.  If, for whatever reason, we are unsure as to whether HiZ is
4029     * enabled or not, this will be false.
4030     */
4031    bool                                         hiz_enabled;
4032 
4033    /**
4034     * We ensure the registers for the gfx12 D16 fix are initialized at the
4035     * first non-NULL depth stencil packet emission of every command buffer.
4036     * For secondary command buffer execution, we transfer the state from the
4037     * last command buffer to the primary (if known).
4038     */
4039    enum anv_depth_reg_mode                      depth_reg_mode;
4040 
4041    struct anv_gfx_dynamic_state dyn_state;
4042 };
4043 
4044 /** State tracking for compute pipeline
4045  *
4046  * This has anv_cmd_pipeline_state as a base struct to track things which get
4047  * bound to a compute pipeline.  Along with general pipeline bind point state
4048  * which is in the anv_cmd_pipeline_state base struct, it also contains other
4049  * state which is compute-specific.
4050  */
4051 struct anv_cmd_compute_state {
4052    struct anv_cmd_pipeline_state base;
4053 
4054    bool pipeline_dirty;
4055 
4056    uint32_t scratch_size;
4057 };
4058 
4059 struct anv_cmd_ray_tracing_state {
4060    struct anv_cmd_pipeline_state base;
4061 
4062    bool pipeline_dirty;
4063 
4064    struct {
4065       struct anv_bo *bo;
4066       struct brw_rt_scratch_layout layout;
4067    } scratch;
4068 
4069    uint32_t debug_marker_count;
4070    enum vk_acceleration_structure_build_step debug_markers[5];
4071 
4072    struct anv_address build_priv_mem_addr;
4073    size_t             build_priv_mem_size;
4074 };
4075 
4076 enum anv_cmd_descriptor_buffer_mode {
4077    ANV_CMD_DESCRIPTOR_BUFFER_MODE_UNKNOWN,
4078    ANV_CMD_DESCRIPTOR_BUFFER_MODE_LEGACY,
4079    ANV_CMD_DESCRIPTOR_BUFFER_MODE_BUFFER,
4080 };
4081 
4082 /** State required while building cmd buffer */
4083 struct anv_cmd_state {
4084    /* PIPELINE_SELECT.PipelineSelection */
4085    uint32_t                                     current_pipeline;
4086    const struct intel_l3_config *               current_l3_config;
4087    uint32_t                                     last_aux_map_state;
4088 
4089    struct anv_cmd_graphics_state                gfx;
4090    struct anv_cmd_compute_state                 compute;
4091    struct anv_cmd_ray_tracing_state             rt;
4092 
4093    enum anv_pipe_bits                           pending_pipe_bits;
4094 
4095    /**
4096     * Whether the last programmed STATE_BASE_ADDRESS references
4097     * anv_device::dynamic_state_pool or anv_device::dynamic_state_pool_db for
4098     * the dynamic state heap.
4099     */
4100    enum anv_cmd_descriptor_buffer_mode          current_db_mode;
4101 
4102    /**
4103     * Whether the command buffer has pending descriptor buffers bound it. This
4104     * variable changes before anv_device::current_db_mode.
4105     */
4106    enum anv_cmd_descriptor_buffer_mode          pending_db_mode;
4107 
4108    struct {
4109       /**
4110        * Tracks operations susceptible to interfere with queries in the
4111        * destination buffer of vkCmdCopyQueryResults, we need those operations to
4112        * have completed before we do the work of vkCmdCopyQueryResults.
4113        */
4114       enum anv_query_bits                          buffer_write_bits;
4115 
4116       /**
4117        * Tracks clear operations of query buffers that can interact with
4118        * vkCmdQueryBegin*, vkCmdWriteTimestamp*,
4119        * vkCmdWriteAccelerationStructuresPropertiesKHR, etc...
4120        *
4121        * We need the clearing of the buffer completed before with write data with
4122        * the command streamer or a shader.
4123        */
4124       enum anv_query_bits                          clear_bits;
4125    } queries;
4126 
4127    VkShaderStageFlags                           descriptors_dirty;
4128    VkShaderStageFlags                           push_descriptors_dirty;
4129    /** Tracks the 3DSTATE_CONSTANT_* instruction that needs to be reemitted */
4130    VkShaderStageFlags                           push_constants_dirty;
4131 
4132    struct {
4133       uint64_t                                  surfaces_address;
4134       uint64_t                                  samplers_address;
4135       bool                                      dirty;
4136       VkShaderStageFlags                        offsets_dirty;
4137       uint64_t                                  address[MAX_SETS];
4138    }                                            descriptor_buffers;
4139 
4140    struct anv_vertex_binding                    vertex_bindings[MAX_VBS];
4141    bool                                         xfb_enabled;
4142    struct anv_xfb_binding                       xfb_bindings[MAX_XFB_BUFFERS];
4143    struct anv_state                             binding_tables[MESA_VULKAN_SHADER_STAGES];
4144    struct anv_state                             samplers[MESA_VULKAN_SHADER_STAGES];
4145 
4146    unsigned char                                sampler_sha1s[MESA_VULKAN_SHADER_STAGES][20];
4147    unsigned char                                surface_sha1s[MESA_VULKAN_SHADER_STAGES][20];
4148    unsigned char                                push_sha1s[MESA_VULKAN_SHADER_STAGES][20];
4149 
4150    /* The last auxiliary surface operation (or equivalent operation) provided
4151     * to genX(cmd_buffer_update_color_aux_op).
4152     */
4153    enum isl_aux_op                              color_aux_op;
4154 
4155    /**
4156     * Whether RHWO optimization is enabled (Wa_1508744258).
4157     */
4158    bool                                         rhwo_optimization_enabled;
4159 
4160    /**
4161     * Pending state of the RHWO optimization, to be applied at the next
4162     * genX(cmd_buffer_apply_pipe_flushes).
4163     */
4164    bool                                         pending_rhwo_optimization_enabled;
4165 
4166    bool                                         conditional_render_enabled;
4167 
4168    /**
4169     * Last rendering scale argument provided to
4170     * genX(cmd_buffer_emit_hashing_mode)().
4171     */
4172    unsigned                                     current_hash_scale;
4173 
4174    /**
4175     * A buffer used for spill/fill of ray queries.
4176     */
4177    struct anv_bo *                              ray_query_shadow_bo;
4178 
4179    /** Pointer to the last emitted COMPUTE_WALKER.
4180     *
4181     * This is used to edit the instruction post emission to replace the "Post
4182     * Sync" field for utrace timestamp emission.
4183     */
4184    void                                        *last_compute_walker;
4185 
4186    /** Pointer to the last emitted EXECUTE_INDIRECT_DISPATCH.
4187     *
4188     * This is used to edit the instruction post emission to replace the "Post
4189     * Sync" field for utrace timestamp emission.
4190     */
4191    void                                        *last_indirect_dispatch;
4192 };
4193 
4194 #define ANV_MIN_CMD_BUFFER_BATCH_SIZE 8192
4195 #define ANV_MAX_CMD_BUFFER_BATCH_SIZE (16 * 1024 * 1024)
4196 
4197 enum anv_cmd_buffer_exec_mode {
4198    ANV_CMD_BUFFER_EXEC_MODE_PRIMARY,
4199    ANV_CMD_BUFFER_EXEC_MODE_EMIT,
4200    ANV_CMD_BUFFER_EXEC_MODE_GROW_AND_EMIT,
4201    ANV_CMD_BUFFER_EXEC_MODE_CHAIN,
4202    ANV_CMD_BUFFER_EXEC_MODE_COPY_AND_CHAIN,
4203    ANV_CMD_BUFFER_EXEC_MODE_CALL_AND_RETURN,
4204 };
4205 
4206 struct anv_measure_batch;
4207 
4208 struct anv_cmd_buffer {
4209    struct vk_command_buffer                     vk;
4210 
4211    struct anv_device *                          device;
4212    struct anv_queue_family *                    queue_family;
4213 
4214    /** Batch where the main commands live */
4215    struct anv_batch                             batch;
4216 
4217    /* Pointer to the location in the batch where MI_BATCH_BUFFER_END was
4218     * recorded upon calling vkEndCommandBuffer(). This is useful if we need to
4219     * rewrite the end to chain multiple batch together at vkQueueSubmit().
4220     */
4221    void *                                       batch_end;
4222 
4223    /* Fields required for the actual chain of anv_batch_bo's.
4224     *
4225     * These fields are initialized by anv_cmd_buffer_init_batch_bo_chain().
4226     */
4227    struct list_head                             batch_bos;
4228    enum anv_cmd_buffer_exec_mode                exec_mode;
4229 
4230    /* A vector of anv_batch_bo pointers for every batch or surface buffer
4231     * referenced by this command buffer
4232     *
4233     * initialized by anv_cmd_buffer_init_batch_bo_chain()
4234     */
4235    struct u_vector                            seen_bbos;
4236 
4237    /* A vector of int32_t's for every block of binding tables.
4238     *
4239     * initialized by anv_cmd_buffer_init_batch_bo_chain()
4240     */
4241    struct u_vector                              bt_block_states;
4242    struct anv_state                             bt_next;
4243 
4244    struct anv_reloc_list                        surface_relocs;
4245 
4246    /* Serial for tracking buffer completion */
4247    uint32_t                                     serial;
4248 
4249    /* Stream objects for storing temporary data */
4250    struct anv_state_stream                      surface_state_stream;
4251    struct anv_state_stream                      dynamic_state_stream;
4252    struct anv_state_stream                      general_state_stream;
4253    struct anv_state_stream                      indirect_push_descriptor_stream;
4254    struct anv_state_stream                      push_descriptor_buffer_stream;
4255 
4256    VkCommandBufferUsageFlags                    usage_flags;
4257 
4258    struct anv_query_pool                       *perf_query_pool;
4259 
4260    struct anv_cmd_state                         state;
4261 
4262    /* Fast-clear statistics. */
4263    uint64_t                                     num_dependent_clears;
4264    uint64_t                                     num_independent_clears;
4265 
4266    struct anv_address                           return_addr;
4267 
4268    /* Set by SetPerformanceMarkerINTEL, written into queries by CmdBeginQuery */
4269    uint64_t                                     intel_perf_marker;
4270 
4271    struct anv_measure_batch *measure;
4272 
4273    /**
4274     * KHR_performance_query requires self modifying command buffers and this
4275     * array has the location of modifying commands to the query begin and end
4276     * instructions storing performance counters. The array length is
4277     * anv_physical_device::n_perf_query_commands.
4278     */
4279    struct mi_address_token                  *self_mod_locations;
4280 
4281    /**
4282     * Index tracking which of the self_mod_locations items have already been
4283     * used.
4284     */
4285    uint32_t                                      perf_reloc_idx;
4286 
4287    /**
4288     * Sum of all the anv_batch_bo written sizes for this command buffer
4289     * including any executed secondary command buffer.
4290     */
4291    uint32_t                                     total_batch_size;
4292 
4293    struct {
4294       /** Batch generating part of the anv_cmd_buffer::batch */
4295       struct anv_batch                          batch;
4296 
4297       /**
4298        * Location in anv_cmd_buffer::batch at which we left some space to
4299        * insert a MI_BATCH_BUFFER_START into the
4300        * anv_cmd_buffer::generation::batch if needed.
4301        */
4302       struct anv_address                        jump_addr;
4303 
4304       /**
4305        * Location in anv_cmd_buffer::batch at which the generation batch
4306        * should jump back to.
4307        */
4308       struct anv_address                        return_addr;
4309 
4310       /** List of anv_batch_bo used for generation
4311        *
4312        * We have to keep this separated of the anv_cmd_buffer::batch_bos that
4313        * is used for a chaining optimization.
4314        */
4315       struct list_head                          batch_bos;
4316 
4317       /** Ring buffer of generated commands
4318        *
4319        * When generating draws in ring mode, this buffer will hold generated
4320        * 3DPRIMITIVE commands.
4321        */
4322       struct anv_bo                            *ring_bo;
4323 
4324       /**
4325        * State tracking of the generation shader (only used for the non-ring
4326        * mode).
4327        */
4328       struct anv_simple_shader                  shader_state;
4329    } generation;
4330 
4331    /**
4332     * A vector of anv_bo pointers for chunks of memory used by the command
4333     * buffer that are too large to be allocated through dynamic_state_stream.
4334     * This is the case for large enough acceleration structures.
4335     *
4336     * initialized by anv_cmd_buffer_init_batch_bo_chain()
4337     */
4338    struct u_vector                              dynamic_bos;
4339 
4340    /**
4341     * Structure holding tracepoints recorded in the command buffer.
4342     */
4343    struct u_trace                               trace;
4344 
4345    struct {
4346       struct anv_video_session *vid;
4347       struct anv_video_session_params *params;
4348    } video;
4349 
4350    /**
4351     * Companion RCS command buffer to support the MSAA operations on compute
4352     * queue.
4353     */
4354    struct anv_cmd_buffer                        *companion_rcs_cmd_buffer;
4355 
4356    /**
4357     * Whether this command buffer is a companion command buffer of compute one.
4358     */
4359    bool                                         is_companion_rcs_cmd_buffer;
4360 
4361 };
4362 
4363 extern const struct vk_command_buffer_ops anv_cmd_buffer_ops;
4364 
4365 /* Determine whether we can chain a given cmd_buffer to another one. We need
4366  * to make sure that we can edit the end of the batch to point to next one,
4367  * which requires the command buffer to not be used simultaneously.
4368  *
4369  * We could in theory also implement chaining with companion command buffers,
4370  * but let's sparse ourselves some pain and misery. This optimization has no
4371  * benefit on the brand new Xe kernel driver.
4372  */
4373 static inline bool
anv_cmd_buffer_is_chainable(struct anv_cmd_buffer * cmd_buffer)4374 anv_cmd_buffer_is_chainable(struct anv_cmd_buffer *cmd_buffer)
4375 {
4376    return !(cmd_buffer->usage_flags &
4377             VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) &&
4378           !(cmd_buffer->is_companion_rcs_cmd_buffer);
4379 }
4380 
4381 static inline bool
anv_cmd_buffer_is_render_queue(const struct anv_cmd_buffer * cmd_buffer)4382 anv_cmd_buffer_is_render_queue(const struct anv_cmd_buffer *cmd_buffer)
4383 {
4384    struct anv_queue_family *queue_family = cmd_buffer->queue_family;
4385    return (queue_family->queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0;
4386 }
4387 
4388 static inline bool
anv_cmd_buffer_is_video_queue(const struct anv_cmd_buffer * cmd_buffer)4389 anv_cmd_buffer_is_video_queue(const struct anv_cmd_buffer *cmd_buffer)
4390 {
4391    struct anv_queue_family *queue_family = cmd_buffer->queue_family;
4392    return ((queue_family->queueFlags & VK_QUEUE_VIDEO_DECODE_BIT_KHR) |
4393            (queue_family->queueFlags & VK_QUEUE_VIDEO_ENCODE_BIT_KHR)) != 0;
4394 }
4395 
4396 static inline bool
anv_cmd_buffer_is_compute_queue(const struct anv_cmd_buffer * cmd_buffer)4397 anv_cmd_buffer_is_compute_queue(const struct anv_cmd_buffer *cmd_buffer)
4398 {
4399    struct anv_queue_family *queue_family = cmd_buffer->queue_family;
4400    return queue_family->engine_class == INTEL_ENGINE_CLASS_COMPUTE;
4401 }
4402 
4403 static inline bool
anv_cmd_buffer_is_blitter_queue(const struct anv_cmd_buffer * cmd_buffer)4404 anv_cmd_buffer_is_blitter_queue(const struct anv_cmd_buffer *cmd_buffer)
4405 {
4406    struct anv_queue_family *queue_family = cmd_buffer->queue_family;
4407    return queue_family->engine_class == INTEL_ENGINE_CLASS_COPY;
4408 }
4409 
4410 static inline bool
anv_cmd_buffer_is_render_or_compute_queue(const struct anv_cmd_buffer * cmd_buffer)4411 anv_cmd_buffer_is_render_or_compute_queue(const struct anv_cmd_buffer *cmd_buffer)
4412 {
4413    return anv_cmd_buffer_is_render_queue(cmd_buffer) ||
4414           anv_cmd_buffer_is_compute_queue(cmd_buffer);
4415 }
4416 
4417 static inline uint8_t
anv_get_ray_query_bo_index(struct anv_cmd_buffer * cmd_buffer)4418 anv_get_ray_query_bo_index(struct anv_cmd_buffer *cmd_buffer)
4419 {
4420    if (intel_needs_workaround(cmd_buffer->device->isl_dev.info, 14022863161))
4421       return anv_cmd_buffer_is_compute_queue(cmd_buffer) ? 1 : 0;
4422    return 0;
4423 }
4424 
4425 static inline struct anv_address
anv_cmd_buffer_dynamic_state_address(struct anv_cmd_buffer * cmd_buffer,struct anv_state state)4426 anv_cmd_buffer_dynamic_state_address(struct anv_cmd_buffer *cmd_buffer,
4427                                      struct anv_state state)
4428 {
4429    return anv_state_pool_state_address(
4430       &cmd_buffer->device->dynamic_state_pool, state);
4431 }
4432 
4433 static inline uint64_t
anv_cmd_buffer_descriptor_buffer_address(struct anv_cmd_buffer * cmd_buffer,int32_t buffer_index)4434 anv_cmd_buffer_descriptor_buffer_address(struct anv_cmd_buffer *cmd_buffer,
4435                                          int32_t buffer_index)
4436 {
4437    if (buffer_index == -1)
4438       return cmd_buffer->device->physical->va.push_descriptor_buffer_pool.addr;
4439 
4440    return cmd_buffer->state.descriptor_buffers.address[buffer_index];
4441 }
4442 
4443 VkResult anv_cmd_buffer_init_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
4444 void anv_cmd_buffer_fini_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
4445 void anv_cmd_buffer_reset_batch_bo_chain(struct anv_cmd_buffer *cmd_buffer);
4446 void anv_cmd_buffer_end_batch_buffer(struct anv_cmd_buffer *cmd_buffer);
4447 void anv_cmd_buffer_add_secondary(struct anv_cmd_buffer *primary,
4448                                   struct anv_cmd_buffer *secondary);
4449 void anv_cmd_buffer_prepare_execbuf(struct anv_cmd_buffer *cmd_buffer);
4450 VkResult anv_cmd_buffer_execbuf(struct anv_queue *queue,
4451                                 struct anv_cmd_buffer *cmd_buffer,
4452                                 const VkSemaphore *in_semaphores,
4453                                 const uint64_t *in_wait_values,
4454                                 uint32_t num_in_semaphores,
4455                                 const VkSemaphore *out_semaphores,
4456                                 const uint64_t *out_signal_values,
4457                                 uint32_t num_out_semaphores,
4458                                 VkFence fence,
4459                                 int perf_query_pass);
4460 
4461 void anv_cmd_buffer_reset(struct vk_command_buffer *vk_cmd_buffer,
4462                           UNUSED VkCommandBufferResetFlags flags);
4463 
4464 struct anv_state anv_cmd_buffer_emit_dynamic(struct anv_cmd_buffer *cmd_buffer,
4465                                              const void *data, uint32_t size, uint32_t alignment);
4466 struct anv_state anv_cmd_buffer_merge_dynamic(struct anv_cmd_buffer *cmd_buffer,
4467                                               uint32_t *a, uint32_t *b,
4468                                               uint32_t dwords, uint32_t alignment);
4469 
4470 struct anv_address
4471 anv_cmd_buffer_surface_base_address(struct anv_cmd_buffer *cmd_buffer);
4472 struct anv_state
4473 anv_cmd_buffer_alloc_binding_table(struct anv_cmd_buffer *cmd_buffer,
4474                                    uint32_t entries, uint32_t *state_offset);
4475 struct anv_state
4476 anv_cmd_buffer_alloc_surface_states(struct anv_cmd_buffer *cmd_buffer,
4477                                     uint32_t count);
4478 struct anv_state
4479 anv_cmd_buffer_alloc_dynamic_state(struct anv_cmd_buffer *cmd_buffer,
4480                                    uint32_t size, uint32_t alignment);
4481 struct anv_state
4482 anv_cmd_buffer_alloc_general_state(struct anv_cmd_buffer *cmd_buffer,
4483                                    uint32_t size, uint32_t alignment);
4484 static inline struct anv_state
anv_cmd_buffer_alloc_temporary_state(struct anv_cmd_buffer * cmd_buffer,uint32_t size,uint32_t alignment)4485 anv_cmd_buffer_alloc_temporary_state(struct anv_cmd_buffer *cmd_buffer,
4486                                      uint32_t size, uint32_t alignment)
4487 {
4488    struct anv_state state =
4489       anv_state_stream_alloc(&cmd_buffer->dynamic_state_stream,
4490                              size, alignment);
4491    if (state.map == NULL)
4492       anv_batch_set_error(&cmd_buffer->batch, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4493    return state;
4494 }
4495 static inline struct anv_address
anv_cmd_buffer_temporary_state_address(struct anv_cmd_buffer * cmd_buffer,struct anv_state state)4496 anv_cmd_buffer_temporary_state_address(struct anv_cmd_buffer *cmd_buffer,
4497                                        struct anv_state state)
4498 {
4499    return anv_state_pool_state_address(
4500       &cmd_buffer->device->dynamic_state_pool, state);
4501 }
4502 
4503 void
4504 anv_cmd_buffer_chain_command_buffers(struct anv_cmd_buffer **cmd_buffers,
4505                                      uint32_t num_cmd_buffers);
4506 void
4507 anv_cmd_buffer_exec_batch_debug(struct anv_queue *queue,
4508                                 uint32_t cmd_buffer_count,
4509                                 struct anv_cmd_buffer **cmd_buffers,
4510                                 struct anv_query_pool *perf_query_pool,
4511                                 uint32_t perf_query_pass);
4512 void
4513 anv_cmd_buffer_clflush(struct anv_cmd_buffer **cmd_buffers,
4514                        uint32_t num_cmd_buffers);
4515 
4516 void
4517 anv_cmd_buffer_update_pending_query_bits(struct anv_cmd_buffer *cmd_buffer,
4518                                          enum anv_pipe_bits flushed_bits);
4519 
4520 /**
4521  * A allocation tied to a command buffer.
4522  *
4523  * Don't use anv_cmd_alloc::address::map to write memory from userspace, use
4524  * anv_cmd_alloc::map instead.
4525  */
4526 struct anv_cmd_alloc {
4527    struct anv_address  address;
4528    void               *map;
4529    size_t              size;
4530 };
4531 
4532 #define ANV_EMPTY_ALLOC ((struct anv_cmd_alloc) { .map = NULL, .size = 0 })
4533 
4534 static inline bool
anv_cmd_alloc_is_empty(struct anv_cmd_alloc alloc)4535 anv_cmd_alloc_is_empty(struct anv_cmd_alloc alloc)
4536 {
4537    return alloc.size == 0;
4538 }
4539 
4540 struct anv_cmd_alloc
4541 anv_cmd_buffer_alloc_space(struct anv_cmd_buffer *cmd_buffer,
4542                            size_t size, uint32_t alignment,
4543                            bool private);
4544 
4545 VkResult
4546 anv_cmd_buffer_new_binding_table_block(struct anv_cmd_buffer *cmd_buffer);
4547 
4548 void anv_cmd_buffer_emit_bt_pool_base_address(struct anv_cmd_buffer *cmd_buffer);
4549 
4550 struct anv_state
4551 anv_cmd_buffer_gfx_push_constants(struct anv_cmd_buffer *cmd_buffer);
4552 struct anv_state
4553 anv_cmd_buffer_cs_push_constants(struct anv_cmd_buffer *cmd_buffer);
4554 
4555 VkResult
4556 anv_cmd_buffer_alloc_blorp_binding_table(struct anv_cmd_buffer *cmd_buffer,
4557                                          uint32_t num_entries,
4558                                          uint32_t *state_offset,
4559                                          struct anv_state *bt_state);
4560 
4561 void anv_cmd_emit_conditional_render_predicate(struct anv_cmd_buffer *cmd_buffer);
4562 
4563 static inline unsigned
anv_cmd_buffer_get_view_count(struct anv_cmd_buffer * cmd_buffer)4564 anv_cmd_buffer_get_view_count(struct anv_cmd_buffer *cmd_buffer)
4565 {
4566    struct anv_cmd_graphics_state *gfx = &cmd_buffer->state.gfx;
4567    return MAX2(1, util_bitcount(gfx->view_mask));
4568 }
4569 
4570 /* Save/restore cmd buffer states for meta operations */
4571 enum anv_cmd_saved_state_flags {
4572    ANV_CMD_SAVED_STATE_COMPUTE_PIPELINE         = BITFIELD_BIT(0),
4573    ANV_CMD_SAVED_STATE_DESCRIPTOR_SET_0         = BITFIELD_BIT(1),
4574    ANV_CMD_SAVED_STATE_DESCRIPTOR_SET_ALL       = BITFIELD_BIT(2),
4575    ANV_CMD_SAVED_STATE_PUSH_CONSTANTS           = BITFIELD_BIT(3),
4576 };
4577 
4578 struct anv_cmd_saved_state {
4579    uint32_t flags;
4580 
4581    struct anv_pipeline *pipeline;
4582    struct anv_descriptor_set *descriptor_set[MAX_SETS];
4583    uint8_t push_constants[MAX_PUSH_CONSTANTS_SIZE];
4584 };
4585 
4586 void anv_cmd_buffer_save_state(struct anv_cmd_buffer *cmd_buffer,
4587                                uint32_t flags,
4588                                struct anv_cmd_saved_state *state);
4589 
4590 void anv_cmd_buffer_restore_state(struct anv_cmd_buffer *cmd_buffer,
4591                                   struct anv_cmd_saved_state *state);
4592 
4593 enum anv_bo_sync_state {
4594    /** Indicates that this is a new (or newly reset fence) */
4595    ANV_BO_SYNC_STATE_RESET,
4596 
4597    /** Indicates that this fence has been submitted to the GPU but is still
4598     * (as far as we know) in use by the GPU.
4599     */
4600    ANV_BO_SYNC_STATE_SUBMITTED,
4601 
4602    ANV_BO_SYNC_STATE_SIGNALED,
4603 };
4604 
4605 struct anv_bo_sync {
4606    struct vk_sync sync;
4607 
4608    enum anv_bo_sync_state state;
4609    struct anv_bo *bo;
4610 };
4611 
4612 extern const struct vk_sync_type anv_bo_sync_type;
4613 
4614 static inline bool
vk_sync_is_anv_bo_sync(const struct vk_sync * sync)4615 vk_sync_is_anv_bo_sync(const struct vk_sync *sync)
4616 {
4617    return sync->type == &anv_bo_sync_type;
4618 }
4619 
4620 VkResult anv_create_sync_for_memory(struct vk_device *device,
4621                                     VkDeviceMemory memory,
4622                                     bool signal_memory,
4623                                     struct vk_sync **sync_out);
4624 
4625 struct anv_event {
4626    struct vk_object_base                        base;
4627    uint64_t                                     semaphore;
4628    struct anv_state                             state;
4629 };
4630 
4631 #define ANV_STAGE_MASK ((1 << MESA_VULKAN_SHADER_STAGES) - 1)
4632 
4633 #define anv_foreach_stage(stage, stage_bits)                         \
4634    for (gl_shader_stage stage,                                       \
4635         __tmp = (gl_shader_stage)((stage_bits) & ANV_STAGE_MASK);    \
4636         stage = __builtin_ffs(__tmp) - 1, __tmp;                     \
4637         __tmp &= ~(1 << (stage)))
4638 
4639 struct anv_pipeline_bind_map {
4640    unsigned char                                surface_sha1[20];
4641    unsigned char                                sampler_sha1[20];
4642    unsigned char                                push_sha1[20];
4643 
4644    uint32_t surface_count;
4645    uint32_t sampler_count;
4646    uint32_t embedded_sampler_count;
4647    uint16_t kernel_args_size;
4648    uint16_t kernel_arg_count;
4649 
4650    struct anv_pipeline_binding *                surface_to_descriptor;
4651    struct anv_pipeline_binding *                sampler_to_descriptor;
4652    struct anv_pipeline_embedded_sampler_binding* embedded_sampler_to_binding;
4653    struct brw_kernel_arg_desc *                 kernel_args;
4654 
4655    struct anv_push_range                        push_ranges[4];
4656 };
4657 
4658 struct anv_push_descriptor_info {
4659    /* A bitfield of descriptors used. */
4660    uint32_t used_descriptors;
4661 
4662    /* A bitfield of UBOs bindings fully promoted to push constants. */
4663    uint32_t fully_promoted_ubo_descriptors;
4664 
4665    /* */
4666    uint8_t used_set_buffer;
4667 };
4668 
4669 /* A list of values we push to implement some of the dynamic states */
4670 enum anv_dynamic_push_bits {
4671    ANV_DYNAMIC_PUSH_INPUT_VERTICES = BITFIELD_BIT(0),
4672 };
4673 
4674 struct anv_shader_upload_params {
4675    gl_shader_stage stage;
4676 
4677    const void *key_data;
4678    uint32_t key_size;
4679 
4680    const void *kernel_data;
4681    uint32_t kernel_size;
4682 
4683    const struct brw_stage_prog_data *prog_data;
4684    uint32_t prog_data_size;
4685 
4686    const struct brw_compile_stats *stats;
4687    uint32_t num_stats;
4688 
4689    const struct nir_xfb_info *xfb_info;
4690 
4691    const struct anv_pipeline_bind_map *bind_map;
4692 
4693    const struct anv_push_descriptor_info *push_desc_info;
4694 
4695    enum anv_dynamic_push_bits dynamic_push_values;
4696 };
4697 
4698 struct anv_embedded_sampler {
4699    uint32_t ref_cnt;
4700 
4701    struct anv_embedded_sampler_key key;
4702 
4703    struct anv_state sampler_state;
4704    struct anv_state border_color_state;
4705 };
4706 
4707 struct anv_shader_bin {
4708    struct vk_pipeline_cache_object base;
4709 
4710    gl_shader_stage stage;
4711 
4712    struct anv_state kernel;
4713    uint32_t kernel_size;
4714 
4715    const struct brw_stage_prog_data *prog_data;
4716    uint32_t prog_data_size;
4717 
4718    struct brw_compile_stats stats[3];
4719    uint32_t num_stats;
4720 
4721    struct nir_xfb_info *xfb_info;
4722 
4723    struct anv_push_descriptor_info push_desc_info;
4724 
4725    struct anv_pipeline_bind_map bind_map;
4726 
4727    enum anv_dynamic_push_bits dynamic_push_values;
4728 
4729    /* Not saved in the pipeline cache.
4730     *
4731     * Array of pointers of length bind_map.embedded_sampler_count
4732     */
4733    struct anv_embedded_sampler **embedded_samplers;
4734 };
4735 
4736 static inline struct anv_shader_bin *
anv_shader_bin_ref(struct anv_shader_bin * shader)4737 anv_shader_bin_ref(struct anv_shader_bin *shader)
4738 {
4739    vk_pipeline_cache_object_ref(&shader->base);
4740 
4741    return shader;
4742 }
4743 
4744 static inline void
anv_shader_bin_unref(struct anv_device * device,struct anv_shader_bin * shader)4745 anv_shader_bin_unref(struct anv_device *device, struct anv_shader_bin *shader)
4746 {
4747    vk_pipeline_cache_object_unref(&device->vk, &shader->base);
4748 }
4749 
4750 struct anv_pipeline_executable {
4751    gl_shader_stage stage;
4752 
4753    struct brw_compile_stats stats;
4754 
4755    char *nir;
4756    char *disasm;
4757 };
4758 
4759 enum anv_pipeline_type {
4760    ANV_PIPELINE_GRAPHICS,
4761    ANV_PIPELINE_GRAPHICS_LIB,
4762    ANV_PIPELINE_COMPUTE,
4763    ANV_PIPELINE_RAY_TRACING,
4764 };
4765 
4766 struct anv_pipeline {
4767    struct vk_object_base                        base;
4768 
4769    struct anv_device *                          device;
4770 
4771    struct anv_batch                             batch;
4772    struct anv_reloc_list                        batch_relocs;
4773 
4774    void *                                       mem_ctx;
4775 
4776    enum anv_pipeline_type                       type;
4777    VkPipelineCreateFlags2KHR                    flags;
4778 
4779    VkShaderStageFlags                           active_stages;
4780 
4781    uint32_t                                     ray_queries;
4782 
4783    /**
4784     * Mask of stages that are accessing push descriptors.
4785     */
4786    VkShaderStageFlags                           use_push_descriptor;
4787 
4788    /**
4789     * Mask of stages that are accessing the push descriptors buffer.
4790     */
4791    VkShaderStageFlags                           use_push_descriptor_buffer;
4792 
4793    /**
4794     * Maximum scratch size for all shaders in this pipeline.
4795     */
4796    uint32_t                                     scratch_size;
4797 
4798    /* Layout of the sets used by the pipeline. */
4799    struct anv_pipeline_sets_layout              layout;
4800 
4801    struct util_dynarray                         executables;
4802 
4803    const struct intel_l3_config *               l3_config;
4804 };
4805 
4806 /* The base graphics pipeline object only hold shaders. */
4807 struct anv_graphics_base_pipeline {
4808    struct anv_pipeline                          base;
4809 
4810    struct vk_sample_locations_state             sample_locations;
4811 
4812    /* Shaders */
4813    struct anv_shader_bin *                      shaders[ANV_GRAPHICS_SHADER_STAGE_COUNT];
4814 
4815    /* A small hash based of shader_info::source_sha1 for identifying
4816     * shaders in renderdoc/shader-db.
4817     */
4818    uint32_t                                     source_hashes[ANV_GRAPHICS_SHADER_STAGE_COUNT];
4819 
4820    /* Feedback index in
4821     * VkPipelineCreationFeedbackCreateInfo::pPipelineStageCreationFeedbacks
4822     *
4823     * For pipeline libraries, we need to remember the order at creation when
4824     * included into a linked pipeline.
4825     */
4826    uint32_t                                     feedback_index[ANV_GRAPHICS_SHADER_STAGE_COUNT];
4827 
4828    /* Robustness flags used shaders
4829     */
4830    enum brw_robustness_flags                    robust_flags[ANV_GRAPHICS_SHADER_STAGE_COUNT];
4831 
4832    /* True if at the time the fragment shader was compiled, it didn't have all
4833     * the information to avoid INTEL_MSAA_FLAG_ENABLE_DYNAMIC.
4834     */
4835    bool                                         fragment_dynamic;
4836 };
4837 
4838 /* The library graphics pipeline object has a partial graphic state and
4839  * possibly some shaders. If requested, shaders are also present in NIR early
4840  * form.
4841  */
4842 struct anv_graphics_lib_pipeline {
4843    struct anv_graphics_base_pipeline            base;
4844 
4845    VkGraphicsPipelineLibraryFlagsEXT            lib_flags;
4846 
4847    struct vk_graphics_pipeline_all_state        all_state;
4848    struct vk_graphics_pipeline_state            state;
4849 
4850    /* Retained shaders for link optimization. */
4851    struct {
4852       /* This hash is the same as computed in
4853        * anv_graphics_pipeline_gather_shaders().
4854        */
4855       unsigned char                             shader_sha1[20];
4856 
4857       enum gl_subgroup_size                     subgroup_size_type;
4858 
4859       /* Hold on the value of VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT
4860        * from library that introduces the stage, so it remains consistent.
4861        */
4862       bool                                      view_index_from_device_index;
4863 
4864       /* NIR captured in anv_pipeline_stage_get_nir(), includes specialization
4865        * constants.
4866        */
4867       nir_shader *                              nir;
4868    }                                            retained_shaders[ANV_GRAPHICS_SHADER_STAGE_COUNT];
4869 
4870    /* Whether the shaders have been retained */
4871    bool                                         retain_shaders;
4872 };
4873 
4874 struct anv_gfx_state_ptr {
4875    /* Both in dwords */
4876    uint16_t  offset;
4877    uint16_t  len;
4878 };
4879 
4880 /* The final graphics pipeline object has all the graphics state ready to be
4881  * programmed into HW packets (dynamic_state field) or fully baked in its
4882  * batch.
4883  */
4884 struct anv_graphics_pipeline {
4885    struct anv_graphics_base_pipeline            base;
4886 
4887    struct vk_vertex_input_state                 vertex_input;
4888    struct vk_sample_locations_state             sample_locations;
4889    struct vk_dynamic_graphics_state             dynamic_state;
4890 
4891    /* If true, the patch control points are passed through push constants
4892     * (anv_push_constants::gfx::tcs_input_vertices)
4893     */
4894    bool                                         dynamic_patch_control_points;
4895 
4896    uint32_t                                     view_mask;
4897    uint32_t                                     instance_multiplier;
4898 
4899    bool                                         rp_has_ds_self_dep;
4900 
4901    bool                                         kill_pixel;
4902    bool                                         uses_xfb;
4903    bool                                         sample_shading_enable;
4904    float                                        min_sample_shading;
4905 
4906    /* Number of VERTEX_ELEMENT_STATE input elements used by the shader */
4907    uint32_t                                     vs_input_elements;
4908 
4909    /* Number of VERTEX_ELEMENT_STATE elements we need to implement some of the
4910     * draw parameters
4911     */
4912    uint32_t                                     svgs_count;
4913 
4914    /* Pre computed VERTEX_ELEMENT_STATE structures for the vertex input that
4915     * can be copied into the anv_cmd_buffer behind a 3DSTATE_VERTEX_BUFFER.
4916     *
4917     * When MESA_VK_DYNAMIC_VI is not dynamic
4918     *
4919     *     vertex_input_elems = vs_input_elements + svgs_count
4920     *
4921     * All the VERTEX_ELEMENT_STATE can be directly copied behind a
4922     * 3DSTATE_VERTEX_ELEMENTS instruction in the command buffer. Otherwise
4923     * this array only holds the svgs_count elements.
4924     */
4925    uint32_t                                     vertex_input_elems;
4926    uint32_t                                     vertex_input_data[2 * 31 /* MAX_VES + 2 internal */];
4927 
4928    /* Number of color outputs used by the fragment shader. */
4929    uint8_t                                      num_color_outputs;
4930    /* Map of color output of the fragment shader to color attachments in the
4931     * render pass.
4932     */
4933    uint8_t                                      color_output_mapping[MAX_RTS];
4934 
4935    /* Pre computed CS instructions that can directly be copied into
4936     * anv_cmd_buffer.
4937     */
4938    uint32_t                                     batch_data[480];
4939 
4940    /* Urb setup utilized by this pipeline. */
4941    struct intel_urb_config urb_cfg;
4942 
4943    /* Fully backed instructions, ready to be emitted in the anv_cmd_buffer */
4944    struct {
4945       struct anv_gfx_state_ptr                  urb;
4946       struct anv_gfx_state_ptr                  vf_sgvs;
4947       struct anv_gfx_state_ptr                  vf_sgvs_2;
4948       struct anv_gfx_state_ptr                  vf_sgvs_instancing;
4949       struct anv_gfx_state_ptr                  vf_instancing;
4950       struct anv_gfx_state_ptr                  primitive_replication;
4951       struct anv_gfx_state_ptr                  sbe;
4952       struct anv_gfx_state_ptr                  sbe_swiz;
4953       struct anv_gfx_state_ptr                  so_decl_list;
4954       struct anv_gfx_state_ptr                  vs;
4955       struct anv_gfx_state_ptr                  hs;
4956       struct anv_gfx_state_ptr                  ds;
4957       struct anv_gfx_state_ptr                  vs_protected;
4958       struct anv_gfx_state_ptr                  hs_protected;
4959       struct anv_gfx_state_ptr                  ds_protected;
4960 
4961       struct anv_gfx_state_ptr                  task_control;
4962       struct anv_gfx_state_ptr                  task_control_protected;
4963       struct anv_gfx_state_ptr                  task_shader;
4964       struct anv_gfx_state_ptr                  task_redistrib;
4965       struct anv_gfx_state_ptr                  clip_mesh;
4966       struct anv_gfx_state_ptr                  mesh_control;
4967       struct anv_gfx_state_ptr                  mesh_control_protected;
4968       struct anv_gfx_state_ptr                  mesh_shader;
4969       struct anv_gfx_state_ptr                  mesh_distrib;
4970       struct anv_gfx_state_ptr                  sbe_mesh;
4971    } final;
4972 
4973    /* Pre packed CS instructions & structures that need to be merged later
4974     * with dynamic state.
4975     */
4976    struct {
4977       struct anv_gfx_state_ptr                  clip;
4978       struct anv_gfx_state_ptr                  sf;
4979       struct anv_gfx_state_ptr                  ps_extra;
4980       struct anv_gfx_state_ptr                  wm;
4981       struct anv_gfx_state_ptr                  so;
4982       struct anv_gfx_state_ptr                  gs;
4983       struct anv_gfx_state_ptr                  gs_protected;
4984       struct anv_gfx_state_ptr                  te;
4985       struct anv_gfx_state_ptr                  ps;
4986       struct anv_gfx_state_ptr                  ps_protected;
4987       struct anv_gfx_state_ptr                  vfg;
4988    } partial;
4989 };
4990 
4991 #define anv_batch_emit_pipeline_state(batch, pipeline, state)           \
4992    do {                                                                 \
4993       if ((pipeline)->state.len == 0)                                   \
4994          break;                                                         \
4995       uint32_t *dw;                                                     \
4996       dw = anv_batch_emit_dwords((batch), (pipeline)->state.len);       \
4997       if (!dw)                                                          \
4998          break;                                                         \
4999       memcpy(dw, &(pipeline)->batch_data[(pipeline)->state.offset],     \
5000              4 * (pipeline)->state.len);                                \
5001    } while (0)
5002 
5003 #define anv_batch_emit_pipeline_state_protected(batch, pipeline,        \
5004                                                 state, protected)       \
5005    do {                                                                 \
5006       struct anv_gfx_state_ptr *_cmd_state = protected ?                \
5007          &(pipeline)->state##_protected : &(pipeline)->state;           \
5008       if (_cmd_state->len == 0)                                         \
5009          break;                                                         \
5010       uint32_t *dw;                                                     \
5011       dw = anv_batch_emit_dwords((batch), _cmd_state->len);             \
5012       if (!dw)                                                          \
5013          break;                                                         \
5014       memcpy(dw, &(pipeline)->batch_data[_cmd_state->offset],           \
5015              4 * _cmd_state->len);                                      \
5016    } while (0)
5017 
5018 
5019 struct anv_compute_pipeline {
5020    struct anv_pipeline                          base;
5021 
5022    struct anv_shader_bin *                      cs;
5023    uint32_t                                     batch_data[9];
5024    uint32_t                                     interface_descriptor_data[8];
5025 
5026    /* A small hash based of shader_info::source_sha1 for identifying shaders
5027     * in renderdoc/shader-db.
5028     */
5029    uint32_t                                     source_hash;
5030 };
5031 
5032 struct anv_rt_shader_group {
5033    VkRayTracingShaderGroupTypeKHR type;
5034 
5035    /* Whether this group was imported from another pipeline */
5036    bool imported;
5037 
5038    struct anv_shader_bin *general;
5039    struct anv_shader_bin *closest_hit;
5040    struct anv_shader_bin *any_hit;
5041    struct anv_shader_bin *intersection;
5042 
5043    /* VK_KHR_ray_tracing requires shaderGroupHandleSize == 32 */
5044    uint32_t handle[8];
5045 };
5046 
5047 struct anv_ray_tracing_pipeline {
5048    struct anv_pipeline                          base;
5049 
5050    /* All shaders in the pipeline */
5051    struct util_dynarray                         shaders;
5052 
5053    uint32_t                                     group_count;
5054    struct anv_rt_shader_group *                 groups;
5055 
5056    /* If non-zero, this is the default computed stack size as per the stack
5057     * size computation in the Vulkan spec.  If zero, that indicates that the
5058     * client has requested a dynamic stack size.
5059     */
5060    uint32_t                                     stack_size;
5061 };
5062 
5063 #define ANV_DECL_PIPELINE_DOWNCAST(pipe_type, pipe_enum)             \
5064    static inline struct anv_##pipe_type##_pipeline *                 \
5065    anv_pipeline_to_##pipe_type(struct anv_pipeline *pipeline)      \
5066    {                                                                 \
5067       assert(pipeline->type == pipe_enum);                           \
5068       return (struct anv_##pipe_type##_pipeline *) pipeline;         \
5069    }
5070 
ANV_DECL_PIPELINE_DOWNCAST(graphics,ANV_PIPELINE_GRAPHICS)5071 ANV_DECL_PIPELINE_DOWNCAST(graphics, ANV_PIPELINE_GRAPHICS)
5072 ANV_DECL_PIPELINE_DOWNCAST(graphics_lib, ANV_PIPELINE_GRAPHICS_LIB)
5073 ANV_DECL_PIPELINE_DOWNCAST(compute, ANV_PIPELINE_COMPUTE)
5074 ANV_DECL_PIPELINE_DOWNCAST(ray_tracing, ANV_PIPELINE_RAY_TRACING)
5075 
5076 /* Can't use the macro because we need to handle both types. */
5077 static inline struct anv_graphics_base_pipeline *
5078 anv_pipeline_to_graphics_base(struct anv_pipeline *pipeline)
5079 {
5080    assert(pipeline->type == ANV_PIPELINE_GRAPHICS ||
5081           pipeline->type == ANV_PIPELINE_GRAPHICS_LIB);
5082    return (struct anv_graphics_base_pipeline *) pipeline;
5083 }
5084 
5085 static inline bool
anv_pipeline_has_stage(const struct anv_graphics_pipeline * pipeline,gl_shader_stage stage)5086 anv_pipeline_has_stage(const struct anv_graphics_pipeline *pipeline,
5087                        gl_shader_stage stage)
5088 {
5089    return (pipeline->base.base.active_stages & mesa_to_vk_shader_stage(stage)) != 0;
5090 }
5091 
5092 static inline bool
anv_pipeline_base_has_stage(const struct anv_graphics_base_pipeline * pipeline,gl_shader_stage stage)5093 anv_pipeline_base_has_stage(const struct anv_graphics_base_pipeline *pipeline,
5094                             gl_shader_stage stage)
5095 {
5096    return (pipeline->base.active_stages & mesa_to_vk_shader_stage(stage)) != 0;
5097 }
5098 
5099 static inline bool
anv_pipeline_is_primitive(const struct anv_graphics_pipeline * pipeline)5100 anv_pipeline_is_primitive(const struct anv_graphics_pipeline *pipeline)
5101 {
5102    return anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX);
5103 }
5104 
5105 static inline bool
anv_pipeline_is_mesh(const struct anv_graphics_pipeline * pipeline)5106 anv_pipeline_is_mesh(const struct anv_graphics_pipeline *pipeline)
5107 {
5108    return anv_pipeline_has_stage(pipeline, MESA_SHADER_MESH);
5109 }
5110 
5111 static inline bool
anv_gfx_all_color_write_masked(const struct anv_cmd_graphics_state * gfx,const struct vk_dynamic_graphics_state * dyn)5112 anv_gfx_all_color_write_masked(const struct anv_cmd_graphics_state *gfx,
5113                                const struct vk_dynamic_graphics_state *dyn)
5114 {
5115    uint8_t color_writes = dyn->cb.color_write_enables;
5116 
5117    /* All writes disabled through vkCmdSetColorWriteEnableEXT */
5118    if ((color_writes & ((1u << gfx->color_att_count) - 1)) == 0)
5119       return true;
5120 
5121    /* Or all write masks are empty */
5122    for (uint32_t i = 0; i < gfx->color_att_count; i++) {
5123       if (dyn->cb.attachments[i].write_mask != 0)
5124          return false;
5125    }
5126 
5127    return true;
5128 }
5129 
5130 static inline void
anv_cmd_graphic_state_update_has_uint_rt(struct anv_cmd_graphics_state * state)5131 anv_cmd_graphic_state_update_has_uint_rt(struct anv_cmd_graphics_state *state)
5132 {
5133    state->has_uint_rt = false;
5134    for (unsigned a = 0; a < state->color_att_count; a++) {
5135       if (vk_format_is_int(state->color_att[a].vk_format)) {
5136          state->has_uint_rt = true;
5137          break;
5138       }
5139    }
5140 }
5141 
5142 #define ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(prefix, stage)             \
5143 static inline const struct brw_##prefix##_prog_data *                   \
5144 get_##prefix##_prog_data(const struct anv_graphics_pipeline *pipeline)  \
5145 {                                                                       \
5146    if (anv_pipeline_has_stage(pipeline, stage)) {                       \
5147       return (const struct brw_##prefix##_prog_data *)                  \
5148          pipeline->base.shaders[stage]->prog_data;                      \
5149    } else {                                                             \
5150       return NULL;                                                      \
5151    }                                                                    \
5152 }
5153 
ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(vs,MESA_SHADER_VERTEX)5154 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(vs, MESA_SHADER_VERTEX)
5155 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(tcs, MESA_SHADER_TESS_CTRL)
5156 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(tes, MESA_SHADER_TESS_EVAL)
5157 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(gs, MESA_SHADER_GEOMETRY)
5158 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(wm, MESA_SHADER_FRAGMENT)
5159 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(mesh, MESA_SHADER_MESH)
5160 ANV_DECL_GET_GRAPHICS_PROG_DATA_FUNC(task, MESA_SHADER_TASK)
5161 
5162 static inline const struct brw_cs_prog_data *
5163 get_cs_prog_data(const struct anv_compute_pipeline *pipeline)
5164 {
5165    assert(pipeline->cs);
5166    return (const struct brw_cs_prog_data *) pipeline->cs->prog_data;
5167 }
5168 
5169 static inline const struct brw_vue_prog_data *
anv_pipeline_get_last_vue_prog_data(const struct anv_graphics_pipeline * pipeline)5170 anv_pipeline_get_last_vue_prog_data(const struct anv_graphics_pipeline *pipeline)
5171 {
5172    if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
5173       return &get_gs_prog_data(pipeline)->base;
5174    else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
5175       return &get_tes_prog_data(pipeline)->base;
5176    else
5177       return &get_vs_prog_data(pipeline)->base;
5178 }
5179 
5180 VkResult
5181 anv_device_init_rt_shaders(struct anv_device *device);
5182 
5183 void
5184 anv_device_finish_rt_shaders(struct anv_device *device);
5185 
5186 struct anv_kernel_arg {
5187    bool is_ptr;
5188    uint16_t size;
5189 
5190    union {
5191       uint64_t u64;
5192       void *ptr;
5193    };
5194 };
5195 
5196 struct anv_kernel {
5197 #ifndef NDEBUG
5198    const char *name;
5199 #endif
5200    struct anv_shader_bin *bin;
5201    const struct intel_l3_config *l3_config;
5202 };
5203 
5204 struct anv_format_plane {
5205    enum isl_format isl_format:16;
5206    struct isl_swizzle swizzle;
5207 
5208    /* What aspect is associated to this plane */
5209    VkImageAspectFlags aspect;
5210 };
5211 
5212 enum anv_format_flag {
5213    /* Format supports YCbCr */
5214    ANV_FORMAT_FLAG_CAN_YCBCR = BITFIELD_BIT(0),
5215    /* Format supports video API */
5216    ANV_FORMAT_FLAG_CAN_VIDEO = BITFIELD_BIT(1),
5217    /* Format works if custom border colors without format is disabled */
5218    ANV_FORMAT_FLAG_NO_CBCWF  = BITFIELD_BIT(2),
5219 };
5220 
5221 struct anv_format {
5222    struct anv_format_plane planes[3];
5223    VkFormat vk_format;
5224    uint8_t n_planes;
5225    enum anv_format_flag flags:8;
5226 };
5227 
5228 static inline void
anv_assert_valid_aspect_set(VkImageAspectFlags aspects)5229 anv_assert_valid_aspect_set(VkImageAspectFlags aspects)
5230 {
5231    if (util_bitcount(aspects) == 1) {
5232       assert(aspects & (VK_IMAGE_ASPECT_COLOR_BIT |
5233                         VK_IMAGE_ASPECT_DEPTH_BIT |
5234                         VK_IMAGE_ASPECT_STENCIL_BIT |
5235                         VK_IMAGE_ASPECT_PLANE_0_BIT |
5236                         VK_IMAGE_ASPECT_PLANE_1_BIT |
5237                         VK_IMAGE_ASPECT_PLANE_2_BIT));
5238    } else if (aspects & VK_IMAGE_ASPECT_PLANES_BITS_ANV) {
5239       assert(aspects == VK_IMAGE_ASPECT_PLANE_0_BIT ||
5240              aspects == (VK_IMAGE_ASPECT_PLANE_0_BIT |
5241                          VK_IMAGE_ASPECT_PLANE_1_BIT) ||
5242              aspects == (VK_IMAGE_ASPECT_PLANE_0_BIT |
5243                          VK_IMAGE_ASPECT_PLANE_1_BIT |
5244                          VK_IMAGE_ASPECT_PLANE_2_BIT));
5245    } else {
5246       assert(aspects == (VK_IMAGE_ASPECT_DEPTH_BIT |
5247                          VK_IMAGE_ASPECT_STENCIL_BIT));
5248    }
5249 }
5250 
5251 /**
5252  * Return the aspect's plane relative to all_aspects.  For an image, for
5253  * instance, all_aspects would be the set of aspects in the image.  For
5254  * an image view, all_aspects would be the subset of aspects represented
5255  * by that particular view.
5256  */
5257 static inline uint32_t
anv_aspect_to_plane(VkImageAspectFlags all_aspects,VkImageAspectFlagBits aspect)5258 anv_aspect_to_plane(VkImageAspectFlags all_aspects,
5259                     VkImageAspectFlagBits aspect)
5260 {
5261    anv_assert_valid_aspect_set(all_aspects);
5262    assert(util_bitcount(aspect) == 1);
5263    assert(!(aspect & ~all_aspects));
5264 
5265    /* Because we always put image and view planes in aspect-bit-order, the
5266     * plane index is the number of bits in all_aspects before aspect.
5267     */
5268    return util_bitcount(all_aspects & (aspect - 1));
5269 }
5270 
5271 #define anv_foreach_image_aspect_bit(b, image, aspects) \
5272    u_foreach_bit(b, vk_image_expand_aspect_mask(&(image)->vk, aspects))
5273 
5274 const struct anv_format *
5275 anv_get_format(const struct anv_physical_device *device, VkFormat format);
5276 
5277 static inline uint32_t
anv_get_format_planes(const struct anv_physical_device * device,VkFormat vk_format)5278 anv_get_format_planes(const struct anv_physical_device *device,
5279                       VkFormat vk_format)
5280 {
5281    const struct anv_format *format = anv_get_format(device, vk_format);
5282 
5283    return format != NULL ? format->n_planes : 0;
5284 }
5285 
5286 struct anv_format_plane
5287 anv_get_format_plane(const struct anv_physical_device *device,
5288                      VkFormat vk_format, uint32_t plane,
5289                      VkImageTiling tiling);
5290 
5291 struct anv_format_plane
5292 anv_get_format_aspect(const struct anv_physical_device *device,
5293                       VkFormat vk_format,
5294                       VkImageAspectFlagBits aspect, VkImageTiling tiling);
5295 
5296 static inline enum isl_format
anv_get_isl_format(const struct anv_physical_device * device,VkFormat vk_format,VkImageAspectFlags aspect,VkImageTiling tiling)5297 anv_get_isl_format(const struct anv_physical_device *device, VkFormat vk_format,
5298                    VkImageAspectFlags aspect, VkImageTiling tiling)
5299 {
5300    return anv_get_format_aspect(device, vk_format, aspect, tiling).isl_format;
5301 }
5302 
5303 bool anv_format_supports_ccs_e(const struct anv_physical_device *device,
5304                                const enum isl_format format);
5305 
5306 bool anv_formats_ccs_e_compatible(const struct anv_physical_device *device,
5307                                   VkImageCreateFlags create_flags,
5308                                   VkFormat vk_format, VkImageTiling vk_tiling,
5309                                   VkImageUsageFlags vk_usage,
5310                                   const VkImageFormatListCreateInfo *fmt_list);
5311 
5312 extern VkFormat
5313 vk_format_from_android(unsigned android_format, unsigned android_usage);
5314 
5315 static inline VkFormat
anv_get_emulation_format(const struct anv_physical_device * pdevice,VkFormat format)5316 anv_get_emulation_format(const struct anv_physical_device *pdevice, VkFormat format)
5317 {
5318    if (pdevice->flush_astc_ldr_void_extent_denorms) {
5319       const struct util_format_description *desc =
5320          vk_format_description(format);
5321       if (desc->layout == UTIL_FORMAT_LAYOUT_ASTC &&
5322           desc->colorspace == UTIL_FORMAT_COLORSPACE_RGB)
5323          return format;
5324    }
5325 
5326    if (pdevice->emu_astc_ldr)
5327       return vk_texcompress_astc_emulation_format(format);
5328 
5329    return VK_FORMAT_UNDEFINED;
5330 }
5331 
5332 static inline bool
anv_is_format_emulated(const struct anv_physical_device * pdevice,VkFormat format)5333 anv_is_format_emulated(const struct anv_physical_device *pdevice, VkFormat format)
5334 {
5335    return anv_get_emulation_format(pdevice, format) != VK_FORMAT_UNDEFINED;
5336 }
5337 
5338 static inline struct isl_swizzle
anv_swizzle_for_render(struct isl_swizzle swizzle)5339 anv_swizzle_for_render(struct isl_swizzle swizzle)
5340 {
5341    /* Sometimes the swizzle will have alpha map to one.  We do this to fake
5342     * RGB as RGBA for texturing
5343     */
5344    assert(swizzle.a == ISL_CHANNEL_SELECT_ONE ||
5345           swizzle.a == ISL_CHANNEL_SELECT_ALPHA);
5346 
5347    /* But it doesn't matter what we render to that channel */
5348    swizzle.a = ISL_CHANNEL_SELECT_ALPHA;
5349 
5350    return swizzle;
5351 }
5352 
5353 void
5354 anv_pipeline_setup_l3_config(struct anv_pipeline *pipeline, bool needs_slm);
5355 
5356 /**
5357  * Describes how each part of anv_image will be bound to memory.
5358  */
5359 struct anv_image_memory_range {
5360    /**
5361     * Disjoint bindings into which each portion of the image will be bound.
5362     *
5363     * Binding images to memory can be complicated and invold binding different
5364     * portions of the image to different memory objects or regions.  For most
5365     * images, everything lives in the MAIN binding and gets bound by
5366     * vkBindImageMemory.  For disjoint multi-planar images, each plane has
5367     * a unique, disjoint binding and gets bound by vkBindImageMemory2 with
5368     * VkBindImagePlaneMemoryInfo.  There may also exist bits of memory which are
5369     * implicit or driver-managed and live in special-case bindings.
5370     */
5371    enum anv_image_memory_binding {
5372       /**
5373        * Used if and only if image is not multi-planar disjoint. Bound by
5374        * vkBindImageMemory2 without VkBindImagePlaneMemoryInfo.
5375        */
5376       ANV_IMAGE_MEMORY_BINDING_MAIN,
5377 
5378       /**
5379        * Used if and only if image is multi-planar disjoint.  Bound by
5380        * vkBindImageMemory2 with VkBindImagePlaneMemoryInfo.
5381        */
5382       ANV_IMAGE_MEMORY_BINDING_PLANE_0,
5383       ANV_IMAGE_MEMORY_BINDING_PLANE_1,
5384       ANV_IMAGE_MEMORY_BINDING_PLANE_2,
5385 
5386       /**
5387        * Driver-private bo. In special cases we may store the aux surface and/or
5388        * aux state in this binding.
5389        */
5390       ANV_IMAGE_MEMORY_BINDING_PRIVATE,
5391 
5392       /** Sentinel */
5393       ANV_IMAGE_MEMORY_BINDING_END,
5394    } binding;
5395 
5396    uint32_t alignment;
5397    uint64_t size;
5398 
5399    /**
5400     * Offset is relative to the start of the binding created by
5401     * vkBindImageMemory, not to the start of the bo.
5402     */
5403    uint64_t offset;
5404 };
5405 
5406 /**
5407  * Subsurface of an anv_image.
5408  */
5409 struct anv_surface {
5410    struct isl_surf isl;
5411    struct anv_image_memory_range memory_range;
5412 };
5413 
5414 static inline bool MUST_CHECK
anv_surface_is_valid(const struct anv_surface * surface)5415 anv_surface_is_valid(const struct anv_surface *surface)
5416 {
5417    return surface->isl.size_B > 0 && surface->memory_range.size > 0;
5418 }
5419 
5420 struct anv_image {
5421    struct vk_image vk;
5422 
5423    uint32_t n_planes;
5424 
5425    /**
5426     * Image has multi-planar format and was created with
5427     * VK_IMAGE_CREATE_DISJOINT_BIT.
5428     */
5429    bool disjoint;
5430 
5431    /**
5432     * Image is a WSI image
5433     */
5434    bool from_wsi;
5435 
5436    /**
5437     * Image is a WSI blit src image, it will never be scanout directly to
5438     * display but will be copied to a dma-buf that can be scanout.
5439     */
5440    bool wsi_blit_src;
5441 
5442    /**
5443     * Image was imported from an struct AHardwareBuffer.  We have to delay
5444     * final image creation until bind time.
5445     */
5446    bool from_ahb;
5447 
5448    /**
5449     * Image was imported from gralloc with VkNativeBufferANDROID. The gralloc bo
5450     * must be released when the image is destroyed.
5451     */
5452    bool from_gralloc;
5453 
5454    /**
5455     * If not UNDEFINED, image has a hidden plane at planes[n_planes] for ASTC
5456     * LDR workaround or emulation.
5457     */
5458    VkFormat emu_plane_format;
5459 
5460    /**
5461     * The set of formats that will be used with the first plane of this image.
5462     *
5463     * Assuming all view formats have the same bits-per-channel, we support the
5464     * largest number of variations which may exist.
5465     */
5466    enum isl_format view_formats[5];
5467    unsigned num_view_formats;
5468 
5469    /**
5470     * The memory bindings created by vkCreateImage and vkBindImageMemory.
5471     *
5472     * For details on the image's memory layout, see check_memory_bindings().
5473     *
5474     * vkCreateImage constructs the `memory_range` for each
5475     * anv_image_memory_binding.  After vkCreateImage, each binding is valid if
5476     * and only if `memory_range::size > 0`.
5477     *
5478     * vkBindImageMemory binds each valid `memory_range` to an `address`.
5479     * Usually, the app will provide the address via the parameters of
5480     * vkBindImageMemory.  However, special-case bindings may be bound to
5481     * driver-private memory.
5482     *
5483     * If needed a host pointer to the image is mapped for host image copies.
5484     */
5485    struct anv_image_binding {
5486       struct anv_image_memory_range memory_range;
5487       struct anv_address address;
5488       struct anv_sparse_binding_data sparse_data;
5489       void *host_map;
5490       uint64_t map_delta;
5491       uint64_t map_size;
5492    } bindings[ANV_IMAGE_MEMORY_BINDING_END];
5493 
5494    /**
5495     * Image subsurfaces
5496     *
5497     * For each foo, anv_image::planes[x].surface is valid if and only if
5498     * anv_image::aspects has a x aspect. Refer to anv_image_aspect_to_plane()
5499     * to figure the number associated with a given aspect.
5500     *
5501     * The hardware requires that the depth buffer and stencil buffer be
5502     * separate surfaces.  From Vulkan's perspective, though, depth and stencil
5503     * reside in the same VkImage.  To satisfy both the hardware and Vulkan, we
5504     * allocate the depth and stencil buffers as separate surfaces in the same
5505     * bo.
5506     */
5507    struct anv_image_plane {
5508       struct anv_surface primary_surface;
5509 
5510       /**
5511        * The base aux usage for this image.  For color images, this can be
5512        * either CCS_E or CCS_D depending on whether or not we can reliably
5513        * leave CCS on all the time.
5514        */
5515       enum isl_aux_usage aux_usage;
5516 
5517       struct anv_surface aux_surface;
5518 
5519       /** Location of the compression control surface.  */
5520       struct anv_image_memory_range compr_ctrl_memory_range;
5521 
5522       /** Location of the fast clear state.  */
5523       struct anv_image_memory_range fast_clear_memory_range;
5524 
5525       struct {
5526          /** Whether the image has CCS data mapped through AUX-TT. */
5527          bool mapped;
5528 
5529          /** Main address of the mapping. */
5530          uint64_t addr;
5531 
5532          /** Size of the mapping. */
5533          uint64_t size;
5534       } aux_tt;
5535    } planes[3];
5536 
5537    struct anv_image_memory_range vid_dmv_top_surface;
5538 
5539    /* Link in the anv_device.image_private_objects list */
5540    struct list_head link;
5541    struct anv_image_memory_range av1_cdf_table;
5542 };
5543 
5544 static inline bool
anv_image_is_protected(const struct anv_image * image)5545 anv_image_is_protected(const struct anv_image *image)
5546 {
5547    return image->vk.create_flags & VK_IMAGE_CREATE_PROTECTED_BIT;
5548 }
5549 
5550 static inline bool
anv_image_is_sparse(const struct anv_image * image)5551 anv_image_is_sparse(const struct anv_image *image)
5552 {
5553    return image->vk.create_flags & VK_IMAGE_CREATE_SPARSE_BINDING_BIT;
5554 }
5555 
5556 static inline bool
anv_image_is_externally_shared(const struct anv_image * image)5557 anv_image_is_externally_shared(const struct anv_image *image)
5558 {
5559    return image->vk.drm_format_mod != DRM_FORMAT_MOD_INVALID ||
5560           image->vk.external_handle_types != 0;
5561 }
5562 
5563 static inline bool
anv_image_has_private_binding(const struct anv_image * image)5564 anv_image_has_private_binding(const struct anv_image *image)
5565 {
5566    const struct anv_image_binding private_binding =
5567       image->bindings[ANV_IMAGE_MEMORY_BINDING_PRIVATE];
5568    return private_binding.memory_range.size != 0;
5569 }
5570 
5571 static inline bool
anv_image_format_is_d16_or_s8(const struct anv_image * image)5572 anv_image_format_is_d16_or_s8(const struct anv_image *image)
5573 {
5574    return image->vk.format == VK_FORMAT_D16_UNORM ||
5575       image->vk.format == VK_FORMAT_D16_UNORM_S8_UINT ||
5576       image->vk.format == VK_FORMAT_D24_UNORM_S8_UINT ||
5577       image->vk.format == VK_FORMAT_D32_SFLOAT_S8_UINT ||
5578       image->vk.format == VK_FORMAT_S8_UINT;
5579 }
5580 
5581 static inline bool
anv_image_can_host_memcpy(const struct anv_image * image)5582 anv_image_can_host_memcpy(const struct anv_image *image)
5583 {
5584    const struct isl_surf *surf = &image->planes[0].primary_surface.isl;
5585    struct isl_tile_info tile_info;
5586    isl_surf_get_tile_info(surf, &tile_info);
5587 
5588    const bool array_pitch_aligned_to_tile =
5589       surf->array_pitch_el_rows % tile_info.logical_extent_el.height == 0;
5590 
5591    return image->vk.tiling != VK_IMAGE_TILING_LINEAR &&
5592           image->n_planes == 1 &&
5593           array_pitch_aligned_to_tile &&
5594           image->vk.mip_levels == 1;
5595 }
5596 
5597 /* The ordering of this enum is important */
5598 enum anv_fast_clear_type {
5599    /** Image does not have/support any fast-clear blocks */
5600    ANV_FAST_CLEAR_NONE = 0,
5601    /** Image has/supports fast-clear but only to the default value */
5602    ANV_FAST_CLEAR_DEFAULT_VALUE = 1,
5603    /** Image has/supports fast-clear with an arbitrary fast-clear value */
5604    ANV_FAST_CLEAR_ANY = 2,
5605 };
5606 
5607 /**
5608  * Return the aspect's _format_ plane, not its _memory_ plane (using the
5609  * vocabulary of VK_EXT_image_drm_format_modifier). As a consequence, \a
5610  * aspect_mask may contain VK_IMAGE_ASPECT_PLANE_*, but must not contain
5611  * VK_IMAGE_ASPECT_MEMORY_PLANE_* .
5612  */
5613 static inline uint32_t
anv_image_aspect_to_plane(const struct anv_image * image,VkImageAspectFlagBits aspect)5614 anv_image_aspect_to_plane(const struct anv_image *image,
5615                           VkImageAspectFlagBits aspect)
5616 {
5617    return anv_aspect_to_plane(image->vk.aspects, aspect);
5618 }
5619 
5620 /* Returns the number of auxiliary buffer levels attached to an image. */
5621 static inline uint8_t
anv_image_aux_levels(const struct anv_image * const image,VkImageAspectFlagBits aspect)5622 anv_image_aux_levels(const struct anv_image * const image,
5623                      VkImageAspectFlagBits aspect)
5624 {
5625    uint32_t plane = anv_image_aspect_to_plane(image, aspect);
5626    if (image->planes[plane].aux_usage == ISL_AUX_USAGE_NONE)
5627       return 0;
5628 
5629    return image->vk.mip_levels;
5630 }
5631 
5632 /* Returns the number of auxiliary buffer layers attached to an image. */
5633 static inline uint32_t
anv_image_aux_layers(const struct anv_image * const image,VkImageAspectFlagBits aspect,const uint8_t miplevel)5634 anv_image_aux_layers(const struct anv_image * const image,
5635                      VkImageAspectFlagBits aspect,
5636                      const uint8_t miplevel)
5637 {
5638    assert(image);
5639 
5640    /* The miplevel must exist in the main buffer. */
5641    assert(miplevel < image->vk.mip_levels);
5642 
5643    if (miplevel >= anv_image_aux_levels(image, aspect)) {
5644       /* There are no layers with auxiliary data because the miplevel has no
5645        * auxiliary data.
5646        */
5647       return 0;
5648    }
5649 
5650    return MAX2(image->vk.array_layers, image->vk.extent.depth >> miplevel);
5651 }
5652 
5653 static inline struct anv_address MUST_CHECK
anv_image_address(const struct anv_image * image,const struct anv_image_memory_range * mem_range)5654 anv_image_address(const struct anv_image *image,
5655                   const struct anv_image_memory_range *mem_range)
5656 {
5657    const struct anv_image_binding *binding = &image->bindings[mem_range->binding];
5658    assert(binding->memory_range.offset == 0);
5659 
5660    if (mem_range->size == 0)
5661       return ANV_NULL_ADDRESS;
5662 
5663    return anv_address_add(binding->address, mem_range->offset);
5664 }
5665 
5666 bool
5667 anv_image_view_formats_incomplete(const struct anv_image *image);
5668 
5669 static inline struct anv_address
anv_image_get_clear_color_addr(UNUSED const struct anv_device * device,const struct anv_image * image,enum isl_format view_format,VkImageAspectFlagBits aspect,bool for_sampler)5670 anv_image_get_clear_color_addr(UNUSED const struct anv_device *device,
5671                                const struct anv_image *image,
5672                                enum isl_format view_format,
5673                                VkImageAspectFlagBits aspect,
5674                                bool for_sampler)
5675 {
5676    uint32_t plane = anv_image_aspect_to_plane(image, aspect);
5677    const struct anv_image_memory_range *mem_range =
5678       &image->planes[plane].fast_clear_memory_range;
5679 
5680    const struct anv_address base_addr = anv_image_address(image, mem_range);
5681    if (anv_address_is_null(base_addr))
5682       return ANV_NULL_ADDRESS;
5683 
5684    if (view_format == ISL_FORMAT_UNSUPPORTED)
5685       view_format = image->planes[plane].primary_surface.isl.format;
5686 
5687    uint64_t access_offset = device->info->ver == 9 && for_sampler ? 16 : 0;
5688    const unsigned clear_state_size = device->info->ver >= 11 ? 64 : 32;
5689    for (int i = 0; i < image->num_view_formats; i++) {
5690       if (view_format == image->view_formats[i]) {
5691          uint64_t entry_offset = i * clear_state_size + access_offset;
5692          return anv_address_add(base_addr, entry_offset);
5693       }
5694    }
5695 
5696    assert(anv_image_view_formats_incomplete(image));
5697    return anv_address_add(base_addr, access_offset);
5698 }
5699 
5700 static inline struct anv_address
anv_image_get_fast_clear_type_addr(const struct anv_device * device,const struct anv_image * image,VkImageAspectFlagBits aspect)5701 anv_image_get_fast_clear_type_addr(const struct anv_device *device,
5702                                    const struct anv_image *image,
5703                                    VkImageAspectFlagBits aspect)
5704 {
5705    /* Xe2+ platforms don't need fast clear type. We shouldn't get here. */
5706    assert(device->info->ver < 20);
5707    struct anv_address addr =
5708       anv_image_get_clear_color_addr(device, image, ISL_FORMAT_UNSUPPORTED,
5709                                      aspect, false);
5710 
5711    /* Refer to add_aux_state_tracking_buffer(). */
5712    unsigned clear_color_state_size;
5713    if (device->info->ver >= 11) {
5714       assert(device->isl_dev.ss.clear_color_state_size == 32);
5715       clear_color_state_size = (image->num_view_formats - 1) * 64 + 32 - 8;
5716    } else {
5717       assert(device->isl_dev.ss.clear_value_size == 16);
5718       clear_color_state_size = image->num_view_formats * 16 * 2;
5719    }
5720 
5721    return anv_address_add(addr, clear_color_state_size);
5722 }
5723 
5724 static inline struct anv_address
anv_image_get_compression_state_addr(const struct anv_device * device,const struct anv_image * image,VkImageAspectFlagBits aspect,uint32_t level,uint32_t array_layer)5725 anv_image_get_compression_state_addr(const struct anv_device *device,
5726                                      const struct anv_image *image,
5727                                      VkImageAspectFlagBits aspect,
5728                                      uint32_t level, uint32_t array_layer)
5729 {
5730    /* Xe2+ platforms don't use compression state. We shouldn't get here. */
5731    assert(device->info->ver < 20);
5732    assert(level < anv_image_aux_levels(image, aspect));
5733    assert(array_layer < anv_image_aux_layers(image, aspect, level));
5734    UNUSED uint32_t plane = anv_image_aspect_to_plane(image, aspect);
5735    assert(isl_aux_usage_has_ccs_e(image->planes[plane].aux_usage));
5736 
5737    /* Relative to start of the plane's fast clear type */
5738    uint32_t offset;
5739 
5740    offset = 4; /* Go past the fast clear type */
5741 
5742    if (image->vk.image_type == VK_IMAGE_TYPE_3D) {
5743       for (uint32_t l = 0; l < level; l++)
5744          offset += u_minify(image->vk.extent.depth, l) * 4;
5745    } else {
5746       offset += level * image->vk.array_layers * 4;
5747    }
5748 
5749    offset += array_layer * 4;
5750 
5751    assert(offset < image->planes[plane].fast_clear_memory_range.size);
5752 
5753    return anv_address_add(
5754       anv_image_get_fast_clear_type_addr(device, image, aspect),
5755       offset);
5756 }
5757 
5758 static inline const struct anv_image_memory_range *
anv_image_get_aux_memory_range(const struct anv_image * image,uint32_t plane)5759 anv_image_get_aux_memory_range(const struct anv_image *image,
5760                                uint32_t plane)
5761 {
5762    if (image->planes[plane].aux_surface.memory_range.size > 0)
5763      return &image->planes[plane].aux_surface.memory_range;
5764    else
5765      return &image->planes[plane].compr_ctrl_memory_range;
5766 }
5767 
5768 /* Returns true if a HiZ-enabled depth buffer can be sampled from. */
5769 static inline bool
anv_can_sample_with_hiz(const struct intel_device_info * const devinfo,const struct anv_image * image)5770 anv_can_sample_with_hiz(const struct intel_device_info * const devinfo,
5771                         const struct anv_image *image)
5772 {
5773    if (!(image->vk.aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
5774       return false;
5775 
5776    /* For Gfx8-11, there are some restrictions around sampling from HiZ.
5777     * The Skylake PRM docs for RENDER_SURFACE_STATE::AuxiliarySurfaceMode
5778     * say:
5779     *
5780     *    "If this field is set to AUX_HIZ, Number of Multisamples must
5781     *    be MULTISAMPLECOUNT_1, and Surface Type cannot be SURFTYPE_3D."
5782     */
5783    if (image->vk.image_type == VK_IMAGE_TYPE_3D)
5784       return false;
5785 
5786    if (!devinfo->has_sample_with_hiz)
5787       return false;
5788 
5789    return image->vk.samples == 1;
5790 }
5791 
5792 /* Returns true if an MCS-enabled buffer can be sampled from. */
5793 static inline bool
anv_can_sample_mcs_with_clear(const struct intel_device_info * const devinfo,const struct anv_image * image)5794 anv_can_sample_mcs_with_clear(const struct intel_device_info * const devinfo,
5795                               const struct anv_image *image)
5796 {
5797    assert(image->vk.aspects == VK_IMAGE_ASPECT_COLOR_BIT);
5798    const uint32_t plane =
5799       anv_image_aspect_to_plane(image, VK_IMAGE_ASPECT_COLOR_BIT);
5800 
5801    assert(isl_aux_usage_has_mcs(image->planes[plane].aux_usage));
5802 
5803    const struct anv_surface *anv_surf = &image->planes[plane].primary_surface;
5804 
5805    /* On TGL, the sampler has an issue with some 8 and 16bpp MSAA fast clears.
5806     * See HSD 1707282275, wa_14013111325. Due to the use of
5807     * format-reinterpretation, a simplified workaround is implemented.
5808     */
5809    if (intel_needs_workaround(devinfo, 14013111325) &&
5810        isl_format_get_layout(anv_surf->isl.format)->bpb <= 16) {
5811       return false;
5812    }
5813 
5814    return true;
5815 }
5816 
5817 static inline bool
anv_image_plane_uses_aux_map(const struct anv_device * device,const struct anv_image * image,uint32_t plane)5818 anv_image_plane_uses_aux_map(const struct anv_device *device,
5819                              const struct anv_image *image,
5820                              uint32_t plane)
5821 {
5822    return device->info->has_aux_map &&
5823       isl_aux_usage_has_ccs(image->planes[plane].aux_usage);
5824 }
5825 
5826 static inline bool
anv_image_uses_aux_map(const struct anv_device * device,const struct anv_image * image)5827 anv_image_uses_aux_map(const struct anv_device *device,
5828                        const struct anv_image *image)
5829 {
5830    for (uint32_t p = 0; p < image->n_planes; ++p) {
5831       if (anv_image_plane_uses_aux_map(device, image, p))
5832          return true;
5833    }
5834 
5835    return false;
5836 }
5837 
5838 static inline bool
anv_bo_allows_aux_map(const struct anv_device * device,const struct anv_bo * bo)5839 anv_bo_allows_aux_map(const struct anv_device *device,
5840                       const struct anv_bo *bo)
5841 {
5842    if (device->aux_map_ctx == NULL)
5843       return false;
5844 
5845    return (bo->alloc_flags & ANV_BO_ALLOC_AUX_TT_ALIGNED) != 0;
5846 }
5847 
5848 static inline bool
anv_address_allows_aux_map(const struct anv_device * device,struct anv_address addr)5849 anv_address_allows_aux_map(const struct anv_device *device,
5850                            struct anv_address addr)
5851 {
5852    if (device->aux_map_ctx == NULL)
5853       return false;
5854 
5855    /* Technically, we really only care about what offset the image is bound
5856     * into on the BO, but we don't have that information here. As a heuristic,
5857     * rely on the BO offset instead.
5858     */
5859    if (anv_address_physical(addr) %
5860        intel_aux_map_get_alignment(device->aux_map_ctx) != 0)
5861       return false;
5862 
5863    return true;
5864 }
5865 
5866 void
5867 anv_cmd_buffer_mark_image_written(struct anv_cmd_buffer *cmd_buffer,
5868                                   const struct anv_image *image,
5869                                   VkImageAspectFlagBits aspect,
5870                                   enum isl_aux_usage aux_usage,
5871                                   uint32_t level,
5872                                   uint32_t base_layer,
5873                                   uint32_t layer_count);
5874 
5875 void
5876 anv_cmd_buffer_mark_image_fast_cleared(struct anv_cmd_buffer *cmd_buffer,
5877                                        const struct anv_image *image,
5878                                        const enum isl_format format,
5879                                        const struct isl_swizzle swizzle,
5880                                        union isl_color_value clear_color);
5881 
5882 void
5883 anv_cmd_buffer_load_clear_color(struct anv_cmd_buffer *cmd_buffer,
5884                                 struct anv_state state,
5885                                 const struct anv_image_view *iview);
5886 
5887 enum anv_image_memory_binding
5888 anv_image_aspect_to_binding(struct anv_image *image,
5889                             VkImageAspectFlags aspect);
5890 
5891 void
5892 anv_image_clear_color(struct anv_cmd_buffer *cmd_buffer,
5893                       const struct anv_image *image,
5894                       VkImageAspectFlagBits aspect,
5895                       enum isl_aux_usage aux_usage,
5896                       enum isl_format format, struct isl_swizzle swizzle,
5897                       uint32_t level, uint32_t base_layer, uint32_t layer_count,
5898                       VkRect2D area, union isl_color_value clear_color);
5899 void
5900 anv_image_clear_depth_stencil(struct anv_cmd_buffer *cmd_buffer,
5901                               const struct anv_image *image,
5902                               VkImageAspectFlags aspects,
5903                               enum isl_aux_usage depth_aux_usage,
5904                               uint32_t level,
5905                               uint32_t base_layer, uint32_t layer_count,
5906                               VkRect2D area,
5907                               const VkClearDepthStencilValue *clear_value);
5908 void
5909 anv_attachment_msaa_resolve(struct anv_cmd_buffer *cmd_buffer,
5910                             const struct anv_attachment *att,
5911                             VkImageLayout layout,
5912                             VkImageAspectFlagBits aspect);
5913 
5914 static inline union isl_color_value
anv_image_hiz_clear_value(const struct anv_image * image)5915 anv_image_hiz_clear_value(const struct anv_image *image)
5916 {
5917    /* The benchmarks we're tracking tend to prefer clearing depth buffers to
5918     * 0.0f when the depth buffers are part of images with multiple aspects.
5919     * Otherwise, they tend to prefer clearing depth buffers to 1.0f.
5920     */
5921    if (image->n_planes == 2)
5922       return (union isl_color_value) { .f32 = { 0.0f, } };
5923    else
5924       return (union isl_color_value) { .f32 = { 1.0f, } };
5925 }
5926 
5927 void
5928 anv_image_hiz_op(struct anv_cmd_buffer *cmd_buffer,
5929                  const struct anv_image *image,
5930                  VkImageAspectFlagBits aspect, uint32_t level,
5931                  uint32_t base_layer, uint32_t layer_count,
5932                  enum isl_aux_op hiz_op);
5933 void
5934 anv_image_hiz_clear(struct anv_cmd_buffer *cmd_buffer,
5935                     const struct anv_image *image,
5936                     VkImageAspectFlags aspects,
5937                     uint32_t level,
5938                     uint32_t base_layer, uint32_t layer_count,
5939                     VkRect2D area,
5940                     const VkClearDepthStencilValue *clear_value);
5941 void
5942 anv_image_mcs_op(struct anv_cmd_buffer *cmd_buffer,
5943                  const struct anv_image *image,
5944                  enum isl_format format, struct isl_swizzle swizzle,
5945                  VkImageAspectFlagBits aspect,
5946                  uint32_t base_layer, uint32_t layer_count,
5947                  enum isl_aux_op mcs_op, union isl_color_value *clear_value,
5948                  bool predicate);
5949 void
5950 anv_image_ccs_op(struct anv_cmd_buffer *cmd_buffer,
5951                  const struct anv_image *image,
5952                  enum isl_format format, struct isl_swizzle swizzle,
5953                  VkImageAspectFlagBits aspect, uint32_t level,
5954                  uint32_t base_layer, uint32_t layer_count,
5955                  enum isl_aux_op ccs_op, union isl_color_value *clear_value,
5956                  bool predicate);
5957 
5958 isl_surf_usage_flags_t
5959 anv_image_choose_isl_surf_usage(struct anv_physical_device *device,
5960                                 VkImageCreateFlags vk_create_flags,
5961                                 VkImageUsageFlags vk_usage,
5962                                 isl_surf_usage_flags_t isl_extra_usage,
5963                                 VkImageAspectFlagBits aspect,
5964                                 VkImageCompressionFlagsEXT comp_flags);
5965 
5966 void
5967 anv_cmd_copy_addr(struct anv_cmd_buffer *cmd_buffer,
5968                   struct anv_address src_addr,
5969                   struct anv_address dst_addr,
5970                   uint64_t size);
5971 void
5972 anv_cmd_buffer_fill_area(struct anv_cmd_buffer *cmd_buffer,
5973                          struct anv_address address,
5974                          VkDeviceSize size,
5975                          uint32_t data,
5976                          bool protected);
5977 void
5978 anv_cmd_fill_buffer_addr(VkCommandBuffer cmd_buffer,
5979                          VkDeviceAddress dstAddr,
5980                          VkDeviceSize size,
5981                          uint32_t data);
5982 void
5983 anv_cmd_buffer_update_addr(struct anv_cmd_buffer *cmd_buffer,
5984                            struct anv_address address,
5985                            VkDeviceSize dstOffset,
5986                            VkDeviceSize dataSize,
5987                            const void* pData,
5988                            bool is_protected);
5989 void
5990 anv_cmd_write_buffer_cp(VkCommandBuffer cmd_buffer,
5991                         VkDeviceAddress dstAddr,
5992                         void *data,
5993                         uint32_t size);
5994 void
5995 anv_cmd_dispatch_unaligned(VkCommandBuffer cmd_buffer,
5996                            uint32_t invocations_x,
5997                            uint32_t invocations_y,
5998                            uint32_t invocations_z);
5999 
6000 void
6001 anv_cmd_flush_buffer_write_cp(VkCommandBuffer cmd_buffer);
6002 
6003 VkResult
6004 anv_cmd_buffer_ensure_rcs_companion(struct anv_cmd_buffer *cmd_buffer);
6005 
6006 bool
6007 anv_can_hiz_clear_ds_view(struct anv_device *device,
6008                           const struct anv_image_view *iview,
6009                           VkImageLayout layout,
6010                           VkImageAspectFlags clear_aspects,
6011                           float depth_clear_value,
6012                           VkRect2D render_area,
6013                           const VkQueueFlagBits queue_flags);
6014 
6015 bool
6016 anv_can_fast_clear_color(const struct anv_cmd_buffer *cmd_buffer,
6017                          const struct anv_image *image,
6018                          unsigned level,
6019                          const struct VkClearRect *clear_rect,
6020                          VkImageLayout layout,
6021                          enum isl_format view_format,
6022                          union isl_color_value clear_color);
6023 
6024 enum isl_aux_state ATTRIBUTE_PURE
6025 anv_layout_to_aux_state(const struct intel_device_info * const devinfo,
6026                         const struct anv_image *image,
6027                         const VkImageAspectFlagBits aspect,
6028                         const VkImageLayout layout,
6029                         const VkQueueFlagBits queue_flags);
6030 
6031 enum isl_aux_usage ATTRIBUTE_PURE
6032 anv_layout_to_aux_usage(const struct intel_device_info * const devinfo,
6033                         const struct anv_image *image,
6034                         const VkImageAspectFlagBits aspect,
6035                         const VkImageUsageFlagBits usage,
6036                         const VkImageLayout layout,
6037                         const VkQueueFlagBits queue_flags);
6038 
6039 enum anv_fast_clear_type ATTRIBUTE_PURE
6040 anv_layout_to_fast_clear_type(const struct intel_device_info * const devinfo,
6041                               const struct anv_image * const image,
6042                               const VkImageAspectFlagBits aspect,
6043                               const VkImageLayout layout,
6044                               const VkQueueFlagBits queue_flags);
6045 
6046 bool ATTRIBUTE_PURE
6047 anv_layout_has_untracked_aux_writes(const struct intel_device_info * const devinfo,
6048                                     const struct anv_image * const image,
6049                                     const VkImageAspectFlagBits aspect,
6050                                     const VkImageLayout layout,
6051                                     const VkQueueFlagBits queue_flags);
6052 
6053 static inline bool
anv_image_aspects_compatible(VkImageAspectFlags aspects1,VkImageAspectFlags aspects2)6054 anv_image_aspects_compatible(VkImageAspectFlags aspects1,
6055                              VkImageAspectFlags aspects2)
6056 {
6057    if (aspects1 == aspects2)
6058       return true;
6059 
6060    /* Only 1 color aspects are compatibles. */
6061    if ((aspects1 & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) != 0 &&
6062        (aspects2 & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) != 0 &&
6063        util_bitcount(aspects1) == util_bitcount(aspects2))
6064       return true;
6065 
6066    return false;
6067 }
6068 
6069 struct anv_image_view {
6070    struct vk_image_view vk;
6071 
6072    const struct anv_image *image; /**< VkImageViewCreateInfo::image */
6073 
6074    unsigned n_planes;
6075 
6076    /**
6077     * True if the surface states (if any) are owned by some anv_state_stream
6078     * from internal_surface_state_pool.
6079     */
6080    bool use_surface_state_stream;
6081 
6082    struct {
6083       struct isl_view isl;
6084 
6085       /**
6086        * A version of the image view for storage usage (can apply 3D image
6087        * slicing).
6088        */
6089       struct isl_view isl_storage;
6090 
6091       /**
6092        * RENDER_SURFACE_STATE when using image as a sampler surface with an
6093        * image layout of SHADER_READ_ONLY_OPTIMAL or
6094        * DEPTH_STENCIL_READ_ONLY_OPTIMAL.
6095        */
6096       struct anv_surface_state optimal_sampler;
6097 
6098       /**
6099        * RENDER_SURFACE_STATE when using image as a sampler surface with an
6100        * image layout of GENERAL.
6101        */
6102       struct anv_surface_state general_sampler;
6103 
6104       /**
6105        * RENDER_SURFACE_STATE when using image as a storage image.
6106        */
6107       struct anv_surface_state storage;
6108    } planes[3];
6109 };
6110 
6111 enum anv_image_view_state_flags {
6112    ANV_IMAGE_VIEW_STATE_TEXTURE_OPTIMAL      = (1 << 0),
6113 };
6114 
6115 void anv_image_fill_surface_state(struct anv_device *device,
6116                                   const struct anv_image *image,
6117                                   VkImageAspectFlagBits aspect,
6118                                   const struct isl_view *view,
6119                                   isl_surf_usage_flags_t view_usage,
6120                                   enum isl_aux_usage aux_usage,
6121                                   const union isl_color_value *clear_color,
6122                                   enum anv_image_view_state_flags flags,
6123                                   struct anv_surface_state *state_inout);
6124 
6125 
6126 static inline const struct anv_surface_state *
anv_image_view_texture_surface_state(const struct anv_image_view * iview,uint32_t plane,VkImageLayout layout)6127 anv_image_view_texture_surface_state(const struct anv_image_view *iview,
6128                                      uint32_t plane, VkImageLayout layout)
6129 {
6130    return (layout == VK_IMAGE_LAYOUT_GENERAL ||
6131            layout == VK_IMAGE_LAYOUT_RENDERING_LOCAL_READ_KHR) ?
6132           &iview->planes[plane].general_sampler :
6133           &iview->planes[plane].optimal_sampler;
6134 }
6135 
6136 static inline const struct anv_surface_state *
anv_image_view_storage_surface_state(const struct anv_image_view * iview)6137 anv_image_view_storage_surface_state(const struct anv_image_view *iview)
6138 {
6139    return &iview->planes[0].storage;
6140 }
6141 
6142 static inline bool
anv_cmd_graphics_state_has_image_as_attachment(const struct anv_cmd_graphics_state * state,const struct anv_image * image)6143 anv_cmd_graphics_state_has_image_as_attachment(const struct anv_cmd_graphics_state *state,
6144                                                const struct anv_image *image)
6145 {
6146    for (unsigned a = 0; a < state->color_att_count; a++) {
6147       if (state->color_att[a].iview &&
6148           state->color_att[a].iview->image == image)
6149          return true;
6150    }
6151 
6152    if (state->depth_att.iview && state->depth_att.iview->image == image)
6153       return true;
6154    if (state->stencil_att.iview && state->stencil_att.iview->image == image)
6155       return true;
6156 
6157    return false;
6158 }
6159 
6160 struct anv_image_create_info {
6161    const VkImageCreateInfo *vk_info;
6162 
6163    /** An opt-in bitmask which filters an ISL-mapping of the Vulkan tiling. */
6164    isl_tiling_flags_t isl_tiling_flags;
6165 
6166    /** These flags will be added to any derived from VkImageCreateInfo. */
6167    isl_surf_usage_flags_t isl_extra_usage_flags;
6168 
6169    /** An opt-in stride in pixels, should be 0 for implicit layouts */
6170    uint32_t stride;
6171 
6172    /** Whether to allocate private binding */
6173    bool no_private_binding_alloc;
6174 };
6175 
6176 VkResult anv_image_init(struct anv_device *device, struct anv_image *image,
6177                         const struct anv_image_create_info *create_info);
6178 
6179 void anv_image_finish(struct anv_image *image);
6180 
6181 void anv_image_get_memory_requirements(struct anv_device *device,
6182                                        struct anv_image *image,
6183                                        VkImageAspectFlags aspects,
6184                                        VkMemoryRequirements2 *pMemoryRequirements);
6185 
6186 void anv_image_view_init(struct anv_device *device,
6187                          struct anv_image_view *iview,
6188                          const VkImageViewCreateInfo *pCreateInfo,
6189                          struct anv_state_stream *state_stream);
6190 
6191 void anv_image_view_finish(struct anv_image_view *iview);
6192 
6193 enum isl_format
6194 anv_isl_format_for_descriptor_type(const struct anv_device *device,
6195                                    VkDescriptorType type);
6196 
6197 static inline isl_surf_usage_flags_t
anv_isl_usage_for_descriptor_type(const VkDescriptorType type)6198 anv_isl_usage_for_descriptor_type(const VkDescriptorType type)
6199 {
6200    switch(type) {
6201       case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
6202       case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
6203          return ISL_SURF_USAGE_CONSTANT_BUFFER_BIT;
6204       default:
6205          return ISL_SURF_USAGE_STORAGE_BIT;
6206    }
6207 }
6208 
6209 VkFormatFeatureFlags2
6210 anv_get_image_format_features2(const struct anv_physical_device *physical_device,
6211                                VkFormat vk_format,
6212                                const struct anv_format *anv_format,
6213                                VkImageTiling vk_tiling,
6214                                const struct isl_drm_modifier_info *isl_mod_info);
6215 
6216 void anv_fill_buffer_surface_state(struct anv_device *device,
6217                                    void *surface_state_ptr,
6218                                    enum isl_format format,
6219                                    struct isl_swizzle swizzle,
6220                                    isl_surf_usage_flags_t usage,
6221                                    struct anv_address address,
6222                                    uint32_t range, uint32_t stride);
6223 
6224 
6225 struct gfx8_border_color {
6226    union {
6227       float float32[4];
6228       uint32_t uint32[4];
6229    };
6230    /* Pad out to 64 bytes */
6231    uint32_t _pad[12];
6232 };
6233 
6234 struct anv_sampler {
6235    struct vk_sampler            vk;
6236 
6237    /* Hash of the sampler state + border color, useful for embedded samplers
6238     * and included in the descriptor layout hash.
6239     */
6240    unsigned char                sha1[20];
6241 
6242    uint32_t                     state[3][4];
6243    /* Packed SAMPLER_STATE without the border color pointer. */
6244    uint32_t                     state_no_bc[3][4];
6245    uint32_t                     n_planes;
6246 
6247    /* Blob of sampler state data which is guaranteed to be 32-byte aligned
6248     * and with a 32-byte stride for use as bindless samplers.
6249     */
6250    struct anv_state             bindless_state;
6251 
6252    struct anv_state             custom_border_color;
6253 };
6254 
6255 
6256 struct anv_query_pool {
6257    struct vk_query_pool                         vk;
6258 
6259    /** Stride between queries, in bytes */
6260    uint32_t                                     stride;
6261    /** Number of slots in this query pool */
6262    struct anv_bo *                              bo;
6263 
6264    /** Location for the KHR_performance_query small batch updating
6265     *  ANV_PERF_QUERY_OFFSET_REG
6266     */
6267    uint32_t                                     khr_perf_preambles_offset;
6268 
6269    /** Size of each small batch */
6270    uint32_t                                     khr_perf_preamble_stride;
6271 
6272    /* KHR perf queries : */
6273    /** Query pass size in bytes(availability + padding + query data) */
6274    uint32_t                                     pass_size;
6275    /** Offset of the query data within a pass */
6276    uint32_t                                     data_offset;
6277    /** query data / 2 */
6278    uint32_t                                     snapshot_size;
6279    uint32_t                                     n_counters;
6280    struct intel_perf_counter_pass                *counter_pass;
6281    uint32_t                                     n_passes;
6282    struct intel_perf_query_info                 **pass_query;
6283 
6284    /* Video encoding queries */
6285    VkVideoCodecOperationFlagsKHR                codec;
6286 };
6287 
khr_perf_query_preamble_offset(const struct anv_query_pool * pool,uint32_t pass)6288 static inline uint32_t khr_perf_query_preamble_offset(const struct anv_query_pool *pool,
6289                                                       uint32_t pass)
6290 {
6291    return pool->khr_perf_preambles_offset +
6292           pool->khr_perf_preamble_stride * pass;
6293 }
6294 
6295 struct anv_vid_mem {
6296    struct anv_device_memory *mem;
6297    VkDeviceSize       offset;
6298    VkDeviceSize       size;
6299 };
6300 
6301 #define ANV_MB_WIDTH 16
6302 #define ANV_MB_HEIGHT 16
6303 #define ANV_VIDEO_H264_MAX_DPB_SLOTS 17
6304 #define ANV_VIDEO_H264_MAX_NUM_REF_FRAME 16
6305 #define ANV_VIDEO_H265_MAX_NUM_REF_FRAME 16
6306 #define ANV_VIDEO_H265_HCP_NUM_REF_FRAME 8
6307 #define ANV_MAX_H265_CTB_SIZE 64
6308 
6309 enum anv_vid_mem_h264_types {
6310    ANV_VID_MEM_H264_INTRA_ROW_STORE,
6311    ANV_VID_MEM_H264_DEBLOCK_FILTER_ROW_STORE,
6312    ANV_VID_MEM_H264_BSD_MPC_ROW_SCRATCH,
6313    ANV_VID_MEM_H264_MPR_ROW_SCRATCH,
6314    ANV_VID_MEM_H264_MAX,
6315 };
6316 
6317 enum anv_vid_mem_h265_types {
6318    ANV_VID_MEM_H265_DEBLOCK_FILTER_ROW_STORE_LINE,
6319    ANV_VID_MEM_H265_DEBLOCK_FILTER_ROW_STORE_TILE_LINE,
6320    ANV_VID_MEM_H265_DEBLOCK_FILTER_ROW_STORE_TILE_COLUMN,
6321    ANV_VID_MEM_H265_METADATA_LINE,
6322    ANV_VID_MEM_H265_METADATA_TILE_LINE,
6323    ANV_VID_MEM_H265_METADATA_TILE_COLUMN,
6324    ANV_VID_MEM_H265_SAO_LINE,
6325    ANV_VID_MEM_H265_SAO_TILE_LINE,
6326    ANV_VID_MEM_H265_SAO_TILE_COLUMN,
6327    ANV_VID_MEM_H265_DEC_MAX,
6328    ANV_VID_MEM_H265_SSE_SRC_PIX_ROW_STORE = ANV_VID_MEM_H265_DEC_MAX,
6329    ANV_VID_MEM_H265_ENC_MAX,
6330 };
6331 
6332 enum anv_vid_mem_av1_types {
6333    ANV_VID_MEM_AV1_BITSTREAM_LINE_ROWSTORE,
6334    ANV_VID_MEM_AV1_BITSTREAM_TILE_LINE_ROWSTORE,
6335    ANV_VID_MEM_AV1_INTRA_PREDICTION_LINE_ROWSTORE,
6336    ANV_VID_MEM_AV1_INTRA_PREDICTION_TILE_LINE_ROWSTORE,
6337    ANV_VID_MEM_AV1_SPATIAL_MOTION_VECTOR_LINE,
6338    ANV_VID_MEM_AV1_SPATIAL_MOTION_VECTOR_TILE_LINE,
6339    ANV_VID_MEM_AV1_LOOP_RESTORATION_META_TILE_COLUMN,
6340    ANV_VID_MEM_AV1_LOOP_RESTORATION_FILTER_TILE_LINE_Y,
6341    ANV_VID_MEM_AV1_LOOP_RESTORATION_FILTER_TILE_LINE_U,
6342    ANV_VID_MEM_AV1_LOOP_RESTORATION_FILTER_TILE_LINE_V,
6343    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_LINE_Y,
6344    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_LINE_U,
6345    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_LINE_V,
6346    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_TILE_LINE_Y,
6347    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_TILE_LINE_U,
6348    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_TILE_LINE_V,
6349    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_TILE_COLUMN_Y,
6350    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_TILE_COLUMN_U,
6351    ANV_VID_MEM_AV1_DEBLOCKER_FILTER_TILE_COLUMN_V,
6352    ANV_VID_MEM_AV1_CDEF_FILTER_LINE,
6353    ANV_VID_MEM_AV1_CDEF_FILTER_TILE_LINE,
6354    ANV_VID_MEM_AV1_CDEF_FILTER_TILE_COLUMN,
6355    ANV_VID_MEM_AV1_CDEF_FILTER_META_TILE_LINE,
6356    ANV_VID_MEM_AV1_CDEF_FILTER_META_TILE_COLUMN,
6357    ANV_VID_MEM_AV1_CDEF_FILTER_TOP_LEFT_CORNER,
6358    ANV_VID_MEM_AV1_SUPER_RES_TILE_COLUMN_Y,
6359    ANV_VID_MEM_AV1_SUPER_RES_TILE_COLUMN_U,
6360    ANV_VID_MEM_AV1_SUPER_RES_TILE_COLUMN_V,
6361    ANV_VID_MEM_AV1_LOOP_RESTORATION_FILTER_TILE_COLUMN_Y,
6362    ANV_VID_MEM_AV1_LOOP_RESTORATION_FILTER_TILE_COLUMN_U,
6363    ANV_VID_MEM_AV1_LOOP_RESTORATION_FILTER_TILE_COLUMN_V,
6364    ANV_VID_MEM_AV1_CDF_DEFAULTS_0,
6365    ANV_VID_MEM_AV1_CDF_DEFAULTS_1,
6366    ANV_VID_MEM_AV1_CDF_DEFAULTS_2,
6367    ANV_VID_MEM_AV1_CDF_DEFAULTS_3,
6368    ANV_VID_MEM_AV1_DBD_BUFFER,
6369    ANV_VID_MEM_AV1_MAX,
6370 };
6371 
6372 struct anv_av1_video_refs_info {
6373    const struct anv_image *img;
6374    uint8_t default_cdf_index;
6375 };
6376 
6377 struct anv_video_session {
6378    struct vk_video_session vk;
6379 
6380    bool cdf_initialized;
6381    /* the decoder needs some private memory allocations */
6382    struct anv_vid_mem vid_mem[ANV_VID_MEM_AV1_MAX];
6383    struct anv_av1_video_refs_info prev_refs[STD_VIDEO_AV1_NUM_REF_FRAMES];
6384 };
6385 
6386 struct anv_video_session_params {
6387    struct vk_video_session_parameters vk;
6388    VkVideoEncodeRateControlModeFlagBitsKHR rc_mode;
6389 };
6390 
6391 void anv_init_av1_cdf_tables(struct anv_cmd_buffer *cmd,
6392                              struct anv_video_session *vid);
6393 
6394 uint32_t anv_video_get_image_mv_size(struct anv_device *device,
6395                                      struct anv_image *image,
6396                                      const struct VkVideoProfileListInfoKHR *profile_list);
6397 
6398 void
6399 anv_dump_pipe_bits(enum anv_pipe_bits bits, FILE *f);
6400 
6401 void
6402 anv_cmd_buffer_pending_pipe_debug(struct anv_cmd_buffer *cmd_buffer,
6403                                   enum anv_pipe_bits bits,
6404                                   const char* reason);
6405 
6406 static inline void
anv_add_pending_pipe_bits(struct anv_cmd_buffer * cmd_buffer,enum anv_pipe_bits bits,const char * reason)6407 anv_add_pending_pipe_bits(struct anv_cmd_buffer* cmd_buffer,
6408                           enum anv_pipe_bits bits,
6409                           const char* reason)
6410 {
6411    cmd_buffer->state.pending_pipe_bits |= bits;
6412    if (INTEL_DEBUG(DEBUG_PIPE_CONTROL)) {
6413       anv_cmd_buffer_pending_pipe_debug(cmd_buffer, bits, reason);
6414    }
6415 }
6416 
6417 struct anv_performance_configuration_intel {
6418    struct vk_object_base      base;
6419 
6420    struct intel_perf_registers *register_config;
6421 
6422    uint64_t                   config_id;
6423 };
6424 
6425 void anv_physical_device_init_va_ranges(struct anv_physical_device *device);
6426 void anv_physical_device_init_perf(struct anv_physical_device *device, int fd);
6427 void anv_device_perf_init(struct anv_device *device);
6428 void anv_device_perf_close(struct anv_device *device);
6429 void anv_perf_write_pass_results(struct intel_perf_config *perf,
6430                                  struct anv_query_pool *pool, uint32_t pass,
6431                                  const struct intel_perf_query_result *accumulated_results,
6432                                  union VkPerformanceCounterResultKHR *results);
6433 
6434 void anv_apply_per_prim_attr_wa(struct nir_shader *ms_nir,
6435                                 struct nir_shader *fs_nir,
6436                                 struct anv_device *device,
6437                                 const VkGraphicsPipelineCreateInfo *info);
6438 
6439 /* Use to emit a series of memcpy operations */
6440 struct anv_memcpy_state {
6441    struct anv_device *device;
6442    struct anv_cmd_buffer *cmd_buffer;
6443    struct anv_batch *batch;
6444 
6445    /* Configuration programmed by the memcpy operation */
6446    struct intel_urb_config urb_cfg;
6447 
6448    struct anv_vb_cache_range vb_bound;
6449    struct anv_vb_cache_range vb_dirty;
6450 };
6451 
6452 VkResult anv_device_init_internal_kernels(struct anv_device *device);
6453 void anv_device_finish_internal_kernels(struct anv_device *device);
6454 VkResult anv_device_get_internal_shader(struct anv_device *device,
6455                                         enum anv_internal_kernel_name name,
6456                                         struct anv_shader_bin **out_bin);
6457 
6458 VkResult anv_device_init_astc_emu(struct anv_device *device);
6459 void anv_device_finish_astc_emu(struct anv_device *device);
6460 void anv_astc_emu_process(struct anv_cmd_buffer *cmd_buffer,
6461                           struct anv_image *image,
6462                           VkImageLayout layout,
6463                           const VkImageSubresourceLayers *subresource,
6464                           VkOffset3D block_offset,
6465                           VkExtent3D block_extent);
6466 
6467 /* This structure is used in 2 scenarios :
6468  *
6469  *    - copy utrace timestamps from command buffer so that command buffer can
6470  *      be resubmitted multiple times without the recorded timestamps being
6471  *      overwritten before they're read back
6472  *
6473  *    - emit trace points for queue debug tagging
6474  *      (vkQueueBeginDebugUtilsLabelEXT/vkQueueEndDebugUtilsLabelEXT)
6475  */
6476 struct anv_utrace_submit {
6477    struct anv_async_submit base;
6478 
6479    /* structure used by the perfetto glue */
6480    struct intel_ds_flush_data ds;
6481 
6482    /* Stream for temporary allocations */
6483    struct anv_state_stream dynamic_state_stream;
6484    struct anv_state_stream general_state_stream;
6485 
6486    /* Last fully read 64bit timestamp (used to rebuild the upper bits of 32bit
6487     * timestamps)
6488     */
6489    uint64_t last_full_timestamp;
6490 
6491    /* Memcpy state tracking (only used for timestamp copies on render engine) */
6492    struct anv_memcpy_state memcpy_state;
6493 
6494    /* Memcpy state tracking (only used for timestamp copies on compute engine) */
6495    struct anv_simple_shader simple_state;
6496 };
6497 
6498 void anv_device_utrace_init(struct anv_device *device);
6499 void anv_device_utrace_finish(struct anv_device *device);
6500 VkResult
6501 anv_device_utrace_flush_cmd_buffers(struct anv_queue *queue,
6502                                     uint32_t cmd_buffer_count,
6503                                     struct anv_cmd_buffer **cmd_buffers,
6504                                     struct anv_utrace_submit **out_submit);
6505 
6506 void
6507 anv_device_utrace_emit_gfx_copy_buffer(struct u_trace_context *utctx,
6508                                        void *cmdstream,
6509                                        void *ts_from, uint64_t from_offset_B,
6510                                        void *ts_to, uint64_t to_offset_B,
6511                                        uint64_t size_B);
6512 
6513 static bool
anv_has_cooperative_matrix(const struct anv_physical_device * device)6514 anv_has_cooperative_matrix(const struct anv_physical_device *device)
6515 {
6516    return device->has_cooperative_matrix;
6517 }
6518 
6519 #define ANV_FROM_HANDLE(__anv_type, __name, __handle) \
6520    VK_FROM_HANDLE(__anv_type, __name, __handle)
6521 
6522 VK_DEFINE_HANDLE_CASTS(anv_cmd_buffer, vk.base, VkCommandBuffer,
6523                        VK_OBJECT_TYPE_COMMAND_BUFFER)
6524 VK_DEFINE_HANDLE_CASTS(anv_device, vk.base, VkDevice, VK_OBJECT_TYPE_DEVICE)
6525 VK_DEFINE_HANDLE_CASTS(anv_instance, vk.base, VkInstance, VK_OBJECT_TYPE_INSTANCE)
6526 VK_DEFINE_HANDLE_CASTS(anv_physical_device, vk.base, VkPhysicalDevice,
6527                        VK_OBJECT_TYPE_PHYSICAL_DEVICE)
6528 VK_DEFINE_HANDLE_CASTS(anv_queue, vk.base, VkQueue, VK_OBJECT_TYPE_QUEUE)
6529 
6530 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer, vk.base, VkBuffer,
6531                                VK_OBJECT_TYPE_BUFFER)
6532 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_buffer_view, vk.base, VkBufferView,
6533                                VK_OBJECT_TYPE_BUFFER_VIEW)
6534 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_pool, base, VkDescriptorPool,
6535                                VK_OBJECT_TYPE_DESCRIPTOR_POOL)
6536 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set, base, VkDescriptorSet,
6537                                VK_OBJECT_TYPE_DESCRIPTOR_SET)
6538 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_descriptor_set_layout, base,
6539                                VkDescriptorSetLayout,
6540                                VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT)
6541 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_device_memory, vk.base, VkDeviceMemory,
6542                                VK_OBJECT_TYPE_DEVICE_MEMORY)
6543 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_event, base, VkEvent, VK_OBJECT_TYPE_EVENT)
6544 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_image, vk.base, VkImage, VK_OBJECT_TYPE_IMAGE)
6545 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_image_view, vk.base, VkImageView,
6546                                VK_OBJECT_TYPE_IMAGE_VIEW);
6547 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline, base, VkPipeline,
6548                                VK_OBJECT_TYPE_PIPELINE)
6549 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_pipeline_layout, base, VkPipelineLayout,
6550                                VK_OBJECT_TYPE_PIPELINE_LAYOUT)
6551 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_query_pool, vk.base, VkQueryPool,
6552                                VK_OBJECT_TYPE_QUERY_POOL)
6553 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_sampler, vk.base, VkSampler,
6554                                VK_OBJECT_TYPE_SAMPLER)
6555 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_performance_configuration_intel, base,
6556                                VkPerformanceConfigurationINTEL,
6557                                VK_OBJECT_TYPE_PERFORMANCE_CONFIGURATION_INTEL)
6558 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_video_session, vk.base,
6559                                VkVideoSessionKHR,
6560                                VK_OBJECT_TYPE_VIDEO_SESSION_KHR)
6561 VK_DEFINE_NONDISP_HANDLE_CASTS(anv_video_session_params, vk.base,
6562                                VkVideoSessionParametersKHR,
6563                                VK_OBJECT_TYPE_VIDEO_SESSION_PARAMETERS_KHR)
6564 
6565 #define anv_genX(devinfo, thing) ({             \
6566    __typeof(&gfx9_##thing) genX_thing;          \
6567    switch ((devinfo)->verx10) {                 \
6568    case 90:                                     \
6569       genX_thing = &gfx9_##thing;               \
6570       break;                                    \
6571    case 110:                                    \
6572       genX_thing = &gfx11_##thing;              \
6573       break;                                    \
6574    case 120:                                    \
6575       genX_thing = &gfx12_##thing;              \
6576       break;                                    \
6577    case 125:                                    \
6578       genX_thing = &gfx125_##thing;             \
6579       break;                                    \
6580    case 200:                                    \
6581       genX_thing = &gfx20_##thing;              \
6582       break;                                    \
6583    case 300:                                    \
6584       genX_thing = &gfx30_##thing;              \
6585       break;                                    \
6586    default:                                     \
6587       unreachable("Unknown hardware generation"); \
6588    }                                            \
6589    genX_thing;                                  \
6590 })
6591 
6592 /* Gen-specific function declarations */
6593 #ifdef genX
6594 #  include "anv_genX.h"
6595 #else
6596 #  define genX(x) gfx9_##x
6597 #  include "anv_genX.h"
6598 #  undef genX
6599 #  define genX(x) gfx11_##x
6600 #  include "anv_genX.h"
6601 #  undef genX
6602 #  define genX(x) gfx12_##x
6603 #  include "anv_genX.h"
6604 #  undef genX
6605 #  define genX(x) gfx125_##x
6606 #  include "anv_genX.h"
6607 #  undef genX
6608 #  define genX(x) gfx20_##x
6609 #  include "anv_genX.h"
6610 #  undef genX
6611 #  define genX(x) gfx30_##x
6612 #  include "anv_genX.h"
6613 #  undef genX
6614 #endif
6615 
6616 #ifdef __cplusplus
6617 }
6618 #endif
6619 
6620 #endif /* ANV_PRIVATE_H */
6621