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