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