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