iris: stencil texturing
[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 #ifndef NDEBUG
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 "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_pipe.h"
105 #include "iris_resource.h"
106
107 #define __gen_address_type struct iris_address
108 #define __gen_user_data struct iris_batch
109
110 #define ARRAY_BYTES(x) (sizeof(uint32_t) * ARRAY_SIZE(x))
111
112 static uint64_t
113 __gen_combine_address(struct iris_batch *batch, void *location,
114 struct iris_address addr, uint32_t delta)
115 {
116 uint64_t result = addr.offset + delta;
117
118 if (addr.bo) {
119 iris_use_pinned_bo(batch, addr.bo, addr.write);
120 /* Assume this is a general address, not relative to a base. */
121 result += addr.bo->gtt_offset;
122 }
123
124 return result;
125 }
126
127 #define __genxml_cmd_length(cmd) cmd ## _length
128 #define __genxml_cmd_length_bias(cmd) cmd ## _length_bias
129 #define __genxml_cmd_header(cmd) cmd ## _header
130 #define __genxml_cmd_pack(cmd) cmd ## _pack
131
132 #define _iris_pack_command(batch, cmd, dst, name) \
133 for (struct cmd name = { __genxml_cmd_header(cmd) }, \
134 *_dst = (void *)(dst); __builtin_expect(_dst != NULL, 1); \
135 ({ __genxml_cmd_pack(cmd)(batch, (void *)_dst, &name); \
136 _dst = NULL; \
137 }))
138
139 #define iris_pack_command(cmd, dst, name) \
140 _iris_pack_command(NULL, cmd, dst, name)
141
142 #define iris_pack_state(cmd, dst, name) \
143 for (struct cmd name = {}, \
144 *_dst = (void *)(dst); __builtin_expect(_dst != NULL, 1); \
145 __genxml_cmd_pack(cmd)(NULL, (void *)_dst, &name), \
146 _dst = NULL)
147
148 #define iris_emit_cmd(batch, cmd, name) \
149 _iris_pack_command(batch, cmd, iris_get_command_space(batch, 4 * __genxml_cmd_length(cmd)), name)
150
151 #define iris_emit_merge(batch, dwords0, dwords1, num_dwords) \
152 do { \
153 uint32_t *dw = iris_get_command_space(batch, 4 * num_dwords); \
154 for (uint32_t i = 0; i < num_dwords; i++) \
155 dw[i] = (dwords0)[i] | (dwords1)[i]; \
156 VG(VALGRIND_CHECK_MEM_IS_DEFINED(dw, num_dwords)); \
157 } while (0)
158
159 #include "genxml/genX_pack.h"
160 #include "genxml/gen_macros.h"
161 #include "genxml/genX_bits.h"
162
163 #define MOCS_WB (2 << 1)
164
165 /**
166 * Statically assert that PIPE_* enums match the hardware packets.
167 * (As long as they match, we don't need to translate them.)
168 */
169 UNUSED static void pipe_asserts()
170 {
171 #define PIPE_ASSERT(x) STATIC_ASSERT((int)x)
172
173 /* pipe_logicop happens to match the hardware. */
174 PIPE_ASSERT(PIPE_LOGICOP_CLEAR == LOGICOP_CLEAR);
175 PIPE_ASSERT(PIPE_LOGICOP_NOR == LOGICOP_NOR);
176 PIPE_ASSERT(PIPE_LOGICOP_AND_INVERTED == LOGICOP_AND_INVERTED);
177 PIPE_ASSERT(PIPE_LOGICOP_COPY_INVERTED == LOGICOP_COPY_INVERTED);
178 PIPE_ASSERT(PIPE_LOGICOP_AND_REVERSE == LOGICOP_AND_REVERSE);
179 PIPE_ASSERT(PIPE_LOGICOP_INVERT == LOGICOP_INVERT);
180 PIPE_ASSERT(PIPE_LOGICOP_XOR == LOGICOP_XOR);
181 PIPE_ASSERT(PIPE_LOGICOP_NAND == LOGICOP_NAND);
182 PIPE_ASSERT(PIPE_LOGICOP_AND == LOGICOP_AND);
183 PIPE_ASSERT(PIPE_LOGICOP_EQUIV == LOGICOP_EQUIV);
184 PIPE_ASSERT(PIPE_LOGICOP_NOOP == LOGICOP_NOOP);
185 PIPE_ASSERT(PIPE_LOGICOP_OR_INVERTED == LOGICOP_OR_INVERTED);
186 PIPE_ASSERT(PIPE_LOGICOP_COPY == LOGICOP_COPY);
187 PIPE_ASSERT(PIPE_LOGICOP_OR_REVERSE == LOGICOP_OR_REVERSE);
188 PIPE_ASSERT(PIPE_LOGICOP_OR == LOGICOP_OR);
189 PIPE_ASSERT(PIPE_LOGICOP_SET == LOGICOP_SET);
190
191 /* pipe_blend_func happens to match the hardware. */
192 PIPE_ASSERT(PIPE_BLENDFACTOR_ONE == BLENDFACTOR_ONE);
193 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_COLOR == BLENDFACTOR_SRC_COLOR);
194 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA == BLENDFACTOR_SRC_ALPHA);
195 PIPE_ASSERT(PIPE_BLENDFACTOR_DST_ALPHA == BLENDFACTOR_DST_ALPHA);
196 PIPE_ASSERT(PIPE_BLENDFACTOR_DST_COLOR == BLENDFACTOR_DST_COLOR);
197 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE == BLENDFACTOR_SRC_ALPHA_SATURATE);
198 PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_COLOR == BLENDFACTOR_CONST_COLOR);
199 PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_ALPHA == BLENDFACTOR_CONST_ALPHA);
200 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_COLOR == BLENDFACTOR_SRC1_COLOR);
201 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_ALPHA == BLENDFACTOR_SRC1_ALPHA);
202 PIPE_ASSERT(PIPE_BLENDFACTOR_ZERO == BLENDFACTOR_ZERO);
203 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_COLOR == BLENDFACTOR_INV_SRC_COLOR);
204 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_ALPHA == BLENDFACTOR_INV_SRC_ALPHA);
205 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_ALPHA == BLENDFACTOR_INV_DST_ALPHA);
206 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_COLOR == BLENDFACTOR_INV_DST_COLOR);
207 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_COLOR == BLENDFACTOR_INV_CONST_COLOR);
208 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_ALPHA == BLENDFACTOR_INV_CONST_ALPHA);
209 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_COLOR == BLENDFACTOR_INV_SRC1_COLOR);
210 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_ALPHA == BLENDFACTOR_INV_SRC1_ALPHA);
211
212 /* pipe_blend_func happens to match the hardware. */
213 PIPE_ASSERT(PIPE_BLEND_ADD == BLENDFUNCTION_ADD);
214 PIPE_ASSERT(PIPE_BLEND_SUBTRACT == BLENDFUNCTION_SUBTRACT);
215 PIPE_ASSERT(PIPE_BLEND_REVERSE_SUBTRACT == BLENDFUNCTION_REVERSE_SUBTRACT);
216 PIPE_ASSERT(PIPE_BLEND_MIN == BLENDFUNCTION_MIN);
217 PIPE_ASSERT(PIPE_BLEND_MAX == BLENDFUNCTION_MAX);
218
219 /* pipe_stencil_op happens to match the hardware. */
220 PIPE_ASSERT(PIPE_STENCIL_OP_KEEP == STENCILOP_KEEP);
221 PIPE_ASSERT(PIPE_STENCIL_OP_ZERO == STENCILOP_ZERO);
222 PIPE_ASSERT(PIPE_STENCIL_OP_REPLACE == STENCILOP_REPLACE);
223 PIPE_ASSERT(PIPE_STENCIL_OP_INCR == STENCILOP_INCRSAT);
224 PIPE_ASSERT(PIPE_STENCIL_OP_DECR == STENCILOP_DECRSAT);
225 PIPE_ASSERT(PIPE_STENCIL_OP_INCR_WRAP == STENCILOP_INCR);
226 PIPE_ASSERT(PIPE_STENCIL_OP_DECR_WRAP == STENCILOP_DECR);
227 PIPE_ASSERT(PIPE_STENCIL_OP_INVERT == STENCILOP_INVERT);
228
229 /* pipe_sprite_coord_mode happens to match 3DSTATE_SBE */
230 PIPE_ASSERT(PIPE_SPRITE_COORD_UPPER_LEFT == UPPERLEFT);
231 PIPE_ASSERT(PIPE_SPRITE_COORD_LOWER_LEFT == LOWERLEFT);
232 #undef PIPE_ASSERT
233 }
234
235 static unsigned
236 translate_prim_type(enum pipe_prim_type prim, uint8_t verts_per_patch)
237 {
238 static const unsigned map[] = {
239 [PIPE_PRIM_POINTS] = _3DPRIM_POINTLIST,
240 [PIPE_PRIM_LINES] = _3DPRIM_LINELIST,
241 [PIPE_PRIM_LINE_LOOP] = _3DPRIM_LINELOOP,
242 [PIPE_PRIM_LINE_STRIP] = _3DPRIM_LINESTRIP,
243 [PIPE_PRIM_TRIANGLES] = _3DPRIM_TRILIST,
244 [PIPE_PRIM_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
245 [PIPE_PRIM_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
246 [PIPE_PRIM_QUADS] = _3DPRIM_QUADLIST,
247 [PIPE_PRIM_QUAD_STRIP] = _3DPRIM_QUADSTRIP,
248 [PIPE_PRIM_POLYGON] = _3DPRIM_POLYGON,
249 [PIPE_PRIM_LINES_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
250 [PIPE_PRIM_LINE_STRIP_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
251 [PIPE_PRIM_TRIANGLES_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
252 [PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
253 [PIPE_PRIM_PATCHES] = _3DPRIM_PATCHLIST_1 - 1,
254 };
255
256 return map[prim] + (prim == PIPE_PRIM_PATCHES ? verts_per_patch : 0);
257 }
258
259 static unsigned
260 translate_compare_func(enum pipe_compare_func pipe_func)
261 {
262 static const unsigned map[] = {
263 [PIPE_FUNC_NEVER] = COMPAREFUNCTION_NEVER,
264 [PIPE_FUNC_LESS] = COMPAREFUNCTION_LESS,
265 [PIPE_FUNC_EQUAL] = COMPAREFUNCTION_EQUAL,
266 [PIPE_FUNC_LEQUAL] = COMPAREFUNCTION_LEQUAL,
267 [PIPE_FUNC_GREATER] = COMPAREFUNCTION_GREATER,
268 [PIPE_FUNC_NOTEQUAL] = COMPAREFUNCTION_NOTEQUAL,
269 [PIPE_FUNC_GEQUAL] = COMPAREFUNCTION_GEQUAL,
270 [PIPE_FUNC_ALWAYS] = COMPAREFUNCTION_ALWAYS,
271 };
272 return map[pipe_func];
273 }
274
275 static unsigned
276 translate_shadow_func(enum pipe_compare_func pipe_func)
277 {
278 /* Gallium specifies the result of shadow comparisons as:
279 *
280 * 1 if ref <op> texel,
281 * 0 otherwise.
282 *
283 * The hardware does:
284 *
285 * 0 if texel <op> ref,
286 * 1 otherwise.
287 *
288 * So we need to flip the operator and also negate.
289 */
290 static const unsigned map[] = {
291 [PIPE_FUNC_NEVER] = PREFILTEROPALWAYS,
292 [PIPE_FUNC_LESS] = PREFILTEROPLEQUAL,
293 [PIPE_FUNC_EQUAL] = PREFILTEROPNOTEQUAL,
294 [PIPE_FUNC_LEQUAL] = PREFILTEROPLESS,
295 [PIPE_FUNC_GREATER] = PREFILTEROPGEQUAL,
296 [PIPE_FUNC_NOTEQUAL] = PREFILTEROPEQUAL,
297 [PIPE_FUNC_GEQUAL] = PREFILTEROPGREATER,
298 [PIPE_FUNC_ALWAYS] = PREFILTEROPNEVER,
299 };
300 return map[pipe_func];
301 }
302
303 static unsigned
304 translate_cull_mode(unsigned pipe_face)
305 {
306 static const unsigned map[4] = {
307 [PIPE_FACE_NONE] = CULLMODE_NONE,
308 [PIPE_FACE_FRONT] = CULLMODE_FRONT,
309 [PIPE_FACE_BACK] = CULLMODE_BACK,
310 [PIPE_FACE_FRONT_AND_BACK] = CULLMODE_BOTH,
311 };
312 return map[pipe_face];
313 }
314
315 static unsigned
316 translate_fill_mode(unsigned pipe_polymode)
317 {
318 static const unsigned map[4] = {
319 [PIPE_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
320 [PIPE_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
321 [PIPE_POLYGON_MODE_POINT] = FILL_MODE_POINT,
322 [PIPE_POLYGON_MODE_FILL_RECTANGLE] = FILL_MODE_SOLID,
323 };
324 return map[pipe_polymode];
325 }
326
327 static unsigned
328 translate_mip_filter(enum pipe_tex_mipfilter pipe_mip)
329 {
330 static const unsigned map[] = {
331 [PIPE_TEX_MIPFILTER_NEAREST] = MIPFILTER_NEAREST,
332 [PIPE_TEX_MIPFILTER_LINEAR] = MIPFILTER_LINEAR,
333 [PIPE_TEX_MIPFILTER_NONE] = MIPFILTER_NONE,
334 };
335 return map[pipe_mip];
336 }
337
338 static uint32_t
339 translate_wrap(unsigned pipe_wrap)
340 {
341 static const unsigned map[] = {
342 [PIPE_TEX_WRAP_REPEAT] = TCM_WRAP,
343 [PIPE_TEX_WRAP_CLAMP] = TCM_HALF_BORDER,
344 [PIPE_TEX_WRAP_CLAMP_TO_EDGE] = TCM_CLAMP,
345 [PIPE_TEX_WRAP_CLAMP_TO_BORDER] = TCM_CLAMP_BORDER,
346 [PIPE_TEX_WRAP_MIRROR_REPEAT] = TCM_MIRROR,
347 [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE] = TCM_MIRROR_ONCE,
348
349 /* These are unsupported. */
350 [PIPE_TEX_WRAP_MIRROR_CLAMP] = -1,
351 [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER] = -1,
352 };
353 return map[pipe_wrap];
354 }
355
356 static struct iris_address
357 ro_bo(struct iris_bo *bo, uint64_t offset)
358 {
359 /* CSOs must pass NULL for bo! Otherwise it will add the BO to the
360 * validation list at CSO creation time, instead of draw time.
361 */
362 return (struct iris_address) { .bo = bo, .offset = offset };
363 }
364
365 static struct iris_address
366 rw_bo(struct iris_bo *bo, uint64_t offset)
367 {
368 /* CSOs must pass NULL for bo! Otherwise it will add the BO to the
369 * validation list at CSO creation time, instead of draw time.
370 */
371 return (struct iris_address) { .bo = bo, .offset = offset, .write = true };
372 }
373
374 /**
375 * Allocate space for some indirect state.
376 *
377 * Return a pointer to the map (to fill it out) and a state ref (for
378 * referring to the state in GPU commands).
379 */
380 static void *
381 upload_state(struct u_upload_mgr *uploader,
382 struct iris_state_ref *ref,
383 unsigned size,
384 unsigned alignment)
385 {
386 void *p = NULL;
387 u_upload_alloc(uploader, 0, size, alignment, &ref->offset, &ref->res, &p);
388 return p;
389 }
390
391 /**
392 * Stream out temporary/short-lived state.
393 *
394 * This allocates space, pins the BO, and includes the BO address in the
395 * returned offset (which works because all state lives in 32-bit memory
396 * zones).
397 */
398 static uint32_t *
399 stream_state(struct iris_batch *batch,
400 struct u_upload_mgr *uploader,
401 struct pipe_resource **out_res,
402 unsigned size,
403 unsigned alignment,
404 uint32_t *out_offset)
405 {
406 void *ptr = NULL;
407
408 u_upload_alloc(uploader, 0, size, alignment, out_offset, out_res, &ptr);
409
410 struct iris_bo *bo = iris_resource_bo(*out_res);
411 iris_use_pinned_bo(batch, bo, false);
412
413 *out_offset += iris_bo_offset_from_base_address(bo);
414
415 return ptr;
416 }
417
418 /**
419 * stream_state() + memcpy.
420 */
421 static uint32_t
422 emit_state(struct iris_batch *batch,
423 struct u_upload_mgr *uploader,
424 struct pipe_resource **out_res,
425 const void *data,
426 unsigned size,
427 unsigned alignment)
428 {
429 unsigned offset = 0;
430 uint32_t *map =
431 stream_state(batch, uploader, out_res, size, alignment, &offset);
432
433 if (map)
434 memcpy(map, data, size);
435
436 return offset;
437 }
438
439 /**
440 * Did field 'x' change between 'old_cso' and 'new_cso'?
441 *
442 * (If so, we may want to set some dirty flags.)
443 */
444 #define cso_changed(x) (!old_cso || (old_cso->x != new_cso->x))
445 #define cso_changed_memcmp(x) \
446 (!old_cso || memcmp(old_cso->x, new_cso->x, sizeof(old_cso->x)) != 0)
447
448 static void
449 flush_for_state_base_change(struct iris_batch *batch)
450 {
451 /* Flush before emitting STATE_BASE_ADDRESS.
452 *
453 * This isn't documented anywhere in the PRM. However, it seems to be
454 * necessary prior to changing the surface state base adress. We've
455 * seen issues in Vulkan where we get GPU hangs when using multi-level
456 * command buffers which clear depth, reset state base address, and then
457 * go render stuff.
458 *
459 * Normally, in GL, we would trust the kernel to do sufficient stalls
460 * and flushes prior to executing our batch. However, it doesn't seem
461 * as if the kernel's flushing is always sufficient and we don't want to
462 * rely on it.
463 *
464 * We make this an end-of-pipe sync instead of a normal flush because we
465 * do not know the current status of the GPU. On Haswell at least,
466 * having a fast-clear operation in flight at the same time as a normal
467 * rendering operation can cause hangs. Since the kernel's flushing is
468 * insufficient, we need to ensure that any rendering operations from
469 * other processes are definitely complete before we try to do our own
470 * rendering. It's a bit of a big hammer but it appears to work.
471 */
472 iris_emit_end_of_pipe_sync(batch,
473 PIPE_CONTROL_RENDER_TARGET_FLUSH |
474 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
475 PIPE_CONTROL_DATA_CACHE_FLUSH);
476 }
477
478 static void
479 _iris_emit_lri(struct iris_batch *batch, uint32_t reg, uint32_t val)
480 {
481 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
482 lri.RegisterOffset = reg;
483 lri.DataDWord = val;
484 }
485 }
486 #define iris_emit_lri(b, r, v) _iris_emit_lri(b, GENX(r##_num), v)
487
488 /**
489 * Upload the initial GPU state for a render context.
490 *
491 * This sets some invariant state that needs to be programmed a particular
492 * way, but we never actually change.
493 */
494 static void
495 iris_init_render_context(struct iris_screen *screen,
496 struct iris_batch *batch,
497 struct iris_vtable *vtbl,
498 struct pipe_debug_callback *dbg)
499 {
500 uint32_t reg_val;
501
502 iris_init_batch(batch, screen, vtbl, dbg, I915_EXEC_RENDER);
503
504 flush_for_state_base_change(batch);
505
506 /* We program most base addresses once at context initialization time.
507 * Each base address points at a 4GB memory zone, and never needs to
508 * change. See iris_bufmgr.h for a description of the memory zones.
509 *
510 * The one exception is Surface State Base Address, which needs to be
511 * updated occasionally. See iris_binder.c for the details there.
512 */
513 iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
514 #if 0
515 // XXX: MOCS is stupid for this.
516 sba.GeneralStateMemoryObjectControlState = MOCS_WB;
517 sba.StatelessDataPortAccessMemoryObjectControlState = MOCS_WB;
518 sba.DynamicStateMemoryObjectControlState = MOCS_WB;
519 sba.IndirectObjectMemoryObjectControlState = MOCS_WB;
520 sba.InstructionMemoryObjectControlState = MOCS_WB;
521 sba.BindlessSurfaceStateMemoryObjectControlState = MOCS_WB;
522 #endif
523
524 sba.GeneralStateBaseAddressModifyEnable = true;
525 sba.DynamicStateBaseAddressModifyEnable = true;
526 sba.IndirectObjectBaseAddressModifyEnable = true;
527 sba.InstructionBaseAddressModifyEnable = true;
528 sba.GeneralStateBufferSizeModifyEnable = true;
529 sba.DynamicStateBufferSizeModifyEnable = true;
530 sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
531 sba.IndirectObjectBufferSizeModifyEnable = true;
532 sba.InstructionBuffersizeModifyEnable = true;
533
534 sba.InstructionBaseAddress = ro_bo(NULL, IRIS_MEMZONE_SHADER_START);
535 sba.DynamicStateBaseAddress = ro_bo(NULL, IRIS_MEMZONE_DYNAMIC_START);
536
537 sba.GeneralStateBufferSize = 0xfffff;
538 sba.IndirectObjectBufferSize = 0xfffff;
539 sba.InstructionBufferSize = 0xfffff;
540 sba.DynamicStateBufferSize = 0xfffff;
541 }
542
543 // XXX: INSTPM on Gen8
544 iris_pack_state(GENX(CS_DEBUG_MODE2), &reg_val, reg) {
545 reg.CONSTANT_BUFFERAddressOffsetDisable = true;
546 reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
547 }
548 iris_emit_lri(batch, CS_DEBUG_MODE2, reg_val);
549
550 #if GEN_GEN == 9
551 iris_pack_state(GENX(CACHE_MODE_1), &reg_val, reg) {
552 reg.FloatBlendOptimizationEnable = true;
553 reg.FloatBlendOptimizationEnableMask = true;
554 reg.PartialResolveDisableInVC = true;
555 reg.PartialResolveDisableInVCMask = true;
556 }
557 iris_emit_lri(batch, CACHE_MODE_1, reg_val);
558 #endif
559
560 #if GEN_GEN == 11
561 iris_pack_state(GENX(SAMPLER_MODE), &reg_val, reg) {
562 reg.HeaderlessMessageforPreemptableContexts = 1;
563 reg.HeaderlessMessageforPreemptableContextsMask = 1;
564 }
565 iris_emit_lri(batch, SAMPLER_MODE, reg_val);
566
567 // XXX: 3D_MODE?
568 #endif
569
570 /* 3DSTATE_DRAWING_RECTANGLE is non-pipelined, so we want to avoid
571 * changing it dynamically. We set it to the maximum size here, and
572 * instead include the render target dimensions in the viewport, so
573 * viewport extents clipping takes care of pruning stray geometry.
574 */
575 iris_emit_cmd(batch, GENX(3DSTATE_DRAWING_RECTANGLE), rect) {
576 rect.ClippedDrawingRectangleXMax = UINT16_MAX;
577 rect.ClippedDrawingRectangleYMax = UINT16_MAX;
578 }
579
580 /* Set the initial MSAA sample positions. */
581 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_PATTERN), pat) {
582 GEN_SAMPLE_POS_1X(pat._1xSample);
583 GEN_SAMPLE_POS_2X(pat._2xSample);
584 GEN_SAMPLE_POS_4X(pat._4xSample);
585 GEN_SAMPLE_POS_8X(pat._8xSample);
586 GEN_SAMPLE_POS_16X(pat._16xSample);
587 }
588
589 /* Use the legacy AA line coverage computation. */
590 iris_emit_cmd(batch, GENX(3DSTATE_AA_LINE_PARAMETERS), foo);
591
592 /* Disable chromakeying (it's for media) */
593 iris_emit_cmd(batch, GENX(3DSTATE_WM_CHROMAKEY), foo);
594
595 /* We want regular rendering, not special HiZ operations. */
596 iris_emit_cmd(batch, GENX(3DSTATE_WM_HZ_OP), foo);
597
598 /* No polygon stippling offsets are necessary. */
599 // XXX: may need to set an offset for origin-UL framebuffers
600 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_OFFSET), foo);
601
602 /* Set a static partitioning of the push constant area. */
603 // XXX: this may be a bad idea...could starve the push ringbuffers...
604 for (int i = 0; i <= MESA_SHADER_FRAGMENT; i++) {
605 iris_emit_cmd(batch, GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
606 alloc._3DCommandSubOpcode = 18 + i;
607 alloc.ConstantBufferOffset = 6 * i;
608 alloc.ConstantBufferSize = i == MESA_SHADER_FRAGMENT ? 8 : 6;
609 }
610 }
611 }
612
613 struct iris_vertex_buffer_state {
614 /** The 3DSTATE_VERTEX_BUFFERS hardware packet. */
615 uint32_t vertex_buffers[1 + 33 * GENX(VERTEX_BUFFER_STATE_length)];
616
617 /** The resource to source vertex data from. */
618 struct pipe_resource *resources[33];
619
620 /** The number of bound vertex buffers. */
621 unsigned num_buffers;
622 };
623
624 struct iris_depth_buffer_state {
625 /* Depth/HiZ/Stencil related hardware packets. */
626 uint32_t packets[GENX(3DSTATE_DEPTH_BUFFER_length) +
627 GENX(3DSTATE_STENCIL_BUFFER_length) +
628 GENX(3DSTATE_HIER_DEPTH_BUFFER_length) +
629 GENX(3DSTATE_CLEAR_PARAMS_length)];
630 };
631
632 /**
633 * Generation-specific context state (ice->state.genx->...).
634 *
635 * Most state can go in iris_context directly, but these encode hardware
636 * packets which vary by generation.
637 */
638 struct iris_genx_state {
639 /** SF_CLIP_VIEWPORT */
640 uint32_t sf_cl_vp[GENX(SF_CLIP_VIEWPORT_length) * IRIS_MAX_VIEWPORTS];
641
642 struct iris_vertex_buffer_state vertex_buffers;
643 struct iris_depth_buffer_state depth_buffer;
644
645 uint32_t so_buffers[4 * GENX(3DSTATE_SO_BUFFER_length)];
646 uint32_t streamout[4 * GENX(3DSTATE_STREAMOUT_length)];
647 };
648
649 // XXX: move this to iris_draw.c
650 static void
651 iris_launch_grid(struct pipe_context *ctx, const struct pipe_grid_info *info)
652 {
653 }
654
655 /**
656 * The pipe->set_blend_color() driver hook.
657 *
658 * This corresponds to our COLOR_CALC_STATE.
659 */
660 static void
661 iris_set_blend_color(struct pipe_context *ctx,
662 const struct pipe_blend_color *state)
663 {
664 struct iris_context *ice = (struct iris_context *) ctx;
665
666 /* Our COLOR_CALC_STATE is exactly pipe_blend_color, so just memcpy */
667 memcpy(&ice->state.blend_color, state, sizeof(struct pipe_blend_color));
668 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
669 }
670
671 /**
672 * Gallium CSO for blend state (see pipe_blend_state).
673 */
674 struct iris_blend_state {
675 /** Partial 3DSTATE_PS_BLEND */
676 uint32_t ps_blend[GENX(3DSTATE_PS_BLEND_length)];
677
678 /** Partial BLEND_STATE */
679 uint32_t blend_state[GENX(BLEND_STATE_length) +
680 BRW_MAX_DRAW_BUFFERS * GENX(BLEND_STATE_ENTRY_length)];
681
682 bool alpha_to_coverage; /* for shader key */
683 };
684
685 /**
686 * The pipe->create_blend_state() driver hook.
687 *
688 * Translates a pipe_blend_state into iris_blend_state.
689 */
690 static void *
691 iris_create_blend_state(struct pipe_context *ctx,
692 const struct pipe_blend_state *state)
693 {
694 struct iris_blend_state *cso = malloc(sizeof(struct iris_blend_state));
695 uint32_t *blend_state = cso->blend_state;
696
697 cso->alpha_to_coverage = state->alpha_to_coverage;
698
699 iris_pack_command(GENX(3DSTATE_PS_BLEND), cso->ps_blend, pb) {
700 /* pb.HasWriteableRT is filled in at draw time. */
701 /* pb.AlphaTestEnable is filled in at draw time. */
702 pb.AlphaToCoverageEnable = state->alpha_to_coverage;
703 pb.IndependentAlphaBlendEnable = state->independent_blend_enable;
704
705 pb.ColorBufferBlendEnable = state->rt[0].blend_enable;
706
707 pb.SourceBlendFactor = state->rt[0].rgb_src_factor;
708 pb.SourceAlphaBlendFactor = state->rt[0].alpha_func;
709 pb.DestinationBlendFactor = state->rt[0].rgb_dst_factor;
710 pb.DestinationAlphaBlendFactor = state->rt[0].alpha_dst_factor;
711 }
712
713 iris_pack_state(GENX(BLEND_STATE), blend_state, bs) {
714 bs.AlphaToCoverageEnable = state->alpha_to_coverage;
715 bs.IndependentAlphaBlendEnable = state->independent_blend_enable;
716 bs.AlphaToOneEnable = state->alpha_to_one;
717 bs.AlphaToCoverageDitherEnable = state->alpha_to_coverage;
718 bs.ColorDitherEnable = state->dither;
719 /* bl.AlphaTestEnable and bs.AlphaTestFunction are filled in later. */
720 }
721
722 blend_state += GENX(BLEND_STATE_length);
723
724 for (int i = 0; i < BRW_MAX_DRAW_BUFFERS; i++) {
725 iris_pack_state(GENX(BLEND_STATE_ENTRY), blend_state, be) {
726 be.LogicOpEnable = state->logicop_enable;
727 be.LogicOpFunction = state->logicop_func;
728
729 be.PreBlendSourceOnlyClampEnable = false;
730 be.ColorClampRange = COLORCLAMP_RTFORMAT;
731 be.PreBlendColorClampEnable = true;
732 be.PostBlendColorClampEnable = true;
733
734 be.ColorBufferBlendEnable = state->rt[i].blend_enable;
735
736 be.ColorBlendFunction = state->rt[i].rgb_func;
737 be.AlphaBlendFunction = state->rt[i].alpha_func;
738 be.SourceBlendFactor = state->rt[i].rgb_src_factor;
739 be.SourceAlphaBlendFactor = state->rt[i].alpha_func;
740 be.DestinationBlendFactor = state->rt[i].rgb_dst_factor;
741 be.DestinationAlphaBlendFactor = state->rt[i].alpha_dst_factor;
742
743 be.WriteDisableRed = !(state->rt[i].colormask & PIPE_MASK_R);
744 be.WriteDisableGreen = !(state->rt[i].colormask & PIPE_MASK_G);
745 be.WriteDisableBlue = !(state->rt[i].colormask & PIPE_MASK_B);
746 be.WriteDisableAlpha = !(state->rt[i].colormask & PIPE_MASK_A);
747 }
748 blend_state += GENX(BLEND_STATE_ENTRY_length);
749 }
750
751 return cso;
752 }
753
754 /**
755 * The pipe->bind_blend_state() driver hook.
756 *
757 * Bind a blending CSO and flag related dirty bits.
758 */
759 static void
760 iris_bind_blend_state(struct pipe_context *ctx, void *state)
761 {
762 struct iris_context *ice = (struct iris_context *) ctx;
763 ice->state.cso_blend = state;
764 ice->state.dirty |= IRIS_DIRTY_PS_BLEND;
765 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
766 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_BLEND];
767 }
768
769 /**
770 * Gallium CSO for depth, stencil, and alpha testing state.
771 */
772 struct iris_depth_stencil_alpha_state {
773 /** Partial 3DSTATE_WM_DEPTH_STENCIL. */
774 uint32_t wmds[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
775
776 /** Outbound to BLEND_STATE, 3DSTATE_PS_BLEND, COLOR_CALC_STATE. */
777 struct pipe_alpha_state alpha;
778
779 /** Outbound to resolve and cache set tracking. */
780 bool depth_writes_enabled;
781 bool stencil_writes_enabled;
782 };
783
784 /**
785 * The pipe->create_depth_stencil_alpha_state() driver hook.
786 *
787 * We encode most of 3DSTATE_WM_DEPTH_STENCIL, and just save off the alpha
788 * testing state since we need pieces of it in a variety of places.
789 */
790 static void *
791 iris_create_zsa_state(struct pipe_context *ctx,
792 const struct pipe_depth_stencil_alpha_state *state)
793 {
794 struct iris_depth_stencil_alpha_state *cso =
795 malloc(sizeof(struct iris_depth_stencil_alpha_state));
796
797 bool two_sided_stencil = state->stencil[1].enabled;
798
799 cso->alpha = state->alpha;
800 cso->depth_writes_enabled = state->depth.writemask;
801 cso->stencil_writes_enabled =
802 state->stencil[0].writemask != 0 ||
803 (two_sided_stencil && state->stencil[1].writemask != 1);
804
805 /* The state tracker needs to optimize away EQUAL writes for us. */
806 assert(!(state->depth.func == PIPE_FUNC_EQUAL && state->depth.writemask));
807
808 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), cso->wmds, wmds) {
809 wmds.StencilFailOp = state->stencil[0].fail_op;
810 wmds.StencilPassDepthFailOp = state->stencil[0].zfail_op;
811 wmds.StencilPassDepthPassOp = state->stencil[0].zpass_op;
812 wmds.StencilTestFunction =
813 translate_compare_func(state->stencil[0].func);
814 wmds.BackfaceStencilFailOp = state->stencil[1].fail_op;
815 wmds.BackfaceStencilPassDepthFailOp = state->stencil[1].zfail_op;
816 wmds.BackfaceStencilPassDepthPassOp = state->stencil[1].zpass_op;
817 wmds.BackfaceStencilTestFunction =
818 translate_compare_func(state->stencil[1].func);
819 wmds.DepthTestFunction = translate_compare_func(state->depth.func);
820 wmds.DoubleSidedStencilEnable = two_sided_stencil;
821 wmds.StencilTestEnable = state->stencil[0].enabled;
822 wmds.StencilBufferWriteEnable =
823 state->stencil[0].writemask != 0 ||
824 (two_sided_stencil && state->stencil[1].writemask != 0);
825 wmds.DepthTestEnable = state->depth.enabled;
826 wmds.DepthBufferWriteEnable = state->depth.writemask;
827 wmds.StencilTestMask = state->stencil[0].valuemask;
828 wmds.StencilWriteMask = state->stencil[0].writemask;
829 wmds.BackfaceStencilTestMask = state->stencil[1].valuemask;
830 wmds.BackfaceStencilWriteMask = state->stencil[1].writemask;
831 /* wmds.[Backface]StencilReferenceValue are merged later */
832 }
833
834 return cso;
835 }
836
837 /**
838 * The pipe->bind_depth_stencil_alpha_state() driver hook.
839 *
840 * Bind a depth/stencil/alpha CSO and flag related dirty bits.
841 */
842 static void
843 iris_bind_zsa_state(struct pipe_context *ctx, void *state)
844 {
845 struct iris_context *ice = (struct iris_context *) ctx;
846 struct iris_depth_stencil_alpha_state *old_cso = ice->state.cso_zsa;
847 struct iris_depth_stencil_alpha_state *new_cso = state;
848
849 if (new_cso) {
850 if (cso_changed(alpha.ref_value))
851 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
852
853 if (cso_changed(alpha.enabled))
854 ice->state.dirty |= IRIS_DIRTY_PS_BLEND | IRIS_DIRTY_BLEND_STATE;
855
856 if (cso_changed(alpha.func))
857 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
858
859 ice->state.depth_writes_enabled = new_cso->depth_writes_enabled;
860 ice->state.stencil_writes_enabled = new_cso->stencil_writes_enabled;
861 }
862
863 ice->state.cso_zsa = new_cso;
864 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
865 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
866 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_DEPTH_STENCIL_ALPHA];
867 }
868
869 /**
870 * Gallium CSO for rasterizer state.
871 */
872 struct iris_rasterizer_state {
873 uint32_t sf[GENX(3DSTATE_SF_length)];
874 uint32_t clip[GENX(3DSTATE_CLIP_length)];
875 uint32_t raster[GENX(3DSTATE_RASTER_length)];
876 uint32_t wm[GENX(3DSTATE_WM_length)];
877 uint32_t line_stipple[GENX(3DSTATE_LINE_STIPPLE_length)];
878
879 bool clip_halfz; /* for CC_VIEWPORT */
880 bool depth_clip_near; /* for CC_VIEWPORT */
881 bool depth_clip_far; /* for CC_VIEWPORT */
882 bool flatshade; /* for shader state */
883 bool flatshade_first; /* for stream output */
884 bool clamp_fragment_color; /* for shader state */
885 bool light_twoside; /* for shader state */
886 bool rasterizer_discard; /* for 3DSTATE_STREAMOUT */
887 bool half_pixel_center; /* for 3DSTATE_MULTISAMPLE */
888 bool line_stipple_enable;
889 bool poly_stipple_enable;
890 bool multisample;
891 bool force_persample_interp;
892 enum pipe_sprite_coord_mode sprite_coord_mode; /* PIPE_SPRITE_* */
893 uint16_t sprite_coord_enable;
894 };
895
896 static float
897 get_line_width(const struct pipe_rasterizer_state *state)
898 {
899 float line_width = state->line_width;
900
901 /* From the OpenGL 4.4 spec:
902 *
903 * "The actual width of non-antialiased lines is determined by rounding
904 * the supplied width to the nearest integer, then clamping it to the
905 * implementation-dependent maximum non-antialiased line width."
906 */
907 if (!state->multisample && !state->line_smooth)
908 line_width = roundf(state->line_width);
909
910 if (!state->multisample && state->line_smooth && line_width < 1.5f) {
911 /* For 1 pixel line thickness or less, the general anti-aliasing
912 * algorithm gives up, and a garbage line is generated. Setting a
913 * Line Width of 0.0 specifies the rasterization of the "thinnest"
914 * (one-pixel-wide), non-antialiased lines.
915 *
916 * Lines rendered with zero Line Width are rasterized using the
917 * "Grid Intersection Quantization" rules as specified by the
918 * "Zero-Width (Cosmetic) Line Rasterization" section of the docs.
919 */
920 line_width = 0.0f;
921 }
922
923 return line_width;
924 }
925
926 /**
927 * The pipe->create_rasterizer_state() driver hook.
928 */
929 static void *
930 iris_create_rasterizer_state(struct pipe_context *ctx,
931 const struct pipe_rasterizer_state *state)
932 {
933 struct iris_rasterizer_state *cso =
934 malloc(sizeof(struct iris_rasterizer_state));
935
936 #if 0
937 point_quad_rasterization -> SBE?
938
939 not necessary?
940 {
941 poly_smooth
942 force_persample_interp - ?
943 bottom_edge_rule
944
945 offset_units_unscaled - cap not exposed
946 }
947 #endif
948
949 // XXX: it may make more sense just to store the pipe_rasterizer_state,
950 // we're copying a lot of booleans here. But we don't need all of them...
951
952 cso->multisample = state->multisample;
953 cso->force_persample_interp = state->force_persample_interp;
954 cso->clip_halfz = state->clip_halfz;
955 cso->depth_clip_near = state->depth_clip_near;
956 cso->depth_clip_far = state->depth_clip_far;
957 cso->flatshade = state->flatshade;
958 cso->flatshade_first = state->flatshade_first;
959 cso->clamp_fragment_color = state->clamp_fragment_color;
960 cso->light_twoside = state->light_twoside;
961 cso->rasterizer_discard = state->rasterizer_discard;
962 cso->half_pixel_center = state->half_pixel_center;
963 cso->sprite_coord_mode = state->sprite_coord_mode;
964 cso->sprite_coord_enable = state->sprite_coord_enable;
965 cso->line_stipple_enable = state->line_stipple_enable;
966 cso->poly_stipple_enable = state->poly_stipple_enable;
967
968 float line_width = get_line_width(state);
969
970 iris_pack_command(GENX(3DSTATE_SF), cso->sf, sf) {
971 sf.StatisticsEnable = true;
972 sf.ViewportTransformEnable = true;
973 sf.AALineDistanceMode = AALINEDISTANCE_TRUE;
974 sf.LineEndCapAntialiasingRegionWidth =
975 state->line_smooth ? _10pixels : _05pixels;
976 sf.LastPixelEnable = state->line_last_pixel;
977 sf.LineWidth = line_width;
978 sf.SmoothPointEnable = state->point_smooth;
979 sf.PointWidthSource = state->point_size_per_vertex ? Vertex : State;
980 sf.PointWidth = state->point_size;
981
982 if (state->flatshade_first) {
983 sf.TriangleFanProvokingVertexSelect = 1;
984 } else {
985 sf.TriangleStripListProvokingVertexSelect = 2;
986 sf.TriangleFanProvokingVertexSelect = 2;
987 sf.LineStripListProvokingVertexSelect = 1;
988 }
989 }
990
991 iris_pack_command(GENX(3DSTATE_RASTER), cso->raster, rr) {
992 rr.FrontWinding = state->front_ccw ? CounterClockwise : Clockwise;
993 rr.CullMode = translate_cull_mode(state->cull_face);
994 rr.FrontFaceFillMode = translate_fill_mode(state->fill_front);
995 rr.BackFaceFillMode = translate_fill_mode(state->fill_back);
996 rr.DXMultisampleRasterizationEnable = state->multisample;
997 rr.GlobalDepthOffsetEnableSolid = state->offset_tri;
998 rr.GlobalDepthOffsetEnableWireframe = state->offset_line;
999 rr.GlobalDepthOffsetEnablePoint = state->offset_point;
1000 rr.GlobalDepthOffsetConstant = state->offset_units * 2;
1001 rr.GlobalDepthOffsetScale = state->offset_scale;
1002 rr.GlobalDepthOffsetClamp = state->offset_clamp;
1003 rr.SmoothPointEnable = state->point_smooth;
1004 rr.AntialiasingEnable = state->line_smooth;
1005 rr.ScissorRectangleEnable = state->scissor;
1006 rr.ViewportZNearClipTestEnable = state->depth_clip_near;
1007 rr.ViewportZFarClipTestEnable = state->depth_clip_far;
1008 //rr.ConservativeRasterizationEnable = not yet supported by Gallium...
1009 }
1010
1011 iris_pack_command(GENX(3DSTATE_CLIP), cso->clip, cl) {
1012 /* cl.NonPerspectiveBarycentricEnable is filled in at draw time from
1013 * the FS program; cl.ForceZeroRTAIndexEnable is filled in from the FB.
1014 */
1015 cl.StatisticsEnable = true;
1016 cl.EarlyCullEnable = true;
1017 cl.UserClipDistanceClipTestEnableBitmask = state->clip_plane_enable;
1018 cl.ForceUserClipDistanceClipTestEnableBitmask = true;
1019 cl.APIMode = state->clip_halfz ? APIMODE_D3D : APIMODE_OGL;
1020 cl.GuardbandClipTestEnable = true;
1021 cl.ClipMode = CLIPMODE_NORMAL;
1022 cl.ClipEnable = true;
1023 cl.ViewportXYClipTestEnable = state->point_tri_clip;
1024 cl.MinimumPointWidth = 0.125;
1025 cl.MaximumPointWidth = 255.875;
1026
1027 if (state->flatshade_first) {
1028 cl.TriangleFanProvokingVertexSelect = 1;
1029 } else {
1030 cl.TriangleStripListProvokingVertexSelect = 2;
1031 cl.TriangleFanProvokingVertexSelect = 2;
1032 cl.LineStripListProvokingVertexSelect = 1;
1033 }
1034 }
1035
1036 iris_pack_command(GENX(3DSTATE_WM), cso->wm, wm) {
1037 /* wm.BarycentricInterpolationMode and wm.EarlyDepthStencilControl are
1038 * filled in at draw time from the FS program.
1039 */
1040 wm.LineAntialiasingRegionWidth = _10pixels;
1041 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1042 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1043 wm.StatisticsEnable = true;
1044 wm.LineStippleEnable = state->line_stipple_enable;
1045 wm.PolygonStippleEnable = state->poly_stipple_enable;
1046 }
1047
1048 /* Remap from 0..255 back to 1..256 */
1049 const unsigned line_stipple_factor = state->line_stipple_factor + 1;
1050
1051 iris_pack_command(GENX(3DSTATE_LINE_STIPPLE), cso->line_stipple, line) {
1052 line.LineStipplePattern = state->line_stipple_pattern;
1053 line.LineStippleInverseRepeatCount = 1.0f / line_stipple_factor;
1054 line.LineStippleRepeatCount = line_stipple_factor;
1055 }
1056
1057 return cso;
1058 }
1059
1060 /**
1061 * The pipe->bind_rasterizer_state() driver hook.
1062 *
1063 * Bind a rasterizer CSO and flag related dirty bits.
1064 */
1065 static void
1066 iris_bind_rasterizer_state(struct pipe_context *ctx, void *state)
1067 {
1068 struct iris_context *ice = (struct iris_context *) ctx;
1069 struct iris_rasterizer_state *old_cso = ice->state.cso_rast;
1070 struct iris_rasterizer_state *new_cso = state;
1071
1072 if (new_cso) {
1073 /* Try to avoid re-emitting 3DSTATE_LINE_STIPPLE, it's non-pipelined */
1074 if (cso_changed_memcmp(line_stipple))
1075 ice->state.dirty |= IRIS_DIRTY_LINE_STIPPLE;
1076
1077 if (cso_changed(half_pixel_center))
1078 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
1079
1080 if (cso_changed(line_stipple_enable) || cso_changed(poly_stipple_enable))
1081 ice->state.dirty |= IRIS_DIRTY_WM;
1082
1083 if (cso_changed(rasterizer_discard) || cso_changed(flatshade_first))
1084 ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
1085
1086 if (cso_changed(depth_clip_near) || cso_changed(depth_clip_far) ||
1087 cso_changed(clip_halfz))
1088 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
1089
1090 if (cso_changed(sprite_coord_enable) || cso_changed(light_twoside))
1091 ice->state.dirty |= IRIS_DIRTY_SBE;
1092 }
1093
1094 ice->state.cso_rast = new_cso;
1095 ice->state.dirty |= IRIS_DIRTY_RASTER;
1096 ice->state.dirty |= IRIS_DIRTY_CLIP;
1097 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_RASTERIZER];
1098 }
1099
1100 /**
1101 * Return true if the given wrap mode requires the border color to exist.
1102 *
1103 * (We can skip uploading it if the sampler isn't going to use it.)
1104 */
1105 static bool
1106 wrap_mode_needs_border_color(unsigned wrap_mode)
1107 {
1108 return wrap_mode == TCM_CLAMP_BORDER || wrap_mode == TCM_HALF_BORDER;
1109 }
1110
1111 /**
1112 * Gallium CSO for sampler state.
1113 */
1114 struct iris_sampler_state {
1115 union pipe_color_union border_color;
1116 bool needs_border_color;
1117
1118 uint32_t sampler_state[GENX(SAMPLER_STATE_length)];
1119 };
1120
1121 /**
1122 * The pipe->create_sampler_state() driver hook.
1123 *
1124 * We fill out SAMPLER_STATE (except for the border color pointer), and
1125 * store that on the CPU. It doesn't make sense to upload it to a GPU
1126 * buffer object yet, because 3DSTATE_SAMPLER_STATE_POINTERS requires
1127 * all bound sampler states to be in contiguous memor.
1128 */
1129 static void *
1130 iris_create_sampler_state(struct pipe_context *ctx,
1131 const struct pipe_sampler_state *state)
1132 {
1133 struct iris_sampler_state *cso = CALLOC_STRUCT(iris_sampler_state);
1134
1135 if (!cso)
1136 return NULL;
1137
1138 STATIC_ASSERT(PIPE_TEX_FILTER_NEAREST == MAPFILTER_NEAREST);
1139 STATIC_ASSERT(PIPE_TEX_FILTER_LINEAR == MAPFILTER_LINEAR);
1140
1141 unsigned wrap_s = translate_wrap(state->wrap_s);
1142 unsigned wrap_t = translate_wrap(state->wrap_t);
1143 unsigned wrap_r = translate_wrap(state->wrap_r);
1144
1145 memcpy(&cso->border_color, &state->border_color, sizeof(cso->border_color));
1146
1147 cso->needs_border_color = wrap_mode_needs_border_color(wrap_s) ||
1148 wrap_mode_needs_border_color(wrap_t) ||
1149 wrap_mode_needs_border_color(wrap_r);
1150
1151 float min_lod = state->min_lod;
1152 unsigned mag_img_filter = state->mag_img_filter;
1153
1154 // XXX: explain this code ported from ilo...I don't get it at all...
1155 if (state->min_mip_filter == PIPE_TEX_MIPFILTER_NONE &&
1156 state->min_lod > 0.0f) {
1157 min_lod = 0.0f;
1158 mag_img_filter = state->min_img_filter;
1159 }
1160
1161 iris_pack_state(GENX(SAMPLER_STATE), cso->sampler_state, samp) {
1162 samp.TCXAddressControlMode = wrap_s;
1163 samp.TCYAddressControlMode = wrap_t;
1164 samp.TCZAddressControlMode = wrap_r;
1165 samp.CubeSurfaceControlMode = state->seamless_cube_map;
1166 samp.NonnormalizedCoordinateEnable = !state->normalized_coords;
1167 samp.MinModeFilter = state->min_img_filter;
1168 samp.MagModeFilter = mag_img_filter;
1169 samp.MipModeFilter = translate_mip_filter(state->min_mip_filter);
1170 samp.MaximumAnisotropy = RATIO21;
1171
1172 if (state->max_anisotropy >= 2) {
1173 if (state->min_img_filter == PIPE_TEX_FILTER_LINEAR) {
1174 samp.MinModeFilter = MAPFILTER_ANISOTROPIC;
1175 samp.AnisotropicAlgorithm = EWAApproximation;
1176 }
1177
1178 if (state->mag_img_filter == PIPE_TEX_FILTER_LINEAR)
1179 samp.MagModeFilter = MAPFILTER_ANISOTROPIC;
1180
1181 samp.MaximumAnisotropy =
1182 MIN2((state->max_anisotropy - 2) / 2, RATIO161);
1183 }
1184
1185 /* Set address rounding bits if not using nearest filtering. */
1186 if (state->min_img_filter != PIPE_TEX_FILTER_NEAREST) {
1187 samp.UAddressMinFilterRoundingEnable = true;
1188 samp.VAddressMinFilterRoundingEnable = true;
1189 samp.RAddressMinFilterRoundingEnable = true;
1190 }
1191
1192 if (state->mag_img_filter != PIPE_TEX_FILTER_NEAREST) {
1193 samp.UAddressMagFilterRoundingEnable = true;
1194 samp.VAddressMagFilterRoundingEnable = true;
1195 samp.RAddressMagFilterRoundingEnable = true;
1196 }
1197
1198 if (state->compare_mode == PIPE_TEX_COMPARE_R_TO_TEXTURE)
1199 samp.ShadowFunction = translate_shadow_func(state->compare_func);
1200
1201 const float hw_max_lod = GEN_GEN >= 7 ? 14 : 13;
1202
1203 samp.LODPreClampMode = CLAMP_MODE_OGL;
1204 samp.MinLOD = CLAMP(min_lod, 0, hw_max_lod);
1205 samp.MaxLOD = CLAMP(state->max_lod, 0, hw_max_lod);
1206 samp.TextureLODBias = CLAMP(state->lod_bias, -16, 15);
1207
1208 /* .BorderColorPointer is filled in by iris_bind_sampler_states. */
1209 }
1210
1211 return cso;
1212 }
1213
1214 /**
1215 * The pipe->bind_sampler_states() driver hook.
1216 *
1217 * Now that we know all the sampler states, we upload them all into a
1218 * contiguous area of GPU memory, for 3DSTATE_SAMPLER_STATE_POINTERS_*.
1219 * We also fill out the border color state pointers at this point.
1220 *
1221 * We could defer this work to draw time, but we assume that binding
1222 * will be less frequent than drawing.
1223 */
1224 // XXX: this may be a bad idea, need to make sure that st/mesa calls us
1225 // XXX: with the complete set of shaders. If it makes multiple calls to
1226 // XXX: things one at a time, we could waste a lot of time assembling things.
1227 // XXX: it doesn't even BUY us anything to do it here, because we only flag
1228 // XXX: IRIS_DIRTY_SAMPLER_STATE when this is called...
1229 static void
1230 iris_bind_sampler_states(struct pipe_context *ctx,
1231 enum pipe_shader_type p_stage,
1232 unsigned start, unsigned count,
1233 void **states)
1234 {
1235 struct iris_context *ice = (struct iris_context *) ctx;
1236 gl_shader_stage stage = stage_from_pipe(p_stage);
1237 struct iris_shader_state *shs = &ice->state.shaders[stage];
1238
1239 assert(start + count <= IRIS_MAX_TEXTURE_SAMPLERS);
1240 shs->num_samplers = MAX2(shs->num_samplers, start + count);
1241
1242 for (int i = 0; i < count; i++) {
1243 shs->samplers[start + i] = states[i];
1244 }
1245
1246 /* Assemble the SAMPLER_STATEs into a contiguous table that lives
1247 * in the dynamic state memory zone, so we can point to it via the
1248 * 3DSTATE_SAMPLER_STATE_POINTERS_* commands.
1249 */
1250 uint32_t *map =
1251 upload_state(ice->state.dynamic_uploader, &shs->sampler_table,
1252 count * 4 * GENX(SAMPLER_STATE_length), 32);
1253 if (unlikely(!map))
1254 return;
1255
1256 struct pipe_resource *res = shs->sampler_table.res;
1257 shs->sampler_table.offset +=
1258 iris_bo_offset_from_base_address(iris_resource_bo(res));
1259
1260 /* Make sure all land in the same BO */
1261 iris_border_color_pool_reserve(ice, IRIS_MAX_TEXTURE_SAMPLERS);
1262
1263 for (int i = 0; i < count; i++) {
1264 struct iris_sampler_state *state = shs->samplers[i];
1265
1266 if (!state) {
1267 memset(map, 0, 4 * GENX(SAMPLER_STATE_length));
1268 } else if (!state->needs_border_color) {
1269 memcpy(map, state->sampler_state, 4 * GENX(SAMPLER_STATE_length));
1270 } else {
1271 ice->state.need_border_colors = true;
1272
1273 /* Stream out the border color and merge the pointer. */
1274 uint32_t offset =
1275 iris_upload_border_color(ice, &state->border_color);
1276
1277 uint32_t dynamic[GENX(SAMPLER_STATE_length)];
1278 iris_pack_state(GENX(SAMPLER_STATE), dynamic, dyns) {
1279 dyns.BorderColorPointer = offset;
1280 }
1281
1282 for (uint32_t j = 0; j < GENX(SAMPLER_STATE_length); j++)
1283 map[j] = state->sampler_state[j] | dynamic[j];
1284 }
1285
1286 map += GENX(SAMPLER_STATE_length);
1287 }
1288
1289 ice->state.dirty |= IRIS_DIRTY_SAMPLER_STATES_VS << stage;
1290 }
1291
1292 /**
1293 * Convert an swizzle enumeration (i.e. PIPE_SWIZZLE_X) to one of the HW's
1294 * "Shader Channel Select" enumerations (i.e. SCS_RED). The mappings are
1295 *
1296 * SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W, SWIZZLE_ZERO, SWIZZLE_ONE
1297 * 0 1 2 3 4 5
1298 * 4 5 6 7 0 1
1299 * SCS_RED, SCS_GREEN, SCS_BLUE, SCS_ALPHA, SCS_ZERO, SCS_ONE
1300 *
1301 * which is simply adding 4 then modding by 8 (or anding with 7).
1302 */
1303 static enum isl_channel_select
1304 pipe_swizzle_to_isl_channel(enum pipe_swizzle swizzle)
1305 {
1306 return (swizzle + 4) & 7;
1307 }
1308
1309 /**
1310 * The pipe->create_sampler_view() driver hook.
1311 */
1312 static struct pipe_sampler_view *
1313 iris_create_sampler_view(struct pipe_context *ctx,
1314 struct pipe_resource *tex,
1315 const struct pipe_sampler_view *tmpl)
1316 {
1317 struct iris_context *ice = (struct iris_context *) ctx;
1318 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1319 struct iris_sampler_view *isv = calloc(1, sizeof(struct iris_sampler_view));
1320
1321 if (!isv)
1322 return NULL;
1323
1324 /* initialize base object */
1325 isv->base = *tmpl;
1326 isv->base.context = ctx;
1327 isv->base.texture = NULL;
1328 pipe_reference_init(&isv->base.reference, 1);
1329 pipe_resource_reference(&isv->base.texture, tex);
1330
1331 void *map = upload_state(ice->state.surface_uploader, &isv->surface_state,
1332 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1333 if (!unlikely(map))
1334 return NULL;
1335
1336 struct iris_bo *state_bo = iris_resource_bo(isv->surface_state.res);
1337 isv->surface_state.offset += iris_bo_offset_from_base_address(state_bo);
1338
1339 if (util_format_is_depth_or_stencil(tmpl->format)) {
1340 struct iris_resource *zres, *sres;
1341 const struct util_format_description *desc =
1342 util_format_description(tmpl->format);
1343
1344 iris_get_depth_stencil_resources(tex, &zres, &sres);
1345
1346 tex = util_format_has_depth(desc) ? &zres->base : &sres->base;
1347 }
1348
1349 isv->res = (struct iris_resource *) tex;
1350
1351 /* XXX: do we need brw_get_texture_swizzle hacks here? */
1352 isv->view = (struct isl_view) {
1353 .format = iris_isl_format_for_pipe_format(tmpl->format),
1354 .swizzle = (struct isl_swizzle) {
1355 .r = pipe_swizzle_to_isl_channel(tmpl->swizzle_r),
1356 .g = pipe_swizzle_to_isl_channel(tmpl->swizzle_g),
1357 .b = pipe_swizzle_to_isl_channel(tmpl->swizzle_b),
1358 .a = pipe_swizzle_to_isl_channel(tmpl->swizzle_a),
1359 },
1360 .usage = ISL_SURF_USAGE_TEXTURE_BIT |
1361 (isv->res->surf.usage & ISL_SURF_USAGE_CUBE_BIT),
1362 };
1363
1364 /* Fill out SURFACE_STATE for this view. */
1365 if (tmpl->target != PIPE_BUFFER) {
1366 isv->view.base_level = tmpl->u.tex.first_level;
1367 isv->view.levels = tmpl->u.tex.last_level - tmpl->u.tex.first_level + 1;
1368 isv->view.base_array_layer = tmpl->u.tex.first_layer;
1369 isv->view.array_len =
1370 tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1;
1371
1372 isl_surf_fill_state(&screen->isl_dev, map,
1373 .surf = &isv->res->surf, .view = &isv->view,
1374 .mocs = MOCS_WB,
1375 .address = isv->res->bo->gtt_offset);
1376 // .aux_surf =
1377 // .clear_color = clear_color,
1378 } else {
1379 // XXX: what to do about isv->view? other drivers don't use it for bufs
1380 const struct isl_format_layout *fmtl =
1381 isl_format_get_layout(isv->view.format);
1382 const unsigned cpp = fmtl->bpb / 8;
1383
1384 isl_buffer_fill_state(&screen->isl_dev, map,
1385 .address = isv->res->bo->gtt_offset +
1386 tmpl->u.buf.offset,
1387 // XXX: buffer_texture_range_size from i965?
1388 .size_B = tmpl->u.buf.size,
1389 .format = isv->view.format,
1390 .stride_B = cpp,
1391 .mocs = MOCS_WB);
1392 }
1393
1394 return &isv->base;
1395 }
1396
1397 static void
1398 iris_sampler_view_destroy(struct pipe_context *ctx,
1399 struct pipe_sampler_view *state)
1400 {
1401 struct iris_sampler_view *isv = (void *) state;
1402 pipe_resource_reference(&state->texture, NULL);
1403 pipe_resource_reference(&isv->surface_state.res, NULL);
1404 free(isv);
1405 }
1406
1407 /**
1408 * The pipe->create_surface() driver hook.
1409 *
1410 * In Gallium nomenclature, "surfaces" are a view of a resource that
1411 * can be bound as a render target or depth/stencil buffer.
1412 */
1413 static struct pipe_surface *
1414 iris_create_surface(struct pipe_context *ctx,
1415 struct pipe_resource *tex,
1416 const struct pipe_surface *tmpl)
1417 {
1418 struct iris_context *ice = (struct iris_context *) ctx;
1419 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1420 const struct gen_device_info *devinfo = &screen->devinfo;
1421 struct iris_surface *surf = calloc(1, sizeof(struct iris_surface));
1422 struct pipe_surface *psurf = &surf->base;
1423 struct iris_resource *res = (struct iris_resource *) tex;
1424
1425 if (!surf)
1426 return NULL;
1427
1428 pipe_reference_init(&psurf->reference, 1);
1429 pipe_resource_reference(&psurf->texture, tex);
1430 psurf->context = ctx;
1431 psurf->format = tmpl->format;
1432 psurf->width = tex->width0;
1433 psurf->height = tex->height0;
1434 psurf->texture = tex;
1435 psurf->u.tex.first_layer = tmpl->u.tex.first_layer;
1436 psurf->u.tex.last_layer = tmpl->u.tex.last_layer;
1437 psurf->u.tex.level = tmpl->u.tex.level;
1438
1439 isl_surf_usage_flags_t usage = 0;
1440 if (tmpl->writable)
1441 usage = ISL_SURF_USAGE_STORAGE_BIT;
1442 else if (util_format_is_depth_or_stencil(tmpl->format))
1443 usage = ISL_SURF_USAGE_DEPTH_BIT;
1444 else
1445 usage = ISL_SURF_USAGE_RENDER_TARGET_BIT;
1446
1447 enum isl_format isl_format =
1448 iris_isl_format_for_usage(devinfo, psurf->format, usage);
1449
1450 if ((usage & ISL_SURF_USAGE_RENDER_TARGET_BIT) &&
1451 !isl_format_supports_rendering(devinfo, isl_format)) {
1452 /* Framebuffer validation will reject this invalid case, but it
1453 * hasn't had the opportunity yet. In the meantime, we need to
1454 * avoid hitting ISL asserts about unsupported formats below.
1455 */
1456 free(surf);
1457 return NULL;
1458 }
1459
1460 surf->view = (struct isl_view) {
1461 .format = isl_format,
1462 .base_level = tmpl->u.tex.level,
1463 .levels = 1,
1464 .base_array_layer = tmpl->u.tex.first_layer,
1465 .array_len = tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1,
1466 .swizzle = ISL_SWIZZLE_IDENTITY,
1467 .usage = usage,
1468 };
1469
1470 /* Bail early for depth/stencil - we don't want SURFACE_STATE for them. */
1471 if (res->surf.usage & (ISL_SURF_USAGE_DEPTH_BIT |
1472 ISL_SURF_USAGE_STENCIL_BIT))
1473 return psurf;
1474
1475
1476 void *map = upload_state(ice->state.surface_uploader, &surf->surface_state,
1477 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1478 if (!unlikely(map))
1479 return NULL;
1480
1481 struct iris_bo *state_bo = iris_resource_bo(surf->surface_state.res);
1482 surf->surface_state.offset += iris_bo_offset_from_base_address(state_bo);
1483
1484 isl_surf_fill_state(&screen->isl_dev, map,
1485 .surf = &res->surf, .view = &surf->view,
1486 .mocs = MOCS_WB,
1487 .address = res->bo->gtt_offset);
1488 // .aux_surf =
1489 // .clear_color = clear_color,
1490
1491 return psurf;
1492 }
1493
1494 /**
1495 * The pipe->set_sampler_views() driver hook.
1496 */
1497 static void
1498 iris_set_sampler_views(struct pipe_context *ctx,
1499 enum pipe_shader_type p_stage,
1500 unsigned start, unsigned count,
1501 struct pipe_sampler_view **views)
1502 {
1503 struct iris_context *ice = (struct iris_context *) ctx;
1504 gl_shader_stage stage = stage_from_pipe(p_stage);
1505 struct iris_shader_state *shs = &ice->state.shaders[stage];
1506
1507 unsigned i;
1508 for (i = 0; i < count; i++) {
1509 pipe_sampler_view_reference((struct pipe_sampler_view **)
1510 &shs->textures[i], views[i]);
1511 }
1512 for (; i < shs->num_textures; i++) {
1513 pipe_sampler_view_reference((struct pipe_sampler_view **)
1514 &shs->textures[i], NULL);
1515 }
1516
1517 shs->num_textures = count;
1518
1519 ice->state.dirty |= (IRIS_DIRTY_BINDINGS_VS << stage);
1520 }
1521
1522 /**
1523 * The pipe->set_tess_state() driver hook.
1524 */
1525 static void
1526 iris_set_tess_state(struct pipe_context *ctx,
1527 const float default_outer_level[4],
1528 const float default_inner_level[2])
1529 {
1530 struct iris_context *ice = (struct iris_context *) ctx;
1531
1532 memcpy(&ice->state.default_outer_level[0], &default_outer_level[0], 4 * sizeof(float));
1533 memcpy(&ice->state.default_inner_level[0], &default_inner_level[0], 2 * sizeof(float));
1534
1535 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_TCS;
1536 }
1537
1538 static void
1539 iris_surface_destroy(struct pipe_context *ctx, struct pipe_surface *p_surf)
1540 {
1541 struct iris_surface *surf = (void *) p_surf;
1542 pipe_resource_reference(&p_surf->texture, NULL);
1543 pipe_resource_reference(&surf->surface_state.res, NULL);
1544 free(surf);
1545 }
1546
1547 // XXX: actually implement user clip planes
1548 static void
1549 iris_set_clip_state(struct pipe_context *ctx,
1550 const struct pipe_clip_state *state)
1551 {
1552 }
1553
1554 /**
1555 * The pipe->set_polygon_stipple() driver hook.
1556 */
1557 static void
1558 iris_set_polygon_stipple(struct pipe_context *ctx,
1559 const struct pipe_poly_stipple *state)
1560 {
1561 struct iris_context *ice = (struct iris_context *) ctx;
1562 memcpy(&ice->state.poly_stipple, state, sizeof(*state));
1563 ice->state.dirty |= IRIS_DIRTY_POLYGON_STIPPLE;
1564 }
1565
1566 /**
1567 * The pipe->set_sample_mask() driver hook.
1568 */
1569 static void
1570 iris_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
1571 {
1572 struct iris_context *ice = (struct iris_context *) ctx;
1573
1574 /* We only support 16x MSAA, so we have 16 bits of sample maks.
1575 * st/mesa may pass us 0xffffffff though, meaning "enable all samples".
1576 */
1577 ice->state.sample_mask = sample_mask & 0xffff;
1578 ice->state.dirty |= IRIS_DIRTY_SAMPLE_MASK;
1579 }
1580
1581 /**
1582 * The pipe->set_scissor_states() driver hook.
1583 *
1584 * This corresponds to our SCISSOR_RECT state structures. It's an
1585 * exact match, so we just store them, and memcpy them out later.
1586 */
1587 static void
1588 iris_set_scissor_states(struct pipe_context *ctx,
1589 unsigned start_slot,
1590 unsigned num_scissors,
1591 const struct pipe_scissor_state *states)
1592 {
1593 struct iris_context *ice = (struct iris_context *) ctx;
1594
1595 for (unsigned i = 0; i < num_scissors; i++) {
1596 ice->state.scissors[start_slot + i] = states[i];
1597 }
1598
1599 ice->state.dirty |= IRIS_DIRTY_SCISSOR_RECT;
1600 }
1601
1602 /**
1603 * The pipe->set_stencil_ref() driver hook.
1604 *
1605 * This is added to 3DSTATE_WM_DEPTH_STENCIL dynamically at draw time.
1606 */
1607 static void
1608 iris_set_stencil_ref(struct pipe_context *ctx,
1609 const struct pipe_stencil_ref *state)
1610 {
1611 struct iris_context *ice = (struct iris_context *) ctx;
1612 memcpy(&ice->state.stencil_ref, state, sizeof(*state));
1613 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
1614 }
1615
1616 static float
1617 viewport_extent(const struct pipe_viewport_state *state, int axis, float sign)
1618 {
1619 return copysignf(state->scale[axis], sign) + state->translate[axis];
1620 }
1621
1622 #if 0
1623 static void
1624 calculate_guardband_size(uint32_t fb_width, uint32_t fb_height,
1625 float m00, float m11, float m30, float m31,
1626 float *xmin, float *xmax,
1627 float *ymin, float *ymax)
1628 {
1629 /* According to the "Vertex X,Y Clamping and Quantization" section of the
1630 * Strips and Fans documentation:
1631 *
1632 * "The vertex X and Y screen-space coordinates are also /clamped/ to the
1633 * fixed-point "guardband" range supported by the rasterization hardware"
1634 *
1635 * and
1636 *
1637 * "In almost all circumstances, if an object’s vertices are actually
1638 * modified by this clamping (i.e., had X or Y coordinates outside of
1639 * the guardband extent the rendered object will not match the intended
1640 * result. Therefore software should take steps to ensure that this does
1641 * not happen - e.g., by clipping objects such that they do not exceed
1642 * these limits after the Drawing Rectangle is applied."
1643 *
1644 * I believe the fundamental restriction is that the rasterizer (in
1645 * the SF/WM stages) have a limit on the number of pixels that can be
1646 * rasterized. We need to ensure any coordinates beyond the rasterizer
1647 * limit are handled by the clipper. So effectively that limit becomes
1648 * the clipper's guardband size.
1649 *
1650 * It goes on to say:
1651 *
1652 * "In addition, in order to be correctly rendered, objects must have a
1653 * screenspace bounding box not exceeding 8K in the X or Y direction.
1654 * This additional restriction must also be comprehended by software,
1655 * i.e., enforced by use of clipping."
1656 *
1657 * This makes no sense. Gen7+ hardware supports 16K render targets,
1658 * and you definitely need to be able to draw polygons that fill the
1659 * surface. Our assumption is that the rasterizer was limited to 8K
1660 * on Sandybridge, which only supports 8K surfaces, and it was actually
1661 * increased to 16K on Ivybridge and later.
1662 *
1663 * So, limit the guardband to 16K on Gen7+ and 8K on Sandybridge.
1664 */
1665 const float gb_size = GEN_GEN >= 7 ? 16384.0f : 8192.0f;
1666
1667 if (m00 != 0 && m11 != 0) {
1668 /* First, we compute the screen-space render area */
1669 const float ss_ra_xmin = MIN3( 0, m30 + m00, m30 - m00);
1670 const float ss_ra_xmax = MAX3( fb_width, m30 + m00, m30 - m00);
1671 const float ss_ra_ymin = MIN3( 0, m31 + m11, m31 - m11);
1672 const float ss_ra_ymax = MAX3(fb_height, m31 + m11, m31 - m11);
1673
1674 /* We want the guardband to be centered on that */
1675 const float ss_gb_xmin = (ss_ra_xmin + ss_ra_xmax) / 2 - gb_size;
1676 const float ss_gb_xmax = (ss_ra_xmin + ss_ra_xmax) / 2 + gb_size;
1677 const float ss_gb_ymin = (ss_ra_ymin + ss_ra_ymax) / 2 - gb_size;
1678 const float ss_gb_ymax = (ss_ra_ymin + ss_ra_ymax) / 2 + gb_size;
1679
1680 /* Now we need it in native device coordinates */
1681 const float ndc_gb_xmin = (ss_gb_xmin - m30) / m00;
1682 const float ndc_gb_xmax = (ss_gb_xmax - m30) / m00;
1683 const float ndc_gb_ymin = (ss_gb_ymin - m31) / m11;
1684 const float ndc_gb_ymax = (ss_gb_ymax - m31) / m11;
1685
1686 /* Thanks to Y-flipping and ORIGIN_UPPER_LEFT, the Y coordinates may be
1687 * flipped upside-down. X should be fine though.
1688 */
1689 assert(ndc_gb_xmin <= ndc_gb_xmax);
1690 *xmin = ndc_gb_xmin;
1691 *xmax = ndc_gb_xmax;
1692 *ymin = MIN2(ndc_gb_ymin, ndc_gb_ymax);
1693 *ymax = MAX2(ndc_gb_ymin, ndc_gb_ymax);
1694 } else {
1695 /* The viewport scales to 0, so nothing will be rendered. */
1696 *xmin = 0.0f;
1697 *xmax = 0.0f;
1698 *ymin = 0.0f;
1699 *ymax = 0.0f;
1700 }
1701 }
1702 #endif
1703
1704 /**
1705 * The pipe->set_viewport_states() driver hook.
1706 *
1707 * This corresponds to our SF_CLIP_VIEWPORT states. We can't calculate
1708 * the guardband yet, as we need the framebuffer dimensions, but we can
1709 * at least fill out the rest.
1710 */
1711 static void
1712 iris_set_viewport_states(struct pipe_context *ctx,
1713 unsigned start_slot,
1714 unsigned count,
1715 const struct pipe_viewport_state *states)
1716 {
1717 struct iris_context *ice = (struct iris_context *) ctx;
1718 struct iris_genx_state *genx = ice->state.genx;
1719 uint32_t *vp_map = &genx->sf_cl_vp[start_slot];
1720
1721 for (unsigned i = 0; i < count; i++) {
1722 const struct pipe_viewport_state *state = &states[i];
1723
1724 memcpy(&ice->state.viewports[start_slot + i], state, sizeof(*state));
1725
1726 iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
1727 vp.ViewportMatrixElementm00 = state->scale[0];
1728 vp.ViewportMatrixElementm11 = state->scale[1];
1729 vp.ViewportMatrixElementm22 = state->scale[2];
1730 vp.ViewportMatrixElementm30 = state->translate[0];
1731 vp.ViewportMatrixElementm31 = state->translate[1];
1732 vp.ViewportMatrixElementm32 = state->translate[2];
1733 /* XXX: in i965 this is computed based on the drawbuffer size,
1734 * but we don't have that here...
1735 */
1736 vp.XMinClipGuardband = -1.0;
1737 vp.XMaxClipGuardband = 1.0;
1738 vp.YMinClipGuardband = -1.0;
1739 vp.YMaxClipGuardband = 1.0;
1740 vp.XMinViewPort = viewport_extent(state, 0, -1.0f);
1741 vp.XMaxViewPort = viewport_extent(state, 0, 1.0f) - 1;
1742 vp.YMinViewPort = viewport_extent(state, 1, -1.0f);
1743 vp.YMaxViewPort = viewport_extent(state, 1, 1.0f) - 1;
1744 }
1745
1746 vp_map += GENX(SF_CLIP_VIEWPORT_length);
1747 }
1748
1749 ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
1750
1751 if (ice->state.cso_rast && (!ice->state.cso_rast->depth_clip_near ||
1752 !ice->state.cso_rast->depth_clip_far))
1753 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
1754 }
1755
1756 /**
1757 * The pipe->set_framebuffer_state() driver hook.
1758 *
1759 * Sets the current draw FBO, including color render targets, depth,
1760 * and stencil buffers.
1761 */
1762 static void
1763 iris_set_framebuffer_state(struct pipe_context *ctx,
1764 const struct pipe_framebuffer_state *state)
1765 {
1766 struct iris_context *ice = (struct iris_context *) ctx;
1767 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1768 struct isl_device *isl_dev = &screen->isl_dev;
1769 struct pipe_framebuffer_state *cso = &ice->state.framebuffer;
1770 struct iris_resource *zres;
1771 struct iris_resource *stencil_res;
1772
1773 unsigned samples = util_framebuffer_get_num_samples(state);
1774
1775 if (cso->samples != samples) {
1776 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
1777 }
1778
1779 if (cso->nr_cbufs != state->nr_cbufs) {
1780 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
1781 }
1782
1783 if ((cso->layers == 0) != (state->layers == 0)) {
1784 ice->state.dirty |= IRIS_DIRTY_CLIP;
1785 }
1786
1787 util_copy_framebuffer_state(cso, state);
1788 cso->samples = samples;
1789
1790 struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
1791
1792 struct isl_view view = {
1793 .base_level = 0,
1794 .levels = 1,
1795 .base_array_layer = 0,
1796 .array_len = 1,
1797 .swizzle = ISL_SWIZZLE_IDENTITY,
1798 };
1799
1800 struct isl_depth_stencil_hiz_emit_info info = {
1801 .view = &view,
1802 .mocs = MOCS_WB,
1803 };
1804
1805 if (cso->zsbuf) {
1806 iris_get_depth_stencil_resources(cso->zsbuf->texture, &zres,
1807 &stencil_res);
1808
1809 view.base_level = cso->zsbuf->u.tex.level;
1810 view.base_array_layer = cso->zsbuf->u.tex.first_layer;
1811 view.array_len =
1812 cso->zsbuf->u.tex.last_layer - cso->zsbuf->u.tex.first_layer + 1;
1813
1814 if (zres) {
1815 view.usage |= ISL_SURF_USAGE_DEPTH_BIT;
1816
1817 info.depth_surf = &zres->surf;
1818 info.depth_address = zres->bo->gtt_offset;
1819 info.hiz_usage = ISL_AUX_USAGE_NONE;
1820
1821 view.format = zres->surf.format;
1822 }
1823
1824 if (stencil_res) {
1825 view.usage |= ISL_SURF_USAGE_STENCIL_BIT;
1826 info.stencil_surf = &stencil_res->surf;
1827 info.stencil_address = stencil_res->bo->gtt_offset;
1828 if (!zres)
1829 view.format = stencil_res->surf.format;
1830 }
1831 }
1832
1833 isl_emit_depth_stencil_hiz_s(isl_dev, cso_z->packets, &info);
1834
1835 /* Make a null surface for unbound buffers */
1836 void *null_surf_map =
1837 upload_state(ice->state.surface_uploader, &ice->state.null_fb,
1838 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1839 isl_null_fill_state(&screen->isl_dev, null_surf_map, isl_extent3d(cso->width, cso->height, cso->layers ? cso->layers : 1));
1840 ice->state.null_fb.offset +=
1841 iris_bo_offset_from_base_address(iris_resource_bo(ice->state.null_fb.res));
1842
1843 ice->state.dirty |= IRIS_DIRTY_DEPTH_BUFFER;
1844
1845 /* Render target change */
1846 ice->state.dirty |= IRIS_DIRTY_BINDINGS_FS;
1847
1848 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_FRAMEBUFFER];
1849
1850 #if GEN_GEN == 11
1851 // XXX: we may want to flag IRIS_DIRTY_MULTISAMPLE (or SAMPLE_MASK?)
1852 // XXX: see commit 979fc1bc9bcc64027ff2cfafd285676f31b930a6
1853
1854 /* The PIPE_CONTROL command description says:
1855 *
1856 * "Whenever a Binding Table Index (BTI) used by a Render Target Message
1857 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
1858 * Target Cache Flush by enabling this bit. When render target flush
1859 * is set due to new association of BTI, PS Scoreboard Stall bit must
1860 * be set in this packet."
1861 */
1862 // XXX: does this need to happen at 3DSTATE_BTP_PS time?
1863 iris_emit_pipe_control_flush(&ice->render_batch,
1864 PIPE_CONTROL_RENDER_TARGET_FLUSH |
1865 PIPE_CONTROL_STALL_AT_SCOREBOARD);
1866 #endif
1867 }
1868
1869 /**
1870 * The pipe->set_constant_buffer() driver hook.
1871 *
1872 * This uploads any constant data in user buffers, and references
1873 * any UBO resources containing constant data.
1874 */
1875 static void
1876 iris_set_constant_buffer(struct pipe_context *ctx,
1877 enum pipe_shader_type p_stage, unsigned index,
1878 const struct pipe_constant_buffer *input)
1879 {
1880 struct iris_context *ice = (struct iris_context *) ctx;
1881 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1882 gl_shader_stage stage = stage_from_pipe(p_stage);
1883 struct iris_shader_state *shs = &ice->state.shaders[stage];
1884 struct iris_const_buffer *cbuf = &shs->constbuf[index];
1885
1886 if (input && (input->buffer || input->user_buffer)) {
1887 if (input->user_buffer) {
1888 u_upload_data(ctx->const_uploader, 0, input->buffer_size, 32,
1889 input->user_buffer, &cbuf->data.offset,
1890 &cbuf->data.res);
1891 } else {
1892 pipe_resource_reference(&cbuf->data.res, input->buffer);
1893 }
1894
1895 // XXX: these are not retained forever, use a separate uploader?
1896 void *map =
1897 upload_state(ice->state.surface_uploader, &cbuf->surface_state,
1898 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1899 if (!unlikely(map)) {
1900 pipe_resource_reference(&cbuf->data.res, NULL);
1901 return;
1902 }
1903
1904 struct iris_resource *res = (void *) cbuf->data.res;
1905 struct iris_bo *surf_bo = iris_resource_bo(cbuf->surface_state.res);
1906 cbuf->surface_state.offset += iris_bo_offset_from_base_address(surf_bo);
1907
1908 isl_buffer_fill_state(&screen->isl_dev, map,
1909 .address = res->bo->gtt_offset + cbuf->data.offset,
1910 .size_B = input->buffer_size,
1911 .format = ISL_FORMAT_R32G32B32A32_FLOAT,
1912 .stride_B = 1,
1913 .mocs = MOCS_WB)
1914 } else {
1915 pipe_resource_reference(&cbuf->data.res, NULL);
1916 pipe_resource_reference(&cbuf->surface_state.res, NULL);
1917 }
1918
1919 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS << stage;
1920 // XXX: maybe not necessary all the time...?
1921 // XXX: we need 3DS_BTP to commit these changes, and if we fell back to
1922 // XXX: pull model we may need actual new bindings...
1923 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
1924 }
1925
1926 /**
1927 * The pipe->set_shader_buffers() driver hook.
1928 *
1929 * This binds SSBOs and ABOs. Unfortunately, we need to stream out
1930 * SURFACE_STATE here, as the buffer offset may change each time.
1931 */
1932 static void
1933 iris_set_shader_buffers(struct pipe_context *ctx,
1934 enum pipe_shader_type p_stage,
1935 unsigned start_slot, unsigned count,
1936 const struct pipe_shader_buffer *buffers)
1937 {
1938 struct iris_context *ice = (struct iris_context *) ctx;
1939 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1940 gl_shader_stage stage = stage_from_pipe(p_stage);
1941 struct iris_shader_state *shs = &ice->state.shaders[stage];
1942
1943 for (unsigned i = 0; i < count; i++) {
1944 if (buffers && buffers[i].buffer) {
1945 const struct pipe_shader_buffer *buffer = &buffers[i];
1946 struct iris_resource *res = (void *) buffer->buffer;
1947 pipe_resource_reference(&shs->ssbo[start_slot + i], &res->base);
1948
1949 // XXX: these are not retained forever, use a separate uploader?
1950 void *map =
1951 upload_state(ice->state.surface_uploader,
1952 &shs->ssbo_surface_state[start_slot + i],
1953 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1954 if (!unlikely(map)) {
1955 pipe_resource_reference(&shs->ssbo[start_slot + i], NULL);
1956 return;
1957 }
1958
1959 struct iris_bo *surf_state_bo =
1960 iris_resource_bo(shs->ssbo_surface_state[start_slot + i].res);
1961 shs->ssbo_surface_state[start_slot + i].offset +=
1962 iris_bo_offset_from_base_address(surf_state_bo);
1963
1964 isl_buffer_fill_state(&screen->isl_dev, map,
1965 .address =
1966 res->bo->gtt_offset + buffer->buffer_offset,
1967 .size_B = buffer->buffer_size,
1968 .format = ISL_FORMAT_RAW,
1969 .stride_B = 1,
1970 .mocs = MOCS_WB);
1971 } else {
1972 pipe_resource_reference(&shs->ssbo[start_slot + i], NULL);
1973 pipe_resource_reference(&shs->ssbo_surface_state[start_slot + i].res,
1974 NULL);
1975 }
1976 }
1977
1978 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
1979 }
1980
1981 static void
1982 iris_delete_state(struct pipe_context *ctx, void *state)
1983 {
1984 free(state);
1985 }
1986
1987 static void
1988 iris_free_vertex_buffers(struct iris_vertex_buffer_state *cso)
1989 {
1990 for (unsigned i = 0; i < cso->num_buffers; i++)
1991 pipe_resource_reference(&cso->resources[i], NULL);
1992 }
1993
1994 /**
1995 * The pipe->set_vertex_buffers() driver hook.
1996 *
1997 * This translates pipe_vertex_buffer to our 3DSTATE_VERTEX_BUFFERS packet.
1998 */
1999 static void
2000 iris_set_vertex_buffers(struct pipe_context *ctx,
2001 unsigned start_slot, unsigned count,
2002 const struct pipe_vertex_buffer *buffers)
2003 {
2004 struct iris_context *ice = (struct iris_context *) ctx;
2005 struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
2006
2007 iris_free_vertex_buffers(&ice->state.genx->vertex_buffers);
2008
2009 if (!buffers)
2010 count = 0;
2011
2012 cso->num_buffers = count;
2013
2014 iris_pack_command(GENX(3DSTATE_VERTEX_BUFFERS), cso->vertex_buffers, vb) {
2015 vb.DWordLength = 4 * MAX2(cso->num_buffers, 1) - 1;
2016 }
2017
2018 uint32_t *vb_pack_dest = &cso->vertex_buffers[1];
2019
2020 if (count == 0) {
2021 iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
2022 vb.VertexBufferIndex = start_slot;
2023 vb.NullVertexBuffer = true;
2024 vb.AddressModifyEnable = true;
2025 }
2026 }
2027
2028 for (unsigned i = 0; i < count; i++) {
2029 assert(!buffers[i].is_user_buffer);
2030
2031 pipe_resource_reference(&cso->resources[i], buffers[i].buffer.resource);
2032 struct iris_resource *res = (void *) cso->resources[i];
2033
2034 iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
2035 vb.VertexBufferIndex = start_slot + i;
2036 vb.MOCS = MOCS_WB;
2037 vb.AddressModifyEnable = true;
2038 vb.BufferPitch = buffers[i].stride;
2039 vb.BufferSize = res->bo->size;
2040 vb.BufferStartingAddress =
2041 ro_bo(NULL, res->bo->gtt_offset + buffers[i].buffer_offset);
2042 }
2043
2044 vb_pack_dest += GENX(VERTEX_BUFFER_STATE_length);
2045 }
2046
2047 ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
2048 }
2049
2050 /**
2051 * Gallium CSO for vertex elements.
2052 */
2053 struct iris_vertex_element_state {
2054 uint32_t vertex_elements[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
2055 uint32_t vf_instancing[33 * GENX(3DSTATE_VF_INSTANCING_length)];
2056 unsigned count;
2057 };
2058
2059 /**
2060 * The pipe->create_vertex_elements() driver hook.
2061 *
2062 * This translates pipe_vertex_element to our 3DSTATE_VERTEX_ELEMENTS
2063 * and 3DSTATE_VF_INSTANCING commands. SGVs are handled at draw time.
2064 */
2065 static void *
2066 iris_create_vertex_elements(struct pipe_context *ctx,
2067 unsigned count,
2068 const struct pipe_vertex_element *state)
2069 {
2070 struct iris_vertex_element_state *cso =
2071 malloc(sizeof(struct iris_vertex_element_state));
2072
2073 cso->count = count;
2074
2075 /* TODO:
2076 * - create edge flag one
2077 * - create SGV ones
2078 * - if those are necessary, use count + 1/2/3... OR in the length
2079 */
2080 iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS), cso->vertex_elements, ve) {
2081 ve.DWordLength =
2082 1 + GENX(VERTEX_ELEMENT_STATE_length) * MAX2(count, 1) - 2;
2083 }
2084
2085 uint32_t *ve_pack_dest = &cso->vertex_elements[1];
2086 uint32_t *vfi_pack_dest = cso->vf_instancing;
2087
2088 if (count == 0) {
2089 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
2090 ve.Valid = true;
2091 ve.SourceElementFormat = ISL_FORMAT_R32G32B32A32_FLOAT;
2092 ve.Component0Control = VFCOMP_STORE_0;
2093 ve.Component1Control = VFCOMP_STORE_0;
2094 ve.Component2Control = VFCOMP_STORE_0;
2095 ve.Component3Control = VFCOMP_STORE_1_FP;
2096 }
2097
2098 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
2099 }
2100 }
2101
2102 for (int i = 0; i < count; i++) {
2103 enum isl_format isl_format =
2104 iris_isl_format_for_pipe_format(state[i].src_format);
2105 unsigned comp[4] = { VFCOMP_STORE_SRC, VFCOMP_STORE_SRC,
2106 VFCOMP_STORE_SRC, VFCOMP_STORE_SRC };
2107
2108 switch (isl_format_get_num_channels(isl_format)) {
2109 case 0: comp[0] = VFCOMP_STORE_0;
2110 case 1: comp[1] = VFCOMP_STORE_0;
2111 case 2: comp[2] = VFCOMP_STORE_0;
2112 case 3:
2113 comp[3] = isl_format_has_int_channel(isl_format) ? VFCOMP_STORE_1_INT
2114 : VFCOMP_STORE_1_FP;
2115 break;
2116 }
2117 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
2118 ve.VertexBufferIndex = state[i].vertex_buffer_index;
2119 ve.Valid = true;
2120 ve.SourceElementOffset = state[i].src_offset;
2121 ve.SourceElementFormat = isl_format;
2122 ve.Component0Control = comp[0];
2123 ve.Component1Control = comp[1];
2124 ve.Component2Control = comp[2];
2125 ve.Component3Control = comp[3];
2126 }
2127
2128 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
2129 vi.VertexElementIndex = i;
2130 vi.InstancingEnable = state[i].instance_divisor > 0;
2131 vi.InstanceDataStepRate = state[i].instance_divisor;
2132 }
2133
2134 ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
2135 vfi_pack_dest += GENX(3DSTATE_VF_INSTANCING_length);
2136 }
2137
2138 return cso;
2139 }
2140
2141 /**
2142 * The pipe->bind_vertex_elements_state() driver hook.
2143 */
2144 static void
2145 iris_bind_vertex_elements_state(struct pipe_context *ctx, void *state)
2146 {
2147 struct iris_context *ice = (struct iris_context *) ctx;
2148 struct iris_vertex_element_state *old_cso = ice->state.cso_vertex_elements;
2149 struct iris_vertex_element_state *new_cso = state;
2150
2151 /* 3DSTATE_VF_SGVs overrides the last VE, so if the count is changing,
2152 * we need to re-emit it to ensure we're overriding the right one.
2153 */
2154 if (new_cso && cso_changed(count))
2155 ice->state.dirty |= IRIS_DIRTY_VF_SGVS;
2156
2157 ice->state.cso_vertex_elements = state;
2158 ice->state.dirty |= IRIS_DIRTY_VERTEX_ELEMENTS;
2159 }
2160
2161 /**
2162 * Gallium CSO for stream output (transform feedback) targets.
2163 */
2164 struct iris_stream_output_target {
2165 struct pipe_stream_output_target base;
2166
2167 uint32_t so_buffer[GENX(3DSTATE_SO_BUFFER_length)];
2168
2169 /** Storage holding the offset where we're writing in the buffer */
2170 struct iris_state_ref offset;
2171 };
2172
2173 /**
2174 * The pipe->create_stream_output_target() driver hook.
2175 *
2176 * "Target" here refers to a destination buffer. We translate this into
2177 * a 3DSTATE_SO_BUFFER packet. We can handle most fields, but don't yet
2178 * know which buffer this represents, or whether we ought to zero the
2179 * write-offsets, or append. Those are handled in the set() hook.
2180 */
2181 static struct pipe_stream_output_target *
2182 iris_create_stream_output_target(struct pipe_context *ctx,
2183 struct pipe_resource *res,
2184 unsigned buffer_offset,
2185 unsigned buffer_size)
2186 {
2187 struct iris_stream_output_target *cso = calloc(1, sizeof(*cso));
2188 if (!cso)
2189 return NULL;
2190
2191 pipe_reference_init(&cso->base.reference, 1);
2192 pipe_resource_reference(&cso->base.buffer, res);
2193 cso->base.buffer_offset = buffer_offset;
2194 cso->base.buffer_size = buffer_size;
2195 cso->base.context = ctx;
2196
2197 upload_state(ctx->stream_uploader, &cso->offset, 4 * sizeof(uint32_t), 4);
2198
2199 iris_pack_command(GENX(3DSTATE_SO_BUFFER), cso->so_buffer, sob) {
2200 sob.SurfaceBaseAddress =
2201 rw_bo(NULL, iris_resource_bo(res)->gtt_offset + buffer_offset);
2202 sob.SOBufferEnable = true;
2203 sob.StreamOffsetWriteEnable = true;
2204 sob.StreamOutputBufferOffsetAddressEnable = true;
2205 sob.MOCS = MOCS_WB; // XXX: MOCS
2206
2207 sob.SurfaceSize = MAX2(buffer_size / 4, 1) - 1;
2208
2209 /* .SOBufferIndex, .StreamOffset, and .StreamOutputBufferOffsetAddress
2210 * are filled in later when we have stream IDs.
2211 */
2212 }
2213
2214 return &cso->base;
2215 }
2216
2217 static void
2218 iris_stream_output_target_destroy(struct pipe_context *ctx,
2219 struct pipe_stream_output_target *state)
2220 {
2221 struct iris_stream_output_target *cso = (void *) state;
2222
2223 pipe_resource_reference(&cso->base.buffer, NULL);
2224 pipe_resource_reference(&cso->offset.res, NULL);
2225
2226 free(cso);
2227 }
2228
2229 /**
2230 * The pipe->set_stream_output_targets() driver hook.
2231 *
2232 * At this point, we know which targets are bound to a particular index,
2233 * and also whether we want to append or start over. We can finish the
2234 * 3DSTATE_SO_BUFFER packets we started earlier.
2235 */
2236 static void
2237 iris_set_stream_output_targets(struct pipe_context *ctx,
2238 unsigned num_targets,
2239 struct pipe_stream_output_target **targets,
2240 const unsigned *offsets)
2241 {
2242 struct iris_context *ice = (struct iris_context *) ctx;
2243 struct iris_genx_state *genx = ice->state.genx;
2244 uint32_t *so_buffers = genx->so_buffers;
2245
2246 const bool active = num_targets > 0;
2247 if (ice->state.streamout_active != active) {
2248 ice->state.streamout_active = active;
2249 ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
2250 }
2251
2252 for (int i = 0; i < 4; i++) {
2253 pipe_so_target_reference(&ice->state.so_target[i],
2254 i < num_targets ? targets[i] : NULL);
2255 }
2256
2257 /* No need to update 3DSTATE_SO_BUFFER unless SOL is active. */
2258 if (!active)
2259 return;
2260
2261 for (unsigned i = 0; i < 4; i++,
2262 so_buffers += GENX(3DSTATE_SO_BUFFER_length)) {
2263
2264 if (i >= num_targets || !targets[i]) {
2265 iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob)
2266 sob.SOBufferIndex = i;
2267 continue;
2268 }
2269
2270 struct iris_stream_output_target *tgt = (void *) targets[i];
2271
2272 /* Note that offsets[i] will either be 0, causing us to zero
2273 * the value in the buffer, or 0xFFFFFFFF, which happens to mean
2274 * "continue appending at the existing offset."
2275 */
2276 assert(offsets[i] == 0 || offsets[i] == 0xFFFFFFFF);
2277
2278 uint32_t dynamic[GENX(3DSTATE_SO_BUFFER_length)];
2279 iris_pack_state(GENX(3DSTATE_SO_BUFFER), dynamic, dyns) {
2280 dyns.SOBufferIndex = i;
2281 dyns.StreamOffset = offsets[i];
2282 dyns.StreamOutputBufferOffsetAddress =
2283 rw_bo(NULL, iris_resource_bo(tgt->offset.res)->gtt_offset + tgt->offset.offset + i * sizeof(uint32_t));
2284 }
2285
2286 for (uint32_t j = 0; j < GENX(3DSTATE_SO_BUFFER_length); j++) {
2287 so_buffers[j] = tgt->so_buffer[j] | dynamic[j];
2288 }
2289 }
2290
2291 ice->state.dirty |= IRIS_DIRTY_SO_BUFFERS;
2292 }
2293
2294 /**
2295 * An iris-vtable helper for encoding the 3DSTATE_SO_DECL_LIST and
2296 * 3DSTATE_STREAMOUT packets.
2297 *
2298 * 3DSTATE_SO_DECL_LIST is a list of shader outputs we want the streamout
2299 * hardware to record. We can create it entirely based on the shader, with
2300 * no dynamic state dependencies.
2301 *
2302 * 3DSTATE_STREAMOUT is an annoying mix of shader-based information and
2303 * state-based settings. We capture the shader-related ones here, and merge
2304 * the rest in at draw time.
2305 */
2306 static uint32_t *
2307 iris_create_so_decl_list(const struct pipe_stream_output_info *info,
2308 const struct brw_vue_map *vue_map)
2309 {
2310 struct GENX(SO_DECL) so_decl[MAX_VERTEX_STREAMS][128];
2311 int buffer_mask[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
2312 int next_offset[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
2313 int decls[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
2314 int max_decls = 0;
2315 STATIC_ASSERT(ARRAY_SIZE(so_decl[0]) >= MAX_PROGRAM_OUTPUTS);
2316
2317 memset(so_decl, 0, sizeof(so_decl));
2318
2319 /* Construct the list of SO_DECLs to be emitted. The formatting of the
2320 * command feels strange -- each dword pair contains a SO_DECL per stream.
2321 */
2322 for (unsigned i = 0; i < info->num_outputs; i++) {
2323 const struct pipe_stream_output *output = &info->output[i];
2324 const int buffer = output->output_buffer;
2325 const int varying = output->register_index;
2326 const unsigned stream_id = output->stream;
2327 assert(stream_id < MAX_VERTEX_STREAMS);
2328
2329 buffer_mask[stream_id] |= 1 << buffer;
2330
2331 assert(vue_map->varying_to_slot[varying] >= 0);
2332
2333 /* Mesa doesn't store entries for gl_SkipComponents in the Outputs[]
2334 * array. Instead, it simply increments DstOffset for the following
2335 * input by the number of components that should be skipped.
2336 *
2337 * Our hardware is unusual in that it requires us to program SO_DECLs
2338 * for fake "hole" components, rather than simply taking the offset
2339 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
2340 * program as many size = 4 holes as we can, then a final hole to
2341 * accommodate the final 1, 2, or 3 remaining.
2342 */
2343 int skip_components = output->dst_offset - next_offset[buffer];
2344
2345 while (skip_components > 0) {
2346 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
2347 .HoleFlag = 1,
2348 .OutputBufferSlot = output->output_buffer,
2349 .ComponentMask = (1 << MIN2(skip_components, 4)) - 1,
2350 };
2351 skip_components -= 4;
2352 }
2353
2354 next_offset[buffer] = output->dst_offset + output->num_components;
2355
2356 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
2357 .OutputBufferSlot = output->output_buffer,
2358 .RegisterIndex = vue_map->varying_to_slot[varying],
2359 .ComponentMask =
2360 ((1 << output->num_components) - 1) << output->start_component,
2361 };
2362
2363 if (decls[stream_id] > max_decls)
2364 max_decls = decls[stream_id];
2365 }
2366
2367 unsigned dwords = GENX(3DSTATE_STREAMOUT_length) + (3 + 2 * max_decls);
2368 uint32_t *map = ralloc_size(NULL, sizeof(uint32_t) * dwords);
2369 uint32_t *so_decl_map = map + GENX(3DSTATE_STREAMOUT_length);
2370
2371 iris_pack_command(GENX(3DSTATE_STREAMOUT), map, sol) {
2372 int urb_entry_read_offset = 0;
2373 int urb_entry_read_length = (vue_map->num_slots + 1) / 2 -
2374 urb_entry_read_offset;
2375
2376 /* We always read the whole vertex. This could be reduced at some
2377 * point by reading less and offsetting the register index in the
2378 * SO_DECLs.
2379 */
2380 sol.Stream0VertexReadOffset = urb_entry_read_offset;
2381 sol.Stream0VertexReadLength = urb_entry_read_length - 1;
2382 sol.Stream1VertexReadOffset = urb_entry_read_offset;
2383 sol.Stream1VertexReadLength = urb_entry_read_length - 1;
2384 sol.Stream2VertexReadOffset = urb_entry_read_offset;
2385 sol.Stream2VertexReadLength = urb_entry_read_length - 1;
2386 sol.Stream3VertexReadOffset = urb_entry_read_offset;
2387 sol.Stream3VertexReadLength = urb_entry_read_length - 1;
2388
2389 /* Set buffer pitches; 0 means unbound. */
2390 sol.Buffer0SurfacePitch = 4 * info->stride[0];
2391 sol.Buffer1SurfacePitch = 4 * info->stride[1];
2392 sol.Buffer2SurfacePitch = 4 * info->stride[2];
2393 sol.Buffer3SurfacePitch = 4 * info->stride[3];
2394 }
2395
2396 iris_pack_command(GENX(3DSTATE_SO_DECL_LIST), so_decl_map, list) {
2397 list.DWordLength = 3 + 2 * max_decls - 2;
2398 list.StreamtoBufferSelects0 = buffer_mask[0];
2399 list.StreamtoBufferSelects1 = buffer_mask[1];
2400 list.StreamtoBufferSelects2 = buffer_mask[2];
2401 list.StreamtoBufferSelects3 = buffer_mask[3];
2402 list.NumEntries0 = decls[0];
2403 list.NumEntries1 = decls[1];
2404 list.NumEntries2 = decls[2];
2405 list.NumEntries3 = decls[3];
2406 }
2407
2408 for (int i = 0; i < max_decls; i++) {
2409 iris_pack_state(GENX(SO_DECL_ENTRY), so_decl_map + 3 + i * 2, entry) {
2410 entry.Stream0Decl = so_decl[0][i];
2411 entry.Stream1Decl = so_decl[1][i];
2412 entry.Stream2Decl = so_decl[2][i];
2413 entry.Stream3Decl = so_decl[3][i];
2414 }
2415 }
2416
2417 return map;
2418 }
2419
2420 static void
2421 iris_compute_sbe_urb_read_interval(uint64_t fs_input_slots,
2422 const struct brw_vue_map *last_vue_map,
2423 bool two_sided_color,
2424 unsigned *out_offset,
2425 unsigned *out_length)
2426 {
2427 /* The compiler computes the first URB slot without considering COL/BFC
2428 * swizzling (because it doesn't know whether it's enabled), so we need
2429 * to do that here too. This may result in a smaller offset, which
2430 * should be safe.
2431 */
2432 const unsigned first_slot =
2433 brw_compute_first_urb_slot_required(fs_input_slots, last_vue_map);
2434
2435 /* This becomes the URB read offset (counted in pairs of slots). */
2436 assert(first_slot % 2 == 0);
2437 *out_offset = first_slot / 2;
2438
2439 /* We need to adjust the inputs read to account for front/back color
2440 * swizzling, as it can make the URB length longer.
2441 */
2442 for (int c = 0; c <= 1; c++) {
2443 if (fs_input_slots & (VARYING_BIT_COL0 << c)) {
2444 /* If two sided color is enabled, the fragment shader's gl_Color
2445 * (COL0) input comes from either the gl_FrontColor (COL0) or
2446 * gl_BackColor (BFC0) input varyings. Mark BFC as used, too.
2447 */
2448 if (two_sided_color)
2449 fs_input_slots |= (VARYING_BIT_BFC0 << c);
2450
2451 /* If front color isn't written, we opt to give them back color
2452 * instead of an undefined value. Switch from COL to BFC.
2453 */
2454 if (last_vue_map->varying_to_slot[VARYING_SLOT_COL0 + c] == -1) {
2455 fs_input_slots &= ~(VARYING_BIT_COL0 << c);
2456 fs_input_slots |= (VARYING_BIT_BFC0 << c);
2457 }
2458 }
2459 }
2460
2461 /* Compute the minimum URB Read Length necessary for the FS inputs.
2462 *
2463 * From the Sandy Bridge PRM, Volume 2, Part 1, documentation for
2464 * 3DSTATE_SF DWord 1 bits 15:11, "Vertex URB Entry Read Length":
2465 *
2466 * "This field should be set to the minimum length required to read the
2467 * maximum source attribute. The maximum source attribute is indicated
2468 * by the maximum value of the enabled Attribute # Source Attribute if
2469 * Attribute Swizzle Enable is set, Number of Output Attributes-1 if
2470 * enable is not set.
2471 * read_length = ceiling((max_source_attr + 1) / 2)
2472 *
2473 * [errata] Corruption/Hang possible if length programmed larger than
2474 * recommended"
2475 *
2476 * Similar text exists for Ivy Bridge.
2477 *
2478 * We find the last URB slot that's actually read by the FS.
2479 */
2480 unsigned last_read_slot = last_vue_map->num_slots - 1;
2481 while (last_read_slot > first_slot && !(fs_input_slots &
2482 (1ull << last_vue_map->slot_to_varying[last_read_slot])))
2483 --last_read_slot;
2484
2485 /* The URB read length is the difference of the two, counted in pairs. */
2486 *out_length = DIV_ROUND_UP(last_read_slot - first_slot + 1, 2);
2487 }
2488
2489 static void
2490 iris_emit_sbe_swiz(struct iris_batch *batch,
2491 const struct iris_context *ice,
2492 unsigned urb_read_offset,
2493 unsigned sprite_coord_enables)
2494 {
2495 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) attr_overrides[16] = {};
2496 const struct brw_wm_prog_data *wm_prog_data = (void *)
2497 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
2498 const struct brw_vue_map *vue_map = ice->shaders.last_vue_map;
2499 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
2500
2501 /* XXX: this should be generated when putting programs in place */
2502
2503 // XXX: raster->sprite_coord_enable
2504
2505 for (int fs_attr = 0; fs_attr < VARYING_SLOT_MAX; fs_attr++) {
2506 const int input_index = wm_prog_data->urb_setup[fs_attr];
2507 if (input_index < 0 || input_index >= 16)
2508 continue;
2509
2510 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) *attr =
2511 &attr_overrides[input_index];
2512 int slot = vue_map->varying_to_slot[fs_attr];
2513
2514 /* Viewport and Layer are stored in the VUE header. We need to override
2515 * them to zero if earlier stages didn't write them, as GL requires that
2516 * they read back as zero when not explicitly set.
2517 */
2518 switch (fs_attr) {
2519 case VARYING_SLOT_VIEWPORT:
2520 case VARYING_SLOT_LAYER:
2521 attr->ComponentOverrideX = true;
2522 attr->ComponentOverrideW = true;
2523 attr->ConstantSource = CONST_0000;
2524
2525 if (!(vue_map->slots_valid & VARYING_BIT_LAYER))
2526 attr->ComponentOverrideY = true;
2527 if (!(vue_map->slots_valid & VARYING_BIT_VIEWPORT))
2528 attr->ComponentOverrideZ = true;
2529 continue;
2530
2531 case VARYING_SLOT_PRIMITIVE_ID:
2532 /* Override if the previous shader stage didn't write gl_PrimitiveID. */
2533 if (slot == -1) {
2534 attr->ComponentOverrideX = true;
2535 attr->ComponentOverrideY = true;
2536 attr->ComponentOverrideZ = true;
2537 attr->ComponentOverrideW = true;
2538 attr->ConstantSource = PRIM_ID;
2539 continue;
2540 }
2541
2542 default:
2543 break;
2544 }
2545
2546 if (sprite_coord_enables & (1 << input_index))
2547 continue;
2548
2549 /* If there was only a back color written but not front, use back
2550 * as the color instead of undefined.
2551 */
2552 if (slot == -1 && fs_attr == VARYING_SLOT_COL0)
2553 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC0];
2554 if (slot == -1 && fs_attr == VARYING_SLOT_COL1)
2555 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC1];
2556
2557 /* Not written by the previous stage - undefined. */
2558 if (slot == -1) {
2559 attr->ComponentOverrideX = true;
2560 attr->ComponentOverrideY = true;
2561 attr->ComponentOverrideZ = true;
2562 attr->ComponentOverrideW = true;
2563 attr->ConstantSource = CONST_0001_FLOAT;
2564 continue;
2565 }
2566
2567 /* Compute the location of the attribute relative to the read offset,
2568 * which is counted in 256-bit increments (two 128-bit VUE slots).
2569 */
2570 const int source_attr = slot - 2 * urb_read_offset;
2571 assert(source_attr >= 0 && source_attr <= 32);
2572 attr->SourceAttribute = source_attr;
2573
2574 /* If we are doing two-sided color, and the VUE slot following this one
2575 * represents a back-facing color, then we need to instruct the SF unit
2576 * to do back-facing swizzling.
2577 */
2578 if (cso_rast->light_twoside &&
2579 ((vue_map->slot_to_varying[slot] == VARYING_SLOT_COL0 &&
2580 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC0) ||
2581 (vue_map->slot_to_varying[slot] == VARYING_SLOT_COL1 &&
2582 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC1)))
2583 attr->SwizzleSelect = INPUTATTR_FACING;
2584 }
2585
2586 iris_emit_cmd(batch, GENX(3DSTATE_SBE_SWIZ), sbes) {
2587 for (int i = 0; i < 16; i++)
2588 sbes.Attribute[i] = attr_overrides[i];
2589 }
2590 }
2591
2592 static unsigned
2593 iris_calculate_point_sprite_overrides(const struct brw_wm_prog_data *prog_data,
2594 const struct iris_rasterizer_state *cso)
2595 {
2596 unsigned overrides = 0;
2597
2598 if (prog_data->urb_setup[VARYING_SLOT_PNTC] != -1)
2599 overrides |= 1 << prog_data->urb_setup[VARYING_SLOT_PNTC];
2600
2601 for (int i = 0; i < 8; i++) {
2602 if ((cso->sprite_coord_enable & (1 << i)) &&
2603 prog_data->urb_setup[VARYING_SLOT_TEX0 + i] != -1)
2604 overrides |= 1 << prog_data->urb_setup[VARYING_SLOT_TEX0 + i];
2605 }
2606
2607 return overrides;
2608 }
2609
2610 static void
2611 iris_emit_sbe(struct iris_batch *batch, const struct iris_context *ice)
2612 {
2613 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
2614 const struct brw_wm_prog_data *wm_prog_data = (void *)
2615 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
2616 const struct shader_info *fs_info =
2617 iris_get_shader_info(ice, MESA_SHADER_FRAGMENT);
2618
2619 unsigned urb_read_offset, urb_read_length;
2620 iris_compute_sbe_urb_read_interval(fs_info->inputs_read,
2621 ice->shaders.last_vue_map,
2622 cso_rast->light_twoside,
2623 &urb_read_offset, &urb_read_length);
2624
2625 unsigned sprite_coord_overrides =
2626 iris_calculate_point_sprite_overrides(wm_prog_data, cso_rast);
2627
2628 iris_emit_cmd(batch, GENX(3DSTATE_SBE), sbe) {
2629 sbe.AttributeSwizzleEnable = true;
2630 sbe.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
2631 sbe.PointSpriteTextureCoordinateOrigin = cso_rast->sprite_coord_mode;
2632 sbe.VertexURBEntryReadOffset = urb_read_offset;
2633 sbe.VertexURBEntryReadLength = urb_read_length;
2634 sbe.ForceVertexURBEntryReadOffset = true;
2635 sbe.ForceVertexURBEntryReadLength = true;
2636 sbe.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
2637 sbe.PointSpriteTextureCoordinateEnable = sprite_coord_overrides;
2638
2639 for (int i = 0; i < 32; i++) {
2640 sbe.AttributeActiveComponentFormat[i] = ACTIVE_COMPONENT_XYZW;
2641 }
2642 }
2643
2644 iris_emit_sbe_swiz(batch, ice, urb_read_offset, sprite_coord_overrides);
2645 }
2646
2647 /* ------------------------------------------------------------------- */
2648
2649 /**
2650 * Set sampler-related program key fields based on the current state.
2651 */
2652 static void
2653 iris_populate_sampler_key(const struct iris_context *ice,
2654 struct brw_sampler_prog_key_data *key)
2655 {
2656 for (int i = 0; i < MAX_SAMPLERS; i++) {
2657 key->swizzles[i] = 0x688; /* XYZW */
2658 }
2659 }
2660
2661 /**
2662 * Populate VS program key fields based on the current state.
2663 */
2664 static void
2665 iris_populate_vs_key(const struct iris_context *ice,
2666 struct brw_vs_prog_key *key)
2667 {
2668 iris_populate_sampler_key(ice, &key->tex);
2669 }
2670
2671 /**
2672 * Populate TCS program key fields based on the current state.
2673 */
2674 static void
2675 iris_populate_tcs_key(const struct iris_context *ice,
2676 struct brw_tcs_prog_key *key)
2677 {
2678 iris_populate_sampler_key(ice, &key->tex);
2679 }
2680
2681 /**
2682 * Populate TES program key fields based on the current state.
2683 */
2684 static void
2685 iris_populate_tes_key(const struct iris_context *ice,
2686 struct brw_tes_prog_key *key)
2687 {
2688 iris_populate_sampler_key(ice, &key->tex);
2689 }
2690
2691 /**
2692 * Populate GS program key fields based on the current state.
2693 */
2694 static void
2695 iris_populate_gs_key(const struct iris_context *ice,
2696 struct brw_gs_prog_key *key)
2697 {
2698 iris_populate_sampler_key(ice, &key->tex);
2699 }
2700
2701 /**
2702 * Populate FS program key fields based on the current state.
2703 */
2704 static void
2705 iris_populate_fs_key(const struct iris_context *ice,
2706 struct brw_wm_prog_key *key)
2707 {
2708 iris_populate_sampler_key(ice, &key->tex);
2709
2710 /* XXX: dirty flags? */
2711 const struct pipe_framebuffer_state *fb = &ice->state.framebuffer;
2712 const struct iris_depth_stencil_alpha_state *zsa = ice->state.cso_zsa;
2713 const struct iris_rasterizer_state *rast = ice->state.cso_rast;
2714 const struct iris_blend_state *blend = ice->state.cso_blend;
2715
2716 key->nr_color_regions = fb->nr_cbufs;
2717
2718 key->clamp_fragment_color = rast->clamp_fragment_color;
2719
2720 key->replicate_alpha = fb->nr_cbufs > 1 &&
2721 (zsa->alpha.enabled || blend->alpha_to_coverage);
2722
2723 /* XXX: only bother if COL0/1 are read */
2724 key->flat_shade = rast->flatshade;
2725
2726 key->persample_interp = rast->force_persample_interp;
2727 key->multisample_fbo = rast->multisample && fb->samples > 1;
2728
2729 key->coherent_fb_fetch = true;
2730
2731 // XXX: uint64_t input_slots_valid; - for >16 inputs
2732
2733 // XXX: key->force_dual_color_blend for unigine
2734 // XXX: respect hint for high_quality_derivatives:1;
2735 }
2736
2737 #if 0
2738 // XXX: these need to go in INIT_THREAD_DISPATCH_FIELDS
2739 pkt.SamplerCount = \
2740 DIV_ROUND_UP(CLAMP(stage_state->sampler_count, 0, 16), 4); \
2741 pkt.PerThreadScratchSpace = prog_data->total_scratch == 0 ? 0 : \
2742 ffs(stage_state->per_thread_scratch) - 11; \
2743
2744 #endif
2745
2746 static uint64_t
2747 KSP(const struct iris_compiled_shader *shader)
2748 {
2749 struct iris_resource *res = (void *) shader->assembly.res;
2750 return iris_bo_offset_from_base_address(res->bo) + shader->assembly.offset;
2751 }
2752
2753 // Gen11 workaround table #2056 WABTPPrefetchDisable suggests to disable
2754 // prefetching of binding tables in A0 and B0 steppings. XXX: Revisit
2755 // this WA on C0 stepping.
2756
2757 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix) \
2758 pkt.KernelStartPointer = KSP(shader); \
2759 pkt.BindingTableEntryCount = GEN_GEN == 11 ? 0 : \
2760 prog_data->binding_table.size_bytes / 4; \
2761 pkt.FloatingPointMode = prog_data->use_alt_mode; \
2762 \
2763 pkt.DispatchGRFStartRegisterForURBData = \
2764 prog_data->dispatch_grf_start_reg; \
2765 pkt.prefix##URBEntryReadLength = vue_prog_data->urb_read_length; \
2766 pkt.prefix##URBEntryReadOffset = 0; \
2767 \
2768 pkt.StatisticsEnable = true; \
2769 pkt.Enable = true;
2770
2771 /**
2772 * Encode most of 3DSTATE_VS based on the compiled shader.
2773 */
2774 static void
2775 iris_store_vs_state(const struct gen_device_info *devinfo,
2776 struct iris_compiled_shader *shader)
2777 {
2778 struct brw_stage_prog_data *prog_data = shader->prog_data;
2779 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2780
2781 iris_pack_command(GENX(3DSTATE_VS), shader->derived_data, vs) {
2782 INIT_THREAD_DISPATCH_FIELDS(vs, Vertex);
2783 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
2784 vs.SIMD8DispatchEnable = true;
2785 vs.UserClipDistanceCullTestEnableBitmask =
2786 vue_prog_data->cull_distance_mask;
2787 }
2788 }
2789
2790 /**
2791 * Encode most of 3DSTATE_HS based on the compiled shader.
2792 */
2793 static void
2794 iris_store_tcs_state(const struct gen_device_info *devinfo,
2795 struct iris_compiled_shader *shader)
2796 {
2797 struct brw_stage_prog_data *prog_data = shader->prog_data;
2798 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2799 struct brw_tcs_prog_data *tcs_prog_data = (void *) prog_data;
2800
2801 iris_pack_command(GENX(3DSTATE_HS), shader->derived_data, hs) {
2802 INIT_THREAD_DISPATCH_FIELDS(hs, Vertex);
2803
2804 hs.InstanceCount = tcs_prog_data->instances - 1;
2805 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
2806 hs.IncludeVertexHandles = true;
2807 }
2808 }
2809
2810 /**
2811 * Encode 3DSTATE_TE and most of 3DSTATE_DS based on the compiled shader.
2812 */
2813 static void
2814 iris_store_tes_state(const struct gen_device_info *devinfo,
2815 struct iris_compiled_shader *shader)
2816 {
2817 struct brw_stage_prog_data *prog_data = shader->prog_data;
2818 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2819 struct brw_tes_prog_data *tes_prog_data = (void *) prog_data;
2820
2821 uint32_t *te_state = (void *) shader->derived_data;
2822 uint32_t *ds_state = te_state + GENX(3DSTATE_TE_length);
2823
2824 iris_pack_command(GENX(3DSTATE_TE), te_state, te) {
2825 te.Partitioning = tes_prog_data->partitioning;
2826 te.OutputTopology = tes_prog_data->output_topology;
2827 te.TEDomain = tes_prog_data->domain;
2828 te.TEEnable = true;
2829 te.MaximumTessellationFactorOdd = 63.0;
2830 te.MaximumTessellationFactorNotOdd = 64.0;
2831 }
2832
2833 iris_pack_command(GENX(3DSTATE_DS), ds_state, ds) {
2834 INIT_THREAD_DISPATCH_FIELDS(ds, Patch);
2835
2836 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
2837 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
2838 ds.ComputeWCoordinateEnable =
2839 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
2840
2841 ds.UserClipDistanceCullTestEnableBitmask =
2842 vue_prog_data->cull_distance_mask;
2843 }
2844
2845 }
2846
2847 /**
2848 * Encode most of 3DSTATE_GS based on the compiled shader.
2849 */
2850 static void
2851 iris_store_gs_state(const struct gen_device_info *devinfo,
2852 struct iris_compiled_shader *shader)
2853 {
2854 struct brw_stage_prog_data *prog_data = shader->prog_data;
2855 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2856 struct brw_gs_prog_data *gs_prog_data = (void *) prog_data;
2857
2858 iris_pack_command(GENX(3DSTATE_GS), shader->derived_data, gs) {
2859 INIT_THREAD_DISPATCH_FIELDS(gs, Vertex);
2860
2861 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
2862 gs.OutputTopology = gs_prog_data->output_topology;
2863 gs.ControlDataHeaderSize =
2864 gs_prog_data->control_data_header_size_hwords;
2865 gs.InstanceControl = gs_prog_data->invocations - 1;
2866 gs.DispatchMode = DISPATCH_MODE_SIMD8;
2867 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
2868 gs.ControlDataFormat = gs_prog_data->control_data_format;
2869 gs.ReorderMode = TRAILING;
2870 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
2871 gs.MaximumNumberofThreads =
2872 GEN_GEN == 8 ? (devinfo->max_gs_threads / 2 - 1)
2873 : (devinfo->max_gs_threads - 1);
2874
2875 if (gs_prog_data->static_vertex_count != -1) {
2876 gs.StaticOutput = true;
2877 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count;
2878 }
2879 gs.IncludeVertexHandles = vue_prog_data->include_vue_handles;
2880
2881 gs.UserClipDistanceCullTestEnableBitmask =
2882 vue_prog_data->cull_distance_mask;
2883
2884 const int urb_entry_write_offset = 1;
2885 const uint32_t urb_entry_output_length =
2886 DIV_ROUND_UP(vue_prog_data->vue_map.num_slots, 2) -
2887 urb_entry_write_offset;
2888
2889 gs.VertexURBEntryOutputReadOffset = urb_entry_write_offset;
2890 gs.VertexURBEntryOutputLength = MAX2(urb_entry_output_length, 1);
2891 }
2892 }
2893
2894 /**
2895 * Encode most of 3DSTATE_PS and 3DSTATE_PS_EXTRA based on the shader.
2896 */
2897 static void
2898 iris_store_fs_state(const struct gen_device_info *devinfo,
2899 struct iris_compiled_shader *shader)
2900 {
2901 struct brw_stage_prog_data *prog_data = shader->prog_data;
2902 struct brw_wm_prog_data *wm_prog_data = (void *) shader->prog_data;
2903
2904 uint32_t *ps_state = (void *) shader->derived_data;
2905 uint32_t *psx_state = ps_state + GENX(3DSTATE_PS_length);
2906
2907 iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
2908 ps.VectorMaskEnable = true;
2909 //ps.SamplerCount = ...
2910 // XXX: WABTPPrefetchDisable, see above, drop at C0
2911 ps.BindingTableEntryCount = GEN_GEN == 11 ? 0 :
2912 prog_data->binding_table.size_bytes / 4;
2913 ps.FloatingPointMode = prog_data->use_alt_mode;
2914 ps.MaximumNumberofThreadsPerPSD = 64 - (GEN_GEN == 8 ? 2 : 1);
2915
2916 ps.PushConstantEnable = prog_data->nr_params > 0 ||
2917 prog_data->ubo_ranges[0].length > 0;
2918
2919 /* From the documentation for this packet:
2920 * "If the PS kernel does not need the Position XY Offsets to
2921 * compute a Position Value, then this field should be programmed
2922 * to POSOFFSET_NONE."
2923 *
2924 * "SW Recommendation: If the PS kernel needs the Position Offsets
2925 * to compute a Position XY value, this field should match Position
2926 * ZW Interpolation Mode to ensure a consistent position.xyzw
2927 * computation."
2928 *
2929 * We only require XY sample offsets. So, this recommendation doesn't
2930 * look useful at the moment. We might need this in future.
2931 */
2932 ps.PositionXYOffsetSelect =
2933 wm_prog_data->uses_pos_offset ? POSOFFSET_SAMPLE : POSOFFSET_NONE;
2934 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
2935 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
2936 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
2937
2938 // XXX: Disable SIMD32 with 16x MSAA
2939
2940 ps.DispatchGRFStartRegisterForConstantSetupData0 =
2941 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
2942 ps.DispatchGRFStartRegisterForConstantSetupData1 =
2943 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
2944 ps.DispatchGRFStartRegisterForConstantSetupData2 =
2945 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
2946
2947 ps.KernelStartPointer0 =
2948 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
2949 ps.KernelStartPointer1 =
2950 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
2951 ps.KernelStartPointer2 =
2952 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
2953 }
2954
2955 iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
2956 psx.PixelShaderValid = true;
2957 psx.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
2958 psx.PixelShaderKillsPixel = wm_prog_data->uses_kill;
2959 psx.AttributeEnable = wm_prog_data->num_varying_inputs != 0;
2960 psx.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
2961 psx.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
2962 psx.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
2963
2964 if (wm_prog_data->uses_sample_mask) {
2965 /* TODO: conservative rasterization */
2966 if (wm_prog_data->post_depth_coverage)
2967 psx.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
2968 else
2969 psx.InputCoverageMaskState = ICMS_NORMAL;
2970 }
2971
2972 psx.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
2973 psx.PixelShaderPullsBary = wm_prog_data->pulls_bary;
2974 psx.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
2975
2976 // XXX: UAV bit
2977 }
2978 }
2979
2980 /**
2981 * Compute the size of the derived data (shader command packets).
2982 *
2983 * This must match the data written by the iris_store_xs_state() functions.
2984 */
2985 static unsigned
2986 iris_derived_program_state_size(enum iris_program_cache_id cache_id)
2987 {
2988 assert(cache_id <= IRIS_CACHE_BLORP);
2989
2990 static const unsigned dwords[] = {
2991 [IRIS_CACHE_VS] = GENX(3DSTATE_VS_length),
2992 [IRIS_CACHE_TCS] = GENX(3DSTATE_HS_length),
2993 [IRIS_CACHE_TES] = GENX(3DSTATE_TE_length) + GENX(3DSTATE_DS_length),
2994 [IRIS_CACHE_GS] = GENX(3DSTATE_GS_length),
2995 [IRIS_CACHE_FS] =
2996 GENX(3DSTATE_PS_length) + GENX(3DSTATE_PS_EXTRA_length),
2997 [IRIS_CACHE_CS] = 0,
2998 [IRIS_CACHE_BLORP] = 0,
2999 };
3000
3001 return sizeof(uint32_t) * dwords[cache_id];
3002 }
3003
3004 /**
3005 * Create any state packets corresponding to the given shader stage
3006 * (i.e. 3DSTATE_VS) and save them as "derived data" in the shader variant.
3007 * This means that we can look up a program in the in-memory cache and
3008 * get most of the state packet without having to reconstruct it.
3009 */
3010 static void
3011 iris_store_derived_program_state(const struct gen_device_info *devinfo,
3012 enum iris_program_cache_id cache_id,
3013 struct iris_compiled_shader *shader)
3014 {
3015 switch (cache_id) {
3016 case IRIS_CACHE_VS:
3017 iris_store_vs_state(devinfo, shader);
3018 break;
3019 case IRIS_CACHE_TCS:
3020 iris_store_tcs_state(devinfo, shader);
3021 break;
3022 case IRIS_CACHE_TES:
3023 iris_store_tes_state(devinfo, shader);
3024 break;
3025 case IRIS_CACHE_GS:
3026 iris_store_gs_state(devinfo, shader);
3027 break;
3028 case IRIS_CACHE_FS:
3029 iris_store_fs_state(devinfo, shader);
3030 break;
3031 case IRIS_CACHE_CS:
3032 case IRIS_CACHE_BLORP:
3033 break;
3034 default:
3035 break;
3036 }
3037 }
3038
3039 /* ------------------------------------------------------------------- */
3040
3041 /**
3042 * Configure the URB.
3043 *
3044 * XXX: write a real comment.
3045 */
3046 static void
3047 iris_upload_urb_config(struct iris_context *ice, struct iris_batch *batch)
3048 {
3049 const struct gen_device_info *devinfo = &batch->screen->devinfo;
3050 const unsigned push_size_kB = 32;
3051 unsigned entries[4];
3052 unsigned start[4];
3053 unsigned size[4];
3054
3055 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
3056 if (!ice->shaders.prog[i]) {
3057 size[i] = 1;
3058 } else {
3059 struct brw_vue_prog_data *vue_prog_data =
3060 (void *) ice->shaders.prog[i]->prog_data;
3061 size[i] = vue_prog_data->urb_entry_size;
3062 }
3063 assert(size[i] != 0);
3064 }
3065
3066 gen_get_urb_config(devinfo, 1024 * push_size_kB,
3067 1024 * ice->shaders.urb_size,
3068 ice->shaders.prog[MESA_SHADER_TESS_EVAL] != NULL,
3069 ice->shaders.prog[MESA_SHADER_GEOMETRY] != NULL,
3070 size, entries, start);
3071
3072 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
3073 iris_emit_cmd(batch, GENX(3DSTATE_URB_VS), urb) {
3074 urb._3DCommandSubOpcode += i;
3075 urb.VSURBStartingAddress = start[i];
3076 urb.VSURBEntryAllocationSize = size[i] - 1;
3077 urb.VSNumberofURBEntries = entries[i];
3078 }
3079 }
3080 }
3081
3082 static const uint32_t push_constant_opcodes[] = {
3083 [MESA_SHADER_VERTEX] = 21,
3084 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
3085 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
3086 [MESA_SHADER_GEOMETRY] = 22,
3087 [MESA_SHADER_FRAGMENT] = 23,
3088 [MESA_SHADER_COMPUTE] = 0,
3089 };
3090
3091 /**
3092 * Add a surface to the validation list, as well as the buffer containing
3093 * the corresponding SURFACE_STATE.
3094 *
3095 * Returns the binding table entry (offset to SURFACE_STATE).
3096 */
3097 static uint32_t
3098 use_surface(struct iris_batch *batch,
3099 struct pipe_surface *p_surf,
3100 bool writeable)
3101 {
3102 struct iris_surface *surf = (void *) p_surf;
3103
3104 iris_use_pinned_bo(batch, iris_resource_bo(p_surf->texture), writeable);
3105 iris_use_pinned_bo(batch, iris_resource_bo(surf->surface_state.res), false);
3106
3107 return surf->surface_state.offset;
3108 }
3109
3110 static uint32_t
3111 use_sampler_view(struct iris_batch *batch, struct iris_sampler_view *isv)
3112 {
3113 iris_use_pinned_bo(batch, isv->res->bo, false);
3114 iris_use_pinned_bo(batch, iris_resource_bo(isv->surface_state.res), false);
3115
3116 return isv->surface_state.offset;
3117 }
3118
3119 static uint32_t
3120 use_const_buffer(struct iris_batch *batch, struct iris_const_buffer *cbuf)
3121 {
3122 iris_use_pinned_bo(batch, iris_resource_bo(cbuf->data.res), false);
3123 iris_use_pinned_bo(batch, iris_resource_bo(cbuf->surface_state.res), false);
3124
3125 return cbuf->surface_state.offset;
3126 }
3127
3128 static uint32_t
3129 use_null_surface(struct iris_batch *batch, struct iris_context *ice)
3130 {
3131 struct iris_bo *state_bo = iris_resource_bo(ice->state.unbound_tex.res);
3132
3133 iris_use_pinned_bo(batch, state_bo, false);
3134
3135 return ice->state.unbound_tex.offset;
3136 }
3137
3138 static uint32_t
3139 use_null_fb_surface(struct iris_batch *batch, struct iris_context *ice)
3140 {
3141 struct iris_bo *state_bo = iris_resource_bo(ice->state.null_fb.res);
3142
3143 iris_use_pinned_bo(batch, state_bo, false);
3144
3145 return ice->state.null_fb.offset;
3146 }
3147
3148 static uint32_t
3149 use_ssbo(struct iris_batch *batch, struct iris_context *ice,
3150 struct iris_shader_state *shs, int i)
3151 {
3152 if (!shs->ssbo[i])
3153 return use_null_surface(batch, ice);
3154
3155 struct iris_state_ref *surf_state = &shs->ssbo_surface_state[i];
3156
3157 iris_use_pinned_bo(batch, iris_resource_bo(shs->ssbo[i]), true);
3158 iris_use_pinned_bo(batch, iris_resource_bo(surf_state->res), false);
3159
3160 return surf_state->offset;
3161 }
3162
3163 #define push_bt_entry(addr) \
3164 assert(addr >= binder_addr); \
3165 if (!pin_only) bt_map[s++] = (addr) - binder_addr;
3166
3167 /**
3168 * Populate the binding table for a given shader stage.
3169 *
3170 * This fills out the table of pointers to surfaces required by the shader,
3171 * and also adds those buffers to the validation list so the kernel can make
3172 * resident before running our batch.
3173 */
3174 static void
3175 iris_populate_binding_table(struct iris_context *ice,
3176 struct iris_batch *batch,
3177 gl_shader_stage stage,
3178 bool pin_only)
3179 {
3180 const struct iris_binder *binder = &ice->state.binder;
3181 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3182 if (!shader)
3183 return;
3184
3185 struct iris_shader_state *shs = &ice->state.shaders[stage];
3186 uint32_t binder_addr = binder->bo->gtt_offset;
3187
3188 //struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
3189 uint32_t *bt_map = binder->map + binder->bt_offset[stage];
3190 int s = 0;
3191
3192 const struct shader_info *info = iris_get_shader_info(ice, stage);
3193 if (!info) {
3194 /* TCS passthrough doesn't need a binding table. */
3195 assert(stage == MESA_SHADER_TESS_CTRL);
3196 return;
3197 }
3198
3199 if (stage == MESA_SHADER_FRAGMENT) {
3200 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3201 /* Note that cso_fb->nr_cbufs == fs_key->nr_color_regions. */
3202 if (cso_fb->nr_cbufs) {
3203 for (unsigned i = 0; i < cso_fb->nr_cbufs; i++) {
3204 uint32_t addr =
3205 cso_fb->cbufs[i] ? use_surface(batch, cso_fb->cbufs[i], true)
3206 : use_null_fb_surface(batch, ice);
3207 push_bt_entry(addr);
3208 }
3209 } else {
3210 uint32_t addr = use_null_fb_surface(batch, ice);
3211 push_bt_entry(addr);
3212 }
3213 }
3214
3215 //assert(prog_data->binding_table.texture_start ==
3216 //(ice->state.num_textures[stage] ? s : 0xd0d0d0d0));
3217
3218 for (int i = 0; i < shs->num_textures; i++) {
3219 struct iris_sampler_view *view = shs->textures[i];
3220 uint32_t addr = view ? use_sampler_view(batch, view)
3221 : use_null_surface(batch, ice);
3222 push_bt_entry(addr);
3223 }
3224
3225 for (int i = 0; i < 1 + info->num_ubos; i++) {
3226 struct iris_const_buffer *cbuf = &shs->constbuf[i];
3227 if (!cbuf->surface_state.res)
3228 break;
3229
3230 uint32_t addr = use_const_buffer(batch, cbuf);
3231 push_bt_entry(addr);
3232 }
3233
3234 /* XXX: st is wasting 16 binding table slots for ABOs. Should add a cap
3235 * for changing nir_lower_atomics_to_ssbos setting and buffer_base offset
3236 * in st_atom_storagebuf.c so it'll compact them into one range, with
3237 * SSBOs starting at info->num_abos. Ideally it'd reset num_abos to 0 too
3238 */
3239 if (info->num_abos + info->num_ssbos > 0) {
3240 for (int i = 0; i < IRIS_MAX_ABOS + info->num_ssbos; i++) {
3241 uint32_t addr = use_ssbo(batch, ice, shs, i);
3242 push_bt_entry(addr);
3243 }
3244 }
3245
3246 #if 0
3247 // XXX: not implemented yet
3248 assert(prog_data->binding_table.image_start == 0xd0d0d0d0);
3249 assert(prog_data->binding_table.plane_start[1] == 0xd0d0d0d0);
3250 assert(prog_data->binding_table.plane_start[2] == 0xd0d0d0d0);
3251 #endif
3252 }
3253
3254 static void
3255 iris_use_optional_res(struct iris_batch *batch,
3256 struct pipe_resource *res,
3257 bool writeable)
3258 {
3259 if (res) {
3260 struct iris_bo *bo = iris_resource_bo(res);
3261 iris_use_pinned_bo(batch, bo, writeable);
3262 }
3263 }
3264
3265 /* ------------------------------------------------------------------- */
3266
3267 /**
3268 * Pin any BOs which were installed by a previous batch, and restored
3269 * via the hardware logical context mechanism.
3270 *
3271 * We don't need to re-emit all state every batch - the hardware context
3272 * mechanism will save and restore it for us. This includes pointers to
3273 * various BOs...which won't exist unless we ask the kernel to pin them
3274 * by adding them to the validation list.
3275 *
3276 * We can skip buffers if we've re-emitted those packets, as we're
3277 * overwriting those stale pointers with new ones, and don't actually
3278 * refer to the old BOs.
3279 */
3280 static void
3281 iris_restore_context_saved_bos(struct iris_context *ice,
3282 struct iris_batch *batch,
3283 const struct pipe_draw_info *draw)
3284 {
3285 // XXX: whack IRIS_SHADER_DIRTY_BINDING_TABLE on new batch
3286
3287 const uint64_t clean = ~ice->state.dirty;
3288
3289 if (clean & IRIS_DIRTY_CC_VIEWPORT) {
3290 iris_use_optional_res(batch, ice->state.last_res.cc_vp, false);
3291 }
3292
3293 if (clean & IRIS_DIRTY_SF_CL_VIEWPORT) {
3294 iris_use_optional_res(batch, ice->state.last_res.sf_cl_vp, false);
3295 }
3296
3297 if (clean & IRIS_DIRTY_BLEND_STATE) {
3298 iris_use_optional_res(batch, ice->state.last_res.blend, false);
3299 }
3300
3301 if (clean & IRIS_DIRTY_COLOR_CALC_STATE) {
3302 iris_use_optional_res(batch, ice->state.last_res.color_calc, false);
3303 }
3304
3305 if (clean & IRIS_DIRTY_SCISSOR_RECT) {
3306 iris_use_optional_res(batch, ice->state.last_res.scissor, false);
3307 }
3308
3309 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3310 if (!(clean & (IRIS_DIRTY_CONSTANTS_VS << stage)))
3311 continue;
3312
3313 struct iris_shader_state *shs = &ice->state.shaders[stage];
3314 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3315
3316 if (!shader)
3317 continue;
3318
3319 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
3320
3321 for (int i = 0; i < 4; i++) {
3322 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
3323
3324 if (range->length == 0)
3325 continue;
3326
3327 struct iris_const_buffer *cbuf = &shs->constbuf[range->block];
3328 struct iris_resource *res = (void *) cbuf->data.res;
3329
3330 if (res)
3331 iris_use_pinned_bo(batch, res->bo, false);
3332 else
3333 iris_use_pinned_bo(batch, batch->screen->workaround_bo, false);
3334 }
3335 }
3336
3337 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3338 if (clean & (IRIS_DIRTY_BINDINGS_VS << stage)) {
3339 /* Re-pin any buffers referred to by the binding table. */
3340 iris_populate_binding_table(ice, batch, stage, true);
3341 }
3342 }
3343
3344 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3345 struct iris_shader_state *shs = &ice->state.shaders[stage];
3346 struct pipe_resource *res = shs->sampler_table.res;
3347 if (res)
3348 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
3349 }
3350
3351 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3352 if (clean & (IRIS_DIRTY_VS << stage)) {
3353 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3354 if (shader) {
3355 struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
3356 iris_use_pinned_bo(batch, bo, false);
3357 }
3358
3359 // XXX: scratch buffer
3360 }
3361 }
3362
3363 if (clean & IRIS_DIRTY_DEPTH_BUFFER) {
3364 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3365
3366 if (cso_fb->zsbuf) {
3367 struct iris_resource *zres, *sres;
3368 iris_get_depth_stencil_resources(cso_fb->zsbuf->texture,
3369 &zres, &sres);
3370 // XXX: might not be writable...
3371 if (zres)
3372 iris_use_pinned_bo(batch, zres->bo, true);
3373 if (sres)
3374 iris_use_pinned_bo(batch, sres->bo, true);
3375 }
3376 }
3377
3378 if (draw->index_size == 0 && ice->state.last_res.index_buffer) {
3379 /* This draw didn't emit a new index buffer, so we are inheriting the
3380 * older index buffer. This draw didn't need it, but future ones may.
3381 */
3382 struct iris_bo *bo = iris_resource_bo(ice->state.last_res.index_buffer);
3383 iris_use_pinned_bo(batch, bo, false);
3384 }
3385
3386 if (clean & IRIS_DIRTY_VERTEX_BUFFERS) {
3387 struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
3388 for (unsigned i = 0; i < cso->num_buffers; i++) {
3389 struct iris_resource *res = (void *) cso->resources[i];
3390 iris_use_pinned_bo(batch, res->bo, false);
3391 }
3392 }
3393 }
3394
3395 /**
3396 * Possibly emit STATE_BASE_ADDRESS to update Surface State Base Address.
3397 */
3398 static void
3399 iris_update_surface_base_address(struct iris_batch *batch,
3400 struct iris_binder *binder)
3401 {
3402 if (batch->last_surface_base_address == binder->bo->gtt_offset)
3403 return;
3404
3405 flush_for_state_base_change(batch);
3406
3407 iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
3408 // XXX: sba.SurfaceStateMemoryObjectControlState = MOCS_WB;
3409 sba.SurfaceStateBaseAddressModifyEnable = true;
3410 sba.SurfaceStateBaseAddress = ro_bo(binder->bo, 0);
3411 }
3412
3413 batch->last_surface_base_address = binder->bo->gtt_offset;
3414 }
3415
3416 static void
3417 iris_upload_dirty_render_state(struct iris_context *ice,
3418 struct iris_batch *batch,
3419 const struct pipe_draw_info *draw)
3420 {
3421 const uint64_t dirty = ice->state.dirty;
3422
3423 if (!dirty)
3424 return;
3425
3426 struct iris_genx_state *genx = ice->state.genx;
3427 struct iris_binder *binder = &ice->state.binder;
3428 struct brw_wm_prog_data *wm_prog_data = (void *)
3429 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
3430
3431 if (dirty & IRIS_DIRTY_CC_VIEWPORT) {
3432 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3433 uint32_t cc_vp_address;
3434
3435 /* XXX: could avoid streaming for depth_clip [0,1] case. */
3436 uint32_t *cc_vp_map =
3437 stream_state(batch, ice->state.dynamic_uploader,
3438 &ice->state.last_res.cc_vp,
3439 4 * ice->state.num_viewports *
3440 GENX(CC_VIEWPORT_length), 32, &cc_vp_address);
3441 for (int i = 0; i < ice->state.num_viewports; i++) {
3442 float zmin, zmax;
3443 util_viewport_zmin_zmax(&ice->state.viewports[i],
3444 cso_rast->clip_halfz, &zmin, &zmax);
3445 if (cso_rast->depth_clip_near)
3446 zmin = 0.0;
3447 if (cso_rast->depth_clip_far)
3448 zmax = 1.0;
3449
3450 iris_pack_state(GENX(CC_VIEWPORT), cc_vp_map, ccv) {
3451 ccv.MinimumDepth = zmin;
3452 ccv.MaximumDepth = zmax;
3453 }
3454
3455 cc_vp_map += GENX(CC_VIEWPORT_length);
3456 }
3457
3458 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_CC), ptr) {
3459 ptr.CCViewportPointer = cc_vp_address;
3460 }
3461 }
3462
3463 if (dirty & IRIS_DIRTY_SF_CL_VIEWPORT) {
3464 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
3465 ptr.SFClipViewportPointer =
3466 emit_state(batch, ice->state.dynamic_uploader,
3467 &ice->state.last_res.sf_cl_vp,
3468 genx->sf_cl_vp, 4 * GENX(SF_CLIP_VIEWPORT_length) *
3469 ice->state.num_viewports, 64);
3470 }
3471 }
3472
3473 /* XXX: L3 State */
3474
3475 // XXX: this is only flagged at setup, we assume a static configuration
3476 if (dirty & IRIS_DIRTY_URB) {
3477 iris_upload_urb_config(ice, batch);
3478 }
3479
3480 if (dirty & IRIS_DIRTY_BLEND_STATE) {
3481 struct iris_blend_state *cso_blend = ice->state.cso_blend;
3482 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3483 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
3484 const int header_dwords = GENX(BLEND_STATE_length);
3485 const int rt_dwords = cso_fb->nr_cbufs * GENX(BLEND_STATE_ENTRY_length);
3486 uint32_t blend_offset;
3487 uint32_t *blend_map =
3488 stream_state(batch, ice->state.dynamic_uploader,
3489 &ice->state.last_res.blend,
3490 4 * (header_dwords + rt_dwords), 64, &blend_offset);
3491
3492 uint32_t blend_state_header;
3493 iris_pack_state(GENX(BLEND_STATE), &blend_state_header, bs) {
3494 bs.AlphaTestEnable = cso_zsa->alpha.enabled;
3495 bs.AlphaTestFunction = translate_compare_func(cso_zsa->alpha.func);
3496 }
3497
3498 blend_map[0] = blend_state_header | cso_blend->blend_state[0];
3499 memcpy(&blend_map[1], &cso_blend->blend_state[1], 4 * rt_dwords);
3500
3501 iris_emit_cmd(batch, GENX(3DSTATE_BLEND_STATE_POINTERS), ptr) {
3502 ptr.BlendStatePointer = blend_offset;
3503 ptr.BlendStatePointerValid = true;
3504 }
3505 }
3506
3507 if (dirty & IRIS_DIRTY_COLOR_CALC_STATE) {
3508 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
3509 uint32_t cc_offset;
3510 void *cc_map =
3511 stream_state(batch, ice->state.dynamic_uploader,
3512 &ice->state.last_res.color_calc,
3513 sizeof(uint32_t) * GENX(COLOR_CALC_STATE_length),
3514 64, &cc_offset);
3515 iris_pack_state(GENX(COLOR_CALC_STATE), cc_map, cc) {
3516 cc.AlphaTestFormat = ALPHATEST_FLOAT32;
3517 cc.AlphaReferenceValueAsFLOAT32 = cso->alpha.ref_value;
3518 cc.BlendConstantColorRed = ice->state.blend_color.color[0];
3519 cc.BlendConstantColorGreen = ice->state.blend_color.color[1];
3520 cc.BlendConstantColorBlue = ice->state.blend_color.color[2];
3521 cc.BlendConstantColorAlpha = ice->state.blend_color.color[3];
3522 }
3523 iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
3524 ptr.ColorCalcStatePointer = cc_offset;
3525 ptr.ColorCalcStatePointerValid = true;
3526 }
3527 }
3528
3529 /* Upload constants for TCS passthrough. */
3530 if ((dirty & IRIS_DIRTY_CONSTANTS_TCS) &&
3531 ice->shaders.prog[MESA_SHADER_TESS_CTRL] &&
3532 !ice->shaders.uncompiled[MESA_SHADER_TESS_CTRL]) {
3533 struct iris_compiled_shader *tes_shader = ice->shaders.prog[MESA_SHADER_TESS_EVAL];
3534 assert(tes_shader);
3535
3536 /* Passthrough always copies 2 vec4s, so when uploading data we ensure
3537 * it is in the right layout for TES.
3538 */
3539 float hdr[8] = {};
3540 struct brw_tes_prog_data *tes_prog_data = (void *) tes_shader->prog_data;
3541 switch (tes_prog_data->domain) {
3542 case BRW_TESS_DOMAIN_QUAD:
3543 for (int i = 0; i < 4; i++)
3544 hdr[7 - i] = ice->state.default_outer_level[i];
3545 hdr[3] = ice->state.default_inner_level[0];
3546 hdr[2] = ice->state.default_inner_level[1];
3547 break;
3548 case BRW_TESS_DOMAIN_TRI:
3549 for (int i = 0; i < 3; i++)
3550 hdr[7 - i] = ice->state.default_outer_level[i];
3551 hdr[4] = ice->state.default_inner_level[0];
3552 break;
3553 case BRW_TESS_DOMAIN_ISOLINE:
3554 hdr[7] = ice->state.default_outer_level[1];
3555 hdr[6] = ice->state.default_outer_level[0];
3556 break;
3557 }
3558
3559 struct iris_shader_state *shs = &ice->state.shaders[MESA_SHADER_TESS_CTRL];
3560 struct iris_const_buffer *cbuf = &shs->constbuf[0];
3561 u_upload_data(ice->ctx.const_uploader, 0, sizeof(hdr), 32,
3562 &hdr[0], &cbuf->data.offset,
3563 &cbuf->data.res);
3564 }
3565
3566 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3567 if (!(dirty & (IRIS_DIRTY_CONSTANTS_VS << stage)))
3568 continue;
3569
3570 struct iris_shader_state *shs = &ice->state.shaders[stage];
3571 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3572
3573 if (!shader)
3574 continue;
3575
3576 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
3577
3578 iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_VS), pkt) {
3579 pkt._3DCommandSubOpcode = push_constant_opcodes[stage];
3580 if (prog_data) {
3581 /* The Skylake PRM contains the following restriction:
3582 *
3583 * "The driver must ensure The following case does not occur
3584 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
3585 * buffer 3 read length equal to zero committed followed by a
3586 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
3587 * zero committed."
3588 *
3589 * To avoid this, we program the buffers in the highest slots.
3590 * This way, slot 0 is only used if slot 3 is also used.
3591 */
3592 int n = 3;
3593
3594 for (int i = 3; i >= 0; i--) {
3595 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
3596
3597 if (range->length == 0)
3598 continue;
3599
3600 // XXX: is range->block a constbuf index? it would be nice
3601 struct iris_const_buffer *cbuf = &shs->constbuf[range->block];
3602 struct iris_resource *res = (void *) cbuf->data.res;
3603
3604 assert(cbuf->data.offset % 32 == 0);
3605
3606 pkt.ConstantBody.ReadLength[n] = range->length;
3607 pkt.ConstantBody.Buffer[n] =
3608 res ? ro_bo(res->bo, range->start * 32 + cbuf->data.offset)
3609 : ro_bo(batch->screen->workaround_bo, 0);
3610 n--;
3611 }
3612 }
3613 }
3614 }
3615
3616 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3617 if (dirty & (IRIS_DIRTY_BINDINGS_VS << stage)) {
3618 iris_emit_cmd(batch, GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), ptr) {
3619 ptr._3DCommandSubOpcode = 38 + stage;
3620 ptr.PointertoVSBindingTable = binder->bt_offset[stage];
3621 }
3622 }
3623 }
3624
3625 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3626 if (dirty & (IRIS_DIRTY_BINDINGS_VS << stage)) {
3627 iris_populate_binding_table(ice, batch, stage, false);
3628 }
3629 }
3630
3631 if (ice->state.need_border_colors)
3632 iris_use_pinned_bo(batch, ice->state.border_color_pool.bo, false);
3633
3634 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3635 if (!(dirty & (IRIS_DIRTY_SAMPLER_STATES_VS << stage)) ||
3636 !ice->shaders.prog[stage])
3637 continue;
3638
3639 struct iris_shader_state *shs = &ice->state.shaders[stage];
3640 struct pipe_resource *res = shs->sampler_table.res;
3641 if (res)
3642 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
3643
3644 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ptr) {
3645 ptr._3DCommandSubOpcode = 43 + stage;
3646 ptr.PointertoVSSamplerState = shs->sampler_table.offset;
3647 }
3648 }
3649
3650 if (dirty & IRIS_DIRTY_MULTISAMPLE) {
3651 iris_emit_cmd(batch, GENX(3DSTATE_MULTISAMPLE), ms) {
3652 ms.PixelLocation =
3653 ice->state.cso_rast->half_pixel_center ? CENTER : UL_CORNER;
3654 if (ice->state.framebuffer.samples > 0)
3655 ms.NumberofMultisamples = ffs(ice->state.framebuffer.samples) - 1;
3656 }
3657 }
3658
3659 if (dirty & IRIS_DIRTY_SAMPLE_MASK) {
3660 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_MASK), ms) {
3661 ms.SampleMask = MAX2(ice->state.sample_mask, 1);
3662 }
3663 }
3664
3665 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3666 if (!(dirty & (IRIS_DIRTY_VS << stage)))
3667 continue;
3668
3669 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3670
3671 if (shader) {
3672 struct iris_resource *cache = (void *) shader->assembly.res;
3673 iris_use_pinned_bo(batch, cache->bo, false);
3674 iris_batch_emit(batch, shader->derived_data,
3675 iris_derived_program_state_size(stage));
3676 } else {
3677 if (stage == MESA_SHADER_TESS_EVAL) {
3678 iris_emit_cmd(batch, GENX(3DSTATE_HS), hs);
3679 iris_emit_cmd(batch, GENX(3DSTATE_TE), te);
3680 iris_emit_cmd(batch, GENX(3DSTATE_DS), ds);
3681 } else if (stage == MESA_SHADER_GEOMETRY) {
3682 iris_emit_cmd(batch, GENX(3DSTATE_GS), gs);
3683 }
3684 }
3685 }
3686
3687 if (ice->state.streamout_active) {
3688 if (dirty & IRIS_DIRTY_SO_BUFFERS) {
3689 iris_batch_emit(batch, genx->so_buffers,
3690 4 * 4 * GENX(3DSTATE_SO_BUFFER_length));
3691 for (int i = 0; i < 4; i++) {
3692 struct iris_stream_output_target *tgt =
3693 (void *) ice->state.so_target[i];
3694 if (tgt) {
3695 iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
3696 true);
3697 iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
3698 true);
3699 }
3700 }
3701 }
3702
3703 if ((dirty & IRIS_DIRTY_SO_DECL_LIST) && ice->state.streamout) {
3704 uint32_t *decl_list =
3705 ice->state.streamout + GENX(3DSTATE_STREAMOUT_length);
3706 iris_batch_emit(batch, decl_list, 4 * ((decl_list[0] & 0xff) + 2));
3707 }
3708
3709 if (dirty & IRIS_DIRTY_STREAMOUT) {
3710 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3711
3712 uint32_t dynamic_sol[GENX(3DSTATE_STREAMOUT_length)];
3713 iris_pack_command(GENX(3DSTATE_STREAMOUT), dynamic_sol, sol) {
3714 sol.SOFunctionEnable = true;
3715 sol.SOStatisticsEnable = true;
3716
3717 sol.RenderingDisable = cso_rast->rasterizer_discard &&
3718 !ice->state.prims_generated_query_active;
3719 sol.ReorderMode = cso_rast->flatshade_first ? LEADING : TRAILING;
3720 }
3721
3722 assert(ice->state.streamout);
3723
3724 iris_emit_merge(batch, ice->state.streamout, dynamic_sol,
3725 GENX(3DSTATE_STREAMOUT_length));
3726 }
3727 } else {
3728 if (dirty & IRIS_DIRTY_STREAMOUT) {
3729 iris_emit_cmd(batch, GENX(3DSTATE_STREAMOUT), sol);
3730 }
3731 }
3732
3733 if (dirty & IRIS_DIRTY_CLIP) {
3734 struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3735 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3736
3737 uint32_t dynamic_clip[GENX(3DSTATE_CLIP_length)];
3738 iris_pack_command(GENX(3DSTATE_CLIP), &dynamic_clip, cl) {
3739 if (wm_prog_data->barycentric_interp_modes &
3740 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS)
3741 cl.NonPerspectiveBarycentricEnable = true;
3742
3743 cl.ForceZeroRTAIndexEnable = cso_fb->layers == 0;
3744 cl.MaximumVPIndex = ice->state.num_viewports - 1;
3745 }
3746 iris_emit_merge(batch, cso_rast->clip, dynamic_clip,
3747 ARRAY_SIZE(cso_rast->clip));
3748 }
3749
3750 if (dirty & IRIS_DIRTY_RASTER) {
3751 struct iris_rasterizer_state *cso = ice->state.cso_rast;
3752 iris_batch_emit(batch, cso->raster, sizeof(cso->raster));
3753 iris_batch_emit(batch, cso->sf, sizeof(cso->sf));
3754
3755 }
3756
3757 /* XXX: FS program updates needs to flag IRIS_DIRTY_WM */
3758 if (dirty & IRIS_DIRTY_WM) {
3759 struct iris_rasterizer_state *cso = ice->state.cso_rast;
3760 uint32_t dynamic_wm[GENX(3DSTATE_WM_length)];
3761
3762 iris_pack_command(GENX(3DSTATE_WM), &dynamic_wm, wm) {
3763 wm.BarycentricInterpolationMode =
3764 wm_prog_data->barycentric_interp_modes;
3765
3766 if (wm_prog_data->early_fragment_tests)
3767 wm.EarlyDepthStencilControl = EDSC_PREPS;
3768 else if (wm_prog_data->has_side_effects)
3769 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
3770 }
3771 iris_emit_merge(batch, cso->wm, dynamic_wm, ARRAY_SIZE(cso->wm));
3772 }
3773
3774 if (dirty & IRIS_DIRTY_SBE) {
3775 iris_emit_sbe(batch, ice);
3776 }
3777
3778 if (dirty & IRIS_DIRTY_PS_BLEND) {
3779 struct iris_blend_state *cso_blend = ice->state.cso_blend;
3780 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
3781 uint32_t dynamic_pb[GENX(3DSTATE_PS_BLEND_length)];
3782 iris_pack_command(GENX(3DSTATE_PS_BLEND), &dynamic_pb, pb) {
3783 pb.HasWriteableRT = true; // XXX: comes from somewhere :(
3784 pb.AlphaTestEnable = cso_zsa->alpha.enabled;
3785 }
3786
3787 iris_emit_merge(batch, cso_blend->ps_blend, dynamic_pb,
3788 ARRAY_SIZE(cso_blend->ps_blend));
3789 }
3790
3791 if (dirty & IRIS_DIRTY_WM_DEPTH_STENCIL) {
3792 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
3793 struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
3794
3795 uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
3796 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
3797 wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
3798 wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
3799 }
3800 iris_emit_merge(batch, cso->wmds, stencil_refs, ARRAY_SIZE(cso->wmds));
3801 }
3802
3803 if (dirty & IRIS_DIRTY_SCISSOR_RECT) {
3804 uint32_t scissor_offset =
3805 emit_state(batch, ice->state.dynamic_uploader,
3806 &ice->state.last_res.scissor,
3807 ice->state.scissors,
3808 sizeof(struct pipe_scissor_state) *
3809 ice->state.num_viewports, 32);
3810
3811 iris_emit_cmd(batch, GENX(3DSTATE_SCISSOR_STATE_POINTERS), ptr) {
3812 ptr.ScissorRectPointer = scissor_offset;
3813 }
3814 }
3815
3816 if (dirty & IRIS_DIRTY_DEPTH_BUFFER) {
3817 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3818 struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
3819
3820 iris_batch_emit(batch, cso_z->packets, sizeof(cso_z->packets));
3821
3822 if (cso_fb->zsbuf) {
3823 struct iris_resource *zres = (void *) cso_fb->zsbuf->texture;
3824 // XXX: depth might not be writable...
3825 iris_use_pinned_bo(batch, zres->bo, true);
3826 }
3827 }
3828
3829 if (dirty & IRIS_DIRTY_POLYGON_STIPPLE) {
3830 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_PATTERN), poly) {
3831 for (int i = 0; i < 32; i++) {
3832 poly.PatternRow[i] = ice->state.poly_stipple.stipple[i];
3833 }
3834 }
3835 }
3836
3837 if (dirty & IRIS_DIRTY_LINE_STIPPLE) {
3838 struct iris_rasterizer_state *cso = ice->state.cso_rast;
3839 iris_batch_emit(batch, cso->line_stipple, sizeof(cso->line_stipple));
3840 }
3841
3842 if (dirty & IRIS_DIRTY_VF_TOPOLOGY) {
3843 iris_emit_cmd(batch, GENX(3DSTATE_VF_TOPOLOGY), topo) {
3844 topo.PrimitiveTopologyType =
3845 translate_prim_type(draw->mode, draw->vertices_per_patch);
3846 }
3847 }
3848
3849 if (dirty & IRIS_DIRTY_VERTEX_BUFFERS) {
3850 struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
3851 const unsigned vb_dwords = GENX(VERTEX_BUFFER_STATE_length);
3852
3853 if (cso->num_buffers > 0) {
3854 iris_batch_emit(batch, cso->vertex_buffers, sizeof(uint32_t) *
3855 (1 + vb_dwords * cso->num_buffers));
3856
3857 for (unsigned i = 0; i < cso->num_buffers; i++) {
3858 struct iris_resource *res = (void *) cso->resources[i];
3859 iris_use_pinned_bo(batch, res->bo, false);
3860 }
3861 }
3862 }
3863
3864 if (dirty & IRIS_DIRTY_VERTEX_ELEMENTS) {
3865 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
3866 const unsigned entries = MAX2(cso->count, 1);
3867 iris_batch_emit(batch, cso->vertex_elements, sizeof(uint32_t) *
3868 (1 + entries * GENX(VERTEX_ELEMENT_STATE_length)));
3869 iris_batch_emit(batch, cso->vf_instancing, sizeof(uint32_t) *
3870 entries * GENX(3DSTATE_VF_INSTANCING_length));
3871 }
3872
3873 if (dirty & IRIS_DIRTY_VF_SGVS) {
3874 const struct brw_vs_prog_data *vs_prog_data = (void *)
3875 ice->shaders.prog[MESA_SHADER_VERTEX]->prog_data;
3876 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
3877
3878 iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS), sgv) {
3879 if (vs_prog_data->uses_vertexid) {
3880 sgv.VertexIDEnable = true;
3881 sgv.VertexIDComponentNumber = 2;
3882 sgv.VertexIDElementOffset = cso->count;
3883 }
3884
3885 if (vs_prog_data->uses_instanceid) {
3886 sgv.InstanceIDEnable = true;
3887 sgv.InstanceIDComponentNumber = 3;
3888 sgv.InstanceIDElementOffset = cso->count;
3889 }
3890 }
3891 }
3892
3893 if (dirty & IRIS_DIRTY_VF) {
3894 iris_emit_cmd(batch, GENX(3DSTATE_VF), vf) {
3895 if (draw->primitive_restart) {
3896 vf.IndexedDrawCutIndexEnable = true;
3897 vf.CutIndex = draw->restart_index;
3898 }
3899 }
3900 }
3901
3902 // XXX: Gen8 - PMA fix
3903 }
3904
3905 static void
3906 iris_upload_render_state(struct iris_context *ice,
3907 struct iris_batch *batch,
3908 const struct pipe_draw_info *draw)
3909 {
3910 /* Always pin the binder. If we're emitting new binding table pointers,
3911 * we need it. If not, we're probably inheriting old tables via the
3912 * context, and need it anyway. Since true zero-bindings cases are
3913 * practically non-existent, just pin it and avoid last_res tracking.
3914 */
3915 iris_use_pinned_bo(batch, ice->state.binder.bo, false);
3916
3917 iris_upload_dirty_render_state(ice, batch, draw);
3918
3919 if (draw->index_size > 0) {
3920 unsigned offset;
3921
3922 if (draw->has_user_indices) {
3923 u_upload_data(ice->ctx.stream_uploader, 0,
3924 draw->count * draw->index_size, 4, draw->index.user,
3925 &offset, &ice->state.last_res.index_buffer);
3926 } else {
3927 pipe_resource_reference(&ice->state.last_res.index_buffer,
3928 draw->index.resource);
3929 offset = 0;
3930 }
3931
3932 struct iris_bo *bo = iris_resource_bo(ice->state.last_res.index_buffer);
3933
3934 iris_emit_cmd(batch, GENX(3DSTATE_INDEX_BUFFER), ib) {
3935 ib.IndexFormat = draw->index_size >> 1;
3936 ib.MOCS = MOCS_WB;
3937 ib.BufferSize = bo->size;
3938 ib.BufferStartingAddress = ro_bo(bo, offset);
3939 }
3940 }
3941
3942 #define _3DPRIM_END_OFFSET 0x2420
3943 #define _3DPRIM_START_VERTEX 0x2430
3944 #define _3DPRIM_VERTEX_COUNT 0x2434
3945 #define _3DPRIM_INSTANCE_COUNT 0x2438
3946 #define _3DPRIM_START_INSTANCE 0x243C
3947 #define _3DPRIM_BASE_VERTEX 0x2440
3948
3949 if (draw->indirect) {
3950 /* We don't support this MultidrawIndirect. */
3951 assert(!draw->indirect->indirect_draw_count);
3952
3953 struct iris_bo *bo = iris_resource_bo(draw->indirect->buffer);
3954 assert(bo);
3955
3956 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3957 lrm.RegisterAddress = _3DPRIM_VERTEX_COUNT;
3958 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 0);
3959 }
3960 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3961 lrm.RegisterAddress = _3DPRIM_INSTANCE_COUNT;
3962 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 4);
3963 }
3964 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3965 lrm.RegisterAddress = _3DPRIM_START_VERTEX;
3966 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 8);
3967 }
3968 if (draw->index_size) {
3969 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3970 lrm.RegisterAddress = _3DPRIM_BASE_VERTEX;
3971 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 12);
3972 }
3973 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3974 lrm.RegisterAddress = _3DPRIM_START_INSTANCE;
3975 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 16);
3976 }
3977 } else {
3978 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3979 lrm.RegisterAddress = _3DPRIM_START_INSTANCE;
3980 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 12);
3981 }
3982 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
3983 lri.RegisterOffset = _3DPRIM_BASE_VERTEX;
3984 lri.DataDWord = 0;
3985 }
3986 }
3987 }
3988
3989 iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
3990 prim.StartInstanceLocation = draw->start_instance;
3991 prim.InstanceCount = draw->instance_count;
3992 prim.VertexCountPerInstance = draw->count;
3993 prim.VertexAccessType = draw->index_size > 0 ? RANDOM : SEQUENTIAL;
3994
3995 // XXX: this is probably bonkers.
3996 prim.StartVertexLocation = draw->start;
3997
3998 prim.IndirectParameterEnable = draw->indirect != NULL;
3999
4000 if (draw->index_size) {
4001 prim.BaseVertexLocation += draw->index_bias;
4002 } else {
4003 prim.StartVertexLocation += draw->index_bias;
4004 }
4005
4006 //prim.BaseVertexLocation = ...;
4007 }
4008
4009 if (!batch->contains_draw) {
4010 iris_restore_context_saved_bos(ice, batch, draw);
4011 batch->contains_draw = true;
4012 }
4013 }
4014
4015 /**
4016 * State module teardown.
4017 */
4018 static void
4019 iris_destroy_state(struct iris_context *ice)
4020 {
4021 iris_free_vertex_buffers(&ice->state.genx->vertex_buffers);
4022
4023 // XXX: unreference resources/surfaces.
4024 for (unsigned i = 0; i < ice->state.framebuffer.nr_cbufs; i++) {
4025 pipe_surface_reference(&ice->state.framebuffer.cbufs[i], NULL);
4026 }
4027 pipe_surface_reference(&ice->state.framebuffer.zsbuf, NULL);
4028
4029 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
4030 struct iris_shader_state *shs = &ice->state.shaders[stage];
4031 pipe_resource_reference(&shs->sampler_table.res, NULL);
4032 }
4033 free(ice->state.genx);
4034
4035 pipe_resource_reference(&ice->state.last_res.cc_vp, NULL);
4036 pipe_resource_reference(&ice->state.last_res.sf_cl_vp, NULL);
4037 pipe_resource_reference(&ice->state.last_res.color_calc, NULL);
4038 pipe_resource_reference(&ice->state.last_res.scissor, NULL);
4039 pipe_resource_reference(&ice->state.last_res.blend, NULL);
4040 pipe_resource_reference(&ice->state.last_res.index_buffer, NULL);
4041 }
4042
4043 /* ------------------------------------------------------------------- */
4044
4045 static void
4046 iris_load_register_imm32(struct iris_batch *batch, uint32_t reg,
4047 uint32_t val)
4048 {
4049 _iris_emit_lri(batch, reg, val);
4050 }
4051
4052 static void
4053 iris_load_register_imm64(struct iris_batch *batch, uint32_t reg,
4054 uint64_t val)
4055 {
4056 _iris_emit_lri(batch, reg + 0, val & 0xffffffff);
4057 _iris_emit_lri(batch, reg + 4, val >> 32);
4058 }
4059
4060 /**
4061 * Emit MI_LOAD_REGISTER_MEM to load a 32-bit MMIO register from a buffer.
4062 */
4063 static void
4064 iris_load_register_mem32(struct iris_batch *batch, uint32_t reg,
4065 struct iris_bo *bo, uint32_t offset)
4066 {
4067 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
4068 lrm.RegisterAddress = reg;
4069 lrm.MemoryAddress = ro_bo(bo, offset);
4070 }
4071 }
4072
4073 /**
4074 * Load a 64-bit value from a buffer into a MMIO register via
4075 * two MI_LOAD_REGISTER_MEM commands.
4076 */
4077 static void
4078 iris_load_register_mem64(struct iris_batch *batch, uint32_t reg,
4079 struct iris_bo *bo, uint32_t offset)
4080 {
4081 iris_load_register_mem32(batch, reg + 0, bo, offset + 0);
4082 iris_load_register_mem32(batch, reg + 4, bo, offset + 4);
4083 }
4084
4085 static void
4086 iris_store_register_mem32(struct iris_batch *batch, uint32_t reg,
4087 struct iris_bo *bo, uint32_t offset,
4088 bool predicated)
4089 {
4090 iris_emit_cmd(batch, GENX(MI_STORE_REGISTER_MEM), srm) {
4091 srm.RegisterAddress = reg;
4092 srm.MemoryAddress = rw_bo(bo, offset);
4093 srm.PredicateEnable = predicated;
4094 }
4095 }
4096
4097 static void
4098 iris_store_register_mem64(struct iris_batch *batch, uint32_t reg,
4099 struct iris_bo *bo, uint32_t offset,
4100 bool predicated)
4101 {
4102 iris_store_register_mem32(batch, reg + 0, bo, offset + 0, predicated);
4103 iris_store_register_mem32(batch, reg + 4, bo, offset + 4, predicated);
4104 }
4105
4106 static void
4107 iris_store_data_imm32(struct iris_batch *batch,
4108 struct iris_bo *bo, uint32_t offset,
4109 uint32_t imm)
4110 {
4111 iris_emit_cmd(batch, GENX(MI_STORE_DATA_IMM), sdi) {
4112 sdi.Address = rw_bo(bo, offset);
4113 sdi.ImmediateData = imm;
4114 }
4115 }
4116
4117 static void
4118 iris_store_data_imm64(struct iris_batch *batch,
4119 struct iris_bo *bo, uint32_t offset,
4120 uint64_t imm)
4121 {
4122 /* Can't use iris_emit_cmd because MI_STORE_DATA_IMM has a length of
4123 * 2 in genxml but it's actually variable length and we need 5 DWords.
4124 */
4125 void *map = iris_get_command_space(batch, 4 * 5);
4126 _iris_pack_command(batch, GENX(MI_STORE_DATA_IMM), map, sdi) {
4127 sdi.DWordLength = 5 - 2;
4128 sdi.Address = rw_bo(bo, offset);
4129 sdi.ImmediateData = imm;
4130 }
4131 }
4132
4133 static void
4134 iris_copy_mem_mem(struct iris_batch *batch,
4135 struct iris_bo *dst_bo, uint32_t dst_offset,
4136 struct iris_bo *src_bo, uint32_t src_offset,
4137 unsigned bytes)
4138 {
4139 /* MI_COPY_MEM_MEM operates on DWords. */
4140 assert(bytes % 4 == 0);
4141 assert(dst_offset % 4 == 0);
4142 assert(src_offset % 4 == 0);
4143
4144 for (unsigned i = 0; i < bytes; i += 4) {
4145 iris_emit_cmd(batch, GENX(MI_COPY_MEM_MEM), cp) {
4146 cp.DestinationMemoryAddress = rw_bo(dst_bo, dst_offset + i);
4147 cp.SourceMemoryAddress = ro_bo(src_bo, src_offset + i);
4148 }
4149 }
4150 }
4151
4152 /* ------------------------------------------------------------------- */
4153
4154 static unsigned
4155 flags_to_post_sync_op(uint32_t flags)
4156 {
4157 if (flags & PIPE_CONTROL_WRITE_IMMEDIATE)
4158 return WriteImmediateData;
4159
4160 if (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT)
4161 return WritePSDepthCount;
4162
4163 if (flags & PIPE_CONTROL_WRITE_TIMESTAMP)
4164 return WriteTimestamp;
4165
4166 return 0;
4167 }
4168
4169 /**
4170 * Do the given flags have a Post Sync or LRI Post Sync operation?
4171 */
4172 static enum pipe_control_flags
4173 get_post_sync_flags(enum pipe_control_flags flags)
4174 {
4175 flags &= PIPE_CONTROL_WRITE_IMMEDIATE |
4176 PIPE_CONTROL_WRITE_DEPTH_COUNT |
4177 PIPE_CONTROL_WRITE_TIMESTAMP |
4178 PIPE_CONTROL_LRI_POST_SYNC_OP;
4179
4180 /* Only one "Post Sync Op" is allowed, and it's mutually exclusive with
4181 * "LRI Post Sync Operation". So more than one bit set would be illegal.
4182 */
4183 assert(util_bitcount(flags) <= 1);
4184
4185 return flags;
4186 }
4187
4188 // XXX: compute support
4189 #define IS_COMPUTE_PIPELINE(batch) (batch->engine != I915_EXEC_RENDER)
4190
4191 /**
4192 * Emit a series of PIPE_CONTROL commands, taking into account any
4193 * workarounds necessary to actually accomplish the caller's request.
4194 *
4195 * Unless otherwise noted, spec quotations in this function come from:
4196 *
4197 * Synchronization of the 3D Pipeline > PIPE_CONTROL Command > Programming
4198 * Restrictions for PIPE_CONTROL.
4199 *
4200 * You should not use this function directly. Use the helpers in
4201 * iris_pipe_control.c instead, which may split the pipe control further.
4202 */
4203 static void
4204 iris_emit_raw_pipe_control(struct iris_batch *batch, uint32_t flags,
4205 struct iris_bo *bo, uint32_t offset, uint64_t imm)
4206 {
4207 UNUSED const struct gen_device_info *devinfo = &batch->screen->devinfo;
4208 enum pipe_control_flags post_sync_flags = get_post_sync_flags(flags);
4209 enum pipe_control_flags non_lri_post_sync_flags =
4210 post_sync_flags & ~PIPE_CONTROL_LRI_POST_SYNC_OP;
4211
4212 /* Recursive PIPE_CONTROL workarounds --------------------------------
4213 * (http://knowyourmeme.com/memes/xzibit-yo-dawg)
4214 *
4215 * We do these first because we want to look at the original operation,
4216 * rather than any workarounds we set.
4217 */
4218 if (GEN_GEN == 9 && (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE)) {
4219 /* The PIPE_CONTROL "VF Cache Invalidation Enable" bit description
4220 * lists several workarounds:
4221 *
4222 * "Project: SKL, KBL, BXT
4223 *
4224 * If the VF Cache Invalidation Enable is set to a 1 in a
4225 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields
4226 * sets to 0, with the VF Cache Invalidation Enable set to 0
4227 * needs to be sent prior to the PIPE_CONTROL with VF Cache
4228 * Invalidation Enable set to a 1."
4229 */
4230 iris_emit_raw_pipe_control(batch, 0, NULL, 0, 0);
4231 }
4232
4233 if (GEN_GEN == 9 && IS_COMPUTE_PIPELINE(batch) && post_sync_flags) {
4234 /* Project: SKL / Argument: LRI Post Sync Operation [23]
4235 *
4236 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
4237 * programmed prior to programming a PIPECONTROL command with "LRI
4238 * Post Sync Operation" in GPGPU mode of operation (i.e when
4239 * PIPELINE_SELECT command is set to GPGPU mode of operation)."
4240 *
4241 * The same text exists a few rows below for Post Sync Op.
4242 */
4243 iris_emit_raw_pipe_control(batch, PIPE_CONTROL_CS_STALL, bo, offset, imm);
4244 }
4245
4246 if (GEN_GEN == 10 && (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH)) {
4247 /* Cannonlake:
4248 * "Before sending a PIPE_CONTROL command with bit 12 set, SW must issue
4249 * another PIPE_CONTROL with Render Target Cache Flush Enable (bit 12)
4250 * = 0 and Pipe Control Flush Enable (bit 7) = 1"
4251 */
4252 iris_emit_raw_pipe_control(batch, PIPE_CONTROL_FLUSH_ENABLE, bo,
4253 offset, imm);
4254 }
4255
4256 /* "Flush Types" workarounds ---------------------------------------------
4257 * We do these now because they may add post-sync operations or CS stalls.
4258 */
4259
4260 if (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) {
4261 /* Project: BDW, SKL+ (stopping at CNL) / Argument: VF Invalidate
4262 *
4263 * "'Post Sync Operation' must be enabled to 'Write Immediate Data' or
4264 * 'Write PS Depth Count' or 'Write Timestamp'."
4265 */
4266 if (!bo) {
4267 flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
4268 post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
4269 non_lri_post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
4270 bo = batch->screen->workaround_bo;
4271 }
4272 }
4273
4274 /* #1130 from Gen10 workarounds page:
4275 *
4276 * "Enable Depth Stall on every Post Sync Op if Render target Cache
4277 * Flush is not enabled in same PIPE CONTROL and Enable Pixel score
4278 * board stall if Render target cache flush is enabled."
4279 *
4280 * Applicable to CNL B0 and C0 steppings only.
4281 *
4282 * The wording here is unclear, and this workaround doesn't look anything
4283 * like the internal bug report recommendations, but leave it be for now...
4284 */
4285 if (GEN_GEN == 10) {
4286 if (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH) {
4287 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
4288 } else if (flags & non_lri_post_sync_flags) {
4289 flags |= PIPE_CONTROL_DEPTH_STALL;
4290 }
4291 }
4292
4293 if (flags & PIPE_CONTROL_DEPTH_STALL) {
4294 /* From the PIPE_CONTROL instruction table, bit 13 (Depth Stall Enable):
4295 *
4296 * "This bit must be DISABLED for operations other than writing
4297 * PS_DEPTH_COUNT."
4298 *
4299 * This seems like nonsense. An Ivybridge workaround requires us to
4300 * emit a PIPE_CONTROL with a depth stall and write immediate post-sync
4301 * operation. Gen8+ requires us to emit depth stalls and depth cache
4302 * flushes together. So, it's hard to imagine this means anything other
4303 * than "we originally intended this to be used for PS_DEPTH_COUNT".
4304 *
4305 * We ignore the supposed restriction and do nothing.
4306 */
4307 }
4308
4309 if (flags & (PIPE_CONTROL_RENDER_TARGET_FLUSH |
4310 PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
4311 /* From the PIPE_CONTROL instruction table, bit 12 and bit 1:
4312 *
4313 * "This bit must be DISABLED for End-of-pipe (Read) fences,
4314 * PS_DEPTH_COUNT or TIMESTAMP queries."
4315 *
4316 * TODO: Implement end-of-pipe checking.
4317 */
4318 assert(!(post_sync_flags & (PIPE_CONTROL_WRITE_DEPTH_COUNT |
4319 PIPE_CONTROL_WRITE_TIMESTAMP)));
4320 }
4321
4322 if (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD) {
4323 /* From the PIPE_CONTROL instruction table, bit 1:
4324 *
4325 * "This bit is ignored if Depth Stall Enable is set.
4326 * Further, the render cache is not flushed even if Write Cache
4327 * Flush Enable bit is set."
4328 *
4329 * We assert that the caller doesn't do this combination, to try and
4330 * prevent mistakes. It shouldn't hurt the GPU, though.
4331 */
4332 assert(!(flags & (PIPE_CONTROL_DEPTH_STALL |
4333 PIPE_CONTROL_RENDER_TARGET_FLUSH)));
4334 }
4335
4336 /* PIPE_CONTROL page workarounds ------------------------------------- */
4337
4338 if (GEN_GEN <= 8 && (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE)) {
4339 /* From the PIPE_CONTROL page itself:
4340 *
4341 * "IVB, HSW, BDW
4342 * Restriction: Pipe_control with CS-stall bit set must be issued
4343 * before a pipe-control command that has the State Cache
4344 * Invalidate bit set."
4345 */
4346 flags |= PIPE_CONTROL_CS_STALL;
4347 }
4348
4349 if (flags & PIPE_CONTROL_FLUSH_LLC) {
4350 /* From the PIPE_CONTROL instruction table, bit 26 (Flush LLC):
4351 *
4352 * "Project: ALL
4353 * SW must always program Post-Sync Operation to "Write Immediate
4354 * Data" when Flush LLC is set."
4355 *
4356 * For now, we just require the caller to do it.
4357 */
4358 assert(flags & PIPE_CONTROL_WRITE_IMMEDIATE);
4359 }
4360
4361 /* "Post-Sync Operation" workarounds -------------------------------- */
4362
4363 /* Project: All / Argument: Global Snapshot Count Reset [19]
4364 *
4365 * "This bit must not be exercised on any product.
4366 * Requires stall bit ([20] of DW1) set."
4367 *
4368 * We don't use this, so we just assert that it isn't used. The
4369 * PIPE_CONTROL instruction page indicates that they intended this
4370 * as a debug feature and don't think it is useful in production,
4371 * but it may actually be usable, should we ever want to.
4372 */
4373 assert((flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) == 0);
4374
4375 if (flags & (PIPE_CONTROL_MEDIA_STATE_CLEAR |
4376 PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE)) {
4377 /* Project: All / Arguments:
4378 *
4379 * - Generic Media State Clear [16]
4380 * - Indirect State Pointers Disable [16]
4381 *
4382 * "Requires stall bit ([20] of DW1) set."
4383 *
4384 * Also, the PIPE_CONTROL instruction table, bit 16 (Generic Media
4385 * State Clear) says:
4386 *
4387 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
4388 * programmed prior to programming a PIPECONTROL command with "Media
4389 * State Clear" set in GPGPU mode of operation"
4390 *
4391 * This is a subset of the earlier rule, so there's nothing to do.
4392 */
4393 flags |= PIPE_CONTROL_CS_STALL;
4394 }
4395
4396 if (flags & PIPE_CONTROL_STORE_DATA_INDEX) {
4397 /* Project: All / Argument: Store Data Index
4398 *
4399 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
4400 * than '0'."
4401 *
4402 * For now, we just assert that the caller does this. We might want to
4403 * automatically add a write to the workaround BO...
4404 */
4405 assert(non_lri_post_sync_flags != 0);
4406 }
4407
4408 if (flags & PIPE_CONTROL_SYNC_GFDT) {
4409 /* Project: All / Argument: Sync GFDT
4410 *
4411 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
4412 * than '0' or 0x2520[13] must be set."
4413 *
4414 * For now, we just assert that the caller does this.
4415 */
4416 assert(non_lri_post_sync_flags != 0);
4417 }
4418
4419 if (flags & PIPE_CONTROL_TLB_INVALIDATE) {
4420 /* Project: IVB+ / Argument: TLB inv
4421 *
4422 * "Requires stall bit ([20] of DW1) set."
4423 *
4424 * Also, from the PIPE_CONTROL instruction table:
4425 *
4426 * "Project: SKL+
4427 * Post Sync Operation or CS stall must be set to ensure a TLB
4428 * invalidation occurs. Otherwise no cycle will occur to the TLB
4429 * cache to invalidate."
4430 *
4431 * This is not a subset of the earlier rule, so there's nothing to do.
4432 */
4433 flags |= PIPE_CONTROL_CS_STALL;
4434 }
4435
4436 if (GEN_GEN == 9 && devinfo->gt == 4) {
4437 /* TODO: The big Skylake GT4 post sync op workaround */
4438 }
4439
4440 /* "GPGPU specific workarounds" (both post-sync and flush) ------------ */
4441
4442 if (IS_COMPUTE_PIPELINE(batch)) {
4443 if (GEN_GEN >= 9 && (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE)) {
4444 /* Project: SKL+ / Argument: Tex Invalidate
4445 * "Requires stall bit ([20] of DW) set for all GPGPU Workloads."
4446 */
4447 flags |= PIPE_CONTROL_CS_STALL;
4448 }
4449
4450 if (GEN_GEN == 8 && (post_sync_flags ||
4451 (flags & (PIPE_CONTROL_NOTIFY_ENABLE |
4452 PIPE_CONTROL_DEPTH_STALL |
4453 PIPE_CONTROL_RENDER_TARGET_FLUSH |
4454 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
4455 PIPE_CONTROL_DATA_CACHE_FLUSH)))) {
4456 /* Project: BDW / Arguments:
4457 *
4458 * - LRI Post Sync Operation [23]
4459 * - Post Sync Op [15:14]
4460 * - Notify En [8]
4461 * - Depth Stall [13]
4462 * - Render Target Cache Flush [12]
4463 * - Depth Cache Flush [0]
4464 * - DC Flush Enable [5]
4465 *
4466 * "Requires stall bit ([20] of DW) set for all GPGPU and Media
4467 * Workloads."
4468 */
4469 flags |= PIPE_CONTROL_CS_STALL;
4470
4471 /* Also, from the PIPE_CONTROL instruction table, bit 20:
4472 *
4473 * "Project: BDW
4474 * This bit must be always set when PIPE_CONTROL command is
4475 * programmed by GPGPU and MEDIA workloads, except for the cases
4476 * when only Read Only Cache Invalidation bits are set (State
4477 * Cache Invalidation Enable, Instruction cache Invalidation
4478 * Enable, Texture Cache Invalidation Enable, Constant Cache
4479 * Invalidation Enable). This is to WA FFDOP CG issue, this WA
4480 * need not implemented when FF_DOP_CG is disable via "Fixed
4481 * Function DOP Clock Gate Disable" bit in RC_PSMI_CTRL register."
4482 *
4483 * It sounds like we could avoid CS stalls in some cases, but we
4484 * don't currently bother. This list isn't exactly the list above,
4485 * either...
4486 */
4487 }
4488 }
4489
4490 /* "Stall" workarounds ----------------------------------------------
4491 * These have to come after the earlier ones because we may have added
4492 * some additional CS stalls above.
4493 */
4494
4495 if (GEN_GEN < 9 && (flags & PIPE_CONTROL_CS_STALL)) {
4496 /* Project: PRE-SKL, VLV, CHV
4497 *
4498 * "[All Stepping][All SKUs]:
4499 *
4500 * One of the following must also be set:
4501 *
4502 * - Render Target Cache Flush Enable ([12] of DW1)
4503 * - Depth Cache Flush Enable ([0] of DW1)
4504 * - Stall at Pixel Scoreboard ([1] of DW1)
4505 * - Depth Stall ([13] of DW1)
4506 * - Post-Sync Operation ([13] of DW1)
4507 * - DC Flush Enable ([5] of DW1)"
4508 *
4509 * If we don't already have one of those bits set, we choose to add
4510 * "Stall at Pixel Scoreboard". Some of the other bits require a
4511 * CS stall as a workaround (see above), which would send us into
4512 * an infinite recursion of PIPE_CONTROLs. "Stall at Pixel Scoreboard"
4513 * appears to be safe, so we choose that.
4514 */
4515 const uint32_t wa_bits = PIPE_CONTROL_RENDER_TARGET_FLUSH |
4516 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
4517 PIPE_CONTROL_WRITE_IMMEDIATE |
4518 PIPE_CONTROL_WRITE_DEPTH_COUNT |
4519 PIPE_CONTROL_WRITE_TIMESTAMP |
4520 PIPE_CONTROL_STALL_AT_SCOREBOARD |
4521 PIPE_CONTROL_DEPTH_STALL |
4522 PIPE_CONTROL_DATA_CACHE_FLUSH;
4523 if (!(flags & wa_bits))
4524 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
4525 }
4526
4527 /* Emit --------------------------------------------------------------- */
4528
4529 iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
4530 pc.LRIPostSyncOperation = NoLRIOperation;
4531 pc.PipeControlFlushEnable = flags & PIPE_CONTROL_FLUSH_ENABLE;
4532 pc.DCFlushEnable = flags & PIPE_CONTROL_DATA_CACHE_FLUSH;
4533 pc.StoreDataIndex = 0;
4534 pc.CommandStreamerStallEnable = flags & PIPE_CONTROL_CS_STALL;
4535 pc.GlobalSnapshotCountReset =
4536 flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET;
4537 pc.TLBInvalidate = flags & PIPE_CONTROL_TLB_INVALIDATE;
4538 pc.GenericMediaStateClear = flags & PIPE_CONTROL_MEDIA_STATE_CLEAR;
4539 pc.StallAtPixelScoreboard = flags & PIPE_CONTROL_STALL_AT_SCOREBOARD;
4540 pc.RenderTargetCacheFlushEnable =
4541 flags & PIPE_CONTROL_RENDER_TARGET_FLUSH;
4542 pc.DepthCacheFlushEnable = flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH;
4543 pc.StateCacheInvalidationEnable =
4544 flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE;
4545 pc.VFCacheInvalidationEnable = flags & PIPE_CONTROL_VF_CACHE_INVALIDATE;
4546 pc.ConstantCacheInvalidationEnable =
4547 flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE;
4548 pc.PostSyncOperation = flags_to_post_sync_op(flags);
4549 pc.DepthStallEnable = flags & PIPE_CONTROL_DEPTH_STALL;
4550 pc.InstructionCacheInvalidateEnable =
4551 flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE;
4552 pc.NotifyEnable = flags & PIPE_CONTROL_NOTIFY_ENABLE;
4553 pc.IndirectStatePointersDisable =
4554 flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE;
4555 pc.TextureCacheInvalidationEnable =
4556 flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
4557 pc.Address = rw_bo(bo, offset);
4558 pc.ImmediateData = imm;
4559 }
4560 }
4561
4562 void
4563 genX(init_state)(struct iris_context *ice)
4564 {
4565 struct pipe_context *ctx = &ice->ctx;
4566 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
4567
4568 ctx->create_blend_state = iris_create_blend_state;
4569 ctx->create_depth_stencil_alpha_state = iris_create_zsa_state;
4570 ctx->create_rasterizer_state = iris_create_rasterizer_state;
4571 ctx->create_sampler_state = iris_create_sampler_state;
4572 ctx->create_sampler_view = iris_create_sampler_view;
4573 ctx->create_surface = iris_create_surface;
4574 ctx->create_vertex_elements_state = iris_create_vertex_elements;
4575 ctx->bind_blend_state = iris_bind_blend_state;
4576 ctx->bind_depth_stencil_alpha_state = iris_bind_zsa_state;
4577 ctx->bind_sampler_states = iris_bind_sampler_states;
4578 ctx->bind_rasterizer_state = iris_bind_rasterizer_state;
4579 ctx->bind_vertex_elements_state = iris_bind_vertex_elements_state;
4580 ctx->delete_blend_state = iris_delete_state;
4581 ctx->delete_depth_stencil_alpha_state = iris_delete_state;
4582 ctx->delete_fs_state = iris_delete_state;
4583 ctx->delete_rasterizer_state = iris_delete_state;
4584 ctx->delete_sampler_state = iris_delete_state;
4585 ctx->delete_vertex_elements_state = iris_delete_state;
4586 ctx->delete_tcs_state = iris_delete_state;
4587 ctx->delete_tes_state = iris_delete_state;
4588 ctx->delete_gs_state = iris_delete_state;
4589 ctx->delete_vs_state = iris_delete_state;
4590 ctx->set_blend_color = iris_set_blend_color;
4591 ctx->set_clip_state = iris_set_clip_state;
4592 ctx->set_constant_buffer = iris_set_constant_buffer;
4593 ctx->set_shader_buffers = iris_set_shader_buffers;
4594 ctx->set_sampler_views = iris_set_sampler_views;
4595 ctx->set_tess_state = iris_set_tess_state;
4596 ctx->set_framebuffer_state = iris_set_framebuffer_state;
4597 ctx->set_polygon_stipple = iris_set_polygon_stipple;
4598 ctx->set_sample_mask = iris_set_sample_mask;
4599 ctx->set_scissor_states = iris_set_scissor_states;
4600 ctx->set_stencil_ref = iris_set_stencil_ref;
4601 ctx->set_vertex_buffers = iris_set_vertex_buffers;
4602 ctx->set_viewport_states = iris_set_viewport_states;
4603 ctx->sampler_view_destroy = iris_sampler_view_destroy;
4604 ctx->surface_destroy = iris_surface_destroy;
4605 ctx->draw_vbo = iris_draw_vbo;
4606 ctx->launch_grid = iris_launch_grid;
4607 ctx->create_stream_output_target = iris_create_stream_output_target;
4608 ctx->stream_output_target_destroy = iris_stream_output_target_destroy;
4609 ctx->set_stream_output_targets = iris_set_stream_output_targets;
4610
4611 ice->vtbl.destroy_state = iris_destroy_state;
4612 ice->vtbl.init_render_context = iris_init_render_context;
4613 ice->vtbl.upload_render_state = iris_upload_render_state;
4614 ice->vtbl.update_surface_base_address = iris_update_surface_base_address;
4615 ice->vtbl.emit_raw_pipe_control = iris_emit_raw_pipe_control;
4616 ice->vtbl.load_register_imm32 = iris_load_register_imm32;
4617 ice->vtbl.load_register_imm64 = iris_load_register_imm64;
4618 ice->vtbl.load_register_mem32 = iris_load_register_mem32;
4619 ice->vtbl.load_register_mem64 = iris_load_register_mem64;
4620 ice->vtbl.store_register_mem32 = iris_store_register_mem32;
4621 ice->vtbl.store_register_mem64 = iris_store_register_mem64;
4622 ice->vtbl.store_data_imm32 = iris_store_data_imm32;
4623 ice->vtbl.store_data_imm64 = iris_store_data_imm64;
4624 ice->vtbl.copy_mem_mem = iris_copy_mem_mem;
4625 ice->vtbl.derived_program_state_size = iris_derived_program_state_size;
4626 ice->vtbl.store_derived_program_state = iris_store_derived_program_state;
4627 ice->vtbl.create_so_decl_list = iris_create_so_decl_list;
4628 ice->vtbl.populate_vs_key = iris_populate_vs_key;
4629 ice->vtbl.populate_tcs_key = iris_populate_tcs_key;
4630 ice->vtbl.populate_tes_key = iris_populate_tes_key;
4631 ice->vtbl.populate_gs_key = iris_populate_gs_key;
4632 ice->vtbl.populate_fs_key = iris_populate_fs_key;
4633
4634 ice->state.dirty = ~0ull;
4635
4636 ice->state.sample_mask = 0xffff;
4637 ice->state.num_viewports = 1;
4638 ice->state.genx = calloc(1, sizeof(struct iris_genx_state));
4639
4640 /* Make a 1x1x1 null surface for unbound textures */
4641 void *null_surf_map =
4642 upload_state(ice->state.surface_uploader, &ice->state.unbound_tex,
4643 4 * GENX(RENDER_SURFACE_STATE_length), 64);
4644 isl_null_fill_state(&screen->isl_dev, null_surf_map, isl_extent3d(1, 1, 1));
4645 ice->state.unbound_tex.offset +=
4646 iris_bo_offset_from_base_address(iris_resource_bo(ice->state.unbound_tex.res));
4647 }