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