• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2017 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 shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20  * DEALINGS IN THE SOFTWARE.
21  */
22 
23 /**
24  * @file iris_state.c
25  *
26  * ============================= GENXML CODE =============================
27  *              [This file is compiled once per generation.]
28  * =======================================================================
29  *
30  * This is the main state upload code.
31  *
32  * Gallium uses Constant State Objects, or CSOs, for most state.  Large,
33  * complex, or highly reusable state can be created once, and bound and
34  * rebound multiple times.  This is modeled with the pipe->create_*_state()
35  * and pipe->bind_*_state() hooks.  Highly dynamic or inexpensive state is
36  * streamed out on the fly, via pipe->set_*_state() hooks.
37  *
38  * OpenGL involves frequently mutating context state, which is mirrored in
39  * core Mesa by highly mutable data structures.  However, most applications
40  * typically draw the same things over and over - from frame to frame, most
41  * of the same objects are still visible and need to be redrawn.  So, rather
42  * than inventing new state all the time, applications usually mutate to swap
43  * between known states that we've seen before.
44  *
45  * Gallium isolates us from this mutation by tracking API state, and
46  * distilling it into a set of Constant State Objects, or CSOs.  Large,
47  * complex, or typically reusable state can be created once, then reused
48  * multiple times.  Drivers can create and store their own associated data.
49  * This create/bind model corresponds to the pipe->create_*_state() and
50  * pipe->bind_*_state() driver hooks.
51  *
52  * Some state is cheap to create, or expected to be highly dynamic.  Rather
53  * than creating and caching piles of CSOs for these, Gallium simply streams
54  * them out, via the pipe->set_*_state() driver hooks.
55  *
56  * To reduce draw time overhead, we try to compute as much state at create
57  * time as possible.  Wherever possible, we translate the Gallium pipe state
58  * to 3DSTATE commands, and store those commands in the CSO.  At draw time,
59  * we can simply memcpy them into a batch buffer.
60  *
61  * No hardware matches the abstraction perfectly, so some commands require
62  * information from multiple CSOs.  In this case, we can store two copies
63  * of the packet (one in each CSO), and simply | together their DWords at
64  * draw time.  Sometimes the second set is trivial (one or two fields), so
65  * we simply pack it at draw time.
66  *
67  * There are two main components in the file below.  First, the CSO hooks
68  * create/bind/track state.  The second are the draw-time upload functions,
69  * iris_upload_render_state() and iris_upload_compute_state(), which read
70  * the context state and emit the commands into the actual batch.
71  */
72 
73 #include <stdio.h>
74 #include <errno.h>
75 
76 #ifdef HAVE_VALGRIND
77 #include <valgrind.h>
78 #include <memcheck.h>
79 #define VG(x) x
80 #else
81 #define VG(x)
82 #endif
83 
84 #include "pipe/p_defines.h"
85 #include "pipe/p_state.h"
86 #include "pipe/p_context.h"
87 #include "pipe/p_screen.h"
88 #include "util/u_dual_blend.h"
89 #include "util/u_inlines.h"
90 #include "util/format/u_format.h"
91 #include "util/u_framebuffer.h"
92 #include "util/u_transfer.h"
93 #include "util/u_upload_mgr.h"
94 #include "util/u_viewport.h"
95 #include "util/u_memory.h"
96 #include "util/u_trace_gallium.h"
97 #include "nir.h"
98 #include "intel/common/intel_aux_map.h"
99 #include "intel/common/intel_l3_config.h"
100 #include "intel/common/intel_sample_positions.h"
101 #include "intel/ds/intel_tracepoints.h"
102 #include "iris_batch.h"
103 #include "iris_context.h"
104 #include "iris_defines.h"
105 #include "iris_pipe.h"
106 #include "iris_resource.h"
107 #include "iris_utrace.h"
108 
109 #include "iris_genx_macros.h"
110 
111 #if GFX_VER >= 9
112 #include "intel/compiler/brw_compiler.h"
113 #include "intel/common/intel_genX_state_brw.h"
114 #else
115 #include "intel/compiler/elk/elk_compiler.h"
116 #include "intel/common/intel_genX_state_elk.h"
117 #endif
118 
119 #include "intel/common/intel_guardband.h"
120 #include "intel/common/intel_pixel_hash.h"
121 #include "intel/common/intel_tiled_render.h"
122 
123 /**
124  * Statically assert that PIPE_* enums match the hardware packets.
125  * (As long as they match, we don't need to translate them.)
126  */
pipe_asserts()127 UNUSED static void pipe_asserts()
128 {
129 #define PIPE_ASSERT(x) STATIC_ASSERT((int)x)
130 
131    /* pipe_logicop happens to match the hardware. */
132    PIPE_ASSERT(PIPE_LOGICOP_CLEAR == LOGICOP_CLEAR);
133    PIPE_ASSERT(PIPE_LOGICOP_NOR == LOGICOP_NOR);
134    PIPE_ASSERT(PIPE_LOGICOP_AND_INVERTED == LOGICOP_AND_INVERTED);
135    PIPE_ASSERT(PIPE_LOGICOP_COPY_INVERTED == LOGICOP_COPY_INVERTED);
136    PIPE_ASSERT(PIPE_LOGICOP_AND_REVERSE == LOGICOP_AND_REVERSE);
137    PIPE_ASSERT(PIPE_LOGICOP_INVERT == LOGICOP_INVERT);
138    PIPE_ASSERT(PIPE_LOGICOP_XOR == LOGICOP_XOR);
139    PIPE_ASSERT(PIPE_LOGICOP_NAND == LOGICOP_NAND);
140    PIPE_ASSERT(PIPE_LOGICOP_AND == LOGICOP_AND);
141    PIPE_ASSERT(PIPE_LOGICOP_EQUIV == LOGICOP_EQUIV);
142    PIPE_ASSERT(PIPE_LOGICOP_NOOP == LOGICOP_NOOP);
143    PIPE_ASSERT(PIPE_LOGICOP_OR_INVERTED == LOGICOP_OR_INVERTED);
144    PIPE_ASSERT(PIPE_LOGICOP_COPY == LOGICOP_COPY);
145    PIPE_ASSERT(PIPE_LOGICOP_OR_REVERSE == LOGICOP_OR_REVERSE);
146    PIPE_ASSERT(PIPE_LOGICOP_OR == LOGICOP_OR);
147    PIPE_ASSERT(PIPE_LOGICOP_SET == LOGICOP_SET);
148 
149    /* pipe_blend_func happens to match the hardware. */
150    PIPE_ASSERT(PIPE_BLENDFACTOR_ONE == BLENDFACTOR_ONE);
151    PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_COLOR == BLENDFACTOR_SRC_COLOR);
152    PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA == BLENDFACTOR_SRC_ALPHA);
153    PIPE_ASSERT(PIPE_BLENDFACTOR_DST_ALPHA == BLENDFACTOR_DST_ALPHA);
154    PIPE_ASSERT(PIPE_BLENDFACTOR_DST_COLOR == BLENDFACTOR_DST_COLOR);
155    PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE == BLENDFACTOR_SRC_ALPHA_SATURATE);
156    PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_COLOR == BLENDFACTOR_CONST_COLOR);
157    PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_ALPHA == BLENDFACTOR_CONST_ALPHA);
158    PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_COLOR == BLENDFACTOR_SRC1_COLOR);
159    PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_ALPHA == BLENDFACTOR_SRC1_ALPHA);
160    PIPE_ASSERT(PIPE_BLENDFACTOR_ZERO == BLENDFACTOR_ZERO);
161    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_COLOR == BLENDFACTOR_INV_SRC_COLOR);
162    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_ALPHA == BLENDFACTOR_INV_SRC_ALPHA);
163    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_ALPHA == BLENDFACTOR_INV_DST_ALPHA);
164    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_COLOR == BLENDFACTOR_INV_DST_COLOR);
165    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_COLOR == BLENDFACTOR_INV_CONST_COLOR);
166    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_ALPHA == BLENDFACTOR_INV_CONST_ALPHA);
167    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_COLOR == BLENDFACTOR_INV_SRC1_COLOR);
168    PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_ALPHA == BLENDFACTOR_INV_SRC1_ALPHA);
169 
170    /* pipe_blend_func happens to match the hardware. */
171    PIPE_ASSERT(PIPE_BLEND_ADD == BLENDFUNCTION_ADD);
172    PIPE_ASSERT(PIPE_BLEND_SUBTRACT == BLENDFUNCTION_SUBTRACT);
173    PIPE_ASSERT(PIPE_BLEND_REVERSE_SUBTRACT == BLENDFUNCTION_REVERSE_SUBTRACT);
174    PIPE_ASSERT(PIPE_BLEND_MIN == BLENDFUNCTION_MIN);
175    PIPE_ASSERT(PIPE_BLEND_MAX == BLENDFUNCTION_MAX);
176 
177    /* pipe_stencil_op happens to match the hardware. */
178    PIPE_ASSERT(PIPE_STENCIL_OP_KEEP == STENCILOP_KEEP);
179    PIPE_ASSERT(PIPE_STENCIL_OP_ZERO == STENCILOP_ZERO);
180    PIPE_ASSERT(PIPE_STENCIL_OP_REPLACE == STENCILOP_REPLACE);
181    PIPE_ASSERT(PIPE_STENCIL_OP_INCR == STENCILOP_INCRSAT);
182    PIPE_ASSERT(PIPE_STENCIL_OP_DECR == STENCILOP_DECRSAT);
183    PIPE_ASSERT(PIPE_STENCIL_OP_INCR_WRAP == STENCILOP_INCR);
184    PIPE_ASSERT(PIPE_STENCIL_OP_DECR_WRAP == STENCILOP_DECR);
185    PIPE_ASSERT(PIPE_STENCIL_OP_INVERT == STENCILOP_INVERT);
186 
187    /* pipe_sprite_coord_mode happens to match 3DSTATE_SBE */
188    PIPE_ASSERT(PIPE_SPRITE_COORD_UPPER_LEFT == UPPERLEFT);
189    PIPE_ASSERT(PIPE_SPRITE_COORD_LOWER_LEFT == LOWERLEFT);
190 #undef PIPE_ASSERT
191 }
192 
193 static unsigned
translate_prim_type(enum mesa_prim prim,uint8_t verts_per_patch)194 translate_prim_type(enum mesa_prim prim, uint8_t verts_per_patch)
195 {
196    static const unsigned map[] = {
197       [MESA_PRIM_POINTS]                   = _3DPRIM_POINTLIST,
198       [MESA_PRIM_LINES]                    = _3DPRIM_LINELIST,
199       [MESA_PRIM_LINE_LOOP]                = _3DPRIM_LINELOOP,
200       [MESA_PRIM_LINE_STRIP]               = _3DPRIM_LINESTRIP,
201       [MESA_PRIM_TRIANGLES]                = _3DPRIM_TRILIST,
202       [MESA_PRIM_TRIANGLE_STRIP]           = _3DPRIM_TRISTRIP,
203       [MESA_PRIM_TRIANGLE_FAN]             = _3DPRIM_TRIFAN,
204       [MESA_PRIM_QUADS]                    = _3DPRIM_QUADLIST,
205       [MESA_PRIM_QUAD_STRIP]               = _3DPRIM_QUADSTRIP,
206       [MESA_PRIM_POLYGON]                  = _3DPRIM_POLYGON,
207       [MESA_PRIM_LINES_ADJACENCY]          = _3DPRIM_LINELIST_ADJ,
208       [MESA_PRIM_LINE_STRIP_ADJACENCY]     = _3DPRIM_LINESTRIP_ADJ,
209       [MESA_PRIM_TRIANGLES_ADJACENCY]      = _3DPRIM_TRILIST_ADJ,
210       [MESA_PRIM_TRIANGLE_STRIP_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
211       [MESA_PRIM_PATCHES]                  = _3DPRIM_PATCHLIST_1 - 1,
212    };
213 
214    return map[prim] + (prim == MESA_PRIM_PATCHES ? verts_per_patch : 0);
215 }
216 
217 static unsigned
translate_compare_func(enum pipe_compare_func pipe_func)218 translate_compare_func(enum pipe_compare_func pipe_func)
219 {
220    static const unsigned map[] = {
221       [PIPE_FUNC_NEVER]    = COMPAREFUNCTION_NEVER,
222       [PIPE_FUNC_LESS]     = COMPAREFUNCTION_LESS,
223       [PIPE_FUNC_EQUAL]    = COMPAREFUNCTION_EQUAL,
224       [PIPE_FUNC_LEQUAL]   = COMPAREFUNCTION_LEQUAL,
225       [PIPE_FUNC_GREATER]  = COMPAREFUNCTION_GREATER,
226       [PIPE_FUNC_NOTEQUAL] = COMPAREFUNCTION_NOTEQUAL,
227       [PIPE_FUNC_GEQUAL]   = COMPAREFUNCTION_GEQUAL,
228       [PIPE_FUNC_ALWAYS]   = COMPAREFUNCTION_ALWAYS,
229    };
230    return map[pipe_func];
231 }
232 
233 static unsigned
translate_shadow_func(enum pipe_compare_func pipe_func)234 translate_shadow_func(enum pipe_compare_func pipe_func)
235 {
236    /* Gallium specifies the result of shadow comparisons as:
237     *
238     *    1 if ref <op> texel,
239     *    0 otherwise.
240     *
241     * The hardware does:
242     *
243     *    0 if texel <op> ref,
244     *    1 otherwise.
245     *
246     * So we need to flip the operator and also negate.
247     */
248    static const unsigned map[] = {
249       [PIPE_FUNC_NEVER]    = PREFILTEROP_ALWAYS,
250       [PIPE_FUNC_LESS]     = PREFILTEROP_LEQUAL,
251       [PIPE_FUNC_EQUAL]    = PREFILTEROP_NOTEQUAL,
252       [PIPE_FUNC_LEQUAL]   = PREFILTEROP_LESS,
253       [PIPE_FUNC_GREATER]  = PREFILTEROP_GEQUAL,
254       [PIPE_FUNC_NOTEQUAL] = PREFILTEROP_EQUAL,
255       [PIPE_FUNC_GEQUAL]   = PREFILTEROP_GREATER,
256       [PIPE_FUNC_ALWAYS]   = PREFILTEROP_NEVER,
257    };
258    return map[pipe_func];
259 }
260 
261 static unsigned
translate_cull_mode(unsigned pipe_face)262 translate_cull_mode(unsigned pipe_face)
263 {
264    static const unsigned map[4] = {
265       [PIPE_FACE_NONE]           = CULLMODE_NONE,
266       [PIPE_FACE_FRONT]          = CULLMODE_FRONT,
267       [PIPE_FACE_BACK]           = CULLMODE_BACK,
268       [PIPE_FACE_FRONT_AND_BACK] = CULLMODE_BOTH,
269    };
270    return map[pipe_face];
271 }
272 
273 static unsigned
translate_fill_mode(unsigned pipe_polymode)274 translate_fill_mode(unsigned pipe_polymode)
275 {
276    static const unsigned map[4] = {
277       [PIPE_POLYGON_MODE_FILL]           = FILL_MODE_SOLID,
278       [PIPE_POLYGON_MODE_LINE]           = FILL_MODE_WIREFRAME,
279       [PIPE_POLYGON_MODE_POINT]          = FILL_MODE_POINT,
280       [PIPE_POLYGON_MODE_FILL_RECTANGLE] = FILL_MODE_SOLID,
281    };
282    return map[pipe_polymode];
283 }
284 
285 static unsigned
translate_mip_filter(enum pipe_tex_mipfilter pipe_mip)286 translate_mip_filter(enum pipe_tex_mipfilter pipe_mip)
287 {
288    static const unsigned map[] = {
289       [PIPE_TEX_MIPFILTER_NEAREST] = MIPFILTER_NEAREST,
290       [PIPE_TEX_MIPFILTER_LINEAR]  = MIPFILTER_LINEAR,
291       [PIPE_TEX_MIPFILTER_NONE]    = MIPFILTER_NONE,
292    };
293    return map[pipe_mip];
294 }
295 
296 static uint32_t
translate_wrap(unsigned pipe_wrap)297 translate_wrap(unsigned pipe_wrap)
298 {
299    static const unsigned map[] = {
300       [PIPE_TEX_WRAP_REPEAT]                 = TCM_WRAP,
301       [PIPE_TEX_WRAP_CLAMP]                  = TCM_HALF_BORDER,
302       [PIPE_TEX_WRAP_CLAMP_TO_EDGE]          = TCM_CLAMP,
303       [PIPE_TEX_WRAP_CLAMP_TO_BORDER]        = TCM_CLAMP_BORDER,
304       [PIPE_TEX_WRAP_MIRROR_REPEAT]          = TCM_MIRROR,
305       [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE]   = TCM_MIRROR_ONCE,
306 
307       /* These are unsupported. */
308       [PIPE_TEX_WRAP_MIRROR_CLAMP]           = -1,
309       [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER] = -1,
310    };
311    return map[pipe_wrap];
312 }
313 
314 
315 static inline uint32_t
iris_encode_slm_size(unsigned gen,uint32_t bytes)316 iris_encode_slm_size(unsigned gen, uint32_t bytes)
317 {
318 #if GFX_VER >= 9
319    return encode_slm_size(gen, bytes);
320 #else
321    return elk_encode_slm_size(gen, bytes);
322 #endif
323 }
324 
325 /**
326  * Allocate space for some indirect state.
327  *
328  * Return a pointer to the map (to fill it out) and a state ref (for
329  * referring to the state in GPU commands).
330  */
331 static void *
upload_state(struct u_upload_mgr * uploader,struct iris_state_ref * ref,unsigned size,unsigned alignment)332 upload_state(struct u_upload_mgr *uploader,
333              struct iris_state_ref *ref,
334              unsigned size,
335              unsigned alignment)
336 {
337    void *p = NULL;
338    u_upload_alloc(uploader, 0, size, alignment, &ref->offset, &ref->res, &p);
339    return p;
340 }
341 
342 /**
343  * Stream out temporary/short-lived state.
344  *
345  * This allocates space, pins the BO, and includes the BO address in the
346  * returned offset (which works because all state lives in 32-bit memory
347  * zones).
348  */
349 static uint32_t *
stream_state(struct iris_batch * batch,struct u_upload_mgr * uploader,struct pipe_resource ** out_res,unsigned size,unsigned alignment,uint32_t * out_offset)350 stream_state(struct iris_batch *batch,
351              struct u_upload_mgr *uploader,
352              struct pipe_resource **out_res,
353              unsigned size,
354              unsigned alignment,
355              uint32_t *out_offset)
356 {
357    void *ptr = NULL;
358 
359    u_upload_alloc(uploader, 0, size, alignment, out_offset, out_res, &ptr);
360 
361    struct iris_bo *bo = iris_resource_bo(*out_res);
362    iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_NONE);
363 
364    iris_record_state_size(batch->state_sizes,
365                           bo->address + *out_offset, size);
366 
367    *out_offset += iris_bo_offset_from_base_address(bo);
368 
369    return ptr;
370 }
371 
372 /**
373  * stream_state() + memcpy.
374  */
375 static uint32_t
emit_state(struct iris_batch * batch,struct u_upload_mgr * uploader,struct pipe_resource ** out_res,const void * data,unsigned size,unsigned alignment)376 emit_state(struct iris_batch *batch,
377            struct u_upload_mgr *uploader,
378            struct pipe_resource **out_res,
379            const void *data,
380            unsigned size,
381            unsigned alignment)
382 {
383    unsigned offset = 0;
384    uint32_t *map =
385       stream_state(batch, uploader, out_res, size, alignment, &offset);
386 
387    if (map)
388       memcpy(map, data, size);
389 
390    return offset;
391 }
392 
393 /**
394  * Did field 'x' change between 'old_cso' and 'new_cso'?
395  *
396  * (If so, we may want to set some dirty flags.)
397  */
398 #define cso_changed(x) (!old_cso || (old_cso->x != new_cso->x))
399 #define cso_changed_memcmp(x) \
400    (!old_cso || memcmp(old_cso->x, new_cso->x, sizeof(old_cso->x)) != 0)
401 #define cso_changed_memcmp_elts(x, n) \
402    (!old_cso || memcmp(old_cso->x, new_cso->x, n * sizeof(old_cso->x[0])) != 0)
403 
404 static void
flush_before_state_base_change(struct iris_batch * batch)405 flush_before_state_base_change(struct iris_batch *batch)
406 {
407    /* Wa_14014427904 - We need additional invalidate/flush when
408     * emitting NP state commands with ATS-M in compute mode.
409     */
410    bool atsm_compute = intel_device_info_is_atsm(batch->screen->devinfo) &&
411                        batch->name == IRIS_BATCH_COMPUTE;
412    uint32_t np_state_wa_bits =
413       PIPE_CONTROL_CS_STALL |
414       PIPE_CONTROL_STATE_CACHE_INVALIDATE |
415       PIPE_CONTROL_CONST_CACHE_INVALIDATE |
416       PIPE_CONTROL_UNTYPED_DATAPORT_CACHE_FLUSH |
417       PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE |
418       PIPE_CONTROL_INSTRUCTION_INVALIDATE |
419       PIPE_CONTROL_FLUSH_HDC;
420 
421    /* Flush before emitting STATE_BASE_ADDRESS.
422     *
423     * This isn't documented anywhere in the PRM.  However, it seems to be
424     * necessary prior to changing the surface state base address.  We've
425     * seen issues in Vulkan where we get GPU hangs when using multi-level
426     * command buffers which clear depth, reset state base address, and then
427     * go render stuff.
428     *
429     * Normally, in GL, we would trust the kernel to do sufficient stalls
430     * and flushes prior to executing our batch.  However, it doesn't seem
431     * as if the kernel's flushing is always sufficient and we don't want to
432     * rely on it.
433     *
434     * We make this an end-of-pipe sync instead of a normal flush because we
435     * do not know the current status of the GPU.  On Haswell at least,
436     * having a fast-clear operation in flight at the same time as a normal
437     * rendering operation can cause hangs.  Since the kernel's flushing is
438     * insufficient, we need to ensure that any rendering operations from
439     * other processes are definitely complete before we try to do our own
440     * rendering.  It's a bit of a big hammer but it appears to work.
441     */
442    iris_emit_end_of_pipe_sync(batch,
443                               "change STATE_BASE_ADDRESS (flushes)",
444                               atsm_compute ? np_state_wa_bits : 0 |
445                               PIPE_CONTROL_RENDER_TARGET_FLUSH |
446                               PIPE_CONTROL_DEPTH_CACHE_FLUSH |
447                               PIPE_CONTROL_DATA_CACHE_FLUSH);
448 }
449 
450 static void
flush_after_state_base_change(struct iris_batch * batch)451 flush_after_state_base_change(struct iris_batch *batch)
452 {
453    const struct intel_device_info *devinfo = batch->screen->devinfo;
454    /* After re-setting the surface state base address, we have to do some
455     * cache flusing so that the sampler engine will pick up the new
456     * SURFACE_STATE objects and binding tables. From the Broadwell PRM,
457     * Shared Function > 3D Sampler > State > State Caching (page 96):
458     *
459     *    Coherency with system memory in the state cache, like the texture
460     *    cache is handled partially by software. It is expected that the
461     *    command stream or shader will issue Cache Flush operation or
462     *    Cache_Flush sampler message to ensure that the L1 cache remains
463     *    coherent with system memory.
464     *
465     *    [...]
466     *
467     *    Whenever the value of the Dynamic_State_Base_Addr,
468     *    Surface_State_Base_Addr are altered, the L1 state cache must be
469     *    invalidated to ensure the new surface or sampler state is fetched
470     *    from system memory.
471     *
472     * The PIPE_CONTROL command has a "State Cache Invalidation Enable" bit
473     * which, according the PIPE_CONTROL instruction documentation in the
474     * Broadwell PRM:
475     *
476     *    Setting this bit is independent of any other bit in this packet.
477     *    This bit controls the invalidation of the L1 and L2 state caches
478     *    at the top of the pipe i.e. at the parsing time.
479     *
480     * Unfortunately, experimentation seems to indicate that state cache
481     * invalidation through a PIPE_CONTROL does nothing whatsoever in
482     * regards to surface state and binding tables.  In stead, it seems that
483     * invalidating the texture cache is what is actually needed.
484     *
485     * XXX:  As far as we have been able to determine through
486     * experimentation, shows that flush the texture cache appears to be
487     * sufficient.  The theory here is that all of the sampling/rendering
488     * units cache the binding table in the texture cache.  However, we have
489     * yet to be able to actually confirm this.
490     *
491     * Wa_16013000631:
492     *
493     *  "DG2 128/256/512-A/B: S/W must program STATE_BASE_ADDRESS command twice
494     *   or program pipe control with Instruction cache invalidate post
495     *   STATE_BASE_ADDRESS command"
496     */
497    iris_emit_end_of_pipe_sync(batch,
498                               "change STATE_BASE_ADDRESS (invalidates)",
499                               PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE |
500                               PIPE_CONTROL_CONST_CACHE_INVALIDATE |
501                               PIPE_CONTROL_STATE_CACHE_INVALIDATE |
502                               (intel_needs_workaround(devinfo, 16013000631) ?
503                                PIPE_CONTROL_INSTRUCTION_INVALIDATE : 0));
504 }
505 
506 static void
iris_load_register_reg32(struct iris_batch * batch,uint32_t dst,uint32_t src)507 iris_load_register_reg32(struct iris_batch *batch, uint32_t dst,
508                          uint32_t src)
509 {
510    struct mi_builder b;
511    mi_builder_init(&b, batch->screen->devinfo, batch);
512    mi_store(&b, mi_reg32(dst), mi_reg32(src));
513 }
514 
515 static void
iris_load_register_reg64(struct iris_batch * batch,uint32_t dst,uint32_t src)516 iris_load_register_reg64(struct iris_batch *batch, uint32_t dst,
517                          uint32_t src)
518 {
519    struct mi_builder b;
520    mi_builder_init(&b, batch->screen->devinfo, batch);
521    mi_store(&b, mi_reg64(dst), mi_reg64(src));
522 }
523 
524 static void
iris_load_register_imm32(struct iris_batch * batch,uint32_t reg,uint32_t val)525 iris_load_register_imm32(struct iris_batch *batch, uint32_t reg,
526                          uint32_t val)
527 {
528    struct mi_builder b;
529    mi_builder_init(&b, batch->screen->devinfo, batch);
530    mi_store(&b, mi_reg32(reg), mi_imm(val));
531 }
532 
533 static void
iris_load_register_imm64(struct iris_batch * batch,uint32_t reg,uint64_t val)534 iris_load_register_imm64(struct iris_batch *batch, uint32_t reg,
535                          uint64_t val)
536 {
537    struct mi_builder b;
538    mi_builder_init(&b, batch->screen->devinfo, batch);
539    mi_store(&b, mi_reg64(reg), mi_imm(val));
540 }
541 
542 /**
543  * Emit MI_LOAD_REGISTER_MEM to load a 32-bit MMIO register from a buffer.
544  */
545 static void
iris_load_register_mem32(struct iris_batch * batch,uint32_t reg,struct iris_bo * bo,uint32_t offset)546 iris_load_register_mem32(struct iris_batch *batch, uint32_t reg,
547                          struct iris_bo *bo, uint32_t offset)
548 {
549    iris_batch_sync_region_start(batch);
550    struct mi_builder b;
551    mi_builder_init(&b, batch->screen->devinfo, batch);
552    struct mi_value src = mi_mem32(ro_bo(bo, offset));
553    mi_store(&b, mi_reg32(reg), src);
554    iris_batch_sync_region_end(batch);
555 }
556 
557 /**
558  * Load a 64-bit value from a buffer into a MMIO register via
559  * two MI_LOAD_REGISTER_MEM commands.
560  */
561 static void
iris_load_register_mem64(struct iris_batch * batch,uint32_t reg,struct iris_bo * bo,uint32_t offset)562 iris_load_register_mem64(struct iris_batch *batch, uint32_t reg,
563                          struct iris_bo *bo, uint32_t offset)
564 {
565    iris_batch_sync_region_start(batch);
566    struct mi_builder b;
567    mi_builder_init(&b, batch->screen->devinfo, batch);
568    struct mi_value src = mi_mem64(ro_bo(bo, offset));
569    mi_store(&b, mi_reg64(reg), src);
570    iris_batch_sync_region_end(batch);
571 }
572 
573 static void
iris_store_register_mem32(struct iris_batch * batch,uint32_t reg,struct iris_bo * bo,uint32_t offset,bool predicated)574 iris_store_register_mem32(struct iris_batch *batch, uint32_t reg,
575                           struct iris_bo *bo, uint32_t offset,
576                           bool predicated)
577 {
578    iris_batch_sync_region_start(batch);
579    struct mi_builder b;
580    mi_builder_init(&b, batch->screen->devinfo, batch);
581    struct mi_value dst = mi_mem32(rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE));
582    struct mi_value src = mi_reg32(reg);
583    if (predicated)
584       mi_store_if(&b, dst, src);
585    else
586       mi_store(&b, dst, src);
587    iris_batch_sync_region_end(batch);
588 }
589 
590 static void
iris_store_register_mem64(struct iris_batch * batch,uint32_t reg,struct iris_bo * bo,uint32_t offset,bool predicated)591 iris_store_register_mem64(struct iris_batch *batch, uint32_t reg,
592                           struct iris_bo *bo, uint32_t offset,
593                           bool predicated)
594 {
595    iris_batch_sync_region_start(batch);
596    struct mi_builder b;
597    mi_builder_init(&b, batch->screen->devinfo, batch);
598    struct mi_value dst = mi_mem64(rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE));
599    struct mi_value src = mi_reg64(reg);
600    if (predicated)
601       mi_store_if(&b, dst, src);
602    else
603       mi_store(&b, dst, src);
604    iris_batch_sync_region_end(batch);
605 }
606 
607 static void
iris_store_data_imm32(struct iris_batch * batch,struct iris_bo * bo,uint32_t offset,uint32_t imm)608 iris_store_data_imm32(struct iris_batch *batch,
609                       struct iris_bo *bo, uint32_t offset,
610                       uint32_t imm)
611 {
612    iris_batch_sync_region_start(batch);
613    struct mi_builder b;
614    mi_builder_init(&b, batch->screen->devinfo, batch);
615    struct mi_value dst = mi_mem32(rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE));
616    struct mi_value src = mi_imm(imm);
617    mi_store(&b, dst, src);
618    iris_batch_sync_region_end(batch);
619 }
620 
621 static void
iris_store_data_imm64(struct iris_batch * batch,struct iris_bo * bo,uint32_t offset,uint64_t imm)622 iris_store_data_imm64(struct iris_batch *batch,
623                       struct iris_bo *bo, uint32_t offset,
624                       uint64_t imm)
625 {
626    iris_batch_sync_region_start(batch);
627    struct mi_builder b;
628    mi_builder_init(&b, batch->screen->devinfo, batch);
629    struct mi_value dst = mi_mem64(rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE));
630    struct mi_value src = mi_imm(imm);
631    mi_store(&b, dst, src);
632    iris_batch_sync_region_end(batch);
633 }
634 
635 static void
iris_copy_mem_mem(struct iris_batch * batch,struct iris_bo * dst_bo,uint32_t dst_offset,struct iris_bo * src_bo,uint32_t src_offset,unsigned bytes)636 iris_copy_mem_mem(struct iris_batch *batch,
637                   struct iris_bo *dst_bo, uint32_t dst_offset,
638                   struct iris_bo *src_bo, uint32_t src_offset,
639                   unsigned bytes)
640 {
641    /* MI_COPY_MEM_MEM operates on DWords. */
642    assert(bytes % 4 == 0);
643    assert(dst_offset % 4 == 0);
644    assert(src_offset % 4 == 0);
645    iris_batch_sync_region_start(batch);
646 
647    for (unsigned i = 0; i < bytes; i += 4) {
648       iris_emit_cmd(batch, GENX(MI_COPY_MEM_MEM), cp) {
649          cp.DestinationMemoryAddress = rw_bo(dst_bo, dst_offset + i,
650                                              IRIS_DOMAIN_OTHER_WRITE);
651          cp.SourceMemoryAddress = ro_bo(src_bo, src_offset + i);
652       }
653    }
654 
655    iris_batch_sync_region_end(batch);
656 }
657 
658 static void
iris_rewrite_compute_walker_pc(struct iris_batch * batch,uint32_t * walker,struct iris_bo * bo,uint32_t offset)659 iris_rewrite_compute_walker_pc(struct iris_batch *batch,
660                                uint32_t *walker,
661                                struct iris_bo *bo,
662                                uint32_t offset)
663 {
664 #if GFX_VERx10 >= 125
665    struct iris_screen *screen = batch->screen;
666    struct iris_address addr = rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE);
667 
668    uint32_t dwords[GENX(COMPUTE_WALKER_length)];
669 
670    _iris_pack_command(batch, GENX(COMPUTE_WALKER), dwords, cw) {
671       cw.PostSync.Operation          = WriteTimestamp;
672       cw.PostSync.DestinationAddress = addr;
673       cw.PostSync.MOCS               = iris_mocs(NULL, &screen->isl_dev, 0);
674    }
675 
676    for (uint32_t i = 0; i < GENX(COMPUTE_WALKER_length); i++)
677       walker[i] |= dwords[i];
678 #else
679    unreachable("Unsupported");
680 #endif
681 }
682 
683 static void
emit_pipeline_select(struct iris_batch * batch,uint32_t pipeline)684 emit_pipeline_select(struct iris_batch *batch, uint32_t pipeline)
685 {
686    /* Bspec 55860: Xe2+ no longer requires PIPELINE_SELECT */
687 #if GFX_VER < 20
688 
689 #if GFX_VER >= 8 && GFX_VER < 10
690    /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
691     *
692     *   Software must clear the COLOR_CALC_STATE Valid field in
693     *   3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
694     *   with Pipeline Select set to GPGPU.
695     *
696     * The internal hardware docs recommend the same workaround for Gfx9
697     * hardware too.
698     */
699    if (pipeline == GPGPU)
700       iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
701 #endif
702 
703 #if GFX_VER >= 12
704    /* From Tigerlake PRM, Volume 2a, PIPELINE_SELECT:
705     *
706     *   "Software must ensure Render Cache, Depth Cache and HDC Pipeline flush
707     *   are flushed through a stalling PIPE_CONTROL command prior to
708     *   programming of PIPELINE_SELECT command transitioning Pipeline Select
709     *   from 3D to GPGPU/Media.
710     *   Software must ensure HDC Pipeline flush and Generic Media State Clear
711     *   is issued through a stalling PIPE_CONTROL command prior to programming
712     *   of PIPELINE_SELECT command transitioning Pipeline Select from
713     *   GPGPU/Media to 3D."
714     *
715     * Note: Issuing PIPE_CONTROL_MEDIA_STATE_CLEAR causes GPU hangs, probably
716     * because PIPE was not in MEDIA mode?!
717     */
718    enum pipe_control_flags flags = PIPE_CONTROL_CS_STALL |
719                                    PIPE_CONTROL_FLUSH_HDC;
720 
721    if (pipeline == GPGPU && batch->name == IRIS_BATCH_RENDER) {
722       flags |= PIPE_CONTROL_RENDER_TARGET_FLUSH |
723                PIPE_CONTROL_DEPTH_CACHE_FLUSH;
724    } else {
725       flags |= PIPE_CONTROL_UNTYPED_DATAPORT_CACHE_FLUSH;
726    }
727    /* Wa_16013063087 -  State Cache Invalidate must be issued prior to
728     * PIPELINE_SELECT when switching from 3D to Compute.
729     *
730     * SW must do this by programming of PIPECONTROL with “CS Stall” followed
731     * by a PIPECONTROL with State Cache Invalidate bit set.
732     */
733    if (pipeline == GPGPU &&
734        intel_needs_workaround(batch->screen->devinfo, 16013063087))
735       flags |= PIPE_CONTROL_STATE_CACHE_INVALIDATE;
736 
737    iris_emit_pipe_control_flush(batch, "PIPELINE_SELECT flush", flags);
738 #else
739    /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
740     * PIPELINE_SELECT [DevBWR+]":
741     *
742     *    "Project: DEVSNB+
743     *
744     *     Software must ensure all the write caches are flushed through a
745     *     stalling PIPE_CONTROL command followed by another PIPE_CONTROL
746     *     command to invalidate read only caches prior to programming
747     *     MI_PIPELINE_SELECT command to change the Pipeline Select Mode."
748     */
749     iris_emit_pipe_control_flush(batch,
750                                  "workaround: PIPELINE_SELECT flushes (1/2)",
751                                  PIPE_CONTROL_RENDER_TARGET_FLUSH |
752                                  PIPE_CONTROL_DEPTH_CACHE_FLUSH |
753                                  PIPE_CONTROL_DATA_CACHE_FLUSH |
754                                  PIPE_CONTROL_UNTYPED_DATAPORT_CACHE_FLUSH |
755                                  PIPE_CONTROL_CS_STALL);
756 
757     iris_emit_pipe_control_flush(batch,
758                                  "workaround: PIPELINE_SELECT flushes (2/2)",
759                                  PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE |
760                                  PIPE_CONTROL_CONST_CACHE_INVALIDATE |
761                                  PIPE_CONTROL_STATE_CACHE_INVALIDATE |
762                                  PIPE_CONTROL_INSTRUCTION_INVALIDATE);
763 #endif
764 
765    iris_emit_cmd(batch, GENX(PIPELINE_SELECT), sel) {
766 #if GFX_VER >= 9
767       sel.MaskBits = GFX_VER == 12 ? 0x13 : 0x3;
768 #if GFX_VER == 12
769       sel.MediaSamplerDOPClockGateEnable = true;
770 #endif /* if GFX_VER == 12 */
771 #endif /* if GFX_VER >= 9 */
772       sel.PipelineSelection = pipeline;
773    }
774 #endif /* if GFX_VER < 20 */
775 }
776 
777 UNUSED static void
init_glk_barrier_mode(struct iris_batch * batch,uint32_t value)778 init_glk_barrier_mode(struct iris_batch *batch, uint32_t value)
779 {
780 #if GFX_VER == 9
781    /* Project: DevGLK
782     *
783     *    "This chicken bit works around a hardware issue with barrier
784     *     logic encountered when switching between GPGPU and 3D pipelines.
785     *     To workaround the issue, this mode bit should be set after a
786     *     pipeline is selected."
787     */
788    iris_emit_reg(batch, GENX(SLICE_COMMON_ECO_CHICKEN1), reg) {
789       reg.GLKBarrierMode = value;
790       reg.GLKBarrierModeMask = 1;
791    }
792 #endif
793 }
794 
795 static void
init_state_base_address(struct iris_batch * batch)796 init_state_base_address(struct iris_batch *batch)
797 {
798    struct isl_device *isl_dev = &batch->screen->isl_dev;
799    uint32_t mocs = isl_mocs(isl_dev, 0, false);
800    flush_before_state_base_change(batch);
801 
802    /* We program most base addresses once at context initialization time.
803     * Each base address points at a 4GB memory zone, and never needs to
804     * change.  See iris_bufmgr.h for a description of the memory zones.
805     *
806     * The one exception is Surface State Base Address, which needs to be
807     * updated occasionally.  See iris_binder.c for the details there.
808     */
809    iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
810       sba.GeneralStateMOCS            = mocs;
811       sba.StatelessDataPortAccessMOCS = mocs;
812       sba.DynamicStateMOCS            = mocs;
813       sba.IndirectObjectMOCS          = mocs;
814       sba.InstructionMOCS             = mocs;
815       sba.SurfaceStateMOCS            = mocs;
816 #if GFX_VER >= 9
817       sba.BindlessSurfaceStateMOCS    = mocs;
818 #endif
819 
820       sba.GeneralStateBaseAddressModifyEnable   = true;
821       sba.DynamicStateBaseAddressModifyEnable   = true;
822       sba.IndirectObjectBaseAddressModifyEnable = true;
823       sba.InstructionBaseAddressModifyEnable    = true;
824       sba.GeneralStateBufferSizeModifyEnable    = true;
825       sba.DynamicStateBufferSizeModifyEnable    = true;
826       sba.SurfaceStateBaseAddressModifyEnable   = true;
827 #if GFX_VER >= 11
828       sba.BindlessSamplerStateMOCS    = mocs;
829 #endif
830       sba.IndirectObjectBufferSizeModifyEnable  = true;
831       sba.InstructionBuffersizeModifyEnable     = true;
832 
833       sba.InstructionBaseAddress  = ro_bo(NULL, IRIS_MEMZONE_SHADER_START);
834       sba.DynamicStateBaseAddress = ro_bo(NULL, IRIS_MEMZONE_DYNAMIC_START);
835       sba.SurfaceStateBaseAddress = ro_bo(NULL, IRIS_MEMZONE_BINDER_START);
836 
837       sba.GeneralStateBufferSize   = 0xfffff;
838       sba.IndirectObjectBufferSize = 0xfffff;
839       sba.InstructionBufferSize    = 0xfffff;
840       sba.DynamicStateBufferSize   = 0xfffff;
841 #if GFX_VERx10 >= 125
842       sba.L1CacheControl = L1CC_WB;
843 #endif
844    }
845 
846    flush_after_state_base_change(batch);
847 }
848 
849 static void
iris_emit_l3_config(struct iris_batch * batch,const struct intel_l3_config * cfg)850 iris_emit_l3_config(struct iris_batch *batch,
851                     const struct intel_l3_config *cfg)
852 {
853 #if GFX_VER < 20
854    assert(cfg || GFX_VER >= 12);
855 
856 #if GFX_VER >= 12
857 #define L3_ALLOCATION_REG GENX(L3ALLOC)
858 #define L3_ALLOCATION_REG_num GENX(L3ALLOC_num)
859 #else
860 #define L3_ALLOCATION_REG GENX(L3CNTLREG)
861 #define L3_ALLOCATION_REG_num GENX(L3CNTLREG_num)
862 #endif
863 
864    iris_emit_reg(batch, L3_ALLOCATION_REG, reg) {
865 #if GFX_VER < 11
866       reg.SLMEnable = cfg->n[INTEL_L3P_SLM] > 0;
867 #endif
868 #if GFX_VER == 11
869       /* Wa_1406697149: Bit 9 "Error Detection Behavior Control" must be set
870        * in L3CNTLREG register. The default setting of the bit is not the
871        * desirable behavior.
872        */
873       reg.ErrorDetectionBehaviorControl = true;
874       reg.UseFullWays = true;
875 #endif
876       if (GFX_VER < 12 || (cfg && cfg->n[INTEL_L3P_ALL] <= 126)) {
877          reg.URBAllocation = cfg->n[INTEL_L3P_URB];
878          reg.ROAllocation = cfg->n[INTEL_L3P_RO];
879          reg.DCAllocation = cfg->n[INTEL_L3P_DC];
880          reg.AllAllocation = cfg->n[INTEL_L3P_ALL];
881       } else {
882          assert(!cfg || !(cfg->n[INTEL_L3P_SLM] || cfg->n[INTEL_L3P_URB] ||
883                           cfg->n[INTEL_L3P_DC] || cfg->n[INTEL_L3P_RO] ||
884                           cfg->n[INTEL_L3P_IS] || cfg->n[INTEL_L3P_C] ||
885                           cfg->n[INTEL_L3P_T] || cfg->n[INTEL_L3P_TC]));
886 #if GFX_VER >= 12
887          reg.L3FullWayAllocationEnable = true;
888 #endif
889       }
890    }
891 #endif /* GFX_VER < 20 */
892 }
893 
894 void
genX(emit_urb_config)895 genX(emit_urb_config)(struct iris_batch *batch,
896                       bool has_tess_eval,
897                       bool has_geometry)
898 {
899    struct iris_screen *screen = batch->screen;
900    struct iris_context *ice = batch->ice;
901 
902    intel_get_urb_config(screen->devinfo,
903                         screen->l3_config_3d,
904                         has_tess_eval,
905                         has_geometry,
906                         &ice->shaders.urb.cfg,
907                         &ice->state.urb_deref_block_size,
908                         &ice->shaders.urb.constrained);
909 
910    genX(urb_workaround)(batch, &ice->shaders.urb.cfg);
911 
912    for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
913       iris_emit_cmd(batch, GENX(3DSTATE_URB_VS), urb) {
914          urb._3DCommandSubOpcode += i;
915          urb.VSURBStartingAddress     = ice->shaders.urb.cfg.start[i];
916          urb.VSURBEntryAllocationSize = ice->shaders.urb.cfg.size[i] - 1;
917          urb.VSNumberofURBEntries     = ice->shaders.urb.cfg.entries[i];
918       }
919    }
920 }
921 
922 #if GFX_VER == 9
923 static void
iris_enable_obj_preemption(struct iris_batch * batch,bool enable)924 iris_enable_obj_preemption(struct iris_batch *batch, bool enable)
925 {
926    /* A fixed function pipe flush is required before modifying this field */
927    iris_emit_end_of_pipe_sync(batch, enable ? "enable preemption"
928                                             : "disable preemption",
929                               PIPE_CONTROL_RENDER_TARGET_FLUSH);
930 
931    /* enable object level preemption */
932    iris_emit_reg(batch, GENX(CS_CHICKEN1), reg) {
933       reg.ReplayMode = enable;
934       reg.ReplayModeMask = true;
935    }
936 }
937 #endif
938 
939 static void
upload_pixel_hashing_tables(struct iris_batch * batch)940 upload_pixel_hashing_tables(struct iris_batch *batch)
941 {
942    UNUSED const struct intel_device_info *devinfo = batch->screen->devinfo;
943    UNUSED struct iris_context *ice = batch->ice;
944    assert(&ice->batches[IRIS_BATCH_RENDER] == batch);
945 
946 #if GFX_VER == 11
947    /* Gfx11 hardware has two pixel pipes at most. */
948    for (unsigned i = 2; i < ARRAY_SIZE(devinfo->ppipe_subslices); i++)
949       assert(devinfo->ppipe_subslices[i] == 0);
950 
951    if (devinfo->ppipe_subslices[0] == devinfo->ppipe_subslices[1])
952       return;
953 
954    unsigned size = GENX(SLICE_HASH_TABLE_length) * 4;
955    uint32_t hash_address;
956    struct pipe_resource *tmp = NULL;
957    uint32_t *map =
958       stream_state(batch, ice->state.dynamic_uploader, &tmp,
959                    size, 64, &hash_address);
960    pipe_resource_reference(&tmp, NULL);
961 
962    const bool flip = devinfo->ppipe_subslices[0] < devinfo->ppipe_subslices[1];
963    struct GENX(SLICE_HASH_TABLE) table;
964    intel_compute_pixel_hash_table_3way(16, 16, 3, 3, flip, table.Entry[0]);
965 
966    GENX(SLICE_HASH_TABLE_pack)(NULL, map, &table);
967 
968    iris_emit_cmd(batch, GENX(3DSTATE_SLICE_TABLE_STATE_POINTERS), ptr) {
969       ptr.SliceHashStatePointerValid = true;
970       ptr.SliceHashTableStatePointer = hash_address;
971    }
972 
973    iris_emit_cmd(batch, GENX(3DSTATE_3D_MODE), mode) {
974       mode.SliceHashingTableEnable = true;
975    }
976 
977 #elif GFX_VERx10 == 120
978    /* For each n calculate ppipes_of[n], equal to the number of pixel pipes
979     * present with n active dual subslices.
980     */
981    unsigned ppipes_of[3] = {};
982 
983    for (unsigned n = 0; n < ARRAY_SIZE(ppipes_of); n++) {
984       for (unsigned p = 0; p < 3; p++)
985          ppipes_of[n] += (devinfo->ppipe_subslices[p] == n);
986    }
987 
988    /* Gfx12 has three pixel pipes. */
989    for (unsigned p = 3; p < ARRAY_SIZE(devinfo->ppipe_subslices); p++)
990       assert(devinfo->ppipe_subslices[p] == 0);
991 
992    if (ppipes_of[2] == 3 || ppipes_of[0] == 2) {
993       /* All three pixel pipes have the maximum number of active dual
994        * subslices, or there is only one active pixel pipe: Nothing to do.
995        */
996       return;
997    }
998 
999    iris_emit_cmd(batch, GENX(3DSTATE_SUBSLICE_HASH_TABLE), p) {
1000       p.SliceHashControl[0] = TABLE_0;
1001 
1002       if (ppipes_of[2] == 2 && ppipes_of[0] == 1)
1003          intel_compute_pixel_hash_table_3way(8, 16, 2, 2, 0, p.TwoWayTableEntry[0]);
1004       else if (ppipes_of[2] == 1 && ppipes_of[1] == 1 && ppipes_of[0] == 1)
1005          intel_compute_pixel_hash_table_3way(8, 16, 3, 3, 0, p.TwoWayTableEntry[0]);
1006 
1007       if (ppipes_of[2] == 2 && ppipes_of[1] == 1)
1008          intel_compute_pixel_hash_table_3way(8, 16, 5, 4, 0, p.ThreeWayTableEntry[0]);
1009       else if (ppipes_of[2] == 2 && ppipes_of[0] == 1)
1010          intel_compute_pixel_hash_table_3way(8, 16, 2, 2, 0, p.ThreeWayTableEntry[0]);
1011       else if (ppipes_of[2] == 1 && ppipes_of[1] == 1 && ppipes_of[0] == 1)
1012          intel_compute_pixel_hash_table_3way(8, 16, 3, 3, 0, p.ThreeWayTableEntry[0]);
1013       else
1014          unreachable("Illegal fusing.");
1015    }
1016 
1017    iris_emit_cmd(batch, GENX(3DSTATE_3D_MODE), p) {
1018       p.SubsliceHashingTableEnable = true;
1019       p.SubsliceHashingTableEnableMask = true;
1020    }
1021 
1022 #elif GFX_VERx10 == 125
1023    struct pipe_screen *pscreen = &batch->screen->base;
1024    const unsigned size = GENX(SLICE_HASH_TABLE_length) * 4;
1025    const struct pipe_resource tmpl = {
1026      .target = PIPE_BUFFER,
1027      .format = PIPE_FORMAT_R8_UNORM,
1028      .bind = PIPE_BIND_CUSTOM,
1029      .usage = PIPE_USAGE_IMMUTABLE,
1030      .flags = IRIS_RESOURCE_FLAG_DYNAMIC_MEMZONE,
1031      .width0 = size,
1032      .height0 = 1,
1033      .depth0 = 1,
1034      .array_size = 1
1035    };
1036 
1037    pipe_resource_reference(&ice->state.pixel_hashing_tables, NULL);
1038    ice->state.pixel_hashing_tables = pscreen->resource_create(pscreen, &tmpl);
1039 
1040    struct iris_resource *res = (struct iris_resource *)ice->state.pixel_hashing_tables;
1041    struct pipe_transfer *transfer = NULL;
1042    uint32_t *map = pipe_buffer_map_range(&ice->ctx, ice->state.pixel_hashing_tables,
1043                                          0, size, PIPE_MAP_WRITE,
1044                                          &transfer);
1045 
1046    /* Calculate the set of present pixel pipes, and another set of
1047     * present pixel pipes with 2 dual subslices enabled, the latter
1048     * will appear on the hashing table with twice the frequency of
1049     * pixel pipes with a single dual subslice present.
1050     */
1051    uint32_t ppipe_mask1 = 0, ppipe_mask2 = 0;
1052    for (unsigned p = 0; p < ARRAY_SIZE(devinfo->ppipe_subslices); p++) {
1053       if (devinfo->ppipe_subslices[p])
1054          ppipe_mask1 |= (1u << p);
1055       if (devinfo->ppipe_subslices[p] > 1)
1056          ppipe_mask2 |= (1u << p);
1057    }
1058    assert(ppipe_mask1);
1059 
1060    struct GENX(SLICE_HASH_TABLE) table;
1061 
1062    /* Note that the hardware expects an array with 7 tables, each
1063     * table is intended to specify the pixel pipe hashing behavior for
1064     * every possible slice count between 2 and 8, however that doesn't
1065     * actually work, among other reasons due to hardware bugs that
1066     * will cause the GPU to erroneously access the table at the wrong
1067     * index in some cases, so in practice all 7 tables need to be
1068     * initialized to the same value.
1069     */
1070    for (unsigned i = 0; i < 7; i++)
1071       intel_compute_pixel_hash_table_nway(16, 16, ppipe_mask1, ppipe_mask2,
1072                                           table.Entry[i][0]);
1073 
1074    GENX(SLICE_HASH_TABLE_pack)(NULL, map, &table);
1075 
1076    pipe_buffer_unmap(&ice->ctx, transfer);
1077 
1078    iris_use_pinned_bo(batch, res->bo, false, IRIS_DOMAIN_NONE);
1079    iris_record_state_size(batch->state_sizes, res->bo->address + res->offset, size);
1080 
1081    iris_emit_cmd(batch, GENX(3DSTATE_SLICE_TABLE_STATE_POINTERS), ptr) {
1082       ptr.SliceHashStatePointerValid = true;
1083       ptr.SliceHashTableStatePointer = iris_bo_offset_from_base_address(res->bo) +
1084                                        res->offset;
1085    }
1086 
1087    iris_emit_cmd(batch, GENX(3DSTATE_3D_MODE), mode) {
1088       mode.SliceHashingTableEnable = true;
1089       mode.SliceHashingTableEnableMask = true;
1090       mode.CrossSliceHashingMode = (util_bitcount(ppipe_mask1) > 1 ?
1091                                     hashing32x32 : NormalMode);
1092       mode.CrossSliceHashingModeMask = -1;
1093    }
1094 #endif
1095 }
1096 
1097 static void
iris_alloc_push_constants(struct iris_batch * batch)1098 iris_alloc_push_constants(struct iris_batch *batch)
1099 {
1100    const struct intel_device_info *devinfo = batch->screen->devinfo;
1101 
1102    /* For now, we set a static partitioning of the push constant area,
1103     * assuming that all stages could be in use.
1104     *
1105     * TODO: Try lazily allocating the HS/DS/GS sections as needed, and
1106     *       see if that improves performance by offering more space to
1107     *       the VS/FS when those aren't in use.  Also, try dynamically
1108     *       enabling/disabling it like i965 does.  This would be more
1109     *       stalls and may not actually help; we don't know yet.
1110     */
1111 
1112    /* Divide as equally as possible with any remainder given to FRAGMENT. */
1113    const unsigned push_constant_kb = devinfo->max_constant_urb_size_kb;
1114    const unsigned stage_size = push_constant_kb / 5;
1115    const unsigned frag_size = push_constant_kb - 4 * stage_size;
1116 
1117    for (int i = 0; i <= MESA_SHADER_FRAGMENT; i++) {
1118       iris_emit_cmd(batch, GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
1119          alloc._3DCommandSubOpcode = 18 + i;
1120          alloc.ConstantBufferOffset = stage_size * i;
1121          alloc.ConstantBufferSize = i == MESA_SHADER_FRAGMENT ? frag_size : stage_size;
1122       }
1123    }
1124 
1125 #if GFX_VERx10 == 125
1126    /* DG2: Wa_22011440098
1127     * MTL: Wa_18022330953
1128     *
1129     * In 3D mode, after programming push constant alloc command immediately
1130     * program push constant command(ZERO length) without any commit between
1131     * them.
1132     */
1133    iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_ALL), c) {
1134       /* Update empty push constants for all stages (bitmask = 11111b) */
1135       c.ShaderUpdateEnable = 0x1f;
1136       c.MOCS = iris_mocs(NULL, &batch->screen->isl_dev, 0);
1137    }
1138 #endif
1139 }
1140 
1141 #if GFX_VER >= 12
1142 static void
1143 init_aux_map_state(struct iris_batch *batch);
1144 #endif
1145 
1146 /* This updates a register. Caller should stall the pipeline as needed. */
1147 static void
iris_disable_rhwo_optimization(struct iris_batch * batch,bool disable)1148 iris_disable_rhwo_optimization(struct iris_batch *batch, bool disable)
1149 {
1150    assert(batch->screen->devinfo->verx10 == 120);
1151 #if GFX_VERx10 == 120
1152    iris_emit_reg(batch, GENX(COMMON_SLICE_CHICKEN1), c1) {
1153       c1.RCCRHWOOptimizationDisable = disable;
1154       c1.RCCRHWOOptimizationDisableMask = true;
1155    };
1156 #endif
1157 }
1158 
1159 /**
1160  * Upload initial GPU state for any kind of context.
1161  *
1162  * These need to happen for both render and compute.
1163  */
1164 static void
iris_init_common_context(struct iris_batch * batch)1165 iris_init_common_context(struct iris_batch *batch)
1166 {
1167 #if GFX_VER == 11
1168    iris_emit_reg(batch, GENX(SAMPLER_MODE), reg) {
1169       reg.HeaderlessMessageforPreemptableContexts = 1;
1170       reg.HeaderlessMessageforPreemptableContextsMask = 1;
1171    }
1172 
1173    /* Bit 1 must be set in HALF_SLICE_CHICKEN7. */
1174    iris_emit_reg(batch, GENX(HALF_SLICE_CHICKEN7), reg) {
1175       reg.EnabledTexelOffsetPrecisionFix = 1;
1176       reg.EnabledTexelOffsetPrecisionFixMask = 1;
1177    }
1178 #endif
1179 
1180    /* Select 256B-aligned binding table mode on Icelake through Tigerlake,
1181     * which gives us larger binding table pointers, at the cost of higher
1182     * alignment requirements (bits 18:8 are valid instead of 15:5).  When
1183     * using this mode, we have to shift binding table pointers by 3 bits,
1184     * as they're still stored in the same bit-location in the field.
1185     */
1186 #if GFX_VER >= 11 && GFX_VERx10 < 125
1187    iris_emit_reg(batch, GENX(GT_MODE), reg) {
1188       reg.BindingTableAlignment = BTP_18_8;
1189       reg.BindingTableAlignmentMask = true;
1190    }
1191 #endif
1192 
1193 #if GFX_VERx10 == 125
1194    /* Even though L3 partial write merging is supposed to be enabled
1195     * by default on Gfx12.5 according to the hardware spec, i915
1196     * appears to accidentally clear the enables during context
1197     * initialization, so make sure to enable them here since partial
1198     * write merging has a large impact on rendering performance.
1199     */
1200    iris_emit_reg(batch, GENX(L3SQCREG5), reg) {
1201       reg.L3CachePartialWriteMergeTimerInitialValue = 0x7f;
1202       reg.CompressiblePartialWriteMergeEnable = true;
1203       reg.CoherentPartialWriteMergeEnable = true;
1204       reg.CrossTilePartialWriteMergeEnable = true;
1205    }
1206 #endif
1207 }
1208 
1209 static void
toggle_protected(struct iris_batch * batch)1210 toggle_protected(struct iris_batch *batch)
1211 {
1212    struct iris_context *ice;
1213 
1214    if (batch->name == IRIS_BATCH_RENDER)
1215       ice =container_of(batch, struct iris_context, batches[IRIS_BATCH_RENDER]);
1216    else if (batch->name == IRIS_BATCH_COMPUTE)
1217       ice = container_of(batch, struct iris_context, batches[IRIS_BATCH_COMPUTE]);
1218    else
1219       unreachable("unhandled batch");
1220 
1221    if (!ice->protected)
1222       return;
1223 
1224 #if GFX_VER >= 12
1225    iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
1226       pc.CommandStreamerStallEnable = true;
1227       pc.RenderTargetCacheFlushEnable = true;
1228       pc.ProtectedMemoryDisable = true;
1229    }
1230    iris_emit_cmd(batch, GENX(MI_SET_APPID), appid) {
1231       /* Default value for single session. */
1232       appid.ProtectedMemoryApplicationID = 0xf;
1233       appid.ProtectedMemoryApplicationIDType = DISPLAY_APP;
1234    }
1235    iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
1236       pc.CommandStreamerStallEnable = true;
1237       pc.RenderTargetCacheFlushEnable = true;
1238       pc.ProtectedMemoryEnable = true;
1239    }
1240 #else
1241    unreachable("Not supported");
1242 #endif
1243 }
1244 
1245 /**
1246  * Upload the initial GPU state for a render context.
1247  *
1248  * This sets some invariant state that needs to be programmed a particular
1249  * way, but we never actually change.
1250  */
1251 static void
iris_init_render_context(struct iris_batch * batch)1252 iris_init_render_context(struct iris_batch *batch)
1253 {
1254    UNUSED const struct intel_device_info *devinfo = batch->screen->devinfo;
1255 
1256    iris_batch_sync_region_start(batch);
1257 
1258    emit_pipeline_select(batch, _3D);
1259 
1260    toggle_protected(batch);
1261 
1262    iris_emit_l3_config(batch, batch->screen->l3_config_3d);
1263 
1264    init_state_base_address(batch);
1265 
1266    iris_init_common_context(batch);
1267 
1268 #if GFX_VER >= 9
1269    iris_emit_reg(batch, GENX(CS_DEBUG_MODE2), reg) {
1270       reg.CONSTANT_BUFFERAddressOffsetDisable = true;
1271       reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
1272    }
1273 #else
1274    iris_emit_reg(batch, GENX(INSTPM), reg) {
1275       reg.CONSTANT_BUFFERAddressOffsetDisable = true;
1276       reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
1277    }
1278 #endif
1279 
1280 #if GFX_VER == 9
1281    iris_emit_reg(batch, GENX(CACHE_MODE_1), reg) {
1282       reg.FloatBlendOptimizationEnable = true;
1283       reg.FloatBlendOptimizationEnableMask = true;
1284       reg.MSCRAWHazardAvoidanceBit = true;
1285       reg.MSCRAWHazardAvoidanceBitMask = true;
1286       reg.PartialResolveDisableInVC = true;
1287       reg.PartialResolveDisableInVCMask = true;
1288    }
1289 
1290    if (devinfo->platform == INTEL_PLATFORM_GLK)
1291       init_glk_barrier_mode(batch, GLK_BARRIER_MODE_3D_HULL);
1292 #endif
1293 
1294 #if GFX_VER == 11
1295    iris_emit_reg(batch, GENX(TCCNTLREG), reg) {
1296       reg.L3DataPartialWriteMergingEnable = true;
1297       reg.ColorZPartialWriteMergingEnable = true;
1298       reg.URBPartialWriteMergingEnable = true;
1299       reg.TCDisable = true;
1300    }
1301 
1302    /* Hardware specification recommends disabling repacking for the
1303     * compatibility with decompression mechanism in display controller.
1304     */
1305    if (devinfo->disable_ccs_repack) {
1306       iris_emit_reg(batch, GENX(CACHE_MODE_0), reg) {
1307          reg.DisableRepackingforCompression = true;
1308          reg.DisableRepackingforCompressionMask = true;
1309       }
1310    }
1311 #endif
1312 
1313 #if GFX_VER == 12
1314    iris_emit_reg(batch, GENX(FF_MODE2), reg) {
1315       /* On Alchemist, the FF_MODE2 docs for the GS timer say:
1316        *
1317        *    "The timer value must be set to 224."
1318        *
1319        * and Wa_16011163337 indicates this is the case for all Gfx12 parts,
1320        * and that this is necessary to avoid hanging the HS/DS units.  It
1321        * also clarifies that 224 is literally 0xE0 in the bits, not 7*32=224.
1322        *
1323        * The HS timer docs also have the same quote for Alchemist.  I am
1324        * unaware of a reason it needs to be set to 224 on Tigerlake, but
1325        * we do so for consistency if nothing else.
1326        *
1327        * For the TDS timer value, the docs say:
1328        *
1329        *    "For best performance, a value of 4 should be programmed."
1330        *
1331        * i915 also sets it this way on Tigerlake due to workarounds.
1332        *
1333        * The default VS timer appears to be 0, so we leave it at that.
1334        */
1335       reg.GSTimerValue  = 224;
1336       reg.HSTimerValue  = 224;
1337       reg.TDSTimerValue = 4;
1338       reg.VSTimerValue  = 0;
1339    }
1340 #endif
1341 
1342 #if INTEL_NEEDS_WA_1508744258
1343    /* The suggested workaround is:
1344     *
1345     *    Disable RHWO by setting 0x7010[14] by default except during resolve
1346     *    pass.
1347     *
1348     * We implement global disabling of the optimization here and we toggle it
1349     * in iris_resolve_color.
1350     *
1351     * iris_init_compute_context is unmodified because we don't expect to
1352     * access the RCC in the compute context. iris_mcs_partial_resolve is
1353     * unmodified because that pass doesn't use a HW bit to perform the
1354     * resolve (related HSDs specifically call out the RenderTargetResolveType
1355     * field in the 3DSTATE_PS instruction).
1356     */
1357    iris_disable_rhwo_optimization(batch, true);
1358 #endif
1359 
1360 #if GFX_VERx10 == 120
1361    /* Wa_1806527549 says to disable the following HiZ optimization when the
1362     * depth buffer is D16_UNORM. We've found the WA to help with more depth
1363     * buffer configurations however, so we always disable it just to be safe.
1364     */
1365    iris_emit_reg(batch, GENX(HIZ_CHICKEN), reg) {
1366       reg.HZDepthTestLEGEOptimizationDisable = true;
1367       reg.HZDepthTestLEGEOptimizationDisableMask = true;
1368    }
1369 #endif
1370 
1371 #if GFX_VERx10 == 125
1372    iris_emit_reg(batch, GENX(CHICKEN_RASTER_2), reg) {
1373       reg.TBIMRBatchSizeOverride = true;
1374       reg.TBIMROpenBatchEnable = true;
1375       reg.TBIMRFastClip = true;
1376       reg.TBIMRBatchSizeOverrideMask = true;
1377       reg.TBIMROpenBatchEnableMask = true;
1378       reg.TBIMRFastClipMask = true;
1379    };
1380 #endif
1381 
1382    upload_pixel_hashing_tables(batch);
1383 
1384    /* 3DSTATE_DRAWING_RECTANGLE is non-pipelined, so we want to avoid
1385     * changing it dynamically.  We set it to the maximum size here, and
1386     * instead include the render target dimensions in the viewport, so
1387     * viewport extents clipping takes care of pruning stray geometry.
1388     */
1389    iris_emit_cmd(batch, GENX(3DSTATE_DRAWING_RECTANGLE), rect) {
1390       rect.ClippedDrawingRectangleXMax = UINT16_MAX;
1391       rect.ClippedDrawingRectangleYMax = UINT16_MAX;
1392    }
1393 
1394    /* Set the initial MSAA sample positions. */
1395    iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_PATTERN), pat) {
1396       INTEL_SAMPLE_POS_1X(pat._1xSample);
1397       INTEL_SAMPLE_POS_2X(pat._2xSample);
1398       INTEL_SAMPLE_POS_4X(pat._4xSample);
1399       INTEL_SAMPLE_POS_8X(pat._8xSample);
1400 #if GFX_VER >= 9
1401       INTEL_SAMPLE_POS_16X(pat._16xSample);
1402 #endif
1403    }
1404 
1405    /* Use the legacy AA line coverage computation. */
1406    iris_emit_cmd(batch, GENX(3DSTATE_AA_LINE_PARAMETERS), foo);
1407 
1408    /* Disable chromakeying (it's for media) */
1409    iris_emit_cmd(batch, GENX(3DSTATE_WM_CHROMAKEY), foo);
1410 
1411    /* We want regular rendering, not special HiZ operations. */
1412    iris_emit_cmd(batch, GENX(3DSTATE_WM_HZ_OP), foo);
1413 
1414    /* No polygon stippling offsets are necessary. */
1415    /* TODO: may need to set an offset for origin-UL framebuffers */
1416    iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_OFFSET), foo);
1417 
1418 #if GFX_VERx10 >= 125
1419    iris_emit_cmd(batch, GENX(3DSTATE_MESH_CONTROL), foo);
1420    iris_emit_cmd(batch, GENX(3DSTATE_TASK_CONTROL), foo);
1421 #endif
1422 
1423    iris_alloc_push_constants(batch);
1424 
1425 
1426 #if GFX_VER >= 12
1427    init_aux_map_state(batch);
1428 #endif
1429 
1430    iris_batch_sync_region_end(batch);
1431 }
1432 
1433 static void
iris_init_compute_context(struct iris_batch * batch)1434 iris_init_compute_context(struct iris_batch *batch)
1435 {
1436    UNUSED const struct intel_device_info *devinfo = batch->screen->devinfo;
1437 
1438    iris_batch_sync_region_start(batch);
1439 
1440    /* Wa_1607854226:
1441     *
1442     *  Start with pipeline in 3D mode to set the STATE_BASE_ADDRESS.
1443     */
1444 #if GFX_VERx10 == 120
1445    emit_pipeline_select(batch, _3D);
1446 #else
1447    emit_pipeline_select(batch, GPGPU);
1448 #endif
1449 
1450    toggle_protected(batch);
1451 
1452    iris_emit_l3_config(batch, batch->screen->l3_config_cs);
1453 
1454    init_state_base_address(batch);
1455 
1456    iris_init_common_context(batch);
1457 
1458 #if GFX_VERx10 == 120
1459    emit_pipeline_select(batch, GPGPU);
1460 #endif
1461 
1462 #if GFX_VER == 9
1463    if (devinfo->platform == INTEL_PLATFORM_GLK)
1464       init_glk_barrier_mode(batch, GLK_BARRIER_MODE_GPGPU);
1465 #endif
1466 
1467 #if GFX_VER >= 12
1468    init_aux_map_state(batch);
1469 #endif
1470 
1471 #if GFX_VERx10 >= 125
1472    iris_emit_cmd(batch, GENX(CFE_STATE), cfe) {
1473       cfe.MaximumNumberofThreads =
1474          devinfo->max_cs_threads * devinfo->subslice_total;
1475    }
1476 #endif
1477 
1478    iris_batch_sync_region_end(batch);
1479 }
1480 
1481 static void
iris_init_copy_context(struct iris_batch * batch)1482 iris_init_copy_context(struct iris_batch *batch)
1483 {
1484    iris_batch_sync_region_start(batch);
1485 
1486 #if GFX_VER >= 12
1487    init_aux_map_state(batch);
1488 #endif
1489 
1490    iris_batch_sync_region_end(batch);
1491 }
1492 
1493 struct iris_vertex_buffer_state {
1494    /** The VERTEX_BUFFER_STATE hardware structure. */
1495    uint32_t state[GENX(VERTEX_BUFFER_STATE_length)];
1496 
1497    /** The resource to source vertex data from. */
1498    struct pipe_resource *resource;
1499 
1500    int offset;
1501 };
1502 
1503 struct iris_depth_buffer_state {
1504    /* Depth/HiZ/Stencil related hardware packets. */
1505 #if GFX_VER < 20
1506    uint32_t packets[GENX(3DSTATE_DEPTH_BUFFER_length) +
1507                     GENX(3DSTATE_STENCIL_BUFFER_length) +
1508                     GENX(3DSTATE_HIER_DEPTH_BUFFER_length) +
1509                     GENX(3DSTATE_CLEAR_PARAMS_length)];
1510 #else
1511    uint32_t packets[GENX(3DSTATE_DEPTH_BUFFER_length) +
1512                     GENX(3DSTATE_STENCIL_BUFFER_length) +
1513                     GENX(3DSTATE_HIER_DEPTH_BUFFER_length)];
1514 #endif
1515 };
1516 
1517 #if INTEL_NEEDS_WA_1808121037
1518 enum iris_depth_reg_mode {
1519    IRIS_DEPTH_REG_MODE_HW_DEFAULT = 0,
1520    IRIS_DEPTH_REG_MODE_D16_1X_MSAA,
1521    IRIS_DEPTH_REG_MODE_UNKNOWN,
1522 };
1523 #endif
1524 
1525 /**
1526  * Generation-specific context state (ice->state.genx->...).
1527  *
1528  * Most state can go in iris_context directly, but these encode hardware
1529  * packets which vary by generation.
1530  */
1531 struct iris_genx_state {
1532    struct iris_vertex_buffer_state vertex_buffers[33];
1533    uint32_t last_index_buffer[GENX(3DSTATE_INDEX_BUFFER_length)];
1534 
1535    struct iris_depth_buffer_state depth_buffer;
1536 
1537    uint32_t so_buffers[4 * GENX(3DSTATE_SO_BUFFER_length)];
1538 
1539 #if GFX_VER == 8
1540    bool pma_fix_enabled;
1541 #endif
1542 
1543    /* Is object level preemption enabled? */
1544    bool object_preemption;
1545 
1546 #if INTEL_NEEDS_WA_1808121037
1547    enum iris_depth_reg_mode depth_reg_mode;
1548 #endif
1549 
1550    struct {
1551 #if GFX_VER == 8
1552       struct isl_image_param image_param[PIPE_MAX_SHADER_IMAGES];
1553 #endif
1554    } shaders[MESA_SHADER_STAGES];
1555 };
1556 
1557 /**
1558  * The pipe->set_blend_color() driver hook.
1559  *
1560  * This corresponds to our COLOR_CALC_STATE.
1561  */
1562 static void
iris_set_blend_color(struct pipe_context * ctx,const struct pipe_blend_color * state)1563 iris_set_blend_color(struct pipe_context *ctx,
1564                      const struct pipe_blend_color *state)
1565 {
1566    struct iris_context *ice = (struct iris_context *) ctx;
1567 
1568    /* Our COLOR_CALC_STATE is exactly pipe_blend_color, so just memcpy */
1569    memcpy(&ice->state.blend_color, state, sizeof(struct pipe_blend_color));
1570    ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
1571 }
1572 
1573 /**
1574  * Gallium CSO for blend state (see pipe_blend_state).
1575  */
1576 struct iris_blend_state {
1577    /** Partial 3DSTATE_PS_BLEND */
1578    uint32_t ps_blend[GENX(3DSTATE_PS_BLEND_length)];
1579 
1580    /** Partial BLEND_STATE */
1581    uint32_t blend_state[GENX(BLEND_STATE_length) +
1582                         IRIS_MAX_DRAW_BUFFERS * GENX(BLEND_STATE_ENTRY_length)];
1583 
1584    bool alpha_to_coverage; /* for shader key */
1585 
1586    /** Bitfield of whether blending is enabled for RT[i] - for aux resolves */
1587    uint8_t blend_enables;
1588 
1589    /** Bitfield of whether color writes are enabled for RT[i] */
1590    uint8_t color_write_enables;
1591 
1592    /** Does RT[0] use dual color blending? */
1593    bool dual_color_blending;
1594 
1595    int ps_dst_blend_factor[IRIS_MAX_DRAW_BUFFERS];
1596    int ps_dst_alpha_blend_factor[IRIS_MAX_DRAW_BUFFERS];
1597 };
1598 
1599 static enum pipe_blendfactor
fix_blendfactor(enum pipe_blendfactor f,bool alpha_to_one)1600 fix_blendfactor(enum pipe_blendfactor f, bool alpha_to_one)
1601 {
1602    if (alpha_to_one) {
1603       if (f == PIPE_BLENDFACTOR_SRC1_ALPHA)
1604          return PIPE_BLENDFACTOR_ONE;
1605 
1606       if (f == PIPE_BLENDFACTOR_INV_SRC1_ALPHA)
1607          return PIPE_BLENDFACTOR_ZERO;
1608    }
1609 
1610    return f;
1611 }
1612 
1613 /**
1614  * The pipe->create_blend_state() driver hook.
1615  *
1616  * Translates a pipe_blend_state into iris_blend_state.
1617  */
1618 static void *
iris_create_blend_state(struct pipe_context * ctx,const struct pipe_blend_state * state)1619 iris_create_blend_state(struct pipe_context *ctx,
1620                         const struct pipe_blend_state *state)
1621 {
1622    struct iris_blend_state *cso = malloc(sizeof(struct iris_blend_state));
1623    uint32_t *blend_entry = cso->blend_state + GENX(BLEND_STATE_length);
1624 
1625    cso->blend_enables = 0;
1626    cso->color_write_enables = 0;
1627    STATIC_ASSERT(IRIS_MAX_DRAW_BUFFERS <= 8);
1628 
1629    cso->alpha_to_coverage = state->alpha_to_coverage;
1630 
1631    bool indep_alpha_blend = false;
1632 
1633    for (int i = 0; i < IRIS_MAX_DRAW_BUFFERS; i++) {
1634       const struct pipe_rt_blend_state *rt =
1635          &state->rt[state->independent_blend_enable ? i : 0];
1636 
1637       enum pipe_blendfactor src_rgb =
1638          fix_blendfactor(rt->rgb_src_factor, state->alpha_to_one);
1639       enum pipe_blendfactor src_alpha =
1640          fix_blendfactor(rt->alpha_src_factor, state->alpha_to_one);
1641       enum pipe_blendfactor dst_rgb =
1642          fix_blendfactor(rt->rgb_dst_factor, state->alpha_to_one);
1643       enum pipe_blendfactor dst_alpha =
1644          fix_blendfactor(rt->alpha_dst_factor, state->alpha_to_one);
1645 
1646       /* Stored separately in cso for dynamic emission. */
1647       cso->ps_dst_blend_factor[i] = (int) dst_rgb;
1648       cso->ps_dst_alpha_blend_factor[i] = (int) dst_alpha;
1649 
1650       if (rt->rgb_func != rt->alpha_func ||
1651           src_rgb != src_alpha || dst_rgb != dst_alpha)
1652          indep_alpha_blend = true;
1653 
1654       if (rt->blend_enable)
1655          cso->blend_enables |= 1u << i;
1656 
1657       if (rt->colormask)
1658          cso->color_write_enables |= 1u << i;
1659 
1660       iris_pack_state(GENX(BLEND_STATE_ENTRY), blend_entry, be) {
1661          be.LogicOpEnable = state->logicop_enable;
1662          be.LogicOpFunction = state->logicop_func;
1663 
1664          be.PreBlendSourceOnlyClampEnable = false;
1665          be.ColorClampRange = COLORCLAMP_RTFORMAT;
1666          be.PreBlendColorClampEnable = true;
1667          be.PostBlendColorClampEnable = true;
1668 
1669          be.ColorBufferBlendEnable = rt->blend_enable;
1670 
1671          be.ColorBlendFunction          = rt->rgb_func;
1672          be.AlphaBlendFunction          = rt->alpha_func;
1673 
1674          /* The casts prevent warnings about implicit enum type conversions. */
1675          be.SourceBlendFactor           = (int) src_rgb;
1676          be.SourceAlphaBlendFactor      = (int) src_alpha;
1677 
1678          be.WriteDisableRed   = !(rt->colormask & PIPE_MASK_R);
1679          be.WriteDisableGreen = !(rt->colormask & PIPE_MASK_G);
1680          be.WriteDisableBlue  = !(rt->colormask & PIPE_MASK_B);
1681          be.WriteDisableAlpha = !(rt->colormask & PIPE_MASK_A);
1682       }
1683       blend_entry += GENX(BLEND_STATE_ENTRY_length);
1684    }
1685 
1686    iris_pack_command(GENX(3DSTATE_PS_BLEND), cso->ps_blend, pb) {
1687       /* pb.HasWriteableRT is filled in at draw time.
1688        * pb.AlphaTestEnable is filled in at draw time.
1689        *
1690        * pb.ColorBufferBlendEnable is filled in at draw time so we can avoid
1691        * setting it when dual color blending without an appropriate shader.
1692        */
1693 
1694       pb.AlphaToCoverageEnable = state->alpha_to_coverage;
1695       pb.IndependentAlphaBlendEnable = indep_alpha_blend;
1696 
1697       /* The casts prevent warnings about implicit enum type conversions. */
1698       pb.SourceBlendFactor =
1699          (int) fix_blendfactor(state->rt[0].rgb_src_factor, state->alpha_to_one);
1700       pb.SourceAlphaBlendFactor =
1701          (int) fix_blendfactor(state->rt[0].alpha_src_factor, state->alpha_to_one);
1702    }
1703 
1704    iris_pack_state(GENX(BLEND_STATE), cso->blend_state, bs) {
1705       bs.AlphaToCoverageEnable = state->alpha_to_coverage;
1706       bs.IndependentAlphaBlendEnable = indep_alpha_blend;
1707       bs.AlphaToOneEnable = state->alpha_to_one;
1708       bs.AlphaToCoverageDitherEnable = state->alpha_to_coverage_dither;
1709       bs.ColorDitherEnable = state->dither;
1710       /* bl.AlphaTestEnable and bs.AlphaTestFunction are filled in later. */
1711    }
1712 
1713    cso->dual_color_blending = util_blend_state_is_dual(state, 0);
1714 
1715    return cso;
1716 }
1717 
1718 /**
1719  * The pipe->bind_blend_state() driver hook.
1720  *
1721  * Bind a blending CSO and flag related dirty bits.
1722  */
1723 static void
iris_bind_blend_state(struct pipe_context * ctx,void * state)1724 iris_bind_blend_state(struct pipe_context *ctx, void *state)
1725 {
1726    struct iris_context *ice = (struct iris_context *) ctx;
1727    struct iris_blend_state *cso = state;
1728 
1729    ice->state.cso_blend = cso;
1730 
1731    ice->state.dirty |= IRIS_DIRTY_PS_BLEND;
1732    ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
1733    ice->state.stage_dirty |= ice->state.stage_dirty_for_nos[IRIS_NOS_BLEND];
1734 
1735    if (GFX_VER == 8)
1736       ice->state.dirty |= IRIS_DIRTY_PMA_FIX;
1737 }
1738 
1739 /**
1740  * Return true if the FS writes to any color outputs which are not disabled
1741  * via color masking.
1742  */
1743 static bool
has_writeable_rt(const struct iris_blend_state * cso_blend,const struct shader_info * fs_info)1744 has_writeable_rt(const struct iris_blend_state *cso_blend,
1745                  const struct shader_info *fs_info)
1746 {
1747    if (!fs_info)
1748       return false;
1749 
1750    unsigned rt_outputs = fs_info->outputs_written >> FRAG_RESULT_DATA0;
1751 
1752    if (fs_info->outputs_written & BITFIELD64_BIT(FRAG_RESULT_COLOR))
1753       rt_outputs = (1 << IRIS_MAX_DRAW_BUFFERS) - 1;
1754 
1755    return cso_blend->color_write_enables & rt_outputs;
1756 }
1757 
1758 /**
1759  * Gallium CSO for depth, stencil, and alpha testing state.
1760  */
1761 struct iris_depth_stencil_alpha_state {
1762    /** Partial 3DSTATE_WM_DEPTH_STENCIL. */
1763    uint32_t wmds[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
1764 
1765 #if GFX_VER >= 12
1766    uint32_t depth_bounds[GENX(3DSTATE_DEPTH_BOUNDS_length)];
1767 #endif
1768 
1769    /** Outbound to BLEND_STATE, 3DSTATE_PS_BLEND, COLOR_CALC_STATE. */
1770    unsigned alpha_enabled:1;
1771    unsigned alpha_func:3;     /**< PIPE_FUNC_x */
1772    float alpha_ref_value;     /**< reference value */
1773 
1774    /** Outbound to resolve and cache set tracking. */
1775    bool depth_writes_enabled;
1776    bool stencil_writes_enabled;
1777 
1778    /** Outbound to Gfx8-9 PMA stall equations */
1779    bool depth_test_enabled;
1780 
1781    /** Tracking state of DS writes for Wa_18019816803. */
1782    bool ds_write_state;
1783 };
1784 
1785 /**
1786  * The pipe->create_depth_stencil_alpha_state() driver hook.
1787  *
1788  * We encode most of 3DSTATE_WM_DEPTH_STENCIL, and just save off the alpha
1789  * testing state since we need pieces of it in a variety of places.
1790  */
1791 static void *
iris_create_zsa_state(struct pipe_context * ctx,const struct pipe_depth_stencil_alpha_state * state)1792 iris_create_zsa_state(struct pipe_context *ctx,
1793                       const struct pipe_depth_stencil_alpha_state *state)
1794 {
1795    struct iris_depth_stencil_alpha_state *cso =
1796       malloc(sizeof(struct iris_depth_stencil_alpha_state));
1797 
1798    bool two_sided_stencil = state->stencil[1].enabled;
1799 
1800    bool depth_write_enabled = false;
1801    bool stencil_write_enabled = false;
1802 
1803    /* Depth writes enabled? */
1804    if (state->depth_writemask &&
1805       ((!state->depth_enabled) ||
1806       ((state->depth_func != PIPE_FUNC_NEVER) &&
1807         (state->depth_func != PIPE_FUNC_EQUAL))))
1808       depth_write_enabled = true;
1809 
1810    bool stencil_all_keep =
1811       state->stencil[0].fail_op == PIPE_STENCIL_OP_KEEP &&
1812       state->stencil[0].zfail_op == PIPE_STENCIL_OP_KEEP &&
1813       state->stencil[0].zpass_op == PIPE_STENCIL_OP_KEEP &&
1814       (!two_sided_stencil ||
1815        (state->stencil[1].fail_op == PIPE_STENCIL_OP_KEEP &&
1816         state->stencil[1].zfail_op == PIPE_STENCIL_OP_KEEP &&
1817         state->stencil[1].zpass_op == PIPE_STENCIL_OP_KEEP));
1818 
1819    bool stencil_mask_zero =
1820       state->stencil[0].writemask == 0 ||
1821       (!two_sided_stencil || state->stencil[1].writemask  == 0);
1822 
1823    bool stencil_func_never =
1824       state->stencil[0].func == PIPE_FUNC_NEVER &&
1825       state->stencil[0].fail_op == PIPE_STENCIL_OP_KEEP &&
1826       (!two_sided_stencil ||
1827        (state->stencil[1].func == PIPE_FUNC_NEVER &&
1828         state->stencil[1].fail_op == PIPE_STENCIL_OP_KEEP));
1829 
1830    /* Stencil writes enabled? */
1831    if (state->stencil[0].writemask != 0 ||
1832       ((two_sided_stencil && state->stencil[1].writemask != 0) &&
1833        (!stencil_all_keep &&
1834         !stencil_mask_zero &&
1835         !stencil_func_never)))
1836       stencil_write_enabled = true;
1837 
1838    cso->ds_write_state = depth_write_enabled || stencil_write_enabled;
1839 
1840    cso->alpha_enabled = state->alpha_enabled;
1841    cso->alpha_func = state->alpha_func;
1842    cso->alpha_ref_value = state->alpha_ref_value;
1843    cso->depth_writes_enabled = state->depth_writemask;
1844    cso->depth_test_enabled = state->depth_enabled;
1845    cso->stencil_writes_enabled =
1846       state->stencil[0].writemask != 0 ||
1847       (two_sided_stencil && state->stencil[1].writemask != 0);
1848 
1849    /* gallium frontends need to optimize away EQUAL writes for us. */
1850    assert(!(state->depth_func == PIPE_FUNC_EQUAL && state->depth_writemask));
1851 
1852    iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), cso->wmds, wmds) {
1853       wmds.StencilFailOp = state->stencil[0].fail_op;
1854       wmds.StencilPassDepthFailOp = state->stencil[0].zfail_op;
1855       wmds.StencilPassDepthPassOp = state->stencil[0].zpass_op;
1856       wmds.StencilTestFunction =
1857          translate_compare_func(state->stencil[0].func);
1858       wmds.BackfaceStencilFailOp = state->stencil[1].fail_op;
1859       wmds.BackfaceStencilPassDepthFailOp = state->stencil[1].zfail_op;
1860       wmds.BackfaceStencilPassDepthPassOp = state->stencil[1].zpass_op;
1861       wmds.BackfaceStencilTestFunction =
1862          translate_compare_func(state->stencil[1].func);
1863       wmds.DepthTestFunction = translate_compare_func(state->depth_func);
1864       wmds.DoubleSidedStencilEnable = two_sided_stencil;
1865       wmds.StencilTestEnable = state->stencil[0].enabled;
1866       wmds.StencilBufferWriteEnable =
1867          state->stencil[0].writemask != 0 ||
1868          (two_sided_stencil && state->stencil[1].writemask != 0);
1869       wmds.DepthTestEnable = state->depth_enabled;
1870       wmds.DepthBufferWriteEnable = state->depth_writemask;
1871       wmds.StencilTestMask = state->stencil[0].valuemask;
1872       wmds.StencilWriteMask = state->stencil[0].writemask;
1873       wmds.BackfaceStencilTestMask = state->stencil[1].valuemask;
1874       wmds.BackfaceStencilWriteMask = state->stencil[1].writemask;
1875       /* wmds.[Backface]StencilReferenceValue are merged later */
1876 #if GFX_VER >= 12
1877       wmds.StencilReferenceValueModifyDisable = true;
1878 #endif
1879    }
1880 
1881 #if GFX_VER >= 12
1882    iris_pack_command(GENX(3DSTATE_DEPTH_BOUNDS), cso->depth_bounds, depth_bounds) {
1883       depth_bounds.DepthBoundsTestValueModifyDisable = false;
1884       depth_bounds.DepthBoundsTestEnableModifyDisable = false;
1885       depth_bounds.DepthBoundsTestEnable = state->depth_bounds_test;
1886       depth_bounds.DepthBoundsTestMinValue = state->depth_bounds_min;
1887       depth_bounds.DepthBoundsTestMaxValue = state->depth_bounds_max;
1888    }
1889 #endif
1890 
1891    return cso;
1892 }
1893 
1894 /**
1895  * The pipe->bind_depth_stencil_alpha_state() driver hook.
1896  *
1897  * Bind a depth/stencil/alpha CSO and flag related dirty bits.
1898  */
1899 static void
iris_bind_zsa_state(struct pipe_context * ctx,void * state)1900 iris_bind_zsa_state(struct pipe_context *ctx, void *state)
1901 {
1902    struct iris_context *ice = (struct iris_context *) ctx;
1903    struct iris_depth_stencil_alpha_state *old_cso = ice->state.cso_zsa;
1904    struct iris_depth_stencil_alpha_state *new_cso = state;
1905 
1906    if (new_cso) {
1907       if (cso_changed(alpha_ref_value))
1908          ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
1909 
1910       if (cso_changed(alpha_enabled))
1911          ice->state.dirty |= IRIS_DIRTY_PS_BLEND | IRIS_DIRTY_BLEND_STATE;
1912 
1913       if (cso_changed(alpha_func))
1914          ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
1915 
1916       if (cso_changed(depth_writes_enabled) || cso_changed(stencil_writes_enabled))
1917          ice->state.dirty |= IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
1918 
1919       ice->state.depth_writes_enabled = new_cso->depth_writes_enabled;
1920       ice->state.stencil_writes_enabled = new_cso->stencil_writes_enabled;
1921 
1922       /* State ds_write_enable changed, need to flag dirty DS. */
1923       if (!old_cso || (ice->state.ds_write_state != new_cso->ds_write_state)) {
1924          ice->state.dirty |= IRIS_DIRTY_DS_WRITE_ENABLE;
1925          ice->state.ds_write_state = new_cso->ds_write_state;
1926       }
1927 
1928 #if GFX_VER >= 12
1929       if (cso_changed(depth_bounds))
1930          ice->state.dirty |= IRIS_DIRTY_DEPTH_BOUNDS;
1931 #endif
1932    }
1933 
1934    ice->state.cso_zsa = new_cso;
1935    ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
1936    ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
1937    ice->state.stage_dirty |=
1938       ice->state.stage_dirty_for_nos[IRIS_NOS_DEPTH_STENCIL_ALPHA];
1939 
1940    if (GFX_VER == 8)
1941       ice->state.dirty |= IRIS_DIRTY_PMA_FIX;
1942 }
1943 
1944 #if GFX_VER == 8
1945 static bool
want_pma_fix(struct iris_context * ice)1946 want_pma_fix(struct iris_context *ice)
1947 {
1948    UNUSED struct iris_screen *screen = (void *) ice->ctx.screen;
1949    UNUSED const struct intel_device_info *devinfo = screen->devinfo;
1950    const struct iris_fs_data *fs_data =
1951       iris_fs_data(ice->shaders.prog[MESA_SHADER_FRAGMENT]);
1952    const struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
1953    const struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
1954    const struct iris_blend_state *cso_blend = ice->state.cso_blend;
1955 
1956    /* In very specific combinations of state, we can instruct Gfx8-9 hardware
1957     * to avoid stalling at the pixel mask array.  The state equations are
1958     * documented in these places:
1959     *
1960     * - Gfx8 Depth PMA Fix:   CACHE_MODE_1::NP_PMA_FIX_ENABLE
1961     * - Gfx9 Stencil PMA Fix: CACHE_MODE_0::STC PMA Optimization Enable
1962     *
1963     * Both equations share some common elements:
1964     *
1965     *    no_hiz_op =
1966     *       !(3DSTATE_WM_HZ_OP::DepthBufferClear ||
1967     *         3DSTATE_WM_HZ_OP::DepthBufferResolve ||
1968     *         3DSTATE_WM_HZ_OP::Hierarchical Depth Buffer Resolve Enable ||
1969     *         3DSTATE_WM_HZ_OP::StencilBufferClear) &&
1970     *
1971     *    killpixels =
1972     *       3DSTATE_WM::ForceKillPix != ForceOff &&
1973     *       (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
1974     *        3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
1975     *        3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
1976     *        3DSTATE_PS_BLEND::AlphaTestEnable ||
1977     *        3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
1978     *
1979     *    (Technically the stencil PMA treats ForceKillPix differently,
1980     *     but I think this is a documentation oversight, and we don't
1981     *     ever use it in this way, so it doesn't matter).
1982     *
1983     *    common_pma_fix =
1984     *       3DSTATE_WM::ForceThreadDispatch != 1 &&
1985     *       3DSTATE_RASTER::ForceSampleCount == NUMRASTSAMPLES_0 &&
1986     *       3DSTATE_DEPTH_BUFFER::SURFACE_TYPE != NULL &&
1987     *       3DSTATE_DEPTH_BUFFER::HIZ Enable &&
1988     *       3DSTATE_WM::EDSC_Mode != EDSC_PREPS &&
1989     *       3DSTATE_PS_EXTRA::PixelShaderValid &&
1990     *       no_hiz_op
1991     *
1992     * These are always true:
1993     *
1994     *    3DSTATE_RASTER::ForceSampleCount == NUMRASTSAMPLES_0
1995     *    3DSTATE_PS_EXTRA::PixelShaderValid
1996     *
1997     * Also, we never use the normal drawing path for HiZ ops; these are true:
1998     *
1999     *    !(3DSTATE_WM_HZ_OP::DepthBufferClear ||
2000     *      3DSTATE_WM_HZ_OP::DepthBufferResolve ||
2001     *      3DSTATE_WM_HZ_OP::Hierarchical Depth Buffer Resolve Enable ||
2002     *      3DSTATE_WM_HZ_OP::StencilBufferClear)
2003     *
2004     * This happens sometimes:
2005     *
2006     *    3DSTATE_WM::ForceThreadDispatch != 1
2007     *
2008     * However, we choose to ignore it as it either agrees with the signal
2009     * (dispatch was already enabled, so nothing out of the ordinary), or
2010     * there are no framebuffer attachments (so no depth or HiZ anyway,
2011     * meaning the PMA signal will already be disabled).
2012     */
2013 
2014    if (!cso_fb->zsbuf)
2015       return false;
2016 
2017    struct iris_resource *zres, *sres;
2018    iris_get_depth_stencil_resources(cso_fb->zsbuf->texture, &zres, &sres);
2019 
2020    /* 3DSTATE_DEPTH_BUFFER::SURFACE_TYPE != NULL &&
2021     * 3DSTATE_DEPTH_BUFFER::HIZ Enable &&
2022     */
2023    if (!zres ||
2024        !iris_resource_level_has_hiz(devinfo, zres, cso_fb->zsbuf->u.tex.level))
2025       return false;
2026 
2027    /* 3DSTATE_WM::EDSC_Mode != EDSC_PREPS */
2028    if (fs_data->early_fragment_tests)
2029       return false;
2030 
2031    /* 3DSTATE_WM::ForceKillPix != ForceOff &&
2032     * (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
2033     *  3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
2034     *  3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
2035     *  3DSTATE_PS_BLEND::AlphaTestEnable ||
2036     *  3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
2037     */
2038    bool killpixels = fs_data->uses_kill || fs_data->uses_omask ||
2039                      cso_blend->alpha_to_coverage || cso_zsa->alpha_enabled;
2040 
2041    /* The Gfx8 depth PMA equation becomes:
2042     *
2043     *    depth_writes =
2044     *       3DSTATE_WM_DEPTH_STENCIL::DepthWriteEnable &&
2045     *       3DSTATE_DEPTH_BUFFER::DEPTH_WRITE_ENABLE
2046     *
2047     *    stencil_writes =
2048     *       3DSTATE_WM_DEPTH_STENCIL::Stencil Buffer Write Enable &&
2049     *       3DSTATE_DEPTH_BUFFER::STENCIL_WRITE_ENABLE &&
2050     *       3DSTATE_STENCIL_BUFFER::STENCIL_BUFFER_ENABLE
2051     *
2052     *    Z_PMA_OPT =
2053     *       common_pma_fix &&
2054     *       3DSTATE_WM_DEPTH_STENCIL::DepthTestEnable &&
2055     *       ((killpixels && (depth_writes || stencil_writes)) ||
2056     *        3DSTATE_PS_EXTRA::PixelShaderComputedDepthMode != PSCDEPTH_OFF)
2057     *
2058     */
2059    if (!cso_zsa->depth_test_enabled)
2060       return false;
2061 
2062    return fs_data->computed_depth_mode != PSCDEPTH_OFF ||
2063           (killpixels && (cso_zsa->depth_writes_enabled ||
2064                           (sres && cso_zsa->stencil_writes_enabled)));
2065 }
2066 #endif
2067 
2068 void
genX(update_pma_fix)2069 genX(update_pma_fix)(struct iris_context *ice,
2070                      struct iris_batch *batch,
2071                      bool enable)
2072 {
2073 #if GFX_VER == 8
2074    struct iris_genx_state *genx = ice->state.genx;
2075 
2076    if (genx->pma_fix_enabled == enable)
2077       return;
2078 
2079    genx->pma_fix_enabled = enable;
2080 
2081    /* According to the Broadwell PIPE_CONTROL documentation, software should
2082     * emit a PIPE_CONTROL with the CS Stall and Depth Cache Flush bits set
2083     * prior to the LRI.  If stencil buffer writes are enabled, then a Render        * Cache Flush is also necessary.
2084     *
2085     * The Gfx9 docs say to use a depth stall rather than a command streamer
2086     * stall.  However, the hardware seems to violently disagree.  A full
2087     * command streamer stall seems to be needed in both cases.
2088     */
2089    iris_emit_pipe_control_flush(batch, "PMA fix change (1/2)",
2090                                 PIPE_CONTROL_CS_STALL |
2091                                 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
2092                                 PIPE_CONTROL_RENDER_TARGET_FLUSH);
2093 
2094    iris_emit_reg(batch, GENX(CACHE_MODE_1), reg) {
2095       reg.NPPMAFixEnable = enable;
2096       reg.NPEarlyZFailsDisable = enable;
2097       reg.NPPMAFixEnableMask = true;
2098       reg.NPEarlyZFailsDisableMask = true;
2099    }
2100 
2101    /* After the LRI, a PIPE_CONTROL with both the Depth Stall and Depth Cache
2102     * Flush bits is often necessary.  We do it regardless because it's easier.
2103     * The render cache flush is also necessary if stencil writes are enabled.
2104     *
2105     * Again, the Gfx9 docs give a different set of flushes but the Broadwell
2106     * flushes seem to work just as well.
2107     */
2108    iris_emit_pipe_control_flush(batch, "PMA fix change (1/2)",
2109                                 PIPE_CONTROL_DEPTH_STALL |
2110                                 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
2111                                 PIPE_CONTROL_RENDER_TARGET_FLUSH);
2112 #endif
2113 }
2114 
2115 /**
2116  * Gallium CSO for rasterizer state.
2117  */
2118 struct iris_rasterizer_state {
2119    uint32_t sf[GENX(3DSTATE_SF_length)];
2120    uint32_t clip[GENX(3DSTATE_CLIP_length)];
2121    uint32_t raster[GENX(3DSTATE_RASTER_length)];
2122    uint32_t wm[GENX(3DSTATE_WM_length)];
2123    uint32_t line_stipple[GENX(3DSTATE_LINE_STIPPLE_length)];
2124 
2125    uint8_t num_clip_plane_consts;
2126    bool clip_halfz; /* for CC_VIEWPORT */
2127    bool depth_clip_near; /* for CC_VIEWPORT */
2128    bool depth_clip_far; /* for CC_VIEWPORT */
2129    bool flatshade; /* for shader state */
2130    bool flatshade_first; /* for stream output */
2131    bool clamp_fragment_color; /* for shader state */
2132    bool light_twoside; /* for shader state */
2133    bool rasterizer_discard; /* for 3DSTATE_STREAMOUT and 3DSTATE_CLIP */
2134    bool half_pixel_center; /* for 3DSTATE_MULTISAMPLE */
2135    bool line_smooth;
2136    bool line_stipple_enable;
2137    bool poly_stipple_enable;
2138    bool multisample;
2139    bool force_persample_interp;
2140    bool conservative_rasterization;
2141    bool fill_mode_point;
2142    bool fill_mode_line;
2143    bool fill_mode_point_or_line;
2144    enum pipe_sprite_coord_mode sprite_coord_mode; /* PIPE_SPRITE_* */
2145    uint16_t sprite_coord_enable;
2146 };
2147 
2148 static float
get_line_width(const struct pipe_rasterizer_state * state)2149 get_line_width(const struct pipe_rasterizer_state *state)
2150 {
2151    float line_width = state->line_width;
2152 
2153    /* From the OpenGL 4.4 spec:
2154     *
2155     * "The actual width of non-antialiased lines is determined by rounding
2156     *  the supplied width to the nearest integer, then clamping it to the
2157     *  implementation-dependent maximum non-antialiased line width."
2158     */
2159    if (!state->multisample && !state->line_smooth)
2160       line_width = roundf(state->line_width);
2161 
2162    if (!state->multisample && state->line_smooth && line_width < 1.5f) {
2163       /* For 1 pixel line thickness or less, the general anti-aliasing
2164        * algorithm gives up, and a garbage line is generated.  Setting a
2165        * Line Width of 0.0 specifies the rasterization of the "thinnest"
2166        * (one-pixel-wide), non-antialiased lines.
2167        *
2168        * Lines rendered with zero Line Width are rasterized using the
2169        * "Grid Intersection Quantization" rules as specified by the
2170        * "Zero-Width (Cosmetic) Line Rasterization" section of the docs.
2171        */
2172       line_width = 0.0f;
2173    }
2174 
2175    return line_width;
2176 }
2177 
2178 /**
2179  * The pipe->create_rasterizer_state() driver hook.
2180  */
2181 static void *
iris_create_rasterizer_state(struct pipe_context * ctx,const struct pipe_rasterizer_state * state)2182 iris_create_rasterizer_state(struct pipe_context *ctx,
2183                              const struct pipe_rasterizer_state *state)
2184 {
2185    struct iris_rasterizer_state *cso =
2186       malloc(sizeof(struct iris_rasterizer_state));
2187 
2188    cso->multisample = state->multisample;
2189    cso->force_persample_interp = state->force_persample_interp;
2190    cso->clip_halfz = state->clip_halfz;
2191    cso->depth_clip_near = state->depth_clip_near;
2192    cso->depth_clip_far = state->depth_clip_far;
2193    cso->flatshade = state->flatshade;
2194    cso->flatshade_first = state->flatshade_first;
2195    cso->clamp_fragment_color = state->clamp_fragment_color;
2196    cso->light_twoside = state->light_twoside;
2197    cso->rasterizer_discard = state->rasterizer_discard;
2198    cso->half_pixel_center = state->half_pixel_center;
2199    cso->sprite_coord_mode = state->sprite_coord_mode;
2200    cso->sprite_coord_enable = state->sprite_coord_enable;
2201    cso->line_smooth = state->line_smooth;
2202    cso->line_stipple_enable = state->line_stipple_enable;
2203    cso->poly_stipple_enable = state->poly_stipple_enable;
2204    cso->conservative_rasterization =
2205       state->conservative_raster_mode == PIPE_CONSERVATIVE_RASTER_POST_SNAP;
2206 
2207    cso->fill_mode_point =
2208       state->fill_front == PIPE_POLYGON_MODE_POINT ||
2209       state->fill_back == PIPE_POLYGON_MODE_POINT;
2210    cso->fill_mode_line =
2211       state->fill_front == PIPE_POLYGON_MODE_LINE ||
2212       state->fill_back == PIPE_POLYGON_MODE_LINE;
2213    cso->fill_mode_point_or_line =
2214       cso->fill_mode_point ||
2215       cso->fill_mode_line;
2216 
2217    if (state->clip_plane_enable != 0)
2218       cso->num_clip_plane_consts = util_logbase2(state->clip_plane_enable) + 1;
2219    else
2220       cso->num_clip_plane_consts = 0;
2221 
2222    float line_width = get_line_width(state);
2223 
2224    iris_pack_command(GENX(3DSTATE_SF), cso->sf, sf) {
2225       sf.StatisticsEnable = true;
2226       sf.AALineDistanceMode = AALINEDISTANCE_TRUE;
2227       sf.LineEndCapAntialiasingRegionWidth =
2228          state->line_smooth ? _10pixels : _05pixels;
2229       sf.LastPixelEnable = state->line_last_pixel;
2230       sf.LineWidth = line_width;
2231       sf.SmoothPointEnable = (state->point_smooth || state->multisample) &&
2232                              !state->point_quad_rasterization;
2233       sf.PointWidthSource = state->point_size_per_vertex ? Vertex : State;
2234       sf.PointWidth = CLAMP(state->point_size, 0.125f, 255.875f);
2235 
2236       if (state->flatshade_first) {
2237          sf.TriangleFanProvokingVertexSelect = 1;
2238       } else {
2239          sf.TriangleStripListProvokingVertexSelect = 2;
2240          sf.TriangleFanProvokingVertexSelect = 2;
2241          sf.LineStripListProvokingVertexSelect = 1;
2242       }
2243    }
2244 
2245    iris_pack_command(GENX(3DSTATE_RASTER), cso->raster, rr) {
2246       rr.FrontWinding = state->front_ccw ? CounterClockwise : Clockwise;
2247       rr.CullMode = translate_cull_mode(state->cull_face);
2248       rr.FrontFaceFillMode = translate_fill_mode(state->fill_front);
2249       rr.BackFaceFillMode = translate_fill_mode(state->fill_back);
2250       rr.DXMultisampleRasterizationEnable = state->multisample;
2251       rr.GlobalDepthOffsetEnableSolid = state->offset_tri;
2252       rr.GlobalDepthOffsetEnableWireframe = state->offset_line;
2253       rr.GlobalDepthOffsetEnablePoint = state->offset_point;
2254       rr.GlobalDepthOffsetConstant = state->offset_units * 2;
2255       rr.GlobalDepthOffsetScale = state->offset_scale;
2256       rr.GlobalDepthOffsetClamp = state->offset_clamp;
2257       rr.SmoothPointEnable = state->point_smooth;
2258       rr.ScissorRectangleEnable = state->scissor;
2259 #if GFX_VER >= 9
2260       rr.ViewportZNearClipTestEnable = state->depth_clip_near;
2261       rr.ViewportZFarClipTestEnable = state->depth_clip_far;
2262       rr.ConservativeRasterizationEnable =
2263          cso->conservative_rasterization;
2264 #else
2265       rr.ViewportZClipTestEnable = (state->depth_clip_near || state->depth_clip_far);
2266 #endif
2267    }
2268 
2269    iris_pack_command(GENX(3DSTATE_CLIP), cso->clip, cl) {
2270       /* cl.NonPerspectiveBarycentricEnable is filled in at draw time from
2271        * the FS program; cl.ForceZeroRTAIndexEnable is filled in from the FB.
2272        */
2273       cl.EarlyCullEnable = true;
2274       cl.UserClipDistanceClipTestEnableBitmask = state->clip_plane_enable;
2275       cl.ForceUserClipDistanceClipTestEnableBitmask = true;
2276       cl.APIMode = state->clip_halfz ? APIMODE_D3D : APIMODE_OGL;
2277       cl.GuardbandClipTestEnable = true;
2278       cl.ClipEnable = true;
2279       cl.MinimumPointWidth = 0.125;
2280       cl.MaximumPointWidth = 255.875;
2281 
2282       if (state->flatshade_first) {
2283          cl.TriangleFanProvokingVertexSelect = 1;
2284       } else {
2285          cl.TriangleStripListProvokingVertexSelect = 2;
2286          cl.TriangleFanProvokingVertexSelect = 2;
2287          cl.LineStripListProvokingVertexSelect = 1;
2288       }
2289    }
2290 
2291    iris_pack_command(GENX(3DSTATE_WM), cso->wm, wm) {
2292       /* wm.BarycentricInterpolationMode and wm.EarlyDepthStencilControl are
2293        * filled in at draw time from the FS program.
2294        */
2295       wm.LineAntialiasingRegionWidth = _10pixels;
2296       wm.LineEndCapAntialiasingRegionWidth = _05pixels;
2297       wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
2298       wm.LineStippleEnable = state->line_stipple_enable;
2299       wm.PolygonStippleEnable = state->poly_stipple_enable;
2300    }
2301 
2302    /* Remap from 0..255 back to 1..256 */
2303    const unsigned line_stipple_factor = state->line_stipple_factor + 1;
2304 
2305    iris_pack_command(GENX(3DSTATE_LINE_STIPPLE), cso->line_stipple, line) {
2306       if (state->line_stipple_enable) {
2307          line.LineStipplePattern = state->line_stipple_pattern;
2308          line.LineStippleInverseRepeatCount = 1.0f / line_stipple_factor;
2309          line.LineStippleRepeatCount = line_stipple_factor;
2310       }
2311    }
2312 
2313    return cso;
2314 }
2315 
2316 /**
2317  * The pipe->bind_rasterizer_state() driver hook.
2318  *
2319  * Bind a rasterizer CSO and flag related dirty bits.
2320  */
2321 static void
iris_bind_rasterizer_state(struct pipe_context * ctx,void * state)2322 iris_bind_rasterizer_state(struct pipe_context *ctx, void *state)
2323 {
2324    struct iris_context *ice = (struct iris_context *) ctx;
2325    struct iris_rasterizer_state *old_cso = ice->state.cso_rast;
2326    struct iris_rasterizer_state *new_cso = state;
2327 
2328    if (new_cso) {
2329       /* Try to avoid re-emitting 3DSTATE_LINE_STIPPLE, it's non-pipelined */
2330       if (cso_changed_memcmp(line_stipple))
2331          ice->state.dirty |= IRIS_DIRTY_LINE_STIPPLE;
2332 
2333       if (cso_changed(half_pixel_center))
2334          ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
2335 
2336       if (cso_changed(line_stipple_enable) || cso_changed(poly_stipple_enable))
2337          ice->state.dirty |= IRIS_DIRTY_WM;
2338 
2339       if (cso_changed(rasterizer_discard))
2340          ice->state.dirty |= IRIS_DIRTY_STREAMOUT | IRIS_DIRTY_CLIP;
2341 
2342       if (cso_changed(flatshade_first))
2343          ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
2344 
2345       if (cso_changed(depth_clip_near) || cso_changed(depth_clip_far) ||
2346           cso_changed(clip_halfz))
2347          ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
2348 
2349       if (cso_changed(sprite_coord_enable) ||
2350           cso_changed(sprite_coord_mode) ||
2351           cso_changed(light_twoside))
2352          ice->state.dirty |= IRIS_DIRTY_SBE;
2353 
2354       if (cso_changed(conservative_rasterization))
2355          ice->state.stage_dirty |= IRIS_STAGE_DIRTY_FS;
2356    }
2357 
2358    ice->state.cso_rast = new_cso;
2359    ice->state.dirty |= IRIS_DIRTY_RASTER;
2360    ice->state.dirty |= IRIS_DIRTY_CLIP;
2361    ice->state.stage_dirty |=
2362       ice->state.stage_dirty_for_nos[IRIS_NOS_RASTERIZER];
2363 }
2364 
2365 /**
2366  * Return true if the given wrap mode requires the border color to exist.
2367  *
2368  * (We can skip uploading it if the sampler isn't going to use it.)
2369  */
2370 static bool
wrap_mode_needs_border_color(unsigned wrap_mode)2371 wrap_mode_needs_border_color(unsigned wrap_mode)
2372 {
2373    return wrap_mode == TCM_CLAMP_BORDER || wrap_mode == TCM_HALF_BORDER;
2374 }
2375 
2376 /**
2377  * Gallium CSO for sampler state.
2378  */
2379 struct iris_sampler_state {
2380    union pipe_color_union border_color;
2381    bool needs_border_color;
2382 
2383    uint32_t sampler_state[GENX(SAMPLER_STATE_length)];
2384 
2385 #if GFX_VERx10 == 125
2386    /* Sampler state structure to use for 3D textures in order to
2387     * implement Wa_14014414195.
2388     */
2389    uint32_t sampler_state_3d[GENX(SAMPLER_STATE_length)];
2390 #endif
2391 };
2392 
2393 static void
fill_sampler_state(uint32_t * sampler_state,const struct pipe_sampler_state * state,unsigned max_anisotropy)2394 fill_sampler_state(uint32_t *sampler_state,
2395                    const struct pipe_sampler_state *state,
2396                    unsigned max_anisotropy)
2397 {
2398    float min_lod = state->min_lod;
2399    unsigned mag_img_filter = state->mag_img_filter;
2400 
2401    // XXX: explain this code ported from ilo...I don't get it at all...
2402    if (state->min_mip_filter == PIPE_TEX_MIPFILTER_NONE &&
2403        state->min_lod > 0.0f) {
2404       min_lod = 0.0f;
2405       mag_img_filter = state->min_img_filter;
2406    }
2407 
2408    iris_pack_state(GENX(SAMPLER_STATE), sampler_state, samp) {
2409       samp.TCXAddressControlMode = translate_wrap(state->wrap_s);
2410       samp.TCYAddressControlMode = translate_wrap(state->wrap_t);
2411       samp.TCZAddressControlMode = translate_wrap(state->wrap_r);
2412       samp.CubeSurfaceControlMode = state->seamless_cube_map;
2413       samp.NonnormalizedCoordinateEnable = state->unnormalized_coords;
2414       samp.MinModeFilter = state->min_img_filter;
2415       samp.MagModeFilter = mag_img_filter;
2416       samp.MipModeFilter = translate_mip_filter(state->min_mip_filter);
2417       samp.MaximumAnisotropy = RATIO21;
2418 
2419       if (max_anisotropy >= 2) {
2420          if (state->min_img_filter == PIPE_TEX_FILTER_LINEAR) {
2421             samp.MinModeFilter = MAPFILTER_ANISOTROPIC;
2422             samp.AnisotropicAlgorithm = EWAApproximation;
2423          }
2424 
2425          if (state->mag_img_filter == PIPE_TEX_FILTER_LINEAR)
2426             samp.MagModeFilter = MAPFILTER_ANISOTROPIC;
2427 
2428          samp.MaximumAnisotropy =
2429             MIN2((max_anisotropy - 2) / 2, RATIO161);
2430       }
2431 
2432       /* Set address rounding bits if not using nearest filtering. */
2433       if (state->min_img_filter != PIPE_TEX_FILTER_NEAREST) {
2434          samp.UAddressMinFilterRoundingEnable = true;
2435          samp.VAddressMinFilterRoundingEnable = true;
2436          samp.RAddressMinFilterRoundingEnable = true;
2437       }
2438 
2439       if (state->mag_img_filter != PIPE_TEX_FILTER_NEAREST) {
2440          samp.UAddressMagFilterRoundingEnable = true;
2441          samp.VAddressMagFilterRoundingEnable = true;
2442          samp.RAddressMagFilterRoundingEnable = true;
2443       }
2444 
2445       if (state->compare_mode == PIPE_TEX_COMPARE_R_TO_TEXTURE)
2446          samp.ShadowFunction = translate_shadow_func(state->compare_func);
2447 
2448       const float hw_max_lod = GFX_VER >= 7 ? 14 : 13;
2449 
2450       samp.LODPreClampMode = CLAMP_MODE_OGL;
2451       samp.MinLOD = CLAMP(min_lod, 0, hw_max_lod);
2452       samp.MaxLOD = CLAMP(state->max_lod, 0, hw_max_lod);
2453       samp.TextureLODBias = CLAMP(state->lod_bias, -16, 15);
2454 
2455       /* .BorderColorPointer is filled in by iris_bind_sampler_states. */
2456    }
2457 }
2458 
2459 /**
2460  * The pipe->create_sampler_state() driver hook.
2461  *
2462  * We fill out SAMPLER_STATE (except for the border color pointer), and
2463  * store that on the CPU.  It doesn't make sense to upload it to a GPU
2464  * buffer object yet, because 3DSTATE_SAMPLER_STATE_POINTERS requires
2465  * all bound sampler states to be in contiguous memor.
2466  */
2467 static void *
iris_create_sampler_state(struct pipe_context * ctx,const struct pipe_sampler_state * state)2468 iris_create_sampler_state(struct pipe_context *ctx,
2469                           const struct pipe_sampler_state *state)
2470 {
2471    UNUSED struct iris_screen *screen = (void *)ctx->screen;
2472    UNUSED const struct intel_device_info *devinfo = screen->devinfo;
2473    struct iris_sampler_state *cso = CALLOC_STRUCT(iris_sampler_state);
2474 
2475    if (!cso)
2476       return NULL;
2477 
2478    STATIC_ASSERT(PIPE_TEX_FILTER_NEAREST == MAPFILTER_NEAREST);
2479    STATIC_ASSERT(PIPE_TEX_FILTER_LINEAR == MAPFILTER_LINEAR);
2480 
2481    unsigned wrap_s = translate_wrap(state->wrap_s);
2482    unsigned wrap_t = translate_wrap(state->wrap_t);
2483    unsigned wrap_r = translate_wrap(state->wrap_r);
2484 
2485    memcpy(&cso->border_color, &state->border_color, sizeof(cso->border_color));
2486 
2487    cso->needs_border_color = wrap_mode_needs_border_color(wrap_s) ||
2488                              wrap_mode_needs_border_color(wrap_t) ||
2489                              wrap_mode_needs_border_color(wrap_r);
2490 
2491    fill_sampler_state(cso->sampler_state, state, state->max_anisotropy);
2492 
2493 #if GFX_VERx10 == 125
2494    /* Fill an extra sampler state structure with anisotropic filtering
2495     * disabled used to implement Wa_14014414195.
2496     */
2497    if (intel_needs_workaround(screen->devinfo, 14014414195))
2498       fill_sampler_state(cso->sampler_state_3d, state, 0);
2499 #endif
2500 
2501    return cso;
2502 }
2503 
2504 /**
2505  * The pipe->bind_sampler_states() driver hook.
2506  */
2507 static void
iris_bind_sampler_states(struct pipe_context * ctx,enum pipe_shader_type p_stage,unsigned start,unsigned count,void ** states)2508 iris_bind_sampler_states(struct pipe_context *ctx,
2509                          enum pipe_shader_type p_stage,
2510                          unsigned start, unsigned count,
2511                          void **states)
2512 {
2513    struct iris_context *ice = (struct iris_context *) ctx;
2514    gl_shader_stage stage = stage_from_pipe(p_stage);
2515    struct iris_shader_state *shs = &ice->state.shaders[stage];
2516 
2517    assert(start + count <= IRIS_MAX_SAMPLERS);
2518 
2519    bool dirty = false;
2520 
2521    for (int i = 0; i < count; i++) {
2522       struct iris_sampler_state *state = states ? states[i] : NULL;
2523       if (shs->samplers[start + i] != state) {
2524          shs->samplers[start + i] = state;
2525          dirty = true;
2526       }
2527    }
2528 
2529    if (dirty)
2530       ice->state.stage_dirty |= IRIS_STAGE_DIRTY_SAMPLER_STATES_VS << stage;
2531 }
2532 
2533 /**
2534  * Upload the sampler states into a contiguous area of GPU memory, for
2535  * for 3DSTATE_SAMPLER_STATE_POINTERS_*.
2536  *
2537  * Also fill out the border color state pointers.
2538  */
2539 static void
iris_upload_sampler_states(struct iris_context * ice,gl_shader_stage stage)2540 iris_upload_sampler_states(struct iris_context *ice, gl_shader_stage stage)
2541 {
2542    struct iris_screen *screen = (struct iris_screen *) ice->ctx.screen;
2543    struct iris_compiled_shader *shader = ice->shaders.prog[stage];
2544    struct iris_shader_state *shs = &ice->state.shaders[stage];
2545    struct iris_border_color_pool *border_color_pool =
2546       iris_bufmgr_get_border_color_pool(screen->bufmgr);
2547 
2548    /* We assume gallium frontends will call pipe->bind_sampler_states()
2549     * if the program's number of textures changes.
2550     */
2551    unsigned count = util_last_bit64(shader->bt.samplers_used_mask);
2552 
2553    if (!count)
2554       return;
2555 
2556    /* Assemble the SAMPLER_STATEs into a contiguous table that lives
2557     * in the dynamic state memory zone, so we can point to it via the
2558     * 3DSTATE_SAMPLER_STATE_POINTERS_* commands.
2559     */
2560    unsigned size = count * 4 * GENX(SAMPLER_STATE_length);
2561    uint32_t *map =
2562       upload_state(ice->state.dynamic_uploader, &shs->sampler_table, size, 32);
2563    if (unlikely(!map))
2564       return;
2565 
2566    struct pipe_resource *res = shs->sampler_table.res;
2567    struct iris_bo *bo = iris_resource_bo(res);
2568 
2569    iris_record_state_size(ice->state.sizes,
2570                           bo->address + shs->sampler_table.offset, size);
2571 
2572    shs->sampler_table.offset += iris_bo_offset_from_base_address(bo);
2573 
2574    ice->state.need_border_colors &= ~(1 << stage);
2575 
2576    for (int i = 0; i < count; i++) {
2577       struct iris_sampler_state *state = shs->samplers[i];
2578       struct iris_sampler_view *tex = shs->textures[i];
2579 
2580       if (!state) {
2581          memset(map, 0, 4 * GENX(SAMPLER_STATE_length));
2582       } else {
2583          const uint32_t *sampler_state = state->sampler_state;
2584 
2585 #if GFX_VERx10 == 125
2586          if (intel_needs_workaround(screen->devinfo, 14014414195) &&
2587              tex && tex->res->base.b.target == PIPE_TEXTURE_3D) {
2588                sampler_state = state->sampler_state_3d;
2589          }
2590 #endif
2591 
2592          if (!state->needs_border_color) {
2593             memcpy(map, sampler_state, 4 * GENX(SAMPLER_STATE_length));
2594          } else {
2595             ice->state.need_border_colors |= 1 << stage;
2596 
2597             /* We may need to swizzle the border color for format faking.
2598              * A/LA formats are faked as R/RG with 000R or R00G swizzles.
2599              * This means we need to move the border color's A channel into
2600              * the R or G channels so that those read swizzles will move it
2601              * back into A.
2602              */
2603             union pipe_color_union *color = &state->border_color;
2604             union pipe_color_union tmp;
2605             if (tex) {
2606                enum pipe_format internal_format = tex->res->internal_format;
2607 
2608                if (util_format_is_alpha(internal_format)) {
2609                   unsigned char swz[4] = {
2610                      PIPE_SWIZZLE_W, PIPE_SWIZZLE_0,
2611                      PIPE_SWIZZLE_0, PIPE_SWIZZLE_0
2612                   };
2613                   util_format_apply_color_swizzle(&tmp, color, swz, true);
2614                   color = &tmp;
2615                } else if (util_format_is_luminance_alpha(internal_format) &&
2616                           internal_format != PIPE_FORMAT_L8A8_SRGB) {
2617                   unsigned char swz[4] = {
2618                      PIPE_SWIZZLE_X, PIPE_SWIZZLE_W,
2619                      PIPE_SWIZZLE_0, PIPE_SWIZZLE_0
2620                   };
2621                   util_format_apply_color_swizzle(&tmp, color, swz, true);
2622                   color = &tmp;
2623                }
2624             }
2625 
2626             /* Stream out the border color and merge the pointer. */
2627             uint32_t offset = iris_upload_border_color(border_color_pool,
2628                                                        color);
2629 
2630             uint32_t dynamic[GENX(SAMPLER_STATE_length)];
2631             iris_pack_state(GENX(SAMPLER_STATE), dynamic, dyns) {
2632                dyns.BorderColorPointer = offset;
2633             }
2634 
2635             for (uint32_t j = 0; j < GENX(SAMPLER_STATE_length); j++)
2636                map[j] = sampler_state[j] | dynamic[j];
2637          }
2638       }
2639 
2640       map += GENX(SAMPLER_STATE_length);
2641    }
2642 }
2643 
2644 static enum isl_channel_select
fmt_swizzle(const struct iris_format_info * fmt,enum pipe_swizzle swz)2645 fmt_swizzle(const struct iris_format_info *fmt, enum pipe_swizzle swz)
2646 {
2647    switch (swz) {
2648    case PIPE_SWIZZLE_X: return fmt->swizzle.r;
2649    case PIPE_SWIZZLE_Y: return fmt->swizzle.g;
2650    case PIPE_SWIZZLE_Z: return fmt->swizzle.b;
2651    case PIPE_SWIZZLE_W: return fmt->swizzle.a;
2652    case PIPE_SWIZZLE_1: return ISL_CHANNEL_SELECT_ONE;
2653    case PIPE_SWIZZLE_0: return ISL_CHANNEL_SELECT_ZERO;
2654    default: unreachable("invalid swizzle");
2655    }
2656 }
2657 
2658 static void
fill_buffer_surface_state(struct isl_device * isl_dev,struct iris_resource * res,void * map,enum isl_format format,struct isl_swizzle swizzle,unsigned offset,unsigned size,isl_surf_usage_flags_t usage)2659 fill_buffer_surface_state(struct isl_device *isl_dev,
2660                           struct iris_resource *res,
2661                           void *map,
2662                           enum isl_format format,
2663                           struct isl_swizzle swizzle,
2664                           unsigned offset,
2665                           unsigned size,
2666                           isl_surf_usage_flags_t usage)
2667 {
2668    const struct isl_format_layout *fmtl = isl_format_get_layout(format);
2669    const unsigned cpp = format == ISL_FORMAT_RAW ? 1 : fmtl->bpb / 8;
2670 
2671    /* The ARB_texture_buffer_specification says:
2672     *
2673     *    "The number of texels in the buffer texture's texel array is given by
2674     *
2675     *       floor(<buffer_size> / (<components> * sizeof(<base_type>)),
2676     *
2677     *     where <buffer_size> is the size of the buffer object, in basic
2678     *     machine units and <components> and <base_type> are the element count
2679     *     and base data type for elements, as specified in Table X.1.  The
2680     *     number of texels in the texel array is then clamped to the
2681     *     implementation-dependent limit MAX_TEXTURE_BUFFER_SIZE_ARB."
2682     *
2683     * We need to clamp the size in bytes to MAX_TEXTURE_BUFFER_SIZE * stride,
2684     * so that when ISL divides by stride to obtain the number of texels, that
2685     * texel count is clamped to MAX_TEXTURE_BUFFER_SIZE.
2686     */
2687    unsigned final_size =
2688       MIN3(size, res->bo->size - res->offset - offset,
2689            IRIS_MAX_TEXTURE_BUFFER_SIZE * cpp);
2690 
2691    isl_buffer_fill_state(isl_dev, map,
2692                          .address = res->bo->address + res->offset + offset,
2693                          .size_B = final_size,
2694                          .format = format,
2695                          .swizzle = swizzle,
2696                          .stride_B = cpp,
2697                          .mocs = iris_mocs(res->bo, isl_dev, usage));
2698 }
2699 
2700 #define SURFACE_STATE_ALIGNMENT 64
2701 
2702 /**
2703  * Allocate several contiguous SURFACE_STATE structures, one for each
2704  * supported auxiliary surface mode.  This only allocates the CPU-side
2705  * copy, they will need to be uploaded later after they're filled in.
2706  */
2707 static void
alloc_surface_states(struct iris_surface_state * surf_state,unsigned aux_usages)2708 alloc_surface_states(struct iris_surface_state *surf_state,
2709                      unsigned aux_usages)
2710 {
2711    enum { surf_size = 4 * GENX(RENDER_SURFACE_STATE_length) };
2712 
2713    /* If this changes, update this to explicitly align pointers */
2714    STATIC_ASSERT(surf_size == SURFACE_STATE_ALIGNMENT);
2715 
2716    assert(aux_usages != 0);
2717 
2718    /* In case we're re-allocating them... */
2719    free(surf_state->cpu);
2720 
2721    surf_state->aux_usages = aux_usages;
2722    surf_state->num_states = util_bitcount(aux_usages);
2723    surf_state->cpu = calloc(surf_state->num_states, surf_size);
2724    surf_state->ref.offset = 0;
2725    pipe_resource_reference(&surf_state->ref.res, NULL);
2726 
2727    assert(surf_state->cpu);
2728 }
2729 
2730 /**
2731  * Upload the CPU side SURFACE_STATEs into a GPU buffer.
2732  */
2733 static void
upload_surface_states(struct u_upload_mgr * mgr,struct iris_surface_state * surf_state)2734 upload_surface_states(struct u_upload_mgr *mgr,
2735                       struct iris_surface_state *surf_state)
2736 {
2737    const unsigned surf_size = 4 * GENX(RENDER_SURFACE_STATE_length);
2738    const unsigned bytes = surf_state->num_states * surf_size;
2739 
2740    void *map =
2741       upload_state(mgr, &surf_state->ref, bytes, SURFACE_STATE_ALIGNMENT);
2742 
2743    surf_state->ref.offset +=
2744       iris_bo_offset_from_base_address(iris_resource_bo(surf_state->ref.res));
2745 
2746    if (map)
2747       memcpy(map, surf_state->cpu, bytes);
2748 }
2749 
2750 /**
2751  * Update resource addresses in a set of SURFACE_STATE descriptors,
2752  * and re-upload them if necessary.
2753  */
2754 static bool
update_surface_state_addrs(struct u_upload_mgr * mgr,struct iris_surface_state * surf_state,struct iris_bo * bo)2755 update_surface_state_addrs(struct u_upload_mgr *mgr,
2756                            struct iris_surface_state *surf_state,
2757                            struct iris_bo *bo)
2758 {
2759    if (surf_state->bo_address == bo->address)
2760       return false;
2761 
2762    STATIC_ASSERT(GENX(RENDER_SURFACE_STATE_SurfaceBaseAddress_start) % 64 == 0);
2763    STATIC_ASSERT(GENX(RENDER_SURFACE_STATE_SurfaceBaseAddress_bits) == 64);
2764 
2765    uint64_t *ss_addr = (uint64_t *) &surf_state->cpu[GENX(RENDER_SURFACE_STATE_SurfaceBaseAddress_start) / 32];
2766 
2767    /* First, update the CPU copies.  We assume no other fields exist in
2768     * the QWord containing Surface Base Address.
2769     */
2770    for (unsigned i = 0; i < surf_state->num_states; i++) {
2771       *ss_addr = *ss_addr - surf_state->bo_address + bo->address;
2772       ss_addr = ((void *) ss_addr) + SURFACE_STATE_ALIGNMENT;
2773    }
2774 
2775    /* Next, upload the updated copies to a GPU buffer. */
2776    upload_surface_states(mgr, surf_state);
2777 
2778    surf_state->bo_address = bo->address;
2779 
2780    return true;
2781 }
2782 
2783 /* We should only use this function when it's needed to fill out
2784  * surf with information provided by the pipe_(image|sampler)_view.
2785  * This is only necessary for CL extension cl_khr_image2d_from_buffer.
2786  * This is the reason why ISL_SURF_DIM_2D is hardcoded on dim field.
2787  */
2788 static void
fill_surf_for_tex2d_from_buffer(struct isl_device * isl_dev,enum isl_format format,unsigned width,unsigned height,unsigned row_stride,isl_surf_usage_flags_t usage,struct isl_surf * surf)2789 fill_surf_for_tex2d_from_buffer(struct isl_device *isl_dev,
2790                                 enum isl_format format,
2791                                 unsigned width,
2792                                 unsigned height,
2793                                 unsigned row_stride,
2794                                 isl_surf_usage_flags_t usage,
2795                                 struct isl_surf *surf)
2796 {
2797    const struct isl_format_layout *fmtl = isl_format_get_layout(format);
2798    const unsigned cpp = format == ISL_FORMAT_RAW ? 1 : fmtl->bpb / 8;
2799 
2800    const struct isl_surf_init_info init_info = {
2801       .dim = ISL_SURF_DIM_2D,
2802       .format = format,
2803       .width = width,
2804       .height = height,
2805       .depth = 1,
2806       .levels = 1,
2807       .array_len = 1,
2808       .samples = 1,
2809       .min_alignment_B = 4,
2810       .row_pitch_B = row_stride * cpp,
2811       .usage = usage,
2812       .tiling_flags = ISL_TILING_LINEAR_BIT,
2813    };
2814 
2815    const bool isl_surf_created_successfully =
2816       isl_surf_init_s(isl_dev, surf, &init_info);
2817 
2818    assert(isl_surf_created_successfully);
2819 }
2820 
2821 static void
fill_surface_state(struct isl_device * isl_dev,void * map,struct iris_resource * res,struct isl_surf * surf,struct isl_view * view,unsigned aux_usage,uint32_t extra_main_offset,uint32_t tile_x_sa,uint32_t tile_y_sa)2822 fill_surface_state(struct isl_device *isl_dev,
2823                    void *map,
2824                    struct iris_resource *res,
2825                    struct isl_surf *surf,
2826                    struct isl_view *view,
2827                    unsigned aux_usage,
2828                    uint32_t extra_main_offset,
2829                    uint32_t tile_x_sa,
2830                    uint32_t tile_y_sa)
2831 {
2832    struct isl_surf_fill_state_info f = {
2833       .surf = surf,
2834       .view = view,
2835       .mocs = iris_mocs(res->bo, isl_dev, view->usage),
2836       .address = res->bo->address + res->offset + extra_main_offset,
2837       .x_offset_sa = tile_x_sa,
2838       .y_offset_sa = tile_y_sa,
2839    };
2840 
2841    if (aux_usage != ISL_AUX_USAGE_NONE) {
2842       f.aux_surf = &res->aux.surf;
2843       f.aux_usage = aux_usage;
2844       f.clear_color = res->aux.clear_color;
2845 
2846       if (aux_usage == ISL_AUX_USAGE_MC)
2847          f.mc_format = iris_format_for_usage(isl_dev->info,
2848                                              res->external_format,
2849                                              surf->usage).fmt;
2850 
2851       if (res->aux.bo)
2852          f.aux_address = res->aux.bo->address + res->aux.offset;
2853 
2854       if (res->aux.clear_color_bo) {
2855          f.clear_address = res->aux.clear_color_bo->address +
2856                            res->aux.clear_color_offset;
2857          f.use_clear_address = isl_dev->info->ver > 9;
2858       }
2859    }
2860 
2861    isl_surf_fill_state_s(isl_dev, map, &f);
2862 }
2863 
2864 static void
fill_surface_states(struct isl_device * isl_dev,struct iris_surface_state * surf_state,struct iris_resource * res,struct isl_surf * surf,struct isl_view * view,uint64_t extra_main_offset,uint32_t tile_x_sa,uint32_t tile_y_sa)2865 fill_surface_states(struct isl_device *isl_dev,
2866                     struct iris_surface_state *surf_state,
2867                     struct iris_resource *res,
2868                     struct isl_surf *surf,
2869                     struct isl_view *view,
2870                     uint64_t extra_main_offset,
2871                     uint32_t tile_x_sa,
2872                     uint32_t tile_y_sa)
2873 {
2874    void *map = surf_state->cpu;
2875    unsigned aux_modes = surf_state->aux_usages;
2876 
2877    while (aux_modes) {
2878       enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
2879 
2880       fill_surface_state(isl_dev, map, res, surf, view, aux_usage,
2881                          extra_main_offset, tile_x_sa, tile_y_sa);
2882 
2883       map += SURFACE_STATE_ALIGNMENT;
2884    }
2885 }
2886 
2887 /**
2888  * The pipe->create_sampler_view() driver hook.
2889  */
2890 static struct pipe_sampler_view *
iris_create_sampler_view(struct pipe_context * ctx,struct pipe_resource * tex,const struct pipe_sampler_view * tmpl)2891 iris_create_sampler_view(struct pipe_context *ctx,
2892                          struct pipe_resource *tex,
2893                          const struct pipe_sampler_view *tmpl)
2894 {
2895    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
2896    const struct intel_device_info *devinfo = screen->devinfo;
2897    struct iris_sampler_view *isv = calloc(1, sizeof(struct iris_sampler_view));
2898 
2899    if (!isv)
2900       return NULL;
2901 
2902    /* initialize base object */
2903    isv->base = *tmpl;
2904    isv->base.context = ctx;
2905    isv->base.texture = NULL;
2906    pipe_reference_init(&isv->base.reference, 1);
2907    pipe_resource_reference(&isv->base.texture, tex);
2908 
2909    if (util_format_is_depth_or_stencil(tmpl->format)) {
2910       struct iris_resource *zres, *sres;
2911       const struct util_format_description *desc =
2912          util_format_description(tmpl->format);
2913 
2914       iris_get_depth_stencil_resources(tex, &zres, &sres);
2915 
2916       tex = util_format_has_depth(desc) ? &zres->base.b : &sres->base.b;
2917    }
2918 
2919    isv->res = (struct iris_resource *) tex;
2920 
2921    isl_surf_usage_flags_t usage = ISL_SURF_USAGE_TEXTURE_BIT;
2922 
2923    if (isv->base.target == PIPE_TEXTURE_CUBE ||
2924        isv->base.target == PIPE_TEXTURE_CUBE_ARRAY)
2925       usage |= ISL_SURF_USAGE_CUBE_BIT;
2926 
2927    const struct iris_format_info fmt =
2928       iris_format_for_usage(devinfo, tmpl->format, usage);
2929 
2930    isv->clear_color = isv->res->aux.clear_color;
2931 
2932    isv->view = (struct isl_view) {
2933       .format = fmt.fmt,
2934       .swizzle = (struct isl_swizzle) {
2935          .r = fmt_swizzle(&fmt, tmpl->swizzle_r),
2936          .g = fmt_swizzle(&fmt, tmpl->swizzle_g),
2937          .b = fmt_swizzle(&fmt, tmpl->swizzle_b),
2938          .a = fmt_swizzle(&fmt, tmpl->swizzle_a),
2939       },
2940       .usage = usage,
2941    };
2942 
2943    unsigned aux_usages = 0;
2944 
2945    if ((isv->res->aux.usage == ISL_AUX_USAGE_CCS_D ||
2946         isv->res->aux.usage == ISL_AUX_USAGE_CCS_E ||
2947         isv->res->aux.usage == ISL_AUX_USAGE_FCV_CCS_E) &&
2948        !isl_format_supports_ccs_e(devinfo, isv->view.format)) {
2949       aux_usages = 1 << ISL_AUX_USAGE_NONE;
2950    } else if (isl_aux_usage_has_hiz(isv->res->aux.usage) &&
2951               !iris_sample_with_depth_aux(devinfo, isv->res)) {
2952       aux_usages = 1 << ISL_AUX_USAGE_NONE;
2953    } else {
2954       aux_usages = 1 << ISL_AUX_USAGE_NONE |
2955                    1 << isv->res->aux.usage;
2956    }
2957 
2958    alloc_surface_states(&isv->surface_state, aux_usages);
2959    isv->surface_state.bo_address = isv->res->bo->address;
2960 
2961    /* Fill out SURFACE_STATE for this view. */
2962    if (tmpl->target != PIPE_BUFFER) {
2963       isv->view.base_level = tmpl->u.tex.first_level;
2964       isv->view.levels = tmpl->u.tex.last_level - tmpl->u.tex.first_level + 1;
2965 
2966       if (tmpl->target == PIPE_TEXTURE_3D) {
2967          isv->view.base_array_layer = 0;
2968          isv->view.array_len = 1;
2969       } else {
2970 #if GFX_VER < 9
2971          /* Hardware older than skylake ignores this value */
2972          assert(tex->target != PIPE_TEXTURE_3D || !tmpl->u.tex.first_layer);
2973 #endif
2974          isv->view.base_array_layer = tmpl->u.tex.first_layer;
2975          isv->view.array_len =
2976             tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1;
2977       }
2978 
2979       fill_surface_states(&screen->isl_dev, &isv->surface_state, isv->res,
2980                           &isv->res->surf, &isv->view, 0, 0, 0);
2981    } else if (isv->base.is_tex2d_from_buf) {
2982       /* In case it's a 2d image created from a buffer, we should
2983        * use fill_surface_states function with image parameters provided
2984        * by the CL application
2985        */
2986       isv->view.base_array_layer = 0;
2987       isv->view.array_len = 1;
2988 
2989       /* Create temp_surf and fill with values provided by CL application */
2990       struct isl_surf temp_surf;
2991       fill_surf_for_tex2d_from_buffer(&screen->isl_dev, fmt.fmt,
2992                                       isv->base.u.tex2d_from_buf.width,
2993                                       isv->base.u.tex2d_from_buf.height,
2994                                       isv->base.u.tex2d_from_buf.row_stride,
2995                                       usage,
2996                                       &temp_surf);
2997 
2998       fill_surface_states(&screen->isl_dev, &isv->surface_state, isv->res,
2999                           &temp_surf, &isv->view, 0, 0, 0);
3000    } else {
3001       fill_buffer_surface_state(&screen->isl_dev, isv->res,
3002                                 isv->surface_state.cpu,
3003                                 isv->view.format, isv->view.swizzle,
3004                                 tmpl->u.buf.offset, tmpl->u.buf.size,
3005                                 ISL_SURF_USAGE_TEXTURE_BIT);
3006    }
3007 
3008    return &isv->base;
3009 }
3010 
3011 static void
iris_sampler_view_destroy(struct pipe_context * ctx,struct pipe_sampler_view * state)3012 iris_sampler_view_destroy(struct pipe_context *ctx,
3013                           struct pipe_sampler_view *state)
3014 {
3015    struct iris_sampler_view *isv = (void *) state;
3016    pipe_resource_reference(&state->texture, NULL);
3017    pipe_resource_reference(&isv->surface_state.ref.res, NULL);
3018    free(isv->surface_state.cpu);
3019    free(isv);
3020 }
3021 
3022 /**
3023  * The pipe->create_surface() driver hook.
3024  *
3025  * In Gallium nomenclature, "surfaces" are a view of a resource that
3026  * can be bound as a render target or depth/stencil buffer.
3027  */
3028 static struct pipe_surface *
iris_create_surface(struct pipe_context * ctx,struct pipe_resource * tex,const struct pipe_surface * tmpl)3029 iris_create_surface(struct pipe_context *ctx,
3030                     struct pipe_resource *tex,
3031                     const struct pipe_surface *tmpl)
3032 {
3033    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
3034    const struct intel_device_info *devinfo = screen->devinfo;
3035 
3036    isl_surf_usage_flags_t usage = 0;
3037    if (tmpl->writable)
3038       usage = ISL_SURF_USAGE_STORAGE_BIT;
3039    else if (util_format_is_depth_or_stencil(tmpl->format))
3040       usage = ISL_SURF_USAGE_DEPTH_BIT;
3041    else
3042       usage = ISL_SURF_USAGE_RENDER_TARGET_BIT;
3043 
3044    const struct iris_format_info fmt =
3045       iris_format_for_usage(devinfo, tmpl->format, usage);
3046 
3047    if ((usage & ISL_SURF_USAGE_RENDER_TARGET_BIT) &&
3048        !isl_format_supports_rendering(devinfo, fmt.fmt)) {
3049       /* Framebuffer validation will reject this invalid case, but it
3050        * hasn't had the opportunity yet.  In the meantime, we need to
3051        * avoid hitting ISL asserts about unsupported formats below.
3052        */
3053       return NULL;
3054    }
3055 
3056    struct iris_surface *surf = calloc(1, sizeof(struct iris_surface));
3057    struct iris_resource *res = (struct iris_resource *) tex;
3058 
3059    if (!surf)
3060       return NULL;
3061 
3062    uint32_t array_len = tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1;
3063 
3064    struct isl_view *view = &surf->view;
3065    *view = (struct isl_view) {
3066       .format = fmt.fmt,
3067       .base_level = tmpl->u.tex.level,
3068       .levels = 1,
3069       .base_array_layer = tmpl->u.tex.first_layer,
3070       .array_len = array_len,
3071       .swizzle = ISL_SWIZZLE_IDENTITY,
3072       .usage = usage,
3073    };
3074 
3075 #if GFX_VER == 8
3076    struct isl_view *read_view = &surf->read_view;
3077    *read_view = (struct isl_view) {
3078       .format = fmt.fmt,
3079       .base_level = tmpl->u.tex.level,
3080       .levels = 1,
3081       .base_array_layer = tmpl->u.tex.first_layer,
3082       .array_len = array_len,
3083       .swizzle = ISL_SWIZZLE_IDENTITY,
3084       .usage = ISL_SURF_USAGE_TEXTURE_BIT,
3085    };
3086 
3087    struct isl_surf read_surf = res->surf;
3088    uint64_t read_surf_offset_B = 0;
3089    uint32_t read_surf_tile_x_sa = 0, read_surf_tile_y_sa = 0;
3090    if (tex->target == PIPE_TEXTURE_3D && array_len == 1) {
3091       /* The minimum array element field of the surface state structure is
3092        * ignored by the sampler unit for 3D textures on some hardware.  If the
3093        * render buffer is a single slice of a 3D texture, create a 2D texture
3094        * covering that slice.
3095        *
3096        * TODO: This only handles the case where we're rendering to a single
3097        * slice of an array texture.  If we have layered rendering combined
3098        * with non-coherent FB fetch and a non-zero base_array_layer, then
3099        * we're going to run into problems.
3100        *
3101        * See https://gitlab.freedesktop.org/mesa/mesa/-/issues/4904
3102        */
3103       isl_surf_get_image_surf(&screen->isl_dev, &res->surf,
3104                               read_view->base_level,
3105                               0, read_view->base_array_layer,
3106                               &read_surf, &read_surf_offset_B,
3107                               &read_surf_tile_x_sa, &read_surf_tile_y_sa);
3108       read_view->base_level = 0;
3109       read_view->base_array_layer = 0;
3110       assert(read_view->array_len == 1);
3111    } else if (tex->target == PIPE_TEXTURE_1D_ARRAY) {
3112       /* Convert 1D array textures to 2D arrays because shaders always provide
3113        * the array index coordinate at the Z component to avoid recompiles
3114        * when changing the texture target of the framebuffer.
3115        */
3116       assert(read_surf.dim_layout == ISL_DIM_LAYOUT_GFX4_2D);
3117       read_surf.dim = ISL_SURF_DIM_2D;
3118    }
3119 #endif
3120 
3121    struct isl_surf isl_surf = res->surf;
3122    uint64_t offset_B = 0;
3123    uint32_t tile_x_el = 0, tile_y_el = 0;
3124    if (isl_format_is_compressed(res->surf.format)) {
3125       /* The resource has a compressed format, which is not renderable, but we
3126        * have a renderable view format.  We must be attempting to upload
3127        * blocks of compressed data via an uncompressed view.
3128        *
3129        * In this case, we can assume there are no auxiliary buffers, a single
3130        * miplevel, and that the resource is single-sampled.  Gallium may try
3131        * and create an uncompressed view with multiple layers, however.
3132        */
3133       assert(res->aux.usage == ISL_AUX_USAGE_NONE);
3134       assert(res->surf.samples == 1);
3135       assert(view->levels == 1);
3136 
3137       bool ok = isl_surf_get_uncompressed_surf(&screen->isl_dev,
3138                                                &res->surf, view,
3139                                                &isl_surf, view, &offset_B,
3140                                                &tile_x_el, &tile_y_el);
3141 
3142       /* On Broadwell, HALIGN and VALIGN are specified in pixels and are
3143        * hard-coded to align to exactly the block size of the compressed
3144        * texture. This means that, when reinterpreted as a non-compressed
3145        * texture, the tile offsets may be anything.
3146        *
3147        * We need them to be multiples of 4 to be usable in RENDER_SURFACE_STATE,
3148        * so force the state tracker to take fallback paths if they're not.
3149        */
3150 #if GFX_VER == 8
3151       if (tile_x_el % 4 != 0 || tile_y_el % 4 != 0) {
3152          ok = false;
3153       }
3154 #endif
3155 
3156       if (!ok) {
3157          free(surf);
3158          return NULL;
3159       }
3160    }
3161 
3162    surf->clear_color = res->aux.clear_color;
3163 
3164    struct pipe_surface *psurf = &surf->base;
3165    pipe_reference_init(&psurf->reference, 1);
3166    pipe_resource_reference(&psurf->texture, tex);
3167    psurf->context = ctx;
3168    psurf->format = tmpl->format;
3169    psurf->width = isl_surf.logical_level0_px.width;
3170    psurf->height = isl_surf.logical_level0_px.height;
3171    psurf->texture = tex;
3172    psurf->u.tex.first_layer = tmpl->u.tex.first_layer;
3173    psurf->u.tex.last_layer = tmpl->u.tex.last_layer;
3174    psurf->u.tex.level = tmpl->u.tex.level;
3175 
3176    /* Bail early for depth/stencil - we don't want SURFACE_STATE for them. */
3177    if (res->surf.usage & (ISL_SURF_USAGE_DEPTH_BIT |
3178                           ISL_SURF_USAGE_STENCIL_BIT))
3179       return psurf;
3180 
3181    /* Fill out a SURFACE_STATE for each possible auxiliary surface mode and
3182     * return the pipe_surface.
3183     */
3184    unsigned aux_usages = 0;
3185 
3186    if ((res->aux.usage == ISL_AUX_USAGE_CCS_E ||
3187         res->aux.usage == ISL_AUX_USAGE_FCV_CCS_E) &&
3188        !isl_format_supports_ccs_e(devinfo, view->format)) {
3189       aux_usages = 1 << ISL_AUX_USAGE_NONE;
3190    } else {
3191       aux_usages = 1 << ISL_AUX_USAGE_NONE |
3192                    1 << res->aux.usage;
3193    }
3194 
3195    alloc_surface_states(&surf->surface_state, aux_usages);
3196    surf->surface_state.bo_address = res->bo->address;
3197    fill_surface_states(&screen->isl_dev, &surf->surface_state, res,
3198                        &isl_surf, view, offset_B, tile_x_el, tile_y_el);
3199 
3200 #if GFX_VER == 8
3201    alloc_surface_states(&surf->surface_state_read, aux_usages);
3202    surf->surface_state_read.bo_address = res->bo->address;
3203    fill_surface_states(&screen->isl_dev, &surf->surface_state_read, res,
3204                        &read_surf, read_view, read_surf_offset_B,
3205                        read_surf_tile_x_sa, read_surf_tile_y_sa);
3206 #endif
3207 
3208    return psurf;
3209 }
3210 
3211 #if GFX_VER < 9
3212 static void
fill_default_image_param(struct isl_image_param * param)3213 fill_default_image_param(struct isl_image_param *param)
3214 {
3215    memset(param, 0, sizeof(*param));
3216    /* Set the swizzling shifts to all-ones to effectively disable swizzling --
3217     * See emit_address_calculation() in brw_fs_surface_builder.cpp for a more
3218     * detailed explanation of these parameters.
3219     */
3220    param->swizzling[0] = 0xff;
3221    param->swizzling[1] = 0xff;
3222 }
3223 
3224 static void
fill_buffer_image_param(struct isl_image_param * param,enum pipe_format pfmt,unsigned size)3225 fill_buffer_image_param(struct isl_image_param *param,
3226                         enum pipe_format pfmt,
3227                         unsigned size)
3228 {
3229    const unsigned cpp = util_format_get_blocksize(pfmt);
3230 
3231    fill_default_image_param(param);
3232    param->size[0] = size / cpp;
3233    param->stride[0] = cpp;
3234 }
3235 #else
3236 #define isl_surf_fill_image_param(x, ...)
3237 #define fill_default_image_param(x, ...)
3238 #define fill_buffer_image_param(x, ...)
3239 #endif
3240 
3241 /**
3242  * The pipe->set_shader_images() driver hook.
3243  */
3244 static void
iris_set_shader_images(struct pipe_context * ctx,enum pipe_shader_type p_stage,unsigned start_slot,unsigned count,unsigned unbind_num_trailing_slots,const struct pipe_image_view * p_images)3245 iris_set_shader_images(struct pipe_context *ctx,
3246                        enum pipe_shader_type p_stage,
3247                        unsigned start_slot, unsigned count,
3248                        unsigned unbind_num_trailing_slots,
3249                        const struct pipe_image_view *p_images)
3250 {
3251    struct iris_context *ice = (struct iris_context *) ctx;
3252    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
3253    gl_shader_stage stage = stage_from_pipe(p_stage);
3254    struct iris_shader_state *shs = &ice->state.shaders[stage];
3255 #if GFX_VER == 8
3256    struct iris_genx_state *genx = ice->state.genx;
3257    struct isl_image_param *image_params = genx->shaders[stage].image_param;
3258 #endif
3259 
3260    shs->bound_image_views &=
3261       ~u_bit_consecutive64(start_slot, count + unbind_num_trailing_slots);
3262 
3263    for (unsigned i = 0; i < count; i++) {
3264       struct iris_image_view *iv = &shs->image[start_slot + i];
3265 
3266       if (p_images && p_images[i].resource) {
3267          const struct pipe_image_view *img = &p_images[i];
3268          struct iris_resource *res = (void *) img->resource;
3269 
3270          util_copy_image_view(&iv->base, img);
3271 
3272          shs->bound_image_views |= BITFIELD64_BIT(start_slot + i);
3273 
3274          res->bind_history |= PIPE_BIND_SHADER_IMAGE;
3275          res->bind_stages |= 1 << stage;
3276 
3277          enum isl_format isl_fmt = iris_image_view_get_format(ice, img);
3278 
3279          unsigned aux_usages = 1 << ISL_AUX_USAGE_NONE;
3280 
3281          /* Gfx12+ supports render compression for images */
3282          if (GFX_VER >= 12 && isl_aux_usage_has_ccs_e(res->aux.usage))
3283             aux_usages |= 1 << ISL_AUX_USAGE_CCS_E;
3284 
3285          alloc_surface_states(&iv->surface_state, aux_usages);
3286          iv->surface_state.bo_address = res->bo->address;
3287 
3288          if (res->base.b.target != PIPE_BUFFER) {
3289             struct isl_view view = {
3290                .format = isl_fmt,
3291                .base_level = img->u.tex.level,
3292                .levels = 1,
3293                .base_array_layer = img->u.tex.first_layer,
3294                .array_len = img->u.tex.last_layer - img->u.tex.first_layer + 1,
3295                .swizzle = ISL_SWIZZLE_IDENTITY,
3296                .usage = ISL_SURF_USAGE_STORAGE_BIT,
3297             };
3298 
3299             /* If using untyped fallback. */
3300             if (isl_fmt == ISL_FORMAT_RAW) {
3301                fill_buffer_surface_state(&screen->isl_dev, res,
3302                                          iv->surface_state.cpu,
3303                                          isl_fmt, ISL_SWIZZLE_IDENTITY,
3304                                          0, res->bo->size,
3305                                          ISL_SURF_USAGE_STORAGE_BIT);
3306             } else {
3307                fill_surface_states(&screen->isl_dev, &iv->surface_state, res,
3308                                    &res->surf, &view, 0, 0, 0);
3309             }
3310 
3311             isl_surf_fill_image_param(&screen->isl_dev,
3312                                       &image_params[start_slot + i],
3313                                       &res->surf, &view);
3314          } else if (img->access & PIPE_IMAGE_ACCESS_TEX2D_FROM_BUFFER) {
3315             /* In case it's a 2d image created from a buffer, we should
3316              * use fill_surface_states function with image parameters provided
3317              * by the CL application
3318              */
3319             isl_surf_usage_flags_t usage =  ISL_SURF_USAGE_STORAGE_BIT;
3320             struct isl_view view = {
3321                .format = isl_fmt,
3322                .base_level = 0,
3323                .levels = 1,
3324                .base_array_layer = 0,
3325                .array_len = 1,
3326                .swizzle = ISL_SWIZZLE_IDENTITY,
3327                .usage = usage,
3328             };
3329 
3330             /* Create temp_surf and fill with values provided by CL application */
3331             struct isl_surf temp_surf;
3332             enum isl_format fmt = iris_image_view_get_format(ice, img);
3333             fill_surf_for_tex2d_from_buffer(&screen->isl_dev, fmt,
3334                                             img->u.tex2d_from_buf.width,
3335                                             img->u.tex2d_from_buf.height,
3336                                             img->u.tex2d_from_buf.row_stride,
3337                                             usage,
3338                                             &temp_surf);
3339 
3340             fill_surface_states(&screen->isl_dev, &iv->surface_state, res,
3341                                 &temp_surf, &view, 0, 0, 0);
3342             isl_surf_fill_image_param(&screen->isl_dev,
3343                                       &image_params[start_slot + i],
3344                                       &temp_surf, &view);
3345          } else {
3346             util_range_add(&res->base.b, &res->valid_buffer_range, img->u.buf.offset,
3347                            img->u.buf.offset + img->u.buf.size);
3348 
3349             fill_buffer_surface_state(&screen->isl_dev, res,
3350                                       iv->surface_state.cpu,
3351                                       isl_fmt, ISL_SWIZZLE_IDENTITY,
3352                                       img->u.buf.offset, img->u.buf.size,
3353                                       ISL_SURF_USAGE_STORAGE_BIT);
3354             fill_buffer_image_param(&image_params[start_slot + i],
3355                                     img->format, img->u.buf.size);
3356          }
3357 
3358          upload_surface_states(ice->state.surface_uploader, &iv->surface_state);
3359       } else {
3360          pipe_resource_reference(&iv->base.resource, NULL);
3361          pipe_resource_reference(&iv->surface_state.ref.res, NULL);
3362          fill_default_image_param(&image_params[start_slot + i]);
3363       }
3364    }
3365 
3366    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_BINDINGS_VS << stage;
3367    ice->state.dirty |=
3368       stage == MESA_SHADER_COMPUTE ? IRIS_DIRTY_COMPUTE_RESOLVES_AND_FLUSHES
3369                                    : IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
3370 
3371    /* Broadwell also needs isl_image_params re-uploaded */
3372    if (GFX_VER < 9) {
3373       ice->state.stage_dirty |= IRIS_STAGE_DIRTY_CONSTANTS_VS << stage;
3374       shs->sysvals_need_upload = true;
3375    }
3376 
3377    if (unbind_num_trailing_slots) {
3378       iris_set_shader_images(ctx, p_stage, start_slot + count,
3379                              unbind_num_trailing_slots, 0, NULL);
3380    }
3381 }
3382 
3383 UNUSED static bool
is_sampler_view_3d(const struct iris_sampler_view * view)3384 is_sampler_view_3d(const struct iris_sampler_view *view)
3385 {
3386    return view && view->res->base.b.target == PIPE_TEXTURE_3D;
3387 }
3388 
3389 /**
3390  * The pipe->set_sampler_views() driver hook.
3391  */
3392 static void
iris_set_sampler_views(struct pipe_context * ctx,enum pipe_shader_type p_stage,unsigned start,unsigned count,unsigned unbind_num_trailing_slots,bool take_ownership,struct pipe_sampler_view ** views)3393 iris_set_sampler_views(struct pipe_context *ctx,
3394                        enum pipe_shader_type p_stage,
3395                        unsigned start, unsigned count,
3396                        unsigned unbind_num_trailing_slots,
3397                        bool take_ownership,
3398                        struct pipe_sampler_view **views)
3399 {
3400    struct iris_context *ice = (struct iris_context *) ctx;
3401    UNUSED struct iris_screen *screen = (void *) ctx->screen;
3402    UNUSED const struct intel_device_info *devinfo = screen->devinfo;
3403    gl_shader_stage stage = stage_from_pipe(p_stage);
3404    struct iris_shader_state *shs = &ice->state.shaders[stage];
3405    unsigned i;
3406 
3407    if (count == 0 && unbind_num_trailing_slots == 0)
3408       return;
3409 
3410    BITSET_CLEAR_RANGE(shs->bound_sampler_views, start,
3411                       start + count + unbind_num_trailing_slots - 1);
3412 
3413    for (i = 0; i < count; i++) {
3414       struct pipe_sampler_view *pview = views ? views[i] : NULL;
3415       struct iris_sampler_view *view = (void *) pview;
3416 
3417 #if GFX_VERx10 == 125
3418       if (intel_needs_workaround(screen->devinfo, 14014414195)) {
3419          if (is_sampler_view_3d(shs->textures[start + i]) !=
3420              is_sampler_view_3d(view))
3421             ice->state.stage_dirty |= IRIS_STAGE_DIRTY_SAMPLER_STATES_VS << stage;
3422       }
3423 #endif
3424 
3425       if (take_ownership) {
3426          pipe_sampler_view_reference((struct pipe_sampler_view **)
3427                                      &shs->textures[start + i], NULL);
3428          shs->textures[start + i] = (struct iris_sampler_view *)pview;
3429       } else {
3430          pipe_sampler_view_reference((struct pipe_sampler_view **)
3431                                      &shs->textures[start + i], pview);
3432       }
3433       if (view) {
3434          view->res->bind_history |= PIPE_BIND_SAMPLER_VIEW;
3435          view->res->bind_stages |= 1 << stage;
3436 
3437          BITSET_SET(shs->bound_sampler_views, start + i);
3438 
3439          update_surface_state_addrs(ice->state.surface_uploader,
3440                                     &view->surface_state, view->res->bo);
3441       }
3442    }
3443    for (; i < count + unbind_num_trailing_slots; i++) {
3444       pipe_sampler_view_reference((struct pipe_sampler_view **)
3445                                   &shs->textures[start + i], NULL);
3446    }
3447 
3448    ice->state.stage_dirty |= (IRIS_STAGE_DIRTY_BINDINGS_VS << stage);
3449    ice->state.dirty |=
3450       stage == MESA_SHADER_COMPUTE ? IRIS_DIRTY_COMPUTE_RESOLVES_AND_FLUSHES
3451                                    : IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
3452 }
3453 
3454 static void
iris_set_compute_resources(struct pipe_context * ctx,unsigned start,unsigned count,struct pipe_surface ** resources)3455 iris_set_compute_resources(struct pipe_context *ctx,
3456                            unsigned start, unsigned count,
3457                            struct pipe_surface **resources)
3458 {
3459    assert(count == 0);
3460 }
3461 
3462 static void
iris_set_global_binding(struct pipe_context * ctx,unsigned start_slot,unsigned count,struct pipe_resource ** resources,uint32_t ** handles)3463 iris_set_global_binding(struct pipe_context *ctx,
3464                         unsigned start_slot, unsigned count,
3465                         struct pipe_resource **resources,
3466                         uint32_t **handles)
3467 {
3468    struct iris_context *ice = (struct iris_context *) ctx;
3469 
3470    assert(start_slot + count <= IRIS_MAX_GLOBAL_BINDINGS);
3471    for (unsigned i = 0; i < count; i++) {
3472       if (resources && resources[i]) {
3473          pipe_resource_reference(&ice->state.global_bindings[start_slot + i],
3474                                  resources[i]);
3475 
3476          struct iris_resource *res = (void *) resources[i];
3477          assert(res->base.b.target == PIPE_BUFFER);
3478          util_range_add(&res->base.b, &res->valid_buffer_range,
3479                         0, res->base.b.width0);
3480 
3481          uint64_t addr = 0;
3482          memcpy(&addr, handles[i], sizeof(addr));
3483          addr += res->bo->address + res->offset;
3484          memcpy(handles[i], &addr, sizeof(addr));
3485       } else {
3486          pipe_resource_reference(&ice->state.global_bindings[start_slot + i],
3487                                  NULL);
3488       }
3489    }
3490 
3491    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_BINDINGS_CS;
3492 }
3493 
3494 /**
3495  * The pipe->set_tess_state() driver hook.
3496  */
3497 static void
iris_set_tess_state(struct pipe_context * ctx,const float default_outer_level[4],const float default_inner_level[2])3498 iris_set_tess_state(struct pipe_context *ctx,
3499                     const float default_outer_level[4],
3500                     const float default_inner_level[2])
3501 {
3502    struct iris_context *ice = (struct iris_context *) ctx;
3503    struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_TESS_CTRL];
3504 
3505    memcpy(&ice->state.default_outer_level[0], &default_outer_level[0], 4 * sizeof(float));
3506    memcpy(&ice->state.default_inner_level[0], &default_inner_level[0], 2 * sizeof(float));
3507 
3508    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_CONSTANTS_TCS;
3509    shs->sysvals_need_upload = true;
3510 }
3511 
3512 static void
iris_set_patch_vertices(struct pipe_context * ctx,uint8_t patch_vertices)3513 iris_set_patch_vertices(struct pipe_context *ctx, uint8_t patch_vertices)
3514 {
3515    struct iris_context *ice = (struct iris_context *) ctx;
3516 
3517    ice->state.patch_vertices = patch_vertices;
3518 }
3519 
3520 static void
iris_surface_destroy(struct pipe_context * ctx,struct pipe_surface * p_surf)3521 iris_surface_destroy(struct pipe_context *ctx, struct pipe_surface *p_surf)
3522 {
3523    struct iris_surface *surf = (void *) p_surf;
3524    pipe_resource_reference(&p_surf->texture, NULL);
3525    pipe_resource_reference(&surf->surface_state.ref.res, NULL);
3526    pipe_resource_reference(&surf->surface_state_read.ref.res, NULL);
3527    free(surf->surface_state.cpu);
3528    free(surf->surface_state_read.cpu);
3529    free(surf);
3530 }
3531 
3532 static void
iris_set_clip_state(struct pipe_context * ctx,const struct pipe_clip_state * state)3533 iris_set_clip_state(struct pipe_context *ctx,
3534                     const struct pipe_clip_state *state)
3535 {
3536    struct iris_context *ice = (struct iris_context *) ctx;
3537    struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_VERTEX];
3538    struct iris_shader_state *gshs = &ice->state.shaders[MESA_SHADER_GEOMETRY];
3539    struct iris_shader_state *tshs = &ice->state.shaders[MESA_SHADER_TESS_EVAL];
3540 
3541    memcpy(&ice->state.clip_planes, state, sizeof(*state));
3542 
3543    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_CONSTANTS_VS |
3544                              IRIS_STAGE_DIRTY_CONSTANTS_GS |
3545                              IRIS_STAGE_DIRTY_CONSTANTS_TES;
3546    shs->sysvals_need_upload = true;
3547    gshs->sysvals_need_upload = true;
3548    tshs->sysvals_need_upload = true;
3549 }
3550 
3551 /**
3552  * The pipe->set_polygon_stipple() driver hook.
3553  */
3554 static void
iris_set_polygon_stipple(struct pipe_context * ctx,const struct pipe_poly_stipple * state)3555 iris_set_polygon_stipple(struct pipe_context *ctx,
3556                          const struct pipe_poly_stipple *state)
3557 {
3558    struct iris_context *ice = (struct iris_context *) ctx;
3559    memcpy(&ice->state.poly_stipple, state, sizeof(*state));
3560    ice->state.dirty |= IRIS_DIRTY_POLYGON_STIPPLE;
3561 }
3562 
3563 /**
3564  * The pipe->set_sample_mask() driver hook.
3565  */
3566 static void
iris_set_sample_mask(struct pipe_context * ctx,unsigned sample_mask)3567 iris_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
3568 {
3569    struct iris_context *ice = (struct iris_context *) ctx;
3570 
3571    /* We only support 16x MSAA, so we have 16 bits of sample maks.
3572     * st/mesa may pass us 0xffffffff though, meaning "enable all samples".
3573     */
3574    ice->state.sample_mask = sample_mask & 0xffff;
3575    ice->state.dirty |= IRIS_DIRTY_SAMPLE_MASK;
3576 }
3577 
3578 /**
3579  * The pipe->set_scissor_states() driver hook.
3580  *
3581  * This corresponds to our SCISSOR_RECT state structures.  It's an
3582  * exact match, so we just store them, and memcpy them out later.
3583  */
3584 static void
iris_set_scissor_states(struct pipe_context * ctx,unsigned start_slot,unsigned num_scissors,const struct pipe_scissor_state * rects)3585 iris_set_scissor_states(struct pipe_context *ctx,
3586                         unsigned start_slot,
3587                         unsigned num_scissors,
3588                         const struct pipe_scissor_state *rects)
3589 {
3590    struct iris_context *ice = (struct iris_context *) ctx;
3591 
3592    for (unsigned i = 0; i < num_scissors; i++) {
3593       if (rects[i].minx == rects[i].maxx || rects[i].miny == rects[i].maxy) {
3594          /* If the scissor was out of bounds and got clamped to 0 width/height
3595           * at the bounds, the subtraction of 1 from maximums could produce a
3596           * negative number and thus not clip anything.  Instead, just provide
3597           * a min > max scissor inside the bounds, which produces the expected
3598           * no rendering.
3599           */
3600          ice->state.scissors[start_slot + i] = (struct pipe_scissor_state) {
3601             .minx = 1, .maxx = 0, .miny = 1, .maxy = 0,
3602          };
3603       } else {
3604          ice->state.scissors[start_slot + i] = (struct pipe_scissor_state) {
3605             .minx = rects[i].minx,     .miny = rects[i].miny,
3606             .maxx = rects[i].maxx - 1, .maxy = rects[i].maxy - 1,
3607          };
3608       }
3609    }
3610 
3611    ice->state.dirty |= IRIS_DIRTY_SCISSOR_RECT;
3612 }
3613 
3614 /**
3615  * The pipe->set_stencil_ref() driver hook.
3616  *
3617  * This is added to 3DSTATE_WM_DEPTH_STENCIL dynamically at draw time.
3618  */
3619 static void
iris_set_stencil_ref(struct pipe_context * ctx,const struct pipe_stencil_ref state)3620 iris_set_stencil_ref(struct pipe_context *ctx,
3621                      const struct pipe_stencil_ref state)
3622 {
3623    struct iris_context *ice = (struct iris_context *) ctx;
3624    memcpy(&ice->state.stencil_ref, &state, sizeof(state));
3625    if (GFX_VER >= 12)
3626       ice->state.dirty |= IRIS_DIRTY_STENCIL_REF;
3627    else if (GFX_VER >= 9)
3628       ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
3629    else
3630       ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
3631 }
3632 
3633 static float
viewport_extent(const struct pipe_viewport_state * state,int axis,float sign)3634 viewport_extent(const struct pipe_viewport_state *state, int axis, float sign)
3635 {
3636    return copysignf(state->scale[axis], sign) + state->translate[axis];
3637 }
3638 
3639 /**
3640  * The pipe->set_viewport_states() driver hook.
3641  *
3642  * This corresponds to our SF_CLIP_VIEWPORT states.  We can't calculate
3643  * the guardband yet, as we need the framebuffer dimensions, but we can
3644  * at least fill out the rest.
3645  */
3646 static void
iris_set_viewport_states(struct pipe_context * ctx,unsigned start_slot,unsigned count,const struct pipe_viewport_state * states)3647 iris_set_viewport_states(struct pipe_context *ctx,
3648                          unsigned start_slot,
3649                          unsigned count,
3650                          const struct pipe_viewport_state *states)
3651 {
3652    struct iris_context *ice = (struct iris_context *) ctx;
3653    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
3654 
3655    memcpy(&ice->state.viewports[start_slot], states, sizeof(*states) * count);
3656 
3657    /* Fix depth test misrenderings by lowering translated depth range */
3658    if (screen->driconf.lower_depth_range_rate != 1.0f)
3659       ice->state.viewports[start_slot].translate[2] *=
3660          screen->driconf.lower_depth_range_rate;
3661 
3662    ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
3663 
3664    if (ice->state.cso_rast && (!ice->state.cso_rast->depth_clip_near ||
3665                                !ice->state.cso_rast->depth_clip_far))
3666       ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
3667 }
3668 
3669 /**
3670  * The pipe->set_framebuffer_state() driver hook.
3671  *
3672  * Sets the current draw FBO, including color render targets, depth,
3673  * and stencil buffers.
3674  */
3675 static void
iris_set_framebuffer_state(struct pipe_context * ctx,const struct pipe_framebuffer_state * state)3676 iris_set_framebuffer_state(struct pipe_context *ctx,
3677                            const struct pipe_framebuffer_state *state)
3678 {
3679    struct iris_context *ice = (struct iris_context *) ctx;
3680    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
3681    const struct intel_device_info *devinfo = screen->devinfo;
3682    struct isl_device *isl_dev = &screen->isl_dev;
3683    struct pipe_framebuffer_state *cso = &ice->state.framebuffer;
3684    struct iris_resource *zres;
3685    struct iris_resource *stencil_res;
3686 
3687    unsigned samples = util_framebuffer_get_num_samples(state);
3688    unsigned layers = util_framebuffer_get_num_layers(state);
3689 
3690    if (cso->samples != samples) {
3691       ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
3692 
3693       /* We need to toggle 3DSTATE_PS::32 Pixel Dispatch Enable */
3694       if (GFX_VER >= 9 && (cso->samples == 16 || samples == 16))
3695          ice->state.stage_dirty |= IRIS_STAGE_DIRTY_FS;
3696 
3697       /* We may need to emit blend state for Wa_14018912822. */
3698       if ((cso->samples > 1) != (samples > 1) &&
3699           intel_needs_workaround(devinfo, 14018912822)) {
3700          ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
3701          ice->state.dirty |= IRIS_DIRTY_PS_BLEND;
3702       }
3703    }
3704 
3705    if (cso->nr_cbufs != state->nr_cbufs) {
3706       ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
3707    }
3708 
3709    if ((cso->layers == 0) != (layers == 0)) {
3710       ice->state.dirty |= IRIS_DIRTY_CLIP;
3711    }
3712 
3713    if (cso->width != state->width || cso->height != state->height) {
3714       ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
3715    }
3716 
3717    if (cso->zsbuf || state->zsbuf) {
3718       ice->state.dirty |= IRIS_DIRTY_DEPTH_BUFFER;
3719    }
3720 
3721    bool has_integer_rt = false;
3722    for (unsigned i = 0; i < state->nr_cbufs; i++) {
3723       if (state->cbufs[i]) {
3724          enum isl_format ifmt =
3725             isl_format_for_pipe_format(state->cbufs[i]->format);
3726          has_integer_rt |= isl_format_has_int_channel(ifmt);
3727       }
3728    }
3729 
3730    /* 3DSTATE_RASTER::AntialiasingEnable */
3731    if (has_integer_rt != ice->state.has_integer_rt ||
3732        cso->samples != samples) {
3733       ice->state.dirty |= IRIS_DIRTY_RASTER;
3734    }
3735 
3736    util_copy_framebuffer_state(cso, state);
3737    cso->samples = samples;
3738    cso->layers = layers;
3739 
3740    ice->state.has_integer_rt = has_integer_rt;
3741 
3742    struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
3743 
3744    struct isl_view view = {
3745       .base_level = 0,
3746       .levels = 1,
3747       .base_array_layer = 0,
3748       .array_len = 1,
3749       .swizzle = ISL_SWIZZLE_IDENTITY,
3750    };
3751 
3752    struct isl_depth_stencil_hiz_emit_info info = {
3753       .view = &view,
3754       .mocs = iris_mocs(NULL, isl_dev, ISL_SURF_USAGE_DEPTH_BIT),
3755    };
3756 
3757    if (cso->zsbuf) {
3758       iris_get_depth_stencil_resources(cso->zsbuf->texture, &zres,
3759                                        &stencil_res);
3760 
3761       view.base_level = cso->zsbuf->u.tex.level;
3762       view.base_array_layer = cso->zsbuf->u.tex.first_layer;
3763       view.array_len =
3764          cso->zsbuf->u.tex.last_layer - cso->zsbuf->u.tex.first_layer + 1;
3765 
3766       if (zres) {
3767          view.usage |= ISL_SURF_USAGE_DEPTH_BIT;
3768 
3769          info.depth_surf = &zres->surf;
3770          info.depth_address = zres->bo->address + zres->offset;
3771          info.mocs = iris_mocs(zres->bo, isl_dev, view.usage);
3772 
3773          view.format = zres->surf.format;
3774 
3775          if (iris_resource_level_has_hiz(devinfo, zres, view.base_level)) {
3776             info.hiz_usage = zres->aux.usage;
3777             info.hiz_surf = &zres->aux.surf;
3778             info.hiz_address = zres->aux.bo->address + zres->aux.offset;
3779          }
3780 
3781          ice->state.hiz_usage = info.hiz_usage;
3782       }
3783 
3784       if (stencil_res) {
3785          view.usage |= ISL_SURF_USAGE_STENCIL_BIT;
3786          info.stencil_aux_usage = stencil_res->aux.usage;
3787          info.stencil_surf = &stencil_res->surf;
3788          info.stencil_address = stencil_res->bo->address + stencil_res->offset;
3789          if (!zres) {
3790             view.format = stencil_res->surf.format;
3791             info.mocs = iris_mocs(stencil_res->bo, isl_dev, view.usage);
3792          }
3793       }
3794    }
3795 
3796    isl_emit_depth_stencil_hiz_s(isl_dev, cso_z->packets, &info);
3797 
3798    /* Make a null surface for unbound buffers */
3799    void *null_surf_map =
3800       upload_state(ice->state.surface_uploader, &ice->state.null_fb,
3801                    4 * GENX(RENDER_SURFACE_STATE_length), 64);
3802    isl_null_fill_state(&screen->isl_dev, null_surf_map,
3803                        .size = isl_extent3d(MAX2(cso->width, 1),
3804                                             MAX2(cso->height, 1),
3805                                             cso->layers ? cso->layers : 1));
3806    ice->state.null_fb.offset +=
3807       iris_bo_offset_from_base_address(iris_resource_bo(ice->state.null_fb.res));
3808 
3809    /* Render target change */
3810    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_BINDINGS_FS;
3811 
3812    ice->state.dirty |= IRIS_DIRTY_RENDER_BUFFER;
3813 
3814    ice->state.dirty |= IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
3815 
3816    ice->state.stage_dirty |=
3817       ice->state.stage_dirty_for_nos[IRIS_NOS_FRAMEBUFFER];
3818 
3819    if (GFX_VER == 8)
3820       ice->state.dirty |= IRIS_DIRTY_PMA_FIX;
3821 }
3822 
3823 /**
3824  * The pipe->set_constant_buffer() driver hook.
3825  *
3826  * This uploads any constant data in user buffers, and references
3827  * any UBO resources containing constant data.
3828  */
3829 static void
iris_set_constant_buffer(struct pipe_context * ctx,enum pipe_shader_type p_stage,unsigned index,bool take_ownership,const struct pipe_constant_buffer * input)3830 iris_set_constant_buffer(struct pipe_context *ctx,
3831                          enum pipe_shader_type p_stage, unsigned index,
3832                          bool take_ownership,
3833                          const struct pipe_constant_buffer *input)
3834 {
3835    struct iris_context *ice = (struct iris_context *) ctx;
3836    gl_shader_stage stage = stage_from_pipe(p_stage);
3837    struct iris_shader_state *shs = &ice->state.shaders[stage];
3838    struct pipe_shader_buffer *cbuf = &shs->constbuf[index];
3839 
3840    /* TODO: Only do this if the buffer changes? */
3841    pipe_resource_reference(&shs->constbuf_surf_state[index].res, NULL);
3842 
3843    if (input && input->buffer_size && (input->buffer || input->user_buffer)) {
3844       shs->bound_cbufs |= 1u << index;
3845 
3846       if (input->user_buffer) {
3847          void *map = NULL;
3848          pipe_resource_reference(&cbuf->buffer, NULL);
3849          u_upload_alloc(ice->ctx.const_uploader, 0, input->buffer_size, 64,
3850                         &cbuf->buffer_offset, &cbuf->buffer, (void **) &map);
3851 
3852          if (!cbuf->buffer) {
3853             /* Allocation was unsuccessful - just unbind */
3854             iris_set_constant_buffer(ctx, p_stage, index, false, NULL);
3855             return;
3856          }
3857 
3858          assert(map);
3859          memcpy(map, input->user_buffer, input->buffer_size);
3860       } else if (input->buffer) {
3861          if (cbuf->buffer != input->buffer) {
3862             ice->state.dirty |= (IRIS_DIRTY_RENDER_MISC_BUFFER_FLUSHES |
3863                                  IRIS_DIRTY_COMPUTE_MISC_BUFFER_FLUSHES);
3864             shs->dirty_cbufs |= 1u << index;
3865          }
3866 
3867          if (take_ownership) {
3868             pipe_resource_reference(&cbuf->buffer, NULL);
3869             cbuf->buffer = input->buffer;
3870          } else {
3871             pipe_resource_reference(&cbuf->buffer, input->buffer);
3872          }
3873 
3874          cbuf->buffer_offset = input->buffer_offset;
3875       }
3876 
3877       cbuf->buffer_size =
3878          MIN2(input->buffer_size,
3879               iris_resource_bo(cbuf->buffer)->size - cbuf->buffer_offset);
3880 
3881       struct iris_resource *res = (void *) cbuf->buffer;
3882       res->bind_history |= PIPE_BIND_CONSTANT_BUFFER;
3883       res->bind_stages |= 1 << stage;
3884    } else {
3885       shs->bound_cbufs &= ~(1u << index);
3886       pipe_resource_reference(&cbuf->buffer, NULL);
3887    }
3888 
3889    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_CONSTANTS_VS << stage;
3890 }
3891 
3892 static void
upload_sysvals(struct iris_context * ice,gl_shader_stage stage,const struct pipe_grid_info * grid)3893 upload_sysvals(struct iris_context *ice,
3894                gl_shader_stage stage,
3895                const struct pipe_grid_info *grid)
3896 {
3897    UNUSED struct iris_genx_state *genx = ice->state.genx;
3898    struct iris_shader_state *shs = &ice->state.shaders[stage];
3899 
3900    struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3901    if (!shader || (shader->num_system_values == 0 &&
3902                    shader->kernel_input_size == 0))
3903       return;
3904 
3905    assert(shader->num_cbufs > 0);
3906 
3907    unsigned sysval_cbuf_index = shader->num_cbufs - 1;
3908    struct pipe_shader_buffer *cbuf = &shs->constbuf[sysval_cbuf_index];
3909    unsigned system_values_start =
3910       ALIGN(shader->kernel_input_size, sizeof(uint32_t));
3911    unsigned upload_size = system_values_start +
3912                           shader->num_system_values * sizeof(uint32_t);
3913    void *map = NULL;
3914 
3915    assert(sysval_cbuf_index < PIPE_MAX_CONSTANT_BUFFERS);
3916    u_upload_alloc(ice->ctx.const_uploader, 0, upload_size, 64,
3917                   &cbuf->buffer_offset, &cbuf->buffer, &map);
3918 
3919    if (shader->kernel_input_size > 0)
3920       memcpy(map, grid->input, shader->kernel_input_size);
3921 
3922    uint32_t *sysval_map = map + system_values_start;
3923    for (int i = 0; i < shader->num_system_values; i++) {
3924       uint32_t sysval = shader->system_values[i];
3925       uint32_t value = 0;
3926 
3927 #if GFX_VER >= 9
3928       #define COMPILER(x) BRW_##x
3929 #else
3930       #define COMPILER(x) ELK_##x
3931 #endif
3932 
3933       if (ELK_PARAM_DOMAIN(sysval) == ELK_PARAM_DOMAIN_IMAGE) {
3934 #if GFX_VER == 8
3935          unsigned img = ELK_PARAM_IMAGE_IDX(sysval);
3936          unsigned offset = ELK_PARAM_IMAGE_OFFSET(sysval);
3937          struct isl_image_param *param =
3938             &genx->shaders[stage].image_param[img];
3939 
3940          assert(offset < sizeof(struct isl_image_param));
3941          value = ((uint32_t *) param)[offset];
3942 #endif
3943       } else if (sysval == COMPILER(PARAM_BUILTIN_ZERO)) {
3944          value = 0;
3945       } else if (COMPILER(PARAM_BUILTIN_IS_CLIP_PLANE(sysval))) {
3946          int plane = COMPILER(PARAM_BUILTIN_CLIP_PLANE_IDX(sysval));
3947          int comp  = COMPILER(PARAM_BUILTIN_CLIP_PLANE_COMP(sysval));
3948          value = fui(ice->state.clip_planes.ucp[plane][comp]);
3949       } else if (sysval == COMPILER(PARAM_BUILTIN_PATCH_VERTICES_IN)) {
3950          if (stage == MESA_SHADER_TESS_CTRL) {
3951             value = ice->state.vertices_per_patch;
3952          } else {
3953             assert(stage == MESA_SHADER_TESS_EVAL);
3954             const struct shader_info *tcs_info =
3955                iris_get_shader_info(ice, MESA_SHADER_TESS_CTRL);
3956             if (tcs_info)
3957                value = tcs_info->tess.tcs_vertices_out;
3958             else
3959                value = ice->state.vertices_per_patch;
3960          }
3961       } else if (sysval >= COMPILER(PARAM_BUILTIN_TESS_LEVEL_OUTER_X) &&
3962                  sysval <= COMPILER(PARAM_BUILTIN_TESS_LEVEL_OUTER_W)) {
3963          unsigned i = sysval - COMPILER(PARAM_BUILTIN_TESS_LEVEL_OUTER_X);
3964          value = fui(ice->state.default_outer_level[i]);
3965       } else if (sysval == COMPILER(PARAM_BUILTIN_TESS_LEVEL_INNER_X)) {
3966          value = fui(ice->state.default_inner_level[0]);
3967       } else if (sysval == COMPILER(PARAM_BUILTIN_TESS_LEVEL_INNER_Y)) {
3968          value = fui(ice->state.default_inner_level[1]);
3969       } else if (sysval >= COMPILER(PARAM_BUILTIN_WORK_GROUP_SIZE_X) &&
3970                  sysval <= COMPILER(PARAM_BUILTIN_WORK_GROUP_SIZE_Z)) {
3971          unsigned i = sysval - COMPILER(PARAM_BUILTIN_WORK_GROUP_SIZE_X);
3972          value = ice->state.last_block[i];
3973       } else if (sysval == COMPILER(PARAM_BUILTIN_WORK_DIM)) {
3974          value = grid->work_dim;
3975       } else {
3976          assert(!"unhandled system value");
3977       }
3978 
3979       *sysval_map++ = value;
3980    }
3981 
3982    cbuf->buffer_size = upload_size;
3983    iris_upload_ubo_ssbo_surf_state(ice, cbuf,
3984                                    &shs->constbuf_surf_state[sysval_cbuf_index],
3985                                    ISL_SURF_USAGE_CONSTANT_BUFFER_BIT);
3986 
3987    shs->sysvals_need_upload = false;
3988 }
3989 
3990 /**
3991  * The pipe->set_shader_buffers() driver hook.
3992  *
3993  * This binds SSBOs and ABOs.  Unfortunately, we need to stream out
3994  * SURFACE_STATE here, as the buffer offset may change each time.
3995  */
3996 static void
iris_set_shader_buffers(struct pipe_context * ctx,enum pipe_shader_type p_stage,unsigned start_slot,unsigned count,const struct pipe_shader_buffer * buffers,unsigned writable_bitmask)3997 iris_set_shader_buffers(struct pipe_context *ctx,
3998                         enum pipe_shader_type p_stage,
3999                         unsigned start_slot, unsigned count,
4000                         const struct pipe_shader_buffer *buffers,
4001                         unsigned writable_bitmask)
4002 {
4003    struct iris_context *ice = (struct iris_context *) ctx;
4004    gl_shader_stage stage = stage_from_pipe(p_stage);
4005    struct iris_shader_state *shs = &ice->state.shaders[stage];
4006 
4007    unsigned modified_bits = u_bit_consecutive(start_slot, count);
4008 
4009    shs->bound_ssbos &= ~modified_bits;
4010    shs->writable_ssbos &= ~modified_bits;
4011    shs->writable_ssbos |= writable_bitmask << start_slot;
4012 
4013    for (unsigned i = 0; i < count; i++) {
4014       if (buffers && buffers[i].buffer) {
4015          struct iris_resource *res = (void *) buffers[i].buffer;
4016          struct pipe_shader_buffer *ssbo = &shs->ssbo[start_slot + i];
4017          struct iris_state_ref *surf_state =
4018             &shs->ssbo_surf_state[start_slot + i];
4019          pipe_resource_reference(&ssbo->buffer, &res->base.b);
4020          ssbo->buffer_offset = buffers[i].buffer_offset;
4021          ssbo->buffer_size =
4022             MIN2(buffers[i].buffer_size, res->bo->size - ssbo->buffer_offset);
4023 
4024          shs->bound_ssbos |= 1 << (start_slot + i);
4025 
4026          isl_surf_usage_flags_t usage = ISL_SURF_USAGE_STORAGE_BIT;
4027 
4028          iris_upload_ubo_ssbo_surf_state(ice, ssbo, surf_state, usage);
4029 
4030          res->bind_history |= PIPE_BIND_SHADER_BUFFER;
4031          res->bind_stages |= 1 << stage;
4032 
4033          util_range_add(&res->base.b, &res->valid_buffer_range, ssbo->buffer_offset,
4034                         ssbo->buffer_offset + ssbo->buffer_size);
4035       } else {
4036          pipe_resource_reference(&shs->ssbo[start_slot + i].buffer, NULL);
4037          pipe_resource_reference(&shs->ssbo_surf_state[start_slot + i].res,
4038                                  NULL);
4039       }
4040    }
4041 
4042    ice->state.dirty |= (IRIS_DIRTY_RENDER_MISC_BUFFER_FLUSHES |
4043                         IRIS_DIRTY_COMPUTE_MISC_BUFFER_FLUSHES);
4044    ice->state.stage_dirty |= IRIS_STAGE_DIRTY_BINDINGS_VS << stage;
4045 }
4046 
4047 static void
iris_delete_state(struct pipe_context * ctx,void * state)4048 iris_delete_state(struct pipe_context *ctx, void *state)
4049 {
4050    free(state);
4051 }
4052 
4053 /**
4054  * The pipe->set_vertex_buffers() driver hook.
4055  *
4056  * This translates pipe_vertex_buffer to our 3DSTATE_VERTEX_BUFFERS packet.
4057  */
4058 static void
iris_set_vertex_buffers(struct pipe_context * ctx,unsigned count,const struct pipe_vertex_buffer * buffers)4059 iris_set_vertex_buffers(struct pipe_context *ctx,
4060                         unsigned count,
4061                         const struct pipe_vertex_buffer *buffers)
4062 {
4063    struct iris_context *ice = (struct iris_context *) ctx;
4064    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
4065    struct iris_genx_state *genx = ice->state.genx;
4066 
4067    unsigned last_count = util_last_bit64(ice->state.bound_vertex_buffers);
4068    ice->state.bound_vertex_buffers = 0;
4069 
4070    for (unsigned i = 0; i < count; i++) {
4071       const struct pipe_vertex_buffer *buffer = buffers ? &buffers[i] : NULL;
4072       struct iris_vertex_buffer_state *state =
4073          &genx->vertex_buffers[i];
4074 
4075       if (!buffer) {
4076          pipe_resource_reference(&state->resource, NULL);
4077          continue;
4078       }
4079 
4080       /* We may see user buffers that are NULL bindings. */
4081       assert(!(buffer->is_user_buffer && buffer->buffer.user != NULL));
4082 
4083       if (buffer->buffer.resource &&
4084           state->resource != buffer->buffer.resource)
4085          ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFER_FLUSHES;
4086 
4087       pipe_resource_reference(&state->resource, NULL);
4088       state->resource = buffer->buffer.resource;
4089 
4090       struct iris_resource *res = (void *) state->resource;
4091 
4092       state->offset = (int) buffer->buffer_offset;
4093 
4094       if (res) {
4095          ice->state.bound_vertex_buffers |= 1ull << i;
4096          res->bind_history |= PIPE_BIND_VERTEX_BUFFER;
4097       }
4098 
4099       iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
4100          vb.VertexBufferIndex = i;
4101          vb.AddressModifyEnable = true;
4102          /* vb.BufferPitch is merged in dynamically from VE state later */
4103          if (res) {
4104             vb.BufferSize = res->base.b.width0 - (int) buffer->buffer_offset;
4105             vb.BufferStartingAddress =
4106                ro_bo(NULL, res->bo->address + (int) buffer->buffer_offset);
4107             vb.MOCS = iris_mocs(res->bo, &screen->isl_dev,
4108                                 ISL_SURF_USAGE_VERTEX_BUFFER_BIT);
4109 #if GFX_VER >= 12
4110             vb.L3BypassDisable       = true;
4111 #endif
4112          } else {
4113             vb.NullVertexBuffer = true;
4114             vb.MOCS = iris_mocs(NULL, &screen->isl_dev,
4115                                 ISL_SURF_USAGE_VERTEX_BUFFER_BIT);
4116          }
4117       }
4118    }
4119 
4120    for (unsigned i = count; i < last_count; i++) {
4121       struct iris_vertex_buffer_state *state =
4122          &genx->vertex_buffers[i];
4123 
4124       pipe_resource_reference(&state->resource, NULL);
4125    }
4126 
4127    ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
4128 }
4129 
4130 /**
4131  * Gallium CSO for vertex elements.
4132  */
4133 struct iris_vertex_element_state {
4134    uint32_t vertex_elements[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
4135    uint32_t vf_instancing[33 * GENX(3DSTATE_VF_INSTANCING_length)];
4136    uint32_t edgeflag_ve[GENX(VERTEX_ELEMENT_STATE_length)];
4137    uint32_t edgeflag_vfi[GENX(3DSTATE_VF_INSTANCING_length)];
4138    uint32_t stride[PIPE_MAX_ATTRIBS];
4139    unsigned vb_count;
4140    unsigned count;
4141 };
4142 
4143 /**
4144  * The pipe->create_vertex_elements_state() driver hook.
4145  *
4146  * This translates pipe_vertex_element to our 3DSTATE_VERTEX_ELEMENTS
4147  * and 3DSTATE_VF_INSTANCING commands. The vertex_elements and vf_instancing
4148  * arrays are ready to be emitted at draw time if no EdgeFlag or SGVs are
4149  * needed. In these cases we will need information available at draw time.
4150  * We setup edgeflag_ve and edgeflag_vfi as alternatives last
4151  * 3DSTATE_VERTEX_ELEMENT and 3DSTATE_VF_INSTANCING that can be used at
4152  * draw time if we detect that EdgeFlag is needed by the Vertex Shader.
4153  */
4154 static void *
iris_create_vertex_elements(struct pipe_context * ctx,unsigned count,const struct pipe_vertex_element * state)4155 iris_create_vertex_elements(struct pipe_context *ctx,
4156                             unsigned count,
4157                             const struct pipe_vertex_element *state)
4158 {
4159    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
4160    const struct intel_device_info *devinfo = screen->devinfo;
4161    struct iris_vertex_element_state *cso =
4162       calloc(1, sizeof(struct iris_vertex_element_state));
4163 
4164    cso->count = count;
4165    cso->vb_count = 0;
4166 
4167    iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS), cso->vertex_elements, ve) {
4168       ve.DWordLength =
4169          1 + GENX(VERTEX_ELEMENT_STATE_length) * MAX2(count, 1) - 2;
4170    }
4171 
4172    uint32_t *ve_pack_dest = &cso->vertex_elements[1];
4173    uint32_t *vfi_pack_dest = cso->vf_instancing;
4174 
4175    if (count == 0) {
4176       iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
4177          ve.Valid = true;
4178          ve.SourceElementFormat = ISL_FORMAT_R32G32B32A32_FLOAT;
4179          ve.Component0Control = VFCOMP_STORE_0;
4180          ve.Component1Control = VFCOMP_STORE_0;
4181          ve.Component2Control = VFCOMP_STORE_0;
4182          ve.Component3Control = VFCOMP_STORE_1_FP;
4183       }
4184 
4185       iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
4186       }
4187    }
4188 
4189    for (int i = 0; i < count; i++) {
4190       const struct iris_format_info fmt =
4191          iris_format_for_usage(devinfo, state[i].src_format, 0);
4192       unsigned comp[4] = { VFCOMP_STORE_SRC, VFCOMP_STORE_SRC,
4193                            VFCOMP_STORE_SRC, VFCOMP_STORE_SRC };
4194 
4195       switch (isl_format_get_num_channels(fmt.fmt)) {
4196       case 0: comp[0] = VFCOMP_STORE_0; FALLTHROUGH;
4197       case 1: comp[1] = VFCOMP_STORE_0; FALLTHROUGH;
4198       case 2: comp[2] = VFCOMP_STORE_0; FALLTHROUGH;
4199       case 3:
4200          comp[3] = isl_format_has_int_channel(fmt.fmt) ? VFCOMP_STORE_1_INT
4201                                                        : VFCOMP_STORE_1_FP;
4202          break;
4203       }
4204       iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
4205          ve.EdgeFlagEnable = false;
4206          ve.VertexBufferIndex = state[i].vertex_buffer_index;
4207          ve.Valid = true;
4208          ve.SourceElementOffset = state[i].src_offset;
4209          ve.SourceElementFormat = fmt.fmt;
4210          ve.Component0Control = comp[0];
4211          ve.Component1Control = comp[1];
4212          ve.Component2Control = comp[2];
4213          ve.Component3Control = comp[3];
4214       }
4215 
4216       iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
4217          vi.VertexElementIndex = i;
4218          vi.InstancingEnable = state[i].instance_divisor > 0;
4219          vi.InstanceDataStepRate = state[i].instance_divisor;
4220       }
4221 
4222       ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
4223       vfi_pack_dest += GENX(3DSTATE_VF_INSTANCING_length);
4224       cso->stride[state[i].vertex_buffer_index] = state[i].src_stride;
4225       cso->vb_count = MAX2(state[i].vertex_buffer_index + 1, cso->vb_count);
4226    }
4227 
4228    /* An alternative version of the last VE and VFI is stored so it
4229     * can be used at draw time in case Vertex Shader uses EdgeFlag
4230     */
4231    if (count) {
4232       const unsigned edgeflag_index = count - 1;
4233       const struct iris_format_info fmt =
4234          iris_format_for_usage(devinfo, state[edgeflag_index].src_format, 0);
4235       iris_pack_state(GENX(VERTEX_ELEMENT_STATE), cso->edgeflag_ve, ve) {
4236          ve.EdgeFlagEnable = true ;
4237          ve.VertexBufferIndex = state[edgeflag_index].vertex_buffer_index;
4238          ve.Valid = true;
4239          ve.SourceElementOffset = state[edgeflag_index].src_offset;
4240          ve.SourceElementFormat = fmt.fmt;
4241          ve.Component0Control = VFCOMP_STORE_SRC;
4242          ve.Component1Control = VFCOMP_STORE_0;
4243          ve.Component2Control = VFCOMP_STORE_0;
4244          ve.Component3Control = VFCOMP_STORE_0;
4245       }
4246       iris_pack_command(GENX(3DSTATE_VF_INSTANCING), cso->edgeflag_vfi, vi) {
4247          /* The vi.VertexElementIndex of the EdgeFlag Vertex Element is filled
4248           * at draw time, as it should change if SGVs are emitted.
4249           */
4250          vi.InstancingEnable = state[edgeflag_index].instance_divisor > 0;
4251          vi.InstanceDataStepRate = state[edgeflag_index].instance_divisor;
4252       }
4253    }
4254 
4255    return cso;
4256 }
4257 
4258 /**
4259  * The pipe->bind_vertex_elements_state() driver hook.
4260  */
4261 static void
iris_bind_vertex_elements_state(struct pipe_context * ctx,void * state)4262 iris_bind_vertex_elements_state(struct pipe_context *ctx, void *state)
4263 {
4264    struct iris_context *ice = (struct iris_context *) ctx;
4265    struct iris_vertex_element_state *old_cso = ice->state.cso_vertex_elements;
4266    struct iris_vertex_element_state *new_cso = state;
4267 
4268    /* 3DSTATE_VF_SGVs overrides the last VE, so if the count is changing,
4269     * we need to re-emit it to ensure we're overriding the right one.
4270     */
4271    if (new_cso && cso_changed(count))
4272       ice->state.dirty |= IRIS_DIRTY_VF_SGVS;
4273 
4274    ice->state.cso_vertex_elements = state;
4275    ice->state.dirty |= IRIS_DIRTY_VERTEX_ELEMENTS;
4276    if (new_cso) {
4277       /* re-emit vertex buffer state if stride changes */
4278       if (cso_changed(vb_count) ||
4279           cso_changed_memcmp_elts(stride, new_cso->vb_count))
4280          ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
4281    }
4282 }
4283 
4284 /**
4285  * The pipe->create_stream_output_target() driver hook.
4286  *
4287  * "Target" here refers to a destination buffer.  We translate this into
4288  * a 3DSTATE_SO_BUFFER packet.  We can handle most fields, but don't yet
4289  * know which buffer this represents, or whether we ought to zero the
4290  * write-offsets, or append.  Those are handled in the set() hook.
4291  */
4292 static struct pipe_stream_output_target *
iris_create_stream_output_target(struct pipe_context * ctx,struct pipe_resource * p_res,unsigned buffer_offset,unsigned buffer_size)4293 iris_create_stream_output_target(struct pipe_context *ctx,
4294                                  struct pipe_resource *p_res,
4295                                  unsigned buffer_offset,
4296                                  unsigned buffer_size)
4297 {
4298    struct iris_resource *res = (void *) p_res;
4299    struct iris_stream_output_target *cso = calloc(1, sizeof(*cso));
4300    if (!cso)
4301       return NULL;
4302 
4303    res->bind_history |= PIPE_BIND_STREAM_OUTPUT;
4304 
4305    pipe_reference_init(&cso->base.reference, 1);
4306    pipe_resource_reference(&cso->base.buffer, p_res);
4307    cso->base.buffer_offset = buffer_offset;
4308    cso->base.buffer_size = buffer_size;
4309    cso->base.context = ctx;
4310 
4311    util_range_add(&res->base.b, &res->valid_buffer_range, buffer_offset,
4312                   buffer_offset + buffer_size);
4313 
4314    return &cso->base;
4315 }
4316 
4317 static void
iris_stream_output_target_destroy(struct pipe_context * ctx,struct pipe_stream_output_target * state)4318 iris_stream_output_target_destroy(struct pipe_context *ctx,
4319                                   struct pipe_stream_output_target *state)
4320 {
4321    struct iris_stream_output_target *cso = (void *) state;
4322 
4323    pipe_resource_reference(&cso->base.buffer, NULL);
4324    pipe_resource_reference(&cso->offset.res, NULL);
4325 
4326    free(cso);
4327 }
4328 
4329 /**
4330  * The pipe->set_stream_output_targets() driver hook.
4331  *
4332  * At this point, we know which targets are bound to a particular index,
4333  * and also whether we want to append or start over.  We can finish the
4334  * 3DSTATE_SO_BUFFER packets we started earlier.
4335  */
4336 static void
iris_set_stream_output_targets(struct pipe_context * ctx,unsigned num_targets,struct pipe_stream_output_target ** targets,const unsigned * offsets)4337 iris_set_stream_output_targets(struct pipe_context *ctx,
4338                                unsigned num_targets,
4339                                struct pipe_stream_output_target **targets,
4340                                const unsigned *offsets)
4341 {
4342    struct iris_context *ice = (struct iris_context *) ctx;
4343    struct iris_genx_state *genx = ice->state.genx;
4344    uint32_t *so_buffers = genx->so_buffers;
4345    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
4346 
4347    const bool active = num_targets > 0;
4348    if (ice->state.streamout_active != active) {
4349       ice->state.streamout_active = active;
4350       ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
4351 
4352       /* We only emit 3DSTATE_SO_DECL_LIST when streamout is active, because
4353        * it's a non-pipelined command.  If we're switching streamout on, we
4354        * may have missed emitting it earlier, so do so now.  (We're already
4355        * taking a stall to update 3DSTATE_SO_BUFFERS anyway...)
4356        */
4357       if (active) {
4358          ice->state.dirty |= IRIS_DIRTY_SO_DECL_LIST;
4359       } else {
4360          for (int i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
4361             struct iris_stream_output_target *tgt =
4362                (void *) ice->state.so_target[i];
4363 
4364             if (tgt)
4365                iris_dirty_for_history(ice, (void *)tgt->base.buffer);
4366          }
4367       }
4368    }
4369 
4370    for (int i = 0; i < 4; i++) {
4371       pipe_so_target_reference(&ice->state.so_target[i],
4372                                i < num_targets ? targets[i] : NULL);
4373    }
4374 
4375    /* No need to update 3DSTATE_SO_BUFFER unless SOL is active. */
4376    if (!active)
4377       return;
4378 
4379    for (unsigned i = 0; i < 4; i++,
4380         so_buffers += GENX(3DSTATE_SO_BUFFER_length)) {
4381 
4382       struct iris_stream_output_target *tgt = (void *) ice->state.so_target[i];
4383       unsigned offset = offsets[i];
4384 
4385       if (!tgt) {
4386          iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob) {
4387 #if GFX_VER < 12
4388             sob.SOBufferIndex = i;
4389 #else
4390             sob._3DCommandOpcode = 0;
4391             sob._3DCommandSubOpcode = SO_BUFFER_INDEX_0_CMD + i;
4392 #endif
4393             sob.MOCS = iris_mocs(NULL, &screen->isl_dev, 0);
4394          }
4395          continue;
4396       }
4397 
4398       if (!tgt->offset.res)
4399          upload_state(ctx->const_uploader, &tgt->offset, sizeof(uint32_t), 4);
4400 
4401       struct iris_resource *res = (void *) tgt->base.buffer;
4402 
4403       /* Note that offsets[i] will either be 0, causing us to zero
4404        * the value in the buffer, or 0xFFFFFFFF, which happens to mean
4405        * "continue appending at the existing offset."
4406        */
4407       assert(offset == 0 || offset == 0xFFFFFFFF);
4408 
4409       /* When we're first called with an offset of 0, we want the next
4410        * 3DSTATE_SO_BUFFER packets to reset the offset to the beginning.
4411        * Any further times we emit those packets, we want to use 0xFFFFFFFF
4412        * to continue appending from the current offset.
4413        *
4414        * Note that we might be called by Begin (offset = 0), Pause, then
4415        * Resume (offset = 0xFFFFFFFF) before ever drawing (where these
4416        * commands will actually be sent to the GPU).  In this case, we
4417        * don't want to append - we still want to do our initial zeroing.
4418        */
4419       if (offset == 0)
4420          tgt->zero_offset = true;
4421 
4422       iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob) {
4423 #if GFX_VER < 12
4424          sob.SOBufferIndex = i;
4425 #else
4426          sob._3DCommandOpcode = 0;
4427          sob._3DCommandSubOpcode = SO_BUFFER_INDEX_0_CMD + i;
4428 #endif
4429          sob.SurfaceBaseAddress =
4430             rw_bo(NULL, res->bo->address + tgt->base.buffer_offset,
4431                   IRIS_DOMAIN_OTHER_WRITE);
4432          sob.SOBufferEnable = true;
4433          sob.StreamOffsetWriteEnable = true;
4434          sob.StreamOutputBufferOffsetAddressEnable = true;
4435          sob.MOCS = iris_mocs(res->bo, &screen->isl_dev,
4436                               ISL_SURF_USAGE_STREAM_OUT_BIT);
4437 
4438          sob.SurfaceSize = MAX2(tgt->base.buffer_size / 4, 1) - 1;
4439          sob.StreamOutputBufferOffsetAddress =
4440             rw_bo(NULL, iris_resource_bo(tgt->offset.res)->address +
4441                         tgt->offset.offset, IRIS_DOMAIN_OTHER_WRITE);
4442          sob.StreamOffset = 0xFFFFFFFF; /* not offset, see above */
4443       }
4444    }
4445 
4446    ice->state.dirty |= IRIS_DIRTY_SO_BUFFERS;
4447 }
4448 
4449 /**
4450  * An iris-vtable helper for encoding the 3DSTATE_SO_DECL_LIST and
4451  * 3DSTATE_STREAMOUT packets.
4452  *
4453  * 3DSTATE_SO_DECL_LIST is a list of shader outputs we want the streamout
4454  * hardware to record.  We can create it entirely based on the shader, with
4455  * no dynamic state dependencies.
4456  *
4457  * 3DSTATE_STREAMOUT is an annoying mix of shader-based information and
4458  * state-based settings.  We capture the shader-related ones here, and merge
4459  * the rest in at draw time.
4460  */
4461 static uint32_t *
iris_create_so_decl_list(const struct pipe_stream_output_info * info,const struct intel_vue_map * vue_map)4462 iris_create_so_decl_list(const struct pipe_stream_output_info *info,
4463                          const struct intel_vue_map *vue_map)
4464 {
4465    struct GENX(SO_DECL) so_decl[PIPE_MAX_VERTEX_STREAMS][128];
4466    int buffer_mask[PIPE_MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
4467    int next_offset[PIPE_MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
4468    int decls[PIPE_MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
4469    int max_decls = 0;
4470    STATIC_ASSERT(ARRAY_SIZE(so_decl[0]) >= PIPE_MAX_SO_OUTPUTS);
4471 
4472    memset(so_decl, 0, sizeof(so_decl));
4473 
4474    /* Construct the list of SO_DECLs to be emitted.  The formatting of the
4475     * command feels strange -- each dword pair contains a SO_DECL per stream.
4476     */
4477    for (unsigned i = 0; i < info->num_outputs; i++) {
4478       const struct pipe_stream_output *output = &info->output[i];
4479       const int buffer = output->output_buffer;
4480       const int varying = output->register_index;
4481       const unsigned stream_id = output->stream;
4482       assert(stream_id < PIPE_MAX_VERTEX_STREAMS);
4483 
4484       buffer_mask[stream_id] |= 1 << buffer;
4485 
4486       assert(vue_map->varying_to_slot[varying] >= 0);
4487 
4488       /* Mesa doesn't store entries for gl_SkipComponents in the Outputs[]
4489        * array.  Instead, it simply increments DstOffset for the following
4490        * input by the number of components that should be skipped.
4491        *
4492        * Our hardware is unusual in that it requires us to program SO_DECLs
4493        * for fake "hole" components, rather than simply taking the offset
4494        * for each real varying.  Each hole can have size 1, 2, 3, or 4; we
4495        * program as many size = 4 holes as we can, then a final hole to
4496        * accommodate the final 1, 2, or 3 remaining.
4497        */
4498       int skip_components = output->dst_offset - next_offset[buffer];
4499 
4500       while (skip_components > 0) {
4501          so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
4502             .HoleFlag = 1,
4503             .OutputBufferSlot = output->output_buffer,
4504             .ComponentMask = (1 << MIN2(skip_components, 4)) - 1,
4505          };
4506          skip_components -= 4;
4507       }
4508 
4509       next_offset[buffer] = output->dst_offset + output->num_components;
4510 
4511       so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
4512          .OutputBufferSlot = output->output_buffer,
4513          .RegisterIndex = vue_map->varying_to_slot[varying],
4514          .ComponentMask =
4515             ((1 << output->num_components) - 1) << output->start_component,
4516       };
4517 
4518       if (decls[stream_id] > max_decls)
4519          max_decls = decls[stream_id];
4520    }
4521 
4522    unsigned dwords = GENX(3DSTATE_STREAMOUT_length) + (3 + 2 * max_decls);
4523    uint32_t *map = ralloc_size(NULL, sizeof(uint32_t) * dwords);
4524    uint32_t *so_decl_map = map + GENX(3DSTATE_STREAMOUT_length);
4525 
4526    iris_pack_command(GENX(3DSTATE_STREAMOUT), map, sol) {
4527       int urb_entry_read_offset = 0;
4528       int urb_entry_read_length = (vue_map->num_slots + 1) / 2 -
4529          urb_entry_read_offset;
4530 
4531       /* We always read the whole vertex.  This could be reduced at some
4532        * point by reading less and offsetting the register index in the
4533        * SO_DECLs.
4534        */
4535       sol.Stream0VertexReadOffset = urb_entry_read_offset;
4536       sol.Stream0VertexReadLength = urb_entry_read_length - 1;
4537       sol.Stream1VertexReadOffset = urb_entry_read_offset;
4538       sol.Stream1VertexReadLength = urb_entry_read_length - 1;
4539       sol.Stream2VertexReadOffset = urb_entry_read_offset;
4540       sol.Stream2VertexReadLength = urb_entry_read_length - 1;
4541       sol.Stream3VertexReadOffset = urb_entry_read_offset;
4542       sol.Stream3VertexReadLength = urb_entry_read_length - 1;
4543 
4544       /* Set buffer pitches; 0 means unbound. */
4545       sol.Buffer0SurfacePitch = 4 * info->stride[0];
4546       sol.Buffer1SurfacePitch = 4 * info->stride[1];
4547       sol.Buffer2SurfacePitch = 4 * info->stride[2];
4548       sol.Buffer3SurfacePitch = 4 * info->stride[3];
4549    }
4550 
4551    iris_pack_command(GENX(3DSTATE_SO_DECL_LIST), so_decl_map, list) {
4552       list.DWordLength = 3 + 2 * max_decls - 2;
4553       list.StreamtoBufferSelects0 = buffer_mask[0];
4554       list.StreamtoBufferSelects1 = buffer_mask[1];
4555       list.StreamtoBufferSelects2 = buffer_mask[2];
4556       list.StreamtoBufferSelects3 = buffer_mask[3];
4557       list.NumEntries0 = decls[0];
4558       list.NumEntries1 = decls[1];
4559       list.NumEntries2 = decls[2];
4560       list.NumEntries3 = decls[3];
4561    }
4562 
4563    for (int i = 0; i < max_decls; i++) {
4564       iris_pack_state(GENX(SO_DECL_ENTRY), so_decl_map + 3 + i * 2, entry) {
4565          entry.Stream0Decl = so_decl[0][i];
4566          entry.Stream1Decl = so_decl[1][i];
4567          entry.Stream2Decl = so_decl[2][i];
4568          entry.Stream3Decl = so_decl[3][i];
4569       }
4570    }
4571 
4572    return map;
4573 }
4574 
4575 static inline int
iris_compute_first_urb_slot_required(uint64_t inputs_read,const struct intel_vue_map * prev_stage_vue_map)4576 iris_compute_first_urb_slot_required(uint64_t inputs_read,
4577                                      const struct intel_vue_map *prev_stage_vue_map)
4578 {
4579 #if GFX_VER >= 9
4580    return brw_compute_first_urb_slot_required(inputs_read, prev_stage_vue_map);
4581 #else
4582    return elk_compute_first_urb_slot_required(inputs_read, prev_stage_vue_map);
4583 #endif
4584 }
4585 
4586 static void
iris_compute_sbe_urb_read_interval(uint64_t fs_input_slots,const struct intel_vue_map * last_vue_map,bool two_sided_color,unsigned * out_offset,unsigned * out_length)4587 iris_compute_sbe_urb_read_interval(uint64_t fs_input_slots,
4588                                    const struct intel_vue_map *last_vue_map,
4589                                    bool two_sided_color,
4590                                    unsigned *out_offset,
4591                                    unsigned *out_length)
4592 {
4593    /* The compiler computes the first URB slot without considering COL/BFC
4594     * swizzling (because it doesn't know whether it's enabled), so we need
4595     * to do that here too.  This may result in a smaller offset, which
4596     * should be safe.
4597     */
4598    const unsigned first_slot =
4599       iris_compute_first_urb_slot_required(fs_input_slots, last_vue_map);
4600 
4601    /* This becomes the URB read offset (counted in pairs of slots). */
4602    assert(first_slot % 2 == 0);
4603    *out_offset = first_slot / 2;
4604 
4605    /* We need to adjust the inputs read to account for front/back color
4606     * swizzling, as it can make the URB length longer.
4607     */
4608    for (int c = 0; c <= 1; c++) {
4609       if (fs_input_slots & (VARYING_BIT_COL0 << c)) {
4610          /* If two sided color is enabled, the fragment shader's gl_Color
4611           * (COL0) input comes from either the gl_FrontColor (COL0) or
4612           * gl_BackColor (BFC0) input varyings.  Mark BFC as used, too.
4613           */
4614          if (two_sided_color)
4615             fs_input_slots |= (VARYING_BIT_BFC0 << c);
4616 
4617          /* If front color isn't written, we opt to give them back color
4618           * instead of an undefined value.  Switch from COL to BFC.
4619           */
4620          if (last_vue_map->varying_to_slot[VARYING_SLOT_COL0 + c] == -1) {
4621             fs_input_slots &= ~(VARYING_BIT_COL0 << c);
4622             fs_input_slots |= (VARYING_BIT_BFC0 << c);
4623          }
4624       }
4625    }
4626 
4627    /* Compute the minimum URB Read Length necessary for the FS inputs.
4628     *
4629     * From the Sandy Bridge PRM, Volume 2, Part 1, documentation for
4630     * 3DSTATE_SF DWord 1 bits 15:11, "Vertex URB Entry Read Length":
4631     *
4632     * "This field should be set to the minimum length required to read the
4633     *  maximum source attribute.  The maximum source attribute is indicated
4634     *  by the maximum value of the enabled Attribute # Source Attribute if
4635     *  Attribute Swizzle Enable is set, Number of Output Attributes-1 if
4636     *  enable is not set.
4637     *  read_length = ceiling((max_source_attr + 1) / 2)
4638     *
4639     *  [errata] Corruption/Hang possible if length programmed larger than
4640     *  recommended"
4641     *
4642     * Similar text exists for Ivy Bridge.
4643     *
4644     * We find the last URB slot that's actually read by the FS.
4645     */
4646    unsigned last_read_slot = last_vue_map->num_slots - 1;
4647    while (last_read_slot > first_slot && !(fs_input_slots &
4648           (1ull << last_vue_map->slot_to_varying[last_read_slot])))
4649       --last_read_slot;
4650 
4651    /* The URB read length is the difference of the two, counted in pairs. */
4652    *out_length = DIV_ROUND_UP(last_read_slot - first_slot + 1, 2);
4653 }
4654 
4655 static void
iris_emit_sbe_swiz(struct iris_batch * batch,const struct iris_context * ice,const struct intel_vue_map * vue_map,unsigned urb_read_offset,unsigned sprite_coord_enables)4656 iris_emit_sbe_swiz(struct iris_batch *batch,
4657                    const struct iris_context *ice,
4658                    const struct intel_vue_map *vue_map,
4659                    unsigned urb_read_offset,
4660                    unsigned sprite_coord_enables)
4661 {
4662    struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) attr_overrides[16] = {};
4663    const struct iris_fs_data *fs_data =
4664       iris_fs_data(ice->shaders.prog[MESA_SHADER_FRAGMENT]);
4665    const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4666 
4667    /* XXX: this should be generated when putting programs in place */
4668 
4669    for (uint8_t idx = 0; idx < fs_data->urb_setup_attribs_count; idx++) {
4670       const uint8_t fs_attr = fs_data->urb_setup_attribs[idx];
4671       const int input_index = fs_data->urb_setup[fs_attr];
4672       if (input_index < 0 || input_index >= 16)
4673          continue;
4674 
4675       struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) *attr =
4676          &attr_overrides[input_index];
4677       int slot = vue_map->varying_to_slot[fs_attr];
4678 
4679       /* Viewport and Layer are stored in the VUE header.  We need to override
4680        * them to zero if earlier stages didn't write them, as GL requires that
4681        * they read back as zero when not explicitly set.
4682        */
4683       switch (fs_attr) {
4684       case VARYING_SLOT_VIEWPORT:
4685       case VARYING_SLOT_LAYER:
4686          attr->ComponentOverrideX = true;
4687          attr->ComponentOverrideW = true;
4688          attr->ConstantSource = CONST_0000;
4689 
4690          if (!(vue_map->slots_valid & VARYING_BIT_LAYER))
4691             attr->ComponentOverrideY = true;
4692          if (!(vue_map->slots_valid & VARYING_BIT_VIEWPORT))
4693             attr->ComponentOverrideZ = true;
4694          continue;
4695 
4696       default:
4697          break;
4698       }
4699 
4700       if (sprite_coord_enables & (1 << input_index))
4701          continue;
4702 
4703       /* If there was only a back color written but not front, use back
4704        * as the color instead of undefined.
4705        */
4706       if (slot == -1 && fs_attr == VARYING_SLOT_COL0)
4707          slot = vue_map->varying_to_slot[VARYING_SLOT_BFC0];
4708       if (slot == -1 && fs_attr == VARYING_SLOT_COL1)
4709          slot = vue_map->varying_to_slot[VARYING_SLOT_BFC1];
4710 
4711       /* Not written by the previous stage - undefined. */
4712       if (slot == -1) {
4713          attr->ComponentOverrideX = true;
4714          attr->ComponentOverrideY = true;
4715          attr->ComponentOverrideZ = true;
4716          attr->ComponentOverrideW = true;
4717          attr->ConstantSource = CONST_0001_FLOAT;
4718          continue;
4719       }
4720 
4721       /* Compute the location of the attribute relative to the read offset,
4722        * which is counted in 256-bit increments (two 128-bit VUE slots).
4723        */
4724       const int source_attr = slot - 2 * urb_read_offset;
4725       assert(source_attr >= 0 && source_attr <= 32);
4726       attr->SourceAttribute = source_attr;
4727 
4728       /* If we are doing two-sided color, and the VUE slot following this one
4729        * represents a back-facing color, then we need to instruct the SF unit
4730        * to do back-facing swizzling.
4731        */
4732       if (cso_rast->light_twoside &&
4733           ((vue_map->slot_to_varying[slot] == VARYING_SLOT_COL0 &&
4734             vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC0) ||
4735            (vue_map->slot_to_varying[slot] == VARYING_SLOT_COL1 &&
4736             vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC1)))
4737          attr->SwizzleSelect = INPUTATTR_FACING;
4738    }
4739 
4740    iris_emit_cmd(batch, GENX(3DSTATE_SBE_SWIZ), sbes) {
4741       for (int i = 0; i < 16; i++)
4742          sbes.Attribute[i] = attr_overrides[i];
4743    }
4744 }
4745 
4746 static bool
iris_is_drawing_points(const struct iris_context * ice)4747 iris_is_drawing_points(const struct iris_context *ice)
4748 {
4749    const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4750 
4751    if (cso_rast->fill_mode_point) {
4752       return true;
4753    }
4754 
4755    if (ice->shaders.prog[MESA_SHADER_GEOMETRY]) {
4756       const struct iris_gs_data *gs_data =
4757          iris_gs_data(ice->shaders.prog[MESA_SHADER_GEOMETRY]);
4758       return gs_data->output_topology == _3DPRIM_POINTLIST;
4759    } else if (ice->shaders.prog[MESA_SHADER_TESS_EVAL]) {
4760       const struct iris_tes_data *tes_data =
4761          iris_tes_data(ice->shaders.prog[MESA_SHADER_TESS_EVAL]);
4762       return tes_data->output_topology == INTEL_TESS_OUTPUT_TOPOLOGY_POINT;
4763    } else {
4764       return ice->state.prim_mode == MESA_PRIM_POINTS;
4765    }
4766 }
4767 
4768 static unsigned
iris_calculate_point_sprite_overrides(const struct iris_fs_data * fs_data,const struct iris_rasterizer_state * cso)4769 iris_calculate_point_sprite_overrides(const struct iris_fs_data *fs_data,
4770                                       const struct iris_rasterizer_state *cso)
4771 {
4772    unsigned overrides = 0;
4773 
4774    if (fs_data->urb_setup[VARYING_SLOT_PNTC] != -1)
4775       overrides |= 1 << fs_data->urb_setup[VARYING_SLOT_PNTC];
4776 
4777    for (int i = 0; i < 8; i++) {
4778       if ((cso->sprite_coord_enable & (1 << i)) &&
4779           fs_data->urb_setup[VARYING_SLOT_TEX0 + i] != -1)
4780          overrides |= 1 << fs_data->urb_setup[VARYING_SLOT_TEX0 + i];
4781    }
4782 
4783    return overrides;
4784 }
4785 
4786 static void
iris_emit_sbe(struct iris_batch * batch,const struct iris_context * ice)4787 iris_emit_sbe(struct iris_batch *batch, const struct iris_context *ice)
4788 {
4789    const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4790    const struct iris_fs_data *fs_data =
4791       iris_fs_data(ice->shaders.prog[MESA_SHADER_FRAGMENT]);
4792    const struct intel_vue_map *last_vue_map =
4793       &iris_vue_data(ice->shaders.last_vue_shader)->vue_map;
4794 
4795    unsigned urb_read_offset, urb_read_length;
4796    iris_compute_sbe_urb_read_interval(fs_data->inputs,
4797                                       last_vue_map,
4798                                       cso_rast->light_twoside,
4799                                       &urb_read_offset, &urb_read_length);
4800 
4801    unsigned sprite_coord_overrides =
4802       iris_is_drawing_points(ice) ?
4803       iris_calculate_point_sprite_overrides(fs_data, cso_rast) : 0;
4804 
4805    iris_emit_cmd(batch, GENX(3DSTATE_SBE), sbe) {
4806       sbe.AttributeSwizzleEnable = true;
4807       sbe.NumberofSFOutputAttributes = fs_data->num_varying_inputs;
4808       sbe.PointSpriteTextureCoordinateOrigin = cso_rast->sprite_coord_mode;
4809       sbe.VertexURBEntryReadOffset = urb_read_offset;
4810       sbe.VertexURBEntryReadLength = urb_read_length;
4811       sbe.ForceVertexURBEntryReadOffset = true;
4812       sbe.ForceVertexURBEntryReadLength = true;
4813       sbe.ConstantInterpolationEnable = fs_data->flat_inputs;
4814       sbe.PointSpriteTextureCoordinateEnable = sprite_coord_overrides;
4815 #if GFX_VER >= 9
4816       for (int i = 0; i < 32; i++) {
4817          sbe.AttributeActiveComponentFormat[i] = ACTIVE_COMPONENT_XYZW;
4818       }
4819 #endif
4820 
4821       /* Ask the hardware to supply PrimitiveID if the fragment shader
4822        * reads it but a previous stage didn't write one.
4823        */
4824       if ((fs_data->inputs & VARYING_BIT_PRIMITIVE_ID) &&
4825           last_vue_map->varying_to_slot[VARYING_SLOT_PRIMITIVE_ID] == -1) {
4826          sbe.PrimitiveIDOverrideAttributeSelect =
4827             fs_data->urb_setup[VARYING_SLOT_PRIMITIVE_ID];
4828          sbe.PrimitiveIDOverrideComponentX = true;
4829          sbe.PrimitiveIDOverrideComponentY = true;
4830          sbe.PrimitiveIDOverrideComponentZ = true;
4831          sbe.PrimitiveIDOverrideComponentW = true;
4832       }
4833    }
4834 
4835    iris_emit_sbe_swiz(batch, ice, last_vue_map, urb_read_offset,
4836                       sprite_coord_overrides);
4837 }
4838 
4839 /* ------------------------------------------------------------------- */
4840 
4841 /**
4842  * Populate VS program key fields based on the current state.
4843  */
4844 static void
iris_populate_vs_key(const struct iris_context * ice,const struct shader_info * info,gl_shader_stage last_stage,struct iris_vs_prog_key * key)4845 iris_populate_vs_key(const struct iris_context *ice,
4846                      const struct shader_info *info,
4847                      gl_shader_stage last_stage,
4848                      struct iris_vs_prog_key *key)
4849 {
4850    const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4851 
4852    if (info->clip_distance_array_size == 0 &&
4853        (info->outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX)) &&
4854        last_stage == MESA_SHADER_VERTEX)
4855       key->vue.nr_userclip_plane_consts = cso_rast->num_clip_plane_consts;
4856 }
4857 
4858 /**
4859  * Populate TCS program key fields based on the current state.
4860  */
4861 static void
iris_populate_tcs_key(const struct iris_context * ice,struct iris_tcs_prog_key * key)4862 iris_populate_tcs_key(const struct iris_context *ice,
4863                       struct iris_tcs_prog_key *key)
4864 {
4865 }
4866 
4867 /**
4868  * Populate TES program key fields based on the current state.
4869  */
4870 static void
iris_populate_tes_key(const struct iris_context * ice,const struct shader_info * info,gl_shader_stage last_stage,struct iris_tes_prog_key * key)4871 iris_populate_tes_key(const struct iris_context *ice,
4872                       const struct shader_info *info,
4873                       gl_shader_stage last_stage,
4874                       struct iris_tes_prog_key *key)
4875 {
4876    const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4877 
4878    if (info->clip_distance_array_size == 0 &&
4879        (info->outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX)) &&
4880        last_stage == MESA_SHADER_TESS_EVAL)
4881       key->vue.nr_userclip_plane_consts = cso_rast->num_clip_plane_consts;
4882 }
4883 
4884 /**
4885  * Populate GS program key fields based on the current state.
4886  */
4887 static void
iris_populate_gs_key(const struct iris_context * ice,const struct shader_info * info,gl_shader_stage last_stage,struct iris_gs_prog_key * key)4888 iris_populate_gs_key(const struct iris_context *ice,
4889                      const struct shader_info *info,
4890                      gl_shader_stage last_stage,
4891                      struct iris_gs_prog_key *key)
4892 {
4893    const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4894 
4895    if (info->clip_distance_array_size == 0 &&
4896        (info->outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX)) &&
4897        last_stage == MESA_SHADER_GEOMETRY)
4898       key->vue.nr_userclip_plane_consts = cso_rast->num_clip_plane_consts;
4899 }
4900 
4901 /**
4902  * Populate FS program key fields based on the current state.
4903  */
4904 static void
iris_populate_fs_key(const struct iris_context * ice,const struct shader_info * info,struct iris_fs_prog_key * key)4905 iris_populate_fs_key(const struct iris_context *ice,
4906                      const struct shader_info *info,
4907                      struct iris_fs_prog_key *key)
4908 {
4909    struct iris_screen *screen = (void *) ice->ctx.screen;
4910    const struct pipe_framebuffer_state *fb = &ice->state.framebuffer;
4911    const struct iris_depth_stencil_alpha_state *zsa = ice->state.cso_zsa;
4912    const struct iris_rasterizer_state *rast = ice->state.cso_rast;
4913    const struct iris_blend_state *blend = ice->state.cso_blend;
4914 
4915    key->nr_color_regions = fb->nr_cbufs;
4916 
4917    key->clamp_fragment_color = rast->clamp_fragment_color;
4918 
4919    key->alpha_to_coverage = blend->alpha_to_coverage;
4920 
4921    key->alpha_test_replicate_alpha = fb->nr_cbufs > 1 && zsa->alpha_enabled;
4922 
4923    key->flat_shade = rast->flatshade &&
4924       (info->inputs_read & (VARYING_BIT_COL0 | VARYING_BIT_COL1));
4925 
4926    key->persample_interp = rast->force_persample_interp;
4927    key->multisample_fbo = rast->multisample && fb->samples > 1;
4928 
4929    key->coherent_fb_fetch = GFX_VER >= 9;
4930 
4931    key->force_dual_color_blend =
4932       screen->driconf.dual_color_blend_by_location &&
4933       (blend->blend_enables & 1) && blend->dual_color_blending;
4934 }
4935 
4936 static void
iris_populate_cs_key(const struct iris_context * ice,struct iris_cs_prog_key * key)4937 iris_populate_cs_key(const struct iris_context *ice,
4938                      struct iris_cs_prog_key *key)
4939 {
4940 }
4941 
4942 static uint32_t
encode_sampler_count(const struct iris_compiled_shader * shader)4943 encode_sampler_count(const struct iris_compiled_shader *shader)
4944 {
4945    uint32_t count = util_last_bit64(shader->bt.samplers_used_mask);
4946    uint32_t count_by_4 = DIV_ROUND_UP(count, 4);
4947 
4948    /* We can potentially have way more than 32 samplers and that's ok.
4949     * However, the 3DSTATE_XS packets only have 3 bits to specify how
4950     * many to pre-fetch and all values above 4 are marked reserved.
4951     */
4952    return MIN2(count_by_4, 4);
4953 }
4954 
4955 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix, stage)                   \
4956    pkt.KernelStartPointer = KSP(shader);                                  \
4957    pkt.BindingTableEntryCount = shader->bt.size_bytes / 4;                \
4958    pkt.SamplerCount = encode_sampler_count(shader);                       \
4959    pkt.FloatingPointMode = shader->use_alt_mode;                          \
4960                                                                           \
4961    pkt.DispatchGRFStartRegisterForURBData =                               \
4962       shader->dispatch_grf_start_reg;                                     \
4963    pkt.prefix##URBEntryReadLength = vue_data->urb_read_length;            \
4964    pkt.prefix##URBEntryReadOffset = 0;                                    \
4965                                                                           \
4966    pkt.StatisticsEnable = true;                                           \
4967    pkt.Enable           = true;                                           \
4968                                                                           \
4969    if (shader->total_scratch) {                                           \
4970       INIT_THREAD_SCRATCH_SIZE(pkt)                                       \
4971    }
4972 
4973 #if GFX_VERx10 >= 125
4974 #define INIT_THREAD_SCRATCH_SIZE(pkt)
4975 #define MERGE_SCRATCH_ADDR(name)                                          \
4976 {                                                                         \
4977    uint32_t pkt2[GENX(name##_length)] = {0};                              \
4978    _iris_pack_command(batch, GENX(name), pkt2, p) {                       \
4979       p.ScratchSpaceBuffer = scratch_addr >> 4;                           \
4980    }                                                                      \
4981    iris_emit_merge(batch, pkt, pkt2, GENX(name##_length));                \
4982 }
4983 #else
4984 #define INIT_THREAD_SCRATCH_SIZE(pkt)                                     \
4985    pkt.PerThreadScratchSpace = ffs(shader->total_scratch) - 11;
4986 #define MERGE_SCRATCH_ADDR(name)                                          \
4987 {                                                                         \
4988    uint32_t pkt2[GENX(name##_length)] = {0};                              \
4989    _iris_pack_command(batch, GENX(name), pkt2, p) {                       \
4990       p.ScratchSpaceBasePointer =                                         \
4991          rw_bo(NULL, scratch_addr, IRIS_DOMAIN_NONE);                     \
4992    }                                                                      \
4993    iris_emit_merge(batch, pkt, pkt2, GENX(name##_length));                \
4994 }
4995 #endif
4996 
4997 
4998 /**
4999  * Encode most of 3DSTATE_VS based on the compiled shader.
5000  */
5001 static void
iris_store_vs_state(const struct intel_device_info * devinfo,struct iris_compiled_shader * shader)5002 iris_store_vs_state(const struct intel_device_info *devinfo,
5003                     struct iris_compiled_shader *shader)
5004 {
5005    struct iris_vue_data *vue_data = iris_vue_data(shader);
5006 
5007    iris_pack_command(GENX(3DSTATE_VS), shader->derived_data, vs) {
5008       INIT_THREAD_DISPATCH_FIELDS(vs, Vertex, MESA_SHADER_VERTEX);
5009       vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
5010 #if GFX_VER < 20
5011       vs.SIMD8DispatchEnable = true;
5012 #endif
5013       vs.UserClipDistanceCullTestEnableBitmask =
5014          vue_data->cull_distance_mask;
5015    }
5016 }
5017 
5018 /**
5019  * Encode most of 3DSTATE_HS based on the compiled shader.
5020  */
5021 static void
iris_store_tcs_state(const struct intel_device_info * devinfo,struct iris_compiled_shader * shader)5022 iris_store_tcs_state(const struct intel_device_info *devinfo,
5023                      struct iris_compiled_shader *shader)
5024 {
5025    struct iris_tcs_data *tcs_data = iris_tcs_data(shader);
5026    struct iris_vue_data *vue_data = &tcs_data->base;
5027 
5028    iris_pack_command(GENX(3DSTATE_HS), shader->derived_data, hs) {
5029       INIT_THREAD_DISPATCH_FIELDS(hs, Vertex, MESA_SHADER_TESS_CTRL);
5030 
5031 #if GFX_VER >= 12
5032       /* Wa_1604578095:
5033        *
5034        *    Hang occurs when the number of max threads is less than 2 times
5035        *    the number of instance count. The number of max threads must be
5036        *    more than 2 times the number of instance count.
5037        */
5038       assert((devinfo->max_tcs_threads / 2) > tcs_data->instances);
5039       hs.DispatchGRFStartRegisterForURBData = shader->dispatch_grf_start_reg & 0x1f;
5040       hs.DispatchGRFStartRegisterForURBData5 = shader->dispatch_grf_start_reg >> 5;
5041 #endif
5042 
5043       hs.InstanceCount = tcs_data->instances - 1;
5044       hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
5045       hs.IncludeVertexHandles = true;
5046 
5047 #if GFX_VER == 12
5048       /* Patch Count threshold specifies the maximum number of patches that
5049        * will be accumulated before a thread dispatch is forced.
5050        */
5051       hs.PatchCountThreshold = tcs_data->patch_count_threshold;
5052 #endif
5053 
5054 #if GFX_VER >= 9
5055 #if GFX_VER < 20
5056       hs.DispatchMode = vue_data->dispatch_mode;
5057 #endif
5058       hs.IncludePrimitiveID = tcs_data->include_primitive_id;
5059 #endif
5060    }
5061 }
5062 
5063 /**
5064  * Encode 3DSTATE_TE and most of 3DSTATE_DS based on the compiled shader.
5065  */
5066 static void
iris_store_tes_state(const struct intel_device_info * devinfo,struct iris_compiled_shader * shader)5067 iris_store_tes_state(const struct intel_device_info *devinfo,
5068                      struct iris_compiled_shader *shader)
5069 {
5070    struct iris_tes_data *tes_data = iris_tes_data(shader);
5071    struct iris_vue_data *vue_data = &tes_data->base;
5072 
5073    uint32_t *ds_state = (void *) shader->derived_data;
5074    uint32_t *te_state = ds_state + GENX(3DSTATE_DS_length);
5075 
5076    iris_pack_command(GENX(3DSTATE_DS), ds_state, ds) {
5077       INIT_THREAD_DISPATCH_FIELDS(ds, Patch, MESA_SHADER_TESS_EVAL);
5078 
5079       ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
5080       ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
5081       ds.ComputeWCoordinateEnable =
5082          tes_data->domain == INTEL_TESS_DOMAIN_TRI;
5083 
5084 #if GFX_VER >= 12
5085       ds.PrimitiveIDNotRequired = !tes_data->include_primitive_id;
5086 #endif
5087       ds.UserClipDistanceCullTestEnableBitmask =
5088          vue_data->cull_distance_mask;
5089    }
5090 
5091    iris_pack_command(GENX(3DSTATE_TE), te_state, te) {
5092       te.Partitioning = tes_data->partitioning;
5093       te.OutputTopology = tes_data->output_topology;
5094       te.TEDomain = tes_data->domain;
5095       te.TEEnable = true;
5096       te.MaximumTessellationFactorOdd = 63.0;
5097       te.MaximumTessellationFactorNotOdd = 64.0;
5098 #if GFX_VERx10 >= 125
5099       STATIC_ASSERT(TEDMODE_OFF == 0);
5100       if (intel_needs_workaround(devinfo, 14015055625)) {
5101          te.TessellationDistributionMode = TEDMODE_OFF;
5102       } else if (intel_needs_workaround(devinfo, 22012699309)) {
5103          te.TessellationDistributionMode = TEDMODE_RR_STRICT;
5104       } else {
5105          te.TessellationDistributionMode = TEDMODE_RR_FREE;
5106       }
5107 
5108    #if GFX_VER >= 20
5109       te.TessellationDistributionLevel = TEDLEVEL_REGION;
5110    #else
5111       te.TessellationDistributionLevel = TEDLEVEL_PATCH;
5112    #endif
5113       /* 64_TRIANGLES */
5114       te.SmallPatchThreshold = 3;
5115       /* 1K_TRIANGLES */
5116       te.TargetBlockSize = 8;
5117       /* 1K_TRIANGLES */
5118       te.LocalBOPAccumulatorThreshold = 1;
5119 #endif
5120    }
5121 }
5122 
5123 /**
5124  * Encode most of 3DSTATE_GS based on the compiled shader.
5125  */
5126 static void
iris_store_gs_state(const struct intel_device_info * devinfo,struct iris_compiled_shader * shader)5127 iris_store_gs_state(const struct intel_device_info *devinfo,
5128                     struct iris_compiled_shader *shader)
5129 {
5130    struct iris_gs_data *gs_data = iris_gs_data(shader);
5131    struct iris_vue_data *vue_data = &gs_data->base;
5132 
5133    iris_pack_command(GENX(3DSTATE_GS), shader->derived_data, gs) {
5134       INIT_THREAD_DISPATCH_FIELDS(gs, Vertex, MESA_SHADER_GEOMETRY);
5135 
5136       gs.OutputVertexSize = gs_data->output_vertex_size_hwords * 2 - 1;
5137       gs.OutputTopology = gs_data->output_topology;
5138       gs.ControlDataHeaderSize = gs_data->control_data_header_size_hwords;
5139       gs.InstanceControl = gs_data->invocations - 1;
5140 #if GFX_VER < 20
5141       gs.DispatchMode = DISPATCH_MODE_SIMD8;
5142 #endif
5143       gs.IncludePrimitiveID = gs_data->include_primitive_id;
5144       gs.ControlDataFormat = gs_data->control_data_format;
5145       gs.ReorderMode = TRAILING;
5146       gs.ExpectedVertexCount = gs_data->vertices_in;
5147       gs.MaximumNumberofThreads =
5148          GFX_VER == 8 ? (devinfo->max_gs_threads / 2 - 1)
5149                       : (devinfo->max_gs_threads - 1);
5150 
5151       if (gs_data->static_vertex_count != -1) {
5152          gs.StaticOutput = true;
5153          gs.StaticOutputVertexCount = gs_data->static_vertex_count;
5154       }
5155       gs.IncludeVertexHandles = vue_data->include_vue_handles;
5156 
5157       gs.UserClipDistanceCullTestEnableBitmask = vue_data->cull_distance_mask;
5158 
5159       const int urb_entry_write_offset = 1;
5160       const uint32_t urb_entry_output_length =
5161          DIV_ROUND_UP(vue_data->vue_map.num_slots, 2) - urb_entry_write_offset;
5162 
5163       gs.VertexURBEntryOutputReadOffset = urb_entry_write_offset;
5164       gs.VertexURBEntryOutputLength = MAX2(urb_entry_output_length, 1);
5165    }
5166 }
5167 
5168 /**
5169  * Encode most of 3DSTATE_PS and 3DSTATE_PS_EXTRA based on the shader.
5170  */
5171 static void
iris_store_fs_state(const struct intel_device_info * devinfo,struct iris_compiled_shader * shader)5172 iris_store_fs_state(const struct intel_device_info *devinfo,
5173                     struct iris_compiled_shader *shader)
5174 {
5175    struct iris_fs_data *fs_data = iris_fs_data(shader);
5176 
5177    uint32_t *ps_state = (void *) shader->derived_data;
5178    uint32_t *psx_state = ps_state + GENX(3DSTATE_PS_length);
5179 
5180    iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
5181       ps.VectorMaskEnable = fs_data->uses_vmask;
5182       ps.BindingTableEntryCount = shader->bt.size_bytes / 4;
5183       ps.SamplerCount = encode_sampler_count(shader);
5184       ps.FloatingPointMode = shader->use_alt_mode;
5185       ps.MaximumNumberofThreadsPerPSD =
5186          devinfo->max_threads_per_psd - (GFX_VER == 8 ? 2 : 1);
5187 
5188 #if GFX_VER < 20
5189       ps.PushConstantEnable = shader->ubo_ranges[0].length > 0;
5190 #endif
5191 
5192       /* From the documentation for this packet:
5193        * "If the PS kernel does not need the Position XY Offsets to
5194        *  compute a Position Value, then this field should be programmed
5195        *  to POSOFFSET_NONE."
5196        *
5197        * "SW Recommendation: If the PS kernel needs the Position Offsets
5198        *  to compute a Position XY value, this field should match Position
5199        *  ZW Interpolation Mode to ensure a consistent position.xyzw
5200        *  computation."
5201        *
5202        * We only require XY sample offsets. So, this recommendation doesn't
5203        * look useful at the moment.  We might need this in future.
5204        */
5205       ps.PositionXYOffsetSelect =
5206          fs_data->uses_pos_offset ? POSOFFSET_SAMPLE : POSOFFSET_NONE;
5207 
5208       if (shader->total_scratch) {
5209          INIT_THREAD_SCRATCH_SIZE(ps);
5210       }
5211    }
5212 
5213    iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
5214       psx.PixelShaderValid = true;
5215       psx.PixelShaderComputedDepthMode = fs_data->computed_depth_mode;
5216       psx.PixelShaderKillsPixel = fs_data->uses_kill;
5217 #if GFX_VER < 20
5218       psx.AttributeEnable = fs_data->num_varying_inputs != 0;
5219 #endif
5220       psx.PixelShaderUsesSourceDepth = fs_data->uses_src_depth;
5221       psx.PixelShaderUsesSourceW = fs_data->uses_src_w;
5222       psx.PixelShaderIsPerSample = fs_data->is_per_sample;
5223       psx.oMaskPresenttoRenderTarget = fs_data->uses_omask;
5224 
5225 #if GFX_VER >= 9
5226 #if GFX_VER >= 20
5227       assert(!fs_data->pulls_bary);
5228 #else
5229       psx.PixelShaderPullsBary = fs_data->pulls_bary;
5230 #endif
5231       psx.PixelShaderComputesStencil = fs_data->computed_stencil;
5232 #endif
5233    }
5234 }
5235 
5236 /**
5237  * Compute the size of the derived data (shader command packets).
5238  *
5239  * This must match the data written by the iris_store_xs_state() functions.
5240  */
5241 static void
iris_store_cs_state(const struct intel_device_info * devinfo,struct iris_compiled_shader * shader)5242 iris_store_cs_state(const struct intel_device_info *devinfo,
5243                     struct iris_compiled_shader *shader)
5244 {
5245    struct iris_cs_data *cs_data = iris_cs_data(shader);
5246    void *map = shader->derived_data;
5247 
5248    iris_pack_state(GENX(INTERFACE_DESCRIPTOR_DATA), map, desc) {
5249 #if GFX_VERx10 < 125
5250       desc.ConstantURBEntryReadLength = cs_data->push.per_thread.regs;
5251       desc.CrossThreadConstantDataReadLength =
5252          cs_data->push.cross_thread.regs;
5253 #else
5254       assert(cs_data->push.per_thread.regs == 0);
5255       assert(cs_data->push.cross_thread.regs == 0);
5256 #endif
5257 #if GFX_VERx10 <= 125
5258       desc.BarrierEnable = cs_data->uses_barrier;
5259 #endif
5260       /* Typically set to 0 to avoid prefetching on every thread dispatch. */
5261       desc.BindingTableEntryCount = devinfo->verx10 == 125 ?
5262          0 : MIN2(shader->bt.size_bytes / 4, 31);
5263       desc.SamplerCount = encode_sampler_count(shader);
5264       /* TODO: Check if we are missing workarounds and enable mid-thread
5265        * preemption.
5266        *
5267        * We still have issues with mid-thread preemption (it was already
5268        * disabled by the kernel on gfx11, due to missing workarounds). It's
5269        * possible that we are just missing some workarounds, and could enable
5270        * it later, but for now let's disable it to fix a GPU in compute in Car
5271        * Chase (and possibly more).
5272        */
5273 #if GFX_VER >= 20
5274       desc.ThreadPreemption = false;
5275 #elif GFX_VER >= 12
5276       desc.ThreadPreemptionDisable = true;
5277 #endif
5278    }
5279 }
5280 
5281 static unsigned
iris_derived_program_state_size(enum iris_program_cache_id cache_id)5282 iris_derived_program_state_size(enum iris_program_cache_id cache_id)
5283 {
5284    assert(cache_id <= IRIS_CACHE_BLORP);
5285 
5286    static const unsigned dwords[] = {
5287       [IRIS_CACHE_VS] = GENX(3DSTATE_VS_length),
5288       [IRIS_CACHE_TCS] = GENX(3DSTATE_HS_length),
5289       [IRIS_CACHE_TES] = GENX(3DSTATE_TE_length) + GENX(3DSTATE_DS_length),
5290       [IRIS_CACHE_GS] = GENX(3DSTATE_GS_length),
5291       [IRIS_CACHE_FS] =
5292          GENX(3DSTATE_PS_length) + GENX(3DSTATE_PS_EXTRA_length),
5293       [IRIS_CACHE_CS] = GENX(INTERFACE_DESCRIPTOR_DATA_length),
5294       [IRIS_CACHE_BLORP] = 0,
5295    };
5296 
5297    return sizeof(uint32_t) * dwords[cache_id];
5298 }
5299 
5300 /**
5301  * Create any state packets corresponding to the given shader stage
5302  * (i.e. 3DSTATE_VS) and save them as "derived data" in the shader variant.
5303  * This means that we can look up a program in the in-memory cache and
5304  * get most of the state packet without having to reconstruct it.
5305  */
5306 static void
iris_store_derived_program_state(const struct intel_device_info * devinfo,enum iris_program_cache_id cache_id,struct iris_compiled_shader * shader)5307 iris_store_derived_program_state(const struct intel_device_info *devinfo,
5308                                  enum iris_program_cache_id cache_id,
5309                                  struct iris_compiled_shader *shader)
5310 {
5311    switch (cache_id) {
5312    case IRIS_CACHE_VS:
5313       iris_store_vs_state(devinfo, shader);
5314       break;
5315    case IRIS_CACHE_TCS:
5316       iris_store_tcs_state(devinfo, shader);
5317       break;
5318    case IRIS_CACHE_TES:
5319       iris_store_tes_state(devinfo, shader);
5320       break;
5321    case IRIS_CACHE_GS:
5322       iris_store_gs_state(devinfo, shader);
5323       break;
5324    case IRIS_CACHE_FS:
5325       iris_store_fs_state(devinfo, shader);
5326       break;
5327    case IRIS_CACHE_CS:
5328       iris_store_cs_state(devinfo, shader);
5329       break;
5330    case IRIS_CACHE_BLORP:
5331       break;
5332    }
5333 }
5334 
5335 /* ------------------------------------------------------------------- */
5336 
5337 static const uint32_t push_constant_opcodes[] = {
5338    [MESA_SHADER_VERTEX]    = 21,
5339    [MESA_SHADER_TESS_CTRL] = 25, /* HS */
5340    [MESA_SHADER_TESS_EVAL] = 26, /* DS */
5341    [MESA_SHADER_GEOMETRY]  = 22,
5342    [MESA_SHADER_FRAGMENT]  = 23,
5343    [MESA_SHADER_COMPUTE]   = 0,
5344 };
5345 
5346 static uint32_t
use_null_surface(struct iris_batch * batch,struct iris_context * ice)5347 use_null_surface(struct iris_batch *batch, struct iris_context *ice)
5348 {
5349    struct iris_bo *state_bo = iris_resource_bo(ice->state.unbound_tex.res);
5350 
5351    iris_use_pinned_bo(batch, state_bo, false, IRIS_DOMAIN_NONE);
5352 
5353    return ice->state.unbound_tex.offset;
5354 }
5355 
5356 static uint32_t
use_null_fb_surface(struct iris_batch * batch,struct iris_context * ice)5357 use_null_fb_surface(struct iris_batch *batch, struct iris_context *ice)
5358 {
5359    /* If set_framebuffer_state() was never called, fall back to 1x1x1 */
5360    if (!ice->state.null_fb.res)
5361       return use_null_surface(batch, ice);
5362 
5363    struct iris_bo *state_bo = iris_resource_bo(ice->state.null_fb.res);
5364 
5365    iris_use_pinned_bo(batch, state_bo, false, IRIS_DOMAIN_NONE);
5366 
5367    return ice->state.null_fb.offset;
5368 }
5369 
5370 static uint32_t
surf_state_offset_for_aux(unsigned aux_modes,enum isl_aux_usage aux_usage)5371 surf_state_offset_for_aux(unsigned aux_modes,
5372                           enum isl_aux_usage aux_usage)
5373 {
5374    assert(aux_modes & (1 << aux_usage));
5375    return SURFACE_STATE_ALIGNMENT *
5376           util_bitcount(aux_modes & ((1 << aux_usage) - 1));
5377 }
5378 
5379 #if GFX_VER == 9
5380 static void
surf_state_update_clear_value(struct iris_batch * batch,struct iris_resource * res,struct iris_surface_state * surf_state,enum isl_aux_usage aux_usage)5381 surf_state_update_clear_value(struct iris_batch *batch,
5382                               struct iris_resource *res,
5383                               struct iris_surface_state *surf_state,
5384                               enum isl_aux_usage aux_usage)
5385 {
5386    struct isl_device *isl_dev = &batch->screen->isl_dev;
5387    struct iris_bo *state_bo = iris_resource_bo(surf_state->ref.res);
5388    uint64_t real_offset = surf_state->ref.offset + IRIS_MEMZONE_BINDER_START;
5389    uint32_t offset_into_bo = real_offset - state_bo->address;
5390    uint32_t clear_offset = offset_into_bo +
5391       isl_dev->ss.clear_value_offset +
5392       surf_state_offset_for_aux(surf_state->aux_usages, aux_usage);
5393    uint32_t *color = res->aux.clear_color.u32;
5394 
5395    assert(isl_dev->ss.clear_value_size == 16);
5396 
5397    if (aux_usage == ISL_AUX_USAGE_HIZ) {
5398       iris_emit_pipe_control_write(batch, "update fast clear value (Z)",
5399                                    PIPE_CONTROL_WRITE_IMMEDIATE,
5400                                    state_bo, clear_offset, color[0]);
5401    } else {
5402       iris_emit_pipe_control_write(batch, "update fast clear color (RG__)",
5403                                    PIPE_CONTROL_WRITE_IMMEDIATE,
5404                                    state_bo, clear_offset,
5405                                    (uint64_t) color[0] |
5406                                    (uint64_t) color[1] << 32);
5407       iris_emit_pipe_control_write(batch, "update fast clear color (__BA)",
5408                                    PIPE_CONTROL_WRITE_IMMEDIATE,
5409                                    state_bo, clear_offset + 8,
5410                                    (uint64_t) color[2] |
5411                                    (uint64_t) color[3] << 32);
5412    }
5413 
5414    iris_emit_pipe_control_flush(batch,
5415                                 "update fast clear: state cache invalidate",
5416                                 PIPE_CONTROL_FLUSH_ENABLE |
5417                                 PIPE_CONTROL_STATE_CACHE_INVALIDATE);
5418 }
5419 #endif
5420 
5421 static void
update_clear_value(struct iris_context * ice,struct iris_batch * batch,struct iris_resource * res,struct iris_surface_state * surf_state,struct isl_view * view)5422 update_clear_value(struct iris_context *ice,
5423                    struct iris_batch *batch,
5424                    struct iris_resource *res,
5425                    struct iris_surface_state *surf_state,
5426                    struct isl_view *view)
5427 {
5428    UNUSED struct isl_device *isl_dev = &batch->screen->isl_dev;
5429    UNUSED unsigned aux_modes = surf_state->aux_usages;
5430 
5431    /* We only need to update the clear color in the surface state for gfx8 and
5432     * gfx9. Newer gens can read it directly from the clear color state buffer.
5433     */
5434 #if GFX_VER == 9
5435    /* Skip updating the ISL_AUX_USAGE_NONE surface state */
5436    aux_modes &= ~(1 << ISL_AUX_USAGE_NONE);
5437 
5438    while (aux_modes) {
5439       enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
5440 
5441       surf_state_update_clear_value(batch, res, surf_state, aux_usage);
5442    }
5443 #elif GFX_VER == 8
5444    /* TODO: Could update rather than re-filling */
5445    alloc_surface_states(surf_state, surf_state->aux_usages);
5446 
5447    fill_surface_states(isl_dev, surf_state, res, &res->surf, view, 0, 0, 0);
5448 
5449    upload_surface_states(ice->state.surface_uploader, surf_state);
5450 #endif
5451 }
5452 
5453 static uint32_t
use_surface_state(struct iris_batch * batch,struct iris_surface_state * surf_state,enum isl_aux_usage aux_usage)5454 use_surface_state(struct iris_batch *batch,
5455                   struct iris_surface_state *surf_state,
5456                   enum isl_aux_usage aux_usage)
5457 {
5458    iris_use_pinned_bo(batch, iris_resource_bo(surf_state->ref.res), false,
5459                       IRIS_DOMAIN_NONE);
5460 
5461    return surf_state->ref.offset +
5462           surf_state_offset_for_aux(surf_state->aux_usages, aux_usage);
5463 }
5464 
5465 /**
5466  * Add a surface to the validation list, as well as the buffer containing
5467  * the corresponding SURFACE_STATE.
5468  *
5469  * Returns the binding table entry (offset to SURFACE_STATE).
5470  */
5471 static uint32_t
use_surface(struct iris_context * ice,struct iris_batch * batch,struct pipe_surface * p_surf,bool writeable,enum isl_aux_usage aux_usage,bool is_read_surface,enum iris_domain access)5472 use_surface(struct iris_context *ice,
5473             struct iris_batch *batch,
5474             struct pipe_surface *p_surf,
5475             bool writeable,
5476             enum isl_aux_usage aux_usage,
5477             bool is_read_surface,
5478             enum iris_domain access)
5479 {
5480    struct iris_surface *surf = (void *) p_surf;
5481    struct iris_resource *res = (void *) p_surf->texture;
5482 
5483    if (GFX_VER == 8 && is_read_surface && !surf->surface_state_read.ref.res) {
5484       upload_surface_states(ice->state.surface_uploader,
5485                             &surf->surface_state_read);
5486    }
5487 
5488    if (!surf->surface_state.ref.res) {
5489       upload_surface_states(ice->state.surface_uploader,
5490                             &surf->surface_state);
5491    }
5492 
5493    if (memcmp(&res->aux.clear_color, &surf->clear_color,
5494               sizeof(surf->clear_color)) != 0) {
5495       update_clear_value(ice, batch, res, &surf->surface_state, &surf->view);
5496       if (GFX_VER == 8) {
5497          update_clear_value(ice, batch, res, &surf->surface_state_read,
5498                             &surf->read_view);
5499       }
5500       surf->clear_color = res->aux.clear_color;
5501    }
5502 
5503    if (res->aux.clear_color_bo)
5504       iris_use_pinned_bo(batch, res->aux.clear_color_bo, false, access);
5505 
5506    if (res->aux.bo)
5507       iris_use_pinned_bo(batch, res->aux.bo, writeable, access);
5508 
5509    iris_use_pinned_bo(batch, res->bo, writeable, access);
5510 
5511    if (GFX_VER == 8 && is_read_surface) {
5512       return use_surface_state(batch, &surf->surface_state_read, aux_usage);
5513    } else {
5514       return use_surface_state(batch, &surf->surface_state, aux_usage);
5515    }
5516 }
5517 
5518 static uint32_t
use_sampler_view(struct iris_context * ice,struct iris_batch * batch,struct iris_sampler_view * isv)5519 use_sampler_view(struct iris_context *ice,
5520                  struct iris_batch *batch,
5521                  struct iris_sampler_view *isv)
5522 {
5523    enum isl_aux_usage aux_usage =
5524       iris_resource_texture_aux_usage(ice, isv->res, isv->view.format,
5525                                       isv->view.base_level, isv->view.levels);
5526 
5527    if (!isv->surface_state.ref.res)
5528       upload_surface_states(ice->state.surface_uploader, &isv->surface_state);
5529 
5530    if (memcmp(&isv->res->aux.clear_color, &isv->clear_color,
5531               sizeof(isv->clear_color)) != 0) {
5532       update_clear_value(ice, batch, isv->res, &isv->surface_state,
5533                          &isv->view);
5534       isv->clear_color = isv->res->aux.clear_color;
5535    }
5536 
5537    if (isv->res->aux.clear_color_bo) {
5538       iris_use_pinned_bo(batch, isv->res->aux.clear_color_bo,
5539                          false, IRIS_DOMAIN_SAMPLER_READ);
5540    }
5541 
5542    if (isv->res->aux.bo) {
5543       iris_use_pinned_bo(batch, isv->res->aux.bo,
5544                          false, IRIS_DOMAIN_SAMPLER_READ);
5545    }
5546 
5547    iris_use_pinned_bo(batch, isv->res->bo, false, IRIS_DOMAIN_SAMPLER_READ);
5548 
5549    return use_surface_state(batch, &isv->surface_state, aux_usage);
5550 }
5551 
5552 static uint32_t
use_ubo_ssbo(struct iris_batch * batch,struct iris_context * ice,struct pipe_shader_buffer * buf,struct iris_state_ref * surf_state,bool writable,enum iris_domain access)5553 use_ubo_ssbo(struct iris_batch *batch,
5554              struct iris_context *ice,
5555              struct pipe_shader_buffer *buf,
5556              struct iris_state_ref *surf_state,
5557              bool writable, enum iris_domain access)
5558 {
5559    if (!buf->buffer || !surf_state->res)
5560       return use_null_surface(batch, ice);
5561 
5562    iris_use_pinned_bo(batch, iris_resource_bo(buf->buffer), writable, access);
5563    iris_use_pinned_bo(batch, iris_resource_bo(surf_state->res), false,
5564                       IRIS_DOMAIN_NONE);
5565 
5566    return surf_state->offset;
5567 }
5568 
5569 static uint32_t
use_image(struct iris_batch * batch,struct iris_context * ice,struct iris_shader_state * shs,const struct shader_info * info,int i)5570 use_image(struct iris_batch *batch, struct iris_context *ice,
5571           struct iris_shader_state *shs, const struct shader_info *info,
5572           int i)
5573 {
5574    struct iris_image_view *iv = &shs->image[i];
5575    struct iris_resource *res = (void *) iv->base.resource;
5576 
5577    if (!res)
5578       return use_null_surface(batch, ice);
5579 
5580    bool write = iv->base.shader_access & PIPE_IMAGE_ACCESS_WRITE;
5581 
5582    iris_use_pinned_bo(batch, res->bo, write, IRIS_DOMAIN_NONE);
5583 
5584    if (res->aux.bo)
5585       iris_use_pinned_bo(batch, res->aux.bo, write, IRIS_DOMAIN_NONE);
5586 
5587    if (res->aux.clear_color_bo) {
5588       iris_use_pinned_bo(batch, res->aux.clear_color_bo, false,
5589                          IRIS_DOMAIN_NONE);
5590    }
5591 
5592    enum isl_aux_usage aux_usage = shs->image_aux_usage[i];
5593 
5594    return use_surface_state(batch, &iv->surface_state, aux_usage);
5595 }
5596 
5597 #define push_bt_entry(addr) \
5598    assert(addr >= surf_base_offset); \
5599    assert(s < shader->bt.size_bytes / sizeof(uint32_t)); \
5600    if (!pin_only) bt_map[s++] = (addr) - surf_base_offset;
5601 
5602 #define bt_assert(section) \
5603    if (!pin_only && shader->bt.used_mask[section] != 0) \
5604       assert(shader->bt.offsets[section] == s);
5605 
5606 /**
5607  * Populate the binding table for a given shader stage.
5608  *
5609  * This fills out the table of pointers to surfaces required by the shader,
5610  * and also adds those buffers to the validation list so the kernel can make
5611  * resident before running our batch.
5612  */
5613 static void
iris_populate_binding_table(struct iris_context * ice,struct iris_batch * batch,gl_shader_stage stage,bool pin_only)5614 iris_populate_binding_table(struct iris_context *ice,
5615                             struct iris_batch *batch,
5616                             gl_shader_stage stage,
5617                             bool pin_only)
5618 {
5619    const struct iris_binder *binder = &ice->state.binder;
5620    struct iris_compiled_shader *shader = ice->shaders.prog[stage];
5621    if (!shader)
5622       return;
5623 
5624    struct iris_binding_table *bt = &shader->bt;
5625    struct iris_shader_state *shs = &ice->state.shaders[stage];
5626    uint32_t surf_base_offset = GFX_VER < 11 ? binder->bo->address : 0;
5627 
5628    uint32_t *bt_map = binder->map + binder->bt_offset[stage];
5629    int s = 0;
5630 
5631    const struct shader_info *info = iris_get_shader_info(ice, stage);
5632    if (!info) {
5633       /* TCS passthrough doesn't need a binding table. */
5634       assert(stage == MESA_SHADER_TESS_CTRL);
5635       return;
5636    }
5637 
5638    if (stage == MESA_SHADER_COMPUTE &&
5639        shader->bt.used_mask[IRIS_SURFACE_GROUP_CS_WORK_GROUPS]) {
5640       /* surface for gl_NumWorkGroups */
5641       struct iris_state_ref *grid_data = &ice->state.grid_size;
5642       struct iris_state_ref *grid_state = &ice->state.grid_surf_state;
5643       iris_use_pinned_bo(batch, iris_resource_bo(grid_data->res), false,
5644                          IRIS_DOMAIN_PULL_CONSTANT_READ);
5645       iris_use_pinned_bo(batch, iris_resource_bo(grid_state->res), false,
5646                          IRIS_DOMAIN_NONE);
5647       push_bt_entry(grid_state->offset);
5648    }
5649 
5650    if (stage == MESA_SHADER_FRAGMENT) {
5651       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
5652       /* Note that cso_fb->nr_cbufs == fs_key->nr_color_regions. */
5653       if (cso_fb->nr_cbufs) {
5654          for (unsigned i = 0; i < cso_fb->nr_cbufs; i++) {
5655             uint32_t addr;
5656             if (cso_fb->cbufs[i]) {
5657                addr = use_surface(ice, batch, cso_fb->cbufs[i], true,
5658                                   ice->state.draw_aux_usage[i], false,
5659                                   IRIS_DOMAIN_RENDER_WRITE);
5660             } else {
5661                addr = use_null_fb_surface(batch, ice);
5662             }
5663             push_bt_entry(addr);
5664          }
5665       } else if (GFX_VER < 11) {
5666          uint32_t addr = use_null_fb_surface(batch, ice);
5667          push_bt_entry(addr);
5668       }
5669    }
5670 
5671 #define foreach_surface_used(index, group) \
5672    bt_assert(group); \
5673    for (int index = 0; index < bt->sizes[group]; index++) \
5674       if (iris_group_index_to_bti(bt, group, index) != \
5675           IRIS_SURFACE_NOT_USED)
5676 
5677    foreach_surface_used(i, IRIS_SURFACE_GROUP_RENDER_TARGET_READ) {
5678       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
5679       uint32_t addr;
5680       if (cso_fb->cbufs[i]) {
5681          addr = use_surface(ice, batch, cso_fb->cbufs[i],
5682                             false, ice->state.draw_aux_usage[i], true,
5683                             IRIS_DOMAIN_SAMPLER_READ);
5684          push_bt_entry(addr);
5685       }
5686    }
5687 
5688    foreach_surface_used(i, IRIS_SURFACE_GROUP_TEXTURE_LOW64) {
5689       struct iris_sampler_view *view = shs->textures[i];
5690       uint32_t addr = view ? use_sampler_view(ice, batch, view)
5691                            : use_null_surface(batch, ice);
5692       push_bt_entry(addr);
5693    }
5694 
5695    foreach_surface_used(i, IRIS_SURFACE_GROUP_TEXTURE_HIGH64) {
5696       struct iris_sampler_view *view = shs->textures[64 + i];
5697       uint32_t addr = view ? use_sampler_view(ice, batch, view)
5698                            : use_null_surface(batch, ice);
5699       push_bt_entry(addr);
5700    }
5701 
5702    foreach_surface_used(i, IRIS_SURFACE_GROUP_IMAGE) {
5703       uint32_t addr = use_image(batch, ice, shs, info, i);
5704       push_bt_entry(addr);
5705    }
5706 
5707    foreach_surface_used(i, IRIS_SURFACE_GROUP_UBO) {
5708       uint32_t addr = use_ubo_ssbo(batch, ice, &shs->constbuf[i],
5709                                    &shs->constbuf_surf_state[i], false,
5710                                    IRIS_DOMAIN_PULL_CONSTANT_READ);
5711       push_bt_entry(addr);
5712    }
5713 
5714    foreach_surface_used(i, IRIS_SURFACE_GROUP_SSBO) {
5715       uint32_t addr =
5716          use_ubo_ssbo(batch, ice, &shs->ssbo[i], &shs->ssbo_surf_state[i],
5717                       shs->writable_ssbos & (1u << i), IRIS_DOMAIN_NONE);
5718       push_bt_entry(addr);
5719    }
5720 
5721 #if 0
5722       /* XXX: YUV surfaces not implemented yet */
5723       bt_assert(plane_start[1], ...);
5724       bt_assert(plane_start[2], ...);
5725 #endif
5726 }
5727 
5728 static void
iris_use_optional_res(struct iris_batch * batch,struct pipe_resource * res,bool writeable,enum iris_domain access)5729 iris_use_optional_res(struct iris_batch *batch,
5730                       struct pipe_resource *res,
5731                       bool writeable,
5732                       enum iris_domain access)
5733 {
5734    if (res) {
5735       struct iris_bo *bo = iris_resource_bo(res);
5736       iris_use_pinned_bo(batch, bo, writeable, access);
5737    }
5738 }
5739 
5740 static void
pin_depth_and_stencil_buffers(struct iris_batch * batch,struct pipe_surface * zsbuf,struct iris_depth_stencil_alpha_state * cso_zsa)5741 pin_depth_and_stencil_buffers(struct iris_batch *batch,
5742                               struct pipe_surface *zsbuf,
5743                               struct iris_depth_stencil_alpha_state *cso_zsa)
5744 {
5745    if (!zsbuf)
5746       return;
5747 
5748    struct iris_resource *zres, *sres;
5749    iris_get_depth_stencil_resources(zsbuf->texture, &zres, &sres);
5750 
5751    if (zres) {
5752       iris_use_pinned_bo(batch, zres->bo, cso_zsa->depth_writes_enabled,
5753                          IRIS_DOMAIN_DEPTH_WRITE);
5754       if (zres->aux.bo) {
5755          iris_use_pinned_bo(batch, zres->aux.bo,
5756                             cso_zsa->depth_writes_enabled,
5757                             IRIS_DOMAIN_DEPTH_WRITE);
5758       }
5759    }
5760 
5761    if (sres) {
5762       iris_use_pinned_bo(batch, sres->bo, cso_zsa->stencil_writes_enabled,
5763                          IRIS_DOMAIN_DEPTH_WRITE);
5764    }
5765 }
5766 
5767 static uint32_t
pin_scratch_space(struct iris_context * ice,struct iris_batch * batch,const struct iris_compiled_shader * shader,gl_shader_stage stage)5768 pin_scratch_space(struct iris_context *ice,
5769                   struct iris_batch *batch,
5770                   const struct iris_compiled_shader *shader,
5771                   gl_shader_stage stage)
5772 {
5773    uint32_t scratch_addr = 0;
5774 
5775    if (shader->total_scratch > 0) {
5776       struct iris_bo *scratch_bo =
5777          iris_get_scratch_space(ice, shader->total_scratch, stage);
5778       iris_use_pinned_bo(batch, scratch_bo, true, IRIS_DOMAIN_NONE);
5779 
5780 #if GFX_VERx10 >= 125
5781       const struct iris_state_ref *ref =
5782          iris_get_scratch_surf(ice, shader->total_scratch);
5783       iris_use_pinned_bo(batch, iris_resource_bo(ref->res),
5784                          false, IRIS_DOMAIN_NONE);
5785       scratch_addr = ref->offset +
5786                      iris_resource_bo(ref->res)->address -
5787                      IRIS_MEMZONE_SCRATCH_START;
5788       assert((scratch_addr & 0x3f) == 0 && scratch_addr < (1 << 26));
5789 #else
5790       scratch_addr = scratch_bo->address;
5791 #endif
5792    }
5793 
5794    return scratch_addr;
5795 }
5796 
5797 /* ------------------------------------------------------------------- */
5798 
5799 /**
5800  * Pin any BOs which were installed by a previous batch, and restored
5801  * via the hardware logical context mechanism.
5802  *
5803  * We don't need to re-emit all state every batch - the hardware context
5804  * mechanism will save and restore it for us.  This includes pointers to
5805  * various BOs...which won't exist unless we ask the kernel to pin them
5806  * by adding them to the validation list.
5807  *
5808  * We can skip buffers if we've re-emitted those packets, as we're
5809  * overwriting those stale pointers with new ones, and don't actually
5810  * refer to the old BOs.
5811  */
5812 static void
iris_restore_render_saved_bos(struct iris_context * ice,struct iris_batch * batch,const struct pipe_draw_info * draw)5813 iris_restore_render_saved_bos(struct iris_context *ice,
5814                               struct iris_batch *batch,
5815                               const struct pipe_draw_info *draw)
5816 {
5817    struct iris_genx_state *genx = ice->state.genx;
5818 
5819    const uint64_t clean = ~ice->state.dirty;
5820    const uint64_t stage_clean = ~ice->state.stage_dirty;
5821 
5822    if (clean & IRIS_DIRTY_CC_VIEWPORT) {
5823       iris_use_optional_res(batch, ice->state.last_res.cc_vp, false,
5824                             IRIS_DOMAIN_NONE);
5825    }
5826 
5827    if (clean & IRIS_DIRTY_SF_CL_VIEWPORT) {
5828       iris_use_optional_res(batch, ice->state.last_res.sf_cl_vp, false,
5829                             IRIS_DOMAIN_NONE);
5830    }
5831 
5832    if (clean & IRIS_DIRTY_BLEND_STATE) {
5833       iris_use_optional_res(batch, ice->state.last_res.blend, false,
5834                             IRIS_DOMAIN_NONE);
5835    }
5836 
5837    if (clean & IRIS_DIRTY_COLOR_CALC_STATE) {
5838       iris_use_optional_res(batch, ice->state.last_res.color_calc, false,
5839                             IRIS_DOMAIN_NONE);
5840    }
5841 
5842    if (clean & IRIS_DIRTY_SCISSOR_RECT) {
5843       iris_use_optional_res(batch, ice->state.last_res.scissor, false,
5844                             IRIS_DOMAIN_NONE);
5845    }
5846 
5847    if (ice->state.streamout_active && (clean & IRIS_DIRTY_SO_BUFFERS)) {
5848       for (int i = 0; i < 4; i++) {
5849          struct iris_stream_output_target *tgt =
5850             (void *) ice->state.so_target[i];
5851          if (tgt) {
5852             iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
5853                                true, IRIS_DOMAIN_OTHER_WRITE);
5854             iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
5855                                true, IRIS_DOMAIN_OTHER_WRITE);
5856          }
5857       }
5858    }
5859 
5860    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
5861       if (!(stage_clean & (IRIS_STAGE_DIRTY_CONSTANTS_VS << stage)))
5862          continue;
5863 
5864       struct iris_shader_state *shs = &ice->state.shaders[stage];
5865       struct iris_compiled_shader *shader = ice->shaders.prog[stage];
5866 
5867       if (!shader)
5868          continue;
5869 
5870       for (int i = 0; i < 4; i++) {
5871          const struct iris_ubo_range *range = &shader->ubo_ranges[i];
5872 
5873          if (range->length == 0)
5874             continue;
5875 
5876          /* Range block is a binding table index, map back to UBO index. */
5877          unsigned block_index = iris_bti_to_group_index(
5878             &shader->bt, IRIS_SURFACE_GROUP_UBO, range->block);
5879          assert(block_index != IRIS_SURFACE_NOT_USED);
5880 
5881          struct pipe_shader_buffer *cbuf = &shs->constbuf[block_index];
5882          struct iris_resource *res = (void *) cbuf->buffer;
5883 
5884          if (res)
5885             iris_use_pinned_bo(batch, res->bo, false, IRIS_DOMAIN_OTHER_READ);
5886          else
5887             iris_use_pinned_bo(batch, batch->screen->workaround_bo, false,
5888                                IRIS_DOMAIN_OTHER_READ);
5889       }
5890    }
5891 
5892    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
5893       if (stage_clean & (IRIS_STAGE_DIRTY_BINDINGS_VS << stage)) {
5894          /* Re-pin any buffers referred to by the binding table. */
5895          iris_populate_binding_table(ice, batch, stage, true);
5896       }
5897    }
5898 
5899    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
5900       struct iris_shader_state *shs = &ice->state.shaders[stage];
5901       struct pipe_resource *res = shs->sampler_table.res;
5902       if (res)
5903          iris_use_pinned_bo(batch, iris_resource_bo(res), false,
5904                             IRIS_DOMAIN_NONE);
5905    }
5906 
5907    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
5908       if (stage_clean & (IRIS_STAGE_DIRTY_VS << stage)) {
5909          struct iris_compiled_shader *shader = ice->shaders.prog[stage];
5910 
5911          if (shader) {
5912             struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
5913             iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_NONE);
5914 
5915             pin_scratch_space(ice, batch, shader, stage);
5916          }
5917       }
5918    }
5919 
5920    if ((clean & IRIS_DIRTY_DEPTH_BUFFER) &&
5921        (clean & IRIS_DIRTY_WM_DEPTH_STENCIL)) {
5922       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
5923       pin_depth_and_stencil_buffers(batch, cso_fb->zsbuf, ice->state.cso_zsa);
5924    }
5925 
5926    iris_use_optional_res(batch, ice->state.last_res.index_buffer, false,
5927                          IRIS_DOMAIN_VF_READ);
5928 
5929    if (clean & IRIS_DIRTY_VERTEX_BUFFERS) {
5930       uint64_t bound = ice->state.bound_vertex_buffers;
5931       while (bound) {
5932          const int i = u_bit_scan64(&bound);
5933          struct pipe_resource *res = genx->vertex_buffers[i].resource;
5934          iris_use_pinned_bo(batch, iris_resource_bo(res), false,
5935                             IRIS_DOMAIN_VF_READ);
5936       }
5937    }
5938 
5939 #if GFX_VERx10 == 125
5940    iris_use_pinned_bo(batch, iris_resource_bo(ice->state.pixel_hashing_tables),
5941                       false, IRIS_DOMAIN_NONE);
5942 #else
5943    assert(!ice->state.pixel_hashing_tables);
5944 #endif
5945 }
5946 
5947 static void
iris_restore_compute_saved_bos(struct iris_context * ice,struct iris_batch * batch,const struct pipe_grid_info * grid)5948 iris_restore_compute_saved_bos(struct iris_context *ice,
5949                                struct iris_batch *batch,
5950                                const struct pipe_grid_info *grid)
5951 {
5952    const uint64_t stage_clean = ~ice->state.stage_dirty;
5953 
5954    const int stage = MESA_SHADER_COMPUTE;
5955    struct iris_shader_state *shs = &ice->state.shaders[stage];
5956 
5957    if (stage_clean & IRIS_STAGE_DIRTY_BINDINGS_CS) {
5958       /* Re-pin any buffers referred to by the binding table. */
5959       iris_populate_binding_table(ice, batch, stage, true);
5960    }
5961 
5962    struct pipe_resource *sampler_res = shs->sampler_table.res;
5963    if (sampler_res)
5964       iris_use_pinned_bo(batch, iris_resource_bo(sampler_res), false,
5965                          IRIS_DOMAIN_NONE);
5966 
5967    if ((stage_clean & IRIS_STAGE_DIRTY_SAMPLER_STATES_CS) &&
5968        (stage_clean & IRIS_STAGE_DIRTY_BINDINGS_CS) &&
5969        (stage_clean & IRIS_STAGE_DIRTY_CONSTANTS_CS) &&
5970        (stage_clean & IRIS_STAGE_DIRTY_CS)) {
5971       iris_use_optional_res(batch, ice->state.last_res.cs_desc, false,
5972                             IRIS_DOMAIN_NONE);
5973    }
5974 
5975    if (stage_clean & IRIS_STAGE_DIRTY_CS) {
5976       struct iris_compiled_shader *shader = ice->shaders.prog[stage];
5977 
5978       if (shader) {
5979          struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
5980          iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_NONE);
5981 
5982          if (GFX_VERx10 < 125) {
5983             struct iris_bo *curbe_bo =
5984                iris_resource_bo(ice->state.last_res.cs_thread_ids);
5985             iris_use_pinned_bo(batch, curbe_bo, false, IRIS_DOMAIN_NONE);
5986          }
5987 
5988          pin_scratch_space(ice, batch, shader, stage);
5989       }
5990    }
5991 }
5992 
5993 /**
5994  * Possibly emit STATE_BASE_ADDRESS to update Surface State Base Address.
5995  */
5996 static void
iris_update_binder_address(struct iris_batch * batch,struct iris_binder * binder)5997 iris_update_binder_address(struct iris_batch *batch,
5998                            struct iris_binder *binder)
5999 {
6000    if (batch->last_binder_address == binder->bo->address)
6001       return;
6002 
6003    struct isl_device *isl_dev = &batch->screen->isl_dev;
6004    uint32_t mocs = isl_mocs(isl_dev, 0, false);
6005 
6006    iris_batch_sync_region_start(batch);
6007 
6008 #if GFX_VER >= 11
6009    /* Use 3DSTATE_BINDING_TABLE_POOL_ALLOC on Icelake and later */
6010 
6011 #if GFX_VERx10 == 120
6012    /* Wa_1607854226:
6013     *
6014     *  Workaround the non pipelined state not applying in MEDIA/GPGPU pipeline
6015     *  mode by putting the pipeline temporarily in 3D mode..
6016     */
6017    if (batch->name == IRIS_BATCH_COMPUTE)
6018       emit_pipeline_select(batch, _3D);
6019 #endif
6020 
6021    iris_emit_pipe_control_flush(batch, "Stall for binder realloc",
6022                                 PIPE_CONTROL_CS_STALL);
6023 
6024    iris_emit_cmd(batch, GENX(3DSTATE_BINDING_TABLE_POOL_ALLOC), btpa) {
6025       btpa.BindingTablePoolBaseAddress = ro_bo(binder->bo, 0);
6026       btpa.BindingTablePoolBufferSize = binder->size / 4096;
6027 #if GFX_VERx10 < 125
6028       btpa.BindingTablePoolEnable = true;
6029 #endif
6030       btpa.MOCS = mocs;
6031    }
6032 
6033 #if GFX_VERx10 == 120
6034    /* Wa_1607854226:
6035     *
6036     *  Put the pipeline back into compute mode.
6037     */
6038    if (batch->name == IRIS_BATCH_COMPUTE)
6039       emit_pipeline_select(batch, GPGPU);
6040 #endif
6041 #else
6042    /* Use STATE_BASE_ADDRESS on older platforms */
6043    flush_before_state_base_change(batch);
6044 
6045    iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
6046       sba.SurfaceStateBaseAddressModifyEnable = true;
6047       sba.SurfaceStateBaseAddress = ro_bo(binder->bo, 0);
6048 
6049       /* The hardware appears to pay attention to the MOCS fields even
6050        * if you don't set the "Address Modify Enable" bit for the base.
6051        */
6052       sba.GeneralStateMOCS            = mocs;
6053       sba.StatelessDataPortAccessMOCS = mocs;
6054       sba.DynamicStateMOCS            = mocs;
6055       sba.IndirectObjectMOCS          = mocs;
6056       sba.InstructionMOCS             = mocs;
6057       sba.SurfaceStateMOCS            = mocs;
6058 #if GFX_VER >= 9
6059       sba.BindlessSurfaceStateMOCS    = mocs;
6060 #endif
6061 #if GFX_VERx10 >= 125
6062       sba.L1CacheControl = L1CC_WB;
6063 #endif
6064    }
6065 #endif
6066 
6067    flush_after_state_base_change(batch);
6068    iris_batch_sync_region_end(batch);
6069 
6070    batch->last_binder_address = binder->bo->address;
6071 }
6072 
6073 static inline void
iris_viewport_zmin_zmax(const struct pipe_viewport_state * vp,bool halfz,bool window_space_position,float * zmin,float * zmax)6074 iris_viewport_zmin_zmax(const struct pipe_viewport_state *vp, bool halfz,
6075                         bool window_space_position, float *zmin, float *zmax)
6076 {
6077    if (window_space_position) {
6078       *zmin = 0.f;
6079       *zmax = 1.f;
6080       return;
6081    }
6082    util_viewport_zmin_zmax(vp, halfz, zmin, zmax);
6083 }
6084 
6085 /* Wa_16018063123 */
6086 static inline void
batch_emit_fast_color_dummy_blit(struct iris_batch * batch)6087 batch_emit_fast_color_dummy_blit(struct iris_batch *batch)
6088 {
6089 #if GFX_VERx10 >= 125
6090    iris_emit_cmd(batch, GENX(XY_FAST_COLOR_BLT), blt) {
6091       blt.DestinationBaseAddress = batch->screen->workaround_address;
6092       blt.DestinationMOCS = batch->screen->isl_dev.mocs.blitter_dst;
6093       blt.DestinationPitch = 63;
6094       blt.DestinationX2 = 1;
6095       blt.DestinationY2 = 4;
6096       blt.DestinationSurfaceWidth = 1;
6097       blt.DestinationSurfaceHeight = 4;
6098       blt.DestinationSurfaceType = XY_SURFTYPE_2D;
6099       blt.DestinationSurfaceQPitch = 4;
6100       blt.DestinationTiling = XY_TILE_LINEAR;
6101    }
6102 #endif
6103 }
6104 
6105 #if GFX_VER >= 12
6106 static void
invalidate_aux_map_state_per_engine(struct iris_batch * batch)6107 invalidate_aux_map_state_per_engine(struct iris_batch *batch)
6108 {
6109    uint64_t register_addr = 0;
6110 
6111    switch (batch->name) {
6112    case IRIS_BATCH_RENDER: {
6113       /* HSD 1209978178: docs say that before programming the aux table:
6114        *
6115        *    "Driver must ensure that the engine is IDLE but ensure it doesn't
6116        *    add extra flushes in the case it knows that the engine is already
6117        *    IDLE."
6118        *
6119        * An end of pipe sync is needed here, otherwise we see GPU hangs in
6120        * dEQP-GLES31.functional.copy_image.* tests.
6121        *
6122        * HSD 22012751911: SW Programming sequence when issuing aux invalidation:
6123        *
6124        *    "Render target Cache Flush + L3 Fabric Flush + State Invalidation + CS Stall"
6125        *
6126        * Notice we don't set the L3 Fabric Flush here, because we have
6127        * PIPE_CONTROL_CS_STALL. The PIPE_CONTROL::L3 Fabric Flush
6128        * documentation says :
6129        *
6130        *    "L3 Fabric Flush will ensure all the pending transactions in the
6131        *     L3 Fabric are flushed to global observation point. HW does
6132        *     implicit L3 Fabric Flush on all stalling flushes (both explicit
6133        *     and implicit) and on PIPECONTROL having Post Sync Operation
6134        *     enabled."
6135        *
6136        * Therefore setting L3 Fabric Flush here would be redundant.
6137        *
6138        * From Bspec 43904 (Register_CCSAuxiliaryTableInvalidate):
6139        * RCS engine idle sequence:
6140        *
6141        *    Gfx125+:
6142        *       PIPE_CONTROL:- DC Flush + L3 Fabric Flush + CS Stall + Render
6143        *                      Target Cache Flush + Depth Cache + CCS flush
6144        *
6145        */
6146       iris_emit_end_of_pipe_sync(batch, "Invalidate aux map table",
6147                                  PIPE_CONTROL_CS_STALL |
6148                                  PIPE_CONTROL_RENDER_TARGET_FLUSH |
6149                                  PIPE_CONTROL_STATE_CACHE_INVALIDATE |
6150                                  (GFX_VERx10 == 125 ?
6151                                   PIPE_CONTROL_CCS_CACHE_FLUSH : 0));
6152 
6153       register_addr = GENX(GFX_CCS_AUX_INV_num);
6154       break;
6155    }
6156    case IRIS_BATCH_COMPUTE: {
6157       /*
6158        * Notice we don't set the L3 Fabric Flush here, because we have
6159        * PIPE_CONTROL_CS_STALL. The PIPE_CONTROL::L3 Fabric Flush
6160        * documentation says :
6161        *
6162        *    "L3 Fabric Flush will ensure all the pending transactions in the
6163        *     L3 Fabric are flushed to global observation point. HW does
6164        *     implicit L3 Fabric Flush on all stalling flushes (both explicit
6165        *     and implicit) and on PIPECONTROL having Post Sync Operation
6166        *     enabled."
6167        *
6168        * Therefore setting L3 Fabric Flush here would be redundant.
6169        *
6170        * From Bspec 43904 (Register_CCSAuxiliaryTableInvalidate):
6171        * Compute engine idle sequence:
6172        *
6173        *    Gfx125+:
6174        *       PIPE_CONTROL:- DC Flush + L3 Fabric Flush + CS Stall + CCS flush
6175        */
6176       iris_emit_end_of_pipe_sync(batch, "Invalidate aux map table",
6177                                  PIPE_CONTROL_DATA_CACHE_FLUSH |
6178                                  PIPE_CONTROL_CS_STALL |
6179                                  (GFX_VERx10 == 125 ?
6180                                   PIPE_CONTROL_CCS_CACHE_FLUSH : 0));
6181 
6182       register_addr = GENX(COMPCS0_CCS_AUX_INV_num);
6183       break;
6184    }
6185    case IRIS_BATCH_BLITTER: {
6186 #if GFX_VERx10 >= 125
6187       /* Wa_16018063123 - emit fast color dummy blit before MI_FLUSH_DW. */
6188       if (intel_needs_workaround(batch->screen->devinfo, 16018063123))
6189          batch_emit_fast_color_dummy_blit(batch);
6190 
6191       /*
6192        * Notice we don't set the L3 Fabric Flush here, because we have
6193        * PIPE_CONTROL_CS_STALL. The PIPE_CONTROL::L3 Fabric Flush
6194        * documentation says :
6195        *
6196        *    "L3 Fabric Flush will ensure all the pending transactions in the
6197        *     L3 Fabric are flushed to global observation point. HW does
6198        *     implicit L3 Fabric Flush on all stalling flushes (both explicit
6199        *     and implicit) and on PIPECONTROL having Post Sync Operation
6200        *     enabled."
6201        *
6202        * Therefore setting L3 Fabric Flush here would be redundant.
6203        *
6204        * From Bspec 43904 (Register_CCSAuxiliaryTableInvalidate):
6205        * Blitter engine idle sequence:
6206        *
6207        *    Gfx125+:
6208        *       MI_FLUSH_DW (dw0;b16 – flush CCS)
6209        */
6210       iris_emit_cmd(batch, GENX(MI_FLUSH_DW), fd) {
6211          fd.FlushCCS = true;
6212       }
6213       register_addr = GENX(BCS_CCS_AUX_INV_num);
6214 #endif
6215       break;
6216    }
6217    default:
6218       unreachable("Invalid batch for aux map invalidation");
6219       break;
6220    }
6221 
6222    if (register_addr != 0) {
6223       /* If the aux-map state number increased, then we need to rewrite the
6224        * register. Rewriting the register is used to both set the aux-map
6225        * translation table address, and also to invalidate any previously
6226        * cached translations.
6227        */
6228       iris_load_register_imm32(batch, register_addr, 1);
6229 
6230       /* HSD 22012751911: SW Programming sequence when issuing aux invalidation:
6231        *
6232        *    "Poll Aux Invalidation bit once the invalidation is set (Register
6233        *     4208 bit 0)"
6234        */
6235       iris_emit_cmd(batch, GENX(MI_SEMAPHORE_WAIT), sem) {
6236          sem.CompareOperation = COMPARE_SAD_EQUAL_SDD;
6237          sem.WaitMode = PollingMode;
6238          sem.RegisterPollMode = true;
6239          sem.SemaphoreDataDword = 0x0;
6240          sem.SemaphoreAddress = ro_bo(NULL, register_addr);
6241       }
6242    }
6243 }
6244 
6245 void
genX(invalidate_aux_map_state)6246 genX(invalidate_aux_map_state)(struct iris_batch *batch)
6247 {
6248    struct iris_screen *screen = batch->screen;
6249    void *aux_map_ctx = iris_bufmgr_get_aux_map_context(screen->bufmgr);
6250    if (!aux_map_ctx)
6251       return;
6252    uint32_t aux_map_state_num = intel_aux_map_get_state_num(aux_map_ctx);
6253    if (batch->last_aux_map_state != aux_map_state_num) {
6254       invalidate_aux_map_state_per_engine(batch);
6255       batch->last_aux_map_state = aux_map_state_num;
6256    }
6257 }
6258 
6259 static void
init_aux_map_state(struct iris_batch * batch)6260 init_aux_map_state(struct iris_batch *batch)
6261 {
6262    struct iris_screen *screen = batch->screen;
6263    void *aux_map_ctx = iris_bufmgr_get_aux_map_context(screen->bufmgr);
6264    if (!aux_map_ctx)
6265       return;
6266 
6267    uint64_t base_addr = intel_aux_map_get_base(aux_map_ctx);
6268    assert(base_addr != 0 && align64(base_addr, 32 * 1024) == base_addr);
6269 
6270    uint32_t reg = 0;
6271    switch (batch->name) {
6272    case IRIS_BATCH_COMPUTE:
6273       if (iris_bufmgr_compute_engine_supported(screen->bufmgr)) {
6274          reg = GENX(COMPCS0_AUX_TABLE_BASE_ADDR_num);
6275          break;
6276       }
6277       /* fallthrough */
6278       FALLTHROUGH;
6279    case IRIS_BATCH_RENDER:
6280       reg = GENX(GFX_AUX_TABLE_BASE_ADDR_num);
6281       break;
6282    case IRIS_BATCH_BLITTER:
6283 #if GFX_VERx10 >= 125
6284       reg = GENX(BCS_AUX_TABLE_BASE_ADDR_num);
6285 #endif
6286       break;
6287    default:
6288       unreachable("Invalid batch for aux map init.");
6289    }
6290 
6291    if (reg)
6292       iris_load_register_imm64(batch, reg, base_addr);
6293 }
6294 #endif
6295 
6296 struct push_bos {
6297    struct {
6298       struct iris_address addr;
6299       uint32_t length;
6300    } buffers[4];
6301    int buffer_count;
6302    uint32_t max_length;
6303 };
6304 
6305 static void
setup_constant_buffers(struct iris_context * ice,struct iris_batch * batch,int stage,struct push_bos * push_bos)6306 setup_constant_buffers(struct iris_context *ice,
6307                        struct iris_batch *batch,
6308                        int stage,
6309                        struct push_bos *push_bos)
6310 {
6311    struct iris_shader_state *shs = &ice->state.shaders[stage];
6312    struct iris_compiled_shader *shader = ice->shaders.prog[stage];
6313 
6314    uint32_t push_range_sum = 0;
6315 
6316    int n = 0;
6317    for (int i = 0; i < 4; i++) {
6318       const struct iris_ubo_range *range = &shader->ubo_ranges[i];
6319 
6320       if (range->length == 0)
6321          continue;
6322 
6323       push_range_sum += range->length;
6324 
6325       if (range->length > push_bos->max_length)
6326          push_bos->max_length = range->length;
6327 
6328       /* Range block is a binding table index, map back to UBO index. */
6329       unsigned block_index = iris_bti_to_group_index(
6330          &shader->bt, IRIS_SURFACE_GROUP_UBO, range->block);
6331       assert(block_index != IRIS_SURFACE_NOT_USED);
6332 
6333       struct pipe_shader_buffer *cbuf = &shs->constbuf[block_index];
6334       struct iris_resource *res = (void *) cbuf->buffer;
6335 
6336       assert(cbuf->buffer_offset % 32 == 0);
6337 
6338       if (res)
6339          iris_emit_buffer_barrier_for(batch, res->bo, IRIS_DOMAIN_OTHER_READ);
6340 
6341       push_bos->buffers[n].length = range->length;
6342       push_bos->buffers[n].addr =
6343          res ? ro_bo(res->bo, range->start * 32 + cbuf->buffer_offset)
6344          : batch->screen->workaround_address;
6345       n++;
6346    }
6347 
6348    /* From the 3DSTATE_CONSTANT_XS and 3DSTATE_CONSTANT_ALL programming notes:
6349     *
6350     *    "The sum of all four read length fields must be less than or
6351     *    equal to the size of 64."
6352     */
6353    assert(push_range_sum <= 64);
6354 
6355    push_bos->buffer_count = n;
6356 }
6357 
6358 static void
emit_push_constant_packets(struct iris_context * ice,struct iris_batch * batch,int stage,const struct push_bos * push_bos)6359 emit_push_constant_packets(struct iris_context *ice,
6360                            struct iris_batch *batch,
6361                            int stage,
6362                            const struct push_bos *push_bos)
6363 {
6364    UNUSED struct isl_device *isl_dev = &batch->screen->isl_dev;
6365 
6366    iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_VS), pkt) {
6367       pkt._3DCommandSubOpcode = push_constant_opcodes[stage];
6368 
6369 #if GFX_VER >= 9
6370       pkt.MOCS = isl_mocs(isl_dev, 0, false);
6371 #endif
6372 
6373       /* The Skylake PRM contains the following restriction:
6374        *
6375        *    "The driver must ensure The following case does not occur
6376        *     without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
6377        *     buffer 3 read length equal to zero committed followed by a
6378        *     3DSTATE_CONSTANT_* with buffer 0 read length not equal to
6379        *     zero committed."
6380        *
6381        * To avoid this, we program the buffers in the highest slots.
6382        * This way, slot 0 is only used if slot 3 is also used.
6383        */
6384       const int n = push_bos->buffer_count;
6385       assert(n <= 4);
6386       const unsigned shift = 4 - n;
6387       for (int i = 0; i < n; i++) {
6388          pkt.ConstantBody.ReadLength[i + shift] =
6389             push_bos->buffers[i].length;
6390          pkt.ConstantBody.Buffer[i + shift] = push_bos->buffers[i].addr;
6391       }
6392    }
6393 }
6394 
6395 #if GFX_VER >= 12
6396 static void
emit_push_constant_packet_all(struct iris_context * ice,struct iris_batch * batch,uint32_t shader_mask,const struct push_bos * push_bos)6397 emit_push_constant_packet_all(struct iris_context *ice,
6398                               struct iris_batch *batch,
6399                               uint32_t shader_mask,
6400                               const struct push_bos *push_bos)
6401 {
6402    struct isl_device *isl_dev = &batch->screen->isl_dev;
6403 
6404    if (!push_bos) {
6405       iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_ALL), pc) {
6406          pc.ShaderUpdateEnable = shader_mask;
6407          pc.MOCS = iris_mocs(NULL, isl_dev, 0);
6408       }
6409       return;
6410    }
6411 
6412    const uint32_t n = push_bos->buffer_count;
6413    const uint32_t max_pointers = 4;
6414    const uint32_t num_dwords = 2 + 2 * n;
6415    uint32_t const_all[2 + 2 * max_pointers];
6416    uint32_t *dw = &const_all[0];
6417 
6418    assert(n <= max_pointers);
6419    iris_pack_command(GENX(3DSTATE_CONSTANT_ALL), dw, all) {
6420       all.DWordLength = num_dwords - 2;
6421       all.MOCS = isl_mocs(isl_dev, 0, false);
6422       all.ShaderUpdateEnable = shader_mask;
6423       all.PointerBufferMask = (1 << n) - 1;
6424    }
6425    dw += 2;
6426 
6427    for (int i = 0; i < n; i++) {
6428       _iris_pack_state(batch, GENX(3DSTATE_CONSTANT_ALL_DATA),
6429                        dw + i * 2, data) {
6430          data.PointerToConstantBuffer = push_bos->buffers[i].addr;
6431          data.ConstantBufferReadLength = push_bos->buffers[i].length;
6432       }
6433    }
6434    iris_batch_emit(batch, const_all, sizeof(uint32_t) * num_dwords);
6435 }
6436 #endif
6437 
6438 void
genX(emit_depth_state_workarounds)6439 genX(emit_depth_state_workarounds)(struct iris_context *ice,
6440                                    struct iris_batch *batch,
6441                                    const struct isl_surf *surf)
6442 {
6443 #if INTEL_NEEDS_WA_1808121037
6444    const bool is_d16_1x_msaa = surf->format == ISL_FORMAT_R16_UNORM &&
6445                                surf->samples == 1;
6446 
6447    switch (ice->state.genx->depth_reg_mode) {
6448    case IRIS_DEPTH_REG_MODE_HW_DEFAULT:
6449       if (!is_d16_1x_msaa)
6450          return;
6451       break;
6452    case IRIS_DEPTH_REG_MODE_D16_1X_MSAA:
6453       if (is_d16_1x_msaa)
6454          return;
6455       break;
6456    case IRIS_DEPTH_REG_MODE_UNKNOWN:
6457       break;
6458    }
6459 
6460    /* We'll change some CHICKEN registers depending on the depth surface
6461     * format. Do a depth flush and stall so the pipeline is not using these
6462     * settings while we change the registers.
6463     */
6464    iris_emit_end_of_pipe_sync(batch,
6465                               "Workaround: Stop pipeline for Wa_1808121037",
6466                               PIPE_CONTROL_DEPTH_STALL |
6467                               PIPE_CONTROL_DEPTH_CACHE_FLUSH);
6468 
6469    /* Wa_1808121037
6470     *
6471     * To avoid sporadic corruptions “Set 0x7010[9] when Depth Buffer
6472     * Surface Format is D16_UNORM , surface type is not NULL & 1X_MSAA”.
6473     */
6474    iris_emit_reg(batch, GENX(COMMON_SLICE_CHICKEN1), reg) {
6475       reg.HIZPlaneOptimizationdisablebit = is_d16_1x_msaa;
6476       reg.HIZPlaneOptimizationdisablebitMask = true;
6477    }
6478 
6479    ice->state.genx->depth_reg_mode =
6480       is_d16_1x_msaa ? IRIS_DEPTH_REG_MODE_D16_1X_MSAA :
6481                        IRIS_DEPTH_REG_MODE_HW_DEFAULT;
6482 #endif
6483 }
6484 
6485 /* Calculate TBIMR tiling parameters adequate for the current pipeline
6486  * setup.  Return true if TBIMR should be enabled.
6487  */
6488 UNUSED static bool
calculate_tile_dimensions(struct iris_context * ice,unsigned * tile_width,unsigned * tile_height)6489 calculate_tile_dimensions(struct iris_context *ice,
6490                           unsigned *tile_width, unsigned *tile_height)
6491 {
6492    struct iris_screen *screen = (void *)ice->ctx.screen;
6493    const struct intel_device_info *devinfo = screen->devinfo;
6494 
6495    /* Perform a rough calculation of the tile cache footprint of the
6496     * pixel pipeline, approximating it as the sum of the amount of
6497     * memory used per pixel by every render target, depth, stencil and
6498     * auxiliary surfaces bound to the pipeline.
6499     */
6500    unsigned pixel_size = 0;
6501 
6502    struct pipe_framebuffer_state *cso = &ice->state.framebuffer;
6503 
6504    if (cso->width == 0 || cso->height == 0)
6505       return false;
6506 
6507    for (unsigned i = 0; i < cso->nr_cbufs; i++) {
6508       const struct iris_surface *surf = (void *)cso->cbufs[i];
6509 
6510       if (surf) {
6511          const struct iris_resource *res = (void *)surf->base.texture;
6512 
6513          pixel_size += intel_calculate_surface_pixel_size(&res->surf);
6514 
6515          /* XXX - Pessimistic, in some cases it might be helpful to neglect
6516           *       aux surface traffic.
6517           */
6518          if (ice->state.draw_aux_usage[i]) {
6519             pixel_size += intel_calculate_surface_pixel_size(&res->aux.surf);
6520             pixel_size += intel_calculate_surface_pixel_size(&res->aux.extra_aux.surf);
6521          }
6522       }
6523    }
6524 
6525    if (cso->zsbuf) {
6526       struct iris_resource *zres;
6527       struct iris_resource *sres;
6528       iris_get_depth_stencil_resources(cso->zsbuf->texture, &zres, &sres);
6529 
6530       if (zres) {
6531          pixel_size += intel_calculate_surface_pixel_size(&zres->surf);
6532 
6533          /* XXX - Pessimistic, in some cases it might be helpful to neglect
6534           *       aux surface traffic.
6535           */
6536          if (iris_resource_level_has_hiz(devinfo, zres, cso->zsbuf->u.tex.level)) {
6537             pixel_size += intel_calculate_surface_pixel_size(&zres->aux.surf);
6538             pixel_size += intel_calculate_surface_pixel_size(&zres->aux.extra_aux.surf);
6539          }
6540       }
6541 
6542       if (sres) {
6543          pixel_size += intel_calculate_surface_pixel_size(&sres->surf);
6544       }
6545    }
6546 
6547    /* Compute a tile layout that allows reasonable utilization of the
6548     * tile cache based on the per-pixel cache footprint estimated
6549     * above.
6550     */
6551    intel_calculate_tile_dimensions(devinfo, screen->l3_config_3d,
6552                                    32, 32, cso->width, cso->height, pixel_size,
6553                                    tile_width, tile_height);
6554 
6555    /* Perform TBIMR tile passes only if the framebuffer covers more
6556     * than a single tile.
6557     */
6558    return *tile_width < cso->width || *tile_height < cso->height;
6559 }
6560 
6561 static void
iris_preemption_streamout_wa(struct iris_context * ice,struct iris_batch * batch,bool enable)6562 iris_preemption_streamout_wa(struct iris_context *ice,
6563                              struct iris_batch *batch,
6564                              bool enable)
6565 {
6566 #if GFX_VERx10 >= 120
6567    if (!intel_needs_workaround(batch->screen->devinfo, 16013994831))
6568       return;
6569 
6570    iris_emit_reg(batch, GENX(CS_CHICKEN1), reg) {
6571       reg.DisablePreemptionandHighPriorityPausingdueto3DPRIMITIVECommand = !enable;
6572       reg.DisablePreemptionandHighPriorityPausingdueto3DPRIMITIVECommandMask = true;
6573    }
6574 
6575    /* Emit CS_STALL and 250 noops. */
6576    iris_emit_pipe_control_flush(batch, "workaround: Wa_16013994831",
6577                                 PIPE_CONTROL_CS_STALL);
6578    for (unsigned i = 0; i < 250; i++)
6579       iris_emit_cmd(batch, GENX(MI_NOOP), noop);
6580 
6581    ice->state.genx->object_preemption = enable;
6582 #endif
6583 }
6584 
6585 static void
shader_program_needs_wa_14015055625(struct iris_context * ice,struct iris_batch * batch,struct iris_compiled_shader * shader,gl_shader_stage stage,bool * program_needs_wa_14015055625)6586 shader_program_needs_wa_14015055625(struct iris_context *ice,
6587                                     struct iris_batch *batch,
6588                                     struct iris_compiled_shader *shader,
6589                                     gl_shader_stage stage,
6590                                     bool *program_needs_wa_14015055625)
6591 {
6592    if (!intel_needs_workaround(batch->screen->devinfo, 14015055625))
6593       return;
6594 
6595    switch (stage) {
6596    case MESA_SHADER_TESS_CTRL: {
6597       struct iris_tcs_data *tcs_data = iris_tcs_data(shader);
6598       *program_needs_wa_14015055625 |= tcs_data->include_primitive_id;
6599       break;
6600    }
6601    case MESA_SHADER_TESS_EVAL: {
6602       struct iris_tes_data *tes_data = iris_tes_data(shader);
6603       *program_needs_wa_14015055625 |= tes_data->include_primitive_id;
6604       break;
6605    }
6606    default:
6607       break;
6608    }
6609 
6610    struct iris_compiled_shader *gs_shader =
6611       ice->shaders.prog[MESA_SHADER_GEOMETRY];
6612    const struct iris_gs_data *gs_data =
6613       gs_shader ? iris_gs_data(gs_shader) : NULL;
6614 
6615    *program_needs_wa_14015055625 |= gs_data && gs_data->include_primitive_id;
6616 }
6617 
6618 static void
emit_wa_18020335297_dummy_draw(struct iris_batch * batch)6619 emit_wa_18020335297_dummy_draw(struct iris_batch *batch)
6620 {
6621 #if GFX_VERx10 >= 125
6622    iris_emit_cmd(batch, GENX(3DSTATE_VFG), vfg) {
6623       vfg.DistributionMode = RR_STRICT;
6624    }
6625    iris_emit_cmd(batch, GENX(3DSTATE_VF), vf) {
6626       vf.GeometryDistributionEnable = true;
6627    }
6628 #endif
6629 
6630 #if GFX_VER >= 12
6631    iris_emit_cmd(batch, GENX(3DSTATE_PRIMITIVE_REPLICATION), pr) {
6632       pr.ReplicaMask = 1;
6633    }
6634 #endif
6635 
6636    iris_emit_cmd(batch, GENX(3DSTATE_RASTER), rr) {
6637       rr.CullMode = CULLMODE_NONE;
6638       rr.FrontFaceFillMode = FILL_MODE_SOLID;
6639       rr.BackFaceFillMode = FILL_MODE_SOLID;
6640    }
6641 
6642    iris_emit_cmd(batch, GENX(3DSTATE_VF_STATISTICS), vf) { }
6643    iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS), sgvs) { }
6644 
6645 #if GFX_VER >= 11
6646    iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS_2), sgvs2) { }
6647 #endif
6648 
6649    iris_emit_cmd(batch, GENX(3DSTATE_CLIP), clip) {
6650       clip.ClipEnable = true;
6651       clip.ClipMode = CLIPMODE_REJECT_ALL;
6652    }
6653 
6654    iris_emit_cmd(batch, GENX(3DSTATE_VS), vs) { }
6655    iris_emit_cmd(batch, GENX(3DSTATE_GS), gs) { }
6656    iris_emit_cmd(batch, GENX(3DSTATE_HS), hs) { }
6657    iris_emit_cmd(batch, GENX(3DSTATE_TE), te) { }
6658    iris_emit_cmd(batch, GENX(3DSTATE_DS), ds) { }
6659    iris_emit_cmd(batch, GENX(3DSTATE_STREAMOUT), so) { }
6660 
6661    uint32_t vertex_elements[1 + 2 * GENX(VERTEX_ELEMENT_STATE_length)];
6662    uint32_t *ve_pack_dest = &vertex_elements[1];
6663 
6664    iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS), vertex_elements, ve) {
6665       ve.DWordLength = 1 + GENX(VERTEX_ELEMENT_STATE_length) * 2 -
6666                        GENX(3DSTATE_VERTEX_ELEMENTS_length_bias);
6667    }
6668 
6669    for (int i = 0; i < 2; i++) {
6670       iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
6671          ve.Valid = true;
6672          ve.SourceElementFormat = ISL_FORMAT_R32G32B32A32_FLOAT;
6673          ve.Component0Control = VFCOMP_STORE_0;
6674          ve.Component1Control = VFCOMP_STORE_0;
6675          ve.Component2Control = i == 0 ? VFCOMP_STORE_0 : VFCOMP_STORE_1_FP;
6676          ve.Component3Control = i == 0 ? VFCOMP_STORE_0 : VFCOMP_STORE_1_FP;
6677       }
6678       ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
6679    }
6680 
6681    iris_batch_emit(batch, vertex_elements, sizeof(uint32_t) *
6682                    (1 + 2 * GENX(VERTEX_ELEMENT_STATE_length)));
6683 
6684    iris_emit_cmd(batch, GENX(3DSTATE_VF_TOPOLOGY), topo) {
6685       topo.PrimitiveTopologyType = _3DPRIM_TRILIST;
6686    }
6687 
6688    /* Emit dummy draw per slice. */
6689    for (unsigned i = 0; i < batch->screen->devinfo->num_slices; i++) {
6690       iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
6691          prim.VertexCountPerInstance = 3;
6692          prim.PrimitiveTopologyType = _3DPRIM_TRILIST;
6693          prim.InstanceCount = 1;
6694          prim.VertexAccessType = SEQUENTIAL;
6695       }
6696    }
6697 }
6698 
6699 static void
iris_upload_dirty_render_state(struct iris_context * ice,struct iris_batch * batch,const struct pipe_draw_info * draw,bool skip_vb_params)6700 iris_upload_dirty_render_state(struct iris_context *ice,
6701                                struct iris_batch *batch,
6702                                const struct pipe_draw_info *draw,
6703                                bool skip_vb_params)
6704 {
6705    struct iris_screen *screen = batch->screen;
6706    struct iris_border_color_pool *border_color_pool =
6707       iris_bufmgr_get_border_color_pool(screen->bufmgr);
6708 
6709    /* Re-emit 3DSTATE_DS before any 3DPRIMITIVE when tessellation is on */
6710    if (intel_needs_workaround(batch->screen->devinfo, 22018402687) &&
6711        ice->shaders.prog[MESA_SHADER_TESS_EVAL])
6712       ice->state.stage_dirty |= IRIS_STAGE_DIRTY_TES;
6713 
6714    uint64_t dirty = ice->state.dirty;
6715    uint64_t stage_dirty = ice->state.stage_dirty;
6716 
6717    if (!(dirty & IRIS_ALL_DIRTY_FOR_RENDER) &&
6718        !(stage_dirty & IRIS_ALL_STAGE_DIRTY_FOR_RENDER))
6719       return;
6720 
6721    struct iris_genx_state *genx = ice->state.genx;
6722    struct iris_binder *binder = &ice->state.binder;
6723    struct iris_fs_data *fs_data =
6724       iris_fs_data(ice->shaders.prog[MESA_SHADER_FRAGMENT]);
6725 
6726    /* When MSAA is enabled, instead of using BLENDFACTOR_ZERO use
6727     * CONST_COLOR, CONST_ALPHA and supply zero by using blend constants.
6728     */
6729    bool needs_wa_14018912822 =
6730       screen->driconf.intel_enable_wa_14018912822 &&
6731       intel_needs_workaround(batch->screen->devinfo, 14018912822) &&
6732       util_framebuffer_get_num_samples(&ice->state.framebuffer) > 1;
6733 
6734    if (dirty & IRIS_DIRTY_CC_VIEWPORT) {
6735       const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
6736       uint32_t cc_vp_address;
6737       bool wa_18020335297_applied = false;
6738 
6739       /* Wa_18020335297 - Apply the WA when viewport ptr is reprogrammed. */
6740       if (intel_needs_workaround(screen->devinfo, 18020335297) &&
6741           batch->name == IRIS_BATCH_RENDER &&
6742           ice->state.viewport_ptr_set) {
6743          emit_wa_18020335297_dummy_draw(batch);
6744          wa_18020335297_applied = true;
6745       }
6746 
6747       /* XXX: could avoid streaming for depth_clip [0,1] case. */
6748       uint32_t *cc_vp_map =
6749          stream_state(batch, ice->state.dynamic_uploader,
6750                       &ice->state.last_res.cc_vp,
6751                       4 * ice->state.num_viewports *
6752                       GENX(CC_VIEWPORT_length), 32, &cc_vp_address);
6753       for (int i = 0; i < ice->state.num_viewports; i++) {
6754          float zmin, zmax;
6755          iris_viewport_zmin_zmax(&ice->state.viewports[i], cso_rast->clip_halfz,
6756                                  ice->state.window_space_position,
6757                                  &zmin, &zmax);
6758          if (cso_rast->depth_clip_near)
6759             zmin = 0.0;
6760          if (cso_rast->depth_clip_far)
6761             zmax = 1.0;
6762 
6763          iris_pack_state(GENX(CC_VIEWPORT), cc_vp_map, ccv) {
6764             ccv.MinimumDepth = zmin;
6765             ccv.MaximumDepth = zmax;
6766          }
6767 
6768          cc_vp_map += GENX(CC_VIEWPORT_length);
6769       }
6770 
6771       iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_CC), ptr) {
6772          ptr.CCViewportPointer = cc_vp_address;
6773       }
6774 
6775       if (wa_18020335297_applied) {
6776 #if GFX_VER >= 12
6777          iris_emit_cmd(batch, GENX(3DSTATE_PRIMITIVE_REPLICATION), pr) { }
6778 #endif
6779          /* Dirty all emitted WA state to make sure that current real
6780           * state is restored.
6781           */
6782          dirty |= IRIS_DIRTY_VFG |
6783                   IRIS_DIRTY_VF |
6784                   IRIS_DIRTY_RASTER |
6785                   IRIS_DIRTY_VF_STATISTICS |
6786                   IRIS_DIRTY_VF_SGVS |
6787                   IRIS_DIRTY_CLIP |
6788                   IRIS_DIRTY_STREAMOUT |
6789                   IRIS_DIRTY_VERTEX_ELEMENTS |
6790                   IRIS_DIRTY_VF_TOPOLOGY;
6791 
6792          for (int stage = 0; stage < MESA_SHADER_FRAGMENT; stage++) {
6793             if (ice->shaders.prog[stage])
6794                stage_dirty |= (IRIS_STAGE_DIRTY_VS << stage);
6795          }
6796       }
6797       ice->state.viewport_ptr_set = true;
6798    }
6799 
6800    if (dirty & IRIS_DIRTY_SF_CL_VIEWPORT) {
6801       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
6802       uint32_t sf_cl_vp_address;
6803       uint32_t *vp_map =
6804          stream_state(batch, ice->state.dynamic_uploader,
6805                       &ice->state.last_res.sf_cl_vp,
6806                       4 * ice->state.num_viewports *
6807                       GENX(SF_CLIP_VIEWPORT_length), 64, &sf_cl_vp_address);
6808 
6809       for (unsigned i = 0; i < ice->state.num_viewports; i++) {
6810          const struct pipe_viewport_state *state = &ice->state.viewports[i];
6811          float gb_xmin, gb_xmax, gb_ymin, gb_ymax;
6812 
6813          float vp_xmin = viewport_extent(state, 0, -1.0f);
6814          float vp_xmax = viewport_extent(state, 0,  1.0f);
6815          float vp_ymin = viewport_extent(state, 1, -1.0f);
6816          float vp_ymax = viewport_extent(state, 1,  1.0f);
6817 
6818          intel_calculate_guardband_size(0, cso_fb->width, 0, cso_fb->height,
6819                                         state->scale[0], state->scale[1],
6820                                         state->translate[0], state->translate[1],
6821                                         &gb_xmin, &gb_xmax, &gb_ymin, &gb_ymax);
6822 
6823          iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
6824             vp.ViewportMatrixElementm00 = state->scale[0];
6825             vp.ViewportMatrixElementm11 = state->scale[1];
6826             vp.ViewportMatrixElementm22 = state->scale[2];
6827             vp.ViewportMatrixElementm30 = state->translate[0];
6828             vp.ViewportMatrixElementm31 = state->translate[1];
6829             vp.ViewportMatrixElementm32 = state->translate[2];
6830             vp.XMinClipGuardband = gb_xmin;
6831             vp.XMaxClipGuardband = gb_xmax;
6832             vp.YMinClipGuardband = gb_ymin;
6833             vp.YMaxClipGuardband = gb_ymax;
6834             vp.XMinViewPort = MAX2(vp_xmin, 0);
6835             vp.XMaxViewPort = MIN2(vp_xmax, cso_fb->width) - 1;
6836             vp.YMinViewPort = MAX2(vp_ymin, 0);
6837             vp.YMaxViewPort = MIN2(vp_ymax, cso_fb->height) - 1;
6838          }
6839 
6840          vp_map += GENX(SF_CLIP_VIEWPORT_length);
6841       }
6842 
6843       iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
6844          ptr.SFClipViewportPointer = sf_cl_vp_address;
6845       }
6846    }
6847 
6848    if (dirty & IRIS_DIRTY_URB) {
6849       for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
6850          if (!ice->shaders.prog[i]) {
6851             ice->shaders.urb.cfg.size[i] = 1;
6852          } else {
6853             struct iris_vue_data *vue_data =
6854                iris_vue_data(ice->shaders.prog[i]);
6855             ice->shaders.urb.cfg.size[i] = vue_data->urb_entry_size;
6856          }
6857          assert(ice->shaders.urb.cfg.size[i] != 0);
6858       }
6859 
6860       genX(emit_urb_config)(batch,
6861                             ice->shaders.prog[MESA_SHADER_TESS_EVAL] != NULL,
6862                             ice->shaders.prog[MESA_SHADER_GEOMETRY] != NULL);
6863    }
6864 
6865    if (dirty & IRIS_DIRTY_BLEND_STATE) {
6866       struct iris_blend_state *cso_blend = ice->state.cso_blend;
6867       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
6868       struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
6869       const int header_dwords = GENX(BLEND_STATE_length);
6870 
6871       bool color_blend_zero = false;
6872       bool alpha_blend_zero = false;
6873 
6874       /* Always write at least one BLEND_STATE - the final RT message will
6875        * reference BLEND_STATE[0] even if there aren't color writes.  There
6876        * may still be alpha testing, computed depth, and so on.
6877        */
6878       const int rt_dwords =
6879          MAX2(cso_fb->nr_cbufs, 1) * GENX(BLEND_STATE_ENTRY_length);
6880 
6881       uint32_t blend_offset;
6882       uint32_t *blend_map =
6883          stream_state(batch, ice->state.dynamic_uploader,
6884                       &ice->state.last_res.blend,
6885                       4 * (header_dwords + rt_dwords), 64, &blend_offset);
6886 
6887       /* Copy of blend entries for merging dynamic changes. */
6888       uint32_t blend_entries[4 * rt_dwords];
6889       memcpy(blend_entries, &cso_blend->blend_state[1], sizeof(blend_entries));
6890 
6891       unsigned cbufs = MAX2(cso_fb->nr_cbufs, 1);
6892 
6893       uint32_t *blend_entry = blend_entries;
6894       for (unsigned i = 0; i < cbufs; i++) {
6895          int dst_blend_factor = cso_blend->ps_dst_blend_factor[i];
6896          int dst_alpha_blend_factor = cso_blend->ps_dst_alpha_blend_factor[i];
6897          uint32_t entry[GENX(BLEND_STATE_ENTRY_length)];
6898          iris_pack_state(GENX(BLEND_STATE_ENTRY), entry, be) {
6899             if (needs_wa_14018912822) {
6900                if (dst_blend_factor == BLENDFACTOR_ZERO) {
6901                   dst_blend_factor = BLENDFACTOR_CONST_COLOR;
6902                   color_blend_zero = true;
6903                }
6904                if (dst_alpha_blend_factor == BLENDFACTOR_ZERO) {
6905                   dst_alpha_blend_factor = BLENDFACTOR_CONST_ALPHA;
6906                   alpha_blend_zero = true;
6907                }
6908             }
6909             be.DestinationBlendFactor = dst_blend_factor;
6910             be.DestinationAlphaBlendFactor = dst_alpha_blend_factor;
6911          }
6912 
6913          /* Merge entry. */
6914          uint32_t *dst = blend_entry;
6915          uint32_t *src = entry;
6916          for (unsigned j = 0; j < GENX(BLEND_STATE_ENTRY_length); j++)
6917             *dst |= *src;
6918 
6919          blend_entry += GENX(BLEND_STATE_ENTRY_length);
6920       }
6921 
6922       /* Blend constants modified for Wa_14018912822. */
6923       if (ice->state.color_blend_zero != color_blend_zero) {
6924          ice->state.color_blend_zero = color_blend_zero;
6925          ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
6926       }
6927       if (ice->state.alpha_blend_zero != alpha_blend_zero) {
6928          ice->state.alpha_blend_zero = alpha_blend_zero;
6929          ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
6930       }
6931 
6932       uint32_t blend_state_header;
6933       iris_pack_state(GENX(BLEND_STATE), &blend_state_header, bs) {
6934          bs.AlphaTestEnable = cso_zsa->alpha_enabled;
6935          bs.AlphaTestFunction = translate_compare_func(cso_zsa->alpha_func);
6936       }
6937 
6938       blend_map[0] = blend_state_header | cso_blend->blend_state[0];
6939       memcpy(&blend_map[1], blend_entries, 4 * rt_dwords);
6940 
6941       iris_emit_cmd(batch, GENX(3DSTATE_BLEND_STATE_POINTERS), ptr) {
6942          ptr.BlendStatePointer = blend_offset;
6943          ptr.BlendStatePointerValid = true;
6944       }
6945    }
6946 
6947    if (dirty & IRIS_DIRTY_COLOR_CALC_STATE) {
6948       struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
6949 #if GFX_VER == 8
6950       struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
6951 #endif
6952       uint32_t cc_offset;
6953       void *cc_map =
6954          stream_state(batch, ice->state.dynamic_uploader,
6955                       &ice->state.last_res.color_calc,
6956                       sizeof(uint32_t) * GENX(COLOR_CALC_STATE_length),
6957                       64, &cc_offset);
6958       iris_pack_state(GENX(COLOR_CALC_STATE), cc_map, cc) {
6959          cc.AlphaTestFormat = ALPHATEST_FLOAT32;
6960          cc.AlphaReferenceValueAsFLOAT32 = cso->alpha_ref_value;
6961          cc.BlendConstantColorRed   = ice->state.color_blend_zero ?
6962             0.0 : ice->state.blend_color.color[0];
6963          cc.BlendConstantColorGreen = ice->state.color_blend_zero ?
6964             0.0 : ice->state.blend_color.color[1];
6965          cc.BlendConstantColorBlue  = ice->state.color_blend_zero ?
6966             0.0 : ice->state.blend_color.color[2];
6967          cc.BlendConstantColorAlpha = ice->state.alpha_blend_zero ?
6968             0.0 : ice->state.blend_color.color[3];
6969 #if GFX_VER == 8
6970 	 cc.StencilReferenceValue = p_stencil_refs->ref_value[0];
6971 	 cc.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
6972 #endif
6973       }
6974       iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
6975          ptr.ColorCalcStatePointer = cc_offset;
6976          ptr.ColorCalcStatePointerValid = true;
6977       }
6978    }
6979 
6980 #if GFX_VERx10 == 125
6981    if (dirty & (IRIS_DIRTY_RENDER_BUFFER | IRIS_DIRTY_DEPTH_BUFFER)) {
6982       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
6983       unsigned tile_width, tile_height;
6984 
6985       ice->state.use_tbimr = batch->screen->driconf.enable_tbimr &&
6986          calculate_tile_dimensions(ice, &tile_width, &tile_height);
6987 
6988       if (ice->state.use_tbimr) {
6989          /* Use a batch size of 128 polygons per slice as recommended
6990           * by BSpec 68436 "TBIMR Programming".
6991           */
6992          const unsigned num_slices = screen->devinfo->num_slices;
6993          const unsigned batch_size = DIV_ROUND_UP(num_slices, 2) * 256;
6994 
6995          iris_emit_cmd(batch, GENX(3DSTATE_TBIMR_TILE_PASS_INFO), tbimr) {
6996             tbimr.TileRectangleHeight = tile_height;
6997             tbimr.TileRectangleWidth = tile_width;
6998             tbimr.VerticalTileCount = DIV_ROUND_UP(cso_fb->height, tile_height);
6999             tbimr.HorizontalTileCount = DIV_ROUND_UP(cso_fb->width, tile_width);
7000             tbimr.TBIMRBatchSize = util_logbase2(batch_size) - 5;
7001             tbimr.TileBoxCheck = true;
7002          }
7003       }
7004    }
7005 #endif
7006 
7007    /* Wa_1604061319
7008     *
7009     *    3DSTATE_CONSTANT_* needs to be programmed before BTP_*
7010     *
7011     * Testing shows that all the 3DSTATE_CONSTANT_XS need to be emitted if
7012     * any stage has a dirty binding table.
7013     */
7014    const bool emit_const_wa = GFX_VER >= 11 &&
7015       ((dirty & IRIS_DIRTY_RENDER_BUFFER) ||
7016        (stage_dirty & IRIS_ALL_STAGE_DIRTY_BINDINGS_FOR_RENDER));
7017 
7018 #if GFX_VER >= 12
7019    uint32_t nobuffer_stages = 0;
7020 #endif
7021 
7022    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
7023       if (!(stage_dirty & (IRIS_STAGE_DIRTY_CONSTANTS_VS << stage)) &&
7024           !emit_const_wa)
7025          continue;
7026 
7027       struct iris_shader_state *shs = &ice->state.shaders[stage];
7028       struct iris_compiled_shader *shader = ice->shaders.prog[stage];
7029 
7030       if (!shader)
7031          continue;
7032 
7033       if (shs->sysvals_need_upload)
7034          upload_sysvals(ice, stage, NULL);
7035 
7036       struct push_bos push_bos = {};
7037       setup_constant_buffers(ice, batch, stage, &push_bos);
7038 
7039 #if GFX_VER >= 12
7040       /* If this stage doesn't have any push constants, emit it later in a
7041        * single CONSTANT_ALL packet with all the other stages.
7042        */
7043       if (push_bos.buffer_count == 0) {
7044          nobuffer_stages |= 1 << stage;
7045          continue;
7046       }
7047 
7048       /* The Constant Buffer Read Length field from 3DSTATE_CONSTANT_ALL
7049        * contains only 5 bits, so we can only use it for buffers smaller than
7050        * 32.
7051        *
7052        * According to Wa_16011448509, Gfx12.0 misinterprets some address bits
7053        * in 3DSTATE_CONSTANT_ALL.  It should still be safe to use the command
7054        * for disabling stages, where all address bits are zero.  However, we
7055        * can't safely use it for general buffers with arbitrary addresses.
7056        * Just fall back to the individual 3DSTATE_CONSTANT_XS commands in that
7057        * case.
7058        */
7059       if (push_bos.max_length < 32 && GFX_VERx10 > 120) {
7060          emit_push_constant_packet_all(ice, batch, 1 << stage, &push_bos);
7061          continue;
7062       }
7063 #endif
7064       emit_push_constant_packets(ice, batch, stage, &push_bos);
7065    }
7066 
7067 #if GFX_VER >= 12
7068    if (nobuffer_stages)
7069       /* Wa_16011448509: all address bits are zero */
7070       emit_push_constant_packet_all(ice, batch, nobuffer_stages, NULL);
7071 #endif
7072 
7073    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
7074       /* Gfx9 requires 3DSTATE_BINDING_TABLE_POINTERS_XS to be re-emitted
7075        * in order to commit constants.  TODO: Investigate "Disable Gather
7076        * at Set Shader" to go back to legacy mode...
7077        */
7078       if (stage_dirty & ((IRIS_STAGE_DIRTY_BINDINGS_VS |
7079                           (GFX_VER == 9 ? IRIS_STAGE_DIRTY_CONSTANTS_VS : 0))
7080                             << stage)) {
7081          iris_emit_cmd(batch, GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), ptr) {
7082             ptr._3DCommandSubOpcode = 38 + stage;
7083             ptr.PointertoVSBindingTable =
7084                binder->bt_offset[stage] >> IRIS_BT_OFFSET_SHIFT;
7085          }
7086       }
7087    }
7088 
7089    if (GFX_VER >= 11 && (dirty & IRIS_DIRTY_RENDER_BUFFER)) {
7090       // XXX: we may want to flag IRIS_DIRTY_MULTISAMPLE (or SAMPLE_MASK?)
7091       // XXX: see commit 979fc1bc9bcc64027ff2cfafd285676f31b930a6
7092 
7093       /* The PIPE_CONTROL command description says:
7094        *
7095        *   "Whenever a Binding Table Index (BTI) used by a Render Target
7096        *    Message points to a different RENDER_SURFACE_STATE, SW must issue a
7097        *    Render Target Cache Flush by enabling this bit. When render target
7098        *    flush is set due to new association of BTI, PS Scoreboard Stall bit
7099        *    must be set in this packet."
7100        */
7101       // XXX: does this need to happen at 3DSTATE_BTP_PS time?
7102       iris_emit_pipe_control_flush(batch, "workaround: RT BTI change [draw]",
7103                                    PIPE_CONTROL_RENDER_TARGET_FLUSH |
7104                                    PIPE_CONTROL_STALL_AT_SCOREBOARD);
7105    }
7106 
7107    if (dirty & IRIS_DIRTY_RENDER_BUFFER)
7108       trace_framebuffer_state(&batch->trace, NULL, &ice->state.framebuffer);
7109 
7110    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
7111       if (stage_dirty & (IRIS_STAGE_DIRTY_BINDINGS_VS << stage)) {
7112          iris_populate_binding_table(ice, batch, stage, false);
7113       }
7114    }
7115 
7116    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
7117       if (!(stage_dirty & (IRIS_STAGE_DIRTY_SAMPLER_STATES_VS << stage)) ||
7118           !ice->shaders.prog[stage])
7119          continue;
7120 
7121       iris_upload_sampler_states(ice, stage);
7122 
7123       struct iris_shader_state *shs = &ice->state.shaders[stage];
7124       struct pipe_resource *res = shs->sampler_table.res;
7125       if (res)
7126          iris_use_pinned_bo(batch, iris_resource_bo(res), false,
7127                             IRIS_DOMAIN_NONE);
7128 
7129       iris_emit_cmd(batch, GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ptr) {
7130          ptr._3DCommandSubOpcode = 43 + stage;
7131          ptr.PointertoVSSamplerState = shs->sampler_table.offset;
7132       }
7133    }
7134 
7135    if (ice->state.need_border_colors)
7136       iris_use_pinned_bo(batch, border_color_pool->bo, false, IRIS_DOMAIN_NONE);
7137 
7138    if (dirty & IRIS_DIRTY_MULTISAMPLE) {
7139       iris_emit_cmd(batch, GENX(3DSTATE_MULTISAMPLE), ms) {
7140          ms.PixelLocation =
7141             ice->state.cso_rast->half_pixel_center ? CENTER : UL_CORNER;
7142          if (ice->state.framebuffer.samples > 0)
7143             ms.NumberofMultisamples = ffs(ice->state.framebuffer.samples) - 1;
7144       }
7145    }
7146 
7147    if (dirty & IRIS_DIRTY_SAMPLE_MASK) {
7148       iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_MASK), ms) {
7149          ms.SampleMask = ice->state.sample_mask;
7150       }
7151    }
7152 
7153 #if GFX_VERx10 >= 125
7154    /* This is only used on >= gfx125 for dynamic 3DSTATE_TE emission
7155     * related workarounds.
7156     */
7157    bool program_needs_wa_14015055625 = false;
7158 #endif
7159 
7160 #if INTEL_WA_14015055625_GFX_VER
7161    /* Check if FS stage will use primitive ID overrides for Wa_14015055625. */
7162    const struct intel_vue_map *last_vue_map =
7163       &iris_vue_data(ice->shaders.last_vue_shader)->vue_map;
7164    if ((fs_data->inputs & VARYING_BIT_PRIMITIVE_ID) &&
7165        last_vue_map->varying_to_slot[VARYING_SLOT_PRIMITIVE_ID] == -1 &&
7166        intel_needs_workaround(batch->screen->devinfo, 14015055625)) {
7167       program_needs_wa_14015055625 = true;
7168    }
7169 #endif
7170 
7171    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
7172       if (!(stage_dirty & (IRIS_STAGE_DIRTY_VS << stage)))
7173          continue;
7174 
7175       struct iris_compiled_shader *shader = ice->shaders.prog[stage];
7176 
7177       if (shader) {
7178          struct iris_resource *cache = (void *) shader->assembly.res;
7179          iris_use_pinned_bo(batch, cache->bo, false, IRIS_DOMAIN_NONE);
7180 
7181          uint32_t scratch_addr =
7182             pin_scratch_space(ice, batch, shader, stage);
7183 
7184 #if INTEL_WA_14015055625_GFX_VER
7185          shader_program_needs_wa_14015055625(ice, batch, shader, stage,
7186                                              &program_needs_wa_14015055625);
7187 #endif
7188 
7189          if (stage == MESA_SHADER_FRAGMENT) {
7190             UNUSED struct iris_rasterizer_state *cso = ice->state.cso_rast;
7191             struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
7192 
7193             uint32_t ps_state[GENX(3DSTATE_PS_length)] = {0};
7194             _iris_pack_command(batch, GENX(3DSTATE_PS), ps_state, ps) {
7195 #if GFX_VER >= 9
7196                struct brw_wm_prog_data *wm_prog_data = brw_wm_prog_data(shader->brw_prog_data);
7197 #else
7198                struct elk_wm_prog_data *wm_prog_data = elk_wm_prog_data(shader->elk_prog_data);
7199 #endif
7200                intel_set_ps_dispatch_state(&ps, batch->screen->devinfo,
7201                                            wm_prog_data, util_framebuffer_get_num_samples(cso_fb),
7202                                            0 /* msaa_flags */);
7203 
7204 #if GFX_VER == 12
7205                assert(fs_data->dispatch_multi == 0 ||
7206                       (fs_data->dispatch_multi == 16 && fs_data->max_polygons == 2));
7207                ps.DualSIMD8DispatchEnable = fs_data->dispatch_multi;
7208                /* XXX - No major improvement observed from enabling
7209                 *       overlapping subspans, but it could be helpful
7210                 *       in theory when the requirements listed on the
7211                 *       BSpec page for 3DSTATE_PS_BODY are met.
7212                 */
7213                ps.OverlappingSubspansEnable = false;
7214 #endif
7215 
7216 #if GFX_VER >= 9
7217                ps.DispatchGRFStartRegisterForConstantSetupData0 =
7218                   brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
7219                ps.DispatchGRFStartRegisterForConstantSetupData1 =
7220                   brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
7221 #if GFX_VER < 20
7222                ps.DispatchGRFStartRegisterForConstantSetupData2 =
7223                   brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
7224 #endif
7225 
7226                ps.KernelStartPointer0 = KSP(shader) +
7227                   brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
7228                ps.KernelStartPointer1 = KSP(shader) +
7229                   brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
7230 #if GFX_VER < 20
7231                ps.KernelStartPointer2 = KSP(shader) +
7232                   brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
7233 #endif
7234 #else
7235                ps.DispatchGRFStartRegisterForConstantSetupData0 =
7236                   elk_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
7237                ps.DispatchGRFStartRegisterForConstantSetupData1 =
7238                   elk_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
7239                ps.DispatchGRFStartRegisterForConstantSetupData2 =
7240                   elk_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
7241 
7242                ps.KernelStartPointer0 = KSP(shader) +
7243                   elk_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
7244                ps.KernelStartPointer1 = KSP(shader) +
7245                   elk_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
7246                ps.KernelStartPointer2 = KSP(shader) +
7247                   elk_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
7248 #endif
7249 
7250 #if GFX_VERx10 >= 125
7251                ps.ScratchSpaceBuffer = scratch_addr >> 4;
7252 #else
7253                ps.ScratchSpaceBasePointer =
7254                   rw_bo(NULL, scratch_addr, IRIS_DOMAIN_NONE);
7255 #endif
7256             }
7257 
7258             uint32_t psx_state[GENX(3DSTATE_PS_EXTRA_length)] = {0};
7259             iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
7260 #if GFX_VER >= 9
7261                if (!fs_data->uses_sample_mask)
7262                   psx.InputCoverageMaskState  = ICMS_NONE;
7263                else if (fs_data->post_depth_coverage)
7264                   psx.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
7265                else if (fs_data->inner_coverage &&
7266                         cso->conservative_rasterization)
7267                   psx.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
7268                else
7269                   psx.InputCoverageMaskState = ICMS_NORMAL;
7270 #else
7271                psx.PixelShaderUsesInputCoverageMask =
7272                   fs_data->uses_sample_mask;
7273 #endif
7274             }
7275 
7276             uint32_t *shader_ps = (uint32_t *) shader->derived_data;
7277             uint32_t *shader_psx = shader_ps + GENX(3DSTATE_PS_length);
7278             iris_emit_merge(batch, shader_ps, ps_state,
7279                             GENX(3DSTATE_PS_length));
7280             iris_emit_merge(batch, shader_psx, psx_state,
7281                             GENX(3DSTATE_PS_EXTRA_length));
7282 #if GFX_VERx10 >= 125
7283          } else if (stage == MESA_SHADER_TESS_EVAL) {
7284             uint32_t te_state[GENX(3DSTATE_TE_length)] = { 0 };
7285             iris_pack_command(GENX(3DSTATE_TE), te_state, te) {
7286                if (intel_needs_workaround(screen->devinfo, 14015055625) &&
7287                    program_needs_wa_14015055625)
7288                   te.TessellationDistributionMode = TEDMODE_OFF;
7289                else if (intel_needs_workaround(screen->devinfo, 22012699309))
7290                   te.TessellationDistributionMode = TEDMODE_RR_STRICT;
7291                else
7292                   te.TessellationDistributionMode = TEDMODE_RR_FREE;
7293             }
7294 
7295             uint32_t ds_state[GENX(3DSTATE_DS_length)] = { 0 };
7296             iris_pack_command(GENX(3DSTATE_DS), ds_state, ds) {
7297                if (scratch_addr)
7298                   ds.ScratchSpaceBuffer = scratch_addr >> 4;
7299             }
7300 
7301             uint32_t *shader_ds = (uint32_t *) shader->derived_data;
7302             uint32_t *shader_te = shader_ds + GENX(3DSTATE_DS_length);
7303 
7304             iris_emit_merge(batch, shader_ds, ds_state,
7305                             GENX(3DSTATE_DS_length));
7306             iris_emit_merge(batch, shader_te, te_state,
7307                             GENX(3DSTATE_TE_length));
7308 #endif
7309          } else if (scratch_addr) {
7310             uint32_t *pkt = (uint32_t *) shader->derived_data;
7311             switch (stage) {
7312             case MESA_SHADER_VERTEX:    MERGE_SCRATCH_ADDR(3DSTATE_VS); break;
7313             case MESA_SHADER_TESS_CTRL: MERGE_SCRATCH_ADDR(3DSTATE_HS); break;
7314             case MESA_SHADER_TESS_EVAL: MERGE_SCRATCH_ADDR(3DSTATE_DS); break;
7315             case MESA_SHADER_GEOMETRY:  MERGE_SCRATCH_ADDR(3DSTATE_GS); break;
7316             }
7317          } else {
7318             iris_batch_emit(batch, shader->derived_data,
7319                             iris_derived_program_state_size(stage));
7320          }
7321       } else {
7322          if (stage == MESA_SHADER_TESS_EVAL) {
7323             iris_emit_cmd(batch, GENX(3DSTATE_HS), hs);
7324             iris_emit_cmd(batch, GENX(3DSTATE_TE), te);
7325             iris_emit_cmd(batch, GENX(3DSTATE_DS), ds);
7326          } else if (stage == MESA_SHADER_GEOMETRY) {
7327             iris_emit_cmd(batch, GENX(3DSTATE_GS), gs);
7328          }
7329       }
7330    }
7331 
7332    if (ice->state.streamout_active) {
7333       if (dirty & IRIS_DIRTY_SO_BUFFERS) {
7334          /* Wa_16011411144
7335           * SW must insert a PIPE_CONTROL cmd before and after the
7336           * 3dstate_so_buffer_index_0/1/2/3 states to ensure so_buffer_index_* state is
7337           * not combined with other state changes.
7338           */
7339          if (intel_device_info_is_dg2(batch->screen->devinfo)) {
7340             iris_emit_pipe_control_flush(batch,
7341                                          "SO pre change stall WA",
7342                                          PIPE_CONTROL_CS_STALL);
7343          }
7344 
7345          for (int i = 0; i < 4; i++) {
7346             struct iris_stream_output_target *tgt =
7347                (void *) ice->state.so_target[i];
7348             enum { dwords = GENX(3DSTATE_SO_BUFFER_length) };
7349             uint32_t *so_buffers = genx->so_buffers + i * dwords;
7350             bool zero_offset = false;
7351 
7352             if (tgt) {
7353                zero_offset = tgt->zero_offset;
7354                iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
7355                                   true, IRIS_DOMAIN_OTHER_WRITE);
7356                iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
7357                                   true, IRIS_DOMAIN_OTHER_WRITE);
7358             }
7359 
7360             if (zero_offset) {
7361                /* Skip the last DWord which contains "Stream Offset" of
7362                 * 0xFFFFFFFF and instead emit a dword of zero directly.
7363                 */
7364                STATIC_ASSERT(GENX(3DSTATE_SO_BUFFER_StreamOffset_start) ==
7365                              32 * (dwords - 1));
7366                const uint32_t zero = 0;
7367                iris_batch_emit(batch, so_buffers, 4 * (dwords - 1));
7368                iris_batch_emit(batch, &zero, sizeof(zero));
7369                tgt->zero_offset = false;
7370             } else {
7371                iris_batch_emit(batch, so_buffers, 4 * dwords);
7372             }
7373          }
7374 
7375          /* Wa_16011411144 */
7376          if (intel_device_info_is_dg2(batch->screen->devinfo)) {
7377             iris_emit_pipe_control_flush(batch,
7378                                          "SO post change stall WA",
7379                                          PIPE_CONTROL_CS_STALL);
7380          }
7381       }
7382 
7383       if ((dirty & IRIS_DIRTY_SO_DECL_LIST) && ice->state.streamout) {
7384          /* Wa_16011773973:
7385           * If SOL is enabled and SO_DECL state has to be programmed,
7386           *    1. Send 3D State SOL state with SOL disabled
7387           *    2. Send SO_DECL NP state
7388           *    3. Send 3D State SOL with SOL Enabled
7389           */
7390          if (intel_device_info_is_dg2(batch->screen->devinfo))
7391             iris_emit_cmd(batch, GENX(3DSTATE_STREAMOUT), sol);
7392 
7393          uint32_t *decl_list =
7394             ice->state.streamout + GENX(3DSTATE_STREAMOUT_length);
7395          iris_batch_emit(batch, decl_list, 4 * ((decl_list[0] & 0xff) + 2));
7396 
7397 #if GFX_VER >= 11
7398          /* ICL PRMs, Volume 2a - Command Reference: Instructions,
7399           * 3DSTATE_SO_DECL_LIST:
7400           *
7401           *    "Workaround: This command must be followed by a PIPE_CONTROL
7402           *     with CS Stall bit set."
7403           *
7404           * On DG2+ also known as Wa_1509820217.
7405           */
7406          iris_emit_pipe_control_flush(batch,
7407                                       "workaround: cs stall after so_decl",
7408                                       PIPE_CONTROL_CS_STALL);
7409 #endif
7410       }
7411 
7412       if (dirty & IRIS_DIRTY_STREAMOUT) {
7413          const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
7414 
7415 #if GFX_VERx10 >= 120
7416          /* Wa_16013994831 - Disable preemption. */
7417          if (intel_needs_workaround(batch->screen->devinfo, 16013994831))
7418             iris_preemption_streamout_wa(ice, batch, false);
7419 #endif
7420 
7421          uint32_t dynamic_sol[GENX(3DSTATE_STREAMOUT_length)];
7422          iris_pack_command(GENX(3DSTATE_STREAMOUT), dynamic_sol, sol) {
7423             sol.SOFunctionEnable = true;
7424             sol.SOStatisticsEnable = true;
7425 
7426             sol.RenderingDisable = cso_rast->rasterizer_discard &&
7427                                    !ice->state.prims_generated_query_active;
7428             sol.ReorderMode = cso_rast->flatshade_first ? LEADING : TRAILING;
7429 
7430 
7431 #if INTEL_NEEDS_WA_18022508906
7432             /* Wa_14017076903 :
7433              *
7434              * SKL PRMs, Volume 7: 3D-Media-GPGPU, Stream Output Logic (SOL) Stage:
7435              *
7436              * SOL_INT::Render_Enable =
7437              *   (3DSTATE_STREAMOUT::Force_Rending == Force_On) ||
7438              *   (
7439              *     (3DSTATE_STREAMOUT::Force_Rending != Force_Off) &&
7440              *     !(3DSTATE_GS::Enable && 3DSTATE_GS::Output Vertex Size == 0) &&
7441              *     !3DSTATE_STREAMOUT::API_Render_Disable &&
7442              *     (
7443              *       3DSTATE_DEPTH_STENCIL_STATE::Stencil_TestEnable ||
7444              *       3DSTATE_DEPTH_STENCIL_STATE::Depth_TestEnable ||
7445              *       3DSTATE_DEPTH_STENCIL_STATE::Depth_WriteEnable ||
7446              *       3DSTATE_PS_EXTRA::PS_Valid ||
7447              *       3DSTATE_WM::Legacy Depth_Buffer_Clear ||
7448              *       3DSTATE_WM::Legacy Depth_Buffer_Resolve_Enable ||
7449              *       3DSTATE_WM::Legacy Hierarchical_Depth_Buffer_Resolve_Enable
7450              *     )
7451              *   )
7452              *
7453              * If SOL_INT::Render_Enable is false, the SO stage will not forward any
7454              * topologies down the pipeline. Which is not what we want for occlusion
7455              * queries.
7456              *
7457              * Here we force rendering to get SOL_INT::Render_Enable when occlusion
7458              * queries are active.
7459              */
7460             const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
7461             if (!cso_rast->rasterizer_discard && ice->state.occlusion_query_active)
7462                sol.ForceRendering = Force_on;
7463 #endif
7464          }
7465 
7466          assert(ice->state.streamout);
7467 
7468          iris_emit_merge(batch, ice->state.streamout, dynamic_sol,
7469                          GENX(3DSTATE_STREAMOUT_length));
7470       }
7471    } else {
7472       if (dirty & IRIS_DIRTY_STREAMOUT) {
7473 
7474 #if GFX_VERx10 >= 120
7475          /* Wa_16013994831 - Enable preemption. */
7476          if (!ice->state.genx->object_preemption)
7477             iris_preemption_streamout_wa(ice, batch, true);
7478 #endif
7479 
7480          iris_emit_cmd(batch, GENX(3DSTATE_STREAMOUT), sol);
7481       }
7482    }
7483 
7484    if (dirty & IRIS_DIRTY_CLIP) {
7485       struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
7486       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
7487 
7488       bool gs_or_tes = ice->shaders.prog[MESA_SHADER_GEOMETRY] ||
7489                        ice->shaders.prog[MESA_SHADER_TESS_EVAL];
7490       bool points_or_lines = cso_rast->fill_mode_point_or_line ||
7491          (gs_or_tes ? ice->shaders.output_topology_is_points_or_lines
7492                     : ice->state.prim_is_points_or_lines);
7493 
7494       uint32_t dynamic_clip[GENX(3DSTATE_CLIP_length)];
7495       iris_pack_command(GENX(3DSTATE_CLIP), &dynamic_clip, cl) {
7496          cl.StatisticsEnable = ice->state.statistics_counters_enabled;
7497          if (cso_rast->rasterizer_discard)
7498             cl.ClipMode = CLIPMODE_REJECT_ALL;
7499          else if (ice->state.window_space_position)
7500             cl.ClipMode = CLIPMODE_ACCEPT_ALL;
7501          else
7502             cl.ClipMode = CLIPMODE_NORMAL;
7503 
7504          cl.PerspectiveDivideDisable = ice->state.window_space_position;
7505          cl.ViewportXYClipTestEnable = !points_or_lines;
7506 
7507          cl.NonPerspectiveBarycentricEnable = fs_data->uses_nonperspective_interp_modes;
7508 
7509          cl.ForceZeroRTAIndexEnable = cso_fb->layers <= 1;
7510          cl.MaximumVPIndex = ice->state.num_viewports - 1;
7511       }
7512       iris_emit_merge(batch, cso_rast->clip, dynamic_clip,
7513                       ARRAY_SIZE(cso_rast->clip));
7514    }
7515 
7516    if (dirty & (IRIS_DIRTY_RASTER | IRIS_DIRTY_URB)) {
7517       /* From the Browadwell PRM, Volume 2, documentation for
7518        * 3DSTATE_RASTER, "Antialiasing Enable":
7519        *
7520        * "This field must be disabled if any of the render targets
7521        * have integer (UINT or SINT) surface format."
7522        *
7523        * Additionally internal documentation for Gfx12+ states:
7524        *
7525        * "This bit MUST not be set when NUM_MULTISAMPLES > 1 OR
7526        *  FORCED_SAMPLE_COUNT > 1."
7527        */
7528       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
7529       unsigned samples = util_framebuffer_get_num_samples(cso_fb);
7530       struct iris_rasterizer_state *cso = ice->state.cso_rast;
7531 
7532       bool aa_enable = cso->line_smooth &&
7533                        !ice->state.has_integer_rt &&
7534                        !(batch->screen->devinfo->ver >= 12 && samples > 1);
7535 
7536       uint32_t dynamic_raster[GENX(3DSTATE_RASTER_length)];
7537       iris_pack_command(GENX(3DSTATE_RASTER), &dynamic_raster, raster) {
7538          raster.AntialiasingEnable = aa_enable;
7539       }
7540       iris_emit_merge(batch, cso->raster, dynamic_raster,
7541                       ARRAY_SIZE(cso->raster));
7542 
7543       uint32_t dynamic_sf[GENX(3DSTATE_SF_length)];
7544       iris_pack_command(GENX(3DSTATE_SF), &dynamic_sf, sf) {
7545          sf.ViewportTransformEnable = !ice->state.window_space_position;
7546 
7547 #if GFX_VER >= 12
7548          sf.DerefBlockSize = ice->state.urb_deref_block_size;
7549 #endif
7550       }
7551       iris_emit_merge(batch, cso->sf, dynamic_sf,
7552                       ARRAY_SIZE(dynamic_sf));
7553    }
7554 
7555    if (dirty & IRIS_DIRTY_WM) {
7556       struct iris_rasterizer_state *cso = ice->state.cso_rast;
7557       uint32_t dynamic_wm[GENX(3DSTATE_WM_length)];
7558 
7559       iris_pack_command(GENX(3DSTATE_WM), &dynamic_wm, wm) {
7560          wm.StatisticsEnable = ice->state.statistics_counters_enabled;
7561 
7562          wm.BarycentricInterpolationMode =
7563             iris_fs_barycentric_modes(ice->shaders.prog[MESA_SHADER_FRAGMENT], 0);
7564 
7565          if (fs_data->early_fragment_tests)
7566             wm.EarlyDepthStencilControl = EDSC_PREPS;
7567          else if (fs_data->has_side_effects)
7568             wm.EarlyDepthStencilControl = EDSC_PSEXEC;
7569          else
7570             wm.EarlyDepthStencilControl = EDSC_NORMAL;
7571 
7572          /* We could skip this bit if color writes are enabled. */
7573          if (fs_data->has_side_effects || fs_data->uses_kill)
7574             wm.ForceThreadDispatchEnable = ForceON;
7575       }
7576       iris_emit_merge(batch, cso->wm, dynamic_wm, ARRAY_SIZE(cso->wm));
7577    }
7578 
7579    if (dirty & IRIS_DIRTY_SBE) {
7580       iris_emit_sbe(batch, ice);
7581    }
7582 
7583    if (dirty & IRIS_DIRTY_PS_BLEND) {
7584       struct iris_blend_state *cso_blend = ice->state.cso_blend;
7585       struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
7586       const struct shader_info *fs_info =
7587          iris_get_shader_info(ice, MESA_SHADER_FRAGMENT);
7588 
7589       int dst_blend_factor = cso_blend->ps_dst_blend_factor[0];
7590       int dst_alpha_blend_factor = cso_blend->ps_dst_alpha_blend_factor[0];
7591 
7592       /* When MSAA is enabled, instead of using BLENDFACTOR_ZERO use
7593        * CONST_COLOR, CONST_ALPHA and supply zero by using blend constants.
7594        */
7595       if (needs_wa_14018912822) {
7596          if (ice->state.color_blend_zero)
7597             dst_blend_factor = BLENDFACTOR_CONST_COLOR;
7598          if (ice->state.alpha_blend_zero)
7599             dst_alpha_blend_factor = BLENDFACTOR_CONST_ALPHA;
7600       }
7601 
7602       uint32_t dynamic_pb[GENX(3DSTATE_PS_BLEND_length)];
7603       iris_pack_command(GENX(3DSTATE_PS_BLEND), &dynamic_pb, pb) {
7604          pb.HasWriteableRT = has_writeable_rt(cso_blend, fs_info);
7605          pb.AlphaTestEnable = cso_zsa->alpha_enabled;
7606 
7607          pb.DestinationBlendFactor = dst_blend_factor;
7608          pb.DestinationAlphaBlendFactor = dst_alpha_blend_factor;
7609 
7610          /* The dual source blending docs caution against using SRC1 factors
7611           * when the shader doesn't use a dual source render target write.
7612           * Empirically, this can lead to GPU hangs, and the results are
7613           * undefined anyway, so simply disable blending to avoid the hang.
7614           */
7615          pb.ColorBufferBlendEnable = (cso_blend->blend_enables & 1) &&
7616             (!cso_blend->dual_color_blending || fs_data->dual_src_blend);
7617       }
7618 
7619       iris_emit_merge(batch, cso_blend->ps_blend, dynamic_pb,
7620                       ARRAY_SIZE(cso_blend->ps_blend));
7621    }
7622 
7623    if (dirty & IRIS_DIRTY_WM_DEPTH_STENCIL) {
7624       struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
7625 #if GFX_VER >= 9 && GFX_VER < 12
7626       struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
7627       uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
7628       iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
7629          wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
7630          wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
7631       }
7632       iris_emit_merge(batch, cso->wmds, stencil_refs, ARRAY_SIZE(cso->wmds));
7633 #else
7634       /* Use modify disable fields which allow us to emit packets
7635        * directly instead of merging them later.
7636        */
7637       iris_batch_emit(batch, cso->wmds, sizeof(cso->wmds));
7638 #endif
7639 
7640    /* Depth or stencil write changed in cso. */
7641    if (intel_needs_workaround(batch->screen->devinfo, 18019816803) &&
7642        (dirty & IRIS_DIRTY_DS_WRITE_ENABLE)) {
7643       iris_emit_pipe_control_flush(
7644          batch, "workaround: PSS stall after DS write enable change",
7645          PIPE_CONTROL_PSS_STALL_SYNC);
7646    }
7647 
7648 #if GFX_VER >= 12
7649       iris_batch_emit(batch, cso->depth_bounds, sizeof(cso->depth_bounds));
7650 #endif
7651    }
7652 
7653    if (dirty & IRIS_DIRTY_STENCIL_REF) {
7654 #if GFX_VER >= 12
7655       /* Use modify disable fields which allow us to emit packets
7656        * directly instead of merging them later.
7657        */
7658       struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
7659       uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
7660       iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
7661          wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
7662          wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
7663          wmds.StencilTestMaskModifyDisable = true;
7664          wmds.StencilWriteMaskModifyDisable = true;
7665          wmds.StencilStateModifyDisable = true;
7666          wmds.DepthStateModifyDisable = true;
7667       }
7668       iris_batch_emit(batch, stencil_refs, sizeof(stencil_refs));
7669 #endif
7670    }
7671 
7672    if (dirty & IRIS_DIRTY_SCISSOR_RECT) {
7673       /* Wa_1409725701:
7674        *    "The viewport-specific state used by the SF unit (SCISSOR_RECT) is
7675        *    stored as an array of up to 16 elements. The location of first
7676        *    element of the array, as specified by Pointer to SCISSOR_RECT,
7677        *    should be aligned to a 64-byte boundary.
7678        */
7679       uint32_t alignment = 64;
7680       uint32_t scissor_offset =
7681          emit_state(batch, ice->state.dynamic_uploader,
7682                     &ice->state.last_res.scissor,
7683                     ice->state.scissors,
7684                     sizeof(struct pipe_scissor_state) *
7685                     ice->state.num_viewports, alignment);
7686 
7687       iris_emit_cmd(batch, GENX(3DSTATE_SCISSOR_STATE_POINTERS), ptr) {
7688          ptr.ScissorRectPointer = scissor_offset;
7689       }
7690    }
7691 
7692    if (dirty & IRIS_DIRTY_DEPTH_BUFFER) {
7693       struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
7694 
7695       /* Do not emit the cso yet. We may need to update clear params first. */
7696       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
7697       struct iris_resource *zres = NULL, *sres = NULL;
7698       if (cso_fb->zsbuf) {
7699          iris_get_depth_stencil_resources(cso_fb->zsbuf->texture,
7700                                           &zres, &sres);
7701       }
7702 
7703       if (zres && ice->state.hiz_usage != ISL_AUX_USAGE_NONE) {
7704 #if GFX_VER < 20
7705          uint32_t *clear_params =
7706             cso_z->packets + ARRAY_SIZE(cso_z->packets) -
7707             GENX(3DSTATE_CLEAR_PARAMS_length);
7708 
7709          iris_pack_command(GENX(3DSTATE_CLEAR_PARAMS), clear_params, clear) {
7710             clear.DepthClearValueValid = true;
7711             clear.DepthClearValue = zres->aux.clear_color.f32[0];
7712          }
7713 #endif
7714       }
7715 
7716       iris_batch_emit(batch, cso_z->packets, sizeof(cso_z->packets));
7717 
7718       /* Wa_14016712196:
7719        * Emit depth flush after state that sends implicit depth flush.
7720        */
7721       if (intel_needs_workaround(batch->screen->devinfo, 14016712196)) {
7722          iris_emit_pipe_control_flush(batch, "Wa_14016712196",
7723                                       PIPE_CONTROL_DEPTH_CACHE_FLUSH);
7724       }
7725 
7726       if (zres)
7727          genX(emit_depth_state_workarounds)(ice, batch, &zres->surf);
7728 
7729       if (intel_needs_workaround(batch->screen->devinfo, 1408224581) ||
7730           intel_needs_workaround(batch->screen->devinfo, 14014097488)) {
7731          /* Wa_1408224581
7732           *
7733           * Workaround: Gfx12LP Astep only An additional pipe control with
7734           * post-sync = store dword operation would be required.( w/a is to
7735           * have an additional pipe control after the stencil state whenever
7736           * the surface state bits of this state is changing).
7737           *
7738           * This also seems sufficient to handle Wa_14014097488.
7739           */
7740          iris_emit_pipe_control_write(batch, "WA for stencil state",
7741                                       PIPE_CONTROL_WRITE_IMMEDIATE,
7742                                       screen->workaround_address.bo,
7743                                       screen->workaround_address.offset, 0);
7744       }
7745    }
7746 
7747    if (dirty & (IRIS_DIRTY_DEPTH_BUFFER | IRIS_DIRTY_WM_DEPTH_STENCIL)) {
7748       /* Listen for buffer changes, and also write enable changes. */
7749       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
7750       pin_depth_and_stencil_buffers(batch, cso_fb->zsbuf, ice->state.cso_zsa);
7751    }
7752 
7753    if (dirty & IRIS_DIRTY_POLYGON_STIPPLE) {
7754       iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_PATTERN), poly) {
7755          for (int i = 0; i < 32; i++) {
7756             poly.PatternRow[i] = ice->state.poly_stipple.stipple[i];
7757          }
7758       }
7759    }
7760 
7761    if (dirty & IRIS_DIRTY_LINE_STIPPLE) {
7762       struct iris_rasterizer_state *cso = ice->state.cso_rast;
7763       iris_batch_emit(batch, cso->line_stipple, sizeof(cso->line_stipple));
7764 #if GFX_VER >= 11
7765       /* ICL PRMs, Volume 2a - Command Reference: Instructions,
7766        * 3DSTATE_LINE_STIPPLE:
7767        *
7768        *    "Workaround: This command must be followed by a PIPE_CONTROL with
7769        *     CS Stall bit set."
7770        */
7771       iris_emit_pipe_control_flush(batch,
7772                                    "workaround: post 3DSTATE_LINE_STIPPLE",
7773                                    PIPE_CONTROL_CS_STALL);
7774 #endif
7775    }
7776 
7777    if (dirty & IRIS_DIRTY_VF_TOPOLOGY) {
7778       iris_emit_cmd(batch, GENX(3DSTATE_VF_TOPOLOGY), topo) {
7779          topo.PrimitiveTopologyType =
7780             translate_prim_type(draw->mode, ice->state.vertices_per_patch);
7781       }
7782    }
7783 
7784    if (dirty & IRIS_DIRTY_VERTEX_BUFFERS) {
7785       int count = util_bitcount64(ice->state.bound_vertex_buffers);
7786       uint64_t dynamic_bound = ice->state.bound_vertex_buffers;
7787 
7788       if (ice->state.vs_uses_draw_params && !skip_vb_params) {
7789          assert(ice->draw.draw_params.res);
7790 
7791          struct iris_vertex_buffer_state *state =
7792             &(ice->state.genx->vertex_buffers[count]);
7793          pipe_resource_reference(&state->resource, ice->draw.draw_params.res);
7794          struct iris_resource *res = (void *) state->resource;
7795 
7796          iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
7797             vb.VertexBufferIndex = count;
7798             vb.AddressModifyEnable = true;
7799             vb.BufferPitch = 0;
7800             vb.BufferSize = res->bo->size - ice->draw.draw_params.offset;
7801             vb.BufferStartingAddress =
7802                ro_bo(NULL, res->bo->address +
7803                            (int) ice->draw.draw_params.offset);
7804             vb.MOCS = iris_mocs(res->bo, &screen->isl_dev,
7805                                 ISL_SURF_USAGE_VERTEX_BUFFER_BIT);
7806 #if GFX_VER >= 12
7807             vb.L3BypassDisable       = true;
7808 #endif
7809          }
7810          dynamic_bound |= 1ull << count;
7811          count++;
7812       }
7813 
7814       if (ice->state.vs_uses_derived_draw_params && !skip_vb_params) {
7815          struct iris_vertex_buffer_state *state =
7816             &(ice->state.genx->vertex_buffers[count]);
7817          pipe_resource_reference(&state->resource,
7818                                  ice->draw.derived_draw_params.res);
7819          struct iris_resource *res = (void *) ice->draw.derived_draw_params.res;
7820 
7821          iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
7822              vb.VertexBufferIndex = count;
7823             vb.AddressModifyEnable = true;
7824             vb.BufferPitch = 0;
7825             vb.BufferSize =
7826                res->bo->size - ice->draw.derived_draw_params.offset;
7827             vb.BufferStartingAddress =
7828                ro_bo(NULL, res->bo->address +
7829                            (int) ice->draw.derived_draw_params.offset);
7830             vb.MOCS = iris_mocs(res->bo, &screen->isl_dev,
7831                                 ISL_SURF_USAGE_VERTEX_BUFFER_BIT);
7832 #if GFX_VER >= 12
7833             vb.L3BypassDisable       = true;
7834 #endif
7835          }
7836          dynamic_bound |= 1ull << count;
7837          count++;
7838       }
7839 
7840       if (count) {
7841 #if GFX_VER >= 11
7842          /* Gfx11+ doesn't need the cache workaround below */
7843          uint64_t bound = dynamic_bound;
7844          while (bound) {
7845             const int i = u_bit_scan64(&bound);
7846             iris_use_optional_res(batch, genx->vertex_buffers[i].resource,
7847                                   false, IRIS_DOMAIN_VF_READ);
7848          }
7849 #else
7850          /* The VF cache designers cut corners, and made the cache key's
7851           * <VertexBufferIndex, Memory Address> tuple only consider the bottom
7852           * 32 bits of the address.  If you have two vertex buffers which get
7853           * placed exactly 4 GiB apart and use them in back-to-back draw calls,
7854           * you can get collisions (even within a single batch).
7855           *
7856           * So, we need to do a VF cache invalidate if the buffer for a VB
7857           * slot slot changes [48:32] address bits from the previous time.
7858           */
7859          unsigned flush_flags = 0;
7860 
7861          uint64_t bound = dynamic_bound;
7862          while (bound) {
7863             const int i = u_bit_scan64(&bound);
7864             uint16_t high_bits = 0;
7865 
7866             struct iris_resource *res =
7867                (void *) genx->vertex_buffers[i].resource;
7868             if (res) {
7869                iris_use_pinned_bo(batch, res->bo, false, IRIS_DOMAIN_VF_READ);
7870 
7871                high_bits = res->bo->address >> 32ull;
7872                if (high_bits != ice->state.last_vbo_high_bits[i]) {
7873                   flush_flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE |
7874                                  PIPE_CONTROL_CS_STALL;
7875                   ice->state.last_vbo_high_bits[i] = high_bits;
7876                }
7877             }
7878          }
7879 
7880          if (flush_flags) {
7881             iris_emit_pipe_control_flush(batch,
7882                                          "workaround: VF cache 32-bit key [VB]",
7883                                          flush_flags);
7884          }
7885 #endif
7886 
7887          const unsigned vb_dwords = GENX(VERTEX_BUFFER_STATE_length);
7888 
7889          uint32_t *map =
7890             iris_get_command_space(batch, 4 * (1 + vb_dwords * count));
7891          _iris_pack_command(batch, GENX(3DSTATE_VERTEX_BUFFERS), map, vb) {
7892             vb.DWordLength = (vb_dwords * count + 1) - 2;
7893          }
7894          map += 1;
7895 
7896          const struct iris_vertex_element_state *cso_ve =
7897             ice->state.cso_vertex_elements;
7898 
7899          bound = dynamic_bound;
7900          while (bound) {
7901             const int i = u_bit_scan64(&bound);
7902 
7903             uint32_t vb_stride[GENX(VERTEX_BUFFER_STATE_length)];
7904             struct iris_bo *bo =
7905                iris_resource_bo(genx->vertex_buffers[i].resource);
7906             iris_pack_state(GENX(VERTEX_BUFFER_STATE), &vb_stride, vbs) {
7907                vbs.BufferPitch = cso_ve->stride[i];
7908                /* Unnecessary except to defeat the genxml nonzero checker */
7909                vbs.MOCS = iris_mocs(bo, &screen->isl_dev,
7910                                     ISL_SURF_USAGE_VERTEX_BUFFER_BIT);
7911             }
7912             for (unsigned d = 0; d < vb_dwords; d++)
7913                map[d] = genx->vertex_buffers[i].state[d] | vb_stride[d];
7914 
7915             map += vb_dwords;
7916          }
7917       }
7918    }
7919 
7920    if (dirty & IRIS_DIRTY_VERTEX_ELEMENTS) {
7921       struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
7922       const unsigned entries = MAX2(cso->count, 1);
7923       if (!(ice->state.vs_needs_sgvs_element ||
7924             ice->state.vs_uses_derived_draw_params ||
7925             ice->state.vs_needs_edge_flag)) {
7926          iris_batch_emit(batch, cso->vertex_elements, sizeof(uint32_t) *
7927                          (1 + entries * GENX(VERTEX_ELEMENT_STATE_length)));
7928       } else {
7929          uint32_t dynamic_ves[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
7930          const unsigned dyn_count = cso->count +
7931             ice->state.vs_needs_sgvs_element +
7932             ice->state.vs_uses_derived_draw_params;
7933 
7934          iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS),
7935                            &dynamic_ves, ve) {
7936             ve.DWordLength =
7937                1 + GENX(VERTEX_ELEMENT_STATE_length) * dyn_count - 2;
7938          }
7939          memcpy(&dynamic_ves[1], &cso->vertex_elements[1],
7940                 (cso->count - ice->state.vs_needs_edge_flag) *
7941                 GENX(VERTEX_ELEMENT_STATE_length) * sizeof(uint32_t));
7942          uint32_t *ve_pack_dest =
7943             &dynamic_ves[1 + (cso->count - ice->state.vs_needs_edge_flag) *
7944                          GENX(VERTEX_ELEMENT_STATE_length)];
7945 
7946          if (ice->state.vs_needs_sgvs_element) {
7947             uint32_t base_ctrl = ice->state.vs_uses_draw_params ?
7948                                  VFCOMP_STORE_SRC : VFCOMP_STORE_0;
7949             iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
7950                ve.Valid = true;
7951                ve.VertexBufferIndex =
7952                   util_bitcount64(ice->state.bound_vertex_buffers);
7953                ve.SourceElementFormat = ISL_FORMAT_R32G32_UINT;
7954                ve.Component0Control = base_ctrl;
7955                ve.Component1Control = base_ctrl;
7956                ve.Component2Control = VFCOMP_STORE_0;
7957                ve.Component3Control = VFCOMP_STORE_0;
7958             }
7959             ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
7960          }
7961          if (ice->state.vs_uses_derived_draw_params) {
7962             iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
7963                ve.Valid = true;
7964                ve.VertexBufferIndex =
7965                   util_bitcount64(ice->state.bound_vertex_buffers) +
7966                   ice->state.vs_uses_draw_params;
7967                ve.SourceElementFormat = ISL_FORMAT_R32G32_UINT;
7968                ve.Component0Control = VFCOMP_STORE_SRC;
7969                ve.Component1Control = VFCOMP_STORE_SRC;
7970                ve.Component2Control = VFCOMP_STORE_0;
7971                ve.Component3Control = VFCOMP_STORE_0;
7972             }
7973             ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
7974          }
7975          if (ice->state.vs_needs_edge_flag) {
7976             for (int i = 0; i < GENX(VERTEX_ELEMENT_STATE_length);  i++)
7977                ve_pack_dest[i] = cso->edgeflag_ve[i];
7978          }
7979 
7980          iris_batch_emit(batch, &dynamic_ves, sizeof(uint32_t) *
7981                          (1 + dyn_count * GENX(VERTEX_ELEMENT_STATE_length)));
7982       }
7983 
7984       if (!ice->state.vs_needs_edge_flag) {
7985          iris_batch_emit(batch, cso->vf_instancing, sizeof(uint32_t) *
7986                          entries * GENX(3DSTATE_VF_INSTANCING_length));
7987       } else {
7988          assert(cso->count > 0);
7989          const unsigned edgeflag_index = cso->count - 1;
7990          uint32_t dynamic_vfi[33 * GENX(3DSTATE_VF_INSTANCING_length)];
7991          memcpy(&dynamic_vfi[0], cso->vf_instancing, edgeflag_index *
7992                 GENX(3DSTATE_VF_INSTANCING_length) * sizeof(uint32_t));
7993 
7994          uint32_t *vfi_pack_dest = &dynamic_vfi[0] +
7995             edgeflag_index * GENX(3DSTATE_VF_INSTANCING_length);
7996          iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
7997             vi.VertexElementIndex = edgeflag_index +
7998                ice->state.vs_needs_sgvs_element +
7999                ice->state.vs_uses_derived_draw_params;
8000          }
8001          for (int i = 0; i < GENX(3DSTATE_VF_INSTANCING_length);  i++)
8002             vfi_pack_dest[i] |= cso->edgeflag_vfi[i];
8003 
8004          iris_batch_emit(batch, &dynamic_vfi[0], sizeof(uint32_t) *
8005                          entries * GENX(3DSTATE_VF_INSTANCING_length));
8006       }
8007    }
8008 
8009    if (dirty & IRIS_DIRTY_VF_SGVS) {
8010       const struct iris_vs_data *vs_data =
8011          iris_vs_data(ice->shaders.prog[MESA_SHADER_VERTEX]);
8012       struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
8013 
8014       iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS), sgv) {
8015          if (vs_data->uses_vertexid) {
8016             sgv.VertexIDEnable = true;
8017             sgv.VertexIDComponentNumber = 2;
8018             sgv.VertexIDElementOffset =
8019                cso->count - ice->state.vs_needs_edge_flag;
8020          }
8021 
8022          if (vs_data->uses_instanceid) {
8023             sgv.InstanceIDEnable = true;
8024             sgv.InstanceIDComponentNumber = 3;
8025             sgv.InstanceIDElementOffset =
8026                cso->count - ice->state.vs_needs_edge_flag;
8027          }
8028       }
8029    }
8030 
8031    if (dirty & IRIS_DIRTY_VF) {
8032       iris_emit_cmd(batch, GENX(3DSTATE_VF), vf) {
8033 #if GFX_VERx10 >= 125
8034          vf.GeometryDistributionEnable = true;
8035 #endif
8036          if (draw->primitive_restart) {
8037             vf.IndexedDrawCutIndexEnable = true;
8038             vf.CutIndex = draw->restart_index;
8039          }
8040       }
8041    }
8042 
8043 #if GFX_VERx10 >= 125
8044    if (dirty & IRIS_DIRTY_VFG) {
8045       iris_emit_cmd(batch, GENX(3DSTATE_VFG), vfg) {
8046          /* If 3DSTATE_TE: TE Enable == 1 then RR_STRICT else RR_FREE*/
8047          vfg.DistributionMode =
8048             ice->shaders.prog[MESA_SHADER_TESS_EVAL] != NULL ? RR_STRICT :
8049                                                                RR_FREE;
8050          vfg.DistributionGranularity = BatchLevelGranularity;
8051 #if INTEL_WA_14014851047_GFX_VER
8052          vfg.GranularityThresholdDisable =
8053             intel_needs_workaround(batch->screen->devinfo, 14014851047);
8054 #endif
8055          vfg.ListCutIndexEnable = draw->primitive_restart;
8056          /* 192 vertices for TRILIST_ADJ */
8057          vfg.ListNBatchSizeScale = 0;
8058          /* Batch size of 384 vertices */
8059          vfg.List3BatchSizeScale = 2;
8060          /* Batch size of 128 vertices */
8061          vfg.List2BatchSizeScale = 1;
8062          /* Batch size of 128 vertices */
8063          vfg.List1BatchSizeScale = 2;
8064          /* Batch size of 256 vertices for STRIP topologies */
8065          vfg.StripBatchSizeScale = 3;
8066          /* 192 control points for PATCHLIST_3 */
8067          vfg.PatchBatchSizeScale = 1;
8068          /* 192 control points for PATCHLIST_3 */
8069          vfg.PatchBatchSizeMultiplier = 31;
8070       }
8071    }
8072 #endif
8073 
8074    if (dirty & IRIS_DIRTY_VF_STATISTICS) {
8075       iris_emit_cmd(batch, GENX(3DSTATE_VF_STATISTICS), vf) {
8076          vf.StatisticsEnable = true;
8077       }
8078    }
8079 
8080 #if GFX_VER == 8
8081    if (dirty & IRIS_DIRTY_PMA_FIX) {
8082       bool enable = want_pma_fix(ice);
8083       genX(update_pma_fix)(ice, batch, enable);
8084    }
8085 #endif
8086 
8087    if (ice->state.current_hash_scale != 1)
8088       genX(emit_hashing_mode)(ice, batch, UINT_MAX, UINT_MAX, 1);
8089 
8090 #if GFX_VER >= 12
8091    genX(invalidate_aux_map_state)(batch);
8092 #endif
8093 }
8094 
8095 static void
flush_vbos(struct iris_context * ice,struct iris_batch * batch)8096 flush_vbos(struct iris_context *ice, struct iris_batch *batch)
8097 {
8098    struct iris_genx_state *genx = ice->state.genx;
8099    uint64_t bound = ice->state.bound_vertex_buffers;
8100    while (bound) {
8101       const int i = u_bit_scan64(&bound);
8102       struct iris_bo *bo = iris_resource_bo(genx->vertex_buffers[i].resource);
8103       iris_emit_buffer_barrier_for(batch, bo, IRIS_DOMAIN_VF_READ);
8104    }
8105 }
8106 
8107 static bool
point_or_line_list(enum mesa_prim prim_type)8108 point_or_line_list(enum mesa_prim prim_type)
8109 {
8110    switch (prim_type) {
8111    case MESA_PRIM_POINTS:
8112    case MESA_PRIM_LINES:
8113    case MESA_PRIM_LINE_STRIP:
8114    case MESA_PRIM_LINES_ADJACENCY:
8115    case MESA_PRIM_LINE_STRIP_ADJACENCY:
8116    case MESA_PRIM_LINE_LOOP:
8117       return true;
8118    default:
8119       return false;
8120    }
8121    return false;
8122 }
8123 
8124 void
genX(emit_breakpoint)8125 genX(emit_breakpoint)(struct iris_batch *batch, bool emit_before_draw)
8126 {
8127    struct iris_context *ice = batch->ice;
8128    uint32_t draw_count = emit_before_draw ?
8129                          p_atomic_inc_return(&ice->draw_call_count) :
8130                          p_atomic_read(&ice->draw_call_count);
8131 
8132    if (((draw_count == intel_debug_bkp_before_draw_count &&
8133          emit_before_draw) ||
8134         (draw_count == intel_debug_bkp_after_draw_count &&
8135          !emit_before_draw)))  {
8136       iris_emit_cmd(batch, GENX(MI_SEMAPHORE_WAIT), sem) {
8137          sem.WaitMode            = PollingMode;
8138          sem.CompareOperation    = COMPARE_SAD_EQUAL_SDD;
8139          sem.SemaphoreDataDword  = 0x1;
8140          sem.SemaphoreAddress    = rw_bo(batch->screen->breakpoint_bo, 0,
8141                                          IRIS_DOMAIN_OTHER_WRITE);
8142       };
8143    }
8144 }
8145 
8146 void
genX(emit_3dprimitive_was)8147 genX(emit_3dprimitive_was)(struct iris_batch *batch,
8148                            const struct pipe_draw_indirect_info *indirect,
8149                            uint32_t primitive_type,
8150                            uint32_t vertex_count)
8151 {
8152    UNUSED const struct intel_device_info *devinfo = batch->screen->devinfo;
8153    UNUSED const struct iris_context *ice = batch->ice;
8154 
8155 #if INTEL_WA_22014412737_GFX_VER || INTEL_WA_16014538804_GFX_VER
8156    if (intel_needs_workaround(devinfo, 22014412737) &&
8157        (point_or_line_list(primitive_type) || indirect ||
8158         (vertex_count == 1 || vertex_count == 2))) {
8159          iris_emit_pipe_control_write(batch, "Wa_22014412737",
8160                                       PIPE_CONTROL_WRITE_IMMEDIATE,
8161                                       batch->screen->workaround_bo,
8162                                       batch->screen->workaround_address.offset,
8163                                       0ull);
8164       batch->num_3d_primitives_emitted = 0;
8165    } else if (intel_needs_workaround(devinfo, 16014538804)) {
8166       batch->num_3d_primitives_emitted++;
8167 
8168       /* Wa_16014538804 - Send empty/dummy pipe control after 3 3DPRIMITIVE. */
8169       if (batch->num_3d_primitives_emitted == 3) {
8170          iris_emit_pipe_control_flush(batch, "Wa_16014538804", 0);
8171          batch->num_3d_primitives_emitted = 0;
8172       }
8173    }
8174 #endif
8175 }
8176 
8177 void
genX(urb_workaround)8178 genX(urb_workaround)(struct iris_batch *batch,
8179                      const struct intel_urb_config *urb_cfg)
8180 {
8181 #if INTEL_NEEDS_WA_16014912113
8182    if (intel_urb_setup_changed(urb_cfg, &batch->ice->shaders.last_urb,
8183                                MESA_SHADER_TESS_EVAL) &&
8184        batch->ice->shaders.last_urb.size[0] != 0) {
8185       for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
8186          iris_emit_cmd(batch, GENX(3DSTATE_URB_VS), urb) {
8187             urb._3DCommandSubOpcode += i;
8188             urb.VSURBStartingAddress =
8189                batch->ice->shaders.last_urb.start[i];
8190             urb.VSURBEntryAllocationSize =
8191                batch->ice->shaders.last_urb.size[i] - 1;
8192             urb.VSNumberofURBEntries = i == 0 ? 256 : 0;
8193          }
8194       }
8195       iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
8196          pc.HDCPipelineFlushEnable = true;
8197       }
8198    }
8199 #endif
8200 
8201    /* Update current urb config. */
8202    memcpy(&batch->ice->shaders.last_urb, &batch->ice->shaders.urb.cfg,
8203           sizeof(struct intel_urb_config));
8204 }
8205 
8206 static void
iris_emit_index_buffer(struct iris_context * ice,struct iris_batch * batch,const struct pipe_draw_info * draw,const struct pipe_draw_start_count_bias * sc)8207 iris_emit_index_buffer(struct iris_context *ice,
8208                        struct iris_batch *batch,
8209                        const struct pipe_draw_info *draw,
8210                        const struct pipe_draw_start_count_bias *sc)
8211 {
8212    unsigned offset;
8213 
8214    if (draw->has_user_indices) {
8215       unsigned start_offset = draw->index_size * sc->start;
8216 
8217       u_upload_data(ice->ctx.const_uploader, start_offset,
8218                     sc->count * draw->index_size, 4,
8219                     (char*)draw->index.user + start_offset,
8220                     &offset, &ice->state.last_res.index_buffer);
8221       offset -= start_offset;
8222    } else {
8223       struct iris_resource *res = (void *) draw->index.resource;
8224       res->bind_history |= PIPE_BIND_INDEX_BUFFER;
8225 
8226       pipe_resource_reference(&ice->state.last_res.index_buffer,
8227                               draw->index.resource);
8228       offset = 0;
8229 
8230       iris_emit_buffer_barrier_for(batch, res->bo, IRIS_DOMAIN_VF_READ);
8231    }
8232 
8233    struct iris_genx_state *genx = ice->state.genx;
8234    struct iris_bo *bo = iris_resource_bo(ice->state.last_res.index_buffer);
8235 
8236    uint32_t ib_packet[GENX(3DSTATE_INDEX_BUFFER_length)];
8237    iris_pack_command(GENX(3DSTATE_INDEX_BUFFER), ib_packet, ib) {
8238       ib.IndexFormat = draw->index_size >> 1;
8239       ib.MOCS = iris_mocs(bo, &batch->screen->isl_dev,
8240                           ISL_SURF_USAGE_INDEX_BUFFER_BIT);
8241       ib.BufferSize = bo->size - offset;
8242       ib.BufferStartingAddress = ro_bo(NULL, bo->address + offset);
8243 #if GFX_VER >= 12
8244       ib.L3BypassDisable       = true;
8245 #endif
8246    }
8247 
8248    if (memcmp(genx->last_index_buffer, ib_packet, sizeof(ib_packet)) != 0) {
8249       memcpy(genx->last_index_buffer, ib_packet, sizeof(ib_packet));
8250       iris_batch_emit(batch, ib_packet, sizeof(ib_packet));
8251       iris_use_pinned_bo(batch, bo, false, IRIS_DOMAIN_VF_READ);
8252    }
8253 
8254 #if GFX_VER < 11
8255    /* The VF cache key only uses 32-bits, see vertex buffer comment above */
8256    uint16_t high_bits = bo->address >> 32ull;
8257    if (high_bits != ice->state.last_index_bo_high_bits) {
8258       iris_emit_pipe_control_flush(batch,
8259                                    "workaround: VF cache 32-bit key [IB]",
8260                                    PIPE_CONTROL_VF_CACHE_INVALIDATE |
8261                                    PIPE_CONTROL_CS_STALL);
8262       ice->state.last_index_bo_high_bits = high_bits;
8263    }
8264 #endif
8265 }
8266 
8267 
8268 static void
iris_upload_render_state(struct iris_context * ice,struct iris_batch * batch,const struct pipe_draw_info * draw,unsigned drawid_offset,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * sc)8269 iris_upload_render_state(struct iris_context *ice,
8270                          struct iris_batch *batch,
8271                          const struct pipe_draw_info *draw,
8272                          unsigned drawid_offset,
8273                          const struct pipe_draw_indirect_info *indirect,
8274                          const struct pipe_draw_start_count_bias *sc)
8275 {
8276    UNUSED const struct intel_device_info *devinfo = batch->screen->devinfo;
8277    bool use_predicate = ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT;
8278 
8279    trace_intel_begin_draw(&batch->trace);
8280 
8281    if (ice->state.dirty & IRIS_DIRTY_VERTEX_BUFFER_FLUSHES)
8282       flush_vbos(ice, batch);
8283 
8284    iris_batch_sync_region_start(batch);
8285 
8286    /* Always pin the binder.  If we're emitting new binding table pointers,
8287     * we need it.  If not, we're probably inheriting old tables via the
8288     * context, and need it anyway.  Since true zero-bindings cases are
8289     * practically non-existent, just pin it and avoid last_res tracking.
8290     */
8291    iris_use_pinned_bo(batch, ice->state.binder.bo, false,
8292                       IRIS_DOMAIN_NONE);
8293 
8294    if (!batch->contains_draw) {
8295       if (GFX_VER == 12) {
8296          /* Re-emit constants when starting a new batch buffer in order to
8297           * work around push constant corruption on context switch.
8298           *
8299           * XXX - Provide hardware spec quotation when available.
8300           */
8301          ice->state.stage_dirty |= (IRIS_STAGE_DIRTY_CONSTANTS_VS  |
8302                                     IRIS_STAGE_DIRTY_CONSTANTS_TCS |
8303                                     IRIS_STAGE_DIRTY_CONSTANTS_TES |
8304                                     IRIS_STAGE_DIRTY_CONSTANTS_GS  |
8305                                     IRIS_STAGE_DIRTY_CONSTANTS_FS);
8306       }
8307       batch->contains_draw = true;
8308    }
8309 
8310    if (!batch->contains_draw_with_next_seqno) {
8311       iris_restore_render_saved_bos(ice, batch, draw);
8312       batch->contains_draw_with_next_seqno = true;
8313    }
8314 
8315    /* Wa_1306463417 - Send HS state for every primitive on gfx11.
8316     * Wa_16011107343 (same for gfx12)
8317     * We implement this by setting TCS dirty on each draw.
8318     */
8319    if ((INTEL_NEEDS_WA_1306463417 || INTEL_NEEDS_WA_16011107343) &&
8320        ice->shaders.prog[MESA_SHADER_TESS_CTRL]) {
8321       ice->state.stage_dirty |= IRIS_STAGE_DIRTY_TCS;
8322    }
8323 
8324    iris_upload_dirty_render_state(ice, batch, draw, false);
8325 
8326    if (draw->index_size > 0)
8327       iris_emit_index_buffer(ice, batch, draw, sc);
8328 
8329    if (indirect) {
8330       struct mi_builder b;
8331       uint32_t mocs;
8332       mi_builder_init(&b, batch->screen->devinfo, batch);
8333 
8334 #define _3DPRIM_END_OFFSET          0x2420
8335 #define _3DPRIM_START_VERTEX        0x2430
8336 #define _3DPRIM_VERTEX_COUNT        0x2434
8337 #define _3DPRIM_INSTANCE_COUNT      0x2438
8338 #define _3DPRIM_START_INSTANCE      0x243C
8339 #define _3DPRIM_BASE_VERTEX         0x2440
8340 
8341       if (!indirect->count_from_stream_output) {
8342          if (indirect->indirect_draw_count) {
8343             use_predicate = true;
8344 
8345             struct iris_bo *draw_count_bo =
8346                iris_resource_bo(indirect->indirect_draw_count);
8347             unsigned draw_count_offset =
8348                indirect->indirect_draw_count_offset;
8349             mocs = iris_mocs(draw_count_bo, &batch->screen->isl_dev, 0);
8350             mi_builder_set_mocs(&b, mocs);
8351 
8352             if (ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT) {
8353                /* comparison = draw id < draw count */
8354                struct mi_value comparison =
8355                   mi_ult(&b, mi_imm(drawid_offset),
8356                              mi_mem32(ro_bo(draw_count_bo, draw_count_offset)));
8357 
8358                /* predicate = comparison & conditional rendering predicate */
8359                mi_store(&b, mi_reg32(MI_PREDICATE_RESULT),
8360                             mi_iand(&b, comparison, mi_reg32(CS_GPR(15))));
8361             } else {
8362                uint32_t mi_predicate;
8363 
8364                /* Upload the id of the current primitive to MI_PREDICATE_SRC1. */
8365                mi_store(&b, mi_reg64(MI_PREDICATE_SRC1), mi_imm(drawid_offset));
8366                /* Upload the current draw count from the draw parameters buffer
8367                 * to MI_PREDICATE_SRC0. Zero the top 32-bits of
8368                 * MI_PREDICATE_SRC0.
8369                 */
8370                mi_store(&b, mi_reg64(MI_PREDICATE_SRC0),
8371                         mi_mem32(ro_bo(draw_count_bo, draw_count_offset)));
8372 
8373                if (drawid_offset == 0) {
8374                   mi_predicate = MI_PREDICATE | MI_PREDICATE_LOADOP_LOADINV |
8375                                  MI_PREDICATE_COMBINEOP_SET |
8376                                  MI_PREDICATE_COMPAREOP_SRCS_EQUAL;
8377                } else {
8378                   /* While draw_index < draw_count the predicate's result will be
8379                    *  (draw_index == draw_count) ^ TRUE = TRUE
8380                    * When draw_index == draw_count the result is
8381                    *  (TRUE) ^ TRUE = FALSE
8382                    * After this all results will be:
8383                    *  (FALSE) ^ FALSE = FALSE
8384                    */
8385                   mi_predicate = MI_PREDICATE | MI_PREDICATE_LOADOP_LOAD |
8386                                  MI_PREDICATE_COMBINEOP_XOR |
8387                                  MI_PREDICATE_COMPAREOP_SRCS_EQUAL;
8388                }
8389                iris_batch_emit(batch, &mi_predicate, sizeof(uint32_t));
8390             }
8391          }
8392          struct iris_bo *bo = iris_resource_bo(indirect->buffer);
8393          assert(bo);
8394 
8395          mocs = iris_mocs(bo, &batch->screen->isl_dev, 0);
8396          mi_builder_set_mocs(&b, mocs);
8397 
8398          mi_store(&b, mi_reg32(_3DPRIM_VERTEX_COUNT),
8399                   mi_mem32(ro_bo(bo, indirect->offset + 0)));
8400          mi_store(&b, mi_reg32(_3DPRIM_INSTANCE_COUNT),
8401                   mi_mem32(ro_bo(bo, indirect->offset + 4)));
8402          mi_store(&b, mi_reg32(_3DPRIM_START_VERTEX),
8403                   mi_mem32(ro_bo(bo, indirect->offset + 8)));
8404          if (draw->index_size) {
8405             mi_store(&b, mi_reg32(_3DPRIM_BASE_VERTEX),
8406                      mi_mem32(ro_bo(bo, indirect->offset + 12)));
8407             mi_store(&b, mi_reg32(_3DPRIM_START_INSTANCE),
8408                      mi_mem32(ro_bo(bo, indirect->offset + 16)));
8409          } else {
8410             mi_store(&b, mi_reg32(_3DPRIM_START_INSTANCE),
8411                      mi_mem32(ro_bo(bo, indirect->offset + 12)));
8412             mi_store(&b, mi_reg32(_3DPRIM_BASE_VERTEX), mi_imm(0));
8413          }
8414       } else if (indirect->count_from_stream_output) {
8415          struct iris_stream_output_target *so =
8416             (void *) indirect->count_from_stream_output;
8417          struct iris_bo *so_bo = iris_resource_bo(so->offset.res);
8418 
8419          mocs = iris_mocs(so_bo, &batch->screen->isl_dev, 0);
8420          mi_builder_set_mocs(&b, mocs);
8421 
8422          iris_emit_buffer_barrier_for(batch, so_bo, IRIS_DOMAIN_OTHER_READ);
8423 
8424          struct iris_address addr = ro_bo(so_bo, so->offset.offset);
8425          struct mi_value offset =
8426             mi_iadd_imm(&b, mi_mem32(addr), -so->base.buffer_offset);
8427          mi_store(&b, mi_reg32(_3DPRIM_VERTEX_COUNT),
8428                       mi_udiv32_imm(&b, offset, so->stride));
8429          mi_store(&b, mi_reg32(_3DPRIM_START_VERTEX), mi_imm(0));
8430          mi_store(&b, mi_reg32(_3DPRIM_BASE_VERTEX), mi_imm(0));
8431          mi_store(&b, mi_reg32(_3DPRIM_START_INSTANCE), mi_imm(0));
8432          mi_store(&b, mi_reg32(_3DPRIM_INSTANCE_COUNT),
8433                   mi_imm(draw->instance_count));
8434       }
8435    }
8436 
8437    iris_measure_snapshot(ice, batch, INTEL_SNAPSHOT_DRAW, draw, indirect, sc);
8438 
8439    genX(maybe_emit_breakpoint)(batch, true);
8440 
8441    iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
8442       prim.VertexAccessType = draw->index_size > 0 ? RANDOM : SEQUENTIAL;
8443       prim.PredicateEnable = use_predicate;
8444 #if GFX_VERx10 >= 125
8445       prim.TBIMREnable = ice->state.use_tbimr;
8446 #endif
8447       if (indirect) {
8448          prim.IndirectParameterEnable = true;
8449       } else {
8450          prim.StartInstanceLocation = draw->start_instance;
8451          prim.InstanceCount = draw->instance_count;
8452          prim.VertexCountPerInstance = sc->count;
8453 
8454          prim.StartVertexLocation = sc->start;
8455 
8456          if (draw->index_size) {
8457             prim.BaseVertexLocation += sc->index_bias;
8458          }
8459       }
8460    }
8461 
8462    genX(emit_3dprimitive_was)(batch, indirect, ice->state.prim_mode, sc->count);
8463    genX(maybe_emit_breakpoint)(batch, false);
8464 
8465    iris_batch_sync_region_end(batch);
8466 
8467    uint32_t count = (sc) ? sc->count : 0;
8468    count *= draw->instance_count ? draw->instance_count : 1;
8469    trace_intel_end_draw(&batch->trace, count);
8470 }
8471 
8472 static void
iris_upload_indirect_render_state(struct iris_context * ice,const struct pipe_draw_info * draw,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * sc)8473 iris_upload_indirect_render_state(struct iris_context *ice,
8474                                   const struct pipe_draw_info *draw,
8475                                   const struct pipe_draw_indirect_info *indirect,
8476                                   const struct pipe_draw_start_count_bias *sc)
8477 {
8478 #if GFX_VERx10 >= 125
8479    assert(indirect);
8480 
8481    struct iris_batch *batch = &ice->batches[IRIS_BATCH_RENDER];
8482    UNUSED struct iris_screen *screen = batch->screen;
8483    UNUSED const struct intel_device_info *devinfo = screen->devinfo;
8484    const bool use_predicate =
8485       ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT;
8486 
8487    trace_intel_begin_draw(&batch->trace);
8488 
8489    if (ice->state.dirty & IRIS_DIRTY_VERTEX_BUFFER_FLUSHES)
8490       flush_vbos(ice, batch);
8491 
8492    iris_batch_sync_region_start(batch);
8493 
8494    /* Always pin the binder.  If we're emitting new binding table pointers,
8495     * we need it.  If not, we're probably inheriting old tables via the
8496     * context, and need it anyway.  Since true zero-bindings cases are
8497     * practically non-existent, just pin it and avoid last_res tracking.
8498     */
8499    iris_use_pinned_bo(batch, ice->state.binder.bo, false,
8500                       IRIS_DOMAIN_NONE);
8501 
8502    if (!batch->contains_draw) {
8503       /* Re-emit constants when starting a new batch buffer in order to
8504        * work around push constant corruption on context switch.
8505        *
8506        * XXX - Provide hardware spec quotation when available.
8507        */
8508       ice->state.stage_dirty |= (IRIS_STAGE_DIRTY_CONSTANTS_VS  |
8509                                  IRIS_STAGE_DIRTY_CONSTANTS_TCS |
8510                                  IRIS_STAGE_DIRTY_CONSTANTS_TES |
8511                                  IRIS_STAGE_DIRTY_CONSTANTS_GS  |
8512                                  IRIS_STAGE_DIRTY_CONSTANTS_FS);
8513       batch->contains_draw = true;
8514    }
8515 
8516    if (!batch->contains_draw_with_next_seqno) {
8517       iris_restore_render_saved_bos(ice, batch, draw);
8518       batch->contains_draw_with_next_seqno = true;
8519    }
8520 
8521    /* Wa_1306463417 - Send HS state for every primitive on gfx11.
8522     * Wa_16011107343 (same for gfx12)
8523     * We implement this by setting TCS dirty on each draw.
8524     */
8525    if ((INTEL_NEEDS_WA_1306463417 || INTEL_NEEDS_WA_16011107343) &&
8526        ice->shaders.prog[MESA_SHADER_TESS_CTRL]) {
8527       ice->state.stage_dirty |= IRIS_STAGE_DIRTY_TCS;
8528    }
8529 
8530    iris_upload_dirty_render_state(ice, batch, draw, false);
8531 
8532    if (draw->index_size > 0)
8533       iris_emit_index_buffer(ice, batch, draw, sc);
8534 
8535    iris_measure_snapshot(ice, batch, INTEL_SNAPSHOT_DRAW, draw, indirect, sc);
8536 
8537    genX(maybe_emit_breakpoint)(batch, true);
8538 
8539    iris_emit_cmd(batch, GENX(EXECUTE_INDIRECT_DRAW), ind) {
8540       ind.ArgumentFormat             =
8541          draw->index_size > 0 ? DRAWINDEXED : DRAW;
8542       ind.PredicateEnable            = use_predicate;
8543       ind.TBIMREnabled               = ice->state.use_tbimr;
8544       ind.MaxCount                   = indirect->draw_count;
8545 
8546       if (indirect->buffer) {
8547          struct iris_bo *bo = iris_resource_bo(indirect->buffer);
8548          ind.ArgumentBufferStartAddress = ro_bo(bo, indirect->offset);
8549          ind.MOCS = iris_mocs(bo, &screen->isl_dev, 0);
8550          } else {
8551          ind.MOCS = iris_mocs(NULL, &screen->isl_dev, 0);
8552       }
8553 
8554       if (indirect->indirect_draw_count) {
8555          struct iris_bo *draw_count_bo      =
8556             iris_resource_bo(indirect->indirect_draw_count);
8557          ind.CountBufferIndirectEnable      = true;
8558          ind.CountBufferAddress             =
8559             ro_bo(draw_count_bo, indirect->indirect_draw_count_offset);
8560       }
8561    }
8562 
8563    genX(emit_3dprimitive_was)(batch, indirect, ice->state.prim_mode, sc->count);
8564    genX(maybe_emit_breakpoint)(batch, false);
8565 
8566    iris_batch_sync_region_end(batch);
8567 
8568    uint32_t count = (sc) ? sc->count : 0;
8569    count *= draw->instance_count ? draw->instance_count : 1;
8570    trace_intel_end_draw(&batch->trace, count);
8571 #else
8572    unreachable("Unsupported path");
8573 #endif /* GFX_VERx10 >= 125 */
8574 }
8575 
8576 static void
iris_upload_indirect_shader_render_state(struct iris_context * ice,const struct pipe_draw_info * draw,const struct pipe_draw_indirect_info * indirect,const struct pipe_draw_start_count_bias * sc)8577 iris_upload_indirect_shader_render_state(struct iris_context *ice,
8578                                          const struct pipe_draw_info *draw,
8579                                          const struct pipe_draw_indirect_info *indirect,
8580                                          const struct pipe_draw_start_count_bias *sc)
8581 {
8582    assert(indirect);
8583 
8584    struct iris_batch *batch = &ice->batches[IRIS_BATCH_RENDER];
8585    UNUSED struct iris_screen *screen = batch->screen;
8586    UNUSED const struct intel_device_info *devinfo = screen->devinfo;
8587 
8588    if (ice->state.dirty & IRIS_DIRTY_VERTEX_BUFFER_FLUSHES)
8589       flush_vbos(ice, batch);
8590 
8591    iris_batch_sync_region_start(batch);
8592 
8593    /* Always pin the binder.  If we're emitting new binding table pointers,
8594     * we need it.  If not, we're probably inheriting old tables via the
8595     * context, and need it anyway.  Since true zero-bindings cases are
8596     * practically non-existent, just pin it and avoid last_res tracking.
8597     */
8598    iris_use_pinned_bo(batch, ice->state.binder.bo, false,
8599                       IRIS_DOMAIN_NONE);
8600 
8601    if (!batch->contains_draw) {
8602       if (GFX_VER == 12) {
8603          /* Re-emit constants when starting a new batch buffer in order to
8604           * work around push constant corruption on context switch.
8605           *
8606           * XXX - Provide hardware spec quotation when available.
8607           */
8608          ice->state.stage_dirty |= (IRIS_STAGE_DIRTY_CONSTANTS_VS  |
8609                                     IRIS_STAGE_DIRTY_CONSTANTS_TCS |
8610                                     IRIS_STAGE_DIRTY_CONSTANTS_TES |
8611                                     IRIS_STAGE_DIRTY_CONSTANTS_GS  |
8612                                     IRIS_STAGE_DIRTY_CONSTANTS_FS);
8613       }
8614       batch->contains_draw = true;
8615    }
8616 
8617    if (!batch->contains_draw_with_next_seqno) {
8618       iris_restore_render_saved_bos(ice, batch, draw);
8619       batch->contains_draw_with_next_seqno = true;
8620    }
8621 
8622    if (draw->index_size > 0)
8623       iris_emit_index_buffer(ice, batch, draw, sc);
8624 
8625    /* Make sure we have enough space to keep all the commands in the single BO
8626     * (because of the jumps)
8627     */
8628    iris_require_command_space(batch, 2000);
8629 
8630 #ifndef NDEBUG
8631    struct iris_bo *command_bo = batch->bo;
8632 #endif
8633 
8634    /* Jump point to generate more draw if we run out of space in the ring
8635     * buffer.
8636     */
8637    uint64_t gen_addr = iris_batch_current_address_u64(batch);
8638 
8639    iris_handle_always_flush_cache(batch);
8640 
8641 #if GFX_VER == 9
8642    iris_emit_pipe_control_flush(batch, "before generation",
8643                                 PIPE_CONTROL_VF_CACHE_INVALIDATE);
8644 #endif
8645 
8646    struct iris_address params_addr;
8647    struct iris_gen_indirect_params *params =
8648       genX(emit_indirect_generate)(batch, draw, indirect, sc,
8649                                    &params_addr);
8650 
8651    iris_emit_pipe_control_flush(batch, "after generation flush",
8652                                 ((ice->state.vs_uses_draw_params ||
8653                                   ice->state.vs_uses_derived_draw_params) ?
8654                                  PIPE_CONTROL_VF_CACHE_INVALIDATE : 0) |
8655                                 PIPE_CONTROL_STALL_AT_SCOREBOARD |
8656                                 PIPE_CONTROL_DATA_CACHE_FLUSH |
8657                                 PIPE_CONTROL_CS_STALL);
8658 
8659    trace_intel_begin_draw(&batch->trace);
8660 
8661    /* Always pin the binder.  If we're emitting new binding table pointers,
8662     * we need it.  If not, we're probably inheriting old tables via the
8663     * context, and need it anyway.  Since true zero-bindings cases are
8664     * practically non-existent, just pin it and avoid last_res tracking.
8665     */
8666    iris_use_pinned_bo(batch, ice->state.binder.bo, false,
8667                       IRIS_DOMAIN_NONE);
8668 
8669    /* Wa_1306463417 - Send HS state for every primitive on gfx11.
8670     * Wa_16011107343 (same for gfx12)
8671     * We implement this by setting TCS dirty on each draw.
8672     */
8673    if ((INTEL_NEEDS_WA_1306463417 || INTEL_NEEDS_WA_16011107343) &&
8674        ice->shaders.prog[MESA_SHADER_TESS_CTRL]) {
8675       ice->state.stage_dirty |= IRIS_STAGE_DIRTY_TCS;
8676    }
8677 
8678    iris_upload_dirty_render_state(ice, batch, draw, true);
8679 
8680    iris_measure_snapshot(ice, batch, INTEL_SNAPSHOT_DRAW, draw, indirect, sc);
8681 
8682    genX(maybe_emit_breakpoint)(batch, true);
8683 
8684 #if GFX_VER >= 12
8685    iris_emit_cmd(batch, GENX(MI_ARB_CHECK), arb) {
8686       arb.PreParserDisableMask = true;
8687       arb.PreParserDisable = true;
8688    }
8689 #endif
8690 
8691    iris_emit_cmd(batch, GENX(MI_BATCH_BUFFER_START), bbs) {
8692       bbs.AddressSpaceIndicator = ASI_PPGTT;
8693       bbs.BatchBufferStartAddress = (struct iris_address) {
8694          .bo = ice->draw.generation.ring_bo,
8695       };
8696    }
8697 
8698    /* Run the ring buffer one more time with the next set of commands */
8699    uint64_t inc_addr = iris_batch_current_address_u64(batch);
8700    {
8701       iris_emit_pipe_control_flush(batch,
8702                                    "post generated draws wait",
8703                                    PIPE_CONTROL_STALL_AT_SCOREBOARD |
8704                                    PIPE_CONTROL_CS_STALL);
8705 
8706       struct mi_builder b;
8707       mi_builder_init(&b, batch->screen->devinfo, batch);
8708 
8709       struct iris_address draw_base_addr = iris_address_add(
8710          params_addr,
8711          offsetof(struct iris_gen_indirect_params, draw_base));
8712 
8713       const uint32_t mocs =
8714          iris_mocs(draw_base_addr.bo, &screen->isl_dev, 0);
8715       mi_builder_set_mocs(&b, mocs);
8716 
8717       mi_store(&b, mi_mem32(draw_base_addr),
8718                    mi_iadd(&b, mi_mem32(draw_base_addr),
8719                                mi_imm(params->ring_count)));
8720 
8721       iris_emit_pipe_control_flush(batch,
8722                                    "post generation base increment",
8723                                    PIPE_CONTROL_CS_STALL |
8724                                    PIPE_CONTROL_CONST_CACHE_INVALIDATE);
8725 
8726       iris_emit_cmd(batch, GENX(MI_BATCH_BUFFER_START), bbs) {
8727          bbs.AddressSpaceIndicator = ASI_PPGTT;
8728          bbs.BatchBufferStartAddress = (struct iris_address) {
8729             .offset = gen_addr,
8730          };
8731       }
8732    }
8733 
8734    /* Exit of the ring buffer */
8735    uint64_t end_addr = iris_batch_current_address_u64(batch);
8736 
8737 #ifndef NDEBUG
8738    assert(command_bo == batch->bo);
8739 #endif
8740 
8741    genX(emit_3dprimitive_was)(batch, indirect, ice->state.prim_mode, sc->count);
8742    genX(maybe_emit_breakpoint)(batch, false);
8743 
8744    iris_emit_pipe_control_flush(batch,
8745                                 "post generated draws wait",
8746                                 PIPE_CONTROL_STALL_AT_SCOREBOARD |
8747                                 PIPE_CONTROL_CS_STALL);
8748 
8749    params->gen_addr = inc_addr;
8750    params->end_addr = end_addr;
8751 
8752    iris_batch_sync_region_end(batch);
8753 
8754    uint32_t count = (sc) ? sc->count : 0;
8755    count *= draw->instance_count ? draw->instance_count : 1;
8756    trace_intel_end_draw(&batch->trace, count);
8757 }
8758 
8759 static void
iris_load_indirect_location(struct iris_context * ice,struct iris_batch * batch,const struct pipe_grid_info * grid)8760 iris_load_indirect_location(struct iris_context *ice,
8761                             struct iris_batch *batch,
8762                             const struct pipe_grid_info *grid)
8763 {
8764 #define GPGPU_DISPATCHDIMX 0x2500
8765 #define GPGPU_DISPATCHDIMY 0x2504
8766 #define GPGPU_DISPATCHDIMZ 0x2508
8767 
8768    assert(grid->indirect);
8769 
8770    struct iris_state_ref *grid_size = &ice->state.grid_size;
8771    struct iris_bo *bo = iris_resource_bo(grid_size->res);
8772    struct mi_builder b;
8773    mi_builder_init(&b, batch->screen->devinfo, batch);
8774    struct mi_value size_x = mi_mem32(ro_bo(bo, grid_size->offset + 0));
8775    struct mi_value size_y = mi_mem32(ro_bo(bo, grid_size->offset + 4));
8776    struct mi_value size_z = mi_mem32(ro_bo(bo, grid_size->offset + 8));
8777    mi_store(&b, mi_reg32(GPGPU_DISPATCHDIMX), size_x);
8778    mi_store(&b, mi_reg32(GPGPU_DISPATCHDIMY), size_y);
8779    mi_store(&b, mi_reg32(GPGPU_DISPATCHDIMZ), size_z);
8780 }
8781 
iris_emit_indirect_dispatch_supported(const struct intel_device_info * devinfo)8782 static bool iris_emit_indirect_dispatch_supported(const struct intel_device_info *devinfo)
8783 {
8784    // TODO: Swizzling X and Y workgroup sizes is not supported in execute indirect dispatch
8785    return devinfo->has_indirect_unroll;
8786 }
8787 
8788 #if GFX_VERx10 >= 125
8789 
iris_emit_execute_indirect_dispatch(struct iris_context * ice,struct iris_batch * batch,const struct pipe_grid_info * grid,const struct GENX (INTERFACE_DESCRIPTOR_DATA)idd)8790 static void iris_emit_execute_indirect_dispatch(struct iris_context *ice,
8791                                                 struct iris_batch *batch,
8792                                                 const struct pipe_grid_info *grid,
8793                                                 const struct GENX(INTERFACE_DESCRIPTOR_DATA) idd)
8794 {
8795    const struct iris_screen *screen = batch->screen;
8796    struct iris_compiled_shader *shader =
8797       ice->shaders.prog[MESA_SHADER_COMPUTE];
8798    const struct intel_cs_dispatch_info dispatch =
8799       iris_get_cs_dispatch_info(screen->devinfo, shader, grid->block);
8800    struct iris_bo *indirect = iris_resource_bo(grid->indirect);
8801    const int dispatch_size = dispatch.simd_size / 16;
8802 
8803    struct GENX(COMPUTE_WALKER_BODY) body = {};
8804    body.SIMDSize            = dispatch_size;
8805    body.MessageSIMD         = dispatch_size;
8806    body.LocalXMaximum       = grid->block[0] - 1;
8807    body.LocalYMaximum       = grid->block[1] - 1;
8808    body.LocalZMaximum       = grid->block[2] - 1;
8809    body.ExecutionMask       = dispatch.right_mask;
8810    body.PostSync.MOCS       = iris_mocs(NULL, &screen->isl_dev, 0);
8811    body.InterfaceDescriptor = idd;
8812 
8813    struct iris_address indirect_bo = ro_bo(indirect, grid->indirect_offset);
8814    iris_emit_cmd(batch, GENX(EXECUTE_INDIRECT_DISPATCH), ind) {
8815       ind.PredicateEnable            =
8816          ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT;
8817       ind.MaxCount                   = 1;
8818       ind.COMPUTE_WALKER_BODY        = body;
8819       ind.ArgumentBufferStartAddress = indirect_bo;
8820       ind.MOCS                       =
8821          iris_mocs(indirect_bo.bo, &screen->isl_dev, 0);
8822    }
8823 }
8824 
8825 static void
iris_upload_compute_walker(struct iris_context * ice,struct iris_batch * batch,const struct pipe_grid_info * grid)8826 iris_upload_compute_walker(struct iris_context *ice,
8827                            struct iris_batch *batch,
8828                            const struct pipe_grid_info *grid)
8829 {
8830    const uint64_t stage_dirty = ice->state.stage_dirty;
8831    struct iris_screen *screen = batch->screen;
8832    const struct intel_device_info *devinfo = screen->devinfo;
8833    struct iris_binder *binder = &ice->state.binder;
8834    struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_COMPUTE];
8835    struct iris_compiled_shader *shader =
8836       ice->shaders.prog[MESA_SHADER_COMPUTE];
8837    const struct iris_cs_data *cs_data = iris_cs_data(shader);
8838    const struct intel_cs_dispatch_info dispatch =
8839       iris_get_cs_dispatch_info(devinfo, shader, grid->block);
8840 
8841    trace_intel_begin_compute(&batch->trace);
8842 
8843    if (stage_dirty & IRIS_STAGE_DIRTY_CS) {
8844       iris_emit_cmd(batch, GENX(CFE_STATE), cfe) {
8845          cfe.MaximumNumberofThreads =
8846             devinfo->max_cs_threads * devinfo->subslice_total;
8847          uint32_t scratch_addr = pin_scratch_space(ice, batch, shader,
8848                                                    MESA_SHADER_COMPUTE);
8849          cfe.ScratchSpaceBuffer = scratch_addr >> 4;
8850       }
8851    }
8852 
8853    struct GENX(INTERFACE_DESCRIPTOR_DATA) idd = {};
8854    idd.KernelStartPointer = KSP(shader);
8855    idd.NumberofThreadsinGPGPUThreadGroup = dispatch.threads;
8856    idd.SharedLocalMemorySize =
8857       iris_encode_slm_size(GFX_VER, shader->total_shared);
8858    idd.SamplerStatePointer = shs->sampler_table.offset;
8859    idd.SamplerCount = encode_sampler_count(shader),
8860    idd.BindingTablePointer = binder->bt_offset[MESA_SHADER_COMPUTE];
8861    /* Typically set to 0 to avoid prefetching on every thread dispatch. */
8862    idd.BindingTableEntryCount = devinfo->verx10 == 125 ?
8863       0 : MIN2(shader->bt.size_bytes / 4, 31);
8864    idd.PreferredSLMAllocationSize = preferred_slm_allocation_size(devinfo);
8865    idd.NumberOfBarriers = cs_data->uses_barrier;
8866 
8867    iris_measure_snapshot(ice, batch, INTEL_SNAPSHOT_COMPUTE, NULL, NULL, NULL);
8868 
8869    if (iris_emit_indirect_dispatch_supported(devinfo) && grid->indirect) {
8870       iris_emit_execute_indirect_dispatch(ice, batch, grid, idd);
8871    } else {
8872       if (grid->indirect)
8873          iris_load_indirect_location(ice, batch, grid);
8874 
8875       iris_measure_snapshot(ice, batch, INTEL_SNAPSHOT_COMPUTE, NULL, NULL, NULL);
8876 
8877       ice->utrace.last_compute_walker =
8878          iris_emit_dwords(batch, GENX(COMPUTE_WALKER_length));
8879       _iris_pack_command(batch, GENX(COMPUTE_WALKER),
8880                          ice->utrace.last_compute_walker, cw) {
8881          cw.IndirectParameterEnable        = grid->indirect;
8882          cw.SIMDSize                       = dispatch.simd_size / 16;
8883          cw.MessageSIMD                    = dispatch.simd_size / 16;
8884          cw.LocalXMaximum                  = grid->block[0] - 1;
8885          cw.LocalYMaximum                  = grid->block[1] - 1;
8886          cw.LocalZMaximum                  = grid->block[2] - 1;
8887          cw.ThreadGroupIDXDimension        = grid->grid[0];
8888          cw.ThreadGroupIDYDimension        = grid->grid[1];
8889          cw.ThreadGroupIDZDimension        = grid->grid[2];
8890          cw.ExecutionMask                  = dispatch.right_mask;
8891          cw.PostSync.MOCS                  = iris_mocs(NULL, &screen->isl_dev, 0);
8892          cw.InterfaceDescriptor            = idd;
8893 
8894 #if GFX_VERx10 >= 125
8895          cw.GenerateLocalID = cs_data->generate_local_id != 0;
8896          cw.EmitLocal       = cs_data->generate_local_id;
8897          cw.WalkOrder       = cs_data->walk_order;
8898          cw.TileLayout = cs_data->walk_order == INTEL_WALK_ORDER_YXZ ?
8899                          TileY32bpe : Linear;
8900 #endif
8901 
8902          assert(iris_cs_push_const_total_size(shader, dispatch.threads) == 0);
8903       }
8904    }
8905 
8906    trace_intel_end_compute(&batch->trace, grid->grid[0], grid->grid[1], grid->grid[2]);
8907 }
8908 
8909 #else /* #if GFX_VERx10 >= 125 */
8910 
8911 static void
iris_upload_gpgpu_walker(struct iris_context * ice,struct iris_batch * batch,const struct pipe_grid_info * grid)8912 iris_upload_gpgpu_walker(struct iris_context *ice,
8913                          struct iris_batch *batch,
8914                          const struct pipe_grid_info *grid)
8915 {
8916    const uint64_t stage_dirty = ice->state.stage_dirty;
8917    struct iris_screen *screen = batch->screen;
8918    const struct intel_device_info *devinfo = screen->devinfo;
8919    struct iris_binder *binder = &ice->state.binder;
8920    struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_COMPUTE];
8921    struct iris_uncompiled_shader *ish =
8922       ice->shaders.uncompiled[MESA_SHADER_COMPUTE];
8923    struct iris_compiled_shader *shader =
8924       ice->shaders.prog[MESA_SHADER_COMPUTE];
8925    struct iris_cs_data *cs_data = iris_cs_data(shader);
8926    const struct intel_cs_dispatch_info dispatch =
8927       iris_get_cs_dispatch_info(screen->devinfo, shader, grid->block);
8928 
8929    trace_intel_begin_compute(&batch->trace);
8930 
8931    if ((stage_dirty & IRIS_STAGE_DIRTY_CS) ||
8932        cs_data->local_size[0] == 0 /* Variable local group size */) {
8933       /* The MEDIA_VFE_STATE documentation for Gfx8+ says:
8934        *
8935        *   "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
8936        *    the only bits that are changed are scoreboard related: Scoreboard
8937        *    Enable, Scoreboard Type, Scoreboard Mask, Scoreboard Delta.  For
8938        *    these scoreboard related states, a MEDIA_STATE_FLUSH is
8939        *    sufficient."
8940        */
8941       iris_emit_pipe_control_flush(batch,
8942                                    "workaround: stall before MEDIA_VFE_STATE",
8943                                    PIPE_CONTROL_CS_STALL);
8944 
8945       iris_emit_cmd(batch, GENX(MEDIA_VFE_STATE), vfe) {
8946          if (shader->total_scratch) {
8947             uint32_t scratch_addr =
8948                pin_scratch_space(ice, batch, shader, MESA_SHADER_COMPUTE);
8949 
8950             vfe.PerThreadScratchSpace = ffs(shader->total_scratch) - 11;
8951             vfe.ScratchSpaceBasePointer =
8952                rw_bo(NULL, scratch_addr, IRIS_DOMAIN_NONE);
8953          }
8954 
8955          vfe.MaximumNumberofThreads =
8956             devinfo->max_cs_threads * devinfo->subslice_total - 1;
8957 #if GFX_VER < 11
8958          vfe.ResetGatewayTimer =
8959             Resettingrelativetimerandlatchingtheglobaltimestamp;
8960 #endif
8961 #if GFX_VER == 8
8962          vfe.BypassGatewayControl = true;
8963 #endif
8964          vfe.NumberofURBEntries = 2;
8965          vfe.URBEntryAllocationSize = 2;
8966 
8967          vfe.CURBEAllocationSize =
8968             ALIGN(cs_data->push.per_thread.regs * dispatch.threads +
8969                   cs_data->push.cross_thread.regs, 2);
8970       }
8971    }
8972 
8973    /* TODO: Combine subgroup-id with cbuf0 so we can push regular uniforms */
8974    if ((stage_dirty & IRIS_STAGE_DIRTY_CS) ||
8975        cs_data->local_size[0] == 0 /* Variable local group size */) {
8976       uint32_t curbe_data_offset = 0;
8977       assert(cs_data->push.cross_thread.dwords == 0 &&
8978              cs_data->push.per_thread.dwords == 1 &&
8979              cs_data->first_param_is_builtin_subgroup_id);
8980       const unsigned push_const_size =
8981          iris_cs_push_const_total_size(shader, dispatch.threads);
8982       uint32_t *curbe_data_map =
8983          stream_state(batch, ice->state.dynamic_uploader,
8984                       &ice->state.last_res.cs_thread_ids,
8985                       ALIGN(push_const_size, 64), 64,
8986                       &curbe_data_offset);
8987       assert(curbe_data_map);
8988       memset(curbe_data_map, 0x5a, ALIGN(push_const_size, 64));
8989       iris_fill_cs_push_const_buffer(screen, shader, dispatch.threads,
8990                                      curbe_data_map);
8991 
8992       iris_emit_cmd(batch, GENX(MEDIA_CURBE_LOAD), curbe) {
8993          curbe.CURBETotalDataLength = ALIGN(push_const_size, 64);
8994          curbe.CURBEDataStartAddress = curbe_data_offset;
8995       }
8996    }
8997 
8998    for (unsigned i = 0; i < IRIS_MAX_GLOBAL_BINDINGS; i++) {
8999       struct pipe_resource *res = ice->state.global_bindings[i];
9000       if (!res)
9001          break;
9002 
9003       iris_use_pinned_bo(batch, iris_resource_bo(res),
9004                          true, IRIS_DOMAIN_NONE);
9005    }
9006 
9007    if (stage_dirty & (IRIS_STAGE_DIRTY_SAMPLER_STATES_CS |
9008                       IRIS_STAGE_DIRTY_BINDINGS_CS |
9009                       IRIS_STAGE_DIRTY_CONSTANTS_CS |
9010                       IRIS_STAGE_DIRTY_CS)) {
9011       uint32_t desc[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
9012 
9013       iris_pack_state(GENX(INTERFACE_DESCRIPTOR_DATA), desc, idd) {
9014          idd.SharedLocalMemorySize =
9015             iris_encode_slm_size(GFX_VER, ish->kernel_shared_size + grid->variable_shared_mem);
9016          idd.KernelStartPointer =
9017             KSP(shader) + iris_cs_data_prog_offset(cs_data, dispatch.simd_size);
9018          idd.SamplerStatePointer = shs->sampler_table.offset;
9019          idd.BindingTablePointer =
9020             binder->bt_offset[MESA_SHADER_COMPUTE] >> IRIS_BT_OFFSET_SHIFT;
9021          idd.NumberofThreadsinGPGPUThreadGroup = dispatch.threads;
9022       }
9023 
9024       for (int i = 0; i < GENX(INTERFACE_DESCRIPTOR_DATA_length); i++)
9025          desc[i] |= ((uint32_t *) shader->derived_data)[i];
9026 
9027       iris_emit_cmd(batch, GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), load) {
9028          load.InterfaceDescriptorTotalLength =
9029             GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
9030          load.InterfaceDescriptorDataStartAddress =
9031             emit_state(batch, ice->state.dynamic_uploader,
9032                        &ice->state.last_res.cs_desc, desc, sizeof(desc), 64);
9033       }
9034    }
9035 
9036    if (grid->indirect)
9037       iris_load_indirect_location(ice, batch, grid);
9038 
9039    iris_measure_snapshot(ice, batch, INTEL_SNAPSHOT_COMPUTE, NULL, NULL, NULL);
9040 
9041    iris_emit_cmd(batch, GENX(GPGPU_WALKER), ggw) {
9042       ggw.IndirectParameterEnable    = grid->indirect != NULL;
9043       ggw.SIMDSize                   = dispatch.simd_size / 16;
9044       ggw.ThreadDepthCounterMaximum  = 0;
9045       ggw.ThreadHeightCounterMaximum = 0;
9046       ggw.ThreadWidthCounterMaximum  = dispatch.threads - 1;
9047       ggw.ThreadGroupIDXDimension    = grid->grid[0];
9048       ggw.ThreadGroupIDYDimension    = grid->grid[1];
9049       ggw.ThreadGroupIDZDimension    = grid->grid[2];
9050       ggw.RightExecutionMask         = dispatch.right_mask;
9051       ggw.BottomExecutionMask        = 0xffffffff;
9052    }
9053 
9054    iris_emit_cmd(batch, GENX(MEDIA_STATE_FLUSH), msf);
9055 
9056    trace_intel_end_compute(&batch->trace, grid->grid[0], grid->grid[1], grid->grid[2]);
9057 }
9058 
9059 #endif /* #if GFX_VERx10 >= 125 */
9060 
9061 static void
iris_upload_compute_state(struct iris_context * ice,struct iris_batch * batch,const struct pipe_grid_info * grid)9062 iris_upload_compute_state(struct iris_context *ice,
9063                           struct iris_batch *batch,
9064                           const struct pipe_grid_info *grid)
9065 {
9066    struct iris_screen *screen = batch->screen;
9067    const uint64_t stage_dirty = ice->state.stage_dirty;
9068    struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_COMPUTE];
9069    struct iris_compiled_shader *shader =
9070       ice->shaders.prog[MESA_SHADER_COMPUTE];
9071    struct iris_border_color_pool *border_color_pool =
9072       iris_bufmgr_get_border_color_pool(screen->bufmgr);
9073 
9074    iris_batch_sync_region_start(batch);
9075 
9076    /* Always pin the binder.  If we're emitting new binding table pointers,
9077     * we need it.  If not, we're probably inheriting old tables via the
9078     * context, and need it anyway.  Since true zero-bindings cases are
9079     * practically non-existent, just pin it and avoid last_res tracking.
9080     */
9081    iris_use_pinned_bo(batch, ice->state.binder.bo, false, IRIS_DOMAIN_NONE);
9082 
9083    if (((stage_dirty & IRIS_STAGE_DIRTY_CONSTANTS_CS) &&
9084         shs->sysvals_need_upload) ||
9085        shader->kernel_input_size > 0)
9086       upload_sysvals(ice, MESA_SHADER_COMPUTE, grid);
9087 
9088    if (stage_dirty & IRIS_STAGE_DIRTY_BINDINGS_CS)
9089       iris_populate_binding_table(ice, batch, MESA_SHADER_COMPUTE, false);
9090 
9091    if (stage_dirty & IRIS_STAGE_DIRTY_SAMPLER_STATES_CS)
9092       iris_upload_sampler_states(ice, MESA_SHADER_COMPUTE);
9093 
9094    iris_use_optional_res(batch, shs->sampler_table.res, false,
9095                          IRIS_DOMAIN_NONE);
9096    iris_use_pinned_bo(batch, iris_resource_bo(shader->assembly.res), false,
9097                       IRIS_DOMAIN_NONE);
9098 
9099    if (ice->state.need_border_colors)
9100       iris_use_pinned_bo(batch, border_color_pool->bo, false,
9101                          IRIS_DOMAIN_NONE);
9102 
9103 #if GFX_VER >= 12
9104    genX(invalidate_aux_map_state)(batch);
9105 #endif
9106 
9107 #if GFX_VERx10 >= 125
9108    iris_upload_compute_walker(ice, batch, grid);
9109 #else
9110    iris_upload_gpgpu_walker(ice, batch, grid);
9111 #endif
9112 
9113    if (!batch->contains_draw_with_next_seqno) {
9114       iris_restore_compute_saved_bos(ice, batch, grid);
9115       batch->contains_draw_with_next_seqno = batch->contains_draw = true;
9116    }
9117 
9118    iris_batch_sync_region_end(batch);
9119 }
9120 
9121 /**
9122  * State module teardown.
9123  */
9124 static void
iris_destroy_state(struct iris_context * ice)9125 iris_destroy_state(struct iris_context *ice)
9126 {
9127    struct iris_genx_state *genx = ice->state.genx;
9128 
9129    pipe_resource_reference(&ice->state.pixel_hashing_tables, NULL);
9130 
9131    pipe_resource_reference(&ice->draw.draw_params.res, NULL);
9132    pipe_resource_reference(&ice->draw.derived_draw_params.res, NULL);
9133    pipe_resource_reference(&ice->draw.generation.params.res, NULL);
9134    pipe_resource_reference(&ice->draw.generation.vertices.res, NULL);
9135 
9136    /* Loop over all VBOs, including ones for draw parameters */
9137    for (unsigned i = 0; i < ARRAY_SIZE(genx->vertex_buffers); i++) {
9138       pipe_resource_reference(&genx->vertex_buffers[i].resource, NULL);
9139    }
9140 
9141    free(ice->state.genx);
9142 
9143    for (int i = 0; i < 4; i++) {
9144       pipe_so_target_reference(&ice->state.so_target[i], NULL);
9145    }
9146 
9147    util_unreference_framebuffer_state(&ice->state.framebuffer);
9148 
9149    for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
9150       struct iris_shader_state *shs = &ice->state.shaders[stage];
9151       pipe_resource_reference(&shs->sampler_table.res, NULL);
9152       for (int i = 0; i < PIPE_MAX_CONSTANT_BUFFERS; i++) {
9153          pipe_resource_reference(&shs->constbuf[i].buffer, NULL);
9154          pipe_resource_reference(&shs->constbuf_surf_state[i].res, NULL);
9155       }
9156       for (int i = 0; i < PIPE_MAX_SHADER_IMAGES; i++) {
9157          pipe_resource_reference(&shs->image[i].base.resource, NULL);
9158          pipe_resource_reference(&shs->image[i].surface_state.ref.res, NULL);
9159          free(shs->image[i].surface_state.cpu);
9160       }
9161       for (int i = 0; i < PIPE_MAX_SHADER_BUFFERS; i++) {
9162          pipe_resource_reference(&shs->ssbo[i].buffer, NULL);
9163          pipe_resource_reference(&shs->ssbo_surf_state[i].res, NULL);
9164       }
9165       for (int i = 0; i < IRIS_MAX_TEXTURES; i++) {
9166          pipe_sampler_view_reference((struct pipe_sampler_view **)
9167                                      &shs->textures[i], NULL);
9168       }
9169    }
9170 
9171    pipe_resource_reference(&ice->state.grid_size.res, NULL);
9172    pipe_resource_reference(&ice->state.grid_surf_state.res, NULL);
9173 
9174    pipe_resource_reference(&ice->state.null_fb.res, NULL);
9175    pipe_resource_reference(&ice->state.unbound_tex.res, NULL);
9176 
9177    pipe_resource_reference(&ice->state.last_res.cc_vp, NULL);
9178    pipe_resource_reference(&ice->state.last_res.sf_cl_vp, NULL);
9179    pipe_resource_reference(&ice->state.last_res.color_calc, NULL);
9180    pipe_resource_reference(&ice->state.last_res.scissor, NULL);
9181    pipe_resource_reference(&ice->state.last_res.blend, NULL);
9182    pipe_resource_reference(&ice->state.last_res.index_buffer, NULL);
9183    pipe_resource_reference(&ice->state.last_res.cs_thread_ids, NULL);
9184    pipe_resource_reference(&ice->state.last_res.cs_desc, NULL);
9185 }
9186 
9187 /* ------------------------------------------------------------------- */
9188 
9189 static void
iris_rebind_buffer(struct iris_context * ice,struct iris_resource * res)9190 iris_rebind_buffer(struct iris_context *ice,
9191                    struct iris_resource *res)
9192 {
9193    struct pipe_context *ctx = &ice->ctx;
9194    struct iris_genx_state *genx = ice->state.genx;
9195 
9196    assert(res->base.b.target == PIPE_BUFFER);
9197 
9198    /* Buffers can't be framebuffer attachments, nor display related,
9199     * and we don't have upstream Clover support.
9200     */
9201    assert(!(res->bind_history & (PIPE_BIND_DEPTH_STENCIL |
9202                                  PIPE_BIND_RENDER_TARGET |
9203                                  PIPE_BIND_BLENDABLE |
9204                                  PIPE_BIND_DISPLAY_TARGET |
9205                                  PIPE_BIND_CURSOR |
9206                                  PIPE_BIND_COMPUTE_RESOURCE |
9207                                  PIPE_BIND_GLOBAL)));
9208 
9209    if (res->bind_history & PIPE_BIND_VERTEX_BUFFER) {
9210       uint64_t bound_vbs = ice->state.bound_vertex_buffers;
9211       while (bound_vbs) {
9212          const int i = u_bit_scan64(&bound_vbs);
9213          struct iris_vertex_buffer_state *state = &genx->vertex_buffers[i];
9214 
9215          /* Update the CPU struct */
9216          STATIC_ASSERT(GENX(VERTEX_BUFFER_STATE_BufferStartingAddress_start) == 32);
9217          STATIC_ASSERT(GENX(VERTEX_BUFFER_STATE_BufferStartingAddress_bits) == 64);
9218          uint64_t *addr = (uint64_t *) &state->state[1];
9219          struct iris_bo *bo = iris_resource_bo(state->resource);
9220 
9221          if (*addr != bo->address + state->offset) {
9222             *addr = bo->address + state->offset;
9223             ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS |
9224                                 IRIS_DIRTY_VERTEX_BUFFER_FLUSHES;
9225          }
9226       }
9227    }
9228 
9229    /* We don't need to handle PIPE_BIND_INDEX_BUFFER here: we re-emit
9230     * the 3DSTATE_INDEX_BUFFER packet whenever the address changes.
9231     *
9232     * There is also no need to handle these:
9233     * - PIPE_BIND_COMMAND_ARGS_BUFFER (emitted for every indirect draw)
9234     * - PIPE_BIND_QUERY_BUFFER (no persistent state references)
9235     */
9236 
9237    if (res->bind_history & PIPE_BIND_STREAM_OUTPUT) {
9238       uint32_t *so_buffers = genx->so_buffers;
9239       for (unsigned i = 0; i < 4; i++,
9240            so_buffers += GENX(3DSTATE_SO_BUFFER_length)) {
9241 
9242          /* There are no other fields in bits 127:64 */
9243          uint64_t *addr = (uint64_t *) &so_buffers[2];
9244          STATIC_ASSERT(GENX(3DSTATE_SO_BUFFER_SurfaceBaseAddress_start) == 66);
9245          STATIC_ASSERT(GENX(3DSTATE_SO_BUFFER_SurfaceBaseAddress_bits) == 46);
9246 
9247          struct pipe_stream_output_target *tgt = ice->state.so_target[i];
9248          if (tgt) {
9249             struct iris_bo *bo = iris_resource_bo(tgt->buffer);
9250             if (*addr != bo->address + tgt->buffer_offset) {
9251                *addr = bo->address + tgt->buffer_offset;
9252                ice->state.dirty |= IRIS_DIRTY_SO_BUFFERS;
9253             }
9254          }
9255       }
9256    }
9257 
9258    for (int s = MESA_SHADER_VERTEX; s < MESA_SHADER_STAGES; s++) {
9259       struct iris_shader_state *shs = &ice->state.shaders[s];
9260       enum pipe_shader_type p_stage = stage_to_pipe(s);
9261 
9262       if (!(res->bind_stages & (1 << s)))
9263          continue;
9264 
9265       if (res->bind_history & PIPE_BIND_CONSTANT_BUFFER) {
9266          /* Skip constant buffer 0, it's for regular uniforms, not UBOs */
9267          uint32_t bound_cbufs = shs->bound_cbufs & ~1u;
9268          while (bound_cbufs) {
9269             const int i = u_bit_scan(&bound_cbufs);
9270             struct pipe_shader_buffer *cbuf = &shs->constbuf[i];
9271             struct iris_state_ref *surf_state = &shs->constbuf_surf_state[i];
9272 
9273             if (res->bo == iris_resource_bo(cbuf->buffer)) {
9274                pipe_resource_reference(&surf_state->res, NULL);
9275                shs->dirty_cbufs |= 1u << i;
9276                ice->state.dirty |= (IRIS_DIRTY_RENDER_MISC_BUFFER_FLUSHES |
9277                                     IRIS_DIRTY_COMPUTE_MISC_BUFFER_FLUSHES);
9278                ice->state.stage_dirty |= IRIS_STAGE_DIRTY_CONSTANTS_VS << s;
9279             }
9280          }
9281       }
9282 
9283       if (res->bind_history & PIPE_BIND_SHADER_BUFFER) {
9284          uint32_t bound_ssbos = shs->bound_ssbos;
9285          while (bound_ssbos) {
9286             const int i = u_bit_scan(&bound_ssbos);
9287             struct pipe_shader_buffer *ssbo = &shs->ssbo[i];
9288 
9289             if (res->bo == iris_resource_bo(ssbo->buffer)) {
9290                struct pipe_shader_buffer buf = {
9291                   .buffer = &res->base.b,
9292                   .buffer_offset = ssbo->buffer_offset,
9293                   .buffer_size = ssbo->buffer_size,
9294                };
9295                iris_set_shader_buffers(ctx, p_stage, i, 1, &buf,
9296                                        (shs->writable_ssbos >> i) & 1);
9297             }
9298          }
9299       }
9300 
9301       if (res->bind_history & PIPE_BIND_SAMPLER_VIEW) {
9302          int i;
9303          BITSET_FOREACH_SET(i, shs->bound_sampler_views, IRIS_MAX_TEXTURES) {
9304             struct iris_sampler_view *isv = shs->textures[i];
9305             struct iris_bo *bo = isv->res->bo;
9306 
9307             if (update_surface_state_addrs(ice->state.surface_uploader,
9308                                            &isv->surface_state, bo)) {
9309                ice->state.stage_dirty |= IRIS_STAGE_DIRTY_BINDINGS_VS << s;
9310             }
9311          }
9312       }
9313 
9314       if (res->bind_history & PIPE_BIND_SHADER_IMAGE) {
9315          uint64_t bound_image_views = shs->bound_image_views;
9316          while (bound_image_views) {
9317             const int i = u_bit_scan64(&bound_image_views);
9318             struct iris_image_view *iv = &shs->image[i];
9319             struct iris_bo *bo = iris_resource_bo(iv->base.resource);
9320 
9321             if (update_surface_state_addrs(ice->state.surface_uploader,
9322                                            &iv->surface_state, bo)) {
9323                ice->state.stage_dirty |= IRIS_STAGE_DIRTY_BINDINGS_VS << s;
9324             }
9325          }
9326       }
9327    }
9328 }
9329 
9330 /* ------------------------------------------------------------------- */
9331 
9332 /**
9333  * Introduce a batch synchronization boundary, and update its cache coherency
9334  * status to reflect the execution of a PIPE_CONTROL command with the
9335  * specified flags.
9336  */
9337 static void
batch_mark_sync_for_pipe_control(struct iris_batch * batch,uint32_t flags)9338 batch_mark_sync_for_pipe_control(struct iris_batch *batch, uint32_t flags)
9339 {
9340    const struct intel_device_info *devinfo = batch->screen->devinfo;
9341 
9342    iris_batch_sync_boundary(batch);
9343 
9344    if ((flags & PIPE_CONTROL_CS_STALL)) {
9345       if ((flags & PIPE_CONTROL_RENDER_TARGET_FLUSH))
9346          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_RENDER_WRITE);
9347 
9348       if ((flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH))
9349          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_DEPTH_WRITE);
9350 
9351       if ((flags & PIPE_CONTROL_TILE_CACHE_FLUSH)) {
9352          /* A tile cache flush makes any C/Z data in L3 visible to memory. */
9353          const unsigned c = IRIS_DOMAIN_RENDER_WRITE;
9354          const unsigned z = IRIS_DOMAIN_DEPTH_WRITE;
9355          batch->coherent_seqnos[c][c] = batch->l3_coherent_seqnos[c];
9356          batch->coherent_seqnos[z][z] = batch->l3_coherent_seqnos[z];
9357       }
9358 
9359       if (flags & (PIPE_CONTROL_FLUSH_HDC | PIPE_CONTROL_DATA_CACHE_FLUSH)) {
9360          /* HDC and DC flushes both flush the data cache out to L3 */
9361          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_DATA_WRITE);
9362       }
9363 
9364       if ((flags & PIPE_CONTROL_DATA_CACHE_FLUSH)) {
9365          /* A DC flush also flushes L3 data cache lines out to memory. */
9366          const unsigned i = IRIS_DOMAIN_DATA_WRITE;
9367          batch->coherent_seqnos[i][i] = batch->l3_coherent_seqnos[i];
9368       }
9369 
9370       if ((flags & PIPE_CONTROL_FLUSH_ENABLE))
9371          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_OTHER_WRITE);
9372 
9373       if ((flags & (PIPE_CONTROL_CACHE_FLUSH_BITS |
9374                     PIPE_CONTROL_STALL_AT_SCOREBOARD))) {
9375          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_VF_READ);
9376          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_SAMPLER_READ);
9377          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_PULL_CONSTANT_READ);
9378          iris_batch_mark_flush_sync(batch, IRIS_DOMAIN_OTHER_READ);
9379       }
9380    }
9381 
9382    if ((flags & PIPE_CONTROL_RENDER_TARGET_FLUSH))
9383       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_RENDER_WRITE);
9384 
9385    if ((flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH))
9386       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_DEPTH_WRITE);
9387 
9388    if (flags & (PIPE_CONTROL_FLUSH_HDC | PIPE_CONTROL_DATA_CACHE_FLUSH))
9389       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_DATA_WRITE);
9390 
9391    if ((flags & PIPE_CONTROL_FLUSH_ENABLE))
9392       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_OTHER_WRITE);
9393 
9394    if ((flags & PIPE_CONTROL_VF_CACHE_INVALIDATE))
9395       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_VF_READ);
9396 
9397    if ((flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE))
9398       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_SAMPLER_READ);
9399 
9400    /* Technically, to invalidate IRIS_DOMAIN_PULL_CONSTANT_READ, we need
9401     * both "Constant Cache Invalidate" and either "Texture Cache Invalidate"
9402     * or "Data Cache Flush" set, depending on the setting of
9403     * iris_indirect_ubos_use_sampler().
9404     *
9405     * However, "Data Cache Flush" and "Constant Cache Invalidate" will never
9406     * appear in the same PIPE_CONTROL command, because one is bottom-of-pipe
9407     * while the other is top-of-pipe.  Because we only look at one flush at
9408     * a time, we won't see both together.
9409     *
9410     * To deal with this, we mark it as invalidated when the constant cache
9411     * is invalidated, and trust the callers to also flush the other related
9412     * cache correctly at the same time.
9413     */
9414    if ((flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE))
9415       iris_batch_mark_invalidate_sync(batch, IRIS_DOMAIN_PULL_CONSTANT_READ);
9416 
9417    /* IRIS_DOMAIN_OTHER_READ no longer uses any caches. */
9418 
9419    if ((flags & PIPE_CONTROL_L3_RO_INVALIDATE_BITS) == PIPE_CONTROL_L3_RO_INVALIDATE_BITS) {
9420       /* If we just invalidated the read-only lines of L3, then writes from non-L3-coherent
9421        * domains will now be visible to those L3 clients.
9422        */
9423       for (unsigned i = 0; i < NUM_IRIS_DOMAINS; i++) {
9424          if (!iris_domain_is_l3_coherent(devinfo, i))
9425             batch->l3_coherent_seqnos[i] = batch->coherent_seqnos[i][i];
9426       }
9427    }
9428 }
9429 
9430 static unsigned
flags_to_post_sync_op(uint32_t flags)9431 flags_to_post_sync_op(uint32_t flags)
9432 {
9433    if (flags & PIPE_CONTROL_WRITE_IMMEDIATE)
9434       return WriteImmediateData;
9435 
9436    if (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT)
9437       return WritePSDepthCount;
9438 
9439    if (flags & PIPE_CONTROL_WRITE_TIMESTAMP)
9440       return WriteTimestamp;
9441 
9442    return 0;
9443 }
9444 
9445 /**
9446  * Do the given flags have a Post Sync or LRI Post Sync operation?
9447  */
9448 static enum pipe_control_flags
get_post_sync_flags(enum pipe_control_flags flags)9449 get_post_sync_flags(enum pipe_control_flags flags)
9450 {
9451    flags &= PIPE_CONTROL_WRITE_IMMEDIATE |
9452             PIPE_CONTROL_WRITE_DEPTH_COUNT |
9453             PIPE_CONTROL_WRITE_TIMESTAMP |
9454             PIPE_CONTROL_LRI_POST_SYNC_OP;
9455 
9456    /* Only one "Post Sync Op" is allowed, and it's mutually exclusive with
9457     * "LRI Post Sync Operation".  So more than one bit set would be illegal.
9458     */
9459    assert(util_bitcount(flags) <= 1);
9460 
9461    return flags;
9462 }
9463 
9464 #define IS_COMPUTE_PIPELINE(batch) (batch->name == IRIS_BATCH_COMPUTE)
9465 
9466 /**
9467  * Emit a series of PIPE_CONTROL commands, taking into account any
9468  * workarounds necessary to actually accomplish the caller's request.
9469  *
9470  * Unless otherwise noted, spec quotations in this function come from:
9471  *
9472  * Synchronization of the 3D Pipeline > PIPE_CONTROL Command > Programming
9473  * Restrictions for PIPE_CONTROL.
9474  *
9475  * You should not use this function directly.  Use the helpers in
9476  * iris_pipe_control.c instead, which may split the pipe control further.
9477  */
9478 static void
iris_emit_raw_pipe_control(struct iris_batch * batch,const char * reason,uint32_t flags,struct iris_bo * bo,uint32_t offset,uint64_t imm)9479 iris_emit_raw_pipe_control(struct iris_batch *batch,
9480                            const char *reason,
9481                            uint32_t flags,
9482                            struct iris_bo *bo,
9483                            uint32_t offset,
9484                            uint64_t imm)
9485 {
9486    UNUSED const struct intel_device_info *devinfo = batch->screen->devinfo;
9487    enum pipe_control_flags post_sync_flags = get_post_sync_flags(flags);
9488    enum pipe_control_flags non_lri_post_sync_flags =
9489       post_sync_flags & ~PIPE_CONTROL_LRI_POST_SYNC_OP;
9490 
9491 #if GFX_VER >= 12
9492    if (batch->name == IRIS_BATCH_BLITTER) {
9493       batch_mark_sync_for_pipe_control(batch, flags);
9494       iris_batch_sync_region_start(batch);
9495 
9496       assert(!(flags & PIPE_CONTROL_WRITE_DEPTH_COUNT));
9497 
9498       /* Wa_16018063123 - emit fast color dummy blit before MI_FLUSH_DW. */
9499       if (intel_needs_workaround(batch->screen->devinfo, 16018063123))
9500          batch_emit_fast_color_dummy_blit(batch);
9501 
9502       /* The blitter doesn't actually use PIPE_CONTROL; rather it uses the
9503        * MI_FLUSH_DW command.  However, all of our code is set up to flush
9504        * via emitting a pipe control, so we just translate it at this point,
9505        * even if it is a bit hacky.
9506        */
9507       iris_emit_cmd(batch, GENX(MI_FLUSH_DW), fd) {
9508          fd.Address = rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE);
9509          fd.ImmediateData = imm;
9510          fd.PostSyncOperation = flags_to_post_sync_op(flags);
9511 #if GFX_VERx10 >= 125
9512          /* TODO: This may not always be necessary */
9513          fd.FlushCCS = true;
9514 #endif
9515       }
9516       iris_batch_sync_region_end(batch);
9517       return;
9518    }
9519 #endif
9520 
9521    /* The "L3 Read Only Cache Invalidation Bit" docs say it "controls the
9522     * invalidation of the Geometry streams cached in L3 cache at the top
9523     * of the pipe".  In other words, index & vertex data that gets cached
9524     * in L3 when VERTEX_BUFFER_STATE::L3BypassDisable is set.
9525     *
9526     * Normally, invalidating L1/L2 read-only caches also invalidate their
9527     * related L3 cachelines, but this isn't the case for the VF cache.
9528     * Emulate it by setting the L3 Read Only bit when doing a VF invalidate.
9529     */
9530    if (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE)
9531       flags |= PIPE_CONTROL_L3_READ_ONLY_CACHE_INVALIDATE;
9532 
9533    /* Recursive PIPE_CONTROL workarounds --------------------------------
9534     * (http://knowyourmeme.com/memes/xzibit-yo-dawg)
9535     *
9536     * We do these first because we want to look at the original operation,
9537     * rather than any workarounds we set.
9538     */
9539    if (GFX_VER == 9 && (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE)) {
9540       /* The PIPE_CONTROL "VF Cache Invalidation Enable" bit description
9541        * lists several workarounds:
9542        *
9543        *    "Project: SKL, KBL, BXT
9544        *
9545        *     If the VF Cache Invalidation Enable is set to a 1 in a
9546        *     PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields
9547        *     sets to 0, with the VF Cache Invalidation Enable set to 0
9548        *     needs to be sent prior to the PIPE_CONTROL with VF Cache
9549        *     Invalidation Enable set to a 1."
9550        */
9551       iris_emit_raw_pipe_control(batch,
9552                                  "workaround: recursive VF cache invalidate",
9553                                  0, NULL, 0, 0);
9554    }
9555 
9556    if (GFX_VER == 9 && IS_COMPUTE_PIPELINE(batch) && post_sync_flags) {
9557       /* Project: SKL / Argument: LRI Post Sync Operation [23]
9558        *
9559        * "PIPECONTROL command with “Command Streamer Stall Enable” must be
9560        *  programmed prior to programming a PIPECONTROL command with "LRI
9561        *  Post Sync Operation" in GPGPU mode of operation (i.e when
9562        *  PIPELINE_SELECT command is set to GPGPU mode of operation)."
9563        *
9564        * The same text exists a few rows below for Post Sync Op.
9565        */
9566       iris_emit_raw_pipe_control(batch,
9567                                  "workaround: CS stall before gpgpu post-sync",
9568                                  PIPE_CONTROL_CS_STALL, bo, offset, imm);
9569    }
9570 
9571    /* "Flush Types" workarounds ---------------------------------------------
9572     * We do these now because they may add post-sync operations or CS stalls.
9573     */
9574 
9575    if (GFX_VER < 11 && flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) {
9576       /* Project: BDW, SKL+ (stopping at CNL) / Argument: VF Invalidate
9577        *
9578        * "'Post Sync Operation' must be enabled to 'Write Immediate Data' or
9579        *  'Write PS Depth Count' or 'Write Timestamp'."
9580        */
9581       if (!bo) {
9582          flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
9583          post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
9584          non_lri_post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
9585          bo = batch->screen->workaround_address.bo;
9586          offset = batch->screen->workaround_address.offset;
9587       }
9588    }
9589 
9590    if (flags & PIPE_CONTROL_DEPTH_STALL) {
9591       /* From the PIPE_CONTROL instruction table, bit 13 (Depth Stall Enable):
9592        *
9593        *    "This bit must be DISABLED for operations other than writing
9594        *     PS_DEPTH_COUNT."
9595        *
9596        * This seems like nonsense.  An Ivybridge workaround requires us to
9597        * emit a PIPE_CONTROL with a depth stall and write immediate post-sync
9598        * operation.  Gfx8+ requires us to emit depth stalls and depth cache
9599        * flushes together.  So, it's hard to imagine this means anything other
9600        * than "we originally intended this to be used for PS_DEPTH_COUNT".
9601        *
9602        * We ignore the supposed restriction and do nothing.
9603        */
9604    }
9605 
9606    if (flags & (PIPE_CONTROL_RENDER_TARGET_FLUSH |
9607                 PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
9608       /* From the PIPE_CONTROL instruction table, bit 12 and bit 1:
9609        *
9610        *    "This bit must be DISABLED for End-of-pipe (Read) fences,
9611        *     PS_DEPTH_COUNT or TIMESTAMP queries."
9612        *
9613        * TODO: Implement end-of-pipe checking.
9614        */
9615       assert(!(post_sync_flags & (PIPE_CONTROL_WRITE_DEPTH_COUNT |
9616                                   PIPE_CONTROL_WRITE_TIMESTAMP)));
9617    }
9618 
9619    if (GFX_VER < 11 && (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
9620       /* From the PIPE_CONTROL instruction table, bit 1:
9621        *
9622        *    "This bit is ignored if Depth Stall Enable is set.
9623        *     Further, the render cache is not flushed even if Write Cache
9624        *     Flush Enable bit is set."
9625        *
9626        * We assert that the caller doesn't do this combination, to try and
9627        * prevent mistakes.  It shouldn't hurt the GPU, though.
9628        *
9629        * We skip this check on Gfx11+ as the "Stall at Pixel Scoreboard"
9630        * and "Render Target Flush" combo is explicitly required for BTI
9631        * update workarounds.
9632        */
9633       assert(!(flags & (PIPE_CONTROL_DEPTH_STALL |
9634                         PIPE_CONTROL_RENDER_TARGET_FLUSH)));
9635    }
9636 
9637    /* PIPE_CONTROL page workarounds ------------------------------------- */
9638 
9639    if (GFX_VER <= 8 && (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE)) {
9640       /* From the PIPE_CONTROL page itself:
9641        *
9642        *    "IVB, HSW, BDW
9643        *     Restriction: Pipe_control with CS-stall bit set must be issued
9644        *     before a pipe-control command that has the State Cache
9645        *     Invalidate bit set."
9646        */
9647       flags |= PIPE_CONTROL_CS_STALL;
9648    }
9649 
9650    if (flags & PIPE_CONTROL_FLUSH_LLC) {
9651       /* From the PIPE_CONTROL instruction table, bit 26 (Flush LLC):
9652        *
9653        *    "Project: ALL
9654        *     SW must always program Post-Sync Operation to "Write Immediate
9655        *     Data" when Flush LLC is set."
9656        *
9657        * For now, we just require the caller to do it.
9658        */
9659       assert(flags & PIPE_CONTROL_WRITE_IMMEDIATE);
9660    }
9661 
9662    /* Emulate a HDC flush with a full Data Cache Flush on older hardware which
9663     * doesn't support the new lightweight flush.
9664     */
9665 #if GFX_VER < 12
9666       if (flags & PIPE_CONTROL_FLUSH_HDC)
9667          flags |= PIPE_CONTROL_DATA_CACHE_FLUSH;
9668 #endif
9669 
9670    /* "Post-Sync Operation" workarounds -------------------------------- */
9671 
9672    /* Project: All / Argument: Global Snapshot Count Reset [19]
9673     *
9674     * "This bit must not be exercised on any product.
9675     *  Requires stall bit ([20] of DW1) set."
9676     *
9677     * We don't use this, so we just assert that it isn't used.  The
9678     * PIPE_CONTROL instruction page indicates that they intended this
9679     * as a debug feature and don't think it is useful in production,
9680     * but it may actually be usable, should we ever want to.
9681     */
9682    assert((flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) == 0);
9683 
9684    if (flags & (PIPE_CONTROL_MEDIA_STATE_CLEAR |
9685                 PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE)) {
9686       /* Project: All / Arguments:
9687        *
9688        * - Generic Media State Clear [16]
9689        * - Indirect State Pointers Disable [16]
9690        *
9691        *    "Requires stall bit ([20] of DW1) set."
9692        *
9693        * Also, the PIPE_CONTROL instruction table, bit 16 (Generic Media
9694        * State Clear) says:
9695        *
9696        *    "PIPECONTROL command with “Command Streamer Stall Enable” must be
9697        *     programmed prior to programming a PIPECONTROL command with "Media
9698        *     State Clear" set in GPGPU mode of operation"
9699        *
9700        * This is a subset of the earlier rule, so there's nothing to do.
9701        */
9702       flags |= PIPE_CONTROL_CS_STALL;
9703    }
9704 
9705    if (flags & PIPE_CONTROL_STORE_DATA_INDEX) {
9706       /* Project: All / Argument: Store Data Index
9707        *
9708        * "Post-Sync Operation ([15:14] of DW1) must be set to something other
9709        *  than '0'."
9710        *
9711        * For now, we just assert that the caller does this.  We might want to
9712        * automatically add a write to the workaround BO...
9713        */
9714       assert(non_lri_post_sync_flags != 0);
9715    }
9716 
9717    if (flags & PIPE_CONTROL_SYNC_GFDT) {
9718       /* Project: All / Argument: Sync GFDT
9719        *
9720        * "Post-Sync Operation ([15:14] of DW1) must be set to something other
9721        *  than '0' or 0x2520[13] must be set."
9722        *
9723        * For now, we just assert that the caller does this.
9724        */
9725       assert(non_lri_post_sync_flags != 0);
9726    }
9727 
9728    if (flags & PIPE_CONTROL_TLB_INVALIDATE) {
9729       /* Project: IVB+ / Argument: TLB inv
9730        *
9731        *    "Requires stall bit ([20] of DW1) set."
9732        *
9733        * Also, from the PIPE_CONTROL instruction table:
9734        *
9735        *    "Project: SKL+
9736        *     Post Sync Operation or CS stall must be set to ensure a TLB
9737        *     invalidation occurs.  Otherwise no cycle will occur to the TLB
9738        *     cache to invalidate."
9739        *
9740        * This is not a subset of the earlier rule, so there's nothing to do.
9741        */
9742       flags |= PIPE_CONTROL_CS_STALL;
9743    }
9744 
9745    if (GFX_VER == 9 && devinfo->gt == 4) {
9746       /* TODO: The big Skylake GT4 post sync op workaround */
9747    }
9748 
9749    /* "GPGPU specific workarounds" (both post-sync and flush) ------------ */
9750 
9751    if (IS_COMPUTE_PIPELINE(batch)) {
9752       if ((GFX_VER == 9 || GFX_VER == 11) &&
9753           (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE)) {
9754          /* Project: SKL, ICL / Argument: Tex Invalidate
9755           * "Requires stall bit ([20] of DW) set for all GPGPU Workloads."
9756           */
9757          flags |= PIPE_CONTROL_CS_STALL;
9758       }
9759 
9760       if (GFX_VER == 8 && (post_sync_flags ||
9761                            (flags & (PIPE_CONTROL_NOTIFY_ENABLE |
9762                                      PIPE_CONTROL_DEPTH_STALL |
9763                                      PIPE_CONTROL_RENDER_TARGET_FLUSH |
9764                                      PIPE_CONTROL_DEPTH_CACHE_FLUSH |
9765                                      PIPE_CONTROL_DATA_CACHE_FLUSH)))) {
9766          /* Project: BDW / Arguments:
9767           *
9768           * - LRI Post Sync Operation   [23]
9769           * - Post Sync Op              [15:14]
9770           * - Notify En                 [8]
9771           * - Depth Stall               [13]
9772           * - Render Target Cache Flush [12]
9773           * - Depth Cache Flush         [0]
9774           * - DC Flush Enable           [5]
9775           *
9776           *    "Requires stall bit ([20] of DW) set for all GPGPU and Media
9777           *     Workloads."
9778           */
9779          flags |= PIPE_CONTROL_CS_STALL;
9780 
9781          /* Also, from the PIPE_CONTROL instruction table, bit 20:
9782           *
9783           *    "Project: BDW
9784           *     This bit must be always set when PIPE_CONTROL command is
9785           *     programmed by GPGPU and MEDIA workloads, except for the cases
9786           *     when only Read Only Cache Invalidation bits are set (State
9787           *     Cache Invalidation Enable, Instruction cache Invalidation
9788           *     Enable, Texture Cache Invalidation Enable, Constant Cache
9789           *     Invalidation Enable). This is to WA FFDOP CG issue, this WA
9790           *     need not implemented when FF_DOP_CG is disable via "Fixed
9791           *     Function DOP Clock Gate Disable" bit in RC_PSMI_CTRL register."
9792           *
9793           * It sounds like we could avoid CS stalls in some cases, but we
9794           * don't currently bother.  This list isn't exactly the list above,
9795           * either...
9796           */
9797       }
9798    }
9799 
9800    /* "Stall" workarounds ----------------------------------------------
9801     * These have to come after the earlier ones because we may have added
9802     * some additional CS stalls above.
9803     */
9804 
9805    if (GFX_VER < 9 && (flags & PIPE_CONTROL_CS_STALL)) {
9806       /* Project: PRE-SKL, VLV, CHV
9807        *
9808        * "[All Stepping][All SKUs]:
9809        *
9810        *  One of the following must also be set:
9811        *
9812        *  - Render Target Cache Flush Enable ([12] of DW1)
9813        *  - Depth Cache Flush Enable ([0] of DW1)
9814        *  - Stall at Pixel Scoreboard ([1] of DW1)
9815        *  - Depth Stall ([13] of DW1)
9816        *  - Post-Sync Operation ([13] of DW1)
9817        *  - DC Flush Enable ([5] of DW1)"
9818        *
9819        * If we don't already have one of those bits set, we choose to add
9820        * "Stall at Pixel Scoreboard".  Some of the other bits require a
9821        * CS stall as a workaround (see above), which would send us into
9822        * an infinite recursion of PIPE_CONTROLs.  "Stall at Pixel Scoreboard"
9823        * appears to be safe, so we choose that.
9824        */
9825       const uint32_t wa_bits = PIPE_CONTROL_RENDER_TARGET_FLUSH |
9826                                PIPE_CONTROL_DEPTH_CACHE_FLUSH |
9827                                PIPE_CONTROL_WRITE_IMMEDIATE |
9828                                PIPE_CONTROL_WRITE_DEPTH_COUNT |
9829                                PIPE_CONTROL_WRITE_TIMESTAMP |
9830                                PIPE_CONTROL_STALL_AT_SCOREBOARD |
9831                                PIPE_CONTROL_DEPTH_STALL |
9832                                PIPE_CONTROL_DATA_CACHE_FLUSH;
9833       if (!(flags & wa_bits))
9834          flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
9835    }
9836 
9837    if (INTEL_NEEDS_WA_1409600907 && (flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH)) {
9838       /* Wa_1409600907:
9839        *
9840        * "PIPE_CONTROL with Depth Stall Enable bit must be set
9841        * with any PIPE_CONTROL with Depth Flush Enable bit set.
9842        */
9843       flags |= PIPE_CONTROL_DEPTH_STALL;
9844    }
9845 
9846    /* Wa_14014966230: For COMPUTE Workload - Any PIPE_CONTROL command with
9847     * POST_SYNC Operation Enabled MUST be preceded by a PIPE_CONTROL
9848     * with CS_STALL Bit set (with No POST_SYNC ENABLED)
9849     */
9850    if (intel_device_info_is_adln(devinfo) &&
9851        IS_COMPUTE_PIPELINE(batch) &&
9852        flags_to_post_sync_op(flags) != NoWrite) {
9853       iris_emit_raw_pipe_control(batch, "Wa_14014966230",
9854                                  PIPE_CONTROL_CS_STALL, NULL, 0, 0);
9855    }
9856 
9857    batch_mark_sync_for_pipe_control(batch, flags);
9858 
9859 #if INTEL_NEEDS_WA_14010840176
9860    /* "If the intention of “constant cache invalidate” is
9861     *  to invalidate the L1 cache (which can cache constants), use “HDC
9862     *  pipeline flush” instead of Constant Cache invalidate command."
9863     *
9864     * "If L3 invalidate is needed, the w/a should be to set state invalidate
9865     * in the pipe control command, in addition to the HDC pipeline flush."
9866     */
9867    if (flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE) {
9868       flags &= ~PIPE_CONTROL_CONST_CACHE_INVALIDATE;
9869       flags |= PIPE_CONTROL_FLUSH_HDC | PIPE_CONTROL_STATE_CACHE_INVALIDATE;
9870    }
9871 #endif
9872 
9873    /* Emit --------------------------------------------------------------- */
9874 
9875    if (INTEL_DEBUG(DEBUG_PIPE_CONTROL)) {
9876       fprintf(stderr,
9877               "  PC [%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%"PRIx64"]: %s\n",
9878               (flags & PIPE_CONTROL_FLUSH_ENABLE) ? "PipeCon " : "",
9879               (flags & PIPE_CONTROL_CS_STALL) ? "CS " : "",
9880               (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD) ? "Scoreboard " : "",
9881               (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) ? "VF " : "",
9882               (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH) ? "RT " : "",
9883               (flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE) ? "Const " : "",
9884               (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE) ? "TC " : "",
9885               (flags & PIPE_CONTROL_DATA_CACHE_FLUSH) ? "DC " : "",
9886               (flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH) ? "ZFlush " : "",
9887               (flags & PIPE_CONTROL_TILE_CACHE_FLUSH) ? "Tile " : "",
9888               (flags & PIPE_CONTROL_CCS_CACHE_FLUSH) ? "CCS " : "",
9889               (flags & PIPE_CONTROL_DEPTH_STALL) ? "ZStall " : "",
9890               (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE) ? "State " : "",
9891               (flags & PIPE_CONTROL_TLB_INVALIDATE) ? "TLB " : "",
9892               (flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE) ? "Inst " : "",
9893               (flags & PIPE_CONTROL_MEDIA_STATE_CLEAR) ? "MediaClear " : "",
9894               (flags & PIPE_CONTROL_NOTIFY_ENABLE) ? "Notify " : "",
9895               (flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) ?
9896                  "SnapRes" : "",
9897               (flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE) ?
9898                   "ISPDis" : "",
9899               (flags & PIPE_CONTROL_WRITE_IMMEDIATE) ? "WriteImm " : "",
9900               (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT) ? "WriteZCount " : "",
9901               (flags & PIPE_CONTROL_WRITE_TIMESTAMP) ? "WriteTimestamp " : "",
9902               (flags & PIPE_CONTROL_FLUSH_HDC) ? "HDC " : "",
9903               (flags & PIPE_CONTROL_PSS_STALL_SYNC) ? "PSS " : "",
9904               (flags & PIPE_CONTROL_UNTYPED_DATAPORT_CACHE_FLUSH) ? "UntypedDataPortCache " : "",
9905               imm, reason);
9906    }
9907 
9908    iris_batch_sync_region_start(batch);
9909 
9910    const bool trace_pc =
9911       (flags & (PIPE_CONTROL_CACHE_FLUSH_BITS | PIPE_CONTROL_CACHE_INVALIDATE_BITS)) != 0;
9912 
9913    if (trace_pc)
9914       trace_intel_begin_stall(&batch->trace);
9915 
9916    iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
9917 #if GFX_VERx10 >= 125
9918       pc.PSSStallSyncEnable = flags & PIPE_CONTROL_PSS_STALL_SYNC;
9919 #endif
9920 #if GFX_VER == 12
9921       pc.TileCacheFlushEnable = flags & PIPE_CONTROL_TILE_CACHE_FLUSH;
9922 #endif
9923 #if GFX_VER > 11
9924       pc.HDCPipelineFlushEnable = flags & PIPE_CONTROL_FLUSH_HDC;
9925 #endif
9926 #if GFX_VERx10 >= 125
9927       pc.UntypedDataPortCacheFlushEnable =
9928          (flags & (PIPE_CONTROL_UNTYPED_DATAPORT_CACHE_FLUSH |
9929                    PIPE_CONTROL_FLUSH_HDC |
9930                    PIPE_CONTROL_DATA_CACHE_FLUSH)) &&
9931          IS_COMPUTE_PIPELINE(batch);
9932       pc.HDCPipelineFlushEnable |= pc.UntypedDataPortCacheFlushEnable;
9933       pc.CCSFlushEnable |= flags & PIPE_CONTROL_CCS_CACHE_FLUSH;
9934 #endif
9935       pc.LRIPostSyncOperation = NoLRIOperation;
9936       pc.PipeControlFlushEnable = flags & PIPE_CONTROL_FLUSH_ENABLE;
9937       pc.DCFlushEnable = flags & PIPE_CONTROL_DATA_CACHE_FLUSH;
9938       pc.StoreDataIndex = 0;
9939       pc.CommandStreamerStallEnable = flags & PIPE_CONTROL_CS_STALL;
9940 #if GFX_VERx10 < 125
9941       pc.GlobalSnapshotCountReset =
9942          flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET;
9943 #endif
9944       pc.TLBInvalidate = flags & PIPE_CONTROL_TLB_INVALIDATE;
9945 #if GFX_VERx10 < 200
9946       pc.GenericMediaStateClear = flags & PIPE_CONTROL_MEDIA_STATE_CLEAR;
9947 #endif
9948       pc.StallAtPixelScoreboard = flags & PIPE_CONTROL_STALL_AT_SCOREBOARD;
9949       pc.RenderTargetCacheFlushEnable =
9950          flags & PIPE_CONTROL_RENDER_TARGET_FLUSH;
9951       pc.DepthCacheFlushEnable = flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH;
9952       pc.StateCacheInvalidationEnable =
9953          flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE;
9954 #if GFX_VER >= 12
9955       pc.L3ReadOnlyCacheInvalidationEnable =
9956          flags & PIPE_CONTROL_L3_READ_ONLY_CACHE_INVALIDATE;
9957 #endif
9958       pc.VFCacheInvalidationEnable = flags & PIPE_CONTROL_VF_CACHE_INVALIDATE;
9959       pc.ConstantCacheInvalidationEnable =
9960          flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE;
9961       pc.PostSyncOperation = flags_to_post_sync_op(flags);
9962       pc.DepthStallEnable = flags & PIPE_CONTROL_DEPTH_STALL;
9963       pc.InstructionCacheInvalidateEnable =
9964          flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE;
9965       pc.NotifyEnable = flags & PIPE_CONTROL_NOTIFY_ENABLE;
9966       pc.IndirectStatePointersDisable =
9967          flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE;
9968       pc.TextureCacheInvalidationEnable =
9969          flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
9970       pc.Address = rw_bo(bo, offset, IRIS_DOMAIN_OTHER_WRITE);
9971       pc.ImmediateData = imm;
9972    }
9973 
9974    if (trace_pc) {
9975       trace_intel_end_stall(&batch->trace, flags,
9976                             iris_utrace_pipe_flush_bit_to_ds_stall_flag,
9977                             reason);
9978    }
9979 
9980    iris_batch_sync_region_end(batch);
9981 }
9982 
9983 #if GFX_VER == 9
9984 /**
9985  * Preemption on Gfx9 has to be enabled or disabled in various cases.
9986  *
9987  * See these workarounds for preemption:
9988  *  - WaDisableMidObjectPreemptionForGSLineStripAdj
9989  *  - WaDisableMidObjectPreemptionForTrifanOrPolygon
9990  *  - WaDisableMidObjectPreemptionForLineLoop
9991  *  - WA#0798
9992  *
9993  * We don't put this in the vtable because it's only used on Gfx9.
9994  */
9995 void
gfx9_toggle_preemption(struct iris_context * ice,struct iris_batch * batch,const struct pipe_draw_info * draw)9996 gfx9_toggle_preemption(struct iris_context *ice,
9997                        struct iris_batch *batch,
9998                        const struct pipe_draw_info *draw)
9999 {
10000    struct iris_genx_state *genx = ice->state.genx;
10001    bool object_preemption = true;
10002 
10003    /* WaDisableMidObjectPreemptionForGSLineStripAdj
10004     *
10005     *    "WA: Disable mid-draw preemption when draw-call is a linestrip_adj
10006     *     and GS is enabled."
10007     */
10008    if (draw->mode == MESA_PRIM_LINE_STRIP_ADJACENCY &&
10009        ice->shaders.prog[MESA_SHADER_GEOMETRY])
10010       object_preemption = false;
10011 
10012    /* WaDisableMidObjectPreemptionForTrifanOrPolygon
10013     *
10014     *    "TriFan miscompare in Execlist Preemption test. Cut index that is
10015     *     on a previous context. End the previous, the resume another context
10016     *     with a tri-fan or polygon, and the vertex count is corrupted. If we
10017     *     prempt again we will cause corruption.
10018     *
10019     *     WA: Disable mid-draw preemption when draw-call has a tri-fan."
10020     */
10021    if (draw->mode == MESA_PRIM_TRIANGLE_FAN)
10022       object_preemption = false;
10023 
10024    /* WaDisableMidObjectPreemptionForLineLoop
10025     *
10026     *    "VF Stats Counters Missing a vertex when preemption enabled.
10027     *
10028     *     WA: Disable mid-draw preemption when the draw uses a lineloop
10029     *     topology."
10030     */
10031    if (draw->mode == MESA_PRIM_LINE_LOOP)
10032       object_preemption = false;
10033 
10034    /* WA#0798
10035     *
10036     *    "VF is corrupting GAFS data when preempted on an instance boundary
10037     *     and replayed with instancing enabled.
10038     *
10039     *     WA: Disable preemption when using instanceing."
10040     */
10041    if (draw->instance_count > 1)
10042       object_preemption = false;
10043 
10044    if (genx->object_preemption != object_preemption) {
10045       iris_enable_obj_preemption(batch, object_preemption);
10046       genx->object_preemption = object_preemption;
10047    }
10048 }
10049 #endif
10050 
10051 static void
iris_lost_genx_state(struct iris_context * ice,struct iris_batch * batch)10052 iris_lost_genx_state(struct iris_context *ice, struct iris_batch *batch)
10053 {
10054    struct iris_genx_state *genx = ice->state.genx;
10055 
10056 #if INTEL_NEEDS_WA_1808121037
10057    genx->depth_reg_mode = IRIS_DEPTH_REG_MODE_UNKNOWN;
10058 #endif
10059 
10060    memset(genx->last_index_buffer, 0, sizeof(genx->last_index_buffer));
10061 }
10062 
10063 static void
iris_emit_mi_report_perf_count(struct iris_batch * batch,struct iris_bo * bo,uint32_t offset_in_bytes,uint32_t report_id)10064 iris_emit_mi_report_perf_count(struct iris_batch *batch,
10065                                struct iris_bo *bo,
10066                                uint32_t offset_in_bytes,
10067                                uint32_t report_id)
10068 {
10069    iris_batch_sync_region_start(batch);
10070    iris_emit_cmd(batch, GENX(MI_REPORT_PERF_COUNT), mi_rpc) {
10071       mi_rpc.MemoryAddress = rw_bo(bo, offset_in_bytes,
10072                                    IRIS_DOMAIN_OTHER_WRITE);
10073       mi_rpc.ReportID = report_id;
10074    }
10075    iris_batch_sync_region_end(batch);
10076 }
10077 
10078 /**
10079  * Update the pixel hashing modes that determine the balancing of PS threads
10080  * across subslices and slices.
10081  *
10082  * \param width Width bound of the rendering area (already scaled down if \p
10083  *              scale is greater than 1).
10084  * \param height Height bound of the rendering area (already scaled down if \p
10085  *               scale is greater than 1).
10086  * \param scale The number of framebuffer samples that could potentially be
10087  *              affected by an individual channel of the PS thread.  This is
10088  *              typically one for single-sampled rendering, but for operations
10089  *              like CCS resolves and fast clears a single PS invocation may
10090  *              update a huge number of pixels, in which case a finer
10091  *              balancing is desirable in order to maximally utilize the
10092  *              bandwidth available.  UINT_MAX can be used as shorthand for
10093  *              "finest hashing mode available".
10094  */
10095 void
genX(emit_hashing_mode)10096 genX(emit_hashing_mode)(struct iris_context *ice, struct iris_batch *batch,
10097                         unsigned width, unsigned height, unsigned scale)
10098 {
10099 #if GFX_VER == 9
10100    const struct intel_device_info *devinfo = batch->screen->devinfo;
10101    const unsigned slice_hashing[] = {
10102       /* Because all Gfx9 platforms with more than one slice require
10103        * three-way subslice hashing, a single "normal" 16x16 slice hashing
10104        * block is guaranteed to suffer from substantial imbalance, with one
10105        * subslice receiving twice as much work as the other two in the
10106        * slice.
10107        *
10108        * The performance impact of that would be particularly severe when
10109        * three-way hashing is also in use for slice balancing (which is the
10110        * case for all Gfx9 GT4 platforms), because one of the slices
10111        * receives one every three 16x16 blocks in either direction, which
10112        * is roughly the periodicity of the underlying subslice imbalance
10113        * pattern ("roughly" because in reality the hardware's
10114        * implementation of three-way hashing doesn't do exact modulo 3
10115        * arithmetic, which somewhat decreases the magnitude of this effect
10116        * in practice).  This leads to a systematic subslice imbalance
10117        * within that slice regardless of the size of the primitive.  The
10118        * 32x32 hashing mode guarantees that the subslice imbalance within a
10119        * single slice hashing block is minimal, largely eliminating this
10120        * effect.
10121        */
10122       _32x32,
10123       /* Finest slice hashing mode available. */
10124       NORMAL
10125    };
10126    const unsigned subslice_hashing[] = {
10127       /* 16x16 would provide a slight cache locality benefit especially
10128        * visible in the sampler L1 cache efficiency of low-bandwidth
10129        * non-LLC platforms, but it comes at the cost of greater subslice
10130        * imbalance for primitives of dimensions approximately intermediate
10131        * between 16x4 and 16x16.
10132        */
10133       _16x4,
10134       /* Finest subslice hashing mode available. */
10135       _8x4
10136    };
10137    /* Dimensions of the smallest hashing block of a given hashing mode.  If
10138     * the rendering area is smaller than this there can't possibly be any
10139     * benefit from switching to this mode, so we optimize out the
10140     * transition.
10141     */
10142    const unsigned min_size[][2] = {
10143       { 16, 4 },
10144       { 8, 4 }
10145    };
10146    const unsigned idx = scale > 1;
10147 
10148    if (width > min_size[idx][0] || height > min_size[idx][1]) {
10149       iris_emit_raw_pipe_control(batch,
10150                                  "workaround: CS stall before GT_MODE LRI",
10151                                  PIPE_CONTROL_STALL_AT_SCOREBOARD |
10152                                  PIPE_CONTROL_CS_STALL,
10153                                  NULL, 0, 0);
10154 
10155       iris_emit_reg(batch, GENX(GT_MODE), reg) {
10156          reg.SliceHashing = (devinfo->num_slices > 1 ? slice_hashing[idx] : 0);
10157          reg.SliceHashingMask = (devinfo->num_slices > 1 ? -1 : 0);
10158          reg.SubsliceHashing = subslice_hashing[idx];
10159          reg.SubsliceHashingMask = -1;
10160       };
10161 
10162       ice->state.current_hash_scale = scale;
10163    }
10164 #endif
10165 }
10166 
10167 static void
iris_set_frontend_noop(struct pipe_context * ctx,bool enable)10168 iris_set_frontend_noop(struct pipe_context *ctx, bool enable)
10169 {
10170    struct iris_context *ice = (struct iris_context *) ctx;
10171 
10172    if (iris_batch_prepare_noop(&ice->batches[IRIS_BATCH_RENDER], enable)) {
10173       ice->state.dirty |= IRIS_ALL_DIRTY_FOR_RENDER;
10174       ice->state.stage_dirty |= IRIS_ALL_STAGE_DIRTY_FOR_RENDER;
10175    }
10176 
10177    if (iris_batch_prepare_noop(&ice->batches[IRIS_BATCH_COMPUTE], enable)) {
10178       ice->state.dirty |= IRIS_ALL_DIRTY_FOR_COMPUTE;
10179       ice->state.stage_dirty |= IRIS_ALL_STAGE_DIRTY_FOR_COMPUTE;
10180    }
10181 }
10182 
10183 void
genX(init_screen_state)10184 genX(init_screen_state)(struct iris_screen *screen)
10185 {
10186    assert(screen->devinfo->verx10 == GFX_VERx10);
10187    screen->vtbl.destroy_state = iris_destroy_state;
10188    screen->vtbl.init_render_context = iris_init_render_context;
10189    screen->vtbl.init_compute_context = iris_init_compute_context;
10190    screen->vtbl.init_copy_context = iris_init_copy_context;
10191    screen->vtbl.upload_render_state = iris_upload_render_state;
10192    screen->vtbl.upload_indirect_render_state = iris_upload_indirect_render_state;
10193    screen->vtbl.upload_indirect_shader_render_state = iris_upload_indirect_shader_render_state;
10194    screen->vtbl.update_binder_address = iris_update_binder_address;
10195    screen->vtbl.upload_compute_state = iris_upload_compute_state;
10196    screen->vtbl.emit_raw_pipe_control = iris_emit_raw_pipe_control;
10197    screen->vtbl.rewrite_compute_walker_pc = iris_rewrite_compute_walker_pc;
10198    screen->vtbl.emit_mi_report_perf_count = iris_emit_mi_report_perf_count;
10199    screen->vtbl.rebind_buffer = iris_rebind_buffer;
10200    screen->vtbl.load_register_reg32 = iris_load_register_reg32;
10201    screen->vtbl.load_register_reg64 = iris_load_register_reg64;
10202    screen->vtbl.load_register_imm32 = iris_load_register_imm32;
10203    screen->vtbl.load_register_imm64 = iris_load_register_imm64;
10204    screen->vtbl.load_register_mem32 = iris_load_register_mem32;
10205    screen->vtbl.load_register_mem64 = iris_load_register_mem64;
10206    screen->vtbl.store_register_mem32 = iris_store_register_mem32;
10207    screen->vtbl.store_register_mem64 = iris_store_register_mem64;
10208    screen->vtbl.store_data_imm32 = iris_store_data_imm32;
10209    screen->vtbl.store_data_imm64 = iris_store_data_imm64;
10210    screen->vtbl.copy_mem_mem = iris_copy_mem_mem;
10211    screen->vtbl.derived_program_state_size = iris_derived_program_state_size;
10212    screen->vtbl.store_derived_program_state = iris_store_derived_program_state;
10213    screen->vtbl.create_so_decl_list = iris_create_so_decl_list;
10214    screen->vtbl.populate_vs_key = iris_populate_vs_key;
10215    screen->vtbl.populate_tcs_key = iris_populate_tcs_key;
10216    screen->vtbl.populate_tes_key = iris_populate_tes_key;
10217    screen->vtbl.populate_gs_key = iris_populate_gs_key;
10218    screen->vtbl.populate_fs_key = iris_populate_fs_key;
10219    screen->vtbl.populate_cs_key = iris_populate_cs_key;
10220    screen->vtbl.lost_genx_state = iris_lost_genx_state;
10221    screen->vtbl.disable_rhwo_optimization = iris_disable_rhwo_optimization;
10222 }
10223 
10224 void
genX(init_state)10225 genX(init_state)(struct iris_context *ice)
10226 {
10227    struct pipe_context *ctx = &ice->ctx;
10228    struct iris_screen *screen = (struct iris_screen *)ctx->screen;
10229 
10230    ctx->create_blend_state = iris_create_blend_state;
10231    ctx->create_depth_stencil_alpha_state = iris_create_zsa_state;
10232    ctx->create_rasterizer_state = iris_create_rasterizer_state;
10233    ctx->create_sampler_state = iris_create_sampler_state;
10234    ctx->create_sampler_view = iris_create_sampler_view;
10235    ctx->create_surface = iris_create_surface;
10236    ctx->create_vertex_elements_state = iris_create_vertex_elements;
10237    ctx->bind_blend_state = iris_bind_blend_state;
10238    ctx->bind_depth_stencil_alpha_state = iris_bind_zsa_state;
10239    ctx->bind_sampler_states = iris_bind_sampler_states;
10240    ctx->bind_rasterizer_state = iris_bind_rasterizer_state;
10241    ctx->bind_vertex_elements_state = iris_bind_vertex_elements_state;
10242    ctx->delete_blend_state = iris_delete_state;
10243    ctx->delete_depth_stencil_alpha_state = iris_delete_state;
10244    ctx->delete_rasterizer_state = iris_delete_state;
10245    ctx->delete_sampler_state = iris_delete_state;
10246    ctx->delete_vertex_elements_state = iris_delete_state;
10247    ctx->set_blend_color = iris_set_blend_color;
10248    ctx->set_clip_state = iris_set_clip_state;
10249    ctx->set_constant_buffer = iris_set_constant_buffer;
10250    ctx->set_shader_buffers = iris_set_shader_buffers;
10251    ctx->set_shader_images = iris_set_shader_images;
10252    ctx->set_sampler_views = iris_set_sampler_views;
10253    ctx->set_compute_resources = iris_set_compute_resources;
10254    ctx->set_global_binding = iris_set_global_binding;
10255    ctx->set_tess_state = iris_set_tess_state;
10256    ctx->set_patch_vertices = iris_set_patch_vertices;
10257    ctx->set_framebuffer_state = iris_set_framebuffer_state;
10258    ctx->set_polygon_stipple = iris_set_polygon_stipple;
10259    ctx->set_sample_mask = iris_set_sample_mask;
10260    ctx->set_scissor_states = iris_set_scissor_states;
10261    ctx->set_stencil_ref = iris_set_stencil_ref;
10262    ctx->set_vertex_buffers = iris_set_vertex_buffers;
10263    ctx->set_viewport_states = iris_set_viewport_states;
10264    ctx->sampler_view_destroy = iris_sampler_view_destroy;
10265    ctx->surface_destroy = iris_surface_destroy;
10266    ctx->draw_vbo = iris_draw_vbo;
10267    ctx->launch_grid = iris_launch_grid;
10268    ctx->create_stream_output_target = iris_create_stream_output_target;
10269    ctx->stream_output_target_destroy = iris_stream_output_target_destroy;
10270    ctx->set_stream_output_targets = iris_set_stream_output_targets;
10271    ctx->set_frontend_noop = iris_set_frontend_noop;
10272 
10273    ice->state.dirty = ~0ull;
10274    ice->state.stage_dirty = ~0ull;
10275 
10276    ice->state.statistics_counters_enabled = true;
10277 
10278    ice->state.sample_mask = 0xffff;
10279    ice->state.num_viewports = 1;
10280    ice->state.prim_mode = MESA_PRIM_COUNT;
10281    ice->state.genx = calloc(1, sizeof(struct iris_genx_state));
10282    ice->draw.derived_params.drawid = -1;
10283 
10284 #if GFX_VERx10 >= 120
10285    ice->state.genx->object_preemption = true;
10286 #endif
10287 
10288    /* Make a 1x1x1 null surface for unbound textures */
10289    void *null_surf_map =
10290       upload_state(ice->state.surface_uploader, &ice->state.unbound_tex,
10291                    4 * GENX(RENDER_SURFACE_STATE_length), 64);
10292    isl_null_fill_state(&screen->isl_dev, null_surf_map,
10293                        .size = isl_extent3d(1, 1, 1));
10294    ice->state.unbound_tex.offset +=
10295       iris_bo_offset_from_base_address(iris_resource_bo(ice->state.unbound_tex.res));
10296 
10297    /* Default all scissor rectangles to be empty regions. */
10298    for (int i = 0; i < IRIS_MAX_VIEWPORTS; i++) {
10299       ice->state.scissors[i] = (struct pipe_scissor_state) {
10300          .minx = 1, .maxx = 0, .miny = 1, .maxy = 0,
10301       };
10302    }
10303 }
10304