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