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