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