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