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