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