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