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