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