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