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