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