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