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