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