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