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