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