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