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