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