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