iris: Fix handling of SIMD32 fragment shaders
[mesa.git] / src / gallium / drivers / iris / iris_state.c
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/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 "drm-uapi/i915_drm.h"
99 #include "nir.h"
100 #include "intel/compiler/brw_compiler.h"
101 #include "intel/common/gen_l3_config.h"
102 #include "intel/common/gen_sample_positions.h"
103 #include "iris_batch.h"
104 #include "iris_context.h"
105 #include "iris_defines.h"
106 #include "iris_pipe.h"
107 #include "iris_resource.h"
108
109 #include "iris_genx_macros.h"
110 #include "intel/common/gen_guardband.h"
111
112 #if GEN_GEN == 8
113 #define MOCS_PTE 0x18
114 #define MOCS_WB 0x78
115 #else
116 #define MOCS_PTE (1 << 1)
117 #define MOCS_WB (2 << 1)
118 #endif
119
120 static uint32_t
121 mocs(const struct iris_bo *bo)
122 {
123 return bo && bo->external ? MOCS_PTE : MOCS_WB;
124 }
125
126 /**
127 * Statically assert that PIPE_* enums match the hardware packets.
128 * (As long as they match, we don't need to translate them.)
129 */
130 UNUSED static void pipe_asserts()
131 {
132 #define PIPE_ASSERT(x) STATIC_ASSERT((int)x)
133
134 /* pipe_logicop happens to match the hardware. */
135 PIPE_ASSERT(PIPE_LOGICOP_CLEAR == LOGICOP_CLEAR);
136 PIPE_ASSERT(PIPE_LOGICOP_NOR == LOGICOP_NOR);
137 PIPE_ASSERT(PIPE_LOGICOP_AND_INVERTED == LOGICOP_AND_INVERTED);
138 PIPE_ASSERT(PIPE_LOGICOP_COPY_INVERTED == LOGICOP_COPY_INVERTED);
139 PIPE_ASSERT(PIPE_LOGICOP_AND_REVERSE == LOGICOP_AND_REVERSE);
140 PIPE_ASSERT(PIPE_LOGICOP_INVERT == LOGICOP_INVERT);
141 PIPE_ASSERT(PIPE_LOGICOP_XOR == LOGICOP_XOR);
142 PIPE_ASSERT(PIPE_LOGICOP_NAND == LOGICOP_NAND);
143 PIPE_ASSERT(PIPE_LOGICOP_AND == LOGICOP_AND);
144 PIPE_ASSERT(PIPE_LOGICOP_EQUIV == LOGICOP_EQUIV);
145 PIPE_ASSERT(PIPE_LOGICOP_NOOP == LOGICOP_NOOP);
146 PIPE_ASSERT(PIPE_LOGICOP_OR_INVERTED == LOGICOP_OR_INVERTED);
147 PIPE_ASSERT(PIPE_LOGICOP_COPY == LOGICOP_COPY);
148 PIPE_ASSERT(PIPE_LOGICOP_OR_REVERSE == LOGICOP_OR_REVERSE);
149 PIPE_ASSERT(PIPE_LOGICOP_OR == LOGICOP_OR);
150 PIPE_ASSERT(PIPE_LOGICOP_SET == LOGICOP_SET);
151
152 /* pipe_blend_func happens to match the hardware. */
153 PIPE_ASSERT(PIPE_BLENDFACTOR_ONE == BLENDFACTOR_ONE);
154 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_COLOR == BLENDFACTOR_SRC_COLOR);
155 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA == BLENDFACTOR_SRC_ALPHA);
156 PIPE_ASSERT(PIPE_BLENDFACTOR_DST_ALPHA == BLENDFACTOR_DST_ALPHA);
157 PIPE_ASSERT(PIPE_BLENDFACTOR_DST_COLOR == BLENDFACTOR_DST_COLOR);
158 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE == BLENDFACTOR_SRC_ALPHA_SATURATE);
159 PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_COLOR == BLENDFACTOR_CONST_COLOR);
160 PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_ALPHA == BLENDFACTOR_CONST_ALPHA);
161 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_COLOR == BLENDFACTOR_SRC1_COLOR);
162 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_ALPHA == BLENDFACTOR_SRC1_ALPHA);
163 PIPE_ASSERT(PIPE_BLENDFACTOR_ZERO == BLENDFACTOR_ZERO);
164 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_COLOR == BLENDFACTOR_INV_SRC_COLOR);
165 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_ALPHA == BLENDFACTOR_INV_SRC_ALPHA);
166 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_ALPHA == BLENDFACTOR_INV_DST_ALPHA);
167 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_COLOR == BLENDFACTOR_INV_DST_COLOR);
168 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_COLOR == BLENDFACTOR_INV_CONST_COLOR);
169 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_ALPHA == BLENDFACTOR_INV_CONST_ALPHA);
170 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_COLOR == BLENDFACTOR_INV_SRC1_COLOR);
171 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_ALPHA == BLENDFACTOR_INV_SRC1_ALPHA);
172
173 /* pipe_blend_func happens to match the hardware. */
174 PIPE_ASSERT(PIPE_BLEND_ADD == BLENDFUNCTION_ADD);
175 PIPE_ASSERT(PIPE_BLEND_SUBTRACT == BLENDFUNCTION_SUBTRACT);
176 PIPE_ASSERT(PIPE_BLEND_REVERSE_SUBTRACT == BLENDFUNCTION_REVERSE_SUBTRACT);
177 PIPE_ASSERT(PIPE_BLEND_MIN == BLENDFUNCTION_MIN);
178 PIPE_ASSERT(PIPE_BLEND_MAX == BLENDFUNCTION_MAX);
179
180 /* pipe_stencil_op happens to match the hardware. */
181 PIPE_ASSERT(PIPE_STENCIL_OP_KEEP == STENCILOP_KEEP);
182 PIPE_ASSERT(PIPE_STENCIL_OP_ZERO == STENCILOP_ZERO);
183 PIPE_ASSERT(PIPE_STENCIL_OP_REPLACE == STENCILOP_REPLACE);
184 PIPE_ASSERT(PIPE_STENCIL_OP_INCR == STENCILOP_INCRSAT);
185 PIPE_ASSERT(PIPE_STENCIL_OP_DECR == STENCILOP_DECRSAT);
186 PIPE_ASSERT(PIPE_STENCIL_OP_INCR_WRAP == STENCILOP_INCR);
187 PIPE_ASSERT(PIPE_STENCIL_OP_DECR_WRAP == STENCILOP_DECR);
188 PIPE_ASSERT(PIPE_STENCIL_OP_INVERT == STENCILOP_INVERT);
189
190 /* pipe_sprite_coord_mode happens to match 3DSTATE_SBE */
191 PIPE_ASSERT(PIPE_SPRITE_COORD_UPPER_LEFT == UPPERLEFT);
192 PIPE_ASSERT(PIPE_SPRITE_COORD_LOWER_LEFT == LOWERLEFT);
193 #undef PIPE_ASSERT
194 }
195
196 static unsigned
197 translate_prim_type(enum pipe_prim_type prim, uint8_t verts_per_patch)
198 {
199 static const unsigned map[] = {
200 [PIPE_PRIM_POINTS] = _3DPRIM_POINTLIST,
201 [PIPE_PRIM_LINES] = _3DPRIM_LINELIST,
202 [PIPE_PRIM_LINE_LOOP] = _3DPRIM_LINELOOP,
203 [PIPE_PRIM_LINE_STRIP] = _3DPRIM_LINESTRIP,
204 [PIPE_PRIM_TRIANGLES] = _3DPRIM_TRILIST,
205 [PIPE_PRIM_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
206 [PIPE_PRIM_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
207 [PIPE_PRIM_QUADS] = _3DPRIM_QUADLIST,
208 [PIPE_PRIM_QUAD_STRIP] = _3DPRIM_QUADSTRIP,
209 [PIPE_PRIM_POLYGON] = _3DPRIM_POLYGON,
210 [PIPE_PRIM_LINES_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
211 [PIPE_PRIM_LINE_STRIP_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
212 [PIPE_PRIM_TRIANGLES_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
213 [PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
214 [PIPE_PRIM_PATCHES] = _3DPRIM_PATCHLIST_1 - 1,
215 };
216
217 return map[prim] + (prim == PIPE_PRIM_PATCHES ? verts_per_patch : 0);
218 }
219
220 static unsigned
221 translate_compare_func(enum pipe_compare_func pipe_func)
222 {
223 static const unsigned map[] = {
224 [PIPE_FUNC_NEVER] = COMPAREFUNCTION_NEVER,
225 [PIPE_FUNC_LESS] = COMPAREFUNCTION_LESS,
226 [PIPE_FUNC_EQUAL] = COMPAREFUNCTION_EQUAL,
227 [PIPE_FUNC_LEQUAL] = COMPAREFUNCTION_LEQUAL,
228 [PIPE_FUNC_GREATER] = COMPAREFUNCTION_GREATER,
229 [PIPE_FUNC_NOTEQUAL] = COMPAREFUNCTION_NOTEQUAL,
230 [PIPE_FUNC_GEQUAL] = COMPAREFUNCTION_GEQUAL,
231 [PIPE_FUNC_ALWAYS] = COMPAREFUNCTION_ALWAYS,
232 };
233 return map[pipe_func];
234 }
235
236 static unsigned
237 translate_shadow_func(enum pipe_compare_func pipe_func)
238 {
239 /* Gallium specifies the result of shadow comparisons as:
240 *
241 * 1 if ref <op> texel,
242 * 0 otherwise.
243 *
244 * The hardware does:
245 *
246 * 0 if texel <op> ref,
247 * 1 otherwise.
248 *
249 * So we need to flip the operator and also negate.
250 */
251 static const unsigned map[] = {
252 [PIPE_FUNC_NEVER] = PREFILTEROPALWAYS,
253 [PIPE_FUNC_LESS] = PREFILTEROPLEQUAL,
254 [PIPE_FUNC_EQUAL] = PREFILTEROPNOTEQUAL,
255 [PIPE_FUNC_LEQUAL] = PREFILTEROPLESS,
256 [PIPE_FUNC_GREATER] = PREFILTEROPGEQUAL,
257 [PIPE_FUNC_NOTEQUAL] = PREFILTEROPEQUAL,
258 [PIPE_FUNC_GEQUAL] = PREFILTEROPGREATER,
259 [PIPE_FUNC_ALWAYS] = PREFILTEROPNEVER,
260 };
261 return map[pipe_func];
262 }
263
264 static unsigned
265 translate_cull_mode(unsigned pipe_face)
266 {
267 static const unsigned map[4] = {
268 [PIPE_FACE_NONE] = CULLMODE_NONE,
269 [PIPE_FACE_FRONT] = CULLMODE_FRONT,
270 [PIPE_FACE_BACK] = CULLMODE_BACK,
271 [PIPE_FACE_FRONT_AND_BACK] = CULLMODE_BOTH,
272 };
273 return map[pipe_face];
274 }
275
276 static unsigned
277 translate_fill_mode(unsigned pipe_polymode)
278 {
279 static const unsigned map[4] = {
280 [PIPE_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
281 [PIPE_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
282 [PIPE_POLYGON_MODE_POINT] = FILL_MODE_POINT,
283 [PIPE_POLYGON_MODE_FILL_RECTANGLE] = FILL_MODE_SOLID,
284 };
285 return map[pipe_polymode];
286 }
287
288 static unsigned
289 translate_mip_filter(enum pipe_tex_mipfilter pipe_mip)
290 {
291 static const unsigned map[] = {
292 [PIPE_TEX_MIPFILTER_NEAREST] = MIPFILTER_NEAREST,
293 [PIPE_TEX_MIPFILTER_LINEAR] = MIPFILTER_LINEAR,
294 [PIPE_TEX_MIPFILTER_NONE] = MIPFILTER_NONE,
295 };
296 return map[pipe_mip];
297 }
298
299 static uint32_t
300 translate_wrap(unsigned pipe_wrap)
301 {
302 static const unsigned map[] = {
303 [PIPE_TEX_WRAP_REPEAT] = TCM_WRAP,
304 [PIPE_TEX_WRAP_CLAMP] = TCM_HALF_BORDER,
305 [PIPE_TEX_WRAP_CLAMP_TO_EDGE] = TCM_CLAMP,
306 [PIPE_TEX_WRAP_CLAMP_TO_BORDER] = TCM_CLAMP_BORDER,
307 [PIPE_TEX_WRAP_MIRROR_REPEAT] = TCM_MIRROR,
308 [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE] = TCM_MIRROR_ONCE,
309
310 /* These are unsupported. */
311 [PIPE_TEX_WRAP_MIRROR_CLAMP] = -1,
312 [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER] = -1,
313 };
314 return map[pipe_wrap];
315 }
316
317 /**
318 * Allocate space for some indirect state.
319 *
320 * Return a pointer to the map (to fill it out) and a state ref (for
321 * referring to the state in GPU commands).
322 */
323 static void *
324 upload_state(struct u_upload_mgr *uploader,
325 struct iris_state_ref *ref,
326 unsigned size,
327 unsigned alignment)
328 {
329 void *p = NULL;
330 u_upload_alloc(uploader, 0, size, alignment, &ref->offset, &ref->res, &p);
331 return p;
332 }
333
334 /**
335 * Stream out temporary/short-lived state.
336 *
337 * This allocates space, pins the BO, and includes the BO address in the
338 * returned offset (which works because all state lives in 32-bit memory
339 * zones).
340 */
341 static uint32_t *
342 stream_state(struct iris_batch *batch,
343 struct u_upload_mgr *uploader,
344 struct pipe_resource **out_res,
345 unsigned size,
346 unsigned alignment,
347 uint32_t *out_offset)
348 {
349 void *ptr = NULL;
350
351 u_upload_alloc(uploader, 0, size, alignment, out_offset, out_res, &ptr);
352
353 struct iris_bo *bo = iris_resource_bo(*out_res);
354 iris_use_pinned_bo(batch, bo, false);
355
356 *out_offset += iris_bo_offset_from_base_address(bo);
357
358 iris_record_state_size(batch->state_sizes, *out_offset, size);
359
360 return ptr;
361 }
362
363 /**
364 * stream_state() + memcpy.
365 */
366 static uint32_t
367 emit_state(struct iris_batch *batch,
368 struct u_upload_mgr *uploader,
369 struct pipe_resource **out_res,
370 const void *data,
371 unsigned size,
372 unsigned alignment)
373 {
374 unsigned offset = 0;
375 uint32_t *map =
376 stream_state(batch, uploader, out_res, size, alignment, &offset);
377
378 if (map)
379 memcpy(map, data, size);
380
381 return offset;
382 }
383
384 /**
385 * Did field 'x' change between 'old_cso' and 'new_cso'?
386 *
387 * (If so, we may want to set some dirty flags.)
388 */
389 #define cso_changed(x) (!old_cso || (old_cso->x != new_cso->x))
390 #define cso_changed_memcmp(x) \
391 (!old_cso || memcmp(old_cso->x, new_cso->x, sizeof(old_cso->x)) != 0)
392
393 static void
394 flush_for_state_base_change(struct iris_batch *batch)
395 {
396 /* Flush before emitting STATE_BASE_ADDRESS.
397 *
398 * This isn't documented anywhere in the PRM. However, it seems to be
399 * necessary prior to changing the surface state base adress. We've
400 * seen issues in Vulkan where we get GPU hangs when using multi-level
401 * command buffers which clear depth, reset state base address, and then
402 * go render stuff.
403 *
404 * Normally, in GL, we would trust the kernel to do sufficient stalls
405 * and flushes prior to executing our batch. However, it doesn't seem
406 * as if the kernel's flushing is always sufficient and we don't want to
407 * rely on it.
408 *
409 * We make this an end-of-pipe sync instead of a normal flush because we
410 * do not know the current status of the GPU. On Haswell at least,
411 * having a fast-clear operation in flight at the same time as a normal
412 * rendering operation can cause hangs. Since the kernel's flushing is
413 * insufficient, we need to ensure that any rendering operations from
414 * other processes are definitely complete before we try to do our own
415 * rendering. It's a bit of a big hammer but it appears to work.
416 */
417 iris_emit_end_of_pipe_sync(batch,
418 "change STATE_BASE_ADDRESS",
419 PIPE_CONTROL_RENDER_TARGET_FLUSH |
420 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
421 PIPE_CONTROL_DATA_CACHE_FLUSH);
422 }
423
424 static void
425 _iris_emit_lri(struct iris_batch *batch, uint32_t reg, uint32_t val)
426 {
427 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
428 lri.RegisterOffset = reg;
429 lri.DataDWord = val;
430 }
431 }
432 #define iris_emit_lri(b, r, v) _iris_emit_lri(b, GENX(r##_num), v)
433
434 static void
435 _iris_emit_lrr(struct iris_batch *batch, uint32_t dst, uint32_t src)
436 {
437 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_REG), lrr) {
438 lrr.SourceRegisterAddress = src;
439 lrr.DestinationRegisterAddress = dst;
440 }
441 }
442
443 static void
444 emit_pipeline_select(struct iris_batch *batch, uint32_t pipeline)
445 {
446 #if GEN_GEN >= 8 && GEN_GEN < 10
447 /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
448 *
449 * Software must clear the COLOR_CALC_STATE Valid field in
450 * 3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
451 * with Pipeline Select set to GPGPU.
452 *
453 * The internal hardware docs recommend the same workaround for Gen9
454 * hardware too.
455 */
456 if (pipeline == GPGPU)
457 iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
458 #endif
459
460
461 /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
462 * PIPELINE_SELECT [DevBWR+]":
463 *
464 * "Project: DEVSNB+
465 *
466 * Software must ensure all the write caches are flushed through a
467 * stalling PIPE_CONTROL command followed by another PIPE_CONTROL
468 * command to invalidate read only caches prior to programming
469 * MI_PIPELINE_SELECT command to change the Pipeline Select Mode."
470 */
471 iris_emit_pipe_control_flush(batch,
472 "workaround: PIPELINE_SELECT flushes (1/2)",
473 PIPE_CONTROL_RENDER_TARGET_FLUSH |
474 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
475 PIPE_CONTROL_DATA_CACHE_FLUSH |
476 PIPE_CONTROL_CS_STALL);
477
478 iris_emit_pipe_control_flush(batch,
479 "workaround: PIPELINE_SELECT flushes (2/2)",
480 PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE |
481 PIPE_CONTROL_CONST_CACHE_INVALIDATE |
482 PIPE_CONTROL_STATE_CACHE_INVALIDATE |
483 PIPE_CONTROL_INSTRUCTION_INVALIDATE);
484
485 iris_emit_cmd(batch, GENX(PIPELINE_SELECT), sel) {
486 #if GEN_GEN >= 9
487 sel.MaskBits = 3;
488 #endif
489 sel.PipelineSelection = pipeline;
490 }
491 }
492
493 UNUSED static void
494 init_glk_barrier_mode(struct iris_batch *batch, uint32_t value)
495 {
496 #if GEN_GEN == 9
497 /* Project: DevGLK
498 *
499 * "This chicken bit works around a hardware issue with barrier
500 * logic encountered when switching between GPGPU and 3D pipelines.
501 * To workaround the issue, this mode bit should be set after a
502 * pipeline is selected."
503 */
504 uint32_t reg_val;
505 iris_pack_state(GENX(SLICE_COMMON_ECO_CHICKEN1), &reg_val, reg) {
506 reg.GLKBarrierMode = value;
507 reg.GLKBarrierModeMask = 1;
508 }
509 iris_emit_lri(batch, SLICE_COMMON_ECO_CHICKEN1, reg_val);
510 #endif
511 }
512
513 static void
514 init_state_base_address(struct iris_batch *batch)
515 {
516 flush_for_state_base_change(batch);
517
518 /* We program most base addresses once at context initialization time.
519 * Each base address points at a 4GB memory zone, and never needs to
520 * change. See iris_bufmgr.h for a description of the memory zones.
521 *
522 * The one exception is Surface State Base Address, which needs to be
523 * updated occasionally. See iris_binder.c for the details there.
524 */
525 iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
526 sba.GeneralStateMOCS = MOCS_WB;
527 sba.StatelessDataPortAccessMOCS = MOCS_WB;
528 sba.DynamicStateMOCS = MOCS_WB;
529 sba.IndirectObjectMOCS = MOCS_WB;
530 sba.InstructionMOCS = MOCS_WB;
531
532 sba.GeneralStateBaseAddressModifyEnable = true;
533 sba.DynamicStateBaseAddressModifyEnable = true;
534 sba.IndirectObjectBaseAddressModifyEnable = true;
535 sba.InstructionBaseAddressModifyEnable = true;
536 sba.GeneralStateBufferSizeModifyEnable = true;
537 sba.DynamicStateBufferSizeModifyEnable = true;
538 #if (GEN_GEN >= 9)
539 sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
540 sba.BindlessSurfaceStateMOCS = MOCS_WB;
541 #endif
542 sba.IndirectObjectBufferSizeModifyEnable = true;
543 sba.InstructionBuffersizeModifyEnable = true;
544
545 sba.InstructionBaseAddress = ro_bo(NULL, IRIS_MEMZONE_SHADER_START);
546 sba.DynamicStateBaseAddress = ro_bo(NULL, IRIS_MEMZONE_DYNAMIC_START);
547
548 sba.GeneralStateBufferSize = 0xfffff;
549 sba.IndirectObjectBufferSize = 0xfffff;
550 sba.InstructionBufferSize = 0xfffff;
551 sba.DynamicStateBufferSize = 0xfffff;
552 }
553 }
554
555 static void
556 iris_emit_l3_config(struct iris_batch *batch, const struct gen_l3_config *cfg,
557 bool has_slm, bool wants_dc_cache)
558 {
559 uint32_t reg_val;
560 iris_pack_state(GENX(L3CNTLREG), &reg_val, reg) {
561 reg.SLMEnable = has_slm;
562 #if GEN_GEN == 11
563 /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
564 * in L3CNTLREG register. The default setting of the bit is not the
565 * desirable behavior.
566 */
567 reg.ErrorDetectionBehaviorControl = true;
568 reg.UseFullWays = true;
569 #endif
570 reg.URBAllocation = cfg->n[GEN_L3P_URB];
571 reg.ROAllocation = cfg->n[GEN_L3P_RO];
572 reg.DCAllocation = cfg->n[GEN_L3P_DC];
573 reg.AllAllocation = cfg->n[GEN_L3P_ALL];
574 }
575 iris_emit_lri(batch, L3CNTLREG, reg_val);
576 }
577
578 static void
579 iris_emit_default_l3_config(struct iris_batch *batch,
580 const struct gen_device_info *devinfo,
581 bool compute)
582 {
583 bool wants_dc_cache = true;
584 bool has_slm = compute;
585 const struct gen_l3_weights w =
586 gen_get_default_l3_weights(devinfo, wants_dc_cache, has_slm);
587 const struct gen_l3_config *cfg = gen_get_l3_config(devinfo, w);
588 iris_emit_l3_config(batch, cfg, has_slm, wants_dc_cache);
589 }
590
591 #if GEN_GEN == 9 || GEN_GEN == 10
592 static void
593 iris_enable_obj_preemption(struct iris_batch *batch, bool enable)
594 {
595 uint32_t reg_val;
596
597 /* A fixed function pipe flush is required before modifying this field */
598 iris_emit_end_of_pipe_sync(batch, enable ? "enable preemption"
599 : "disable preemption",
600 PIPE_CONTROL_RENDER_TARGET_FLUSH);
601
602 /* enable object level preemption */
603 iris_pack_state(GENX(CS_CHICKEN1), &reg_val, reg) {
604 reg.ReplayMode = enable;
605 reg.ReplayModeMask = true;
606 }
607 iris_emit_lri(batch, CS_CHICKEN1, reg_val);
608 }
609 #endif
610
611 /**
612 * Upload the initial GPU state for a render context.
613 *
614 * This sets some invariant state that needs to be programmed a particular
615 * way, but we never actually change.
616 */
617 static void
618 iris_init_render_context(struct iris_screen *screen,
619 struct iris_batch *batch,
620 struct iris_vtable *vtbl,
621 struct pipe_debug_callback *dbg)
622 {
623 UNUSED const struct gen_device_info *devinfo = &screen->devinfo;
624 uint32_t reg_val;
625
626 emit_pipeline_select(batch, _3D);
627
628 iris_emit_default_l3_config(batch, devinfo, false);
629
630 init_state_base_address(batch);
631
632 #if GEN_GEN >= 9
633 iris_pack_state(GENX(CS_DEBUG_MODE2), &reg_val, reg) {
634 reg.CONSTANT_BUFFERAddressOffsetDisable = true;
635 reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
636 }
637 iris_emit_lri(batch, CS_DEBUG_MODE2, reg_val);
638 #else
639 iris_pack_state(GENX(INSTPM), &reg_val, reg) {
640 reg.CONSTANT_BUFFERAddressOffsetDisable = true;
641 reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
642 }
643 iris_emit_lri(batch, INSTPM, reg_val);
644 #endif
645
646 #if GEN_GEN == 9
647 iris_pack_state(GENX(CACHE_MODE_1), &reg_val, reg) {
648 reg.FloatBlendOptimizationEnable = true;
649 reg.FloatBlendOptimizationEnableMask = true;
650 reg.PartialResolveDisableInVC = true;
651 reg.PartialResolveDisableInVCMask = true;
652 }
653 iris_emit_lri(batch, CACHE_MODE_1, reg_val);
654
655 if (devinfo->is_geminilake)
656 init_glk_barrier_mode(batch, GLK_BARRIER_MODE_3D_HULL);
657 #endif
658
659 #if GEN_GEN == 11
660 iris_pack_state(GENX(SAMPLER_MODE), &reg_val, reg) {
661 reg.HeaderlessMessageforPreemptableContexts = 1;
662 reg.HeaderlessMessageforPreemptableContextsMask = 1;
663 }
664 iris_emit_lri(batch, SAMPLER_MODE, reg_val);
665
666 /* Bit 1 must be set in HALF_SLICE_CHICKEN7. */
667 iris_pack_state(GENX(HALF_SLICE_CHICKEN7), &reg_val, reg) {
668 reg.EnabledTexelOffsetPrecisionFix = 1;
669 reg.EnabledTexelOffsetPrecisionFixMask = 1;
670 }
671 iris_emit_lri(batch, HALF_SLICE_CHICKEN7, reg_val);
672
673 iris_pack_state(GENX(SLICE_COMMON_ECO_CHICKEN1), &reg_val, reg) {
674 reg.StateCacheRedirectToCSSectionEnable = true;
675 reg.StateCacheRedirectToCSSectionEnableMask = true;
676 }
677 iris_emit_lri(batch, SLICE_COMMON_ECO_CHICKEN1, reg_val);
678
679 /* Hardware specification recommends disabling repacking for the
680 * compatibility with decompression mechanism in display controller.
681 */
682 if (devinfo->disable_ccs_repack) {
683 iris_pack_state(GENX(CACHE_MODE_0), &reg_val, reg) {
684 reg.DisableRepackingforCompression = true;
685 reg.DisableRepackingforCompressionMask = true;
686 }
687 iris_emit_lri(batch, CACHE_MODE_0, reg_val);
688 }
689
690 // XXX: 3D_MODE?
691 #endif
692
693 /* 3DSTATE_DRAWING_RECTANGLE is non-pipelined, so we want to avoid
694 * changing it dynamically. We set it to the maximum size here, and
695 * instead include the render target dimensions in the viewport, so
696 * viewport extents clipping takes care of pruning stray geometry.
697 */
698 iris_emit_cmd(batch, GENX(3DSTATE_DRAWING_RECTANGLE), rect) {
699 rect.ClippedDrawingRectangleXMax = UINT16_MAX;
700 rect.ClippedDrawingRectangleYMax = UINT16_MAX;
701 }
702
703 /* Set the initial MSAA sample positions. */
704 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_PATTERN), pat) {
705 GEN_SAMPLE_POS_1X(pat._1xSample);
706 GEN_SAMPLE_POS_2X(pat._2xSample);
707 GEN_SAMPLE_POS_4X(pat._4xSample);
708 GEN_SAMPLE_POS_8X(pat._8xSample);
709 #if GEN_GEN >= 9
710 GEN_SAMPLE_POS_16X(pat._16xSample);
711 #endif
712 }
713
714 /* Use the legacy AA line coverage computation. */
715 iris_emit_cmd(batch, GENX(3DSTATE_AA_LINE_PARAMETERS), foo);
716
717 /* Disable chromakeying (it's for media) */
718 iris_emit_cmd(batch, GENX(3DSTATE_WM_CHROMAKEY), foo);
719
720 /* We want regular rendering, not special HiZ operations. */
721 iris_emit_cmd(batch, GENX(3DSTATE_WM_HZ_OP), foo);
722
723 /* No polygon stippling offsets are necessary. */
724 /* TODO: may need to set an offset for origin-UL framebuffers */
725 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_OFFSET), foo);
726
727 /* Set a static partitioning of the push constant area. */
728 /* TODO: this may be a bad idea...could starve the push ringbuffers... */
729 for (int i = 0; i <= MESA_SHADER_FRAGMENT; i++) {
730 iris_emit_cmd(batch, GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
731 alloc._3DCommandSubOpcode = 18 + i;
732 alloc.ConstantBufferOffset = 6 * i;
733 alloc.ConstantBufferSize = i == MESA_SHADER_FRAGMENT ? 8 : 6;
734 }
735 }
736
737 #if GEN_GEN == 10
738 /* Gen11+ is enabled for us by the kernel. */
739 iris_enable_obj_preemption(batch, true);
740 #endif
741 }
742
743 static void
744 iris_init_compute_context(struct iris_screen *screen,
745 struct iris_batch *batch,
746 struct iris_vtable *vtbl,
747 struct pipe_debug_callback *dbg)
748 {
749 UNUSED const struct gen_device_info *devinfo = &screen->devinfo;
750
751 emit_pipeline_select(batch, GPGPU);
752
753 iris_emit_default_l3_config(batch, devinfo, true);
754
755 init_state_base_address(batch);
756
757 #if GEN_GEN == 9
758 if (devinfo->is_geminilake)
759 init_glk_barrier_mode(batch, GLK_BARRIER_MODE_GPGPU);
760 #endif
761 }
762
763 struct iris_vertex_buffer_state {
764 /** The VERTEX_BUFFER_STATE hardware structure. */
765 uint32_t state[GENX(VERTEX_BUFFER_STATE_length)];
766
767 /** The resource to source vertex data from. */
768 struct pipe_resource *resource;
769 };
770
771 struct iris_depth_buffer_state {
772 /* Depth/HiZ/Stencil related hardware packets. */
773 uint32_t packets[GENX(3DSTATE_DEPTH_BUFFER_length) +
774 GENX(3DSTATE_STENCIL_BUFFER_length) +
775 GENX(3DSTATE_HIER_DEPTH_BUFFER_length) +
776 GENX(3DSTATE_CLEAR_PARAMS_length)];
777 };
778
779 /**
780 * Generation-specific context state (ice->state.genx->...).
781 *
782 * Most state can go in iris_context directly, but these encode hardware
783 * packets which vary by generation.
784 */
785 struct iris_genx_state {
786 struct iris_vertex_buffer_state vertex_buffers[33];
787 uint32_t last_index_buffer[GENX(3DSTATE_INDEX_BUFFER_length)];
788
789 struct iris_depth_buffer_state depth_buffer;
790
791 uint32_t so_buffers[4 * GENX(3DSTATE_SO_BUFFER_length)];
792
793 #if GEN_GEN == 9
794 /* Is object level preemption enabled? */
795 bool object_preemption;
796 #endif
797
798 struct {
799 #if GEN_GEN == 8
800 struct brw_image_param image_param[PIPE_MAX_SHADER_IMAGES];
801 #endif
802 } shaders[MESA_SHADER_STAGES];
803 };
804
805 /**
806 * The pipe->set_blend_color() driver hook.
807 *
808 * This corresponds to our COLOR_CALC_STATE.
809 */
810 static void
811 iris_set_blend_color(struct pipe_context *ctx,
812 const struct pipe_blend_color *state)
813 {
814 struct iris_context *ice = (struct iris_context *) ctx;
815
816 /* Our COLOR_CALC_STATE is exactly pipe_blend_color, so just memcpy */
817 memcpy(&ice->state.blend_color, state, sizeof(struct pipe_blend_color));
818 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
819 }
820
821 /**
822 * Gallium CSO for blend state (see pipe_blend_state).
823 */
824 struct iris_blend_state {
825 /** Partial 3DSTATE_PS_BLEND */
826 uint32_t ps_blend[GENX(3DSTATE_PS_BLEND_length)];
827
828 /** Partial BLEND_STATE */
829 uint32_t blend_state[GENX(BLEND_STATE_length) +
830 BRW_MAX_DRAW_BUFFERS * GENX(BLEND_STATE_ENTRY_length)];
831
832 bool alpha_to_coverage; /* for shader key */
833
834 /** Bitfield of whether blending is enabled for RT[i] - for aux resolves */
835 uint8_t blend_enables;
836
837 /** Bitfield of whether color writes are enabled for RT[i] */
838 uint8_t color_write_enables;
839
840 /** Does RT[0] use dual color blending? */
841 bool dual_color_blending;
842 };
843
844 static enum pipe_blendfactor
845 fix_blendfactor(enum pipe_blendfactor f, bool alpha_to_one)
846 {
847 if (alpha_to_one) {
848 if (f == PIPE_BLENDFACTOR_SRC1_ALPHA)
849 return PIPE_BLENDFACTOR_ONE;
850
851 if (f == PIPE_BLENDFACTOR_INV_SRC1_ALPHA)
852 return PIPE_BLENDFACTOR_ZERO;
853 }
854
855 return f;
856 }
857
858 /**
859 * The pipe->create_blend_state() driver hook.
860 *
861 * Translates a pipe_blend_state into iris_blend_state.
862 */
863 static void *
864 iris_create_blend_state(struct pipe_context *ctx,
865 const struct pipe_blend_state *state)
866 {
867 struct iris_blend_state *cso = malloc(sizeof(struct iris_blend_state));
868 uint32_t *blend_entry = cso->blend_state + GENX(BLEND_STATE_length);
869
870 cso->blend_enables = 0;
871 cso->color_write_enables = 0;
872 STATIC_ASSERT(BRW_MAX_DRAW_BUFFERS <= 8);
873
874 cso->alpha_to_coverage = state->alpha_to_coverage;
875
876 bool indep_alpha_blend = false;
877
878 for (int i = 0; i < BRW_MAX_DRAW_BUFFERS; i++) {
879 const struct pipe_rt_blend_state *rt =
880 &state->rt[state->independent_blend_enable ? i : 0];
881
882 enum pipe_blendfactor src_rgb =
883 fix_blendfactor(rt->rgb_src_factor, state->alpha_to_one);
884 enum pipe_blendfactor src_alpha =
885 fix_blendfactor(rt->alpha_src_factor, state->alpha_to_one);
886 enum pipe_blendfactor dst_rgb =
887 fix_blendfactor(rt->rgb_dst_factor, state->alpha_to_one);
888 enum pipe_blendfactor dst_alpha =
889 fix_blendfactor(rt->alpha_dst_factor, state->alpha_to_one);
890
891 if (rt->rgb_func != rt->alpha_func ||
892 src_rgb != src_alpha || dst_rgb != dst_alpha)
893 indep_alpha_blend = true;
894
895 if (rt->blend_enable)
896 cso->blend_enables |= 1u << i;
897
898 if (rt->colormask)
899 cso->color_write_enables |= 1u << i;
900
901 iris_pack_state(GENX(BLEND_STATE_ENTRY), blend_entry, be) {
902 be.LogicOpEnable = state->logicop_enable;
903 be.LogicOpFunction = state->logicop_func;
904
905 be.PreBlendSourceOnlyClampEnable = false;
906 be.ColorClampRange = COLORCLAMP_RTFORMAT;
907 be.PreBlendColorClampEnable = true;
908 be.PostBlendColorClampEnable = true;
909
910 be.ColorBufferBlendEnable = rt->blend_enable;
911
912 be.ColorBlendFunction = rt->rgb_func;
913 be.AlphaBlendFunction = rt->alpha_func;
914 be.SourceBlendFactor = src_rgb;
915 be.SourceAlphaBlendFactor = src_alpha;
916 be.DestinationBlendFactor = dst_rgb;
917 be.DestinationAlphaBlendFactor = dst_alpha;
918
919 be.WriteDisableRed = !(rt->colormask & PIPE_MASK_R);
920 be.WriteDisableGreen = !(rt->colormask & PIPE_MASK_G);
921 be.WriteDisableBlue = !(rt->colormask & PIPE_MASK_B);
922 be.WriteDisableAlpha = !(rt->colormask & PIPE_MASK_A);
923 }
924 blend_entry += GENX(BLEND_STATE_ENTRY_length);
925 }
926
927 iris_pack_command(GENX(3DSTATE_PS_BLEND), cso->ps_blend, pb) {
928 /* pb.HasWriteableRT is filled in at draw time.
929 * pb.AlphaTestEnable is filled in at draw time.
930 *
931 * pb.ColorBufferBlendEnable is filled in at draw time so we can avoid
932 * setting it when dual color blending without an appropriate shader.
933 */
934
935 pb.AlphaToCoverageEnable = state->alpha_to_coverage;
936 pb.IndependentAlphaBlendEnable = indep_alpha_blend;
937
938 pb.SourceBlendFactor =
939 fix_blendfactor(state->rt[0].rgb_src_factor, state->alpha_to_one);
940 pb.SourceAlphaBlendFactor =
941 fix_blendfactor(state->rt[0].alpha_src_factor, state->alpha_to_one);
942 pb.DestinationBlendFactor =
943 fix_blendfactor(state->rt[0].rgb_dst_factor, state->alpha_to_one);
944 pb.DestinationAlphaBlendFactor =
945 fix_blendfactor(state->rt[0].alpha_dst_factor, state->alpha_to_one);
946 }
947
948 iris_pack_state(GENX(BLEND_STATE), cso->blend_state, bs) {
949 bs.AlphaToCoverageEnable = state->alpha_to_coverage;
950 bs.IndependentAlphaBlendEnable = indep_alpha_blend;
951 bs.AlphaToOneEnable = state->alpha_to_one;
952 bs.AlphaToCoverageDitherEnable = state->alpha_to_coverage;
953 bs.ColorDitherEnable = state->dither;
954 /* bl.AlphaTestEnable and bs.AlphaTestFunction are filled in later. */
955 }
956
957 cso->dual_color_blending = util_blend_state_is_dual(state, 0);
958
959 return cso;
960 }
961
962 /**
963 * The pipe->bind_blend_state() driver hook.
964 *
965 * Bind a blending CSO and flag related dirty bits.
966 */
967 static void
968 iris_bind_blend_state(struct pipe_context *ctx, void *state)
969 {
970 struct iris_context *ice = (struct iris_context *) ctx;
971 struct iris_blend_state *cso = state;
972
973 ice->state.cso_blend = cso;
974 ice->state.blend_enables = cso ? cso->blend_enables : 0;
975
976 ice->state.dirty |= IRIS_DIRTY_PS_BLEND;
977 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
978 ice->state.dirty |= IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
979 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_BLEND];
980 }
981
982 /**
983 * Return true if the FS writes to any color outputs which are not disabled
984 * via color masking.
985 */
986 static bool
987 has_writeable_rt(const struct iris_blend_state *cso_blend,
988 const struct shader_info *fs_info)
989 {
990 if (!fs_info)
991 return false;
992
993 unsigned rt_outputs = fs_info->outputs_written >> FRAG_RESULT_DATA0;
994
995 if (fs_info->outputs_written & BITFIELD64_BIT(FRAG_RESULT_COLOR))
996 rt_outputs = (1 << BRW_MAX_DRAW_BUFFERS) - 1;
997
998 return cso_blend->color_write_enables & rt_outputs;
999 }
1000
1001 /**
1002 * Gallium CSO for depth, stencil, and alpha testing state.
1003 */
1004 struct iris_depth_stencil_alpha_state {
1005 /** Partial 3DSTATE_WM_DEPTH_STENCIL. */
1006 uint32_t wmds[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
1007
1008 /** Outbound to BLEND_STATE, 3DSTATE_PS_BLEND, COLOR_CALC_STATE. */
1009 struct pipe_alpha_state alpha;
1010
1011 /** Outbound to resolve and cache set tracking. */
1012 bool depth_writes_enabled;
1013 bool stencil_writes_enabled;
1014 };
1015
1016 /**
1017 * The pipe->create_depth_stencil_alpha_state() driver hook.
1018 *
1019 * We encode most of 3DSTATE_WM_DEPTH_STENCIL, and just save off the alpha
1020 * testing state since we need pieces of it in a variety of places.
1021 */
1022 static void *
1023 iris_create_zsa_state(struct pipe_context *ctx,
1024 const struct pipe_depth_stencil_alpha_state *state)
1025 {
1026 struct iris_depth_stencil_alpha_state *cso =
1027 malloc(sizeof(struct iris_depth_stencil_alpha_state));
1028
1029 bool two_sided_stencil = state->stencil[1].enabled;
1030
1031 cso->alpha = state->alpha;
1032 cso->depth_writes_enabled = state->depth.writemask;
1033 cso->stencil_writes_enabled =
1034 state->stencil[0].writemask != 0 ||
1035 (two_sided_stencil && state->stencil[1].writemask != 0);
1036
1037 /* The state tracker needs to optimize away EQUAL writes for us. */
1038 assert(!(state->depth.func == PIPE_FUNC_EQUAL && state->depth.writemask));
1039
1040 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), cso->wmds, wmds) {
1041 wmds.StencilFailOp = state->stencil[0].fail_op;
1042 wmds.StencilPassDepthFailOp = state->stencil[0].zfail_op;
1043 wmds.StencilPassDepthPassOp = state->stencil[0].zpass_op;
1044 wmds.StencilTestFunction =
1045 translate_compare_func(state->stencil[0].func);
1046 wmds.BackfaceStencilFailOp = state->stencil[1].fail_op;
1047 wmds.BackfaceStencilPassDepthFailOp = state->stencil[1].zfail_op;
1048 wmds.BackfaceStencilPassDepthPassOp = state->stencil[1].zpass_op;
1049 wmds.BackfaceStencilTestFunction =
1050 translate_compare_func(state->stencil[1].func);
1051 wmds.DepthTestFunction = translate_compare_func(state->depth.func);
1052 wmds.DoubleSidedStencilEnable = two_sided_stencil;
1053 wmds.StencilTestEnable = state->stencil[0].enabled;
1054 wmds.StencilBufferWriteEnable =
1055 state->stencil[0].writemask != 0 ||
1056 (two_sided_stencil && state->stencil[1].writemask != 0);
1057 wmds.DepthTestEnable = state->depth.enabled;
1058 wmds.DepthBufferWriteEnable = state->depth.writemask;
1059 wmds.StencilTestMask = state->stencil[0].valuemask;
1060 wmds.StencilWriteMask = state->stencil[0].writemask;
1061 wmds.BackfaceStencilTestMask = state->stencil[1].valuemask;
1062 wmds.BackfaceStencilWriteMask = state->stencil[1].writemask;
1063 /* wmds.[Backface]StencilReferenceValue are merged later */
1064 }
1065
1066 return cso;
1067 }
1068
1069 /**
1070 * The pipe->bind_depth_stencil_alpha_state() driver hook.
1071 *
1072 * Bind a depth/stencil/alpha CSO and flag related dirty bits.
1073 */
1074 static void
1075 iris_bind_zsa_state(struct pipe_context *ctx, void *state)
1076 {
1077 struct iris_context *ice = (struct iris_context *) ctx;
1078 struct iris_depth_stencil_alpha_state *old_cso = ice->state.cso_zsa;
1079 struct iris_depth_stencil_alpha_state *new_cso = state;
1080
1081 if (new_cso) {
1082 if (cso_changed(alpha.ref_value))
1083 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
1084
1085 if (cso_changed(alpha.enabled))
1086 ice->state.dirty |= IRIS_DIRTY_PS_BLEND | IRIS_DIRTY_BLEND_STATE;
1087
1088 if (cso_changed(alpha.func))
1089 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
1090
1091 if (cso_changed(depth_writes_enabled))
1092 ice->state.dirty |= IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
1093
1094 ice->state.depth_writes_enabled = new_cso->depth_writes_enabled;
1095 ice->state.stencil_writes_enabled = new_cso->stencil_writes_enabled;
1096 }
1097
1098 ice->state.cso_zsa = new_cso;
1099 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
1100 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
1101 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_DEPTH_STENCIL_ALPHA];
1102 }
1103
1104 /**
1105 * Gallium CSO for rasterizer state.
1106 */
1107 struct iris_rasterizer_state {
1108 uint32_t sf[GENX(3DSTATE_SF_length)];
1109 uint32_t clip[GENX(3DSTATE_CLIP_length)];
1110 uint32_t raster[GENX(3DSTATE_RASTER_length)];
1111 uint32_t wm[GENX(3DSTATE_WM_length)];
1112 uint32_t line_stipple[GENX(3DSTATE_LINE_STIPPLE_length)];
1113
1114 uint8_t num_clip_plane_consts;
1115 bool clip_halfz; /* for CC_VIEWPORT */
1116 bool depth_clip_near; /* for CC_VIEWPORT */
1117 bool depth_clip_far; /* for CC_VIEWPORT */
1118 bool flatshade; /* for shader state */
1119 bool flatshade_first; /* for stream output */
1120 bool clamp_fragment_color; /* for shader state */
1121 bool light_twoside; /* for shader state */
1122 bool rasterizer_discard; /* for 3DSTATE_STREAMOUT and 3DSTATE_CLIP */
1123 bool half_pixel_center; /* for 3DSTATE_MULTISAMPLE */
1124 bool line_stipple_enable;
1125 bool poly_stipple_enable;
1126 bool multisample;
1127 bool force_persample_interp;
1128 bool conservative_rasterization;
1129 bool fill_mode_point_or_line;
1130 enum pipe_sprite_coord_mode sprite_coord_mode; /* PIPE_SPRITE_* */
1131 uint16_t sprite_coord_enable;
1132 };
1133
1134 static float
1135 get_line_width(const struct pipe_rasterizer_state *state)
1136 {
1137 float line_width = state->line_width;
1138
1139 /* From the OpenGL 4.4 spec:
1140 *
1141 * "The actual width of non-antialiased lines is determined by rounding
1142 * the supplied width to the nearest integer, then clamping it to the
1143 * implementation-dependent maximum non-antialiased line width."
1144 */
1145 if (!state->multisample && !state->line_smooth)
1146 line_width = roundf(state->line_width);
1147
1148 if (!state->multisample && state->line_smooth && line_width < 1.5f) {
1149 /* For 1 pixel line thickness or less, the general anti-aliasing
1150 * algorithm gives up, and a garbage line is generated. Setting a
1151 * Line Width of 0.0 specifies the rasterization of the "thinnest"
1152 * (one-pixel-wide), non-antialiased lines.
1153 *
1154 * Lines rendered with zero Line Width are rasterized using the
1155 * "Grid Intersection Quantization" rules as specified by the
1156 * "Zero-Width (Cosmetic) Line Rasterization" section of the docs.
1157 */
1158 line_width = 0.0f;
1159 }
1160
1161 return line_width;
1162 }
1163
1164 /**
1165 * The pipe->create_rasterizer_state() driver hook.
1166 */
1167 static void *
1168 iris_create_rasterizer_state(struct pipe_context *ctx,
1169 const struct pipe_rasterizer_state *state)
1170 {
1171 struct iris_rasterizer_state *cso =
1172 malloc(sizeof(struct iris_rasterizer_state));
1173
1174 cso->multisample = state->multisample;
1175 cso->force_persample_interp = state->force_persample_interp;
1176 cso->clip_halfz = state->clip_halfz;
1177 cso->depth_clip_near = state->depth_clip_near;
1178 cso->depth_clip_far = state->depth_clip_far;
1179 cso->flatshade = state->flatshade;
1180 cso->flatshade_first = state->flatshade_first;
1181 cso->clamp_fragment_color = state->clamp_fragment_color;
1182 cso->light_twoside = state->light_twoside;
1183 cso->rasterizer_discard = state->rasterizer_discard;
1184 cso->half_pixel_center = state->half_pixel_center;
1185 cso->sprite_coord_mode = state->sprite_coord_mode;
1186 cso->sprite_coord_enable = state->sprite_coord_enable;
1187 cso->line_stipple_enable = state->line_stipple_enable;
1188 cso->poly_stipple_enable = state->poly_stipple_enable;
1189 cso->conservative_rasterization =
1190 state->conservative_raster_mode == PIPE_CONSERVATIVE_RASTER_POST_SNAP;
1191
1192 cso->fill_mode_point_or_line =
1193 state->fill_front == PIPE_POLYGON_MODE_LINE ||
1194 state->fill_front == PIPE_POLYGON_MODE_POINT ||
1195 state->fill_back == PIPE_POLYGON_MODE_LINE ||
1196 state->fill_back == PIPE_POLYGON_MODE_POINT;
1197
1198 if (state->clip_plane_enable != 0)
1199 cso->num_clip_plane_consts = util_logbase2(state->clip_plane_enable) + 1;
1200 else
1201 cso->num_clip_plane_consts = 0;
1202
1203 float line_width = get_line_width(state);
1204
1205 iris_pack_command(GENX(3DSTATE_SF), cso->sf, sf) {
1206 sf.StatisticsEnable = true;
1207 sf.ViewportTransformEnable = true;
1208 sf.AALineDistanceMode = AALINEDISTANCE_TRUE;
1209 sf.LineEndCapAntialiasingRegionWidth =
1210 state->line_smooth ? _10pixels : _05pixels;
1211 sf.LastPixelEnable = state->line_last_pixel;
1212 sf.LineWidth = line_width;
1213 sf.SmoothPointEnable = (state->point_smooth || state->multisample) &&
1214 !state->point_quad_rasterization;
1215 sf.PointWidthSource = state->point_size_per_vertex ? Vertex : State;
1216 sf.PointWidth = state->point_size;
1217
1218 if (state->flatshade_first) {
1219 sf.TriangleFanProvokingVertexSelect = 1;
1220 } else {
1221 sf.TriangleStripListProvokingVertexSelect = 2;
1222 sf.TriangleFanProvokingVertexSelect = 2;
1223 sf.LineStripListProvokingVertexSelect = 1;
1224 }
1225 }
1226
1227 iris_pack_command(GENX(3DSTATE_RASTER), cso->raster, rr) {
1228 rr.FrontWinding = state->front_ccw ? CounterClockwise : Clockwise;
1229 rr.CullMode = translate_cull_mode(state->cull_face);
1230 rr.FrontFaceFillMode = translate_fill_mode(state->fill_front);
1231 rr.BackFaceFillMode = translate_fill_mode(state->fill_back);
1232 rr.DXMultisampleRasterizationEnable = state->multisample;
1233 rr.GlobalDepthOffsetEnableSolid = state->offset_tri;
1234 rr.GlobalDepthOffsetEnableWireframe = state->offset_line;
1235 rr.GlobalDepthOffsetEnablePoint = state->offset_point;
1236 rr.GlobalDepthOffsetConstant = state->offset_units * 2;
1237 rr.GlobalDepthOffsetScale = state->offset_scale;
1238 rr.GlobalDepthOffsetClamp = state->offset_clamp;
1239 rr.SmoothPointEnable = state->point_smooth;
1240 rr.AntialiasingEnable = state->line_smooth;
1241 rr.ScissorRectangleEnable = state->scissor;
1242 #if GEN_GEN >= 9
1243 rr.ViewportZNearClipTestEnable = state->depth_clip_near;
1244 rr.ViewportZFarClipTestEnable = state->depth_clip_far;
1245 rr.ConservativeRasterizationEnable =
1246 cso->conservative_rasterization;
1247 #else
1248 rr.ViewportZClipTestEnable = (state->depth_clip_near || state->depth_clip_far);
1249 #endif
1250 }
1251
1252 iris_pack_command(GENX(3DSTATE_CLIP), cso->clip, cl) {
1253 /* cl.NonPerspectiveBarycentricEnable is filled in at draw time from
1254 * the FS program; cl.ForceZeroRTAIndexEnable is filled in from the FB.
1255 */
1256 cl.EarlyCullEnable = true;
1257 cl.UserClipDistanceClipTestEnableBitmask = state->clip_plane_enable;
1258 cl.ForceUserClipDistanceClipTestEnableBitmask = true;
1259 cl.APIMode = state->clip_halfz ? APIMODE_D3D : APIMODE_OGL;
1260 cl.GuardbandClipTestEnable = true;
1261 cl.ClipEnable = true;
1262 cl.MinimumPointWidth = 0.125;
1263 cl.MaximumPointWidth = 255.875;
1264
1265 if (state->flatshade_first) {
1266 cl.TriangleFanProvokingVertexSelect = 1;
1267 } else {
1268 cl.TriangleStripListProvokingVertexSelect = 2;
1269 cl.TriangleFanProvokingVertexSelect = 2;
1270 cl.LineStripListProvokingVertexSelect = 1;
1271 }
1272 }
1273
1274 iris_pack_command(GENX(3DSTATE_WM), cso->wm, wm) {
1275 /* wm.BarycentricInterpolationMode and wm.EarlyDepthStencilControl are
1276 * filled in at draw time from the FS program.
1277 */
1278 wm.LineAntialiasingRegionWidth = _10pixels;
1279 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1280 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1281 wm.LineStippleEnable = state->line_stipple_enable;
1282 wm.PolygonStippleEnable = state->poly_stipple_enable;
1283 }
1284
1285 /* Remap from 0..255 back to 1..256 */
1286 const unsigned line_stipple_factor = state->line_stipple_factor + 1;
1287
1288 iris_pack_command(GENX(3DSTATE_LINE_STIPPLE), cso->line_stipple, line) {
1289 line.LineStipplePattern = state->line_stipple_pattern;
1290 line.LineStippleInverseRepeatCount = 1.0f / line_stipple_factor;
1291 line.LineStippleRepeatCount = line_stipple_factor;
1292 }
1293
1294 return cso;
1295 }
1296
1297 /**
1298 * The pipe->bind_rasterizer_state() driver hook.
1299 *
1300 * Bind a rasterizer CSO and flag related dirty bits.
1301 */
1302 static void
1303 iris_bind_rasterizer_state(struct pipe_context *ctx, void *state)
1304 {
1305 struct iris_context *ice = (struct iris_context *) ctx;
1306 struct iris_rasterizer_state *old_cso = ice->state.cso_rast;
1307 struct iris_rasterizer_state *new_cso = state;
1308
1309 if (new_cso) {
1310 /* Try to avoid re-emitting 3DSTATE_LINE_STIPPLE, it's non-pipelined */
1311 if (cso_changed_memcmp(line_stipple))
1312 ice->state.dirty |= IRIS_DIRTY_LINE_STIPPLE;
1313
1314 if (cso_changed(half_pixel_center))
1315 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
1316
1317 if (cso_changed(line_stipple_enable) || cso_changed(poly_stipple_enable))
1318 ice->state.dirty |= IRIS_DIRTY_WM;
1319
1320 if (cso_changed(rasterizer_discard))
1321 ice->state.dirty |= IRIS_DIRTY_STREAMOUT | IRIS_DIRTY_CLIP;
1322
1323 if (cso_changed(flatshade_first))
1324 ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
1325
1326 if (cso_changed(depth_clip_near) || cso_changed(depth_clip_far) ||
1327 cso_changed(clip_halfz))
1328 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
1329
1330 if (cso_changed(sprite_coord_enable) ||
1331 cso_changed(sprite_coord_mode) ||
1332 cso_changed(light_twoside))
1333 ice->state.dirty |= IRIS_DIRTY_SBE;
1334
1335 if (cso_changed(conservative_rasterization))
1336 ice->state.dirty |= IRIS_DIRTY_FS;
1337 }
1338
1339 ice->state.cso_rast = new_cso;
1340 ice->state.dirty |= IRIS_DIRTY_RASTER;
1341 ice->state.dirty |= IRIS_DIRTY_CLIP;
1342 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_RASTERIZER];
1343 }
1344
1345 /**
1346 * Return true if the given wrap mode requires the border color to exist.
1347 *
1348 * (We can skip uploading it if the sampler isn't going to use it.)
1349 */
1350 static bool
1351 wrap_mode_needs_border_color(unsigned wrap_mode)
1352 {
1353 return wrap_mode == TCM_CLAMP_BORDER || wrap_mode == TCM_HALF_BORDER;
1354 }
1355
1356 /**
1357 * Gallium CSO for sampler state.
1358 */
1359 struct iris_sampler_state {
1360 union pipe_color_union border_color;
1361 bool needs_border_color;
1362
1363 uint32_t sampler_state[GENX(SAMPLER_STATE_length)];
1364 };
1365
1366 /**
1367 * The pipe->create_sampler_state() driver hook.
1368 *
1369 * We fill out SAMPLER_STATE (except for the border color pointer), and
1370 * store that on the CPU. It doesn't make sense to upload it to a GPU
1371 * buffer object yet, because 3DSTATE_SAMPLER_STATE_POINTERS requires
1372 * all bound sampler states to be in contiguous memor.
1373 */
1374 static void *
1375 iris_create_sampler_state(struct pipe_context *ctx,
1376 const struct pipe_sampler_state *state)
1377 {
1378 struct iris_sampler_state *cso = CALLOC_STRUCT(iris_sampler_state);
1379
1380 if (!cso)
1381 return NULL;
1382
1383 STATIC_ASSERT(PIPE_TEX_FILTER_NEAREST == MAPFILTER_NEAREST);
1384 STATIC_ASSERT(PIPE_TEX_FILTER_LINEAR == MAPFILTER_LINEAR);
1385
1386 unsigned wrap_s = translate_wrap(state->wrap_s);
1387 unsigned wrap_t = translate_wrap(state->wrap_t);
1388 unsigned wrap_r = translate_wrap(state->wrap_r);
1389
1390 memcpy(&cso->border_color, &state->border_color, sizeof(cso->border_color));
1391
1392 cso->needs_border_color = wrap_mode_needs_border_color(wrap_s) ||
1393 wrap_mode_needs_border_color(wrap_t) ||
1394 wrap_mode_needs_border_color(wrap_r);
1395
1396 float min_lod = state->min_lod;
1397 unsigned mag_img_filter = state->mag_img_filter;
1398
1399 // XXX: explain this code ported from ilo...I don't get it at all...
1400 if (state->min_mip_filter == PIPE_TEX_MIPFILTER_NONE &&
1401 state->min_lod > 0.0f) {
1402 min_lod = 0.0f;
1403 mag_img_filter = state->min_img_filter;
1404 }
1405
1406 iris_pack_state(GENX(SAMPLER_STATE), cso->sampler_state, samp) {
1407 samp.TCXAddressControlMode = wrap_s;
1408 samp.TCYAddressControlMode = wrap_t;
1409 samp.TCZAddressControlMode = wrap_r;
1410 samp.CubeSurfaceControlMode = state->seamless_cube_map;
1411 samp.NonnormalizedCoordinateEnable = !state->normalized_coords;
1412 samp.MinModeFilter = state->min_img_filter;
1413 samp.MagModeFilter = mag_img_filter;
1414 samp.MipModeFilter = translate_mip_filter(state->min_mip_filter);
1415 samp.MaximumAnisotropy = RATIO21;
1416
1417 if (state->max_anisotropy >= 2) {
1418 if (state->min_img_filter == PIPE_TEX_FILTER_LINEAR) {
1419 samp.MinModeFilter = MAPFILTER_ANISOTROPIC;
1420 samp.AnisotropicAlgorithm = EWAApproximation;
1421 }
1422
1423 if (state->mag_img_filter == PIPE_TEX_FILTER_LINEAR)
1424 samp.MagModeFilter = MAPFILTER_ANISOTROPIC;
1425
1426 samp.MaximumAnisotropy =
1427 MIN2((state->max_anisotropy - 2) / 2, RATIO161);
1428 }
1429
1430 /* Set address rounding bits if not using nearest filtering. */
1431 if (state->min_img_filter != PIPE_TEX_FILTER_NEAREST) {
1432 samp.UAddressMinFilterRoundingEnable = true;
1433 samp.VAddressMinFilterRoundingEnable = true;
1434 samp.RAddressMinFilterRoundingEnable = true;
1435 }
1436
1437 if (state->mag_img_filter != PIPE_TEX_FILTER_NEAREST) {
1438 samp.UAddressMagFilterRoundingEnable = true;
1439 samp.VAddressMagFilterRoundingEnable = true;
1440 samp.RAddressMagFilterRoundingEnable = true;
1441 }
1442
1443 if (state->compare_mode == PIPE_TEX_COMPARE_R_TO_TEXTURE)
1444 samp.ShadowFunction = translate_shadow_func(state->compare_func);
1445
1446 const float hw_max_lod = GEN_GEN >= 7 ? 14 : 13;
1447
1448 samp.LODPreClampMode = CLAMP_MODE_OGL;
1449 samp.MinLOD = CLAMP(min_lod, 0, hw_max_lod);
1450 samp.MaxLOD = CLAMP(state->max_lod, 0, hw_max_lod);
1451 samp.TextureLODBias = CLAMP(state->lod_bias, -16, 15);
1452
1453 /* .BorderColorPointer is filled in by iris_bind_sampler_states. */
1454 }
1455
1456 return cso;
1457 }
1458
1459 /**
1460 * The pipe->bind_sampler_states() driver hook.
1461 */
1462 static void
1463 iris_bind_sampler_states(struct pipe_context *ctx,
1464 enum pipe_shader_type p_stage,
1465 unsigned start, unsigned count,
1466 void **states)
1467 {
1468 struct iris_context *ice = (struct iris_context *) ctx;
1469 gl_shader_stage stage = stage_from_pipe(p_stage);
1470 struct iris_shader_state *shs = &ice->state.shaders[stage];
1471
1472 assert(start + count <= IRIS_MAX_TEXTURE_SAMPLERS);
1473
1474 for (int i = 0; i < count; i++) {
1475 shs->samplers[start + i] = states[i];
1476 }
1477
1478 ice->state.dirty |= IRIS_DIRTY_SAMPLER_STATES_VS << stage;
1479 }
1480
1481 /**
1482 * Upload the sampler states into a contiguous area of GPU memory, for
1483 * for 3DSTATE_SAMPLER_STATE_POINTERS_*.
1484 *
1485 * Also fill out the border color state pointers.
1486 */
1487 static void
1488 iris_upload_sampler_states(struct iris_context *ice, gl_shader_stage stage)
1489 {
1490 struct iris_shader_state *shs = &ice->state.shaders[stage];
1491 const struct shader_info *info = iris_get_shader_info(ice, stage);
1492
1493 /* We assume the state tracker will call pipe->bind_sampler_states()
1494 * if the program's number of textures changes.
1495 */
1496 unsigned count = info ? util_last_bit(info->textures_used) : 0;
1497
1498 if (!count)
1499 return;
1500
1501 /* Assemble the SAMPLER_STATEs into a contiguous table that lives
1502 * in the dynamic state memory zone, so we can point to it via the
1503 * 3DSTATE_SAMPLER_STATE_POINTERS_* commands.
1504 */
1505 unsigned size = count * 4 * GENX(SAMPLER_STATE_length);
1506 uint32_t *map =
1507 upload_state(ice->state.dynamic_uploader, &shs->sampler_table, size, 32);
1508 if (unlikely(!map))
1509 return;
1510
1511 struct pipe_resource *res = shs->sampler_table.res;
1512 shs->sampler_table.offset +=
1513 iris_bo_offset_from_base_address(iris_resource_bo(res));
1514
1515 iris_record_state_size(ice->state.sizes, shs->sampler_table.offset, size);
1516
1517 /* Make sure all land in the same BO */
1518 iris_border_color_pool_reserve(ice, IRIS_MAX_TEXTURE_SAMPLERS);
1519
1520 ice->state.need_border_colors &= ~(1 << stage);
1521
1522 for (int i = 0; i < count; i++) {
1523 struct iris_sampler_state *state = shs->samplers[i];
1524 struct iris_sampler_view *tex = shs->textures[i];
1525
1526 if (!state) {
1527 memset(map, 0, 4 * GENX(SAMPLER_STATE_length));
1528 } else if (!state->needs_border_color) {
1529 memcpy(map, state->sampler_state, 4 * GENX(SAMPLER_STATE_length));
1530 } else {
1531 ice->state.need_border_colors |= 1 << stage;
1532
1533 /* We may need to swizzle the border color for format faking.
1534 * A/LA formats are faked as R/RG with 000R or R00G swizzles.
1535 * This means we need to move the border color's A channel into
1536 * the R or G channels so that those read swizzles will move it
1537 * back into A.
1538 */
1539 union pipe_color_union *color = &state->border_color;
1540 union pipe_color_union tmp;
1541 if (tex) {
1542 enum pipe_format internal_format = tex->res->internal_format;
1543
1544 if (util_format_is_alpha(internal_format)) {
1545 unsigned char swz[4] = {
1546 PIPE_SWIZZLE_W, PIPE_SWIZZLE_0,
1547 PIPE_SWIZZLE_0, PIPE_SWIZZLE_0
1548 };
1549 util_format_apply_color_swizzle(&tmp, color, swz, true);
1550 color = &tmp;
1551 } else if (util_format_is_luminance_alpha(internal_format) &&
1552 internal_format != PIPE_FORMAT_L8A8_SRGB) {
1553 unsigned char swz[4] = {
1554 PIPE_SWIZZLE_X, PIPE_SWIZZLE_W,
1555 PIPE_SWIZZLE_0, PIPE_SWIZZLE_0
1556 };
1557 util_format_apply_color_swizzle(&tmp, color, swz, true);
1558 color = &tmp;
1559 }
1560 }
1561
1562 /* Stream out the border color and merge the pointer. */
1563 uint32_t offset = iris_upload_border_color(ice, color);
1564
1565 uint32_t dynamic[GENX(SAMPLER_STATE_length)];
1566 iris_pack_state(GENX(SAMPLER_STATE), dynamic, dyns) {
1567 dyns.BorderColorPointer = offset;
1568 }
1569
1570 for (uint32_t j = 0; j < GENX(SAMPLER_STATE_length); j++)
1571 map[j] = state->sampler_state[j] | dynamic[j];
1572 }
1573
1574 map += GENX(SAMPLER_STATE_length);
1575 }
1576 }
1577
1578 static enum isl_channel_select
1579 fmt_swizzle(const struct iris_format_info *fmt, enum pipe_swizzle swz)
1580 {
1581 switch (swz) {
1582 case PIPE_SWIZZLE_X: return fmt->swizzle.r;
1583 case PIPE_SWIZZLE_Y: return fmt->swizzle.g;
1584 case PIPE_SWIZZLE_Z: return fmt->swizzle.b;
1585 case PIPE_SWIZZLE_W: return fmt->swizzle.a;
1586 case PIPE_SWIZZLE_1: return SCS_ONE;
1587 case PIPE_SWIZZLE_0: return SCS_ZERO;
1588 default: unreachable("invalid swizzle");
1589 }
1590 }
1591
1592 static void
1593 fill_buffer_surface_state(struct isl_device *isl_dev,
1594 struct iris_resource *res,
1595 void *map,
1596 enum isl_format format,
1597 struct isl_swizzle swizzle,
1598 unsigned offset,
1599 unsigned size)
1600 {
1601 const struct isl_format_layout *fmtl = isl_format_get_layout(format);
1602 const unsigned cpp = format == ISL_FORMAT_RAW ? 1 : fmtl->bpb / 8;
1603
1604 /* The ARB_texture_buffer_specification says:
1605 *
1606 * "The number of texels in the buffer texture's texel array is given by
1607 *
1608 * floor(<buffer_size> / (<components> * sizeof(<base_type>)),
1609 *
1610 * where <buffer_size> is the size of the buffer object, in basic
1611 * machine units and <components> and <base_type> are the element count
1612 * and base data type for elements, as specified in Table X.1. The
1613 * number of texels in the texel array is then clamped to the
1614 * implementation-dependent limit MAX_TEXTURE_BUFFER_SIZE_ARB."
1615 *
1616 * We need to clamp the size in bytes to MAX_TEXTURE_BUFFER_SIZE * stride,
1617 * so that when ISL divides by stride to obtain the number of texels, that
1618 * texel count is clamped to MAX_TEXTURE_BUFFER_SIZE.
1619 */
1620 unsigned final_size =
1621 MIN3(size, res->bo->size - res->offset - offset,
1622 IRIS_MAX_TEXTURE_BUFFER_SIZE * cpp);
1623
1624 isl_buffer_fill_state(isl_dev, map,
1625 .address = res->bo->gtt_offset + res->offset + offset,
1626 .size_B = final_size,
1627 .format = format,
1628 .swizzle = swizzle,
1629 .stride_B = cpp,
1630 .mocs = mocs(res->bo));
1631 }
1632
1633 #define SURFACE_STATE_ALIGNMENT 64
1634
1635 /**
1636 * Allocate several contiguous SURFACE_STATE structures, one for each
1637 * supported auxiliary surface mode.
1638 */
1639 static void *
1640 alloc_surface_states(struct u_upload_mgr *mgr,
1641 struct iris_state_ref *ref,
1642 unsigned aux_usages)
1643 {
1644 const unsigned surf_size = 4 * GENX(RENDER_SURFACE_STATE_length);
1645
1646 /* If this changes, update this to explicitly align pointers */
1647 STATIC_ASSERT(surf_size == SURFACE_STATE_ALIGNMENT);
1648
1649 assert(aux_usages != 0);
1650
1651 void *map =
1652 upload_state(mgr, ref, util_bitcount(aux_usages) * surf_size,
1653 SURFACE_STATE_ALIGNMENT);
1654
1655 ref->offset += iris_bo_offset_from_base_address(iris_resource_bo(ref->res));
1656
1657 return map;
1658 }
1659
1660 static void
1661 fill_surface_state(struct isl_device *isl_dev,
1662 void *map,
1663 struct iris_resource *res,
1664 struct isl_view *view,
1665 unsigned aux_usage)
1666 {
1667 struct isl_surf_fill_state_info f = {
1668 .surf = &res->surf,
1669 .view = view,
1670 .mocs = mocs(res->bo),
1671 .address = res->bo->gtt_offset + res->offset,
1672 };
1673
1674 if (aux_usage != ISL_AUX_USAGE_NONE) {
1675 f.aux_surf = &res->aux.surf;
1676 f.aux_usage = aux_usage;
1677 f.aux_address = res->aux.bo->gtt_offset + res->aux.offset;
1678
1679 struct iris_bo *clear_bo = NULL;
1680 uint64_t clear_offset = 0;
1681 f.clear_color =
1682 iris_resource_get_clear_color(res, &clear_bo, &clear_offset);
1683 if (clear_bo) {
1684 f.clear_address = clear_bo->gtt_offset + clear_offset;
1685 f.use_clear_address = isl_dev->info->gen > 9;
1686 }
1687 }
1688
1689 isl_surf_fill_state_s(isl_dev, map, &f);
1690 }
1691
1692 /**
1693 * The pipe->create_sampler_view() driver hook.
1694 */
1695 static struct pipe_sampler_view *
1696 iris_create_sampler_view(struct pipe_context *ctx,
1697 struct pipe_resource *tex,
1698 const struct pipe_sampler_view *tmpl)
1699 {
1700 struct iris_context *ice = (struct iris_context *) ctx;
1701 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1702 const struct gen_device_info *devinfo = &screen->devinfo;
1703 struct iris_sampler_view *isv = calloc(1, sizeof(struct iris_sampler_view));
1704
1705 if (!isv)
1706 return NULL;
1707
1708 /* initialize base object */
1709 isv->base = *tmpl;
1710 isv->base.context = ctx;
1711 isv->base.texture = NULL;
1712 pipe_reference_init(&isv->base.reference, 1);
1713 pipe_resource_reference(&isv->base.texture, tex);
1714
1715 if (util_format_is_depth_or_stencil(tmpl->format)) {
1716 struct iris_resource *zres, *sres;
1717 const struct util_format_description *desc =
1718 util_format_description(tmpl->format);
1719
1720 iris_get_depth_stencil_resources(tex, &zres, &sres);
1721
1722 tex = util_format_has_depth(desc) ? &zres->base : &sres->base;
1723 }
1724
1725 isv->res = (struct iris_resource *) tex;
1726
1727 void *map = alloc_surface_states(ice->state.surface_uploader,
1728 &isv->surface_state,
1729 isv->res->aux.sampler_usages);
1730 if (!unlikely(map))
1731 return NULL;
1732
1733 isl_surf_usage_flags_t usage = ISL_SURF_USAGE_TEXTURE_BIT;
1734
1735 if (isv->base.target == PIPE_TEXTURE_CUBE ||
1736 isv->base.target == PIPE_TEXTURE_CUBE_ARRAY)
1737 usage |= ISL_SURF_USAGE_CUBE_BIT;
1738
1739 const struct iris_format_info fmt =
1740 iris_format_for_usage(devinfo, tmpl->format, usage);
1741
1742 isv->clear_color = isv->res->aux.clear_color;
1743
1744 isv->view = (struct isl_view) {
1745 .format = fmt.fmt,
1746 .swizzle = (struct isl_swizzle) {
1747 .r = fmt_swizzle(&fmt, tmpl->swizzle_r),
1748 .g = fmt_swizzle(&fmt, tmpl->swizzle_g),
1749 .b = fmt_swizzle(&fmt, tmpl->swizzle_b),
1750 .a = fmt_swizzle(&fmt, tmpl->swizzle_a),
1751 },
1752 .usage = usage,
1753 };
1754
1755 /* Fill out SURFACE_STATE for this view. */
1756 if (tmpl->target != PIPE_BUFFER) {
1757 isv->view.base_level = tmpl->u.tex.first_level;
1758 isv->view.levels = tmpl->u.tex.last_level - tmpl->u.tex.first_level + 1;
1759 // XXX: do I need to port f9fd0cf4790cb2a530e75d1a2206dbb9d8af7cb2?
1760 isv->view.base_array_layer = tmpl->u.tex.first_layer;
1761 isv->view.array_len =
1762 tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1;
1763
1764 unsigned aux_modes = isv->res->aux.sampler_usages;
1765 while (aux_modes) {
1766 enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
1767
1768 /* If we have a multisampled depth buffer, do not create a sampler
1769 * surface state with HiZ.
1770 */
1771 fill_surface_state(&screen->isl_dev, map, isv->res, &isv->view,
1772 aux_usage);
1773
1774 map += SURFACE_STATE_ALIGNMENT;
1775 }
1776 } else {
1777 fill_buffer_surface_state(&screen->isl_dev, isv->res, map,
1778 isv->view.format, isv->view.swizzle,
1779 tmpl->u.buf.offset, tmpl->u.buf.size);
1780 }
1781
1782 return &isv->base;
1783 }
1784
1785 static void
1786 iris_sampler_view_destroy(struct pipe_context *ctx,
1787 struct pipe_sampler_view *state)
1788 {
1789 struct iris_sampler_view *isv = (void *) state;
1790 pipe_resource_reference(&state->texture, NULL);
1791 pipe_resource_reference(&isv->surface_state.res, NULL);
1792 free(isv);
1793 }
1794
1795 /**
1796 * The pipe->create_surface() driver hook.
1797 *
1798 * In Gallium nomenclature, "surfaces" are a view of a resource that
1799 * can be bound as a render target or depth/stencil buffer.
1800 */
1801 static struct pipe_surface *
1802 iris_create_surface(struct pipe_context *ctx,
1803 struct pipe_resource *tex,
1804 const struct pipe_surface *tmpl)
1805 {
1806 struct iris_context *ice = (struct iris_context *) ctx;
1807 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1808 const struct gen_device_info *devinfo = &screen->devinfo;
1809
1810 isl_surf_usage_flags_t usage = 0;
1811 if (tmpl->writable)
1812 usage = ISL_SURF_USAGE_STORAGE_BIT;
1813 else if (util_format_is_depth_or_stencil(tmpl->format))
1814 usage = ISL_SURF_USAGE_DEPTH_BIT;
1815 else
1816 usage = ISL_SURF_USAGE_RENDER_TARGET_BIT;
1817
1818 const struct iris_format_info fmt =
1819 iris_format_for_usage(devinfo, tmpl->format, usage);
1820
1821 if ((usage & ISL_SURF_USAGE_RENDER_TARGET_BIT) &&
1822 !isl_format_supports_rendering(devinfo, fmt.fmt)) {
1823 /* Framebuffer validation will reject this invalid case, but it
1824 * hasn't had the opportunity yet. In the meantime, we need to
1825 * avoid hitting ISL asserts about unsupported formats below.
1826 */
1827 return NULL;
1828 }
1829
1830 struct iris_surface *surf = calloc(1, sizeof(struct iris_surface));
1831 struct pipe_surface *psurf = &surf->base;
1832 struct iris_resource *res = (struct iris_resource *) tex;
1833
1834 if (!surf)
1835 return NULL;
1836
1837 pipe_reference_init(&psurf->reference, 1);
1838 pipe_resource_reference(&psurf->texture, tex);
1839 psurf->context = ctx;
1840 psurf->format = tmpl->format;
1841 psurf->width = tex->width0;
1842 psurf->height = tex->height0;
1843 psurf->texture = tex;
1844 psurf->u.tex.first_layer = tmpl->u.tex.first_layer;
1845 psurf->u.tex.last_layer = tmpl->u.tex.last_layer;
1846 psurf->u.tex.level = tmpl->u.tex.level;
1847
1848 struct isl_view *view = &surf->view;
1849 *view = (struct isl_view) {
1850 .format = fmt.fmt,
1851 .base_level = tmpl->u.tex.level,
1852 .levels = 1,
1853 .base_array_layer = tmpl->u.tex.first_layer,
1854 .array_len = tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1,
1855 .swizzle = ISL_SWIZZLE_IDENTITY,
1856 .usage = usage,
1857 };
1858
1859 surf->clear_color = res->aux.clear_color;
1860
1861 /* Bail early for depth/stencil - we don't want SURFACE_STATE for them. */
1862 if (res->surf.usage & (ISL_SURF_USAGE_DEPTH_BIT |
1863 ISL_SURF_USAGE_STENCIL_BIT))
1864 return psurf;
1865
1866
1867 void *map = alloc_surface_states(ice->state.surface_uploader,
1868 &surf->surface_state,
1869 res->aux.possible_usages);
1870 if (!unlikely(map))
1871 return NULL;
1872
1873 if (!isl_format_is_compressed(res->surf.format)) {
1874 /* This is a normal surface. Fill out a SURFACE_STATE for each possible
1875 * auxiliary surface mode and return the pipe_surface.
1876 */
1877 unsigned aux_modes = res->aux.possible_usages;
1878 while (aux_modes) {
1879 enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
1880
1881 fill_surface_state(&screen->isl_dev, map, res, view, aux_usage);
1882
1883 map += SURFACE_STATE_ALIGNMENT;
1884 }
1885
1886 return psurf;
1887 }
1888
1889 /* The resource has a compressed format, which is not renderable, but we
1890 * have a renderable view format. We must be attempting to upload blocks
1891 * of compressed data via an uncompressed view.
1892 *
1893 * In this case, we can assume there are no auxiliary buffers, a single
1894 * miplevel, and that the resource is single-sampled. Gallium may try
1895 * and create an uncompressed view with multiple layers, however.
1896 */
1897 assert(!isl_format_is_compressed(fmt.fmt));
1898 assert(res->aux.possible_usages == 1 << ISL_AUX_USAGE_NONE);
1899 assert(res->surf.samples == 1);
1900 assert(view->levels == 1);
1901
1902 struct isl_surf isl_surf;
1903 uint32_t offset_B = 0, tile_x_sa = 0, tile_y_sa = 0;
1904
1905 if (view->base_level > 0) {
1906 /* We can't rely on the hardware's miplevel selection with such
1907 * a substantial lie about the format, so we select a single image
1908 * using the Tile X/Y Offset fields. In this case, we can't handle
1909 * multiple array slices.
1910 *
1911 * On Broadwell, HALIGN and VALIGN are specified in pixels and are
1912 * hard-coded to align to exactly the block size of the compressed
1913 * texture. This means that, when reinterpreted as a non-compressed
1914 * texture, the tile offsets may be anything and we can't rely on
1915 * X/Y Offset.
1916 *
1917 * Return NULL to force the state tracker to take fallback paths.
1918 */
1919 if (view->array_len > 1 || GEN_GEN == 8)
1920 return NULL;
1921
1922 const bool is_3d = res->surf.dim == ISL_SURF_DIM_3D;
1923 isl_surf_get_image_surf(&screen->isl_dev, &res->surf,
1924 view->base_level,
1925 is_3d ? 0 : view->base_array_layer,
1926 is_3d ? view->base_array_layer : 0,
1927 &isl_surf,
1928 &offset_B, &tile_x_sa, &tile_y_sa);
1929
1930 /* We use address and tile offsets to access a single level/layer
1931 * as a subimage, so reset level/layer so it doesn't offset again.
1932 */
1933 view->base_array_layer = 0;
1934 view->base_level = 0;
1935 } else {
1936 /* Level 0 doesn't require tile offsets, and the hardware can find
1937 * array slices using QPitch even with the format override, so we
1938 * can allow layers in this case. Copy the original ISL surface.
1939 */
1940 memcpy(&isl_surf, &res->surf, sizeof(isl_surf));
1941 }
1942
1943 /* Scale down the image dimensions by the block size. */
1944 const struct isl_format_layout *fmtl =
1945 isl_format_get_layout(res->surf.format);
1946 isl_surf.format = fmt.fmt;
1947 isl_surf.logical_level0_px = isl_surf_get_logical_level0_el(&isl_surf);
1948 isl_surf.phys_level0_sa = isl_surf_get_phys_level0_el(&isl_surf);
1949 tile_x_sa /= fmtl->bw;
1950 tile_y_sa /= fmtl->bh;
1951
1952 psurf->width = isl_surf.logical_level0_px.width;
1953 psurf->height = isl_surf.logical_level0_px.height;
1954
1955 struct isl_surf_fill_state_info f = {
1956 .surf = &isl_surf,
1957 .view = view,
1958 .mocs = mocs(res->bo),
1959 .address = res->bo->gtt_offset + offset_B,
1960 .x_offset_sa = tile_x_sa,
1961 .y_offset_sa = tile_y_sa,
1962 };
1963
1964 isl_surf_fill_state_s(&screen->isl_dev, map, &f);
1965 return psurf;
1966 }
1967
1968 #if GEN_GEN < 9
1969 static void
1970 fill_default_image_param(struct brw_image_param *param)
1971 {
1972 memset(param, 0, sizeof(*param));
1973 /* Set the swizzling shifts to all-ones to effectively disable swizzling --
1974 * See emit_address_calculation() in brw_fs_surface_builder.cpp for a more
1975 * detailed explanation of these parameters.
1976 */
1977 param->swizzling[0] = 0xff;
1978 param->swizzling[1] = 0xff;
1979 }
1980
1981 static void
1982 fill_buffer_image_param(struct brw_image_param *param,
1983 enum pipe_format pfmt,
1984 unsigned size)
1985 {
1986 const unsigned cpp = util_format_get_blocksize(pfmt);
1987
1988 fill_default_image_param(param);
1989 param->size[0] = size / cpp;
1990 param->stride[0] = cpp;
1991 }
1992 #else
1993 #define isl_surf_fill_image_param(x, ...)
1994 #define fill_default_image_param(x, ...)
1995 #define fill_buffer_image_param(x, ...)
1996 #endif
1997
1998 /**
1999 * The pipe->set_shader_images() driver hook.
2000 */
2001 static void
2002 iris_set_shader_images(struct pipe_context *ctx,
2003 enum pipe_shader_type p_stage,
2004 unsigned start_slot, unsigned count,
2005 const struct pipe_image_view *p_images)
2006 {
2007 struct iris_context *ice = (struct iris_context *) ctx;
2008 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
2009 const struct gen_device_info *devinfo = &screen->devinfo;
2010 gl_shader_stage stage = stage_from_pipe(p_stage);
2011 struct iris_shader_state *shs = &ice->state.shaders[stage];
2012 #if GEN_GEN == 8
2013 struct iris_genx_state *genx = ice->state.genx;
2014 struct brw_image_param *image_params = genx->shaders[stage].image_param;
2015 #endif
2016
2017 shs->bound_image_views &= ~u_bit_consecutive(start_slot, count);
2018
2019 for (unsigned i = 0; i < count; i++) {
2020 struct iris_image_view *iv = &shs->image[start_slot + i];
2021
2022 if (p_images && p_images[i].resource) {
2023 const struct pipe_image_view *img = &p_images[i];
2024 struct iris_resource *res = (void *) img->resource;
2025
2026 void *map =
2027 alloc_surface_states(ice->state.surface_uploader,
2028 &iv->surface_state, 1 << ISL_AUX_USAGE_NONE);
2029 if (!unlikely(map))
2030 return;
2031
2032 util_copy_image_view(&iv->base, img);
2033
2034 shs->bound_image_views |= 1 << (start_slot + i);
2035
2036 res->bind_history |= PIPE_BIND_SHADER_IMAGE;
2037
2038 isl_surf_usage_flags_t usage = ISL_SURF_USAGE_STORAGE_BIT;
2039 enum isl_format isl_fmt =
2040 iris_format_for_usage(devinfo, img->format, usage).fmt;
2041
2042 bool untyped_fallback = false;
2043
2044 if (img->shader_access & PIPE_IMAGE_ACCESS_READ) {
2045 /* On Gen8, try to use typed surfaces reads (which support a
2046 * limited number of formats), and if not possible, fall back
2047 * to untyped reads.
2048 */
2049 untyped_fallback = GEN_GEN == 8 &&
2050 !isl_has_matching_typed_storage_image_format(devinfo, isl_fmt);
2051
2052 if (untyped_fallback)
2053 isl_fmt = ISL_FORMAT_RAW;
2054 else
2055 isl_fmt = isl_lower_storage_image_format(devinfo, isl_fmt);
2056 }
2057
2058 if (res->base.target != PIPE_BUFFER) {
2059 struct isl_view view = {
2060 .format = isl_fmt,
2061 .base_level = img->u.tex.level,
2062 .levels = 1,
2063 .base_array_layer = img->u.tex.first_layer,
2064 .array_len = img->u.tex.last_layer - img->u.tex.first_layer + 1,
2065 .swizzle = ISL_SWIZZLE_IDENTITY,
2066 .usage = usage,
2067 };
2068
2069 if (untyped_fallback) {
2070 fill_buffer_surface_state(&screen->isl_dev, res, map,
2071 isl_fmt, ISL_SWIZZLE_IDENTITY,
2072 0, res->bo->size);
2073 } else {
2074 /* Images don't support compression */
2075 unsigned aux_modes = 1 << ISL_AUX_USAGE_NONE;
2076 while (aux_modes) {
2077 enum isl_aux_usage usage = u_bit_scan(&aux_modes);
2078
2079 fill_surface_state(&screen->isl_dev, map, res, &view, usage);
2080
2081 map += SURFACE_STATE_ALIGNMENT;
2082 }
2083 }
2084
2085 isl_surf_fill_image_param(&screen->isl_dev,
2086 &image_params[start_slot + i],
2087 &res->surf, &view);
2088 } else {
2089 util_range_add(&res->valid_buffer_range, img->u.buf.offset,
2090 img->u.buf.offset + img->u.buf.size);
2091
2092 fill_buffer_surface_state(&screen->isl_dev, res, map,
2093 isl_fmt, ISL_SWIZZLE_IDENTITY,
2094 img->u.buf.offset, img->u.buf.size);
2095 fill_buffer_image_param(&image_params[start_slot + i],
2096 img->format, img->u.buf.size);
2097 }
2098 } else {
2099 pipe_resource_reference(&iv->base.resource, NULL);
2100 pipe_resource_reference(&iv->surface_state.res, NULL);
2101 fill_default_image_param(&image_params[start_slot + i]);
2102 }
2103 }
2104
2105 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
2106 ice->state.dirty |=
2107 stage == MESA_SHADER_COMPUTE ? IRIS_DIRTY_COMPUTE_RESOLVES_AND_FLUSHES
2108 : IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
2109
2110 /* Broadwell also needs brw_image_params re-uploaded */
2111 if (GEN_GEN < 9) {
2112 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS << stage;
2113 shs->sysvals_need_upload = true;
2114 }
2115 }
2116
2117
2118 /**
2119 * The pipe->set_sampler_views() driver hook.
2120 */
2121 static void
2122 iris_set_sampler_views(struct pipe_context *ctx,
2123 enum pipe_shader_type p_stage,
2124 unsigned start, unsigned count,
2125 struct pipe_sampler_view **views)
2126 {
2127 struct iris_context *ice = (struct iris_context *) ctx;
2128 gl_shader_stage stage = stage_from_pipe(p_stage);
2129 struct iris_shader_state *shs = &ice->state.shaders[stage];
2130
2131 shs->bound_sampler_views &= ~u_bit_consecutive(start, count);
2132
2133 for (unsigned i = 0; i < count; i++) {
2134 struct pipe_sampler_view *pview = views ? views[i] : NULL;
2135 pipe_sampler_view_reference((struct pipe_sampler_view **)
2136 &shs->textures[start + i], pview);
2137 struct iris_sampler_view *view = (void *) pview;
2138 if (view) {
2139 view->res->bind_history |= PIPE_BIND_SAMPLER_VIEW;
2140 shs->bound_sampler_views |= 1 << (start + i);
2141 }
2142 }
2143
2144 ice->state.dirty |= (IRIS_DIRTY_BINDINGS_VS << stage);
2145 ice->state.dirty |=
2146 stage == MESA_SHADER_COMPUTE ? IRIS_DIRTY_COMPUTE_RESOLVES_AND_FLUSHES
2147 : IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
2148 }
2149
2150 /**
2151 * The pipe->set_tess_state() driver hook.
2152 */
2153 static void
2154 iris_set_tess_state(struct pipe_context *ctx,
2155 const float default_outer_level[4],
2156 const float default_inner_level[2])
2157 {
2158 struct iris_context *ice = (struct iris_context *) ctx;
2159 struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_TESS_CTRL];
2160
2161 memcpy(&ice->state.default_outer_level[0], &default_outer_level[0], 4 * sizeof(float));
2162 memcpy(&ice->state.default_inner_level[0], &default_inner_level[0], 2 * sizeof(float));
2163
2164 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_TCS;
2165 shs->sysvals_need_upload = true;
2166 }
2167
2168 static void
2169 iris_surface_destroy(struct pipe_context *ctx, struct pipe_surface *p_surf)
2170 {
2171 struct iris_surface *surf = (void *) p_surf;
2172 pipe_resource_reference(&p_surf->texture, NULL);
2173 pipe_resource_reference(&surf->surface_state.res, NULL);
2174 free(surf);
2175 }
2176
2177 static void
2178 iris_set_clip_state(struct pipe_context *ctx,
2179 const struct pipe_clip_state *state)
2180 {
2181 struct iris_context *ice = (struct iris_context *) ctx;
2182 struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_VERTEX];
2183 struct iris_shader_state *gshs = &ice->state.shaders[MESA_SHADER_GEOMETRY];
2184 struct iris_shader_state *tshs = &ice->state.shaders[MESA_SHADER_TESS_EVAL];
2185
2186 memcpy(&ice->state.clip_planes, state, sizeof(*state));
2187
2188 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS | IRIS_DIRTY_CONSTANTS_GS |
2189 IRIS_DIRTY_CONSTANTS_TES;
2190 shs->sysvals_need_upload = true;
2191 gshs->sysvals_need_upload = true;
2192 tshs->sysvals_need_upload = true;
2193 }
2194
2195 /**
2196 * The pipe->set_polygon_stipple() driver hook.
2197 */
2198 static void
2199 iris_set_polygon_stipple(struct pipe_context *ctx,
2200 const struct pipe_poly_stipple *state)
2201 {
2202 struct iris_context *ice = (struct iris_context *) ctx;
2203 memcpy(&ice->state.poly_stipple, state, sizeof(*state));
2204 ice->state.dirty |= IRIS_DIRTY_POLYGON_STIPPLE;
2205 }
2206
2207 /**
2208 * The pipe->set_sample_mask() driver hook.
2209 */
2210 static void
2211 iris_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
2212 {
2213 struct iris_context *ice = (struct iris_context *) ctx;
2214
2215 /* We only support 16x MSAA, so we have 16 bits of sample maks.
2216 * st/mesa may pass us 0xffffffff though, meaning "enable all samples".
2217 */
2218 ice->state.sample_mask = sample_mask & 0xffff;
2219 ice->state.dirty |= IRIS_DIRTY_SAMPLE_MASK;
2220 }
2221
2222 /**
2223 * The pipe->set_scissor_states() driver hook.
2224 *
2225 * This corresponds to our SCISSOR_RECT state structures. It's an
2226 * exact match, so we just store them, and memcpy them out later.
2227 */
2228 static void
2229 iris_set_scissor_states(struct pipe_context *ctx,
2230 unsigned start_slot,
2231 unsigned num_scissors,
2232 const struct pipe_scissor_state *rects)
2233 {
2234 struct iris_context *ice = (struct iris_context *) ctx;
2235
2236 for (unsigned i = 0; i < num_scissors; i++) {
2237 if (rects[i].minx == rects[i].maxx || rects[i].miny == rects[i].maxy) {
2238 /* If the scissor was out of bounds and got clamped to 0 width/height
2239 * at the bounds, the subtraction of 1 from maximums could produce a
2240 * negative number and thus not clip anything. Instead, just provide
2241 * a min > max scissor inside the bounds, which produces the expected
2242 * no rendering.
2243 */
2244 ice->state.scissors[start_slot + i] = (struct pipe_scissor_state) {
2245 .minx = 1, .maxx = 0, .miny = 1, .maxy = 0,
2246 };
2247 } else {
2248 ice->state.scissors[start_slot + i] = (struct pipe_scissor_state) {
2249 .minx = rects[i].minx, .miny = rects[i].miny,
2250 .maxx = rects[i].maxx - 1, .maxy = rects[i].maxy - 1,
2251 };
2252 }
2253 }
2254
2255 ice->state.dirty |= IRIS_DIRTY_SCISSOR_RECT;
2256 }
2257
2258 /**
2259 * The pipe->set_stencil_ref() driver hook.
2260 *
2261 * This is added to 3DSTATE_WM_DEPTH_STENCIL dynamically at draw time.
2262 */
2263 static void
2264 iris_set_stencil_ref(struct pipe_context *ctx,
2265 const struct pipe_stencil_ref *state)
2266 {
2267 struct iris_context *ice = (struct iris_context *) ctx;
2268 memcpy(&ice->state.stencil_ref, state, sizeof(*state));
2269 if (GEN_GEN == 8)
2270 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
2271 else
2272 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
2273 }
2274
2275 static float
2276 viewport_extent(const struct pipe_viewport_state *state, int axis, float sign)
2277 {
2278 return copysignf(state->scale[axis], sign) + state->translate[axis];
2279 }
2280
2281 /**
2282 * The pipe->set_viewport_states() driver hook.
2283 *
2284 * This corresponds to our SF_CLIP_VIEWPORT states. We can't calculate
2285 * the guardband yet, as we need the framebuffer dimensions, but we can
2286 * at least fill out the rest.
2287 */
2288 static void
2289 iris_set_viewport_states(struct pipe_context *ctx,
2290 unsigned start_slot,
2291 unsigned count,
2292 const struct pipe_viewport_state *states)
2293 {
2294 struct iris_context *ice = (struct iris_context *) ctx;
2295
2296 memcpy(&ice->state.viewports[start_slot], states, sizeof(*states) * count);
2297
2298 ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
2299
2300 if (ice->state.cso_rast && (!ice->state.cso_rast->depth_clip_near ||
2301 !ice->state.cso_rast->depth_clip_far))
2302 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
2303 }
2304
2305 /**
2306 * The pipe->set_framebuffer_state() driver hook.
2307 *
2308 * Sets the current draw FBO, including color render targets, depth,
2309 * and stencil buffers.
2310 */
2311 static void
2312 iris_set_framebuffer_state(struct pipe_context *ctx,
2313 const struct pipe_framebuffer_state *state)
2314 {
2315 struct iris_context *ice = (struct iris_context *) ctx;
2316 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
2317 struct isl_device *isl_dev = &screen->isl_dev;
2318 struct pipe_framebuffer_state *cso = &ice->state.framebuffer;
2319 struct iris_resource *zres;
2320 struct iris_resource *stencil_res;
2321
2322 unsigned samples = util_framebuffer_get_num_samples(state);
2323 unsigned layers = util_framebuffer_get_num_layers(state);
2324
2325 if (cso->samples != samples) {
2326 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
2327
2328 /* We need to toggle 3DSTATE_PS::32 Pixel Dispatch Enable */
2329 if (GEN_GEN >= 9 && (cso->samples == 16 || samples == 16))
2330 ice->state.dirty |= IRIS_DIRTY_FS;
2331 }
2332
2333 if (cso->nr_cbufs != state->nr_cbufs) {
2334 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
2335 }
2336
2337 if ((cso->layers == 0) != (layers == 0)) {
2338 ice->state.dirty |= IRIS_DIRTY_CLIP;
2339 }
2340
2341 if (cso->width != state->width || cso->height != state->height) {
2342 ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
2343 }
2344
2345 if (cso->zsbuf || state->zsbuf) {
2346 ice->state.dirty |= IRIS_DIRTY_DEPTH_BUFFER;
2347 }
2348
2349 util_copy_framebuffer_state(cso, state);
2350 cso->samples = samples;
2351 cso->layers = layers;
2352
2353 struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
2354
2355 struct isl_view view = {
2356 .base_level = 0,
2357 .levels = 1,
2358 .base_array_layer = 0,
2359 .array_len = 1,
2360 .swizzle = ISL_SWIZZLE_IDENTITY,
2361 };
2362
2363 struct isl_depth_stencil_hiz_emit_info info = { .view = &view };
2364
2365 if (cso->zsbuf) {
2366 iris_get_depth_stencil_resources(cso->zsbuf->texture, &zres,
2367 &stencil_res);
2368
2369 view.base_level = cso->zsbuf->u.tex.level;
2370 view.base_array_layer = cso->zsbuf->u.tex.first_layer;
2371 view.array_len =
2372 cso->zsbuf->u.tex.last_layer - cso->zsbuf->u.tex.first_layer + 1;
2373
2374 if (zres) {
2375 view.usage |= ISL_SURF_USAGE_DEPTH_BIT;
2376
2377 info.depth_surf = &zres->surf;
2378 info.depth_address = zres->bo->gtt_offset + zres->offset;
2379 info.mocs = mocs(zres->bo);
2380
2381 view.format = zres->surf.format;
2382
2383 if (iris_resource_level_has_hiz(zres, view.base_level)) {
2384 info.hiz_usage = ISL_AUX_USAGE_HIZ;
2385 info.hiz_surf = &zres->aux.surf;
2386 info.hiz_address = zres->aux.bo->gtt_offset;
2387 }
2388 }
2389
2390 if (stencil_res) {
2391 view.usage |= ISL_SURF_USAGE_STENCIL_BIT;
2392 info.stencil_surf = &stencil_res->surf;
2393 info.stencil_address = stencil_res->bo->gtt_offset + stencil_res->offset;
2394 if (!zres) {
2395 view.format = stencil_res->surf.format;
2396 info.mocs = mocs(stencil_res->bo);
2397 }
2398 }
2399 }
2400
2401 isl_emit_depth_stencil_hiz_s(isl_dev, cso_z->packets, &info);
2402
2403 /* Make a null surface for unbound buffers */
2404 void *null_surf_map =
2405 upload_state(ice->state.surface_uploader, &ice->state.null_fb,
2406 4 * GENX(RENDER_SURFACE_STATE_length), 64);
2407 isl_null_fill_state(&screen->isl_dev, null_surf_map,
2408 isl_extent3d(MAX2(cso->width, 1),
2409 MAX2(cso->height, 1),
2410 cso->layers ? cso->layers : 1));
2411 ice->state.null_fb.offset +=
2412 iris_bo_offset_from_base_address(iris_resource_bo(ice->state.null_fb.res));
2413
2414 /* Render target change */
2415 ice->state.dirty |= IRIS_DIRTY_BINDINGS_FS;
2416
2417 ice->state.dirty |= IRIS_DIRTY_RENDER_RESOLVES_AND_FLUSHES;
2418
2419 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_FRAMEBUFFER];
2420
2421 #if GEN_GEN == 11
2422 // XXX: we may want to flag IRIS_DIRTY_MULTISAMPLE (or SAMPLE_MASK?)
2423 // XXX: see commit 979fc1bc9bcc64027ff2cfafd285676f31b930a6
2424
2425 /* The PIPE_CONTROL command description says:
2426 *
2427 * "Whenever a Binding Table Index (BTI) used by a Render Target Message
2428 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
2429 * Target Cache Flush by enabling this bit. When render target flush
2430 * is set due to new association of BTI, PS Scoreboard Stall bit must
2431 * be set in this packet."
2432 */
2433 // XXX: does this need to happen at 3DSTATE_BTP_PS time?
2434 iris_emit_pipe_control_flush(&ice->batches[IRIS_BATCH_RENDER],
2435 "workaround: RT BTI change [draw]",
2436 PIPE_CONTROL_RENDER_TARGET_FLUSH |
2437 PIPE_CONTROL_STALL_AT_SCOREBOARD);
2438 #endif
2439 }
2440
2441 /**
2442 * The pipe->set_constant_buffer() driver hook.
2443 *
2444 * This uploads any constant data in user buffers, and references
2445 * any UBO resources containing constant data.
2446 */
2447 static void
2448 iris_set_constant_buffer(struct pipe_context *ctx,
2449 enum pipe_shader_type p_stage, unsigned index,
2450 const struct pipe_constant_buffer *input)
2451 {
2452 struct iris_context *ice = (struct iris_context *) ctx;
2453 gl_shader_stage stage = stage_from_pipe(p_stage);
2454 struct iris_shader_state *shs = &ice->state.shaders[stage];
2455 struct pipe_shader_buffer *cbuf = &shs->constbuf[index];
2456
2457 if (input && input->buffer_size && (input->buffer || input->user_buffer)) {
2458 shs->bound_cbufs |= 1u << index;
2459
2460 if (input->user_buffer) {
2461 void *map = NULL;
2462 pipe_resource_reference(&cbuf->buffer, NULL);
2463 u_upload_alloc(ice->ctx.const_uploader, 0, input->buffer_size, 64,
2464 &cbuf->buffer_offset, &cbuf->buffer, (void **) &map);
2465
2466 if (!cbuf->buffer) {
2467 /* Allocation was unsuccessful - just unbind */
2468 iris_set_constant_buffer(ctx, p_stage, index, NULL);
2469 return;
2470 }
2471
2472 assert(map);
2473 memcpy(map, input->user_buffer, input->buffer_size);
2474 } else if (input->buffer) {
2475 pipe_resource_reference(&cbuf->buffer, input->buffer);
2476
2477 cbuf->buffer_offset = input->buffer_offset;
2478 cbuf->buffer_size =
2479 MIN2(input->buffer_size,
2480 iris_resource_bo(cbuf->buffer)->size - cbuf->buffer_offset);
2481 }
2482
2483 struct iris_resource *res = (void *) cbuf->buffer;
2484 res->bind_history |= PIPE_BIND_CONSTANT_BUFFER;
2485
2486 iris_upload_ubo_ssbo_surf_state(ice, cbuf,
2487 &shs->constbuf_surf_state[index],
2488 false);
2489 } else {
2490 shs->bound_cbufs &= ~(1u << index);
2491 pipe_resource_reference(&cbuf->buffer, NULL);
2492 pipe_resource_reference(&shs->constbuf_surf_state[index].res, NULL);
2493 }
2494
2495 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS << stage;
2496 // XXX: maybe not necessary all the time...?
2497 // XXX: we need 3DS_BTP to commit these changes, and if we fell back to
2498 // XXX: pull model we may need actual new bindings...
2499 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
2500 }
2501
2502 static void
2503 upload_sysvals(struct iris_context *ice,
2504 gl_shader_stage stage)
2505 {
2506 UNUSED struct iris_genx_state *genx = ice->state.genx;
2507 struct iris_shader_state *shs = &ice->state.shaders[stage];
2508
2509 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
2510 if (!shader || shader->num_system_values == 0)
2511 return;
2512
2513 assert(shader->num_cbufs > 0);
2514
2515 unsigned sysval_cbuf_index = shader->num_cbufs - 1;
2516 struct pipe_shader_buffer *cbuf = &shs->constbuf[sysval_cbuf_index];
2517 unsigned upload_size = shader->num_system_values * sizeof(uint32_t);
2518 uint32_t *map = NULL;
2519
2520 assert(sysval_cbuf_index < PIPE_MAX_CONSTANT_BUFFERS);
2521 u_upload_alloc(ice->ctx.const_uploader, 0, upload_size, 64,
2522 &cbuf->buffer_offset, &cbuf->buffer, (void **) &map);
2523
2524 for (int i = 0; i < shader->num_system_values; i++) {
2525 uint32_t sysval = shader->system_values[i];
2526 uint32_t value = 0;
2527
2528 if (BRW_PARAM_DOMAIN(sysval) == BRW_PARAM_DOMAIN_IMAGE) {
2529 #if GEN_GEN == 8
2530 unsigned img = BRW_PARAM_IMAGE_IDX(sysval);
2531 unsigned offset = BRW_PARAM_IMAGE_OFFSET(sysval);
2532 struct brw_image_param *param =
2533 &genx->shaders[stage].image_param[img];
2534
2535 assert(offset < sizeof(struct brw_image_param));
2536 value = ((uint32_t *) param)[offset];
2537 #endif
2538 } else if (sysval == BRW_PARAM_BUILTIN_ZERO) {
2539 value = 0;
2540 } else if (BRW_PARAM_BUILTIN_IS_CLIP_PLANE(sysval)) {
2541 int plane = BRW_PARAM_BUILTIN_CLIP_PLANE_IDX(sysval);
2542 int comp = BRW_PARAM_BUILTIN_CLIP_PLANE_COMP(sysval);
2543 value = fui(ice->state.clip_planes.ucp[plane][comp]);
2544 } else if (sysval == BRW_PARAM_BUILTIN_PATCH_VERTICES_IN) {
2545 if (stage == MESA_SHADER_TESS_CTRL) {
2546 value = ice->state.vertices_per_patch;
2547 } else {
2548 assert(stage == MESA_SHADER_TESS_EVAL);
2549 const struct shader_info *tcs_info =
2550 iris_get_shader_info(ice, MESA_SHADER_TESS_CTRL);
2551 if (tcs_info)
2552 value = tcs_info->tess.tcs_vertices_out;
2553 else
2554 value = ice->state.vertices_per_patch;
2555 }
2556 } else if (sysval >= BRW_PARAM_BUILTIN_TESS_LEVEL_OUTER_X &&
2557 sysval <= BRW_PARAM_BUILTIN_TESS_LEVEL_OUTER_W) {
2558 unsigned i = sysval - BRW_PARAM_BUILTIN_TESS_LEVEL_OUTER_X;
2559 value = fui(ice->state.default_outer_level[i]);
2560 } else if (sysval == BRW_PARAM_BUILTIN_TESS_LEVEL_INNER_X) {
2561 value = fui(ice->state.default_inner_level[0]);
2562 } else if (sysval == BRW_PARAM_BUILTIN_TESS_LEVEL_INNER_Y) {
2563 value = fui(ice->state.default_inner_level[1]);
2564 } else {
2565 assert(!"unhandled system value");
2566 }
2567
2568 *map++ = value;
2569 }
2570
2571 cbuf->buffer_size = upload_size;
2572 iris_upload_ubo_ssbo_surf_state(ice, cbuf,
2573 &shs->constbuf_surf_state[sysval_cbuf_index], false);
2574
2575 shs->sysvals_need_upload = false;
2576 }
2577
2578 /**
2579 * The pipe->set_shader_buffers() driver hook.
2580 *
2581 * This binds SSBOs and ABOs. Unfortunately, we need to stream out
2582 * SURFACE_STATE here, as the buffer offset may change each time.
2583 */
2584 static void
2585 iris_set_shader_buffers(struct pipe_context *ctx,
2586 enum pipe_shader_type p_stage,
2587 unsigned start_slot, unsigned count,
2588 const struct pipe_shader_buffer *buffers,
2589 unsigned writable_bitmask)
2590 {
2591 struct iris_context *ice = (struct iris_context *) ctx;
2592 gl_shader_stage stage = stage_from_pipe(p_stage);
2593 struct iris_shader_state *shs = &ice->state.shaders[stage];
2594
2595 unsigned modified_bits = u_bit_consecutive(start_slot, count);
2596
2597 shs->bound_ssbos &= ~modified_bits;
2598 shs->writable_ssbos &= ~modified_bits;
2599 shs->writable_ssbos |= writable_bitmask << start_slot;
2600
2601 for (unsigned i = 0; i < count; i++) {
2602 if (buffers && buffers[i].buffer) {
2603 struct iris_resource *res = (void *) buffers[i].buffer;
2604 struct pipe_shader_buffer *ssbo = &shs->ssbo[start_slot + i];
2605 struct iris_state_ref *surf_state =
2606 &shs->ssbo_surf_state[start_slot + i];
2607 pipe_resource_reference(&ssbo->buffer, &res->base);
2608 ssbo->buffer_offset = buffers[i].buffer_offset;
2609 ssbo->buffer_size =
2610 MIN2(buffers[i].buffer_size, res->bo->size - ssbo->buffer_offset);
2611
2612 shs->bound_ssbos |= 1 << (start_slot + i);
2613
2614 iris_upload_ubo_ssbo_surf_state(ice, ssbo, surf_state, true);
2615
2616 res->bind_history |= PIPE_BIND_SHADER_BUFFER;
2617
2618 util_range_add(&res->valid_buffer_range, ssbo->buffer_offset,
2619 ssbo->buffer_offset + ssbo->buffer_size);
2620 } else {
2621 pipe_resource_reference(&shs->ssbo[start_slot + i].buffer, NULL);
2622 pipe_resource_reference(&shs->ssbo_surf_state[start_slot + i].res,
2623 NULL);
2624 }
2625 }
2626
2627 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
2628 }
2629
2630 static void
2631 iris_delete_state(struct pipe_context *ctx, void *state)
2632 {
2633 free(state);
2634 }
2635
2636 /**
2637 * The pipe->set_vertex_buffers() driver hook.
2638 *
2639 * This translates pipe_vertex_buffer to our 3DSTATE_VERTEX_BUFFERS packet.
2640 */
2641 static void
2642 iris_set_vertex_buffers(struct pipe_context *ctx,
2643 unsigned start_slot, unsigned count,
2644 const struct pipe_vertex_buffer *buffers)
2645 {
2646 struct iris_context *ice = (struct iris_context *) ctx;
2647 struct iris_genx_state *genx = ice->state.genx;
2648
2649 ice->state.bound_vertex_buffers &= ~u_bit_consecutive64(start_slot, count);
2650
2651 for (unsigned i = 0; i < count; i++) {
2652 const struct pipe_vertex_buffer *buffer = buffers ? &buffers[i] : NULL;
2653 struct iris_vertex_buffer_state *state =
2654 &genx->vertex_buffers[start_slot + i];
2655
2656 if (!buffer) {
2657 pipe_resource_reference(&state->resource, NULL);
2658 continue;
2659 }
2660
2661 /* We may see user buffers that are NULL bindings. */
2662 assert(!(buffer->is_user_buffer && buffer->buffer.user != NULL));
2663
2664 pipe_resource_reference(&state->resource, buffer->buffer.resource);
2665 struct iris_resource *res = (void *) state->resource;
2666
2667 if (res) {
2668 ice->state.bound_vertex_buffers |= 1ull << (start_slot + i);
2669 res->bind_history |= PIPE_BIND_VERTEX_BUFFER;
2670 }
2671
2672 iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
2673 vb.VertexBufferIndex = start_slot + i;
2674 vb.AddressModifyEnable = true;
2675 vb.BufferPitch = buffer->stride;
2676 if (res) {
2677 vb.BufferSize = res->bo->size - (int) buffer->buffer_offset;
2678 vb.BufferStartingAddress =
2679 ro_bo(NULL, res->bo->gtt_offset + (int) buffer->buffer_offset);
2680 vb.MOCS = mocs(res->bo);
2681 } else {
2682 vb.NullVertexBuffer = true;
2683 }
2684 }
2685 }
2686
2687 ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
2688 }
2689
2690 /**
2691 * Gallium CSO for vertex elements.
2692 */
2693 struct iris_vertex_element_state {
2694 uint32_t vertex_elements[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
2695 uint32_t vf_instancing[33 * GENX(3DSTATE_VF_INSTANCING_length)];
2696 uint32_t edgeflag_ve[GENX(VERTEX_ELEMENT_STATE_length)];
2697 uint32_t edgeflag_vfi[GENX(3DSTATE_VF_INSTANCING_length)];
2698 unsigned count;
2699 };
2700
2701 /**
2702 * The pipe->create_vertex_elements() driver hook.
2703 *
2704 * This translates pipe_vertex_element to our 3DSTATE_VERTEX_ELEMENTS
2705 * and 3DSTATE_VF_INSTANCING commands. The vertex_elements and vf_instancing
2706 * arrays are ready to be emitted at draw time if no EdgeFlag or SGVs are
2707 * needed. In these cases we will need information available at draw time.
2708 * We setup edgeflag_ve and edgeflag_vfi as alternatives last
2709 * 3DSTATE_VERTEX_ELEMENT and 3DSTATE_VF_INSTANCING that can be used at
2710 * draw time if we detect that EdgeFlag is needed by the Vertex Shader.
2711 */
2712 static void *
2713 iris_create_vertex_elements(struct pipe_context *ctx,
2714 unsigned count,
2715 const struct pipe_vertex_element *state)
2716 {
2717 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
2718 const struct gen_device_info *devinfo = &screen->devinfo;
2719 struct iris_vertex_element_state *cso =
2720 malloc(sizeof(struct iris_vertex_element_state));
2721
2722 cso->count = count;
2723
2724 iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS), cso->vertex_elements, ve) {
2725 ve.DWordLength =
2726 1 + GENX(VERTEX_ELEMENT_STATE_length) * MAX2(count, 1) - 2;
2727 }
2728
2729 uint32_t *ve_pack_dest = &cso->vertex_elements[1];
2730 uint32_t *vfi_pack_dest = cso->vf_instancing;
2731
2732 if (count == 0) {
2733 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
2734 ve.Valid = true;
2735 ve.SourceElementFormat = ISL_FORMAT_R32G32B32A32_FLOAT;
2736 ve.Component0Control = VFCOMP_STORE_0;
2737 ve.Component1Control = VFCOMP_STORE_0;
2738 ve.Component2Control = VFCOMP_STORE_0;
2739 ve.Component3Control = VFCOMP_STORE_1_FP;
2740 }
2741
2742 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
2743 }
2744 }
2745
2746 for (int i = 0; i < count; i++) {
2747 const struct iris_format_info fmt =
2748 iris_format_for_usage(devinfo, state[i].src_format, 0);
2749 unsigned comp[4] = { VFCOMP_STORE_SRC, VFCOMP_STORE_SRC,
2750 VFCOMP_STORE_SRC, VFCOMP_STORE_SRC };
2751
2752 switch (isl_format_get_num_channels(fmt.fmt)) {
2753 case 0: comp[0] = VFCOMP_STORE_0; /* fallthrough */
2754 case 1: comp[1] = VFCOMP_STORE_0; /* fallthrough */
2755 case 2: comp[2] = VFCOMP_STORE_0; /* fallthrough */
2756 case 3:
2757 comp[3] = isl_format_has_int_channel(fmt.fmt) ? VFCOMP_STORE_1_INT
2758 : VFCOMP_STORE_1_FP;
2759 break;
2760 }
2761 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
2762 ve.EdgeFlagEnable = false;
2763 ve.VertexBufferIndex = state[i].vertex_buffer_index;
2764 ve.Valid = true;
2765 ve.SourceElementOffset = state[i].src_offset;
2766 ve.SourceElementFormat = fmt.fmt;
2767 ve.Component0Control = comp[0];
2768 ve.Component1Control = comp[1];
2769 ve.Component2Control = comp[2];
2770 ve.Component3Control = comp[3];
2771 }
2772
2773 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
2774 vi.VertexElementIndex = i;
2775 vi.InstancingEnable = state[i].instance_divisor > 0;
2776 vi.InstanceDataStepRate = state[i].instance_divisor;
2777 }
2778
2779 ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
2780 vfi_pack_dest += GENX(3DSTATE_VF_INSTANCING_length);
2781 }
2782
2783 /* An alternative version of the last VE and VFI is stored so it
2784 * can be used at draw time in case Vertex Shader uses EdgeFlag
2785 */
2786 if (count) {
2787 const unsigned edgeflag_index = count - 1;
2788 const struct iris_format_info fmt =
2789 iris_format_for_usage(devinfo, state[edgeflag_index].src_format, 0);
2790 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), cso->edgeflag_ve, ve) {
2791 ve.EdgeFlagEnable = true ;
2792 ve.VertexBufferIndex = state[edgeflag_index].vertex_buffer_index;
2793 ve.Valid = true;
2794 ve.SourceElementOffset = state[edgeflag_index].src_offset;
2795 ve.SourceElementFormat = fmt.fmt;
2796 ve.Component0Control = VFCOMP_STORE_SRC;
2797 ve.Component1Control = VFCOMP_STORE_0;
2798 ve.Component2Control = VFCOMP_STORE_0;
2799 ve.Component3Control = VFCOMP_STORE_0;
2800 }
2801 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), cso->edgeflag_vfi, vi) {
2802 /* The vi.VertexElementIndex of the EdgeFlag Vertex Element is filled
2803 * at draw time, as it should change if SGVs are emitted.
2804 */
2805 vi.InstancingEnable = state[edgeflag_index].instance_divisor > 0;
2806 vi.InstanceDataStepRate = state[edgeflag_index].instance_divisor;
2807 }
2808 }
2809
2810 return cso;
2811 }
2812
2813 /**
2814 * The pipe->bind_vertex_elements_state() driver hook.
2815 */
2816 static void
2817 iris_bind_vertex_elements_state(struct pipe_context *ctx, void *state)
2818 {
2819 struct iris_context *ice = (struct iris_context *) ctx;
2820 struct iris_vertex_element_state *old_cso = ice->state.cso_vertex_elements;
2821 struct iris_vertex_element_state *new_cso = state;
2822
2823 /* 3DSTATE_VF_SGVs overrides the last VE, so if the count is changing,
2824 * we need to re-emit it to ensure we're overriding the right one.
2825 */
2826 if (new_cso && cso_changed(count))
2827 ice->state.dirty |= IRIS_DIRTY_VF_SGVS;
2828
2829 ice->state.cso_vertex_elements = state;
2830 ice->state.dirty |= IRIS_DIRTY_VERTEX_ELEMENTS;
2831 }
2832
2833 /**
2834 * The pipe->create_stream_output_target() driver hook.
2835 *
2836 * "Target" here refers to a destination buffer. We translate this into
2837 * a 3DSTATE_SO_BUFFER packet. We can handle most fields, but don't yet
2838 * know which buffer this represents, or whether we ought to zero the
2839 * write-offsets, or append. Those are handled in the set() hook.
2840 */
2841 static struct pipe_stream_output_target *
2842 iris_create_stream_output_target(struct pipe_context *ctx,
2843 struct pipe_resource *p_res,
2844 unsigned buffer_offset,
2845 unsigned buffer_size)
2846 {
2847 struct iris_resource *res = (void *) p_res;
2848 struct iris_stream_output_target *cso = calloc(1, sizeof(*cso));
2849 if (!cso)
2850 return NULL;
2851
2852 res->bind_history |= PIPE_BIND_STREAM_OUTPUT;
2853
2854 pipe_reference_init(&cso->base.reference, 1);
2855 pipe_resource_reference(&cso->base.buffer, p_res);
2856 cso->base.buffer_offset = buffer_offset;
2857 cso->base.buffer_size = buffer_size;
2858 cso->base.context = ctx;
2859
2860 util_range_add(&res->valid_buffer_range, buffer_offset,
2861 buffer_offset + buffer_size);
2862
2863 upload_state(ctx->stream_uploader, &cso->offset, sizeof(uint32_t), 4);
2864
2865 return &cso->base;
2866 }
2867
2868 static void
2869 iris_stream_output_target_destroy(struct pipe_context *ctx,
2870 struct pipe_stream_output_target *state)
2871 {
2872 struct iris_stream_output_target *cso = (void *) state;
2873
2874 pipe_resource_reference(&cso->base.buffer, NULL);
2875 pipe_resource_reference(&cso->offset.res, NULL);
2876
2877 free(cso);
2878 }
2879
2880 /**
2881 * The pipe->set_stream_output_targets() driver hook.
2882 *
2883 * At this point, we know which targets are bound to a particular index,
2884 * and also whether we want to append or start over. We can finish the
2885 * 3DSTATE_SO_BUFFER packets we started earlier.
2886 */
2887 static void
2888 iris_set_stream_output_targets(struct pipe_context *ctx,
2889 unsigned num_targets,
2890 struct pipe_stream_output_target **targets,
2891 const unsigned *offsets)
2892 {
2893 struct iris_context *ice = (struct iris_context *) ctx;
2894 struct iris_genx_state *genx = ice->state.genx;
2895 uint32_t *so_buffers = genx->so_buffers;
2896
2897 const bool active = num_targets > 0;
2898 if (ice->state.streamout_active != active) {
2899 ice->state.streamout_active = active;
2900 ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
2901
2902 /* We only emit 3DSTATE_SO_DECL_LIST when streamout is active, because
2903 * it's a non-pipelined command. If we're switching streamout on, we
2904 * may have missed emitting it earlier, so do so now. (We're already
2905 * taking a stall to update 3DSTATE_SO_BUFFERS anyway...)
2906 */
2907 if (active) {
2908 ice->state.dirty |= IRIS_DIRTY_SO_DECL_LIST;
2909 } else {
2910 uint32_t flush = 0;
2911 for (int i = 0; i < PIPE_MAX_SO_BUFFERS; i++) {
2912 struct iris_stream_output_target *tgt =
2913 (void *) ice->state.so_target[i];
2914 if (tgt) {
2915 struct iris_resource *res = (void *) tgt->base.buffer;
2916
2917 flush |= iris_flush_bits_for_history(res);
2918 iris_dirty_for_history(ice, res);
2919 }
2920 }
2921 iris_emit_pipe_control_flush(&ice->batches[IRIS_BATCH_RENDER],
2922 "make streamout results visible", flush);
2923 }
2924 }
2925
2926 for (int i = 0; i < 4; i++) {
2927 pipe_so_target_reference(&ice->state.so_target[i],
2928 i < num_targets ? targets[i] : NULL);
2929 }
2930
2931 /* No need to update 3DSTATE_SO_BUFFER unless SOL is active. */
2932 if (!active)
2933 return;
2934
2935 for (unsigned i = 0; i < 4; i++,
2936 so_buffers += GENX(3DSTATE_SO_BUFFER_length)) {
2937
2938 struct iris_stream_output_target *tgt = (void *) ice->state.so_target[i];
2939 unsigned offset = offsets[i];
2940
2941 if (!tgt) {
2942 iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob)
2943 sob.SOBufferIndex = i;
2944 continue;
2945 }
2946
2947 struct iris_resource *res = (void *) tgt->base.buffer;
2948
2949 /* Note that offsets[i] will either be 0, causing us to zero
2950 * the value in the buffer, or 0xFFFFFFFF, which happens to mean
2951 * "continue appending at the existing offset."
2952 */
2953 assert(offset == 0 || offset == 0xFFFFFFFF);
2954
2955 /* We might be called by Begin (offset = 0), Pause, then Resume
2956 * (offset = 0xFFFFFFFF) before ever drawing (where these commands
2957 * will actually be sent to the GPU). In this case, we don't want
2958 * to append - we still want to do our initial zeroing.
2959 */
2960 if (!tgt->zeroed)
2961 offset = 0;
2962
2963 iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob) {
2964 sob.SurfaceBaseAddress =
2965 rw_bo(NULL, res->bo->gtt_offset + tgt->base.buffer_offset);
2966 sob.SOBufferEnable = true;
2967 sob.StreamOffsetWriteEnable = true;
2968 sob.StreamOutputBufferOffsetAddressEnable = true;
2969 sob.MOCS = mocs(res->bo);
2970
2971 sob.SurfaceSize = MAX2(tgt->base.buffer_size / 4, 1) - 1;
2972
2973 sob.SOBufferIndex = i;
2974 sob.StreamOffset = offset;
2975 sob.StreamOutputBufferOffsetAddress =
2976 rw_bo(NULL, iris_resource_bo(tgt->offset.res)->gtt_offset +
2977 tgt->offset.offset);
2978 }
2979 }
2980
2981 ice->state.dirty |= IRIS_DIRTY_SO_BUFFERS;
2982 }
2983
2984 /**
2985 * An iris-vtable helper for encoding the 3DSTATE_SO_DECL_LIST and
2986 * 3DSTATE_STREAMOUT packets.
2987 *
2988 * 3DSTATE_SO_DECL_LIST is a list of shader outputs we want the streamout
2989 * hardware to record. We can create it entirely based on the shader, with
2990 * no dynamic state dependencies.
2991 *
2992 * 3DSTATE_STREAMOUT is an annoying mix of shader-based information and
2993 * state-based settings. We capture the shader-related ones here, and merge
2994 * the rest in at draw time.
2995 */
2996 static uint32_t *
2997 iris_create_so_decl_list(const struct pipe_stream_output_info *info,
2998 const struct brw_vue_map *vue_map)
2999 {
3000 struct GENX(SO_DECL) so_decl[MAX_VERTEX_STREAMS][128];
3001 int buffer_mask[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
3002 int next_offset[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
3003 int decls[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
3004 int max_decls = 0;
3005 STATIC_ASSERT(ARRAY_SIZE(so_decl[0]) >= MAX_PROGRAM_OUTPUTS);
3006
3007 memset(so_decl, 0, sizeof(so_decl));
3008
3009 /* Construct the list of SO_DECLs to be emitted. The formatting of the
3010 * command feels strange -- each dword pair contains a SO_DECL per stream.
3011 */
3012 for (unsigned i = 0; i < info->num_outputs; i++) {
3013 const struct pipe_stream_output *output = &info->output[i];
3014 const int buffer = output->output_buffer;
3015 const int varying = output->register_index;
3016 const unsigned stream_id = output->stream;
3017 assert(stream_id < MAX_VERTEX_STREAMS);
3018
3019 buffer_mask[stream_id] |= 1 << buffer;
3020
3021 assert(vue_map->varying_to_slot[varying] >= 0);
3022
3023 /* Mesa doesn't store entries for gl_SkipComponents in the Outputs[]
3024 * array. Instead, it simply increments DstOffset for the following
3025 * input by the number of components that should be skipped.
3026 *
3027 * Our hardware is unusual in that it requires us to program SO_DECLs
3028 * for fake "hole" components, rather than simply taking the offset
3029 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
3030 * program as many size = 4 holes as we can, then a final hole to
3031 * accommodate the final 1, 2, or 3 remaining.
3032 */
3033 int skip_components = output->dst_offset - next_offset[buffer];
3034
3035 while (skip_components > 0) {
3036 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
3037 .HoleFlag = 1,
3038 .OutputBufferSlot = output->output_buffer,
3039 .ComponentMask = (1 << MIN2(skip_components, 4)) - 1,
3040 };
3041 skip_components -= 4;
3042 }
3043
3044 next_offset[buffer] = output->dst_offset + output->num_components;
3045
3046 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
3047 .OutputBufferSlot = output->output_buffer,
3048 .RegisterIndex = vue_map->varying_to_slot[varying],
3049 .ComponentMask =
3050 ((1 << output->num_components) - 1) << output->start_component,
3051 };
3052
3053 if (decls[stream_id] > max_decls)
3054 max_decls = decls[stream_id];
3055 }
3056
3057 unsigned dwords = GENX(3DSTATE_STREAMOUT_length) + (3 + 2 * max_decls);
3058 uint32_t *map = ralloc_size(NULL, sizeof(uint32_t) * dwords);
3059 uint32_t *so_decl_map = map + GENX(3DSTATE_STREAMOUT_length);
3060
3061 iris_pack_command(GENX(3DSTATE_STREAMOUT), map, sol) {
3062 int urb_entry_read_offset = 0;
3063 int urb_entry_read_length = (vue_map->num_slots + 1) / 2 -
3064 urb_entry_read_offset;
3065
3066 /* We always read the whole vertex. This could be reduced at some
3067 * point by reading less and offsetting the register index in the
3068 * SO_DECLs.
3069 */
3070 sol.Stream0VertexReadOffset = urb_entry_read_offset;
3071 sol.Stream0VertexReadLength = urb_entry_read_length - 1;
3072 sol.Stream1VertexReadOffset = urb_entry_read_offset;
3073 sol.Stream1VertexReadLength = urb_entry_read_length - 1;
3074 sol.Stream2VertexReadOffset = urb_entry_read_offset;
3075 sol.Stream2VertexReadLength = urb_entry_read_length - 1;
3076 sol.Stream3VertexReadOffset = urb_entry_read_offset;
3077 sol.Stream3VertexReadLength = urb_entry_read_length - 1;
3078
3079 /* Set buffer pitches; 0 means unbound. */
3080 sol.Buffer0SurfacePitch = 4 * info->stride[0];
3081 sol.Buffer1SurfacePitch = 4 * info->stride[1];
3082 sol.Buffer2SurfacePitch = 4 * info->stride[2];
3083 sol.Buffer3SurfacePitch = 4 * info->stride[3];
3084 }
3085
3086 iris_pack_command(GENX(3DSTATE_SO_DECL_LIST), so_decl_map, list) {
3087 list.DWordLength = 3 + 2 * max_decls - 2;
3088 list.StreamtoBufferSelects0 = buffer_mask[0];
3089 list.StreamtoBufferSelects1 = buffer_mask[1];
3090 list.StreamtoBufferSelects2 = buffer_mask[2];
3091 list.StreamtoBufferSelects3 = buffer_mask[3];
3092 list.NumEntries0 = decls[0];
3093 list.NumEntries1 = decls[1];
3094 list.NumEntries2 = decls[2];
3095 list.NumEntries3 = decls[3];
3096 }
3097
3098 for (int i = 0; i < max_decls; i++) {
3099 iris_pack_state(GENX(SO_DECL_ENTRY), so_decl_map + 3 + i * 2, entry) {
3100 entry.Stream0Decl = so_decl[0][i];
3101 entry.Stream1Decl = so_decl[1][i];
3102 entry.Stream2Decl = so_decl[2][i];
3103 entry.Stream3Decl = so_decl[3][i];
3104 }
3105 }
3106
3107 return map;
3108 }
3109
3110 static void
3111 iris_compute_sbe_urb_read_interval(uint64_t fs_input_slots,
3112 const struct brw_vue_map *last_vue_map,
3113 bool two_sided_color,
3114 unsigned *out_offset,
3115 unsigned *out_length)
3116 {
3117 /* The compiler computes the first URB slot without considering COL/BFC
3118 * swizzling (because it doesn't know whether it's enabled), so we need
3119 * to do that here too. This may result in a smaller offset, which
3120 * should be safe.
3121 */
3122 const unsigned first_slot =
3123 brw_compute_first_urb_slot_required(fs_input_slots, last_vue_map);
3124
3125 /* This becomes the URB read offset (counted in pairs of slots). */
3126 assert(first_slot % 2 == 0);
3127 *out_offset = first_slot / 2;
3128
3129 /* We need to adjust the inputs read to account for front/back color
3130 * swizzling, as it can make the URB length longer.
3131 */
3132 for (int c = 0; c <= 1; c++) {
3133 if (fs_input_slots & (VARYING_BIT_COL0 << c)) {
3134 /* If two sided color is enabled, the fragment shader's gl_Color
3135 * (COL0) input comes from either the gl_FrontColor (COL0) or
3136 * gl_BackColor (BFC0) input varyings. Mark BFC as used, too.
3137 */
3138 if (two_sided_color)
3139 fs_input_slots |= (VARYING_BIT_BFC0 << c);
3140
3141 /* If front color isn't written, we opt to give them back color
3142 * instead of an undefined value. Switch from COL to BFC.
3143 */
3144 if (last_vue_map->varying_to_slot[VARYING_SLOT_COL0 + c] == -1) {
3145 fs_input_slots &= ~(VARYING_BIT_COL0 << c);
3146 fs_input_slots |= (VARYING_BIT_BFC0 << c);
3147 }
3148 }
3149 }
3150
3151 /* Compute the minimum URB Read Length necessary for the FS inputs.
3152 *
3153 * From the Sandy Bridge PRM, Volume 2, Part 1, documentation for
3154 * 3DSTATE_SF DWord 1 bits 15:11, "Vertex URB Entry Read Length":
3155 *
3156 * "This field should be set to the minimum length required to read the
3157 * maximum source attribute. The maximum source attribute is indicated
3158 * by the maximum value of the enabled Attribute # Source Attribute if
3159 * Attribute Swizzle Enable is set, Number of Output Attributes-1 if
3160 * enable is not set.
3161 * read_length = ceiling((max_source_attr + 1) / 2)
3162 *
3163 * [errata] Corruption/Hang possible if length programmed larger than
3164 * recommended"
3165 *
3166 * Similar text exists for Ivy Bridge.
3167 *
3168 * We find the last URB slot that's actually read by the FS.
3169 */
3170 unsigned last_read_slot = last_vue_map->num_slots - 1;
3171 while (last_read_slot > first_slot && !(fs_input_slots &
3172 (1ull << last_vue_map->slot_to_varying[last_read_slot])))
3173 --last_read_slot;
3174
3175 /* The URB read length is the difference of the two, counted in pairs. */
3176 *out_length = DIV_ROUND_UP(last_read_slot - first_slot + 1, 2);
3177 }
3178
3179 static void
3180 iris_emit_sbe_swiz(struct iris_batch *batch,
3181 const struct iris_context *ice,
3182 unsigned urb_read_offset,
3183 unsigned sprite_coord_enables)
3184 {
3185 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) attr_overrides[16] = {};
3186 const struct brw_wm_prog_data *wm_prog_data = (void *)
3187 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
3188 const struct brw_vue_map *vue_map = ice->shaders.last_vue_map;
3189 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3190
3191 /* XXX: this should be generated when putting programs in place */
3192
3193 for (int fs_attr = 0; fs_attr < VARYING_SLOT_MAX; fs_attr++) {
3194 const int input_index = wm_prog_data->urb_setup[fs_attr];
3195 if (input_index < 0 || input_index >= 16)
3196 continue;
3197
3198 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) *attr =
3199 &attr_overrides[input_index];
3200 int slot = vue_map->varying_to_slot[fs_attr];
3201
3202 /* Viewport and Layer are stored in the VUE header. We need to override
3203 * them to zero if earlier stages didn't write them, as GL requires that
3204 * they read back as zero when not explicitly set.
3205 */
3206 switch (fs_attr) {
3207 case VARYING_SLOT_VIEWPORT:
3208 case VARYING_SLOT_LAYER:
3209 attr->ComponentOverrideX = true;
3210 attr->ComponentOverrideW = true;
3211 attr->ConstantSource = CONST_0000;
3212
3213 if (!(vue_map->slots_valid & VARYING_BIT_LAYER))
3214 attr->ComponentOverrideY = true;
3215 if (!(vue_map->slots_valid & VARYING_BIT_VIEWPORT))
3216 attr->ComponentOverrideZ = true;
3217 continue;
3218
3219 case VARYING_SLOT_PRIMITIVE_ID:
3220 /* Override if the previous shader stage didn't write gl_PrimitiveID. */
3221 if (slot == -1) {
3222 attr->ComponentOverrideX = true;
3223 attr->ComponentOverrideY = true;
3224 attr->ComponentOverrideZ = true;
3225 attr->ComponentOverrideW = true;
3226 attr->ConstantSource = PRIM_ID;
3227 continue;
3228 }
3229
3230 default:
3231 break;
3232 }
3233
3234 if (sprite_coord_enables & (1 << input_index))
3235 continue;
3236
3237 /* If there was only a back color written but not front, use back
3238 * as the color instead of undefined.
3239 */
3240 if (slot == -1 && fs_attr == VARYING_SLOT_COL0)
3241 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC0];
3242 if (slot == -1 && fs_attr == VARYING_SLOT_COL1)
3243 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC1];
3244
3245 /* Not written by the previous stage - undefined. */
3246 if (slot == -1) {
3247 attr->ComponentOverrideX = true;
3248 attr->ComponentOverrideY = true;
3249 attr->ComponentOverrideZ = true;
3250 attr->ComponentOverrideW = true;
3251 attr->ConstantSource = CONST_0001_FLOAT;
3252 continue;
3253 }
3254
3255 /* Compute the location of the attribute relative to the read offset,
3256 * which is counted in 256-bit increments (two 128-bit VUE slots).
3257 */
3258 const int source_attr = slot - 2 * urb_read_offset;
3259 assert(source_attr >= 0 && source_attr <= 32);
3260 attr->SourceAttribute = source_attr;
3261
3262 /* If we are doing two-sided color, and the VUE slot following this one
3263 * represents a back-facing color, then we need to instruct the SF unit
3264 * to do back-facing swizzling.
3265 */
3266 if (cso_rast->light_twoside &&
3267 ((vue_map->slot_to_varying[slot] == VARYING_SLOT_COL0 &&
3268 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC0) ||
3269 (vue_map->slot_to_varying[slot] == VARYING_SLOT_COL1 &&
3270 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC1)))
3271 attr->SwizzleSelect = INPUTATTR_FACING;
3272 }
3273
3274 iris_emit_cmd(batch, GENX(3DSTATE_SBE_SWIZ), sbes) {
3275 for (int i = 0; i < 16; i++)
3276 sbes.Attribute[i] = attr_overrides[i];
3277 }
3278 }
3279
3280 static unsigned
3281 iris_calculate_point_sprite_overrides(const struct brw_wm_prog_data *prog_data,
3282 const struct iris_rasterizer_state *cso)
3283 {
3284 unsigned overrides = 0;
3285
3286 if (prog_data->urb_setup[VARYING_SLOT_PNTC] != -1)
3287 overrides |= 1 << prog_data->urb_setup[VARYING_SLOT_PNTC];
3288
3289 for (int i = 0; i < 8; i++) {
3290 if ((cso->sprite_coord_enable & (1 << i)) &&
3291 prog_data->urb_setup[VARYING_SLOT_TEX0 + i] != -1)
3292 overrides |= 1 << prog_data->urb_setup[VARYING_SLOT_TEX0 + i];
3293 }
3294
3295 return overrides;
3296 }
3297
3298 static void
3299 iris_emit_sbe(struct iris_batch *batch, const struct iris_context *ice)
3300 {
3301 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3302 const struct brw_wm_prog_data *wm_prog_data = (void *)
3303 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
3304 const struct shader_info *fs_info =
3305 iris_get_shader_info(ice, MESA_SHADER_FRAGMENT);
3306
3307 unsigned urb_read_offset, urb_read_length;
3308 iris_compute_sbe_urb_read_interval(fs_info->inputs_read,
3309 ice->shaders.last_vue_map,
3310 cso_rast->light_twoside,
3311 &urb_read_offset, &urb_read_length);
3312
3313 unsigned sprite_coord_overrides =
3314 iris_calculate_point_sprite_overrides(wm_prog_data, cso_rast);
3315
3316 iris_emit_cmd(batch, GENX(3DSTATE_SBE), sbe) {
3317 sbe.AttributeSwizzleEnable = true;
3318 sbe.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
3319 sbe.PointSpriteTextureCoordinateOrigin = cso_rast->sprite_coord_mode;
3320 sbe.VertexURBEntryReadOffset = urb_read_offset;
3321 sbe.VertexURBEntryReadLength = urb_read_length;
3322 sbe.ForceVertexURBEntryReadOffset = true;
3323 sbe.ForceVertexURBEntryReadLength = true;
3324 sbe.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
3325 sbe.PointSpriteTextureCoordinateEnable = sprite_coord_overrides;
3326 #if GEN_GEN >= 9
3327 for (int i = 0; i < 32; i++) {
3328 sbe.AttributeActiveComponentFormat[i] = ACTIVE_COMPONENT_XYZW;
3329 }
3330 #endif
3331 }
3332
3333 iris_emit_sbe_swiz(batch, ice, urb_read_offset, sprite_coord_overrides);
3334 }
3335
3336 /* ------------------------------------------------------------------- */
3337
3338 /**
3339 * Populate VS program key fields based on the current state.
3340 */
3341 static void
3342 iris_populate_vs_key(const struct iris_context *ice,
3343 const struct shader_info *info,
3344 gl_shader_stage last_stage,
3345 struct brw_vs_prog_key *key)
3346 {
3347 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3348
3349 if (info->clip_distance_array_size == 0 &&
3350 (info->outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX)) &&
3351 last_stage == MESA_SHADER_VERTEX)
3352 key->nr_userclip_plane_consts = cso_rast->num_clip_plane_consts;
3353 }
3354
3355 /**
3356 * Populate TCS program key fields based on the current state.
3357 */
3358 static void
3359 iris_populate_tcs_key(const struct iris_context *ice,
3360 struct brw_tcs_prog_key *key)
3361 {
3362 }
3363
3364 /**
3365 * Populate TES program key fields based on the current state.
3366 */
3367 static void
3368 iris_populate_tes_key(const struct iris_context *ice,
3369 const struct shader_info *info,
3370 gl_shader_stage last_stage,
3371 struct brw_tes_prog_key *key)
3372 {
3373 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3374
3375 if (info->clip_distance_array_size == 0 &&
3376 (info->outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX)) &&
3377 last_stage == MESA_SHADER_TESS_EVAL)
3378 key->nr_userclip_plane_consts = cso_rast->num_clip_plane_consts;
3379 }
3380
3381 /**
3382 * Populate GS program key fields based on the current state.
3383 */
3384 static void
3385 iris_populate_gs_key(const struct iris_context *ice,
3386 const struct shader_info *info,
3387 gl_shader_stage last_stage,
3388 struct brw_gs_prog_key *key)
3389 {
3390 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3391
3392 if (info->clip_distance_array_size == 0 &&
3393 (info->outputs_written & (VARYING_BIT_POS | VARYING_BIT_CLIP_VERTEX)) &&
3394 last_stage == MESA_SHADER_GEOMETRY)
3395 key->nr_userclip_plane_consts = cso_rast->num_clip_plane_consts;
3396 }
3397
3398 /**
3399 * Populate FS program key fields based on the current state.
3400 */
3401 static void
3402 iris_populate_fs_key(const struct iris_context *ice,
3403 const struct shader_info *info,
3404 struct brw_wm_prog_key *key)
3405 {
3406 struct iris_screen *screen = (void *) ice->ctx.screen;
3407 const struct pipe_framebuffer_state *fb = &ice->state.framebuffer;
3408 const struct iris_depth_stencil_alpha_state *zsa = ice->state.cso_zsa;
3409 const struct iris_rasterizer_state *rast = ice->state.cso_rast;
3410 const struct iris_blend_state *blend = ice->state.cso_blend;
3411
3412 key->nr_color_regions = fb->nr_cbufs;
3413
3414 key->clamp_fragment_color = rast->clamp_fragment_color;
3415
3416 key->alpha_to_coverage = blend->alpha_to_coverage;
3417
3418 key->alpha_test_replicate_alpha = fb->nr_cbufs > 1 && zsa->alpha.enabled;
3419
3420 key->flat_shade = rast->flatshade &&
3421 (info->inputs_read & (VARYING_BIT_COL0 | VARYING_BIT_COL1));
3422
3423 key->persample_interp = rast->force_persample_interp;
3424 key->multisample_fbo = rast->multisample && fb->samples > 1;
3425
3426 key->coherent_fb_fetch = true;
3427
3428 key->force_dual_color_blend =
3429 screen->driconf.dual_color_blend_by_location &&
3430 (blend->blend_enables & 1) && blend->dual_color_blending;
3431
3432 /* TODO: Respect glHint for key->high_quality_derivatives */
3433 }
3434
3435 static void
3436 iris_populate_cs_key(const struct iris_context *ice,
3437 struct brw_cs_prog_key *key)
3438 {
3439 }
3440
3441 static uint64_t
3442 KSP(const struct iris_compiled_shader *shader)
3443 {
3444 struct iris_resource *res = (void *) shader->assembly.res;
3445 return iris_bo_offset_from_base_address(res->bo) + shader->assembly.offset;
3446 }
3447
3448 /* Gen11 workaround table #2056 WABTPPrefetchDisable suggests to disable
3449 * prefetching of binding tables in A0 and B0 steppings. XXX: Revisit
3450 * this WA on C0 stepping.
3451 *
3452 * TODO: Fill out SamplerCount for prefetching?
3453 */
3454
3455 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix, stage) \
3456 pkt.KernelStartPointer = KSP(shader); \
3457 pkt.BindingTableEntryCount = GEN_GEN == 11 ? 0 : \
3458 shader->bt.size_bytes / 4; \
3459 pkt.FloatingPointMode = prog_data->use_alt_mode; \
3460 \
3461 pkt.DispatchGRFStartRegisterForURBData = \
3462 prog_data->dispatch_grf_start_reg; \
3463 pkt.prefix##URBEntryReadLength = vue_prog_data->urb_read_length; \
3464 pkt.prefix##URBEntryReadOffset = 0; \
3465 \
3466 pkt.StatisticsEnable = true; \
3467 pkt.Enable = true; \
3468 \
3469 if (prog_data->total_scratch) { \
3470 struct iris_bo *bo = \
3471 iris_get_scratch_space(ice, prog_data->total_scratch, stage); \
3472 uint32_t scratch_addr = bo->gtt_offset; \
3473 pkt.PerThreadScratchSpace = ffs(prog_data->total_scratch) - 11; \
3474 pkt.ScratchSpaceBasePointer = rw_bo(NULL, scratch_addr); \
3475 }
3476
3477 /**
3478 * Encode most of 3DSTATE_VS based on the compiled shader.
3479 */
3480 static void
3481 iris_store_vs_state(struct iris_context *ice,
3482 const struct gen_device_info *devinfo,
3483 struct iris_compiled_shader *shader)
3484 {
3485 struct brw_stage_prog_data *prog_data = shader->prog_data;
3486 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
3487
3488 iris_pack_command(GENX(3DSTATE_VS), shader->derived_data, vs) {
3489 INIT_THREAD_DISPATCH_FIELDS(vs, Vertex, MESA_SHADER_VERTEX);
3490 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
3491 vs.SIMD8DispatchEnable = true;
3492 vs.UserClipDistanceCullTestEnableBitmask =
3493 vue_prog_data->cull_distance_mask;
3494 }
3495 }
3496
3497 /**
3498 * Encode most of 3DSTATE_HS based on the compiled shader.
3499 */
3500 static void
3501 iris_store_tcs_state(struct iris_context *ice,
3502 const struct gen_device_info *devinfo,
3503 struct iris_compiled_shader *shader)
3504 {
3505 struct brw_stage_prog_data *prog_data = shader->prog_data;
3506 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
3507 struct brw_tcs_prog_data *tcs_prog_data = (void *) prog_data;
3508
3509 iris_pack_command(GENX(3DSTATE_HS), shader->derived_data, hs) {
3510 INIT_THREAD_DISPATCH_FIELDS(hs, Vertex, MESA_SHADER_TESS_CTRL);
3511
3512 hs.InstanceCount = tcs_prog_data->instances - 1;
3513 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
3514 hs.IncludeVertexHandles = true;
3515
3516 #if GEN_GEN >= 9
3517 hs.DispatchMode = vue_prog_data->dispatch_mode;
3518 hs.IncludePrimitiveID = tcs_prog_data->include_primitive_id;
3519 #endif
3520 }
3521 }
3522
3523 /**
3524 * Encode 3DSTATE_TE and most of 3DSTATE_DS based on the compiled shader.
3525 */
3526 static void
3527 iris_store_tes_state(struct iris_context *ice,
3528 const struct gen_device_info *devinfo,
3529 struct iris_compiled_shader *shader)
3530 {
3531 struct brw_stage_prog_data *prog_data = shader->prog_data;
3532 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
3533 struct brw_tes_prog_data *tes_prog_data = (void *) prog_data;
3534
3535 uint32_t *te_state = (void *) shader->derived_data;
3536 uint32_t *ds_state = te_state + GENX(3DSTATE_TE_length);
3537
3538 iris_pack_command(GENX(3DSTATE_TE), te_state, te) {
3539 te.Partitioning = tes_prog_data->partitioning;
3540 te.OutputTopology = tes_prog_data->output_topology;
3541 te.TEDomain = tes_prog_data->domain;
3542 te.TEEnable = true;
3543 te.MaximumTessellationFactorOdd = 63.0;
3544 te.MaximumTessellationFactorNotOdd = 64.0;
3545 }
3546
3547 iris_pack_command(GENX(3DSTATE_DS), ds_state, ds) {
3548 INIT_THREAD_DISPATCH_FIELDS(ds, Patch, MESA_SHADER_TESS_EVAL);
3549
3550 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
3551 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
3552 ds.ComputeWCoordinateEnable =
3553 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
3554
3555 ds.UserClipDistanceCullTestEnableBitmask =
3556 vue_prog_data->cull_distance_mask;
3557 }
3558
3559 }
3560
3561 /**
3562 * Encode most of 3DSTATE_GS based on the compiled shader.
3563 */
3564 static void
3565 iris_store_gs_state(struct iris_context *ice,
3566 const struct gen_device_info *devinfo,
3567 struct iris_compiled_shader *shader)
3568 {
3569 struct brw_stage_prog_data *prog_data = shader->prog_data;
3570 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
3571 struct brw_gs_prog_data *gs_prog_data = (void *) prog_data;
3572
3573 iris_pack_command(GENX(3DSTATE_GS), shader->derived_data, gs) {
3574 INIT_THREAD_DISPATCH_FIELDS(gs, Vertex, MESA_SHADER_GEOMETRY);
3575
3576 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
3577 gs.OutputTopology = gs_prog_data->output_topology;
3578 gs.ControlDataHeaderSize =
3579 gs_prog_data->control_data_header_size_hwords;
3580 gs.InstanceControl = gs_prog_data->invocations - 1;
3581 gs.DispatchMode = DISPATCH_MODE_SIMD8;
3582 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
3583 gs.ControlDataFormat = gs_prog_data->control_data_format;
3584 gs.ReorderMode = TRAILING;
3585 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
3586 gs.MaximumNumberofThreads =
3587 GEN_GEN == 8 ? (devinfo->max_gs_threads / 2 - 1)
3588 : (devinfo->max_gs_threads - 1);
3589
3590 if (gs_prog_data->static_vertex_count != -1) {
3591 gs.StaticOutput = true;
3592 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count;
3593 }
3594 gs.IncludeVertexHandles = vue_prog_data->include_vue_handles;
3595
3596 gs.UserClipDistanceCullTestEnableBitmask =
3597 vue_prog_data->cull_distance_mask;
3598
3599 const int urb_entry_write_offset = 1;
3600 const uint32_t urb_entry_output_length =
3601 DIV_ROUND_UP(vue_prog_data->vue_map.num_slots, 2) -
3602 urb_entry_write_offset;
3603
3604 gs.VertexURBEntryOutputReadOffset = urb_entry_write_offset;
3605 gs.VertexURBEntryOutputLength = MAX2(urb_entry_output_length, 1);
3606 }
3607 }
3608
3609 /**
3610 * Encode most of 3DSTATE_PS and 3DSTATE_PS_EXTRA based on the shader.
3611 */
3612 static void
3613 iris_store_fs_state(struct iris_context *ice,
3614 const struct gen_device_info *devinfo,
3615 struct iris_compiled_shader *shader)
3616 {
3617 struct brw_stage_prog_data *prog_data = shader->prog_data;
3618 struct brw_wm_prog_data *wm_prog_data = (void *) shader->prog_data;
3619
3620 uint32_t *ps_state = (void *) shader->derived_data;
3621 uint32_t *psx_state = ps_state + GENX(3DSTATE_PS_length);
3622
3623 iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
3624 ps.VectorMaskEnable = true;
3625 // XXX: WABTPPrefetchDisable, see above, drop at C0
3626 ps.BindingTableEntryCount = GEN_GEN == 11 ? 0 :
3627 shader->bt.size_bytes / 4;
3628 ps.FloatingPointMode = prog_data->use_alt_mode;
3629 ps.MaximumNumberofThreadsPerPSD = 64 - (GEN_GEN == 8 ? 2 : 1);
3630
3631 ps.PushConstantEnable = prog_data->ubo_ranges[0].length > 0;
3632
3633 /* From the documentation for this packet:
3634 * "If the PS kernel does not need the Position XY Offsets to
3635 * compute a Position Value, then this field should be programmed
3636 * to POSOFFSET_NONE."
3637 *
3638 * "SW Recommendation: If the PS kernel needs the Position Offsets
3639 * to compute a Position XY value, this field should match Position
3640 * ZW Interpolation Mode to ensure a consistent position.xyzw
3641 * computation."
3642 *
3643 * We only require XY sample offsets. So, this recommendation doesn't
3644 * look useful at the moment. We might need this in future.
3645 */
3646 ps.PositionXYOffsetSelect =
3647 wm_prog_data->uses_pos_offset ? POSOFFSET_SAMPLE : POSOFFSET_NONE;
3648
3649 if (prog_data->total_scratch) {
3650 struct iris_bo *bo =
3651 iris_get_scratch_space(ice, prog_data->total_scratch,
3652 MESA_SHADER_FRAGMENT);
3653 uint32_t scratch_addr = bo->gtt_offset;
3654 ps.PerThreadScratchSpace = ffs(prog_data->total_scratch) - 11;
3655 ps.ScratchSpaceBasePointer = rw_bo(NULL, scratch_addr);
3656 }
3657 }
3658
3659 iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
3660 psx.PixelShaderValid = true;
3661 psx.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
3662 psx.PixelShaderKillsPixel = wm_prog_data->uses_kill;
3663 psx.AttributeEnable = wm_prog_data->num_varying_inputs != 0;
3664 psx.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
3665 psx.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
3666 psx.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
3667 psx.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
3668
3669 #if GEN_GEN >= 9
3670 psx.PixelShaderPullsBary = wm_prog_data->pulls_bary;
3671 psx.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
3672 #endif
3673 }
3674 }
3675
3676 /**
3677 * Compute the size of the derived data (shader command packets).
3678 *
3679 * This must match the data written by the iris_store_xs_state() functions.
3680 */
3681 static void
3682 iris_store_cs_state(struct iris_context *ice,
3683 const struct gen_device_info *devinfo,
3684 struct iris_compiled_shader *shader)
3685 {
3686 struct brw_stage_prog_data *prog_data = shader->prog_data;
3687 struct brw_cs_prog_data *cs_prog_data = (void *) shader->prog_data;
3688 void *map = shader->derived_data;
3689
3690 iris_pack_state(GENX(INTERFACE_DESCRIPTOR_DATA), map, desc) {
3691 desc.KernelStartPointer = KSP(shader);
3692 desc.ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs;
3693 desc.NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads;
3694 desc.SharedLocalMemorySize =
3695 encode_slm_size(GEN_GEN, prog_data->total_shared);
3696 desc.BarrierEnable = cs_prog_data->uses_barrier;
3697 desc.CrossThreadConstantDataReadLength =
3698 cs_prog_data->push.cross_thread.regs;
3699 }
3700 }
3701
3702 static unsigned
3703 iris_derived_program_state_size(enum iris_program_cache_id cache_id)
3704 {
3705 assert(cache_id <= IRIS_CACHE_BLORP);
3706
3707 static const unsigned dwords[] = {
3708 [IRIS_CACHE_VS] = GENX(3DSTATE_VS_length),
3709 [IRIS_CACHE_TCS] = GENX(3DSTATE_HS_length),
3710 [IRIS_CACHE_TES] = GENX(3DSTATE_TE_length) + GENX(3DSTATE_DS_length),
3711 [IRIS_CACHE_GS] = GENX(3DSTATE_GS_length),
3712 [IRIS_CACHE_FS] =
3713 GENX(3DSTATE_PS_length) + GENX(3DSTATE_PS_EXTRA_length),
3714 [IRIS_CACHE_CS] = GENX(INTERFACE_DESCRIPTOR_DATA_length),
3715 [IRIS_CACHE_BLORP] = 0,
3716 };
3717
3718 return sizeof(uint32_t) * dwords[cache_id];
3719 }
3720
3721 /**
3722 * Create any state packets corresponding to the given shader stage
3723 * (i.e. 3DSTATE_VS) and save them as "derived data" in the shader variant.
3724 * This means that we can look up a program in the in-memory cache and
3725 * get most of the state packet without having to reconstruct it.
3726 */
3727 static void
3728 iris_store_derived_program_state(struct iris_context *ice,
3729 enum iris_program_cache_id cache_id,
3730 struct iris_compiled_shader *shader)
3731 {
3732 struct iris_screen *screen = (void *) ice->ctx.screen;
3733 const struct gen_device_info *devinfo = &screen->devinfo;
3734
3735 switch (cache_id) {
3736 case IRIS_CACHE_VS:
3737 iris_store_vs_state(ice, devinfo, shader);
3738 break;
3739 case IRIS_CACHE_TCS:
3740 iris_store_tcs_state(ice, devinfo, shader);
3741 break;
3742 case IRIS_CACHE_TES:
3743 iris_store_tes_state(ice, devinfo, shader);
3744 break;
3745 case IRIS_CACHE_GS:
3746 iris_store_gs_state(ice, devinfo, shader);
3747 break;
3748 case IRIS_CACHE_FS:
3749 iris_store_fs_state(ice, devinfo, shader);
3750 break;
3751 case IRIS_CACHE_CS:
3752 iris_store_cs_state(ice, devinfo, shader);
3753 case IRIS_CACHE_BLORP:
3754 break;
3755 default:
3756 break;
3757 }
3758 }
3759
3760 /* ------------------------------------------------------------------- */
3761
3762 static const uint32_t push_constant_opcodes[] = {
3763 [MESA_SHADER_VERTEX] = 21,
3764 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
3765 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
3766 [MESA_SHADER_GEOMETRY] = 22,
3767 [MESA_SHADER_FRAGMENT] = 23,
3768 [MESA_SHADER_COMPUTE] = 0,
3769 };
3770
3771 static uint32_t
3772 use_null_surface(struct iris_batch *batch, struct iris_context *ice)
3773 {
3774 struct iris_bo *state_bo = iris_resource_bo(ice->state.unbound_tex.res);
3775
3776 iris_use_pinned_bo(batch, state_bo, false);
3777
3778 return ice->state.unbound_tex.offset;
3779 }
3780
3781 static uint32_t
3782 use_null_fb_surface(struct iris_batch *batch, struct iris_context *ice)
3783 {
3784 /* If set_framebuffer_state() was never called, fall back to 1x1x1 */
3785 if (!ice->state.null_fb.res)
3786 return use_null_surface(batch, ice);
3787
3788 struct iris_bo *state_bo = iris_resource_bo(ice->state.null_fb.res);
3789
3790 iris_use_pinned_bo(batch, state_bo, false);
3791
3792 return ice->state.null_fb.offset;
3793 }
3794
3795 static uint32_t
3796 surf_state_offset_for_aux(struct iris_resource *res,
3797 unsigned aux_modes,
3798 enum isl_aux_usage aux_usage)
3799 {
3800 return SURFACE_STATE_ALIGNMENT *
3801 util_bitcount(res->aux.possible_usages & ((1 << aux_usage) - 1));
3802 }
3803
3804 static void
3805 surf_state_update_clear_value(struct iris_batch *batch,
3806 struct iris_resource *res,
3807 struct iris_state_ref *state,
3808 unsigned aux_modes,
3809 enum isl_aux_usage aux_usage)
3810 {
3811 struct isl_device *isl_dev = &batch->screen->isl_dev;
3812 struct iris_bo *state_bo = iris_resource_bo(state->res);
3813 uint64_t real_offset = state->offset +
3814 IRIS_MEMZONE_BINDER_START;
3815 uint32_t offset_into_bo = real_offset - state_bo->gtt_offset;
3816 uint32_t clear_offset = offset_into_bo +
3817 isl_dev->ss.clear_value_offset +
3818 surf_state_offset_for_aux(res, aux_modes, aux_usage);
3819
3820 batch->vtbl->copy_mem_mem(batch, state_bo, clear_offset,
3821 res->aux.clear_color_bo,
3822 res->aux.clear_color_offset,
3823 isl_dev->ss.clear_value_size);
3824 }
3825
3826 static void
3827 update_clear_value(struct iris_context *ice,
3828 struct iris_batch *batch,
3829 struct iris_resource *res,
3830 struct iris_state_ref *state,
3831 unsigned aux_modes,
3832 struct isl_view *view)
3833 {
3834 struct iris_screen *screen = batch->screen;
3835 const struct gen_device_info *devinfo = &screen->devinfo;
3836
3837 /* We only need to update the clear color in the surface state for gen8 and
3838 * gen9. Newer gens can read it directly from the clear color state buffer.
3839 */
3840 if (devinfo->gen > 9)
3841 return;
3842
3843 if (devinfo->gen == 9) {
3844 /* Skip updating the ISL_AUX_USAGE_NONE surface state */
3845 aux_modes &= ~(1 << ISL_AUX_USAGE_NONE);
3846
3847 while (aux_modes) {
3848 enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
3849
3850 surf_state_update_clear_value(batch, res, state, aux_modes,
3851 aux_usage);
3852 }
3853 } else if (devinfo->gen == 8) {
3854 pipe_resource_reference(&state->res, NULL);
3855 void *map = alloc_surface_states(ice->state.surface_uploader,
3856 state, res->aux.possible_usages);
3857 while (aux_modes) {
3858 enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
3859 fill_surface_state(&screen->isl_dev, map, res, view, aux_usage);
3860 map += SURFACE_STATE_ALIGNMENT;
3861 }
3862 }
3863 }
3864
3865 /**
3866 * Add a surface to the validation list, as well as the buffer containing
3867 * the corresponding SURFACE_STATE.
3868 *
3869 * Returns the binding table entry (offset to SURFACE_STATE).
3870 */
3871 static uint32_t
3872 use_surface(struct iris_context *ice,
3873 struct iris_batch *batch,
3874 struct pipe_surface *p_surf,
3875 bool writeable,
3876 enum isl_aux_usage aux_usage)
3877 {
3878 struct iris_surface *surf = (void *) p_surf;
3879 struct iris_resource *res = (void *) p_surf->texture;
3880
3881 iris_use_pinned_bo(batch, iris_resource_bo(p_surf->texture), writeable);
3882 iris_use_pinned_bo(batch, iris_resource_bo(surf->surface_state.res), false);
3883
3884 if (res->aux.bo) {
3885 iris_use_pinned_bo(batch, res->aux.bo, writeable);
3886 if (res->aux.clear_color_bo)
3887 iris_use_pinned_bo(batch, res->aux.clear_color_bo, false);
3888
3889 if (memcmp(&res->aux.clear_color, &surf->clear_color,
3890 sizeof(surf->clear_color)) != 0) {
3891 update_clear_value(ice, batch, res, &surf->surface_state,
3892 res->aux.possible_usages, &surf->view);
3893 surf->clear_color = res->aux.clear_color;
3894 }
3895 }
3896
3897 return surf->surface_state.offset +
3898 surf_state_offset_for_aux(res, res->aux.possible_usages, aux_usage);
3899 }
3900
3901 static uint32_t
3902 use_sampler_view(struct iris_context *ice,
3903 struct iris_batch *batch,
3904 struct iris_sampler_view *isv)
3905 {
3906 // XXX: ASTC hacks
3907 enum isl_aux_usage aux_usage =
3908 iris_resource_texture_aux_usage(ice, isv->res, isv->view.format, 0);
3909
3910 iris_use_pinned_bo(batch, isv->res->bo, false);
3911 iris_use_pinned_bo(batch, iris_resource_bo(isv->surface_state.res), false);
3912
3913 if (isv->res->aux.bo) {
3914 iris_use_pinned_bo(batch, isv->res->aux.bo, false);
3915 if (isv->res->aux.clear_color_bo)
3916 iris_use_pinned_bo(batch, isv->res->aux.clear_color_bo, false);
3917 if (memcmp(&isv->res->aux.clear_color, &isv->clear_color,
3918 sizeof(isv->clear_color)) != 0) {
3919 update_clear_value(ice, batch, isv->res, &isv->surface_state,
3920 isv->res->aux.sampler_usages, &isv->view);
3921 isv->clear_color = isv->res->aux.clear_color;
3922 }
3923 }
3924
3925 return isv->surface_state.offset +
3926 surf_state_offset_for_aux(isv->res, isv->res->aux.sampler_usages,
3927 aux_usage);
3928 }
3929
3930 static uint32_t
3931 use_ubo_ssbo(struct iris_batch *batch,
3932 struct iris_context *ice,
3933 struct pipe_shader_buffer *buf,
3934 struct iris_state_ref *surf_state,
3935 bool writable)
3936 {
3937 if (!buf->buffer)
3938 return use_null_surface(batch, ice);
3939
3940 iris_use_pinned_bo(batch, iris_resource_bo(buf->buffer), writable);
3941 iris_use_pinned_bo(batch, iris_resource_bo(surf_state->res), false);
3942
3943 return surf_state->offset;
3944 }
3945
3946 static uint32_t
3947 use_image(struct iris_batch *batch, struct iris_context *ice,
3948 struct iris_shader_state *shs, int i)
3949 {
3950 struct iris_image_view *iv = &shs->image[i];
3951 struct iris_resource *res = (void *) iv->base.resource;
3952
3953 if (!res)
3954 return use_null_surface(batch, ice);
3955
3956 bool write = iv->base.shader_access & PIPE_IMAGE_ACCESS_WRITE;
3957
3958 iris_use_pinned_bo(batch, res->bo, write);
3959 iris_use_pinned_bo(batch, iris_resource_bo(iv->surface_state.res), false);
3960
3961 if (res->aux.bo)
3962 iris_use_pinned_bo(batch, res->aux.bo, write);
3963
3964 return iv->surface_state.offset;
3965 }
3966
3967 #define push_bt_entry(addr) \
3968 assert(addr >= binder_addr); \
3969 assert(s < shader->bt.size_bytes / sizeof(uint32_t)); \
3970 if (!pin_only) bt_map[s++] = (addr) - binder_addr;
3971
3972 #define bt_assert(section) \
3973 if (!pin_only && shader->bt.used_mask[section] != 0) \
3974 assert(shader->bt.offsets[section] == s);
3975
3976 /**
3977 * Populate the binding table for a given shader stage.
3978 *
3979 * This fills out the table of pointers to surfaces required by the shader,
3980 * and also adds those buffers to the validation list so the kernel can make
3981 * resident before running our batch.
3982 */
3983 static void
3984 iris_populate_binding_table(struct iris_context *ice,
3985 struct iris_batch *batch,
3986 gl_shader_stage stage,
3987 bool pin_only)
3988 {
3989 const struct iris_binder *binder = &ice->state.binder;
3990 struct iris_uncompiled_shader *ish = ice->shaders.uncompiled[stage];
3991 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3992 if (!shader)
3993 return;
3994
3995 struct iris_binding_table *bt = &shader->bt;
3996 UNUSED struct brw_stage_prog_data *prog_data = shader->prog_data;
3997 struct iris_shader_state *shs = &ice->state.shaders[stage];
3998 uint32_t binder_addr = binder->bo->gtt_offset;
3999
4000 uint32_t *bt_map = binder->map + binder->bt_offset[stage];
4001 int s = 0;
4002
4003 const struct shader_info *info = iris_get_shader_info(ice, stage);
4004 if (!info) {
4005 /* TCS passthrough doesn't need a binding table. */
4006 assert(stage == MESA_SHADER_TESS_CTRL);
4007 return;
4008 }
4009
4010 if (stage == MESA_SHADER_COMPUTE &&
4011 shader->bt.used_mask[IRIS_SURFACE_GROUP_CS_WORK_GROUPS]) {
4012 /* surface for gl_NumWorkGroups */
4013 struct iris_state_ref *grid_data = &ice->state.grid_size;
4014 struct iris_state_ref *grid_state = &ice->state.grid_surf_state;
4015 iris_use_pinned_bo(batch, iris_resource_bo(grid_data->res), false);
4016 iris_use_pinned_bo(batch, iris_resource_bo(grid_state->res), false);
4017 push_bt_entry(grid_state->offset);
4018 }
4019
4020 if (stage == MESA_SHADER_FRAGMENT) {
4021 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4022 /* Note that cso_fb->nr_cbufs == fs_key->nr_color_regions. */
4023 if (cso_fb->nr_cbufs) {
4024 for (unsigned i = 0; i < cso_fb->nr_cbufs; i++) {
4025 uint32_t addr;
4026 if (cso_fb->cbufs[i]) {
4027 addr = use_surface(ice, batch, cso_fb->cbufs[i], true,
4028 ice->state.draw_aux_usage[i]);
4029 } else {
4030 addr = use_null_fb_surface(batch, ice);
4031 }
4032 push_bt_entry(addr);
4033 }
4034 } else {
4035 uint32_t addr = use_null_fb_surface(batch, ice);
4036 push_bt_entry(addr);
4037 }
4038 }
4039
4040 #define foreach_surface_used(index, group) \
4041 bt_assert(group); \
4042 for (int index = 0; index < bt->sizes[group]; index++) \
4043 if (iris_group_index_to_bti(bt, group, index) != \
4044 IRIS_SURFACE_NOT_USED)
4045
4046 foreach_surface_used(i, IRIS_SURFACE_GROUP_TEXTURE) {
4047 struct iris_sampler_view *view = shs->textures[i];
4048 uint32_t addr = view ? use_sampler_view(ice, batch, view)
4049 : use_null_surface(batch, ice);
4050 push_bt_entry(addr);
4051 }
4052
4053 foreach_surface_used(i, IRIS_SURFACE_GROUP_IMAGE) {
4054 uint32_t addr = use_image(batch, ice, shs, i);
4055 push_bt_entry(addr);
4056 }
4057
4058 foreach_surface_used(i, IRIS_SURFACE_GROUP_UBO) {
4059 uint32_t addr;
4060
4061 if (i == bt->sizes[IRIS_SURFACE_GROUP_UBO] - 1) {
4062 if (ish->const_data) {
4063 iris_use_pinned_bo(batch, iris_resource_bo(ish->const_data), false);
4064 iris_use_pinned_bo(batch, iris_resource_bo(ish->const_data_state.res),
4065 false);
4066 addr = ish->const_data_state.offset;
4067 } else {
4068 /* This can only happen with INTEL_DISABLE_COMPACT_BINDING_TABLE=1. */
4069 addr = use_null_surface(batch, ice);
4070 }
4071 } else {
4072 addr = use_ubo_ssbo(batch, ice, &shs->constbuf[i],
4073 &shs->constbuf_surf_state[i], false);
4074 }
4075
4076 push_bt_entry(addr);
4077 }
4078
4079 foreach_surface_used(i, IRIS_SURFACE_GROUP_SSBO) {
4080 uint32_t addr =
4081 use_ubo_ssbo(batch, ice, &shs->ssbo[i], &shs->ssbo_surf_state[i],
4082 shs->writable_ssbos & (1u << i));
4083 push_bt_entry(addr);
4084 }
4085
4086 #if 0
4087 /* XXX: YUV surfaces not implemented yet */
4088 bt_assert(plane_start[1], ...);
4089 bt_assert(plane_start[2], ...);
4090 #endif
4091 }
4092
4093 static void
4094 iris_use_optional_res(struct iris_batch *batch,
4095 struct pipe_resource *res,
4096 bool writeable)
4097 {
4098 if (res) {
4099 struct iris_bo *bo = iris_resource_bo(res);
4100 iris_use_pinned_bo(batch, bo, writeable);
4101 }
4102 }
4103
4104 static void
4105 pin_depth_and_stencil_buffers(struct iris_batch *batch,
4106 struct pipe_surface *zsbuf,
4107 struct iris_depth_stencil_alpha_state *cso_zsa)
4108 {
4109 if (!zsbuf)
4110 return;
4111
4112 struct iris_resource *zres, *sres;
4113 iris_get_depth_stencil_resources(zsbuf->texture, &zres, &sres);
4114
4115 if (zres) {
4116 iris_use_pinned_bo(batch, zres->bo, cso_zsa->depth_writes_enabled);
4117 if (zres->aux.bo) {
4118 iris_use_pinned_bo(batch, zres->aux.bo,
4119 cso_zsa->depth_writes_enabled);
4120 }
4121 }
4122
4123 if (sres) {
4124 iris_use_pinned_bo(batch, sres->bo, cso_zsa->stencil_writes_enabled);
4125 }
4126 }
4127
4128 /* ------------------------------------------------------------------- */
4129
4130 /**
4131 * Pin any BOs which were installed by a previous batch, and restored
4132 * via the hardware logical context mechanism.
4133 *
4134 * We don't need to re-emit all state every batch - the hardware context
4135 * mechanism will save and restore it for us. This includes pointers to
4136 * various BOs...which won't exist unless we ask the kernel to pin them
4137 * by adding them to the validation list.
4138 *
4139 * We can skip buffers if we've re-emitted those packets, as we're
4140 * overwriting those stale pointers with new ones, and don't actually
4141 * refer to the old BOs.
4142 */
4143 static void
4144 iris_restore_render_saved_bos(struct iris_context *ice,
4145 struct iris_batch *batch,
4146 const struct pipe_draw_info *draw)
4147 {
4148 struct iris_genx_state *genx = ice->state.genx;
4149
4150 const uint64_t clean = ~ice->state.dirty;
4151
4152 if (clean & IRIS_DIRTY_CC_VIEWPORT) {
4153 iris_use_optional_res(batch, ice->state.last_res.cc_vp, false);
4154 }
4155
4156 if (clean & IRIS_DIRTY_SF_CL_VIEWPORT) {
4157 iris_use_optional_res(batch, ice->state.last_res.sf_cl_vp, false);
4158 }
4159
4160 if (clean & IRIS_DIRTY_BLEND_STATE) {
4161 iris_use_optional_res(batch, ice->state.last_res.blend, false);
4162 }
4163
4164 if (clean & IRIS_DIRTY_COLOR_CALC_STATE) {
4165 iris_use_optional_res(batch, ice->state.last_res.color_calc, false);
4166 }
4167
4168 if (clean & IRIS_DIRTY_SCISSOR_RECT) {
4169 iris_use_optional_res(batch, ice->state.last_res.scissor, false);
4170 }
4171
4172 if (ice->state.streamout_active && (clean & IRIS_DIRTY_SO_BUFFERS)) {
4173 for (int i = 0; i < 4; i++) {
4174 struct iris_stream_output_target *tgt =
4175 (void *) ice->state.so_target[i];
4176 if (tgt) {
4177 iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
4178 true);
4179 iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
4180 true);
4181 }
4182 }
4183 }
4184
4185 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4186 if (!(clean & (IRIS_DIRTY_CONSTANTS_VS << stage)))
4187 continue;
4188
4189 struct iris_shader_state *shs = &ice->state.shaders[stage];
4190 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
4191
4192 if (!shader)
4193 continue;
4194
4195 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
4196
4197 for (int i = 0; i < 4; i++) {
4198 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
4199
4200 if (range->length == 0)
4201 continue;
4202
4203 /* Range block is a binding table index, map back to UBO index. */
4204 unsigned block_index = iris_bti_to_group_index(
4205 &shader->bt, IRIS_SURFACE_GROUP_UBO, range->block);
4206 assert(block_index != IRIS_SURFACE_NOT_USED);
4207
4208 struct pipe_shader_buffer *cbuf = &shs->constbuf[block_index];
4209 struct iris_resource *res = (void *) cbuf->buffer;
4210
4211 if (res)
4212 iris_use_pinned_bo(batch, res->bo, false);
4213 else
4214 iris_use_pinned_bo(batch, batch->screen->workaround_bo, false);
4215 }
4216 }
4217
4218 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4219 if (clean & (IRIS_DIRTY_BINDINGS_VS << stage)) {
4220 /* Re-pin any buffers referred to by the binding table. */
4221 iris_populate_binding_table(ice, batch, stage, true);
4222 }
4223 }
4224
4225 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4226 struct iris_shader_state *shs = &ice->state.shaders[stage];
4227 struct pipe_resource *res = shs->sampler_table.res;
4228 if (res)
4229 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
4230 }
4231
4232 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4233 if (clean & (IRIS_DIRTY_VS << stage)) {
4234 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
4235
4236 if (shader) {
4237 struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
4238 iris_use_pinned_bo(batch, bo, false);
4239
4240 struct brw_stage_prog_data *prog_data = shader->prog_data;
4241
4242 if (prog_data->total_scratch > 0) {
4243 struct iris_bo *bo =
4244 iris_get_scratch_space(ice, prog_data->total_scratch, stage);
4245 iris_use_pinned_bo(batch, bo, true);
4246 }
4247 }
4248 }
4249 }
4250
4251 if ((clean & IRIS_DIRTY_DEPTH_BUFFER) &&
4252 (clean & IRIS_DIRTY_WM_DEPTH_STENCIL)) {
4253 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4254 pin_depth_and_stencil_buffers(batch, cso_fb->zsbuf, ice->state.cso_zsa);
4255 }
4256
4257 iris_use_optional_res(batch, ice->state.last_res.index_buffer, false);
4258
4259 if (clean & IRIS_DIRTY_VERTEX_BUFFERS) {
4260 uint64_t bound = ice->state.bound_vertex_buffers;
4261 while (bound) {
4262 const int i = u_bit_scan64(&bound);
4263 struct pipe_resource *res = genx->vertex_buffers[i].resource;
4264 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
4265 }
4266 }
4267 }
4268
4269 static void
4270 iris_restore_compute_saved_bos(struct iris_context *ice,
4271 struct iris_batch *batch,
4272 const struct pipe_grid_info *grid)
4273 {
4274 const uint64_t clean = ~ice->state.dirty;
4275
4276 const int stage = MESA_SHADER_COMPUTE;
4277 struct iris_shader_state *shs = &ice->state.shaders[stage];
4278
4279 if (clean & IRIS_DIRTY_BINDINGS_CS) {
4280 /* Re-pin any buffers referred to by the binding table. */
4281 iris_populate_binding_table(ice, batch, stage, true);
4282 }
4283
4284 struct pipe_resource *sampler_res = shs->sampler_table.res;
4285 if (sampler_res)
4286 iris_use_pinned_bo(batch, iris_resource_bo(sampler_res), false);
4287
4288 if ((clean & IRIS_DIRTY_SAMPLER_STATES_CS) &&
4289 (clean & IRIS_DIRTY_BINDINGS_CS) &&
4290 (clean & IRIS_DIRTY_CONSTANTS_CS) &&
4291 (clean & IRIS_DIRTY_CS)) {
4292 iris_use_optional_res(batch, ice->state.last_res.cs_desc, false);
4293 }
4294
4295 if (clean & IRIS_DIRTY_CS) {
4296 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
4297
4298 if (shader) {
4299 struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
4300 iris_use_pinned_bo(batch, bo, false);
4301
4302 struct iris_bo *curbe_bo =
4303 iris_resource_bo(ice->state.last_res.cs_thread_ids);
4304 iris_use_pinned_bo(batch, curbe_bo, false);
4305
4306 struct brw_stage_prog_data *prog_data = shader->prog_data;
4307
4308 if (prog_data->total_scratch > 0) {
4309 struct iris_bo *bo =
4310 iris_get_scratch_space(ice, prog_data->total_scratch, stage);
4311 iris_use_pinned_bo(batch, bo, true);
4312 }
4313 }
4314 }
4315 }
4316
4317 /**
4318 * Possibly emit STATE_BASE_ADDRESS to update Surface State Base Address.
4319 */
4320 static void
4321 iris_update_surface_base_address(struct iris_batch *batch,
4322 struct iris_binder *binder)
4323 {
4324 if (batch->last_surface_base_address == binder->bo->gtt_offset)
4325 return;
4326
4327 flush_for_state_base_change(batch);
4328
4329 iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
4330 sba.SurfaceStateMOCS = MOCS_WB;
4331 sba.SurfaceStateBaseAddressModifyEnable = true;
4332 sba.SurfaceStateBaseAddress = ro_bo(binder->bo, 0);
4333 }
4334
4335 batch->last_surface_base_address = binder->bo->gtt_offset;
4336 }
4337
4338 static void
4339 iris_upload_dirty_render_state(struct iris_context *ice,
4340 struct iris_batch *batch,
4341 const struct pipe_draw_info *draw)
4342 {
4343 const uint64_t dirty = ice->state.dirty;
4344
4345 if (!(dirty & IRIS_ALL_DIRTY_FOR_RENDER))
4346 return;
4347
4348 struct iris_genx_state *genx = ice->state.genx;
4349 struct iris_binder *binder = &ice->state.binder;
4350 struct brw_wm_prog_data *wm_prog_data = (void *)
4351 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
4352
4353 if (dirty & IRIS_DIRTY_CC_VIEWPORT) {
4354 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4355 uint32_t cc_vp_address;
4356
4357 /* XXX: could avoid streaming for depth_clip [0,1] case. */
4358 uint32_t *cc_vp_map =
4359 stream_state(batch, ice->state.dynamic_uploader,
4360 &ice->state.last_res.cc_vp,
4361 4 * ice->state.num_viewports *
4362 GENX(CC_VIEWPORT_length), 32, &cc_vp_address);
4363 for (int i = 0; i < ice->state.num_viewports; i++) {
4364 float zmin, zmax;
4365 util_viewport_zmin_zmax(&ice->state.viewports[i],
4366 cso_rast->clip_halfz, &zmin, &zmax);
4367 if (cso_rast->depth_clip_near)
4368 zmin = 0.0;
4369 if (cso_rast->depth_clip_far)
4370 zmax = 1.0;
4371
4372 iris_pack_state(GENX(CC_VIEWPORT), cc_vp_map, ccv) {
4373 ccv.MinimumDepth = zmin;
4374 ccv.MaximumDepth = zmax;
4375 }
4376
4377 cc_vp_map += GENX(CC_VIEWPORT_length);
4378 }
4379
4380 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_CC), ptr) {
4381 ptr.CCViewportPointer = cc_vp_address;
4382 }
4383 }
4384
4385 if (dirty & IRIS_DIRTY_SF_CL_VIEWPORT) {
4386 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4387 uint32_t sf_cl_vp_address;
4388 uint32_t *vp_map =
4389 stream_state(batch, ice->state.dynamic_uploader,
4390 &ice->state.last_res.sf_cl_vp,
4391 4 * ice->state.num_viewports *
4392 GENX(SF_CLIP_VIEWPORT_length), 64, &sf_cl_vp_address);
4393
4394 for (unsigned i = 0; i < ice->state.num_viewports; i++) {
4395 const struct pipe_viewport_state *state = &ice->state.viewports[i];
4396 float gb_xmin, gb_xmax, gb_ymin, gb_ymax;
4397
4398 float vp_xmin = viewport_extent(state, 0, -1.0f);
4399 float vp_xmax = viewport_extent(state, 0, 1.0f);
4400 float vp_ymin = viewport_extent(state, 1, -1.0f);
4401 float vp_ymax = viewport_extent(state, 1, 1.0f);
4402
4403 gen_calculate_guardband_size(cso_fb->width, cso_fb->height,
4404 state->scale[0], state->scale[1],
4405 state->translate[0], state->translate[1],
4406 &gb_xmin, &gb_xmax, &gb_ymin, &gb_ymax);
4407
4408 iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
4409 vp.ViewportMatrixElementm00 = state->scale[0];
4410 vp.ViewportMatrixElementm11 = state->scale[1];
4411 vp.ViewportMatrixElementm22 = state->scale[2];
4412 vp.ViewportMatrixElementm30 = state->translate[0];
4413 vp.ViewportMatrixElementm31 = state->translate[1];
4414 vp.ViewportMatrixElementm32 = state->translate[2];
4415 vp.XMinClipGuardband = gb_xmin;
4416 vp.XMaxClipGuardband = gb_xmax;
4417 vp.YMinClipGuardband = gb_ymin;
4418 vp.YMaxClipGuardband = gb_ymax;
4419 vp.XMinViewPort = MAX2(vp_xmin, 0);
4420 vp.XMaxViewPort = MIN2(vp_xmax, cso_fb->width) - 1;
4421 vp.YMinViewPort = MAX2(vp_ymin, 0);
4422 vp.YMaxViewPort = MIN2(vp_ymax, cso_fb->height) - 1;
4423 }
4424
4425 vp_map += GENX(SF_CLIP_VIEWPORT_length);
4426 }
4427
4428 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
4429 ptr.SFClipViewportPointer = sf_cl_vp_address;
4430 }
4431 }
4432
4433 if (dirty & IRIS_DIRTY_URB) {
4434 unsigned size[4];
4435
4436 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
4437 if (!ice->shaders.prog[i]) {
4438 size[i] = 1;
4439 } else {
4440 struct brw_vue_prog_data *vue_prog_data =
4441 (void *) ice->shaders.prog[i]->prog_data;
4442 size[i] = vue_prog_data->urb_entry_size;
4443 }
4444 assert(size[i] != 0);
4445 }
4446
4447 genX(emit_urb_setup)(ice, batch, size,
4448 ice->shaders.prog[MESA_SHADER_TESS_EVAL] != NULL,
4449 ice->shaders.prog[MESA_SHADER_GEOMETRY] != NULL);
4450 }
4451
4452 if (dirty & IRIS_DIRTY_BLEND_STATE) {
4453 struct iris_blend_state *cso_blend = ice->state.cso_blend;
4454 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4455 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
4456 const int header_dwords = GENX(BLEND_STATE_length);
4457
4458 /* Always write at least one BLEND_STATE - the final RT message will
4459 * reference BLEND_STATE[0] even if there aren't color writes. There
4460 * may still be alpha testing, computed depth, and so on.
4461 */
4462 const int rt_dwords =
4463 MAX2(cso_fb->nr_cbufs, 1) * GENX(BLEND_STATE_ENTRY_length);
4464
4465 uint32_t blend_offset;
4466 uint32_t *blend_map =
4467 stream_state(batch, ice->state.dynamic_uploader,
4468 &ice->state.last_res.blend,
4469 4 * (header_dwords + rt_dwords), 64, &blend_offset);
4470
4471 uint32_t blend_state_header;
4472 iris_pack_state(GENX(BLEND_STATE), &blend_state_header, bs) {
4473 bs.AlphaTestEnable = cso_zsa->alpha.enabled;
4474 bs.AlphaTestFunction = translate_compare_func(cso_zsa->alpha.func);
4475 }
4476
4477 blend_map[0] = blend_state_header | cso_blend->blend_state[0];
4478 memcpy(&blend_map[1], &cso_blend->blend_state[1], 4 * rt_dwords);
4479
4480 iris_emit_cmd(batch, GENX(3DSTATE_BLEND_STATE_POINTERS), ptr) {
4481 ptr.BlendStatePointer = blend_offset;
4482 ptr.BlendStatePointerValid = true;
4483 }
4484 }
4485
4486 if (dirty & IRIS_DIRTY_COLOR_CALC_STATE) {
4487 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
4488 #if GEN_GEN == 8
4489 struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
4490 #endif
4491 uint32_t cc_offset;
4492 void *cc_map =
4493 stream_state(batch, ice->state.dynamic_uploader,
4494 &ice->state.last_res.color_calc,
4495 sizeof(uint32_t) * GENX(COLOR_CALC_STATE_length),
4496 64, &cc_offset);
4497 iris_pack_state(GENX(COLOR_CALC_STATE), cc_map, cc) {
4498 cc.AlphaTestFormat = ALPHATEST_FLOAT32;
4499 cc.AlphaReferenceValueAsFLOAT32 = cso->alpha.ref_value;
4500 cc.BlendConstantColorRed = ice->state.blend_color.color[0];
4501 cc.BlendConstantColorGreen = ice->state.blend_color.color[1];
4502 cc.BlendConstantColorBlue = ice->state.blend_color.color[2];
4503 cc.BlendConstantColorAlpha = ice->state.blend_color.color[3];
4504 #if GEN_GEN == 8
4505 cc.StencilReferenceValue = p_stencil_refs->ref_value[0];
4506 cc.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
4507 #endif
4508 }
4509 iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
4510 ptr.ColorCalcStatePointer = cc_offset;
4511 ptr.ColorCalcStatePointerValid = true;
4512 }
4513 }
4514
4515 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4516 if (!(dirty & (IRIS_DIRTY_CONSTANTS_VS << stage)))
4517 continue;
4518
4519 struct iris_shader_state *shs = &ice->state.shaders[stage];
4520 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
4521
4522 if (!shader)
4523 continue;
4524
4525 if (shs->sysvals_need_upload)
4526 upload_sysvals(ice, stage);
4527
4528 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
4529
4530 iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_VS), pkt) {
4531 pkt._3DCommandSubOpcode = push_constant_opcodes[stage];
4532 if (prog_data) {
4533 /* The Skylake PRM contains the following restriction:
4534 *
4535 * "The driver must ensure The following case does not occur
4536 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
4537 * buffer 3 read length equal to zero committed followed by a
4538 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
4539 * zero committed."
4540 *
4541 * To avoid this, we program the buffers in the highest slots.
4542 * This way, slot 0 is only used if slot 3 is also used.
4543 */
4544 int n = 3;
4545
4546 for (int i = 3; i >= 0; i--) {
4547 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
4548
4549 if (range->length == 0)
4550 continue;
4551
4552 /* Range block is a binding table index, map back to UBO index. */
4553 unsigned block_index = iris_bti_to_group_index(
4554 &shader->bt, IRIS_SURFACE_GROUP_UBO, range->block);
4555 assert(block_index != IRIS_SURFACE_NOT_USED);
4556
4557 struct pipe_shader_buffer *cbuf = &shs->constbuf[block_index];
4558 struct iris_resource *res = (void *) cbuf->buffer;
4559
4560 assert(cbuf->buffer_offset % 32 == 0);
4561
4562 pkt.ConstantBody.ReadLength[n] = range->length;
4563 pkt.ConstantBody.Buffer[n] =
4564 res ? ro_bo(res->bo, range->start * 32 + cbuf->buffer_offset)
4565 : ro_bo(batch->screen->workaround_bo, 0);
4566 n--;
4567 }
4568 }
4569 }
4570 }
4571
4572 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4573 if (dirty & (IRIS_DIRTY_BINDINGS_VS << stage)) {
4574 iris_emit_cmd(batch, GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), ptr) {
4575 ptr._3DCommandSubOpcode = 38 + stage;
4576 ptr.PointertoVSBindingTable = binder->bt_offset[stage];
4577 }
4578 }
4579 }
4580
4581 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4582 if (dirty & (IRIS_DIRTY_BINDINGS_VS << stage)) {
4583 iris_populate_binding_table(ice, batch, stage, false);
4584 }
4585 }
4586
4587 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4588 if (!(dirty & (IRIS_DIRTY_SAMPLER_STATES_VS << stage)) ||
4589 !ice->shaders.prog[stage])
4590 continue;
4591
4592 iris_upload_sampler_states(ice, stage);
4593
4594 struct iris_shader_state *shs = &ice->state.shaders[stage];
4595 struct pipe_resource *res = shs->sampler_table.res;
4596 if (res)
4597 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
4598
4599 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ptr) {
4600 ptr._3DCommandSubOpcode = 43 + stage;
4601 ptr.PointertoVSSamplerState = shs->sampler_table.offset;
4602 }
4603 }
4604
4605 if (ice->state.need_border_colors)
4606 iris_use_pinned_bo(batch, ice->state.border_color_pool.bo, false);
4607
4608 if (dirty & IRIS_DIRTY_MULTISAMPLE) {
4609 iris_emit_cmd(batch, GENX(3DSTATE_MULTISAMPLE), ms) {
4610 ms.PixelLocation =
4611 ice->state.cso_rast->half_pixel_center ? CENTER : UL_CORNER;
4612 if (ice->state.framebuffer.samples > 0)
4613 ms.NumberofMultisamples = ffs(ice->state.framebuffer.samples) - 1;
4614 }
4615 }
4616
4617 if (dirty & IRIS_DIRTY_SAMPLE_MASK) {
4618 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_MASK), ms) {
4619 ms.SampleMask = ice->state.sample_mask;
4620 }
4621 }
4622
4623 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
4624 if (!(dirty & (IRIS_DIRTY_VS << stage)))
4625 continue;
4626
4627 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
4628
4629 if (shader) {
4630 struct brw_stage_prog_data *prog_data = shader->prog_data;
4631 struct iris_resource *cache = (void *) shader->assembly.res;
4632 iris_use_pinned_bo(batch, cache->bo, false);
4633
4634 if (prog_data->total_scratch > 0) {
4635 struct iris_bo *bo =
4636 iris_get_scratch_space(ice, prog_data->total_scratch, stage);
4637 iris_use_pinned_bo(batch, bo, true);
4638 }
4639
4640 if (stage == MESA_SHADER_FRAGMENT) {
4641 UNUSED struct iris_rasterizer_state *cso = ice->state.cso_rast;
4642 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4643
4644 uint32_t ps_state[GENX(3DSTATE_PS_length)] = {0};
4645 iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
4646 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
4647 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
4648 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
4649
4650 /* The docs for 3DSTATE_PS::32 Pixel Dispatch Enable say:
4651 *
4652 * "When NUM_MULTISAMPLES = 16 or FORCE_SAMPLE_COUNT = 16,
4653 * SIMD32 Dispatch must not be enabled for PER_PIXEL dispatch
4654 * mode."
4655 *
4656 * 16x MSAA only exists on Gen9+, so we can skip this on Gen8.
4657 */
4658 if (GEN_GEN >= 9 && cso_fb->samples == 16 &&
4659 !wm_prog_data->persample_dispatch) {
4660 assert(ps._8PixelDispatchEnable || ps._16PixelDispatchEnable);
4661 ps._32PixelDispatchEnable = false;
4662 }
4663
4664 ps.DispatchGRFStartRegisterForConstantSetupData0 =
4665 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
4666 ps.DispatchGRFStartRegisterForConstantSetupData1 =
4667 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
4668 ps.DispatchGRFStartRegisterForConstantSetupData2 =
4669 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
4670
4671 ps.KernelStartPointer0 = KSP(shader) +
4672 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
4673 ps.KernelStartPointer1 = KSP(shader) +
4674 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
4675 ps.KernelStartPointer2 = KSP(shader) +
4676 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
4677 }
4678
4679 uint32_t psx_state[GENX(3DSTATE_PS_EXTRA_length)] = {0};
4680 iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
4681 #if GEN_GEN >= 9
4682 if (wm_prog_data->post_depth_coverage)
4683 psx.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
4684 else if (wm_prog_data->inner_coverage &&
4685 cso->conservative_rasterization)
4686 psx.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
4687 else
4688 psx.InputCoverageMaskState = ICMS_NORMAL;
4689 #else
4690 psx.PixelShaderUsesInputCoverageMask =
4691 wm_prog_data->uses_sample_mask;
4692 #endif
4693 }
4694
4695 uint32_t *shader_ps = (uint32_t *) shader->derived_data;
4696 uint32_t *shader_psx = shader_ps + GENX(3DSTATE_PS_length);
4697 iris_emit_merge(batch, shader_ps, ps_state,
4698 GENX(3DSTATE_PS_length));
4699 iris_emit_merge(batch, shader_psx, psx_state,
4700 GENX(3DSTATE_PS_EXTRA_length));
4701 } else {
4702 iris_batch_emit(batch, shader->derived_data,
4703 iris_derived_program_state_size(stage));
4704 }
4705 } else {
4706 if (stage == MESA_SHADER_TESS_EVAL) {
4707 iris_emit_cmd(batch, GENX(3DSTATE_HS), hs);
4708 iris_emit_cmd(batch, GENX(3DSTATE_TE), te);
4709 iris_emit_cmd(batch, GENX(3DSTATE_DS), ds);
4710 } else if (stage == MESA_SHADER_GEOMETRY) {
4711 iris_emit_cmd(batch, GENX(3DSTATE_GS), gs);
4712 }
4713 }
4714 }
4715
4716 if (ice->state.streamout_active) {
4717 if (dirty & IRIS_DIRTY_SO_BUFFERS) {
4718 iris_batch_emit(batch, genx->so_buffers,
4719 4 * 4 * GENX(3DSTATE_SO_BUFFER_length));
4720 for (int i = 0; i < 4; i++) {
4721 struct iris_stream_output_target *tgt =
4722 (void *) ice->state.so_target[i];
4723 if (tgt) {
4724 tgt->zeroed = true;
4725 iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
4726 true);
4727 iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
4728 true);
4729 }
4730 }
4731 }
4732
4733 if ((dirty & IRIS_DIRTY_SO_DECL_LIST) && ice->state.streamout) {
4734 uint32_t *decl_list =
4735 ice->state.streamout + GENX(3DSTATE_STREAMOUT_length);
4736 iris_batch_emit(batch, decl_list, 4 * ((decl_list[0] & 0xff) + 2));
4737 }
4738
4739 if (dirty & IRIS_DIRTY_STREAMOUT) {
4740 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4741
4742 uint32_t dynamic_sol[GENX(3DSTATE_STREAMOUT_length)];
4743 iris_pack_command(GENX(3DSTATE_STREAMOUT), dynamic_sol, sol) {
4744 sol.SOFunctionEnable = true;
4745 sol.SOStatisticsEnable = true;
4746
4747 sol.RenderingDisable = cso_rast->rasterizer_discard &&
4748 !ice->state.prims_generated_query_active;
4749 sol.ReorderMode = cso_rast->flatshade_first ? LEADING : TRAILING;
4750 }
4751
4752 assert(ice->state.streamout);
4753
4754 iris_emit_merge(batch, ice->state.streamout, dynamic_sol,
4755 GENX(3DSTATE_STREAMOUT_length));
4756 }
4757 } else {
4758 if (dirty & IRIS_DIRTY_STREAMOUT) {
4759 iris_emit_cmd(batch, GENX(3DSTATE_STREAMOUT), sol);
4760 }
4761 }
4762
4763 if (dirty & IRIS_DIRTY_CLIP) {
4764 struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
4765 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4766
4767 bool gs_or_tes = ice->shaders.prog[MESA_SHADER_GEOMETRY] ||
4768 ice->shaders.prog[MESA_SHADER_TESS_EVAL];
4769 bool points_or_lines = cso_rast->fill_mode_point_or_line ||
4770 (gs_or_tes ? ice->shaders.output_topology_is_points_or_lines
4771 : ice->state.prim_is_points_or_lines);
4772
4773 uint32_t dynamic_clip[GENX(3DSTATE_CLIP_length)];
4774 iris_pack_command(GENX(3DSTATE_CLIP), &dynamic_clip, cl) {
4775 cl.StatisticsEnable = ice->state.statistics_counters_enabled;
4776 cl.ClipMode = cso_rast->rasterizer_discard ? CLIPMODE_REJECT_ALL
4777 : CLIPMODE_NORMAL;
4778 cl.ViewportXYClipTestEnable = !points_or_lines;
4779
4780 if (wm_prog_data->barycentric_interp_modes &
4781 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS)
4782 cl.NonPerspectiveBarycentricEnable = true;
4783
4784 cl.ForceZeroRTAIndexEnable = cso_fb->layers == 0;
4785 cl.MaximumVPIndex = ice->state.num_viewports - 1;
4786 }
4787 iris_emit_merge(batch, cso_rast->clip, dynamic_clip,
4788 ARRAY_SIZE(cso_rast->clip));
4789 }
4790
4791 if (dirty & IRIS_DIRTY_RASTER) {
4792 struct iris_rasterizer_state *cso = ice->state.cso_rast;
4793 iris_batch_emit(batch, cso->raster, sizeof(cso->raster));
4794 iris_batch_emit(batch, cso->sf, sizeof(cso->sf));
4795
4796 }
4797
4798 if (dirty & IRIS_DIRTY_WM) {
4799 struct iris_rasterizer_state *cso = ice->state.cso_rast;
4800 uint32_t dynamic_wm[GENX(3DSTATE_WM_length)];
4801
4802 iris_pack_command(GENX(3DSTATE_WM), &dynamic_wm, wm) {
4803 wm.StatisticsEnable = ice->state.statistics_counters_enabled;
4804
4805 wm.BarycentricInterpolationMode =
4806 wm_prog_data->barycentric_interp_modes;
4807
4808 if (wm_prog_data->early_fragment_tests)
4809 wm.EarlyDepthStencilControl = EDSC_PREPS;
4810 else if (wm_prog_data->has_side_effects)
4811 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
4812
4813 /* We could skip this bit if color writes are enabled. */
4814 if (wm_prog_data->has_side_effects || wm_prog_data->uses_kill)
4815 wm.ForceThreadDispatchEnable = ForceON;
4816 }
4817 iris_emit_merge(batch, cso->wm, dynamic_wm, ARRAY_SIZE(cso->wm));
4818 }
4819
4820 if (dirty & IRIS_DIRTY_SBE) {
4821 iris_emit_sbe(batch, ice);
4822 }
4823
4824 if (dirty & IRIS_DIRTY_PS_BLEND) {
4825 struct iris_blend_state *cso_blend = ice->state.cso_blend;
4826 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
4827 const struct shader_info *fs_info =
4828 iris_get_shader_info(ice, MESA_SHADER_FRAGMENT);
4829
4830 uint32_t dynamic_pb[GENX(3DSTATE_PS_BLEND_length)];
4831 iris_pack_command(GENX(3DSTATE_PS_BLEND), &dynamic_pb, pb) {
4832 pb.HasWriteableRT = has_writeable_rt(cso_blend, fs_info);
4833 pb.AlphaTestEnable = cso_zsa->alpha.enabled;
4834
4835 /* The dual source blending docs caution against using SRC1 factors
4836 * when the shader doesn't use a dual source render target write.
4837 * Empirically, this can lead to GPU hangs, and the results are
4838 * undefined anyway, so simply disable blending to avoid the hang.
4839 */
4840 pb.ColorBufferBlendEnable = (cso_blend->blend_enables & 1) &&
4841 (!cso_blend->dual_color_blending || wm_prog_data->dual_src_blend);
4842 }
4843
4844 iris_emit_merge(batch, cso_blend->ps_blend, dynamic_pb,
4845 ARRAY_SIZE(cso_blend->ps_blend));
4846 }
4847
4848 if (dirty & IRIS_DIRTY_WM_DEPTH_STENCIL) {
4849 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
4850 #if GEN_GEN >= 9
4851 struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
4852 uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
4853 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
4854 wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
4855 wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
4856 }
4857 iris_emit_merge(batch, cso->wmds, stencil_refs, ARRAY_SIZE(cso->wmds));
4858 #else
4859 iris_batch_emit(batch, cso->wmds, sizeof(cso->wmds));
4860 #endif
4861 }
4862
4863 if (dirty & IRIS_DIRTY_SCISSOR_RECT) {
4864 uint32_t scissor_offset =
4865 emit_state(batch, ice->state.dynamic_uploader,
4866 &ice->state.last_res.scissor,
4867 ice->state.scissors,
4868 sizeof(struct pipe_scissor_state) *
4869 ice->state.num_viewports, 32);
4870
4871 iris_emit_cmd(batch, GENX(3DSTATE_SCISSOR_STATE_POINTERS), ptr) {
4872 ptr.ScissorRectPointer = scissor_offset;
4873 }
4874 }
4875
4876 if (dirty & IRIS_DIRTY_DEPTH_BUFFER) {
4877 struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
4878
4879 /* Do not emit the clear params yets. We need to update the clear value
4880 * first.
4881 */
4882 uint32_t clear_length = GENX(3DSTATE_CLEAR_PARAMS_length) * 4;
4883 uint32_t cso_z_size = sizeof(cso_z->packets) - clear_length;
4884 iris_batch_emit(batch, cso_z->packets, cso_z_size);
4885
4886 union isl_color_value clear_value = { .f32 = { 0, } };
4887
4888 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4889 if (cso_fb->zsbuf) {
4890 struct iris_resource *zres, *sres;
4891 iris_get_depth_stencil_resources(cso_fb->zsbuf->texture,
4892 &zres, &sres);
4893 if (zres && zres->aux.bo)
4894 clear_value = iris_resource_get_clear_color(zres, NULL, NULL);
4895 }
4896
4897 uint32_t clear_params[GENX(3DSTATE_CLEAR_PARAMS_length)];
4898 iris_pack_command(GENX(3DSTATE_CLEAR_PARAMS), clear_params, clear) {
4899 clear.DepthClearValueValid = true;
4900 clear.DepthClearValue = clear_value.f32[0];
4901 }
4902 iris_batch_emit(batch, clear_params, clear_length);
4903 }
4904
4905 if (dirty & (IRIS_DIRTY_DEPTH_BUFFER | IRIS_DIRTY_WM_DEPTH_STENCIL)) {
4906 /* Listen for buffer changes, and also write enable changes. */
4907 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
4908 pin_depth_and_stencil_buffers(batch, cso_fb->zsbuf, ice->state.cso_zsa);
4909 }
4910
4911 if (dirty & IRIS_DIRTY_POLYGON_STIPPLE) {
4912 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_PATTERN), poly) {
4913 for (int i = 0; i < 32; i++) {
4914 poly.PatternRow[i] = ice->state.poly_stipple.stipple[i];
4915 }
4916 }
4917 }
4918
4919 if (dirty & IRIS_DIRTY_LINE_STIPPLE) {
4920 struct iris_rasterizer_state *cso = ice->state.cso_rast;
4921 iris_batch_emit(batch, cso->line_stipple, sizeof(cso->line_stipple));
4922 }
4923
4924 if (dirty & IRIS_DIRTY_VF_TOPOLOGY) {
4925 iris_emit_cmd(batch, GENX(3DSTATE_VF_TOPOLOGY), topo) {
4926 topo.PrimitiveTopologyType =
4927 translate_prim_type(draw->mode, draw->vertices_per_patch);
4928 }
4929 }
4930
4931 if (dirty & IRIS_DIRTY_VERTEX_BUFFERS) {
4932 int count = util_bitcount64(ice->state.bound_vertex_buffers);
4933 int dynamic_bound = ice->state.bound_vertex_buffers;
4934
4935 if (ice->state.vs_uses_draw_params) {
4936 if (ice->draw.draw_params_offset == 0) {
4937 u_upload_data(ice->ctx.stream_uploader, 0, sizeof(ice->draw.params),
4938 4, &ice->draw.params, &ice->draw.draw_params_offset,
4939 &ice->draw.draw_params_res);
4940 }
4941 assert(ice->draw.draw_params_res);
4942
4943 struct iris_vertex_buffer_state *state =
4944 &(ice->state.genx->vertex_buffers[count]);
4945 pipe_resource_reference(&state->resource, ice->draw.draw_params_res);
4946 struct iris_resource *res = (void *) state->resource;
4947
4948 iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
4949 vb.VertexBufferIndex = count;
4950 vb.AddressModifyEnable = true;
4951 vb.BufferPitch = 0;
4952 vb.BufferSize = res->bo->size - ice->draw.draw_params_offset;
4953 vb.BufferStartingAddress =
4954 ro_bo(NULL, res->bo->gtt_offset +
4955 (int) ice->draw.draw_params_offset);
4956 vb.MOCS = mocs(res->bo);
4957 }
4958 dynamic_bound |= 1ull << count;
4959 count++;
4960 }
4961
4962 if (ice->state.vs_uses_derived_draw_params) {
4963 u_upload_data(ice->ctx.stream_uploader, 0,
4964 sizeof(ice->draw.derived_params), 4,
4965 &ice->draw.derived_params,
4966 &ice->draw.derived_draw_params_offset,
4967 &ice->draw.derived_draw_params_res);
4968
4969 struct iris_vertex_buffer_state *state =
4970 &(ice->state.genx->vertex_buffers[count]);
4971 pipe_resource_reference(&state->resource,
4972 ice->draw.derived_draw_params_res);
4973 struct iris_resource *res = (void *) ice->draw.derived_draw_params_res;
4974
4975 iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
4976 vb.VertexBufferIndex = count;
4977 vb.AddressModifyEnable = true;
4978 vb.BufferPitch = 0;
4979 vb.BufferSize =
4980 res->bo->size - ice->draw.derived_draw_params_offset;
4981 vb.BufferStartingAddress =
4982 ro_bo(NULL, res->bo->gtt_offset +
4983 (int) ice->draw.derived_draw_params_offset);
4984 vb.MOCS = mocs(res->bo);
4985 }
4986 dynamic_bound |= 1ull << count;
4987 count++;
4988 }
4989
4990 if (count) {
4991 /* The VF cache designers cut corners, and made the cache key's
4992 * <VertexBufferIndex, Memory Address> tuple only consider the bottom
4993 * 32 bits of the address. If you have two vertex buffers which get
4994 * placed exactly 4 GiB apart and use them in back-to-back draw calls,
4995 * you can get collisions (even within a single batch).
4996 *
4997 * So, we need to do a VF cache invalidate if the buffer for a VB
4998 * slot slot changes [48:32] address bits from the previous time.
4999 */
5000 unsigned flush_flags = 0;
5001
5002 uint64_t bound = dynamic_bound;
5003 while (bound) {
5004 const int i = u_bit_scan64(&bound);
5005 uint16_t high_bits = 0;
5006
5007 struct iris_resource *res =
5008 (void *) genx->vertex_buffers[i].resource;
5009 if (res) {
5010 iris_use_pinned_bo(batch, res->bo, false);
5011
5012 high_bits = res->bo->gtt_offset >> 32ull;
5013 if (high_bits != ice->state.last_vbo_high_bits[i]) {
5014 flush_flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE |
5015 PIPE_CONTROL_CS_STALL;
5016 ice->state.last_vbo_high_bits[i] = high_bits;
5017 }
5018 }
5019 }
5020
5021 if (flush_flags) {
5022 iris_emit_pipe_control_flush(batch,
5023 "workaround: VF cache 32-bit key [VB]",
5024 flush_flags);
5025 }
5026
5027 const unsigned vb_dwords = GENX(VERTEX_BUFFER_STATE_length);
5028
5029 uint32_t *map =
5030 iris_get_command_space(batch, 4 * (1 + vb_dwords * count));
5031 _iris_pack_command(batch, GENX(3DSTATE_VERTEX_BUFFERS), map, vb) {
5032 vb.DWordLength = (vb_dwords * count + 1) - 2;
5033 }
5034 map += 1;
5035
5036 bound = dynamic_bound;
5037 while (bound) {
5038 const int i = u_bit_scan64(&bound);
5039 memcpy(map, genx->vertex_buffers[i].state,
5040 sizeof(uint32_t) * vb_dwords);
5041 map += vb_dwords;
5042 }
5043 }
5044 }
5045
5046 if (dirty & IRIS_DIRTY_VERTEX_ELEMENTS) {
5047 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
5048 const unsigned entries = MAX2(cso->count, 1);
5049 if (!(ice->state.vs_needs_sgvs_element ||
5050 ice->state.vs_uses_derived_draw_params ||
5051 ice->state.vs_needs_edge_flag)) {
5052 iris_batch_emit(batch, cso->vertex_elements, sizeof(uint32_t) *
5053 (1 + entries * GENX(VERTEX_ELEMENT_STATE_length)));
5054 } else {
5055 uint32_t dynamic_ves[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
5056 const unsigned dyn_count = cso->count +
5057 ice->state.vs_needs_sgvs_element +
5058 ice->state.vs_uses_derived_draw_params;
5059
5060 iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS),
5061 &dynamic_ves, ve) {
5062 ve.DWordLength =
5063 1 + GENX(VERTEX_ELEMENT_STATE_length) * dyn_count - 2;
5064 }
5065 memcpy(&dynamic_ves[1], &cso->vertex_elements[1],
5066 (cso->count - ice->state.vs_needs_edge_flag) *
5067 GENX(VERTEX_ELEMENT_STATE_length) * sizeof(uint32_t));
5068 uint32_t *ve_pack_dest =
5069 &dynamic_ves[1 + (cso->count - ice->state.vs_needs_edge_flag) *
5070 GENX(VERTEX_ELEMENT_STATE_length)];
5071
5072 if (ice->state.vs_needs_sgvs_element) {
5073 uint32_t base_ctrl = ice->state.vs_uses_draw_params ?
5074 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
5075 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
5076 ve.Valid = true;
5077 ve.VertexBufferIndex =
5078 util_bitcount64(ice->state.bound_vertex_buffers);
5079 ve.SourceElementFormat = ISL_FORMAT_R32G32_UINT;
5080 ve.Component0Control = base_ctrl;
5081 ve.Component1Control = base_ctrl;
5082 ve.Component2Control = VFCOMP_STORE_0;
5083 ve.Component3Control = VFCOMP_STORE_0;
5084 }
5085 ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
5086 }
5087 if (ice->state.vs_uses_derived_draw_params) {
5088 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
5089 ve.Valid = true;
5090 ve.VertexBufferIndex =
5091 util_bitcount64(ice->state.bound_vertex_buffers) +
5092 ice->state.vs_uses_draw_params;
5093 ve.SourceElementFormat = ISL_FORMAT_R32G32_UINT;
5094 ve.Component0Control = VFCOMP_STORE_SRC;
5095 ve.Component1Control = VFCOMP_STORE_SRC;
5096 ve.Component2Control = VFCOMP_STORE_0;
5097 ve.Component3Control = VFCOMP_STORE_0;
5098 }
5099 ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
5100 }
5101 if (ice->state.vs_needs_edge_flag) {
5102 for (int i = 0; i < GENX(VERTEX_ELEMENT_STATE_length); i++)
5103 ve_pack_dest[i] = cso->edgeflag_ve[i];
5104 }
5105
5106 iris_batch_emit(batch, &dynamic_ves, sizeof(uint32_t) *
5107 (1 + dyn_count * GENX(VERTEX_ELEMENT_STATE_length)));
5108 }
5109
5110 if (!ice->state.vs_needs_edge_flag) {
5111 iris_batch_emit(batch, cso->vf_instancing, sizeof(uint32_t) *
5112 entries * GENX(3DSTATE_VF_INSTANCING_length));
5113 } else {
5114 assert(cso->count > 0);
5115 const unsigned edgeflag_index = cso->count - 1;
5116 uint32_t dynamic_vfi[33 * GENX(3DSTATE_VF_INSTANCING_length)];
5117 memcpy(&dynamic_vfi[0], cso->vf_instancing, edgeflag_index *
5118 GENX(3DSTATE_VF_INSTANCING_length) * sizeof(uint32_t));
5119
5120 uint32_t *vfi_pack_dest = &dynamic_vfi[0] +
5121 edgeflag_index * GENX(3DSTATE_VF_INSTANCING_length);
5122 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
5123 vi.VertexElementIndex = edgeflag_index +
5124 ice->state.vs_needs_sgvs_element +
5125 ice->state.vs_uses_derived_draw_params;
5126 }
5127 for (int i = 0; i < GENX(3DSTATE_VF_INSTANCING_length); i++)
5128 vfi_pack_dest[i] |= cso->edgeflag_vfi[i];
5129
5130 iris_batch_emit(batch, &dynamic_vfi[0], sizeof(uint32_t) *
5131 entries * GENX(3DSTATE_VF_INSTANCING_length));
5132 }
5133 }
5134
5135 if (dirty & IRIS_DIRTY_VF_SGVS) {
5136 const struct brw_vs_prog_data *vs_prog_data = (void *)
5137 ice->shaders.prog[MESA_SHADER_VERTEX]->prog_data;
5138 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
5139
5140 iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS), sgv) {
5141 if (vs_prog_data->uses_vertexid) {
5142 sgv.VertexIDEnable = true;
5143 sgv.VertexIDComponentNumber = 2;
5144 sgv.VertexIDElementOffset =
5145 cso->count - ice->state.vs_needs_edge_flag;
5146 }
5147
5148 if (vs_prog_data->uses_instanceid) {
5149 sgv.InstanceIDEnable = true;
5150 sgv.InstanceIDComponentNumber = 3;
5151 sgv.InstanceIDElementOffset =
5152 cso->count - ice->state.vs_needs_edge_flag;
5153 }
5154 }
5155 }
5156
5157 if (dirty & IRIS_DIRTY_VF) {
5158 iris_emit_cmd(batch, GENX(3DSTATE_VF), vf) {
5159 if (draw->primitive_restart) {
5160 vf.IndexedDrawCutIndexEnable = true;
5161 vf.CutIndex = draw->restart_index;
5162 }
5163 }
5164 }
5165
5166 if (dirty & IRIS_DIRTY_VF_STATISTICS) {
5167 iris_emit_cmd(batch, GENX(3DSTATE_VF_STATISTICS), vf) {
5168 vf.StatisticsEnable = true;
5169 }
5170 }
5171
5172 /* TODO: Gen8 PMA fix */
5173 }
5174
5175 static void
5176 iris_upload_render_state(struct iris_context *ice,
5177 struct iris_batch *batch,
5178 const struct pipe_draw_info *draw)
5179 {
5180 bool use_predicate = ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT;
5181
5182 /* Always pin the binder. If we're emitting new binding table pointers,
5183 * we need it. If not, we're probably inheriting old tables via the
5184 * context, and need it anyway. Since true zero-bindings cases are
5185 * practically non-existent, just pin it and avoid last_res tracking.
5186 */
5187 iris_use_pinned_bo(batch, ice->state.binder.bo, false);
5188
5189 if (!batch->contains_draw) {
5190 iris_restore_render_saved_bos(ice, batch, draw);
5191 batch->contains_draw = true;
5192 }
5193
5194 iris_upload_dirty_render_state(ice, batch, draw);
5195
5196 if (draw->index_size > 0) {
5197 unsigned offset;
5198
5199 if (draw->has_user_indices) {
5200 u_upload_data(ice->ctx.stream_uploader, 0,
5201 draw->count * draw->index_size, 4, draw->index.user,
5202 &offset, &ice->state.last_res.index_buffer);
5203 } else {
5204 struct iris_resource *res = (void *) draw->index.resource;
5205 res->bind_history |= PIPE_BIND_INDEX_BUFFER;
5206
5207 pipe_resource_reference(&ice->state.last_res.index_buffer,
5208 draw->index.resource);
5209 offset = 0;
5210 }
5211
5212 struct iris_genx_state *genx = ice->state.genx;
5213 struct iris_bo *bo = iris_resource_bo(ice->state.last_res.index_buffer);
5214
5215 uint32_t ib_packet[GENX(3DSTATE_INDEX_BUFFER_length)];
5216 iris_pack_command(GENX(3DSTATE_INDEX_BUFFER), ib_packet, ib) {
5217 ib.IndexFormat = draw->index_size >> 1;
5218 ib.MOCS = mocs(bo);
5219 ib.BufferSize = bo->size - offset;
5220 ib.BufferStartingAddress = ro_bo(NULL, bo->gtt_offset + offset);
5221 }
5222
5223 if (memcmp(genx->last_index_buffer, ib_packet, sizeof(ib_packet)) != 0) {
5224 memcpy(genx->last_index_buffer, ib_packet, sizeof(ib_packet));
5225 iris_batch_emit(batch, ib_packet, sizeof(ib_packet));
5226 iris_use_pinned_bo(batch, bo, false);
5227 }
5228
5229 /* The VF cache key only uses 32-bits, see vertex buffer comment above */
5230 uint16_t high_bits = bo->gtt_offset >> 32ull;
5231 if (high_bits != ice->state.last_index_bo_high_bits) {
5232 iris_emit_pipe_control_flush(batch,
5233 "workaround: VF cache 32-bit key [IB]",
5234 PIPE_CONTROL_VF_CACHE_INVALIDATE |
5235 PIPE_CONTROL_CS_STALL);
5236 ice->state.last_index_bo_high_bits = high_bits;
5237 }
5238 }
5239
5240 #define _3DPRIM_END_OFFSET 0x2420
5241 #define _3DPRIM_START_VERTEX 0x2430
5242 #define _3DPRIM_VERTEX_COUNT 0x2434
5243 #define _3DPRIM_INSTANCE_COUNT 0x2438
5244 #define _3DPRIM_START_INSTANCE 0x243C
5245 #define _3DPRIM_BASE_VERTEX 0x2440
5246
5247 if (draw->indirect) {
5248 if (draw->indirect->indirect_draw_count) {
5249 use_predicate = true;
5250
5251 struct iris_bo *draw_count_bo =
5252 iris_resource_bo(draw->indirect->indirect_draw_count);
5253 unsigned draw_count_offset =
5254 draw->indirect->indirect_draw_count_offset;
5255
5256 iris_emit_pipe_control_flush(batch,
5257 "ensure indirect draw buffer is flushed",
5258 PIPE_CONTROL_FLUSH_ENABLE);
5259
5260 if (ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT) {
5261 struct gen_mi_builder b;
5262 gen_mi_builder_init(&b, batch);
5263
5264 /* comparison = draw id < draw count */
5265 struct gen_mi_value comparison =
5266 gen_mi_ult(&b, gen_mi_imm(draw->drawid),
5267 gen_mi_mem32(ro_bo(draw_count_bo,
5268 draw_count_offset)));
5269
5270 /* predicate = comparison & conditional rendering predicate */
5271 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_RESULT),
5272 gen_mi_iand(&b, comparison,
5273 gen_mi_reg32(CS_GPR(15))));
5274 } else {
5275 uint32_t mi_predicate;
5276
5277 /* Upload the id of the current primitive to MI_PREDICATE_SRC1. */
5278 ice->vtbl.load_register_imm64(batch, MI_PREDICATE_SRC1,
5279 draw->drawid);
5280 /* Upload the current draw count from the draw parameters buffer
5281 * to MI_PREDICATE_SRC0.
5282 */
5283 ice->vtbl.load_register_mem32(batch, MI_PREDICATE_SRC0,
5284 draw_count_bo, draw_count_offset);
5285 /* Zero the top 32-bits of MI_PREDICATE_SRC0 */
5286 ice->vtbl.load_register_imm32(batch, MI_PREDICATE_SRC0 + 4, 0);
5287
5288 if (draw->drawid == 0) {
5289 mi_predicate = MI_PREDICATE | MI_PREDICATE_LOADOP_LOADINV |
5290 MI_PREDICATE_COMBINEOP_SET |
5291 MI_PREDICATE_COMPAREOP_SRCS_EQUAL;
5292 } else {
5293 /* While draw_index < draw_count the predicate's result will be
5294 * (draw_index == draw_count) ^ TRUE = TRUE
5295 * When draw_index == draw_count the result is
5296 * (TRUE) ^ TRUE = FALSE
5297 * After this all results will be:
5298 * (FALSE) ^ FALSE = FALSE
5299 */
5300 mi_predicate = MI_PREDICATE | MI_PREDICATE_LOADOP_LOAD |
5301 MI_PREDICATE_COMBINEOP_XOR |
5302 MI_PREDICATE_COMPAREOP_SRCS_EQUAL;
5303 }
5304 iris_batch_emit(batch, &mi_predicate, sizeof(uint32_t));
5305 }
5306 }
5307 struct iris_bo *bo = iris_resource_bo(draw->indirect->buffer);
5308 assert(bo);
5309
5310 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5311 lrm.RegisterAddress = _3DPRIM_VERTEX_COUNT;
5312 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 0);
5313 }
5314 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5315 lrm.RegisterAddress = _3DPRIM_INSTANCE_COUNT;
5316 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 4);
5317 }
5318 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5319 lrm.RegisterAddress = _3DPRIM_START_VERTEX;
5320 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 8);
5321 }
5322 if (draw->index_size) {
5323 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5324 lrm.RegisterAddress = _3DPRIM_BASE_VERTEX;
5325 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 12);
5326 }
5327 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5328 lrm.RegisterAddress = _3DPRIM_START_INSTANCE;
5329 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 16);
5330 }
5331 } else {
5332 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5333 lrm.RegisterAddress = _3DPRIM_START_INSTANCE;
5334 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 12);
5335 }
5336 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
5337 lri.RegisterOffset = _3DPRIM_BASE_VERTEX;
5338 lri.DataDWord = 0;
5339 }
5340 }
5341 } else if (draw->count_from_stream_output) {
5342 struct iris_stream_output_target *so =
5343 (void *) draw->count_from_stream_output;
5344
5345 /* XXX: Replace with actual cache tracking */
5346 iris_emit_pipe_control_flush(batch,
5347 "draw count from stream output stall",
5348 PIPE_CONTROL_CS_STALL);
5349
5350 struct gen_mi_builder b;
5351 gen_mi_builder_init(&b, batch);
5352
5353 struct iris_address addr =
5354 ro_bo(iris_resource_bo(so->offset.res), so->offset.offset);
5355 struct gen_mi_value offset =
5356 gen_mi_iadd_imm(&b, gen_mi_mem32(addr), -so->base.buffer_offset);
5357
5358 gen_mi_store(&b, gen_mi_reg32(_3DPRIM_VERTEX_COUNT),
5359 gen_mi_udiv32_imm(&b, offset, so->stride));
5360
5361 _iris_emit_lri(batch, _3DPRIM_START_VERTEX, 0);
5362 _iris_emit_lri(batch, _3DPRIM_BASE_VERTEX, 0);
5363 _iris_emit_lri(batch, _3DPRIM_START_INSTANCE, 0);
5364 _iris_emit_lri(batch, _3DPRIM_INSTANCE_COUNT, draw->instance_count);
5365 }
5366
5367 iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
5368 prim.VertexAccessType = draw->index_size > 0 ? RANDOM : SEQUENTIAL;
5369 prim.PredicateEnable = use_predicate;
5370
5371 if (draw->indirect || draw->count_from_stream_output) {
5372 prim.IndirectParameterEnable = true;
5373 } else {
5374 prim.StartInstanceLocation = draw->start_instance;
5375 prim.InstanceCount = draw->instance_count;
5376 prim.VertexCountPerInstance = draw->count;
5377
5378 prim.StartVertexLocation = draw->start;
5379
5380 if (draw->index_size) {
5381 prim.BaseVertexLocation += draw->index_bias;
5382 } else {
5383 prim.StartVertexLocation += draw->index_bias;
5384 }
5385 }
5386 }
5387 }
5388
5389 static void
5390 iris_upload_compute_state(struct iris_context *ice,
5391 struct iris_batch *batch,
5392 const struct pipe_grid_info *grid)
5393 {
5394 const uint64_t dirty = ice->state.dirty;
5395 struct iris_screen *screen = batch->screen;
5396 const struct gen_device_info *devinfo = &screen->devinfo;
5397 struct iris_binder *binder = &ice->state.binder;
5398 struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_COMPUTE];
5399 struct iris_compiled_shader *shader =
5400 ice->shaders.prog[MESA_SHADER_COMPUTE];
5401 struct brw_stage_prog_data *prog_data = shader->prog_data;
5402 struct brw_cs_prog_data *cs_prog_data = (void *) prog_data;
5403
5404 /* Always pin the binder. If we're emitting new binding table pointers,
5405 * we need it. If not, we're probably inheriting old tables via the
5406 * context, and need it anyway. Since true zero-bindings cases are
5407 * practically non-existent, just pin it and avoid last_res tracking.
5408 */
5409 iris_use_pinned_bo(batch, ice->state.binder.bo, false);
5410
5411 if ((dirty & IRIS_DIRTY_CONSTANTS_CS) && shs->sysvals_need_upload)
5412 upload_sysvals(ice, MESA_SHADER_COMPUTE);
5413
5414 if (dirty & IRIS_DIRTY_BINDINGS_CS)
5415 iris_populate_binding_table(ice, batch, MESA_SHADER_COMPUTE, false);
5416
5417 if (dirty & IRIS_DIRTY_SAMPLER_STATES_CS)
5418 iris_upload_sampler_states(ice, MESA_SHADER_COMPUTE);
5419
5420 iris_use_optional_res(batch, shs->sampler_table.res, false);
5421 iris_use_pinned_bo(batch, iris_resource_bo(shader->assembly.res), false);
5422
5423 if (ice->state.need_border_colors)
5424 iris_use_pinned_bo(batch, ice->state.border_color_pool.bo, false);
5425
5426 if (dirty & IRIS_DIRTY_CS) {
5427 /* The MEDIA_VFE_STATE documentation for Gen8+ says:
5428 *
5429 * "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
5430 * the only bits that are changed are scoreboard related: Scoreboard
5431 * Enable, Scoreboard Type, Scoreboard Mask, Scoreboard Delta. For
5432 * these scoreboard related states, a MEDIA_STATE_FLUSH is
5433 * sufficient."
5434 */
5435 iris_emit_pipe_control_flush(batch,
5436 "workaround: stall before MEDIA_VFE_STATE",
5437 PIPE_CONTROL_CS_STALL);
5438
5439 iris_emit_cmd(batch, GENX(MEDIA_VFE_STATE), vfe) {
5440 if (prog_data->total_scratch) {
5441 struct iris_bo *bo =
5442 iris_get_scratch_space(ice, prog_data->total_scratch,
5443 MESA_SHADER_COMPUTE);
5444 vfe.PerThreadScratchSpace = ffs(prog_data->total_scratch) - 11;
5445 vfe.ScratchSpaceBasePointer = rw_bo(bo, 0);
5446 }
5447
5448 vfe.MaximumNumberofThreads =
5449 devinfo->max_cs_threads * screen->subslice_total - 1;
5450 #if GEN_GEN < 11
5451 vfe.ResetGatewayTimer =
5452 Resettingrelativetimerandlatchingtheglobaltimestamp;
5453 #endif
5454 #if GEN_GEN == 8
5455 vfe.BypassGatewayControl = true;
5456 #endif
5457 vfe.NumberofURBEntries = 2;
5458 vfe.URBEntryAllocationSize = 2;
5459
5460 vfe.CURBEAllocationSize =
5461 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
5462 cs_prog_data->push.cross_thread.regs, 2);
5463 }
5464 }
5465
5466 /* TODO: Combine subgroup-id with cbuf0 so we can push regular uniforms */
5467 if (dirty & IRIS_DIRTY_CS) {
5468 uint32_t curbe_data_offset = 0;
5469 assert(cs_prog_data->push.cross_thread.dwords == 0 &&
5470 cs_prog_data->push.per_thread.dwords == 1 &&
5471 cs_prog_data->base.param[0] == BRW_PARAM_BUILTIN_SUBGROUP_ID);
5472 uint32_t *curbe_data_map =
5473 stream_state(batch, ice->state.dynamic_uploader,
5474 &ice->state.last_res.cs_thread_ids,
5475 ALIGN(cs_prog_data->push.total.size, 64), 64,
5476 &curbe_data_offset);
5477 assert(curbe_data_map);
5478 memset(curbe_data_map, 0x5a, ALIGN(cs_prog_data->push.total.size, 64));
5479 iris_fill_cs_push_const_buffer(cs_prog_data, curbe_data_map);
5480
5481 iris_emit_cmd(batch, GENX(MEDIA_CURBE_LOAD), curbe) {
5482 curbe.CURBETotalDataLength =
5483 ALIGN(cs_prog_data->push.total.size, 64);
5484 curbe.CURBEDataStartAddress = curbe_data_offset;
5485 }
5486 }
5487
5488 if (dirty & (IRIS_DIRTY_SAMPLER_STATES_CS |
5489 IRIS_DIRTY_BINDINGS_CS |
5490 IRIS_DIRTY_CONSTANTS_CS |
5491 IRIS_DIRTY_CS)) {
5492 uint32_t desc[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
5493
5494 iris_pack_state(GENX(INTERFACE_DESCRIPTOR_DATA), desc, idd) {
5495 idd.SamplerStatePointer = shs->sampler_table.offset;
5496 idd.BindingTablePointer = binder->bt_offset[MESA_SHADER_COMPUTE];
5497 }
5498
5499 for (int i = 0; i < GENX(INTERFACE_DESCRIPTOR_DATA_length); i++)
5500 desc[i] |= ((uint32_t *) shader->derived_data)[i];
5501
5502 iris_emit_cmd(batch, GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), load) {
5503 load.InterfaceDescriptorTotalLength =
5504 GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
5505 load.InterfaceDescriptorDataStartAddress =
5506 emit_state(batch, ice->state.dynamic_uploader,
5507 &ice->state.last_res.cs_desc, desc, sizeof(desc), 64);
5508 }
5509 }
5510
5511 uint32_t group_size = grid->block[0] * grid->block[1] * grid->block[2];
5512 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
5513 uint32_t right_mask;
5514
5515 if (remainder > 0)
5516 right_mask = ~0u >> (32 - remainder);
5517 else
5518 right_mask = ~0u >> (32 - cs_prog_data->simd_size);
5519
5520 #define GPGPU_DISPATCHDIMX 0x2500
5521 #define GPGPU_DISPATCHDIMY 0x2504
5522 #define GPGPU_DISPATCHDIMZ 0x2508
5523
5524 if (grid->indirect) {
5525 struct iris_state_ref *grid_size = &ice->state.grid_size;
5526 struct iris_bo *bo = iris_resource_bo(grid_size->res);
5527 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5528 lrm.RegisterAddress = GPGPU_DISPATCHDIMX;
5529 lrm.MemoryAddress = ro_bo(bo, grid_size->offset + 0);
5530 }
5531 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5532 lrm.RegisterAddress = GPGPU_DISPATCHDIMY;
5533 lrm.MemoryAddress = ro_bo(bo, grid_size->offset + 4);
5534 }
5535 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5536 lrm.RegisterAddress = GPGPU_DISPATCHDIMZ;
5537 lrm.MemoryAddress = ro_bo(bo, grid_size->offset + 8);
5538 }
5539 }
5540
5541 iris_emit_cmd(batch, GENX(GPGPU_WALKER), ggw) {
5542 ggw.IndirectParameterEnable = grid->indirect != NULL;
5543 ggw.SIMDSize = cs_prog_data->simd_size / 16;
5544 ggw.ThreadDepthCounterMaximum = 0;
5545 ggw.ThreadHeightCounterMaximum = 0;
5546 ggw.ThreadWidthCounterMaximum = cs_prog_data->threads - 1;
5547 ggw.ThreadGroupIDXDimension = grid->grid[0];
5548 ggw.ThreadGroupIDYDimension = grid->grid[1];
5549 ggw.ThreadGroupIDZDimension = grid->grid[2];
5550 ggw.RightExecutionMask = right_mask;
5551 ggw.BottomExecutionMask = 0xffffffff;
5552 }
5553
5554 iris_emit_cmd(batch, GENX(MEDIA_STATE_FLUSH), msf);
5555
5556 if (!batch->contains_draw) {
5557 iris_restore_compute_saved_bos(ice, batch, grid);
5558 batch->contains_draw = true;
5559 }
5560 }
5561
5562 /**
5563 * State module teardown.
5564 */
5565 static void
5566 iris_destroy_state(struct iris_context *ice)
5567 {
5568 struct iris_genx_state *genx = ice->state.genx;
5569
5570 pipe_resource_reference(&ice->draw.draw_params_res, NULL);
5571 pipe_resource_reference(&ice->draw.derived_draw_params_res, NULL);
5572
5573 uint64_t bound_vbs = ice->state.bound_vertex_buffers;
5574 while (bound_vbs) {
5575 const int i = u_bit_scan64(&bound_vbs);
5576 pipe_resource_reference(&genx->vertex_buffers[i].resource, NULL);
5577 }
5578 free(ice->state.genx);
5579
5580 for (int i = 0; i < 4; i++) {
5581 pipe_so_target_reference(&ice->state.so_target[i], NULL);
5582 }
5583
5584 for (unsigned i = 0; i < ice->state.framebuffer.nr_cbufs; i++) {
5585 pipe_surface_reference(&ice->state.framebuffer.cbufs[i], NULL);
5586 }
5587 pipe_surface_reference(&ice->state.framebuffer.zsbuf, NULL);
5588
5589 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
5590 struct iris_shader_state *shs = &ice->state.shaders[stage];
5591 pipe_resource_reference(&shs->sampler_table.res, NULL);
5592 for (int i = 0; i < PIPE_MAX_CONSTANT_BUFFERS; i++) {
5593 pipe_resource_reference(&shs->constbuf[i].buffer, NULL);
5594 pipe_resource_reference(&shs->constbuf_surf_state[i].res, NULL);
5595 }
5596 for (int i = 0; i < PIPE_MAX_SHADER_IMAGES; i++) {
5597 pipe_resource_reference(&shs->image[i].base.resource, NULL);
5598 pipe_resource_reference(&shs->image[i].surface_state.res, NULL);
5599 }
5600 for (int i = 0; i < PIPE_MAX_SHADER_BUFFERS; i++) {
5601 pipe_resource_reference(&shs->ssbo[i].buffer, NULL);
5602 pipe_resource_reference(&shs->ssbo_surf_state[i].res, NULL);
5603 }
5604 for (int i = 0; i < IRIS_MAX_TEXTURE_SAMPLERS; i++) {
5605 pipe_sampler_view_reference((struct pipe_sampler_view **)
5606 &shs->textures[i], NULL);
5607 }
5608 }
5609
5610 pipe_resource_reference(&ice->state.grid_size.res, NULL);
5611 pipe_resource_reference(&ice->state.grid_surf_state.res, NULL);
5612
5613 pipe_resource_reference(&ice->state.null_fb.res, NULL);
5614 pipe_resource_reference(&ice->state.unbound_tex.res, NULL);
5615
5616 pipe_resource_reference(&ice->state.last_res.cc_vp, NULL);
5617 pipe_resource_reference(&ice->state.last_res.sf_cl_vp, NULL);
5618 pipe_resource_reference(&ice->state.last_res.color_calc, NULL);
5619 pipe_resource_reference(&ice->state.last_res.scissor, NULL);
5620 pipe_resource_reference(&ice->state.last_res.blend, NULL);
5621 pipe_resource_reference(&ice->state.last_res.index_buffer, NULL);
5622 pipe_resource_reference(&ice->state.last_res.cs_thread_ids, NULL);
5623 pipe_resource_reference(&ice->state.last_res.cs_desc, NULL);
5624 }
5625
5626 /* ------------------------------------------------------------------- */
5627
5628 static void
5629 iris_rebind_buffer(struct iris_context *ice,
5630 struct iris_resource *res,
5631 uint64_t old_address)
5632 {
5633 struct pipe_context *ctx = &ice->ctx;
5634 struct iris_screen *screen = (void *) ctx->screen;
5635 struct iris_genx_state *genx = ice->state.genx;
5636
5637 assert(res->base.target == PIPE_BUFFER);
5638
5639 /* Buffers can't be framebuffer attachments, nor display related,
5640 * and we don't have upstream Clover support.
5641 */
5642 assert(!(res->bind_history & (PIPE_BIND_DEPTH_STENCIL |
5643 PIPE_BIND_RENDER_TARGET |
5644 PIPE_BIND_BLENDABLE |
5645 PIPE_BIND_DISPLAY_TARGET |
5646 PIPE_BIND_CURSOR |
5647 PIPE_BIND_COMPUTE_RESOURCE |
5648 PIPE_BIND_GLOBAL)));
5649
5650 if (res->bind_history & PIPE_BIND_VERTEX_BUFFER) {
5651 uint64_t bound_vbs = ice->state.bound_vertex_buffers;
5652 while (bound_vbs) {
5653 const int i = u_bit_scan64(&bound_vbs);
5654 struct iris_vertex_buffer_state *state = &genx->vertex_buffers[i];
5655
5656 /* Update the CPU struct */
5657 STATIC_ASSERT(GENX(VERTEX_BUFFER_STATE_BufferStartingAddress_start) == 32);
5658 STATIC_ASSERT(GENX(VERTEX_BUFFER_STATE_BufferStartingAddress_bits) == 64);
5659 uint64_t *addr = (uint64_t *) &state->state[1];
5660
5661 if (*addr == old_address) {
5662 *addr = res->bo->gtt_offset;
5663 ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
5664 }
5665 }
5666 }
5667
5668 /* We don't need to handle PIPE_BIND_INDEX_BUFFER here: we re-emit
5669 * the 3DSTATE_INDEX_BUFFER packet whenever the address changes.
5670 *
5671 * There is also no need to handle these:
5672 * - PIPE_BIND_COMMAND_ARGS_BUFFER (emitted for every indirect draw)
5673 * - PIPE_BIND_QUERY_BUFFER (no persistent state references)
5674 */
5675
5676 if (res->bind_history & PIPE_BIND_STREAM_OUTPUT) {
5677 /* XXX: be careful about resetting vs appending... */
5678 assert(false);
5679 }
5680
5681 for (int s = MESA_SHADER_VERTEX; s < MESA_SHADER_STAGES; s++) {
5682 struct iris_shader_state *shs = &ice->state.shaders[s];
5683 enum pipe_shader_type p_stage = stage_to_pipe(s);
5684
5685 if (res->bind_history & PIPE_BIND_CONSTANT_BUFFER) {
5686 /* Skip constant buffer 0, it's for regular uniforms, not UBOs */
5687 uint32_t bound_cbufs = shs->bound_cbufs & ~1u;
5688 while (bound_cbufs) {
5689 const int i = u_bit_scan(&bound_cbufs);
5690 struct pipe_shader_buffer *cbuf = &shs->constbuf[i];
5691 struct iris_state_ref *surf_state = &shs->constbuf_surf_state[i];
5692
5693 if (res->bo == iris_resource_bo(cbuf->buffer)) {
5694 iris_upload_ubo_ssbo_surf_state(ice, cbuf, surf_state, false);
5695 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS << s;
5696 }
5697 }
5698 }
5699
5700 if (res->bind_history & PIPE_BIND_SHADER_BUFFER) {
5701 uint32_t bound_ssbos = shs->bound_ssbos;
5702 while (bound_ssbos) {
5703 const int i = u_bit_scan(&bound_ssbos);
5704 struct pipe_shader_buffer *ssbo = &shs->ssbo[i];
5705
5706 if (res->bo == iris_resource_bo(ssbo->buffer)) {
5707 struct pipe_shader_buffer buf = {
5708 .buffer = &res->base,
5709 .buffer_offset = ssbo->buffer_offset,
5710 .buffer_size = ssbo->buffer_size,
5711 };
5712 iris_set_shader_buffers(ctx, p_stage, i, 1, &buf,
5713 (shs->writable_ssbos >> i) & 1);
5714 }
5715 }
5716 }
5717
5718 if (res->bind_history & PIPE_BIND_SAMPLER_VIEW) {
5719 uint32_t bound_sampler_views = shs->bound_sampler_views;
5720 while (bound_sampler_views) {
5721 const int i = u_bit_scan(&bound_sampler_views);
5722 struct iris_sampler_view *isv = shs->textures[i];
5723
5724 if (res->bo == iris_resource_bo(isv->base.texture)) {
5725 void *map = alloc_surface_states(ice->state.surface_uploader,
5726 &isv->surface_state,
5727 isv->res->aux.sampler_usages);
5728 assert(map);
5729 fill_buffer_surface_state(&screen->isl_dev, isv->res, map,
5730 isv->view.format, isv->view.swizzle,
5731 isv->base.u.buf.offset,
5732 isv->base.u.buf.size);
5733 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << s;
5734 }
5735 }
5736 }
5737
5738 if (res->bind_history & PIPE_BIND_SHADER_IMAGE) {
5739 uint32_t bound_image_views = shs->bound_image_views;
5740 while (bound_image_views) {
5741 const int i = u_bit_scan(&bound_image_views);
5742 struct iris_image_view *iv = &shs->image[i];
5743
5744 if (res->bo == iris_resource_bo(iv->base.resource)) {
5745 iris_set_shader_images(ctx, p_stage, i, 1, &iv->base);
5746 }
5747 }
5748 }
5749 }
5750 }
5751
5752 /* ------------------------------------------------------------------- */
5753
5754 static void
5755 iris_load_register_reg32(struct iris_batch *batch, uint32_t dst,
5756 uint32_t src)
5757 {
5758 _iris_emit_lrr(batch, dst, src);
5759 }
5760
5761 static void
5762 iris_load_register_reg64(struct iris_batch *batch, uint32_t dst,
5763 uint32_t src)
5764 {
5765 _iris_emit_lrr(batch, dst, src);
5766 _iris_emit_lrr(batch, dst + 4, src + 4);
5767 }
5768
5769 static void
5770 iris_load_register_imm32(struct iris_batch *batch, uint32_t reg,
5771 uint32_t val)
5772 {
5773 _iris_emit_lri(batch, reg, val);
5774 }
5775
5776 static void
5777 iris_load_register_imm64(struct iris_batch *batch, uint32_t reg,
5778 uint64_t val)
5779 {
5780 _iris_emit_lri(batch, reg + 0, val & 0xffffffff);
5781 _iris_emit_lri(batch, reg + 4, val >> 32);
5782 }
5783
5784 /**
5785 * Emit MI_LOAD_REGISTER_MEM to load a 32-bit MMIO register from a buffer.
5786 */
5787 static void
5788 iris_load_register_mem32(struct iris_batch *batch, uint32_t reg,
5789 struct iris_bo *bo, uint32_t offset)
5790 {
5791 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
5792 lrm.RegisterAddress = reg;
5793 lrm.MemoryAddress = ro_bo(bo, offset);
5794 }
5795 }
5796
5797 /**
5798 * Load a 64-bit value from a buffer into a MMIO register via
5799 * two MI_LOAD_REGISTER_MEM commands.
5800 */
5801 static void
5802 iris_load_register_mem64(struct iris_batch *batch, uint32_t reg,
5803 struct iris_bo *bo, uint32_t offset)
5804 {
5805 iris_load_register_mem32(batch, reg + 0, bo, offset + 0);
5806 iris_load_register_mem32(batch, reg + 4, bo, offset + 4);
5807 }
5808
5809 static void
5810 iris_store_register_mem32(struct iris_batch *batch, uint32_t reg,
5811 struct iris_bo *bo, uint32_t offset,
5812 bool predicated)
5813 {
5814 iris_emit_cmd(batch, GENX(MI_STORE_REGISTER_MEM), srm) {
5815 srm.RegisterAddress = reg;
5816 srm.MemoryAddress = rw_bo(bo, offset);
5817 srm.PredicateEnable = predicated;
5818 }
5819 }
5820
5821 static void
5822 iris_store_register_mem64(struct iris_batch *batch, uint32_t reg,
5823 struct iris_bo *bo, uint32_t offset,
5824 bool predicated)
5825 {
5826 iris_store_register_mem32(batch, reg + 0, bo, offset + 0, predicated);
5827 iris_store_register_mem32(batch, reg + 4, bo, offset + 4, predicated);
5828 }
5829
5830 static void
5831 iris_store_data_imm32(struct iris_batch *batch,
5832 struct iris_bo *bo, uint32_t offset,
5833 uint32_t imm)
5834 {
5835 iris_emit_cmd(batch, GENX(MI_STORE_DATA_IMM), sdi) {
5836 sdi.Address = rw_bo(bo, offset);
5837 sdi.ImmediateData = imm;
5838 }
5839 }
5840
5841 static void
5842 iris_store_data_imm64(struct iris_batch *batch,
5843 struct iris_bo *bo, uint32_t offset,
5844 uint64_t imm)
5845 {
5846 /* Can't use iris_emit_cmd because MI_STORE_DATA_IMM has a length of
5847 * 2 in genxml but it's actually variable length and we need 5 DWords.
5848 */
5849 void *map = iris_get_command_space(batch, 4 * 5);
5850 _iris_pack_command(batch, GENX(MI_STORE_DATA_IMM), map, sdi) {
5851 sdi.DWordLength = 5 - 2;
5852 sdi.Address = rw_bo(bo, offset);
5853 sdi.ImmediateData = imm;
5854 }
5855 }
5856
5857 static void
5858 iris_copy_mem_mem(struct iris_batch *batch,
5859 struct iris_bo *dst_bo, uint32_t dst_offset,
5860 struct iris_bo *src_bo, uint32_t src_offset,
5861 unsigned bytes)
5862 {
5863 /* MI_COPY_MEM_MEM operates on DWords. */
5864 assert(bytes % 4 == 0);
5865 assert(dst_offset % 4 == 0);
5866 assert(src_offset % 4 == 0);
5867
5868 for (unsigned i = 0; i < bytes; i += 4) {
5869 iris_emit_cmd(batch, GENX(MI_COPY_MEM_MEM), cp) {
5870 cp.DestinationMemoryAddress = rw_bo(dst_bo, dst_offset + i);
5871 cp.SourceMemoryAddress = ro_bo(src_bo, src_offset + i);
5872 }
5873 }
5874 }
5875
5876 /* ------------------------------------------------------------------- */
5877
5878 static unsigned
5879 flags_to_post_sync_op(uint32_t flags)
5880 {
5881 if (flags & PIPE_CONTROL_WRITE_IMMEDIATE)
5882 return WriteImmediateData;
5883
5884 if (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT)
5885 return WritePSDepthCount;
5886
5887 if (flags & PIPE_CONTROL_WRITE_TIMESTAMP)
5888 return WriteTimestamp;
5889
5890 return 0;
5891 }
5892
5893 /**
5894 * Do the given flags have a Post Sync or LRI Post Sync operation?
5895 */
5896 static enum pipe_control_flags
5897 get_post_sync_flags(enum pipe_control_flags flags)
5898 {
5899 flags &= PIPE_CONTROL_WRITE_IMMEDIATE |
5900 PIPE_CONTROL_WRITE_DEPTH_COUNT |
5901 PIPE_CONTROL_WRITE_TIMESTAMP |
5902 PIPE_CONTROL_LRI_POST_SYNC_OP;
5903
5904 /* Only one "Post Sync Op" is allowed, and it's mutually exclusive with
5905 * "LRI Post Sync Operation". So more than one bit set would be illegal.
5906 */
5907 assert(util_bitcount(flags) <= 1);
5908
5909 return flags;
5910 }
5911
5912 #define IS_COMPUTE_PIPELINE(batch) (batch->name == IRIS_BATCH_COMPUTE)
5913
5914 /**
5915 * Emit a series of PIPE_CONTROL commands, taking into account any
5916 * workarounds necessary to actually accomplish the caller's request.
5917 *
5918 * Unless otherwise noted, spec quotations in this function come from:
5919 *
5920 * Synchronization of the 3D Pipeline > PIPE_CONTROL Command > Programming
5921 * Restrictions for PIPE_CONTROL.
5922 *
5923 * You should not use this function directly. Use the helpers in
5924 * iris_pipe_control.c instead, which may split the pipe control further.
5925 */
5926 static void
5927 iris_emit_raw_pipe_control(struct iris_batch *batch,
5928 const char *reason,
5929 uint32_t flags,
5930 struct iris_bo *bo,
5931 uint32_t offset,
5932 uint64_t imm)
5933 {
5934 UNUSED const struct gen_device_info *devinfo = &batch->screen->devinfo;
5935 enum pipe_control_flags post_sync_flags = get_post_sync_flags(flags);
5936 enum pipe_control_flags non_lri_post_sync_flags =
5937 post_sync_flags & ~PIPE_CONTROL_LRI_POST_SYNC_OP;
5938
5939 /* Recursive PIPE_CONTROL workarounds --------------------------------
5940 * (http://knowyourmeme.com/memes/xzibit-yo-dawg)
5941 *
5942 * We do these first because we want to look at the original operation,
5943 * rather than any workarounds we set.
5944 */
5945 if (GEN_GEN == 9 && (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE)) {
5946 /* The PIPE_CONTROL "VF Cache Invalidation Enable" bit description
5947 * lists several workarounds:
5948 *
5949 * "Project: SKL, KBL, BXT
5950 *
5951 * If the VF Cache Invalidation Enable is set to a 1 in a
5952 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields
5953 * sets to 0, with the VF Cache Invalidation Enable set to 0
5954 * needs to be sent prior to the PIPE_CONTROL with VF Cache
5955 * Invalidation Enable set to a 1."
5956 */
5957 iris_emit_raw_pipe_control(batch,
5958 "workaround: recursive VF cache invalidate",
5959 0, NULL, 0, 0);
5960 }
5961
5962 if (GEN_GEN == 9 && IS_COMPUTE_PIPELINE(batch) && post_sync_flags) {
5963 /* Project: SKL / Argument: LRI Post Sync Operation [23]
5964 *
5965 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
5966 * programmed prior to programming a PIPECONTROL command with "LRI
5967 * Post Sync Operation" in GPGPU mode of operation (i.e when
5968 * PIPELINE_SELECT command is set to GPGPU mode of operation)."
5969 *
5970 * The same text exists a few rows below for Post Sync Op.
5971 */
5972 iris_emit_raw_pipe_control(batch,
5973 "workaround: CS stall before gpgpu post-sync",
5974 PIPE_CONTROL_CS_STALL, bo, offset, imm);
5975 }
5976
5977 if (GEN_GEN == 10 && (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH)) {
5978 /* Cannonlake:
5979 * "Before sending a PIPE_CONTROL command with bit 12 set, SW must issue
5980 * another PIPE_CONTROL with Render Target Cache Flush Enable (bit 12)
5981 * = 0 and Pipe Control Flush Enable (bit 7) = 1"
5982 */
5983 iris_emit_raw_pipe_control(batch,
5984 "workaround: PC flush before RT flush",
5985 PIPE_CONTROL_FLUSH_ENABLE, bo, offset, imm);
5986 }
5987
5988 /* "Flush Types" workarounds ---------------------------------------------
5989 * We do these now because they may add post-sync operations or CS stalls.
5990 */
5991
5992 if (GEN_GEN < 11 && flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) {
5993 /* Project: BDW, SKL+ (stopping at CNL) / Argument: VF Invalidate
5994 *
5995 * "'Post Sync Operation' must be enabled to 'Write Immediate Data' or
5996 * 'Write PS Depth Count' or 'Write Timestamp'."
5997 */
5998 if (!bo) {
5999 flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
6000 post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
6001 non_lri_post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
6002 bo = batch->screen->workaround_bo;
6003 }
6004 }
6005
6006 /* #1130 from Gen10 workarounds page:
6007 *
6008 * "Enable Depth Stall on every Post Sync Op if Render target Cache
6009 * Flush is not enabled in same PIPE CONTROL and Enable Pixel score
6010 * board stall if Render target cache flush is enabled."
6011 *
6012 * Applicable to CNL B0 and C0 steppings only.
6013 *
6014 * The wording here is unclear, and this workaround doesn't look anything
6015 * like the internal bug report recommendations, but leave it be for now...
6016 */
6017 if (GEN_GEN == 10) {
6018 if (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH) {
6019 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
6020 } else if (flags & non_lri_post_sync_flags) {
6021 flags |= PIPE_CONTROL_DEPTH_STALL;
6022 }
6023 }
6024
6025 if (flags & PIPE_CONTROL_DEPTH_STALL) {
6026 /* From the PIPE_CONTROL instruction table, bit 13 (Depth Stall Enable):
6027 *
6028 * "This bit must be DISABLED for operations other than writing
6029 * PS_DEPTH_COUNT."
6030 *
6031 * This seems like nonsense. An Ivybridge workaround requires us to
6032 * emit a PIPE_CONTROL with a depth stall and write immediate post-sync
6033 * operation. Gen8+ requires us to emit depth stalls and depth cache
6034 * flushes together. So, it's hard to imagine this means anything other
6035 * than "we originally intended this to be used for PS_DEPTH_COUNT".
6036 *
6037 * We ignore the supposed restriction and do nothing.
6038 */
6039 }
6040
6041 if (flags & (PIPE_CONTROL_RENDER_TARGET_FLUSH |
6042 PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
6043 /* From the PIPE_CONTROL instruction table, bit 12 and bit 1:
6044 *
6045 * "This bit must be DISABLED for End-of-pipe (Read) fences,
6046 * PS_DEPTH_COUNT or TIMESTAMP queries."
6047 *
6048 * TODO: Implement end-of-pipe checking.
6049 */
6050 assert(!(post_sync_flags & (PIPE_CONTROL_WRITE_DEPTH_COUNT |
6051 PIPE_CONTROL_WRITE_TIMESTAMP)));
6052 }
6053
6054 if (GEN_GEN < 11 && (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
6055 /* From the PIPE_CONTROL instruction table, bit 1:
6056 *
6057 * "This bit is ignored if Depth Stall Enable is set.
6058 * Further, the render cache is not flushed even if Write Cache
6059 * Flush Enable bit is set."
6060 *
6061 * We assert that the caller doesn't do this combination, to try and
6062 * prevent mistakes. It shouldn't hurt the GPU, though.
6063 *
6064 * We skip this check on Gen11+ as the "Stall at Pixel Scoreboard"
6065 * and "Render Target Flush" combo is explicitly required for BTI
6066 * update workarounds.
6067 */
6068 assert(!(flags & (PIPE_CONTROL_DEPTH_STALL |
6069 PIPE_CONTROL_RENDER_TARGET_FLUSH)));
6070 }
6071
6072 /* PIPE_CONTROL page workarounds ------------------------------------- */
6073
6074 if (GEN_GEN <= 8 && (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE)) {
6075 /* From the PIPE_CONTROL page itself:
6076 *
6077 * "IVB, HSW, BDW
6078 * Restriction: Pipe_control with CS-stall bit set must be issued
6079 * before a pipe-control command that has the State Cache
6080 * Invalidate bit set."
6081 */
6082 flags |= PIPE_CONTROL_CS_STALL;
6083 }
6084
6085 if (flags & PIPE_CONTROL_FLUSH_LLC) {
6086 /* From the PIPE_CONTROL instruction table, bit 26 (Flush LLC):
6087 *
6088 * "Project: ALL
6089 * SW must always program Post-Sync Operation to "Write Immediate
6090 * Data" when Flush LLC is set."
6091 *
6092 * For now, we just require the caller to do it.
6093 */
6094 assert(flags & PIPE_CONTROL_WRITE_IMMEDIATE);
6095 }
6096
6097 /* "Post-Sync Operation" workarounds -------------------------------- */
6098
6099 /* Project: All / Argument: Global Snapshot Count Reset [19]
6100 *
6101 * "This bit must not be exercised on any product.
6102 * Requires stall bit ([20] of DW1) set."
6103 *
6104 * We don't use this, so we just assert that it isn't used. The
6105 * PIPE_CONTROL instruction page indicates that they intended this
6106 * as a debug feature and don't think it is useful in production,
6107 * but it may actually be usable, should we ever want to.
6108 */
6109 assert((flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) == 0);
6110
6111 if (flags & (PIPE_CONTROL_MEDIA_STATE_CLEAR |
6112 PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE)) {
6113 /* Project: All / Arguments:
6114 *
6115 * - Generic Media State Clear [16]
6116 * - Indirect State Pointers Disable [16]
6117 *
6118 * "Requires stall bit ([20] of DW1) set."
6119 *
6120 * Also, the PIPE_CONTROL instruction table, bit 16 (Generic Media
6121 * State Clear) says:
6122 *
6123 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
6124 * programmed prior to programming a PIPECONTROL command with "Media
6125 * State Clear" set in GPGPU mode of operation"
6126 *
6127 * This is a subset of the earlier rule, so there's nothing to do.
6128 */
6129 flags |= PIPE_CONTROL_CS_STALL;
6130 }
6131
6132 if (flags & PIPE_CONTROL_STORE_DATA_INDEX) {
6133 /* Project: All / Argument: Store Data Index
6134 *
6135 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
6136 * than '0'."
6137 *
6138 * For now, we just assert that the caller does this. We might want to
6139 * automatically add a write to the workaround BO...
6140 */
6141 assert(non_lri_post_sync_flags != 0);
6142 }
6143
6144 if (flags & PIPE_CONTROL_SYNC_GFDT) {
6145 /* Project: All / Argument: Sync GFDT
6146 *
6147 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
6148 * than '0' or 0x2520[13] must be set."
6149 *
6150 * For now, we just assert that the caller does this.
6151 */
6152 assert(non_lri_post_sync_flags != 0);
6153 }
6154
6155 if (flags & PIPE_CONTROL_TLB_INVALIDATE) {
6156 /* Project: IVB+ / Argument: TLB inv
6157 *
6158 * "Requires stall bit ([20] of DW1) set."
6159 *
6160 * Also, from the PIPE_CONTROL instruction table:
6161 *
6162 * "Project: SKL+
6163 * Post Sync Operation or CS stall must be set to ensure a TLB
6164 * invalidation occurs. Otherwise no cycle will occur to the TLB
6165 * cache to invalidate."
6166 *
6167 * This is not a subset of the earlier rule, so there's nothing to do.
6168 */
6169 flags |= PIPE_CONTROL_CS_STALL;
6170 }
6171
6172 if (GEN_GEN == 9 && devinfo->gt == 4) {
6173 /* TODO: The big Skylake GT4 post sync op workaround */
6174 }
6175
6176 /* "GPGPU specific workarounds" (both post-sync and flush) ------------ */
6177
6178 if (IS_COMPUTE_PIPELINE(batch)) {
6179 if (GEN_GEN >= 9 && (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE)) {
6180 /* Project: SKL+ / Argument: Tex Invalidate
6181 * "Requires stall bit ([20] of DW) set for all GPGPU Workloads."
6182 */
6183 flags |= PIPE_CONTROL_CS_STALL;
6184 }
6185
6186 if (GEN_GEN == 8 && (post_sync_flags ||
6187 (flags & (PIPE_CONTROL_NOTIFY_ENABLE |
6188 PIPE_CONTROL_DEPTH_STALL |
6189 PIPE_CONTROL_RENDER_TARGET_FLUSH |
6190 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
6191 PIPE_CONTROL_DATA_CACHE_FLUSH)))) {
6192 /* Project: BDW / Arguments:
6193 *
6194 * - LRI Post Sync Operation [23]
6195 * - Post Sync Op [15:14]
6196 * - Notify En [8]
6197 * - Depth Stall [13]
6198 * - Render Target Cache Flush [12]
6199 * - Depth Cache Flush [0]
6200 * - DC Flush Enable [5]
6201 *
6202 * "Requires stall bit ([20] of DW) set for all GPGPU and Media
6203 * Workloads."
6204 */
6205 flags |= PIPE_CONTROL_CS_STALL;
6206
6207 /* Also, from the PIPE_CONTROL instruction table, bit 20:
6208 *
6209 * "Project: BDW
6210 * This bit must be always set when PIPE_CONTROL command is
6211 * programmed by GPGPU and MEDIA workloads, except for the cases
6212 * when only Read Only Cache Invalidation bits are set (State
6213 * Cache Invalidation Enable, Instruction cache Invalidation
6214 * Enable, Texture Cache Invalidation Enable, Constant Cache
6215 * Invalidation Enable). This is to WA FFDOP CG issue, this WA
6216 * need not implemented when FF_DOP_CG is disable via "Fixed
6217 * Function DOP Clock Gate Disable" bit in RC_PSMI_CTRL register."
6218 *
6219 * It sounds like we could avoid CS stalls in some cases, but we
6220 * don't currently bother. This list isn't exactly the list above,
6221 * either...
6222 */
6223 }
6224 }
6225
6226 /* "Stall" workarounds ----------------------------------------------
6227 * These have to come after the earlier ones because we may have added
6228 * some additional CS stalls above.
6229 */
6230
6231 if (GEN_GEN < 9 && (flags & PIPE_CONTROL_CS_STALL)) {
6232 /* Project: PRE-SKL, VLV, CHV
6233 *
6234 * "[All Stepping][All SKUs]:
6235 *
6236 * One of the following must also be set:
6237 *
6238 * - Render Target Cache Flush Enable ([12] of DW1)
6239 * - Depth Cache Flush Enable ([0] of DW1)
6240 * - Stall at Pixel Scoreboard ([1] of DW1)
6241 * - Depth Stall ([13] of DW1)
6242 * - Post-Sync Operation ([13] of DW1)
6243 * - DC Flush Enable ([5] of DW1)"
6244 *
6245 * If we don't already have one of those bits set, we choose to add
6246 * "Stall at Pixel Scoreboard". Some of the other bits require a
6247 * CS stall as a workaround (see above), which would send us into
6248 * an infinite recursion of PIPE_CONTROLs. "Stall at Pixel Scoreboard"
6249 * appears to be safe, so we choose that.
6250 */
6251 const uint32_t wa_bits = PIPE_CONTROL_RENDER_TARGET_FLUSH |
6252 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
6253 PIPE_CONTROL_WRITE_IMMEDIATE |
6254 PIPE_CONTROL_WRITE_DEPTH_COUNT |
6255 PIPE_CONTROL_WRITE_TIMESTAMP |
6256 PIPE_CONTROL_STALL_AT_SCOREBOARD |
6257 PIPE_CONTROL_DEPTH_STALL |
6258 PIPE_CONTROL_DATA_CACHE_FLUSH;
6259 if (!(flags & wa_bits))
6260 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
6261 }
6262
6263 /* Emit --------------------------------------------------------------- */
6264
6265 if (INTEL_DEBUG & DEBUG_PIPE_CONTROL) {
6266 fprintf(stderr,
6267 " PC [%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%"PRIx64"]: %s\n",
6268 (flags & PIPE_CONTROL_FLUSH_ENABLE) ? "PipeCon " : "",
6269 (flags & PIPE_CONTROL_CS_STALL) ? "CS " : "",
6270 (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD) ? "Scoreboard " : "",
6271 (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) ? "VF " : "",
6272 (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH) ? "RT " : "",
6273 (flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE) ? "Const " : "",
6274 (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE) ? "TC " : "",
6275 (flags & PIPE_CONTROL_DATA_CACHE_FLUSH) ? "DC " : "",
6276 (flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH) ? "ZFlush " : "",
6277 (flags & PIPE_CONTROL_DEPTH_STALL) ? "ZStall " : "",
6278 (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE) ? "State " : "",
6279 (flags & PIPE_CONTROL_TLB_INVALIDATE) ? "TLB " : "",
6280 (flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE) ? "Inst " : "",
6281 (flags & PIPE_CONTROL_MEDIA_STATE_CLEAR) ? "MediaClear " : "",
6282 (flags & PIPE_CONTROL_NOTIFY_ENABLE) ? "Notify " : "",
6283 (flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) ?
6284 "SnapRes" : "",
6285 (flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE) ?
6286 "ISPDis" : "",
6287 (flags & PIPE_CONTROL_WRITE_IMMEDIATE) ? "WriteImm " : "",
6288 (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT) ? "WriteZCount " : "",
6289 (flags & PIPE_CONTROL_WRITE_TIMESTAMP) ? "WriteTimestamp " : "",
6290 imm, reason);
6291 }
6292
6293 iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
6294 pc.LRIPostSyncOperation = NoLRIOperation;
6295 pc.PipeControlFlushEnable = flags & PIPE_CONTROL_FLUSH_ENABLE;
6296 pc.DCFlushEnable = flags & PIPE_CONTROL_DATA_CACHE_FLUSH;
6297 pc.StoreDataIndex = 0;
6298 pc.CommandStreamerStallEnable = flags & PIPE_CONTROL_CS_STALL;
6299 pc.GlobalSnapshotCountReset =
6300 flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET;
6301 pc.TLBInvalidate = flags & PIPE_CONTROL_TLB_INVALIDATE;
6302 pc.GenericMediaStateClear = flags & PIPE_CONTROL_MEDIA_STATE_CLEAR;
6303 pc.StallAtPixelScoreboard = flags & PIPE_CONTROL_STALL_AT_SCOREBOARD;
6304 pc.RenderTargetCacheFlushEnable =
6305 flags & PIPE_CONTROL_RENDER_TARGET_FLUSH;
6306 pc.DepthCacheFlushEnable = flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH;
6307 pc.StateCacheInvalidationEnable =
6308 flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE;
6309 pc.VFCacheInvalidationEnable = flags & PIPE_CONTROL_VF_CACHE_INVALIDATE;
6310 pc.ConstantCacheInvalidationEnable =
6311 flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE;
6312 pc.PostSyncOperation = flags_to_post_sync_op(flags);
6313 pc.DepthStallEnable = flags & PIPE_CONTROL_DEPTH_STALL;
6314 pc.InstructionCacheInvalidateEnable =
6315 flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE;
6316 pc.NotifyEnable = flags & PIPE_CONTROL_NOTIFY_ENABLE;
6317 pc.IndirectStatePointersDisable =
6318 flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE;
6319 pc.TextureCacheInvalidationEnable =
6320 flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
6321 pc.Address = rw_bo(bo, offset);
6322 pc.ImmediateData = imm;
6323 }
6324 }
6325
6326 void
6327 genX(emit_urb_setup)(struct iris_context *ice,
6328 struct iris_batch *batch,
6329 const unsigned size[4],
6330 bool tess_present, bool gs_present)
6331 {
6332 const struct gen_device_info *devinfo = &batch->screen->devinfo;
6333 const unsigned push_size_kB = 32;
6334 unsigned entries[4];
6335 unsigned start[4];
6336
6337 ice->shaders.last_vs_entry_size = size[MESA_SHADER_VERTEX];
6338
6339 gen_get_urb_config(devinfo, 1024 * push_size_kB,
6340 1024 * ice->shaders.urb_size,
6341 tess_present, gs_present,
6342 size, entries, start);
6343
6344 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
6345 iris_emit_cmd(batch, GENX(3DSTATE_URB_VS), urb) {
6346 urb._3DCommandSubOpcode += i;
6347 urb.VSURBStartingAddress = start[i];
6348 urb.VSURBEntryAllocationSize = size[i] - 1;
6349 urb.VSNumberofURBEntries = entries[i];
6350 }
6351 }
6352 }
6353
6354 #if GEN_GEN == 9
6355 /**
6356 * Preemption on Gen9 has to be enabled or disabled in various cases.
6357 *
6358 * See these workarounds for preemption:
6359 * - WaDisableMidObjectPreemptionForGSLineStripAdj
6360 * - WaDisableMidObjectPreemptionForTrifanOrPolygon
6361 * - WaDisableMidObjectPreemptionForLineLoop
6362 * - WA#0798
6363 *
6364 * We don't put this in the vtable because it's only used on Gen9.
6365 */
6366 void
6367 gen9_toggle_preemption(struct iris_context *ice,
6368 struct iris_batch *batch,
6369 const struct pipe_draw_info *draw)
6370 {
6371 struct iris_genx_state *genx = ice->state.genx;
6372 bool object_preemption = true;
6373
6374 /* WaDisableMidObjectPreemptionForGSLineStripAdj
6375 *
6376 * "WA: Disable mid-draw preemption when draw-call is a linestrip_adj
6377 * and GS is enabled."
6378 */
6379 if (draw->mode == PIPE_PRIM_LINE_STRIP_ADJACENCY &&
6380 ice->shaders.prog[MESA_SHADER_GEOMETRY])
6381 object_preemption = false;
6382
6383 /* WaDisableMidObjectPreemptionForTrifanOrPolygon
6384 *
6385 * "TriFan miscompare in Execlist Preemption test. Cut index that is
6386 * on a previous context. End the previous, the resume another context
6387 * with a tri-fan or polygon, and the vertex count is corrupted. If we
6388 * prempt again we will cause corruption.
6389 *
6390 * WA: Disable mid-draw preemption when draw-call has a tri-fan."
6391 */
6392 if (draw->mode == PIPE_PRIM_TRIANGLE_FAN)
6393 object_preemption = false;
6394
6395 /* WaDisableMidObjectPreemptionForLineLoop
6396 *
6397 * "VF Stats Counters Missing a vertex when preemption enabled.
6398 *
6399 * WA: Disable mid-draw preemption when the draw uses a lineloop
6400 * topology."
6401 */
6402 if (draw->mode == PIPE_PRIM_LINE_LOOP)
6403 object_preemption = false;
6404
6405 /* WA#0798
6406 *
6407 * "VF is corrupting GAFS data when preempted on an instance boundary
6408 * and replayed with instancing enabled.
6409 *
6410 * WA: Disable preemption when using instanceing."
6411 */
6412 if (draw->instance_count > 1)
6413 object_preemption = false;
6414
6415 if (genx->object_preemption != object_preemption) {
6416 iris_enable_obj_preemption(batch, object_preemption);
6417 genx->object_preemption = object_preemption;
6418 }
6419 }
6420 #endif
6421
6422 static void
6423 iris_lost_genx_state(struct iris_context *ice, struct iris_batch *batch)
6424 {
6425 struct iris_genx_state *genx = ice->state.genx;
6426
6427 memset(genx->last_index_buffer, 0, sizeof(genx->last_index_buffer));
6428 }
6429
6430 void
6431 genX(init_state)(struct iris_context *ice)
6432 {
6433 struct pipe_context *ctx = &ice->ctx;
6434 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
6435
6436 ctx->create_blend_state = iris_create_blend_state;
6437 ctx->create_depth_stencil_alpha_state = iris_create_zsa_state;
6438 ctx->create_rasterizer_state = iris_create_rasterizer_state;
6439 ctx->create_sampler_state = iris_create_sampler_state;
6440 ctx->create_sampler_view = iris_create_sampler_view;
6441 ctx->create_surface = iris_create_surface;
6442 ctx->create_vertex_elements_state = iris_create_vertex_elements;
6443 ctx->bind_blend_state = iris_bind_blend_state;
6444 ctx->bind_depth_stencil_alpha_state = iris_bind_zsa_state;
6445 ctx->bind_sampler_states = iris_bind_sampler_states;
6446 ctx->bind_rasterizer_state = iris_bind_rasterizer_state;
6447 ctx->bind_vertex_elements_state = iris_bind_vertex_elements_state;
6448 ctx->delete_blend_state = iris_delete_state;
6449 ctx->delete_depth_stencil_alpha_state = iris_delete_state;
6450 ctx->delete_rasterizer_state = iris_delete_state;
6451 ctx->delete_sampler_state = iris_delete_state;
6452 ctx->delete_vertex_elements_state = iris_delete_state;
6453 ctx->set_blend_color = iris_set_blend_color;
6454 ctx->set_clip_state = iris_set_clip_state;
6455 ctx->set_constant_buffer = iris_set_constant_buffer;
6456 ctx->set_shader_buffers = iris_set_shader_buffers;
6457 ctx->set_shader_images = iris_set_shader_images;
6458 ctx->set_sampler_views = iris_set_sampler_views;
6459 ctx->set_tess_state = iris_set_tess_state;
6460 ctx->set_framebuffer_state = iris_set_framebuffer_state;
6461 ctx->set_polygon_stipple = iris_set_polygon_stipple;
6462 ctx->set_sample_mask = iris_set_sample_mask;
6463 ctx->set_scissor_states = iris_set_scissor_states;
6464 ctx->set_stencil_ref = iris_set_stencil_ref;
6465 ctx->set_vertex_buffers = iris_set_vertex_buffers;
6466 ctx->set_viewport_states = iris_set_viewport_states;
6467 ctx->sampler_view_destroy = iris_sampler_view_destroy;
6468 ctx->surface_destroy = iris_surface_destroy;
6469 ctx->draw_vbo = iris_draw_vbo;
6470 ctx->launch_grid = iris_launch_grid;
6471 ctx->create_stream_output_target = iris_create_stream_output_target;
6472 ctx->stream_output_target_destroy = iris_stream_output_target_destroy;
6473 ctx->set_stream_output_targets = iris_set_stream_output_targets;
6474
6475 ice->vtbl.destroy_state = iris_destroy_state;
6476 ice->vtbl.init_render_context = iris_init_render_context;
6477 ice->vtbl.init_compute_context = iris_init_compute_context;
6478 ice->vtbl.upload_render_state = iris_upload_render_state;
6479 ice->vtbl.update_surface_base_address = iris_update_surface_base_address;
6480 ice->vtbl.upload_compute_state = iris_upload_compute_state;
6481 ice->vtbl.emit_raw_pipe_control = iris_emit_raw_pipe_control;
6482 ice->vtbl.rebind_buffer = iris_rebind_buffer;
6483 ice->vtbl.load_register_reg32 = iris_load_register_reg32;
6484 ice->vtbl.load_register_reg64 = iris_load_register_reg64;
6485 ice->vtbl.load_register_imm32 = iris_load_register_imm32;
6486 ice->vtbl.load_register_imm64 = iris_load_register_imm64;
6487 ice->vtbl.load_register_mem32 = iris_load_register_mem32;
6488 ice->vtbl.load_register_mem64 = iris_load_register_mem64;
6489 ice->vtbl.store_register_mem32 = iris_store_register_mem32;
6490 ice->vtbl.store_register_mem64 = iris_store_register_mem64;
6491 ice->vtbl.store_data_imm32 = iris_store_data_imm32;
6492 ice->vtbl.store_data_imm64 = iris_store_data_imm64;
6493 ice->vtbl.copy_mem_mem = iris_copy_mem_mem;
6494 ice->vtbl.derived_program_state_size = iris_derived_program_state_size;
6495 ice->vtbl.store_derived_program_state = iris_store_derived_program_state;
6496 ice->vtbl.create_so_decl_list = iris_create_so_decl_list;
6497 ice->vtbl.populate_vs_key = iris_populate_vs_key;
6498 ice->vtbl.populate_tcs_key = iris_populate_tcs_key;
6499 ice->vtbl.populate_tes_key = iris_populate_tes_key;
6500 ice->vtbl.populate_gs_key = iris_populate_gs_key;
6501 ice->vtbl.populate_fs_key = iris_populate_fs_key;
6502 ice->vtbl.populate_cs_key = iris_populate_cs_key;
6503 ice->vtbl.mocs = mocs;
6504 ice->vtbl.lost_genx_state = iris_lost_genx_state;
6505
6506 ice->state.dirty = ~0ull;
6507
6508 ice->state.statistics_counters_enabled = true;
6509
6510 ice->state.sample_mask = 0xffff;
6511 ice->state.num_viewports = 1;
6512 ice->state.genx = calloc(1, sizeof(struct iris_genx_state));
6513
6514 /* Make a 1x1x1 null surface for unbound textures */
6515 void *null_surf_map =
6516 upload_state(ice->state.surface_uploader, &ice->state.unbound_tex,
6517 4 * GENX(RENDER_SURFACE_STATE_length), 64);
6518 isl_null_fill_state(&screen->isl_dev, null_surf_map, isl_extent3d(1, 1, 1));
6519 ice->state.unbound_tex.offset +=
6520 iris_bo_offset_from_base_address(iris_resource_bo(ice->state.unbound_tex.res));
6521
6522 /* Default all scissor rectangles to be empty regions. */
6523 for (int i = 0; i < IRIS_MAX_VIEWPORTS; i++) {
6524 ice->state.scissors[i] = (struct pipe_scissor_state) {
6525 .minx = 1, .maxx = 0, .miny = 1, .maxy = 0,
6526 };
6527 }
6528 }