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