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