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