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