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