iris: totally untested icelake support
[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 // XXX: do we need this
1116 struct pipe_sampler_state base;
1117
1118 bool needs_border_color;
1119
1120 uint32_t sampler_state[GENX(SAMPLER_STATE_length)];
1121 };
1122
1123 /**
1124 * The pipe->create_sampler_state() driver hook.
1125 *
1126 * We fill out SAMPLER_STATE (except for the border color pointer), and
1127 * store that on the CPU. It doesn't make sense to upload it to a GPU
1128 * buffer object yet, because 3DSTATE_SAMPLER_STATE_POINTERS requires
1129 * all bound sampler states to be in contiguous memor.
1130 */
1131 static void *
1132 iris_create_sampler_state(struct pipe_context *ctx,
1133 const struct pipe_sampler_state *state)
1134 {
1135 struct iris_sampler_state *cso = CALLOC_STRUCT(iris_sampler_state);
1136
1137 if (!cso)
1138 return NULL;
1139
1140 memcpy(&cso->base, state, sizeof(*state));
1141
1142 STATIC_ASSERT(PIPE_TEX_FILTER_NEAREST == MAPFILTER_NEAREST);
1143 STATIC_ASSERT(PIPE_TEX_FILTER_LINEAR == MAPFILTER_LINEAR);
1144
1145 unsigned wrap_s = translate_wrap(state->wrap_s);
1146 unsigned wrap_t = translate_wrap(state->wrap_t);
1147 unsigned wrap_r = translate_wrap(state->wrap_r);
1148
1149 cso->needs_border_color = wrap_mode_needs_border_color(wrap_s) ||
1150 wrap_mode_needs_border_color(wrap_t) ||
1151 wrap_mode_needs_border_color(wrap_r);
1152
1153 float min_lod = state->min_lod;
1154 unsigned mag_img_filter = state->mag_img_filter;
1155
1156 // XXX: explain this code ported from ilo...I don't get it at all...
1157 if (state->min_mip_filter == PIPE_TEX_MIPFILTER_NONE &&
1158 state->min_lod > 0.0f) {
1159 min_lod = 0.0f;
1160 mag_img_filter = state->min_img_filter;
1161 }
1162
1163 iris_pack_state(GENX(SAMPLER_STATE), cso->sampler_state, samp) {
1164 samp.TCXAddressControlMode = wrap_s;
1165 samp.TCYAddressControlMode = wrap_t;
1166 samp.TCZAddressControlMode = wrap_r;
1167 samp.CubeSurfaceControlMode = state->seamless_cube_map;
1168 samp.NonnormalizedCoordinateEnable = !state->normalized_coords;
1169 samp.MinModeFilter = state->min_img_filter;
1170 samp.MagModeFilter = mag_img_filter;
1171 samp.MipModeFilter = translate_mip_filter(state->min_mip_filter);
1172 samp.MaximumAnisotropy = RATIO21;
1173
1174 if (state->max_anisotropy >= 2) {
1175 if (state->min_img_filter == PIPE_TEX_FILTER_LINEAR) {
1176 samp.MinModeFilter = MAPFILTER_ANISOTROPIC;
1177 samp.AnisotropicAlgorithm = EWAApproximation;
1178 }
1179
1180 if (state->mag_img_filter == PIPE_TEX_FILTER_LINEAR)
1181 samp.MagModeFilter = MAPFILTER_ANISOTROPIC;
1182
1183 samp.MaximumAnisotropy =
1184 MIN2((state->max_anisotropy - 2) / 2, RATIO161);
1185 }
1186
1187 /* Set address rounding bits if not using nearest filtering. */
1188 if (state->min_img_filter != PIPE_TEX_FILTER_NEAREST) {
1189 samp.UAddressMinFilterRoundingEnable = true;
1190 samp.VAddressMinFilterRoundingEnable = true;
1191 samp.RAddressMinFilterRoundingEnable = true;
1192 }
1193
1194 if (state->mag_img_filter != PIPE_TEX_FILTER_NEAREST) {
1195 samp.UAddressMagFilterRoundingEnable = true;
1196 samp.VAddressMagFilterRoundingEnable = true;
1197 samp.RAddressMagFilterRoundingEnable = true;
1198 }
1199
1200 if (state->compare_mode == PIPE_TEX_COMPARE_R_TO_TEXTURE)
1201 samp.ShadowFunction = translate_shadow_func(state->compare_func);
1202
1203 const float hw_max_lod = GEN_GEN >= 7 ? 14 : 13;
1204
1205 samp.LODPreClampMode = CLAMP_MODE_OGL;
1206 samp.MinLOD = CLAMP(min_lod, 0, hw_max_lod);
1207 samp.MaxLOD = CLAMP(state->max_lod, 0, hw_max_lod);
1208 samp.TextureLODBias = CLAMP(state->lod_bias, -16, 15);
1209
1210 /* .BorderColorPointer is filled in by iris_bind_sampler_states. */
1211 }
1212
1213 return cso;
1214 }
1215
1216 /**
1217 * The pipe->bind_sampler_states() driver hook.
1218 *
1219 * Now that we know all the sampler states, we upload them all into a
1220 * contiguous area of GPU memory, for 3DSTATE_SAMPLER_STATE_POINTERS_*.
1221 * We also fill out the border color state pointers at this point.
1222 *
1223 * We could defer this work to draw time, but we assume that binding
1224 * will be less frequent than drawing.
1225 */
1226 // XXX: this may be a bad idea, need to make sure that st/mesa calls us
1227 // XXX: with the complete set of shaders. If it makes multiple calls to
1228 // XXX: things one at a time, we could waste a lot of time assembling things.
1229 // XXX: it doesn't even BUY us anything to do it here, because we only flag
1230 // XXX: IRIS_DIRTY_SAMPLER_STATE when this is called...
1231 static void
1232 iris_bind_sampler_states(struct pipe_context *ctx,
1233 enum pipe_shader_type p_stage,
1234 unsigned start, unsigned count,
1235 void **states)
1236 {
1237 struct iris_context *ice = (struct iris_context *) ctx;
1238 gl_shader_stage stage = stage_from_pipe(p_stage);
1239 struct iris_shader_state *shs = &ice->state.shaders[stage];
1240
1241 assert(start + count <= IRIS_MAX_TEXTURE_SAMPLERS);
1242 shs->num_samplers = MAX2(shs->num_samplers, start + count);
1243
1244 for (int i = 0; i < count; i++) {
1245 shs->samplers[start + i] = states[i];
1246 }
1247
1248 /* Assemble the SAMPLER_STATEs into a contiguous table that lives
1249 * in the dynamic state memory zone, so we can point to it via the
1250 * 3DSTATE_SAMPLER_STATE_POINTERS_* commands.
1251 */
1252 uint32_t *map =
1253 upload_state(ice->state.dynamic_uploader, &shs->sampler_table,
1254 count * 4 * GENX(SAMPLER_STATE_length), 32);
1255 if (unlikely(!map))
1256 return;
1257
1258 struct pipe_resource *res = shs->sampler_table.res;
1259 shs->sampler_table.offset +=
1260 iris_bo_offset_from_base_address(iris_resource_bo(res));
1261
1262 /* Make sure all land in the same BO */
1263 iris_border_color_pool_reserve(ice, IRIS_MAX_TEXTURE_SAMPLERS);
1264
1265 for (int i = 0; i < count; i++) {
1266 struct iris_sampler_state *state = shs->samplers[i];
1267
1268 if (!state) {
1269 memset(map, 0, 4 * GENX(SAMPLER_STATE_length));
1270 } else if (!state->needs_border_color) {
1271 memcpy(map, state->sampler_state, 4 * GENX(SAMPLER_STATE_length));
1272 } else {
1273 ice->state.need_border_colors = true;
1274
1275 /* Stream out the border color and merge the pointer. */
1276 uint32_t offset =
1277 iris_upload_border_color(ice, &state->base.border_color);
1278
1279 uint32_t dynamic[GENX(SAMPLER_STATE_length)];
1280 iris_pack_state(GENX(SAMPLER_STATE), dynamic, dyns) {
1281 dyns.BorderColorPointer = offset;
1282 }
1283
1284 for (uint32_t j = 0; j < GENX(SAMPLER_STATE_length); j++)
1285 map[j] = state->sampler_state[j] | dynamic[j];
1286 }
1287
1288 map += GENX(SAMPLER_STATE_length);
1289 }
1290
1291 ice->state.dirty |= IRIS_DIRTY_SAMPLER_STATES_VS << stage;
1292 }
1293
1294 /**
1295 * Convert an swizzle enumeration (i.e. PIPE_SWIZZLE_X) to one of the HW's
1296 * "Shader Channel Select" enumerations (i.e. SCS_RED). The mappings are
1297 *
1298 * SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W, SWIZZLE_ZERO, SWIZZLE_ONE
1299 * 0 1 2 3 4 5
1300 * 4 5 6 7 0 1
1301 * SCS_RED, SCS_GREEN, SCS_BLUE, SCS_ALPHA, SCS_ZERO, SCS_ONE
1302 *
1303 * which is simply adding 4 then modding by 8 (or anding with 7).
1304 */
1305 static enum isl_channel_select
1306 pipe_swizzle_to_isl_channel(enum pipe_swizzle swizzle)
1307 {
1308 return (swizzle + 4) & 7;
1309 }
1310
1311 /**
1312 * The pipe->create_sampler_view() driver hook.
1313 */
1314 static struct pipe_sampler_view *
1315 iris_create_sampler_view(struct pipe_context *ctx,
1316 struct pipe_resource *tex,
1317 const struct pipe_sampler_view *tmpl)
1318 {
1319 struct iris_context *ice = (struct iris_context *) ctx;
1320 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1321 struct iris_resource *itex = (struct iris_resource *) tex;
1322 struct iris_sampler_view *isv = calloc(1, sizeof(struct iris_sampler_view));
1323
1324 if (!isv)
1325 return NULL;
1326
1327 /* initialize base object */
1328 isv->base = *tmpl;
1329 isv->base.context = ctx;
1330 isv->base.texture = NULL;
1331 pipe_reference_init(&isv->base.reference, 1);
1332 pipe_resource_reference(&isv->base.texture, tex);
1333
1334 void *map = upload_state(ice->state.surface_uploader, &isv->surface_state,
1335 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1336 if (!unlikely(map))
1337 return NULL;
1338
1339 struct iris_bo *state_bo = iris_resource_bo(isv->surface_state.res);
1340 isv->surface_state.offset += iris_bo_offset_from_base_address(state_bo);
1341
1342 /* XXX: do we need brw_get_texture_swizzle hacks here? */
1343 isv->view = (struct isl_view) {
1344 .format = iris_isl_format_for_pipe_format(tmpl->format),
1345 .swizzle = (struct isl_swizzle) {
1346 .r = pipe_swizzle_to_isl_channel(tmpl->swizzle_r),
1347 .g = pipe_swizzle_to_isl_channel(tmpl->swizzle_g),
1348 .b = pipe_swizzle_to_isl_channel(tmpl->swizzle_b),
1349 .a = pipe_swizzle_to_isl_channel(tmpl->swizzle_a),
1350 },
1351 .usage = ISL_SURF_USAGE_TEXTURE_BIT |
1352 (itex->surf.usage & ISL_SURF_USAGE_CUBE_BIT),
1353 };
1354
1355 /* Fill out SURFACE_STATE for this view. */
1356 if (tmpl->target != PIPE_BUFFER) {
1357 isv->view.base_level = tmpl->u.tex.first_level;
1358 isv->view.levels = tmpl->u.tex.last_level - tmpl->u.tex.first_level + 1;
1359 isv->view.base_array_layer = tmpl->u.tex.first_layer;
1360 isv->view.array_len =
1361 tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1;
1362
1363 isl_surf_fill_state(&screen->isl_dev, map,
1364 .surf = &itex->surf, .view = &isv->view,
1365 .mocs = MOCS_WB,
1366 .address = itex->bo->gtt_offset);
1367 // .aux_surf =
1368 // .clear_color = clear_color,
1369 } else {
1370 // XXX: what to do about isv->view? other drivers don't use it for bufs
1371 const struct isl_format_layout *fmtl =
1372 isl_format_get_layout(isv->view.format);
1373 const unsigned cpp = fmtl->bpb / 8;
1374
1375 isl_buffer_fill_state(&screen->isl_dev, map,
1376 .address = itex->bo->gtt_offset +
1377 tmpl->u.buf.offset,
1378 // XXX: buffer_texture_range_size from i965?
1379 .size_B = tmpl->u.buf.size,
1380 .format = isv->view.format,
1381 .stride_B = cpp,
1382 .mocs = MOCS_WB);
1383 }
1384
1385 return &isv->base;
1386 }
1387
1388 static void
1389 iris_sampler_view_destroy(struct pipe_context *ctx,
1390 struct pipe_sampler_view *state)
1391 {
1392 struct iris_sampler_view *isv = (void *) state;
1393 pipe_resource_reference(&state->texture, NULL);
1394 pipe_resource_reference(&isv->surface_state.res, NULL);
1395 free(isv);
1396 }
1397
1398 /**
1399 * The pipe->create_surface() driver hook.
1400 *
1401 * In Gallium nomenclature, "surfaces" are a view of a resource that
1402 * can be bound as a render target or depth/stencil buffer.
1403 */
1404 static struct pipe_surface *
1405 iris_create_surface(struct pipe_context *ctx,
1406 struct pipe_resource *tex,
1407 const struct pipe_surface *tmpl)
1408 {
1409 struct iris_context *ice = (struct iris_context *) ctx;
1410 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1411 const struct gen_device_info *devinfo = &screen->devinfo;
1412 struct iris_surface *surf = calloc(1, sizeof(struct iris_surface));
1413 struct pipe_surface *psurf = &surf->base;
1414 struct iris_resource *res = (struct iris_resource *) tex;
1415
1416 if (!surf)
1417 return NULL;
1418
1419 pipe_reference_init(&psurf->reference, 1);
1420 pipe_resource_reference(&psurf->texture, tex);
1421 psurf->context = ctx;
1422 psurf->format = tmpl->format;
1423 psurf->width = tex->width0;
1424 psurf->height = tex->height0;
1425 psurf->texture = tex;
1426 psurf->u.tex.first_layer = tmpl->u.tex.first_layer;
1427 psurf->u.tex.last_layer = tmpl->u.tex.last_layer;
1428 psurf->u.tex.level = tmpl->u.tex.level;
1429
1430 isl_surf_usage_flags_t usage = 0;
1431 if (tmpl->writable)
1432 usage = ISL_SURF_USAGE_STORAGE_BIT;
1433 else if (util_format_is_depth_or_stencil(tmpl->format))
1434 usage = ISL_SURF_USAGE_DEPTH_BIT;
1435 else
1436 usage = ISL_SURF_USAGE_RENDER_TARGET_BIT;
1437
1438 enum isl_format isl_format =
1439 iris_isl_format_for_usage(devinfo, psurf->format, usage);
1440
1441 if ((usage & ISL_SURF_USAGE_RENDER_TARGET_BIT) &&
1442 !isl_format_supports_rendering(devinfo, isl_format)) {
1443 /* Framebuffer validation will reject this invalid case, but it
1444 * hasn't had the opportunity yet. In the meantime, we need to
1445 * avoid hitting ISL asserts about unsupported formats below.
1446 */
1447 free(surf);
1448 return NULL;
1449 }
1450
1451 surf->view = (struct isl_view) {
1452 .format = isl_format,
1453 .base_level = tmpl->u.tex.level,
1454 .levels = 1,
1455 .base_array_layer = tmpl->u.tex.first_layer,
1456 .array_len = tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1,
1457 .swizzle = ISL_SWIZZLE_IDENTITY,
1458 .usage = usage,
1459 };
1460
1461 /* Bail early for depth/stencil - we don't want SURFACE_STATE for them. */
1462 if (res->surf.usage & (ISL_SURF_USAGE_DEPTH_BIT |
1463 ISL_SURF_USAGE_STENCIL_BIT))
1464 return psurf;
1465
1466
1467 void *map = upload_state(ice->state.surface_uploader, &surf->surface_state,
1468 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1469 if (!unlikely(map))
1470 return NULL;
1471
1472 struct iris_bo *state_bo = iris_resource_bo(surf->surface_state.res);
1473 surf->surface_state.offset += iris_bo_offset_from_base_address(state_bo);
1474
1475 isl_surf_fill_state(&screen->isl_dev, map,
1476 .surf = &res->surf, .view = &surf->view,
1477 .mocs = MOCS_WB,
1478 .address = res->bo->gtt_offset);
1479 // .aux_surf =
1480 // .clear_color = clear_color,
1481
1482 return psurf;
1483 }
1484
1485 /**
1486 * The pipe->set_sampler_views() driver hook.
1487 */
1488 static void
1489 iris_set_sampler_views(struct pipe_context *ctx,
1490 enum pipe_shader_type p_stage,
1491 unsigned start, unsigned count,
1492 struct pipe_sampler_view **views)
1493 {
1494 struct iris_context *ice = (struct iris_context *) ctx;
1495 gl_shader_stage stage = stage_from_pipe(p_stage);
1496 struct iris_shader_state *shs = &ice->state.shaders[stage];
1497
1498 unsigned i;
1499 for (i = 0; i < count; i++) {
1500 pipe_sampler_view_reference((struct pipe_sampler_view **)
1501 &shs->textures[i], views[i]);
1502 }
1503 for (; i < shs->num_textures; i++) {
1504 pipe_sampler_view_reference((struct pipe_sampler_view **)
1505 &shs->textures[i], NULL);
1506 }
1507
1508 shs->num_textures = count;
1509
1510 ice->state.dirty |= (IRIS_DIRTY_BINDINGS_VS << stage);
1511 }
1512
1513 static void
1514 iris_surface_destroy(struct pipe_context *ctx, struct pipe_surface *p_surf)
1515 {
1516 struct iris_surface *surf = (void *) p_surf;
1517 pipe_resource_reference(&p_surf->texture, NULL);
1518 pipe_resource_reference(&surf->surface_state.res, NULL);
1519 free(surf);
1520 }
1521
1522 // XXX: actually implement user clip planes
1523 static void
1524 iris_set_clip_state(struct pipe_context *ctx,
1525 const struct pipe_clip_state *state)
1526 {
1527 }
1528
1529 /**
1530 * The pipe->set_polygon_stipple() driver hook.
1531 */
1532 static void
1533 iris_set_polygon_stipple(struct pipe_context *ctx,
1534 const struct pipe_poly_stipple *state)
1535 {
1536 struct iris_context *ice = (struct iris_context *) ctx;
1537 memcpy(&ice->state.poly_stipple, state, sizeof(*state));
1538 ice->state.dirty |= IRIS_DIRTY_POLYGON_STIPPLE;
1539 }
1540
1541 /**
1542 * The pipe->set_sample_mask() driver hook.
1543 */
1544 static void
1545 iris_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
1546 {
1547 struct iris_context *ice = (struct iris_context *) ctx;
1548
1549 /* We only support 16x MSAA, so we have 16 bits of sample maks.
1550 * st/mesa may pass us 0xffffffff though, meaning "enable all samples".
1551 */
1552 ice->state.sample_mask = sample_mask & 0xffff;
1553 ice->state.dirty |= IRIS_DIRTY_SAMPLE_MASK;
1554 }
1555
1556 /**
1557 * The pipe->set_scissor_states() driver hook.
1558 *
1559 * This corresponds to our SCISSOR_RECT state structures. It's an
1560 * exact match, so we just store them, and memcpy them out later.
1561 */
1562 static void
1563 iris_set_scissor_states(struct pipe_context *ctx,
1564 unsigned start_slot,
1565 unsigned num_scissors,
1566 const struct pipe_scissor_state *states)
1567 {
1568 struct iris_context *ice = (struct iris_context *) ctx;
1569
1570 for (unsigned i = 0; i < num_scissors; i++) {
1571 ice->state.scissors[start_slot + i] = states[i];
1572 }
1573
1574 ice->state.dirty |= IRIS_DIRTY_SCISSOR_RECT;
1575 }
1576
1577 /**
1578 * The pipe->set_stencil_ref() driver hook.
1579 *
1580 * This is added to 3DSTATE_WM_DEPTH_STENCIL dynamically at draw time.
1581 */
1582 static void
1583 iris_set_stencil_ref(struct pipe_context *ctx,
1584 const struct pipe_stencil_ref *state)
1585 {
1586 struct iris_context *ice = (struct iris_context *) ctx;
1587 memcpy(&ice->state.stencil_ref, state, sizeof(*state));
1588 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
1589 }
1590
1591 static float
1592 viewport_extent(const struct pipe_viewport_state *state, int axis, float sign)
1593 {
1594 return copysignf(state->scale[axis], sign) + state->translate[axis];
1595 }
1596
1597 #if 0
1598 static void
1599 calculate_guardband_size(uint32_t fb_width, uint32_t fb_height,
1600 float m00, float m11, float m30, float m31,
1601 float *xmin, float *xmax,
1602 float *ymin, float *ymax)
1603 {
1604 /* According to the "Vertex X,Y Clamping and Quantization" section of the
1605 * Strips and Fans documentation:
1606 *
1607 * "The vertex X and Y screen-space coordinates are also /clamped/ to the
1608 * fixed-point "guardband" range supported by the rasterization hardware"
1609 *
1610 * and
1611 *
1612 * "In almost all circumstances, if an object’s vertices are actually
1613 * modified by this clamping (i.e., had X or Y coordinates outside of
1614 * the guardband extent the rendered object will not match the intended
1615 * result. Therefore software should take steps to ensure that this does
1616 * not happen - e.g., by clipping objects such that they do not exceed
1617 * these limits after the Drawing Rectangle is applied."
1618 *
1619 * I believe the fundamental restriction is that the rasterizer (in
1620 * the SF/WM stages) have a limit on the number of pixels that can be
1621 * rasterized. We need to ensure any coordinates beyond the rasterizer
1622 * limit are handled by the clipper. So effectively that limit becomes
1623 * the clipper's guardband size.
1624 *
1625 * It goes on to say:
1626 *
1627 * "In addition, in order to be correctly rendered, objects must have a
1628 * screenspace bounding box not exceeding 8K in the X or Y direction.
1629 * This additional restriction must also be comprehended by software,
1630 * i.e., enforced by use of clipping."
1631 *
1632 * This makes no sense. Gen7+ hardware supports 16K render targets,
1633 * and you definitely need to be able to draw polygons that fill the
1634 * surface. Our assumption is that the rasterizer was limited to 8K
1635 * on Sandybridge, which only supports 8K surfaces, and it was actually
1636 * increased to 16K on Ivybridge and later.
1637 *
1638 * So, limit the guardband to 16K on Gen7+ and 8K on Sandybridge.
1639 */
1640 const float gb_size = GEN_GEN >= 7 ? 16384.0f : 8192.0f;
1641
1642 if (m00 != 0 && m11 != 0) {
1643 /* First, we compute the screen-space render area */
1644 const float ss_ra_xmin = MIN3( 0, m30 + m00, m30 - m00);
1645 const float ss_ra_xmax = MAX3( fb_width, m30 + m00, m30 - m00);
1646 const float ss_ra_ymin = MIN3( 0, m31 + m11, m31 - m11);
1647 const float ss_ra_ymax = MAX3(fb_height, m31 + m11, m31 - m11);
1648
1649 /* We want the guardband to be centered on that */
1650 const float ss_gb_xmin = (ss_ra_xmin + ss_ra_xmax) / 2 - gb_size;
1651 const float ss_gb_xmax = (ss_ra_xmin + ss_ra_xmax) / 2 + gb_size;
1652 const float ss_gb_ymin = (ss_ra_ymin + ss_ra_ymax) / 2 - gb_size;
1653 const float ss_gb_ymax = (ss_ra_ymin + ss_ra_ymax) / 2 + gb_size;
1654
1655 /* Now we need it in native device coordinates */
1656 const float ndc_gb_xmin = (ss_gb_xmin - m30) / m00;
1657 const float ndc_gb_xmax = (ss_gb_xmax - m30) / m00;
1658 const float ndc_gb_ymin = (ss_gb_ymin - m31) / m11;
1659 const float ndc_gb_ymax = (ss_gb_ymax - m31) / m11;
1660
1661 /* Thanks to Y-flipping and ORIGIN_UPPER_LEFT, the Y coordinates may be
1662 * flipped upside-down. X should be fine though.
1663 */
1664 assert(ndc_gb_xmin <= ndc_gb_xmax);
1665 *xmin = ndc_gb_xmin;
1666 *xmax = ndc_gb_xmax;
1667 *ymin = MIN2(ndc_gb_ymin, ndc_gb_ymax);
1668 *ymax = MAX2(ndc_gb_ymin, ndc_gb_ymax);
1669 } else {
1670 /* The viewport scales to 0, so nothing will be rendered. */
1671 *xmin = 0.0f;
1672 *xmax = 0.0f;
1673 *ymin = 0.0f;
1674 *ymax = 0.0f;
1675 }
1676 }
1677 #endif
1678
1679 /**
1680 * The pipe->set_viewport_states() driver hook.
1681 *
1682 * This corresponds to our SF_CLIP_VIEWPORT states. We can't calculate
1683 * the guardband yet, as we need the framebuffer dimensions, but we can
1684 * at least fill out the rest.
1685 */
1686 static void
1687 iris_set_viewport_states(struct pipe_context *ctx,
1688 unsigned start_slot,
1689 unsigned count,
1690 const struct pipe_viewport_state *states)
1691 {
1692 struct iris_context *ice = (struct iris_context *) ctx;
1693 struct iris_genx_state *genx = ice->state.genx;
1694 uint32_t *vp_map = &genx->sf_cl_vp[start_slot];
1695
1696 for (unsigned i = 0; i < count; i++) {
1697 const struct pipe_viewport_state *state = &states[i];
1698
1699 memcpy(&ice->state.viewports[start_slot + i], state, sizeof(*state));
1700
1701 iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
1702 vp.ViewportMatrixElementm00 = state->scale[0];
1703 vp.ViewportMatrixElementm11 = state->scale[1];
1704 vp.ViewportMatrixElementm22 = state->scale[2];
1705 vp.ViewportMatrixElementm30 = state->translate[0];
1706 vp.ViewportMatrixElementm31 = state->translate[1];
1707 vp.ViewportMatrixElementm32 = state->translate[2];
1708 /* XXX: in i965 this is computed based on the drawbuffer size,
1709 * but we don't have that here...
1710 */
1711 vp.XMinClipGuardband = -1.0;
1712 vp.XMaxClipGuardband = 1.0;
1713 vp.YMinClipGuardband = -1.0;
1714 vp.YMaxClipGuardband = 1.0;
1715 vp.XMinViewPort = viewport_extent(state, 0, -1.0f);
1716 vp.XMaxViewPort = viewport_extent(state, 0, 1.0f) - 1;
1717 vp.YMinViewPort = viewport_extent(state, 1, -1.0f);
1718 vp.YMaxViewPort = viewport_extent(state, 1, 1.0f) - 1;
1719 }
1720
1721 vp_map += GENX(SF_CLIP_VIEWPORT_length);
1722 }
1723
1724 ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
1725
1726 if (ice->state.cso_rast && (!ice->state.cso_rast->depth_clip_near ||
1727 !ice->state.cso_rast->depth_clip_far))
1728 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
1729 }
1730
1731 /**
1732 * The pipe->set_framebuffer_state() driver hook.
1733 *
1734 * Sets the current draw FBO, including color render targets, depth,
1735 * and stencil buffers.
1736 */
1737 static void
1738 iris_set_framebuffer_state(struct pipe_context *ctx,
1739 const struct pipe_framebuffer_state *state)
1740 {
1741 struct iris_context *ice = (struct iris_context *) ctx;
1742 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1743 struct isl_device *isl_dev = &screen->isl_dev;
1744 struct pipe_framebuffer_state *cso = &ice->state.framebuffer;
1745 struct iris_resource *zres;
1746 struct iris_resource *stencil_res;
1747
1748 unsigned samples = util_framebuffer_get_num_samples(state);
1749
1750 if (cso->samples != samples) {
1751 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
1752 }
1753
1754 if (cso->nr_cbufs != state->nr_cbufs) {
1755 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
1756 }
1757
1758 if ((cso->layers == 0) != (state->layers == 0)) {
1759 ice->state.dirty |= IRIS_DIRTY_CLIP;
1760 }
1761
1762 util_copy_framebuffer_state(cso, state);
1763 cso->samples = samples;
1764
1765 struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
1766
1767 struct isl_view view = {
1768 .base_level = 0,
1769 .levels = 1,
1770 .base_array_layer = 0,
1771 .array_len = 1,
1772 .swizzle = ISL_SWIZZLE_IDENTITY,
1773 };
1774
1775 struct isl_depth_stencil_hiz_emit_info info = {
1776 .view = &view,
1777 .mocs = MOCS_WB,
1778 };
1779
1780 if (cso->zsbuf) {
1781 iris_get_depth_stencil_resources(cso->zsbuf->texture, &zres,
1782 &stencil_res);
1783
1784 view.base_level = cso->zsbuf->u.tex.level;
1785 view.base_array_layer = cso->zsbuf->u.tex.first_layer;
1786 view.array_len =
1787 cso->zsbuf->u.tex.last_layer - cso->zsbuf->u.tex.first_layer + 1;
1788
1789 if (zres) {
1790 view.usage |= ISL_SURF_USAGE_DEPTH_BIT;
1791
1792 info.depth_surf = &zres->surf;
1793 info.depth_address = zres->bo->gtt_offset;
1794 info.hiz_usage = ISL_AUX_USAGE_NONE;
1795
1796 view.format = zres->surf.format;
1797 }
1798
1799 if (stencil_res) {
1800 view.usage |= ISL_SURF_USAGE_STENCIL_BIT;
1801 info.stencil_surf = &stencil_res->surf;
1802 info.stencil_address = stencil_res->bo->gtt_offset;
1803 if (!zres)
1804 view.format = stencil_res->surf.format;
1805 }
1806 }
1807
1808 isl_emit_depth_stencil_hiz_s(isl_dev, cso_z->packets, &info);
1809
1810 /* Make a null surface for unbound buffers */
1811 void *null_surf_map =
1812 upload_state(ice->state.surface_uploader, &ice->state.null_fb,
1813 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1814 isl_null_fill_state(&screen->isl_dev, null_surf_map, isl_extent3d(cso->width, cso->height, cso->layers ? cso->layers : 1));
1815 ice->state.null_fb.offset +=
1816 iris_bo_offset_from_base_address(iris_resource_bo(ice->state.null_fb.res));
1817
1818 ice->state.dirty |= IRIS_DIRTY_DEPTH_BUFFER;
1819
1820 /* Render target change */
1821 ice->state.dirty |= IRIS_DIRTY_BINDINGS_FS;
1822
1823 ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_FRAMEBUFFER];
1824
1825 #if GEN_GEN == 11
1826 // XXX: we may want to flag IRIS_DIRTY_MULTISAMPLE (or SAMPLE_MASK?)
1827 // XXX: see commit 979fc1bc9bcc64027ff2cfafd285676f31b930a6
1828
1829 /* The PIPE_CONTROL command description says:
1830 *
1831 * "Whenever a Binding Table Index (BTI) used by a Render Target Message
1832 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
1833 * Target Cache Flush by enabling this bit. When render target flush
1834 * is set due to new association of BTI, PS Scoreboard Stall bit must
1835 * be set in this packet."
1836 */
1837 // XXX: does this need to happen at 3DSTATE_BTP_PS time?
1838 iris_emit_pipe_control_flush(&ice->render_batch,
1839 PIPE_CONTROL_RENDER_TARGET_FLUSH |
1840 PIPE_CONTROL_STALL_AT_SCOREBOARD);
1841 #endif
1842 }
1843
1844 /**
1845 * The pipe->set_constant_buffer() driver hook.
1846 *
1847 * This uploads any constant data in user buffers, and references
1848 * any UBO resources containing constant data.
1849 */
1850 static void
1851 iris_set_constant_buffer(struct pipe_context *ctx,
1852 enum pipe_shader_type p_stage, unsigned index,
1853 const struct pipe_constant_buffer *input)
1854 {
1855 struct iris_context *ice = (struct iris_context *) ctx;
1856 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1857 gl_shader_stage stage = stage_from_pipe(p_stage);
1858 struct iris_shader_state *shs = &ice->state.shaders[stage];
1859 struct iris_const_buffer *cbuf = &shs->constbuf[index];
1860
1861 if (input && (input->buffer || input->user_buffer)) {
1862 if (input->user_buffer) {
1863 u_upload_data(ctx->const_uploader, 0, input->buffer_size, 32,
1864 input->user_buffer, &cbuf->data.offset,
1865 &cbuf->data.res);
1866 } else {
1867 pipe_resource_reference(&cbuf->data.res, input->buffer);
1868 }
1869
1870 // XXX: these are not retained forever, use a separate uploader?
1871 void *map =
1872 upload_state(ice->state.surface_uploader, &cbuf->surface_state,
1873 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1874 if (!unlikely(map)) {
1875 pipe_resource_reference(&cbuf->data.res, NULL);
1876 return;
1877 }
1878
1879 struct iris_resource *res = (void *) cbuf->data.res;
1880 struct iris_bo *surf_bo = iris_resource_bo(cbuf->surface_state.res);
1881 cbuf->surface_state.offset += iris_bo_offset_from_base_address(surf_bo);
1882
1883 isl_buffer_fill_state(&screen->isl_dev, map,
1884 .address = res->bo->gtt_offset + cbuf->data.offset,
1885 .size_B = input->buffer_size,
1886 .format = ISL_FORMAT_R32G32B32A32_FLOAT,
1887 .stride_B = 1,
1888 .mocs = MOCS_WB)
1889 } else {
1890 pipe_resource_reference(&cbuf->data.res, NULL);
1891 pipe_resource_reference(&cbuf->surface_state.res, NULL);
1892 }
1893
1894 ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS << stage;
1895 // XXX: maybe not necessary all the time...?
1896 // XXX: we need 3DS_BTP to commit these changes, and if we fell back to
1897 // XXX: pull model we may need actual new bindings...
1898 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
1899 }
1900
1901 /**
1902 * The pipe->set_shader_buffers() driver hook.
1903 *
1904 * This binds SSBOs and ABOs. Unfortunately, we need to stream out
1905 * SURFACE_STATE here, as the buffer offset may change each time.
1906 */
1907 static void
1908 iris_set_shader_buffers(struct pipe_context *ctx,
1909 enum pipe_shader_type p_stage,
1910 unsigned start_slot, unsigned count,
1911 const struct pipe_shader_buffer *buffers)
1912 {
1913 struct iris_context *ice = (struct iris_context *) ctx;
1914 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1915 gl_shader_stage stage = stage_from_pipe(p_stage);
1916 struct iris_shader_state *shs = &ice->state.shaders[stage];
1917
1918 for (unsigned i = 0; i < count; i++) {
1919 if (buffers && buffers[i].buffer) {
1920 const struct pipe_shader_buffer *buffer = &buffers[i];
1921 struct iris_resource *res = (void *) buffer->buffer;
1922 pipe_resource_reference(&shs->ssbo[start_slot + i], &res->base);
1923
1924 // XXX: these are not retained forever, use a separate uploader?
1925 void *map =
1926 upload_state(ice->state.surface_uploader,
1927 &shs->ssbo_surface_state[start_slot + i],
1928 4 * GENX(RENDER_SURFACE_STATE_length), 64);
1929 if (!unlikely(map)) {
1930 pipe_resource_reference(&shs->ssbo[start_slot + i], NULL);
1931 return;
1932 }
1933
1934 struct iris_bo *surf_state_bo =
1935 iris_resource_bo(shs->ssbo_surface_state[start_slot + i].res);
1936 shs->ssbo_surface_state[start_slot + i].offset +=
1937 iris_bo_offset_from_base_address(surf_state_bo);
1938
1939 isl_buffer_fill_state(&screen->isl_dev, map,
1940 .address =
1941 res->bo->gtt_offset + buffer->buffer_offset,
1942 .size_B = buffer->buffer_size,
1943 .format = ISL_FORMAT_RAW,
1944 .stride_B = 1,
1945 .mocs = MOCS_WB);
1946 } else {
1947 pipe_resource_reference(&shs->ssbo[start_slot + i], NULL);
1948 pipe_resource_reference(&shs->ssbo_surface_state[start_slot + i].res,
1949 NULL);
1950 }
1951 }
1952
1953 ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
1954 }
1955
1956 static void
1957 iris_delete_state(struct pipe_context *ctx, void *state)
1958 {
1959 free(state);
1960 }
1961
1962 static void
1963 iris_free_vertex_buffers(struct iris_vertex_buffer_state *cso)
1964 {
1965 for (unsigned i = 0; i < cso->num_buffers; i++)
1966 pipe_resource_reference(&cso->resources[i], NULL);
1967 }
1968
1969 /**
1970 * The pipe->set_vertex_buffers() driver hook.
1971 *
1972 * This translates pipe_vertex_buffer to our 3DSTATE_VERTEX_BUFFERS packet.
1973 */
1974 static void
1975 iris_set_vertex_buffers(struct pipe_context *ctx,
1976 unsigned start_slot, unsigned count,
1977 const struct pipe_vertex_buffer *buffers)
1978 {
1979 struct iris_context *ice = (struct iris_context *) ctx;
1980 struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
1981
1982 iris_free_vertex_buffers(&ice->state.genx->vertex_buffers);
1983
1984 if (!buffers)
1985 count = 0;
1986
1987 cso->num_buffers = count;
1988
1989 iris_pack_command(GENX(3DSTATE_VERTEX_BUFFERS), cso->vertex_buffers, vb) {
1990 vb.DWordLength = 4 * MAX2(cso->num_buffers, 1) - 1;
1991 }
1992
1993 uint32_t *vb_pack_dest = &cso->vertex_buffers[1];
1994
1995 if (count == 0) {
1996 iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
1997 vb.VertexBufferIndex = start_slot;
1998 vb.NullVertexBuffer = true;
1999 vb.AddressModifyEnable = true;
2000 }
2001 }
2002
2003 for (unsigned i = 0; i < count; i++) {
2004 assert(!buffers[i].is_user_buffer);
2005
2006 pipe_resource_reference(&cso->resources[i], buffers[i].buffer.resource);
2007 struct iris_resource *res = (void *) cso->resources[i];
2008
2009 iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
2010 vb.VertexBufferIndex = start_slot + i;
2011 vb.MOCS = MOCS_WB;
2012 vb.AddressModifyEnable = true;
2013 vb.BufferPitch = buffers[i].stride;
2014 vb.BufferSize = res->bo->size;
2015 vb.BufferStartingAddress =
2016 ro_bo(NULL, res->bo->gtt_offset + buffers[i].buffer_offset);
2017 }
2018
2019 vb_pack_dest += GENX(VERTEX_BUFFER_STATE_length);
2020 }
2021
2022 ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
2023 }
2024
2025 /**
2026 * Gallium CSO for vertex elements.
2027 */
2028 struct iris_vertex_element_state {
2029 uint32_t vertex_elements[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
2030 uint32_t vf_instancing[33 * GENX(3DSTATE_VF_INSTANCING_length)];
2031 unsigned count;
2032 };
2033
2034 /**
2035 * The pipe->create_vertex_elements() driver hook.
2036 *
2037 * This translates pipe_vertex_element to our 3DSTATE_VERTEX_ELEMENTS
2038 * and 3DSTATE_VF_INSTANCING commands. SGVs are handled at draw time.
2039 */
2040 static void *
2041 iris_create_vertex_elements(struct pipe_context *ctx,
2042 unsigned count,
2043 const struct pipe_vertex_element *state)
2044 {
2045 struct iris_vertex_element_state *cso =
2046 malloc(sizeof(struct iris_vertex_element_state));
2047
2048 cso->count = count;
2049
2050 /* TODO:
2051 * - create edge flag one
2052 * - create SGV ones
2053 * - if those are necessary, use count + 1/2/3... OR in the length
2054 */
2055 iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS), cso->vertex_elements, ve) {
2056 ve.DWordLength =
2057 1 + GENX(VERTEX_ELEMENT_STATE_length) * MAX2(count, 1) - 2;
2058 }
2059
2060 uint32_t *ve_pack_dest = &cso->vertex_elements[1];
2061 uint32_t *vfi_pack_dest = cso->vf_instancing;
2062
2063 if (count == 0) {
2064 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
2065 ve.Valid = true;
2066 ve.SourceElementFormat = ISL_FORMAT_R32G32B32A32_FLOAT;
2067 ve.Component0Control = VFCOMP_STORE_0;
2068 ve.Component1Control = VFCOMP_STORE_0;
2069 ve.Component2Control = VFCOMP_STORE_0;
2070 ve.Component3Control = VFCOMP_STORE_1_FP;
2071 }
2072
2073 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
2074 }
2075 }
2076
2077 for (int i = 0; i < count; i++) {
2078 enum isl_format isl_format =
2079 iris_isl_format_for_pipe_format(state[i].src_format);
2080 unsigned comp[4] = { VFCOMP_STORE_SRC, VFCOMP_STORE_SRC,
2081 VFCOMP_STORE_SRC, VFCOMP_STORE_SRC };
2082
2083 switch (isl_format_get_num_channels(isl_format)) {
2084 case 0: comp[0] = VFCOMP_STORE_0;
2085 case 1: comp[1] = VFCOMP_STORE_0;
2086 case 2: comp[2] = VFCOMP_STORE_0;
2087 case 3:
2088 comp[3] = isl_format_has_int_channel(isl_format) ? VFCOMP_STORE_1_INT
2089 : VFCOMP_STORE_1_FP;
2090 break;
2091 }
2092 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
2093 ve.VertexBufferIndex = state[i].vertex_buffer_index;
2094 ve.Valid = true;
2095 ve.SourceElementOffset = state[i].src_offset;
2096 ve.SourceElementFormat = isl_format;
2097 ve.Component0Control = comp[0];
2098 ve.Component1Control = comp[1];
2099 ve.Component2Control = comp[2];
2100 ve.Component3Control = comp[3];
2101 }
2102
2103 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
2104 vi.VertexElementIndex = i;
2105 vi.InstancingEnable = state[i].instance_divisor > 0;
2106 vi.InstanceDataStepRate = state[i].instance_divisor;
2107 }
2108
2109 ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
2110 vfi_pack_dest += GENX(3DSTATE_VF_INSTANCING_length);
2111 }
2112
2113 return cso;
2114 }
2115
2116 /**
2117 * The pipe->bind_vertex_elements_state() driver hook.
2118 */
2119 static void
2120 iris_bind_vertex_elements_state(struct pipe_context *ctx, void *state)
2121 {
2122 struct iris_context *ice = (struct iris_context *) ctx;
2123 struct iris_vertex_element_state *old_cso = ice->state.cso_vertex_elements;
2124 struct iris_vertex_element_state *new_cso = state;
2125
2126 /* 3DSTATE_VF_SGVs overrides the last VE, so if the count is changing,
2127 * we need to re-emit it to ensure we're overriding the right one.
2128 */
2129 if (new_cso && cso_changed(count))
2130 ice->state.dirty |= IRIS_DIRTY_VF_SGVS;
2131
2132 ice->state.cso_vertex_elements = state;
2133 ice->state.dirty |= IRIS_DIRTY_VERTEX_ELEMENTS;
2134 }
2135
2136 static void *
2137 iris_create_compute_state(struct pipe_context *ctx,
2138 const struct pipe_compute_state *state)
2139 {
2140 // XXX: actually do something
2141 return malloc(1);
2142 }
2143
2144 /**
2145 * Gallium CSO for stream output (transform feedback) targets.
2146 */
2147 struct iris_stream_output_target {
2148 struct pipe_stream_output_target base;
2149
2150 uint32_t so_buffer[GENX(3DSTATE_SO_BUFFER_length)];
2151
2152 /** Storage holding the offset where we're writing in the buffer */
2153 struct iris_state_ref offset;
2154 };
2155
2156 /**
2157 * The pipe->create_stream_output_target() driver hook.
2158 *
2159 * "Target" here refers to a destination buffer. We translate this into
2160 * a 3DSTATE_SO_BUFFER packet. We can handle most fields, but don't yet
2161 * know which buffer this represents, or whether we ought to zero the
2162 * write-offsets, or append. Those are handled in the set() hook.
2163 */
2164 static struct pipe_stream_output_target *
2165 iris_create_stream_output_target(struct pipe_context *ctx,
2166 struct pipe_resource *res,
2167 unsigned buffer_offset,
2168 unsigned buffer_size)
2169 {
2170 struct iris_stream_output_target *cso = calloc(1, sizeof(*cso));
2171 if (!cso)
2172 return NULL;
2173
2174 pipe_reference_init(&cso->base.reference, 1);
2175 pipe_resource_reference(&cso->base.buffer, res);
2176 cso->base.buffer_offset = buffer_offset;
2177 cso->base.buffer_size = buffer_size;
2178 cso->base.context = ctx;
2179
2180 upload_state(ctx->stream_uploader, &cso->offset, 4 * sizeof(uint32_t), 4);
2181
2182 iris_pack_command(GENX(3DSTATE_SO_BUFFER), cso->so_buffer, sob) {
2183 sob.SurfaceBaseAddress =
2184 rw_bo(NULL, iris_resource_bo(res)->gtt_offset + buffer_offset);
2185 sob.SOBufferEnable = true;
2186 sob.StreamOffsetWriteEnable = true;
2187 sob.StreamOutputBufferOffsetAddressEnable = true;
2188 sob.MOCS = MOCS_WB; // XXX: MOCS
2189
2190 sob.SurfaceSize = MAX2(buffer_size / 4, 1) - 1;
2191
2192 /* .SOBufferIndex, .StreamOffset, and .StreamOutputBufferOffsetAddress
2193 * are filled in later when we have stream IDs.
2194 */
2195 }
2196
2197 return &cso->base;
2198 }
2199
2200 static void
2201 iris_stream_output_target_destroy(struct pipe_context *ctx,
2202 struct pipe_stream_output_target *state)
2203 {
2204 struct iris_stream_output_target *cso = (void *) state;
2205
2206 pipe_resource_reference(&cso->base.buffer, NULL);
2207 pipe_resource_reference(&cso->offset.res, NULL);
2208
2209 free(cso);
2210 }
2211
2212 /**
2213 * The pipe->set_stream_output_targets() driver hook.
2214 *
2215 * At this point, we know which targets are bound to a particular index,
2216 * and also whether we want to append or start over. We can finish the
2217 * 3DSTATE_SO_BUFFER packets we started earlier.
2218 */
2219 static void
2220 iris_set_stream_output_targets(struct pipe_context *ctx,
2221 unsigned num_targets,
2222 struct pipe_stream_output_target **targets,
2223 const unsigned *offsets)
2224 {
2225 struct iris_context *ice = (struct iris_context *) ctx;
2226 struct iris_genx_state *genx = ice->state.genx;
2227 uint32_t *so_buffers = genx->so_buffers;
2228
2229 const bool active = num_targets > 0;
2230 if (ice->state.streamout_active != active) {
2231 ice->state.streamout_active = active;
2232 ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
2233 }
2234
2235 for (int i = 0; i < 4; i++) {
2236 pipe_so_target_reference(&ice->state.so_target[i],
2237 i < num_targets ? targets[i] : NULL);
2238 }
2239
2240 /* No need to update 3DSTATE_SO_BUFFER unless SOL is active. */
2241 if (!active)
2242 return;
2243
2244 for (unsigned i = 0; i < 4; i++,
2245 so_buffers += GENX(3DSTATE_SO_BUFFER_length)) {
2246
2247 if (i >= num_targets || !targets[i]) {
2248 iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob)
2249 sob.SOBufferIndex = i;
2250 continue;
2251 }
2252
2253 struct iris_stream_output_target *tgt = (void *) targets[i];
2254
2255 /* Note that offsets[i] will either be 0, causing us to zero
2256 * the value in the buffer, or 0xFFFFFFFF, which happens to mean
2257 * "continue appending at the existing offset."
2258 */
2259 assert(offsets[i] == 0 || offsets[i] == 0xFFFFFFFF);
2260
2261 uint32_t dynamic[GENX(3DSTATE_SO_BUFFER_length)];
2262 iris_pack_state(GENX(3DSTATE_SO_BUFFER), dynamic, dyns) {
2263 dyns.SOBufferIndex = i;
2264 dyns.StreamOffset = offsets[i];
2265 dyns.StreamOutputBufferOffsetAddress =
2266 rw_bo(NULL, iris_resource_bo(tgt->offset.res)->gtt_offset + tgt->offset.offset + i * sizeof(uint32_t));
2267 }
2268
2269 for (uint32_t j = 0; j < GENX(3DSTATE_SO_BUFFER_length); j++) {
2270 so_buffers[j] = tgt->so_buffer[j] | dynamic[j];
2271 }
2272 }
2273
2274 ice->state.dirty |= IRIS_DIRTY_SO_BUFFERS;
2275 }
2276
2277 /**
2278 * An iris-vtable helper for encoding the 3DSTATE_SO_DECL_LIST and
2279 * 3DSTATE_STREAMOUT packets.
2280 *
2281 * 3DSTATE_SO_DECL_LIST is a list of shader outputs we want the streamout
2282 * hardware to record. We can create it entirely based on the shader, with
2283 * no dynamic state dependencies.
2284 *
2285 * 3DSTATE_STREAMOUT is an annoying mix of shader-based information and
2286 * state-based settings. We capture the shader-related ones here, and merge
2287 * the rest in at draw time.
2288 */
2289 static uint32_t *
2290 iris_create_so_decl_list(const struct pipe_stream_output_info *info,
2291 const struct brw_vue_map *vue_map)
2292 {
2293 struct GENX(SO_DECL) so_decl[MAX_VERTEX_STREAMS][128];
2294 int buffer_mask[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
2295 int next_offset[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
2296 int decls[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
2297 int max_decls = 0;
2298 STATIC_ASSERT(ARRAY_SIZE(so_decl[0]) >= MAX_PROGRAM_OUTPUTS);
2299
2300 memset(so_decl, 0, sizeof(so_decl));
2301
2302 /* Construct the list of SO_DECLs to be emitted. The formatting of the
2303 * command feels strange -- each dword pair contains a SO_DECL per stream.
2304 */
2305 for (unsigned i = 0; i < info->num_outputs; i++) {
2306 const struct pipe_stream_output *output = &info->output[i];
2307 const int buffer = output->output_buffer;
2308 const int varying = output->register_index;
2309 const unsigned stream_id = output->stream;
2310 assert(stream_id < MAX_VERTEX_STREAMS);
2311
2312 buffer_mask[stream_id] |= 1 << buffer;
2313
2314 assert(vue_map->varying_to_slot[varying] >= 0);
2315
2316 /* Mesa doesn't store entries for gl_SkipComponents in the Outputs[]
2317 * array. Instead, it simply increments DstOffset for the following
2318 * input by the number of components that should be skipped.
2319 *
2320 * Our hardware is unusual in that it requires us to program SO_DECLs
2321 * for fake "hole" components, rather than simply taking the offset
2322 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
2323 * program as many size = 4 holes as we can, then a final hole to
2324 * accommodate the final 1, 2, or 3 remaining.
2325 */
2326 int skip_components = output->dst_offset - next_offset[buffer];
2327
2328 while (skip_components > 0) {
2329 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
2330 .HoleFlag = 1,
2331 .OutputBufferSlot = output->output_buffer,
2332 .ComponentMask = (1 << MIN2(skip_components, 4)) - 1,
2333 };
2334 skip_components -= 4;
2335 }
2336
2337 next_offset[buffer] = output->dst_offset + output->num_components;
2338
2339 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
2340 .OutputBufferSlot = output->output_buffer,
2341 .RegisterIndex = vue_map->varying_to_slot[varying],
2342 .ComponentMask =
2343 ((1 << output->num_components) - 1) << output->start_component,
2344 };
2345
2346 if (decls[stream_id] > max_decls)
2347 max_decls = decls[stream_id];
2348 }
2349
2350 unsigned dwords = GENX(3DSTATE_STREAMOUT_length) + (3 + 2 * max_decls);
2351 uint32_t *map = ralloc_size(NULL, sizeof(uint32_t) * dwords);
2352 uint32_t *so_decl_map = map + GENX(3DSTATE_STREAMOUT_length);
2353
2354 iris_pack_command(GENX(3DSTATE_STREAMOUT), map, sol) {
2355 int urb_entry_read_offset = 0;
2356 int urb_entry_read_length = (vue_map->num_slots + 1) / 2 -
2357 urb_entry_read_offset;
2358
2359 /* We always read the whole vertex. This could be reduced at some
2360 * point by reading less and offsetting the register index in the
2361 * SO_DECLs.
2362 */
2363 sol.Stream0VertexReadOffset = urb_entry_read_offset;
2364 sol.Stream0VertexReadLength = urb_entry_read_length - 1;
2365 sol.Stream1VertexReadOffset = urb_entry_read_offset;
2366 sol.Stream1VertexReadLength = urb_entry_read_length - 1;
2367 sol.Stream2VertexReadOffset = urb_entry_read_offset;
2368 sol.Stream2VertexReadLength = urb_entry_read_length - 1;
2369 sol.Stream3VertexReadOffset = urb_entry_read_offset;
2370 sol.Stream3VertexReadLength = urb_entry_read_length - 1;
2371
2372 /* Set buffer pitches; 0 means unbound. */
2373 sol.Buffer0SurfacePitch = 4 * info->stride[0];
2374 sol.Buffer1SurfacePitch = 4 * info->stride[1];
2375 sol.Buffer2SurfacePitch = 4 * info->stride[2];
2376 sol.Buffer3SurfacePitch = 4 * info->stride[3];
2377 }
2378
2379 iris_pack_command(GENX(3DSTATE_SO_DECL_LIST), so_decl_map, list) {
2380 list.DWordLength = 3 + 2 * max_decls - 2;
2381 list.StreamtoBufferSelects0 = buffer_mask[0];
2382 list.StreamtoBufferSelects1 = buffer_mask[1];
2383 list.StreamtoBufferSelects2 = buffer_mask[2];
2384 list.StreamtoBufferSelects3 = buffer_mask[3];
2385 list.NumEntries0 = decls[0];
2386 list.NumEntries1 = decls[1];
2387 list.NumEntries2 = decls[2];
2388 list.NumEntries3 = decls[3];
2389 }
2390
2391 for (int i = 0; i < max_decls; i++) {
2392 iris_pack_state(GENX(SO_DECL_ENTRY), so_decl_map + 3 + i * 2, entry) {
2393 entry.Stream0Decl = so_decl[0][i];
2394 entry.Stream1Decl = so_decl[1][i];
2395 entry.Stream2Decl = so_decl[2][i];
2396 entry.Stream3Decl = so_decl[3][i];
2397 }
2398 }
2399
2400 return map;
2401 }
2402
2403 static void
2404 iris_compute_sbe_urb_read_interval(uint64_t fs_input_slots,
2405 const struct brw_vue_map *last_vue_map,
2406 bool two_sided_color,
2407 unsigned *out_offset,
2408 unsigned *out_length)
2409 {
2410 /* The compiler computes the first URB slot without considering COL/BFC
2411 * swizzling (because it doesn't know whether it's enabled), so we need
2412 * to do that here too. This may result in a smaller offset, which
2413 * should be safe.
2414 */
2415 const unsigned first_slot =
2416 brw_compute_first_urb_slot_required(fs_input_slots, last_vue_map);
2417
2418 /* This becomes the URB read offset (counted in pairs of slots). */
2419 assert(first_slot % 2 == 0);
2420 *out_offset = first_slot / 2;
2421
2422 /* We need to adjust the inputs read to account for front/back color
2423 * swizzling, as it can make the URB length longer.
2424 */
2425 for (int c = 0; c <= 1; c++) {
2426 if (fs_input_slots & (VARYING_BIT_COL0 << c)) {
2427 /* If two sided color is enabled, the fragment shader's gl_Color
2428 * (COL0) input comes from either the gl_FrontColor (COL0) or
2429 * gl_BackColor (BFC0) input varyings. Mark BFC as used, too.
2430 */
2431 if (two_sided_color)
2432 fs_input_slots |= (VARYING_BIT_BFC0 << c);
2433
2434 /* If front color isn't written, we opt to give them back color
2435 * instead of an undefined value. Switch from COL to BFC.
2436 */
2437 if (last_vue_map->varying_to_slot[VARYING_SLOT_COL0 + c] == -1) {
2438 fs_input_slots &= ~(VARYING_BIT_COL0 << c);
2439 fs_input_slots |= (VARYING_BIT_BFC0 << c);
2440 }
2441 }
2442 }
2443
2444 /* Compute the minimum URB Read Length necessary for the FS inputs.
2445 *
2446 * From the Sandy Bridge PRM, Volume 2, Part 1, documentation for
2447 * 3DSTATE_SF DWord 1 bits 15:11, "Vertex URB Entry Read Length":
2448 *
2449 * "This field should be set to the minimum length required to read the
2450 * maximum source attribute. The maximum source attribute is indicated
2451 * by the maximum value of the enabled Attribute # Source Attribute if
2452 * Attribute Swizzle Enable is set, Number of Output Attributes-1 if
2453 * enable is not set.
2454 * read_length = ceiling((max_source_attr + 1) / 2)
2455 *
2456 * [errata] Corruption/Hang possible if length programmed larger than
2457 * recommended"
2458 *
2459 * Similar text exists for Ivy Bridge.
2460 *
2461 * We find the last URB slot that's actually read by the FS.
2462 */
2463 unsigned last_read_slot = last_vue_map->num_slots - 1;
2464 while (last_read_slot > first_slot && !(fs_input_slots &
2465 (1ull << last_vue_map->slot_to_varying[last_read_slot])))
2466 --last_read_slot;
2467
2468 /* The URB read length is the difference of the two, counted in pairs. */
2469 *out_length = DIV_ROUND_UP(last_read_slot - first_slot + 1, 2);
2470 }
2471
2472 static void
2473 iris_emit_sbe_swiz(struct iris_batch *batch,
2474 const struct iris_context *ice,
2475 unsigned urb_read_offset,
2476 unsigned sprite_coord_enables)
2477 {
2478 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) attr_overrides[16] = {};
2479 const struct brw_wm_prog_data *wm_prog_data = (void *)
2480 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
2481 const struct brw_vue_map *vue_map = ice->shaders.last_vue_map;
2482 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
2483
2484 /* XXX: this should be generated when putting programs in place */
2485
2486 // XXX: raster->sprite_coord_enable
2487
2488 for (int fs_attr = 0; fs_attr < VARYING_SLOT_MAX; fs_attr++) {
2489 const int input_index = wm_prog_data->urb_setup[fs_attr];
2490 if (input_index < 0 || input_index >= 16)
2491 continue;
2492
2493 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) *attr =
2494 &attr_overrides[input_index];
2495 int slot = vue_map->varying_to_slot[fs_attr];
2496
2497 /* Viewport and Layer are stored in the VUE header. We need to override
2498 * them to zero if earlier stages didn't write them, as GL requires that
2499 * they read back as zero when not explicitly set.
2500 */
2501 switch (fs_attr) {
2502 case VARYING_SLOT_VIEWPORT:
2503 case VARYING_SLOT_LAYER:
2504 attr->ComponentOverrideX = true;
2505 attr->ComponentOverrideW = true;
2506 attr->ConstantSource = CONST_0000;
2507
2508 if (!(vue_map->slots_valid & VARYING_BIT_LAYER))
2509 attr->ComponentOverrideY = true;
2510 if (!(vue_map->slots_valid & VARYING_BIT_VIEWPORT))
2511 attr->ComponentOverrideZ = true;
2512 continue;
2513
2514 case VARYING_SLOT_PRIMITIVE_ID:
2515 /* Override if the previous shader stage didn't write gl_PrimitiveID. */
2516 if (slot == -1) {
2517 attr->ComponentOverrideX = true;
2518 attr->ComponentOverrideY = true;
2519 attr->ComponentOverrideZ = true;
2520 attr->ComponentOverrideW = true;
2521 attr->ConstantSource = PRIM_ID;
2522 continue;
2523 }
2524
2525 default:
2526 break;
2527 }
2528
2529 if (sprite_coord_enables & (1 << input_index))
2530 continue;
2531
2532 /* If there was only a back color written but not front, use back
2533 * as the color instead of undefined.
2534 */
2535 if (slot == -1 && fs_attr == VARYING_SLOT_COL0)
2536 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC0];
2537 if (slot == -1 && fs_attr == VARYING_SLOT_COL1)
2538 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC1];
2539
2540 /* Not written by the previous stage - undefined. */
2541 if (slot == -1) {
2542 attr->ComponentOverrideX = true;
2543 attr->ComponentOverrideY = true;
2544 attr->ComponentOverrideZ = true;
2545 attr->ComponentOverrideW = true;
2546 attr->ConstantSource = CONST_0001_FLOAT;
2547 continue;
2548 }
2549
2550 /* Compute the location of the attribute relative to the read offset,
2551 * which is counted in 256-bit increments (two 128-bit VUE slots).
2552 */
2553 const int source_attr = slot - 2 * urb_read_offset;
2554 assert(source_attr >= 0 && source_attr <= 32);
2555 attr->SourceAttribute = source_attr;
2556
2557 /* If we are doing two-sided color, and the VUE slot following this one
2558 * represents a back-facing color, then we need to instruct the SF unit
2559 * to do back-facing swizzling.
2560 */
2561 if (cso_rast->light_twoside &&
2562 ((vue_map->slot_to_varying[slot] == VARYING_SLOT_COL0 &&
2563 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC0) ||
2564 (vue_map->slot_to_varying[slot] == VARYING_SLOT_COL1 &&
2565 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC1)))
2566 attr->SwizzleSelect = INPUTATTR_FACING;
2567 }
2568
2569 iris_emit_cmd(batch, GENX(3DSTATE_SBE_SWIZ), sbes) {
2570 for (int i = 0; i < 16; i++)
2571 sbes.Attribute[i] = attr_overrides[i];
2572 }
2573 }
2574
2575 static unsigned
2576 iris_calculate_point_sprite_overrides(const struct brw_wm_prog_data *prog_data,
2577 const struct iris_rasterizer_state *cso)
2578 {
2579 unsigned overrides = 0;
2580
2581 if (prog_data->urb_setup[VARYING_SLOT_PNTC] != -1)
2582 overrides |= 1 << prog_data->urb_setup[VARYING_SLOT_PNTC];
2583
2584 for (int i = 0; i < 8; i++) {
2585 if ((cso->sprite_coord_enable & (1 << i)) &&
2586 prog_data->urb_setup[VARYING_SLOT_TEX0 + i] != -1)
2587 overrides |= 1 << prog_data->urb_setup[VARYING_SLOT_TEX0 + i];
2588 }
2589
2590 return overrides;
2591 }
2592
2593 static void
2594 iris_emit_sbe(struct iris_batch *batch, const struct iris_context *ice)
2595 {
2596 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
2597 const struct brw_wm_prog_data *wm_prog_data = (void *)
2598 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
2599 const struct shader_info *fs_info =
2600 iris_get_shader_info(ice, MESA_SHADER_FRAGMENT);
2601
2602 unsigned urb_read_offset, urb_read_length;
2603 iris_compute_sbe_urb_read_interval(fs_info->inputs_read,
2604 ice->shaders.last_vue_map,
2605 cso_rast->light_twoside,
2606 &urb_read_offset, &urb_read_length);
2607
2608 unsigned sprite_coord_overrides =
2609 iris_calculate_point_sprite_overrides(wm_prog_data, cso_rast);
2610
2611 iris_emit_cmd(batch, GENX(3DSTATE_SBE), sbe) {
2612 sbe.AttributeSwizzleEnable = true;
2613 sbe.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
2614 sbe.PointSpriteTextureCoordinateOrigin = cso_rast->sprite_coord_mode;
2615 sbe.VertexURBEntryReadOffset = urb_read_offset;
2616 sbe.VertexURBEntryReadLength = urb_read_length;
2617 sbe.ForceVertexURBEntryReadOffset = true;
2618 sbe.ForceVertexURBEntryReadLength = true;
2619 sbe.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
2620 sbe.PointSpriteTextureCoordinateEnable = sprite_coord_overrides;
2621
2622 for (int i = 0; i < 32; i++) {
2623 sbe.AttributeActiveComponentFormat[i] = ACTIVE_COMPONENT_XYZW;
2624 }
2625 }
2626
2627 iris_emit_sbe_swiz(batch, ice, urb_read_offset, sprite_coord_overrides);
2628 }
2629
2630 static void
2631 iris_bind_compute_state(struct pipe_context *ctx, void *state)
2632 {
2633 // XXX: do something
2634 }
2635
2636 /* ------------------------------------------------------------------- */
2637
2638 /**
2639 * Set sampler-related program key fields based on the current state.
2640 */
2641 static void
2642 iris_populate_sampler_key(const struct iris_context *ice,
2643 struct brw_sampler_prog_key_data *key)
2644 {
2645 for (int i = 0; i < MAX_SAMPLERS; i++) {
2646 key->swizzles[i] = 0x688; /* XYZW */
2647 }
2648 }
2649
2650 /**
2651 * Populate VS program key fields based on the current state.
2652 */
2653 static void
2654 iris_populate_vs_key(const struct iris_context *ice,
2655 struct brw_vs_prog_key *key)
2656 {
2657 iris_populate_sampler_key(ice, &key->tex);
2658 }
2659
2660 /**
2661 * Populate TCS program key fields based on the current state.
2662 */
2663 static void
2664 iris_populate_tcs_key(const struct iris_context *ice,
2665 struct brw_tcs_prog_key *key)
2666 {
2667 iris_populate_sampler_key(ice, &key->tex);
2668 }
2669
2670 /**
2671 * Populate TES program key fields based on the current state.
2672 */
2673 static void
2674 iris_populate_tes_key(const struct iris_context *ice,
2675 struct brw_tes_prog_key *key)
2676 {
2677 iris_populate_sampler_key(ice, &key->tex);
2678 }
2679
2680 /**
2681 * Populate GS program key fields based on the current state.
2682 */
2683 static void
2684 iris_populate_gs_key(const struct iris_context *ice,
2685 struct brw_gs_prog_key *key)
2686 {
2687 iris_populate_sampler_key(ice, &key->tex);
2688 }
2689
2690 /**
2691 * Populate FS program key fields based on the current state.
2692 */
2693 static void
2694 iris_populate_fs_key(const struct iris_context *ice,
2695 struct brw_wm_prog_key *key)
2696 {
2697 iris_populate_sampler_key(ice, &key->tex);
2698
2699 /* XXX: dirty flags? */
2700 const struct pipe_framebuffer_state *fb = &ice->state.framebuffer;
2701 const struct iris_depth_stencil_alpha_state *zsa = ice->state.cso_zsa;
2702 const struct iris_rasterizer_state *rast = ice->state.cso_rast;
2703 const struct iris_blend_state *blend = ice->state.cso_blend;
2704
2705 key->nr_color_regions = fb->nr_cbufs;
2706
2707 key->clamp_fragment_color = rast->clamp_fragment_color;
2708
2709 key->replicate_alpha = fb->nr_cbufs > 1 &&
2710 (zsa->alpha.enabled || blend->alpha_to_coverage);
2711
2712 /* XXX: only bother if COL0/1 are read */
2713 key->flat_shade = rast->flatshade;
2714
2715 key->persample_interp = rast->force_persample_interp;
2716 key->multisample_fbo = rast->multisample && fb->samples > 1;
2717
2718 key->coherent_fb_fetch = true;
2719
2720 // XXX: uint64_t input_slots_valid; - for >16 inputs
2721
2722 // XXX: key->force_dual_color_blend for unigine
2723 // XXX: respect hint for high_quality_derivatives:1;
2724 }
2725
2726 #if 0
2727 // XXX: these need to go in INIT_THREAD_DISPATCH_FIELDS
2728 pkt.SamplerCount = \
2729 DIV_ROUND_UP(CLAMP(stage_state->sampler_count, 0, 16), 4); \
2730 pkt.PerThreadScratchSpace = prog_data->total_scratch == 0 ? 0 : \
2731 ffs(stage_state->per_thread_scratch) - 11; \
2732
2733 #endif
2734
2735 static uint64_t
2736 KSP(const struct iris_compiled_shader *shader)
2737 {
2738 struct iris_resource *res = (void *) shader->assembly.res;
2739 return iris_bo_offset_from_base_address(res->bo) + shader->assembly.offset;
2740 }
2741
2742 // Gen11 workaround table #2056 WABTPPrefetchDisable suggests to disable
2743 // prefetching of binding tables in A0 and B0 steppings. XXX: Revisit
2744 // this WA on C0 stepping.
2745
2746 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix) \
2747 pkt.KernelStartPointer = KSP(shader); \
2748 pkt.BindingTableEntryCount = GEN_GEN == 11 ? 0 : \
2749 prog_data->binding_table.size_bytes / 4; \
2750 pkt.FloatingPointMode = prog_data->use_alt_mode; \
2751 \
2752 pkt.DispatchGRFStartRegisterForURBData = \
2753 prog_data->dispatch_grf_start_reg; \
2754 pkt.prefix##URBEntryReadLength = vue_prog_data->urb_read_length; \
2755 pkt.prefix##URBEntryReadOffset = 0; \
2756 \
2757 pkt.StatisticsEnable = true; \
2758 pkt.Enable = true;
2759
2760 /**
2761 * Encode most of 3DSTATE_VS based on the compiled shader.
2762 */
2763 static void
2764 iris_store_vs_state(const struct gen_device_info *devinfo,
2765 struct iris_compiled_shader *shader)
2766 {
2767 struct brw_stage_prog_data *prog_data = shader->prog_data;
2768 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2769
2770 iris_pack_command(GENX(3DSTATE_VS), shader->derived_data, vs) {
2771 INIT_THREAD_DISPATCH_FIELDS(vs, Vertex);
2772 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
2773 vs.SIMD8DispatchEnable = true;
2774 vs.UserClipDistanceCullTestEnableBitmask =
2775 vue_prog_data->cull_distance_mask;
2776 }
2777 }
2778
2779 /**
2780 * Encode most of 3DSTATE_HS based on the compiled shader.
2781 */
2782 static void
2783 iris_store_tcs_state(const struct gen_device_info *devinfo,
2784 struct iris_compiled_shader *shader)
2785 {
2786 struct brw_stage_prog_data *prog_data = shader->prog_data;
2787 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2788 struct brw_tcs_prog_data *tcs_prog_data = (void *) prog_data;
2789
2790 iris_pack_command(GENX(3DSTATE_HS), shader->derived_data, hs) {
2791 INIT_THREAD_DISPATCH_FIELDS(hs, Vertex);
2792
2793 hs.InstanceCount = tcs_prog_data->instances - 1;
2794 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
2795 hs.IncludeVertexHandles = true;
2796 }
2797 }
2798
2799 /**
2800 * Encode 3DSTATE_TE and most of 3DSTATE_DS based on the compiled shader.
2801 */
2802 static void
2803 iris_store_tes_state(const struct gen_device_info *devinfo,
2804 struct iris_compiled_shader *shader)
2805 {
2806 struct brw_stage_prog_data *prog_data = shader->prog_data;
2807 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2808 struct brw_tes_prog_data *tes_prog_data = (void *) prog_data;
2809
2810 uint32_t *te_state = (void *) shader->derived_data;
2811 uint32_t *ds_state = te_state + GENX(3DSTATE_TE_length);
2812
2813 iris_pack_command(GENX(3DSTATE_TE), te_state, te) {
2814 te.Partitioning = tes_prog_data->partitioning;
2815 te.OutputTopology = tes_prog_data->output_topology;
2816 te.TEDomain = tes_prog_data->domain;
2817 te.TEEnable = true;
2818 te.MaximumTessellationFactorOdd = 63.0;
2819 te.MaximumTessellationFactorNotOdd = 64.0;
2820 }
2821
2822 iris_pack_command(GENX(3DSTATE_DS), ds_state, ds) {
2823 INIT_THREAD_DISPATCH_FIELDS(ds, Patch);
2824
2825 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
2826 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
2827 ds.ComputeWCoordinateEnable =
2828 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
2829
2830 ds.UserClipDistanceCullTestEnableBitmask =
2831 vue_prog_data->cull_distance_mask;
2832 }
2833
2834 }
2835
2836 /**
2837 * Encode most of 3DSTATE_GS based on the compiled shader.
2838 */
2839 static void
2840 iris_store_gs_state(const struct gen_device_info *devinfo,
2841 struct iris_compiled_shader *shader)
2842 {
2843 struct brw_stage_prog_data *prog_data = shader->prog_data;
2844 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
2845 struct brw_gs_prog_data *gs_prog_data = (void *) prog_data;
2846
2847 iris_pack_command(GENX(3DSTATE_GS), shader->derived_data, gs) {
2848 INIT_THREAD_DISPATCH_FIELDS(gs, Vertex);
2849
2850 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
2851 gs.OutputTopology = gs_prog_data->output_topology;
2852 gs.ControlDataHeaderSize =
2853 gs_prog_data->control_data_header_size_hwords;
2854 gs.InstanceControl = gs_prog_data->invocations - 1;
2855 gs.DispatchMode = DISPATCH_MODE_SIMD8;
2856 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
2857 gs.ControlDataFormat = gs_prog_data->control_data_format;
2858 gs.ReorderMode = TRAILING;
2859 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
2860 gs.MaximumNumberofThreads =
2861 GEN_GEN == 8 ? (devinfo->max_gs_threads / 2 - 1)
2862 : (devinfo->max_gs_threads - 1);
2863
2864 if (gs_prog_data->static_vertex_count != -1) {
2865 gs.StaticOutput = true;
2866 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count;
2867 }
2868 gs.IncludeVertexHandles = vue_prog_data->include_vue_handles;
2869
2870 gs.UserClipDistanceCullTestEnableBitmask =
2871 vue_prog_data->cull_distance_mask;
2872
2873 const int urb_entry_write_offset = 1;
2874 const uint32_t urb_entry_output_length =
2875 DIV_ROUND_UP(vue_prog_data->vue_map.num_slots, 2) -
2876 urb_entry_write_offset;
2877
2878 gs.VertexURBEntryOutputReadOffset = urb_entry_write_offset;
2879 gs.VertexURBEntryOutputLength = MAX2(urb_entry_output_length, 1);
2880 }
2881 }
2882
2883 /**
2884 * Encode most of 3DSTATE_PS and 3DSTATE_PS_EXTRA based on the shader.
2885 */
2886 static void
2887 iris_store_fs_state(const struct gen_device_info *devinfo,
2888 struct iris_compiled_shader *shader)
2889 {
2890 struct brw_stage_prog_data *prog_data = shader->prog_data;
2891 struct brw_wm_prog_data *wm_prog_data = (void *) shader->prog_data;
2892
2893 uint32_t *ps_state = (void *) shader->derived_data;
2894 uint32_t *psx_state = ps_state + GENX(3DSTATE_PS_length);
2895
2896 iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
2897 ps.VectorMaskEnable = true;
2898 //ps.SamplerCount = ...
2899 // XXX: WABTPPrefetchDisable, see above, drop at C0
2900 ps.BindingTableEntryCount = GEN_GEN == 11 ? 0 :
2901 prog_data->binding_table.size_bytes / 4;
2902 ps.FloatingPointMode = prog_data->use_alt_mode;
2903 ps.MaximumNumberofThreadsPerPSD = 64 - (GEN_GEN == 8 ? 2 : 1);
2904
2905 ps.PushConstantEnable = prog_data->nr_params > 0 ||
2906 prog_data->ubo_ranges[0].length > 0;
2907
2908 /* From the documentation for this packet:
2909 * "If the PS kernel does not need the Position XY Offsets to
2910 * compute a Position Value, then this field should be programmed
2911 * to POSOFFSET_NONE."
2912 *
2913 * "SW Recommendation: If the PS kernel needs the Position Offsets
2914 * to compute a Position XY value, this field should match Position
2915 * ZW Interpolation Mode to ensure a consistent position.xyzw
2916 * computation."
2917 *
2918 * We only require XY sample offsets. So, this recommendation doesn't
2919 * look useful at the moment. We might need this in future.
2920 */
2921 ps.PositionXYOffsetSelect =
2922 wm_prog_data->uses_pos_offset ? POSOFFSET_SAMPLE : POSOFFSET_NONE;
2923 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
2924 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
2925 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
2926
2927 // XXX: Disable SIMD32 with 16x MSAA
2928
2929 ps.DispatchGRFStartRegisterForConstantSetupData0 =
2930 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
2931 ps.DispatchGRFStartRegisterForConstantSetupData1 =
2932 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
2933 ps.DispatchGRFStartRegisterForConstantSetupData2 =
2934 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
2935
2936 ps.KernelStartPointer0 =
2937 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
2938 ps.KernelStartPointer1 =
2939 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
2940 ps.KernelStartPointer2 =
2941 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
2942 }
2943
2944 iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
2945 psx.PixelShaderValid = true;
2946 psx.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
2947 psx.PixelShaderKillsPixel = wm_prog_data->uses_kill;
2948 psx.AttributeEnable = wm_prog_data->num_varying_inputs != 0;
2949 psx.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
2950 psx.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
2951 psx.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
2952
2953 if (wm_prog_data->uses_sample_mask) {
2954 /* TODO: conservative rasterization */
2955 if (wm_prog_data->post_depth_coverage)
2956 psx.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
2957 else
2958 psx.InputCoverageMaskState = ICMS_NORMAL;
2959 }
2960
2961 psx.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
2962 psx.PixelShaderPullsBary = wm_prog_data->pulls_bary;
2963 psx.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
2964
2965 // XXX: UAV bit
2966 }
2967 }
2968
2969 /**
2970 * Compute the size of the derived data (shader command packets).
2971 *
2972 * This must match the data written by the iris_store_xs_state() functions.
2973 */
2974 static unsigned
2975 iris_derived_program_state_size(enum iris_program_cache_id cache_id)
2976 {
2977 assert(cache_id <= IRIS_CACHE_BLORP);
2978
2979 static const unsigned dwords[] = {
2980 [IRIS_CACHE_VS] = GENX(3DSTATE_VS_length),
2981 [IRIS_CACHE_TCS] = GENX(3DSTATE_HS_length),
2982 [IRIS_CACHE_TES] = GENX(3DSTATE_TE_length) + GENX(3DSTATE_DS_length),
2983 [IRIS_CACHE_GS] = GENX(3DSTATE_GS_length),
2984 [IRIS_CACHE_FS] =
2985 GENX(3DSTATE_PS_length) + GENX(3DSTATE_PS_EXTRA_length),
2986 [IRIS_CACHE_CS] = 0,
2987 [IRIS_CACHE_BLORP] = 0,
2988 };
2989
2990 return sizeof(uint32_t) * dwords[cache_id];
2991 }
2992
2993 /**
2994 * Create any state packets corresponding to the given shader stage
2995 * (i.e. 3DSTATE_VS) and save them as "derived data" in the shader variant.
2996 * This means that we can look up a program in the in-memory cache and
2997 * get most of the state packet without having to reconstruct it.
2998 */
2999 static void
3000 iris_store_derived_program_state(const struct gen_device_info *devinfo,
3001 enum iris_program_cache_id cache_id,
3002 struct iris_compiled_shader *shader)
3003 {
3004 switch (cache_id) {
3005 case IRIS_CACHE_VS:
3006 iris_store_vs_state(devinfo, shader);
3007 break;
3008 case IRIS_CACHE_TCS:
3009 iris_store_tcs_state(devinfo, shader);
3010 break;
3011 case IRIS_CACHE_TES:
3012 iris_store_tes_state(devinfo, shader);
3013 break;
3014 case IRIS_CACHE_GS:
3015 iris_store_gs_state(devinfo, shader);
3016 break;
3017 case IRIS_CACHE_FS:
3018 iris_store_fs_state(devinfo, shader);
3019 break;
3020 case IRIS_CACHE_CS:
3021 case IRIS_CACHE_BLORP:
3022 break;
3023 default:
3024 break;
3025 }
3026 }
3027
3028 /* ------------------------------------------------------------------- */
3029
3030 /**
3031 * Configure the URB.
3032 *
3033 * XXX: write a real comment.
3034 */
3035 static void
3036 iris_upload_urb_config(struct iris_context *ice, struct iris_batch *batch)
3037 {
3038 const struct gen_device_info *devinfo = &batch->screen->devinfo;
3039 const unsigned push_size_kB = 32;
3040 unsigned entries[4];
3041 unsigned start[4];
3042 unsigned size[4];
3043
3044 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
3045 if (!ice->shaders.prog[i]) {
3046 size[i] = 1;
3047 } else {
3048 struct brw_vue_prog_data *vue_prog_data =
3049 (void *) ice->shaders.prog[i]->prog_data;
3050 size[i] = vue_prog_data->urb_entry_size;
3051 }
3052 assert(size[i] != 0);
3053 }
3054
3055 gen_get_urb_config(devinfo, 1024 * push_size_kB,
3056 1024 * ice->shaders.urb_size,
3057 ice->shaders.prog[MESA_SHADER_TESS_EVAL] != NULL,
3058 ice->shaders.prog[MESA_SHADER_GEOMETRY] != NULL,
3059 size, entries, start);
3060
3061 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
3062 iris_emit_cmd(batch, GENX(3DSTATE_URB_VS), urb) {
3063 urb._3DCommandSubOpcode += i;
3064 urb.VSURBStartingAddress = start[i];
3065 urb.VSURBEntryAllocationSize = size[i] - 1;
3066 urb.VSNumberofURBEntries = entries[i];
3067 }
3068 }
3069 }
3070
3071 static const uint32_t push_constant_opcodes[] = {
3072 [MESA_SHADER_VERTEX] = 21,
3073 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
3074 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
3075 [MESA_SHADER_GEOMETRY] = 22,
3076 [MESA_SHADER_FRAGMENT] = 23,
3077 [MESA_SHADER_COMPUTE] = 0,
3078 };
3079
3080 /**
3081 * Add a surface to the validation list, as well as the buffer containing
3082 * the corresponding SURFACE_STATE.
3083 *
3084 * Returns the binding table entry (offset to SURFACE_STATE).
3085 */
3086 static uint32_t
3087 use_surface(struct iris_batch *batch,
3088 struct pipe_surface *p_surf,
3089 bool writeable)
3090 {
3091 struct iris_surface *surf = (void *) p_surf;
3092
3093 iris_use_pinned_bo(batch, iris_resource_bo(p_surf->texture), writeable);
3094 iris_use_pinned_bo(batch, iris_resource_bo(surf->surface_state.res), false);
3095
3096 return surf->surface_state.offset;
3097 }
3098
3099 static uint32_t
3100 use_sampler_view(struct iris_batch *batch, struct iris_sampler_view *isv)
3101 {
3102 iris_use_pinned_bo(batch, iris_resource_bo(isv->base.texture), false);
3103 iris_use_pinned_bo(batch, iris_resource_bo(isv->surface_state.res), false);
3104
3105 return isv->surface_state.offset;
3106 }
3107
3108 static uint32_t
3109 use_const_buffer(struct iris_batch *batch, struct iris_const_buffer *cbuf)
3110 {
3111 iris_use_pinned_bo(batch, iris_resource_bo(cbuf->data.res), false);
3112 iris_use_pinned_bo(batch, iris_resource_bo(cbuf->surface_state.res), false);
3113
3114 return cbuf->surface_state.offset;
3115 }
3116
3117 static uint32_t
3118 use_null_surface(struct iris_batch *batch, struct iris_context *ice)
3119 {
3120 struct iris_bo *state_bo = iris_resource_bo(ice->state.unbound_tex.res);
3121
3122 iris_use_pinned_bo(batch, state_bo, false);
3123
3124 return ice->state.unbound_tex.offset;
3125 }
3126
3127 static uint32_t
3128 use_null_fb_surface(struct iris_batch *batch, struct iris_context *ice)
3129 {
3130 struct iris_bo *state_bo = iris_resource_bo(ice->state.null_fb.res);
3131
3132 iris_use_pinned_bo(batch, state_bo, false);
3133
3134 return ice->state.null_fb.offset;
3135 }
3136
3137 static uint32_t
3138 use_ssbo(struct iris_batch *batch, struct iris_context *ice,
3139 struct iris_shader_state *shs, int i)
3140 {
3141 if (!shs->ssbo[i])
3142 return use_null_surface(batch, ice);
3143
3144 struct iris_state_ref *surf_state = &shs->ssbo_surface_state[i];
3145
3146 iris_use_pinned_bo(batch, iris_resource_bo(shs->ssbo[i]), true);
3147 iris_use_pinned_bo(batch, iris_resource_bo(surf_state->res), false);
3148
3149 return surf_state->offset;
3150 }
3151
3152 #define push_bt_entry(addr) \
3153 assert(addr >= binder_addr); \
3154 if (!pin_only) bt_map[s++] = (addr) - binder_addr;
3155
3156 /**
3157 * Populate the binding table for a given shader stage.
3158 *
3159 * This fills out the table of pointers to surfaces required by the shader,
3160 * and also adds those buffers to the validation list so the kernel can make
3161 * resident before running our batch.
3162 */
3163 static void
3164 iris_populate_binding_table(struct iris_context *ice,
3165 struct iris_batch *batch,
3166 gl_shader_stage stage,
3167 bool pin_only)
3168 {
3169 const struct iris_binder *binder = &ice->state.binder;
3170 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3171 if (!shader)
3172 return;
3173
3174 const struct shader_info *info = iris_get_shader_info(ice, stage);
3175 struct iris_shader_state *shs = &ice->state.shaders[stage];
3176 uint32_t binder_addr = binder->bo->gtt_offset;
3177
3178 //struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
3179 uint32_t *bt_map = binder->map + binder->bt_offset[stage];
3180 int s = 0;
3181
3182 if (stage == MESA_SHADER_FRAGMENT) {
3183 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3184 /* Note that cso_fb->nr_cbufs == fs_key->nr_color_regions. */
3185 if (cso_fb->nr_cbufs) {
3186 for (unsigned i = 0; i < cso_fb->nr_cbufs; i++) {
3187 uint32_t addr =
3188 cso_fb->cbufs[i] ? use_surface(batch, cso_fb->cbufs[i], true)
3189 : use_null_fb_surface(batch, ice);
3190 push_bt_entry(addr);
3191 }
3192 } else {
3193 uint32_t addr = use_null_fb_surface(batch, ice);
3194 push_bt_entry(addr);
3195 }
3196 }
3197
3198 //assert(prog_data->binding_table.texture_start ==
3199 //(ice->state.num_textures[stage] ? s : 0xd0d0d0d0));
3200
3201 for (int i = 0; i < shs->num_textures; i++) {
3202 struct iris_sampler_view *view = shs->textures[i];
3203 uint32_t addr = view ? use_sampler_view(batch, view)
3204 : use_null_surface(batch, ice);
3205 push_bt_entry(addr);
3206 }
3207
3208 for (int i = 0; i < 1 + info->num_ubos; i++) {
3209 struct iris_const_buffer *cbuf = &shs->constbuf[i];
3210 if (!cbuf->surface_state.res)
3211 break;
3212
3213 uint32_t addr = use_const_buffer(batch, cbuf);
3214 push_bt_entry(addr);
3215 }
3216
3217 /* XXX: st is wasting 16 binding table slots for ABOs. Should add a cap
3218 * for changing nir_lower_atomics_to_ssbos setting and buffer_base offset
3219 * in st_atom_storagebuf.c so it'll compact them into one range, with
3220 * SSBOs starting at info->num_abos. Ideally it'd reset num_abos to 0 too
3221 */
3222 if (info->num_abos + info->num_ssbos > 0) {
3223 for (int i = 0; i < IRIS_MAX_ABOS + info->num_ssbos; i++) {
3224 uint32_t addr = use_ssbo(batch, ice, shs, i);
3225 push_bt_entry(addr);
3226 }
3227 }
3228
3229 #if 0
3230 // XXX: not implemented yet
3231 assert(prog_data->binding_table.image_start == 0xd0d0d0d0);
3232 assert(prog_data->binding_table.plane_start[1] == 0xd0d0d0d0);
3233 assert(prog_data->binding_table.plane_start[2] == 0xd0d0d0d0);
3234 #endif
3235 }
3236
3237 static void
3238 iris_use_optional_res(struct iris_batch *batch,
3239 struct pipe_resource *res,
3240 bool writeable)
3241 {
3242 if (res) {
3243 struct iris_bo *bo = iris_resource_bo(res);
3244 iris_use_pinned_bo(batch, bo, writeable);
3245 }
3246 }
3247
3248 /* ------------------------------------------------------------------- */
3249
3250 /**
3251 * Pin any BOs which were installed by a previous batch, and restored
3252 * via the hardware logical context mechanism.
3253 *
3254 * We don't need to re-emit all state every batch - the hardware context
3255 * mechanism will save and restore it for us. This includes pointers to
3256 * various BOs...which won't exist unless we ask the kernel to pin them
3257 * by adding them to the validation list.
3258 *
3259 * We can skip buffers if we've re-emitted those packets, as we're
3260 * overwriting those stale pointers with new ones, and don't actually
3261 * refer to the old BOs.
3262 */
3263 static void
3264 iris_restore_context_saved_bos(struct iris_context *ice,
3265 struct iris_batch *batch,
3266 const struct pipe_draw_info *draw)
3267 {
3268 // XXX: whack IRIS_SHADER_DIRTY_BINDING_TABLE on new batch
3269
3270 const uint64_t clean = ~ice->state.dirty;
3271
3272 if (clean & IRIS_DIRTY_CC_VIEWPORT) {
3273 iris_use_optional_res(batch, ice->state.last_res.cc_vp, false);
3274 }
3275
3276 if (clean & IRIS_DIRTY_SF_CL_VIEWPORT) {
3277 iris_use_optional_res(batch, ice->state.last_res.sf_cl_vp, false);
3278 }
3279
3280 if (clean & IRIS_DIRTY_BLEND_STATE) {
3281 iris_use_optional_res(batch, ice->state.last_res.blend, false);
3282 }
3283
3284 if (clean & IRIS_DIRTY_COLOR_CALC_STATE) {
3285 iris_use_optional_res(batch, ice->state.last_res.color_calc, false);
3286 }
3287
3288 if (clean & IRIS_DIRTY_SCISSOR_RECT) {
3289 iris_use_optional_res(batch, ice->state.last_res.scissor, false);
3290 }
3291
3292 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3293 if (clean & (IRIS_DIRTY_CONSTANTS_VS << stage))
3294 continue;
3295
3296 struct iris_shader_state *shs = &ice->state.shaders[stage];
3297 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3298
3299 if (!shader)
3300 continue;
3301
3302 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
3303
3304 for (int i = 0; i < 4; i++) {
3305 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
3306
3307 if (range->length == 0)
3308 continue;
3309
3310 struct iris_const_buffer *cbuf = &shs->constbuf[range->block];
3311 struct iris_resource *res = (void *) cbuf->data.res;
3312
3313 if (res)
3314 iris_use_pinned_bo(batch, res->bo, false);
3315 else
3316 iris_use_pinned_bo(batch, batch->screen->workaround_bo, false);
3317 }
3318 }
3319
3320 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3321 if (clean & (IRIS_DIRTY_BINDINGS_VS << stage)) {
3322 /* Re-pin any buffers referred to by the binding table. */
3323 iris_populate_binding_table(ice, batch, stage, true);
3324 }
3325 }
3326
3327 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3328 struct iris_shader_state *shs = &ice->state.shaders[stage];
3329 struct pipe_resource *res = shs->sampler_table.res;
3330 if (res)
3331 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
3332 }
3333
3334 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3335 if (clean & (IRIS_DIRTY_VS << stage)) {
3336 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3337 if (shader) {
3338 struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
3339 iris_use_pinned_bo(batch, bo, false);
3340 }
3341
3342 // XXX: scratch buffer
3343 }
3344 }
3345
3346 if (clean & IRIS_DIRTY_DEPTH_BUFFER) {
3347 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3348
3349 if (cso_fb->zsbuf) {
3350 struct iris_resource *zres = (void *) cso_fb->zsbuf->texture;
3351 // XXX: depth might not be writable...
3352 iris_use_pinned_bo(batch, zres->bo, true);
3353 }
3354 }
3355
3356 if (draw->index_size > 0) {
3357 // XXX: index buffer
3358 }
3359
3360 if (clean & IRIS_DIRTY_VERTEX_BUFFERS) {
3361 struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
3362 for (unsigned i = 0; i < cso->num_buffers; i++) {
3363 struct iris_resource *res = (void *) cso->resources[i];
3364 iris_use_pinned_bo(batch, res->bo, false);
3365 }
3366 }
3367 }
3368
3369 /**
3370 * Possibly emit STATE_BASE_ADDRESS to update Surface State Base Address.
3371 */
3372 static void
3373 iris_update_surface_base_address(struct iris_batch *batch,
3374 struct iris_binder *binder)
3375 {
3376 if (batch->last_surface_base_address == binder->bo->gtt_offset)
3377 return;
3378
3379 flush_for_state_base_change(batch);
3380
3381 iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
3382 // XXX: sba.SurfaceStateMemoryObjectControlState = MOCS_WB;
3383 sba.SurfaceStateBaseAddressModifyEnable = true;
3384 sba.SurfaceStateBaseAddress = ro_bo(binder->bo, 0);
3385 }
3386
3387 batch->last_surface_base_address = binder->bo->gtt_offset;
3388 }
3389
3390 static void
3391 iris_upload_dirty_render_state(struct iris_context *ice,
3392 struct iris_batch *batch,
3393 const struct pipe_draw_info *draw)
3394 {
3395 const uint64_t dirty = ice->state.dirty;
3396
3397 if (!dirty)
3398 return;
3399
3400 struct iris_genx_state *genx = ice->state.genx;
3401 struct iris_binder *binder = &ice->state.binder;
3402 struct brw_wm_prog_data *wm_prog_data = (void *)
3403 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
3404
3405 if (dirty & IRIS_DIRTY_CC_VIEWPORT) {
3406 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3407 uint32_t cc_vp_address;
3408
3409 /* XXX: could avoid streaming for depth_clip [0,1] case. */
3410 uint32_t *cc_vp_map =
3411 stream_state(batch, ice->state.dynamic_uploader,
3412 &ice->state.last_res.cc_vp,
3413 4 * ice->state.num_viewports *
3414 GENX(CC_VIEWPORT_length), 32, &cc_vp_address);
3415 for (int i = 0; i < ice->state.num_viewports; i++) {
3416 float zmin, zmax;
3417 util_viewport_zmin_zmax(&ice->state.viewports[i],
3418 cso_rast->clip_halfz, &zmin, &zmax);
3419 if (cso_rast->depth_clip_near)
3420 zmin = 0.0;
3421 if (cso_rast->depth_clip_far)
3422 zmax = 1.0;
3423
3424 iris_pack_state(GENX(CC_VIEWPORT), cc_vp_map, ccv) {
3425 ccv.MinimumDepth = zmin;
3426 ccv.MaximumDepth = zmax;
3427 }
3428
3429 cc_vp_map += GENX(CC_VIEWPORT_length);
3430 }
3431
3432 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_CC), ptr) {
3433 ptr.CCViewportPointer = cc_vp_address;
3434 }
3435 }
3436
3437 if (dirty & IRIS_DIRTY_SF_CL_VIEWPORT) {
3438 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
3439 ptr.SFClipViewportPointer =
3440 emit_state(batch, ice->state.dynamic_uploader,
3441 &ice->state.last_res.sf_cl_vp,
3442 genx->sf_cl_vp, 4 * GENX(SF_CLIP_VIEWPORT_length) *
3443 ice->state.num_viewports, 64);
3444 }
3445 }
3446
3447 /* XXX: L3 State */
3448
3449 // XXX: this is only flagged at setup, we assume a static configuration
3450 if (dirty & IRIS_DIRTY_URB) {
3451 iris_upload_urb_config(ice, batch);
3452 }
3453
3454 if (dirty & IRIS_DIRTY_BLEND_STATE) {
3455 struct iris_blend_state *cso_blend = ice->state.cso_blend;
3456 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3457 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
3458 const int header_dwords = GENX(BLEND_STATE_length);
3459 const int rt_dwords = cso_fb->nr_cbufs * GENX(BLEND_STATE_ENTRY_length);
3460 uint32_t blend_offset;
3461 uint32_t *blend_map =
3462 stream_state(batch, ice->state.dynamic_uploader,
3463 &ice->state.last_res.blend,
3464 4 * (header_dwords + rt_dwords), 64, &blend_offset);
3465
3466 uint32_t blend_state_header;
3467 iris_pack_state(GENX(BLEND_STATE), &blend_state_header, bs) {
3468 bs.AlphaTestEnable = cso_zsa->alpha.enabled;
3469 bs.AlphaTestFunction = translate_compare_func(cso_zsa->alpha.func);
3470 }
3471
3472 blend_map[0] = blend_state_header | cso_blend->blend_state[0];
3473 memcpy(&blend_map[1], &cso_blend->blend_state[1], 4 * rt_dwords);
3474
3475 iris_emit_cmd(batch, GENX(3DSTATE_BLEND_STATE_POINTERS), ptr) {
3476 ptr.BlendStatePointer = blend_offset;
3477 ptr.BlendStatePointerValid = true;
3478 }
3479 }
3480
3481 if (dirty & IRIS_DIRTY_COLOR_CALC_STATE) {
3482 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
3483 uint32_t cc_offset;
3484 void *cc_map =
3485 stream_state(batch, ice->state.dynamic_uploader,
3486 &ice->state.last_res.color_calc,
3487 sizeof(uint32_t) * GENX(COLOR_CALC_STATE_length),
3488 64, &cc_offset);
3489 iris_pack_state(GENX(COLOR_CALC_STATE), cc_map, cc) {
3490 cc.AlphaTestFormat = ALPHATEST_FLOAT32;
3491 cc.AlphaReferenceValueAsFLOAT32 = cso->alpha.ref_value;
3492 cc.BlendConstantColorRed = ice->state.blend_color.color[0];
3493 cc.BlendConstantColorGreen = ice->state.blend_color.color[1];
3494 cc.BlendConstantColorBlue = ice->state.blend_color.color[2];
3495 cc.BlendConstantColorAlpha = ice->state.blend_color.color[3];
3496 }
3497 iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
3498 ptr.ColorCalcStatePointer = cc_offset;
3499 ptr.ColorCalcStatePointerValid = true;
3500 }
3501 }
3502
3503 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3504 // XXX: wrong dirty tracking...
3505 if (!(dirty & (IRIS_DIRTY_CONSTANTS_VS << stage)))
3506 continue;
3507
3508 struct iris_shader_state *shs = &ice->state.shaders[stage];
3509 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3510
3511 if (!shader)
3512 continue;
3513
3514 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
3515
3516 iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_VS), pkt) {
3517 pkt._3DCommandSubOpcode = push_constant_opcodes[stage];
3518 if (prog_data) {
3519 /* The Skylake PRM contains the following restriction:
3520 *
3521 * "The driver must ensure The following case does not occur
3522 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
3523 * buffer 3 read length equal to zero committed followed by a
3524 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
3525 * zero committed."
3526 *
3527 * To avoid this, we program the buffers in the highest slots.
3528 * This way, slot 0 is only used if slot 3 is also used.
3529 */
3530 int n = 3;
3531
3532 for (int i = 3; i >= 0; i--) {
3533 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
3534
3535 if (range->length == 0)
3536 continue;
3537
3538 // XXX: is range->block a constbuf index? it would be nice
3539 struct iris_const_buffer *cbuf = &shs->constbuf[range->block];
3540 struct iris_resource *res = (void *) cbuf->data.res;
3541
3542 assert(cbuf->data.offset % 32 == 0);
3543
3544 pkt.ConstantBody.ReadLength[n] = range->length;
3545 pkt.ConstantBody.Buffer[n] =
3546 res ? ro_bo(res->bo, range->start * 32 + cbuf->data.offset)
3547 : ro_bo(batch->screen->workaround_bo, 0);
3548 n--;
3549 }
3550 }
3551 }
3552 }
3553
3554 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3555 if (dirty & (IRIS_DIRTY_BINDINGS_VS << stage)) {
3556 iris_emit_cmd(batch, GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), ptr) {
3557 ptr._3DCommandSubOpcode = 38 + stage;
3558 ptr.PointertoVSBindingTable = binder->bt_offset[stage];
3559 }
3560 }
3561 }
3562
3563 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3564 if (dirty & (IRIS_DIRTY_BINDINGS_VS << stage)) {
3565 iris_populate_binding_table(ice, batch, stage, false);
3566 }
3567 }
3568
3569 if (ice->state.need_border_colors)
3570 iris_use_pinned_bo(batch, ice->state.border_color_pool.bo, false);
3571
3572 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3573 if (!(dirty & (IRIS_DIRTY_SAMPLER_STATES_VS << stage)) ||
3574 !ice->shaders.prog[stage])
3575 continue;
3576
3577 struct iris_shader_state *shs = &ice->state.shaders[stage];
3578 struct pipe_resource *res = shs->sampler_table.res;
3579 if (res)
3580 iris_use_pinned_bo(batch, iris_resource_bo(res), false);
3581
3582 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ptr) {
3583 ptr._3DCommandSubOpcode = 43 + stage;
3584 ptr.PointertoVSSamplerState = shs->sampler_table.offset;
3585 }
3586 }
3587
3588 if (dirty & IRIS_DIRTY_MULTISAMPLE) {
3589 iris_emit_cmd(batch, GENX(3DSTATE_MULTISAMPLE), ms) {
3590 ms.PixelLocation =
3591 ice->state.cso_rast->half_pixel_center ? CENTER : UL_CORNER;
3592 if (ice->state.framebuffer.samples > 0)
3593 ms.NumberofMultisamples = ffs(ice->state.framebuffer.samples) - 1;
3594 }
3595 }
3596
3597 if (dirty & IRIS_DIRTY_SAMPLE_MASK) {
3598 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_MASK), ms) {
3599 ms.SampleMask = MAX2(ice->state.sample_mask, 1);
3600 }
3601 }
3602
3603 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
3604 if (!(dirty & (IRIS_DIRTY_VS << stage)))
3605 continue;
3606
3607 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
3608
3609 if (shader) {
3610 struct iris_resource *cache = (void *) shader->assembly.res;
3611 iris_use_pinned_bo(batch, cache->bo, false);
3612 iris_batch_emit(batch, shader->derived_data,
3613 iris_derived_program_state_size(stage));
3614 } else {
3615 if (stage == MESA_SHADER_TESS_EVAL) {
3616 iris_emit_cmd(batch, GENX(3DSTATE_HS), hs);
3617 iris_emit_cmd(batch, GENX(3DSTATE_TE), te);
3618 iris_emit_cmd(batch, GENX(3DSTATE_DS), ds);
3619 } else if (stage == MESA_SHADER_GEOMETRY) {
3620 iris_emit_cmd(batch, GENX(3DSTATE_GS), gs);
3621 }
3622 }
3623 }
3624
3625 if (ice->state.streamout_active) {
3626 if (dirty & IRIS_DIRTY_SO_BUFFERS) {
3627 iris_batch_emit(batch, genx->so_buffers,
3628 4 * 4 * GENX(3DSTATE_SO_BUFFER_length));
3629 for (int i = 0; i < 4; i++) {
3630 struct iris_stream_output_target *tgt =
3631 (void *) ice->state.so_target[i];
3632 if (tgt) {
3633 iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
3634 true);
3635 iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
3636 true);
3637 }
3638 }
3639 }
3640
3641 if ((dirty & IRIS_DIRTY_SO_DECL_LIST) && ice->state.streamout) {
3642 uint32_t *decl_list =
3643 ice->state.streamout + GENX(3DSTATE_STREAMOUT_length);
3644 iris_batch_emit(batch, decl_list, 4 * ((decl_list[0] & 0xff) + 2));
3645 }
3646
3647 if (dirty & IRIS_DIRTY_STREAMOUT) {
3648 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3649
3650 uint32_t dynamic_sol[GENX(3DSTATE_STREAMOUT_length)];
3651 iris_pack_command(GENX(3DSTATE_STREAMOUT), dynamic_sol, sol) {
3652 sol.SOFunctionEnable = true;
3653 sol.SOStatisticsEnable = true;
3654
3655 // XXX: GL_PRIMITIVES_GENERATED query
3656 sol.RenderingDisable = cso_rast->rasterizer_discard;
3657 sol.ReorderMode = cso_rast->flatshade_first ? LEADING : TRAILING;
3658 }
3659
3660 assert(ice->state.streamout);
3661
3662 iris_emit_merge(batch, ice->state.streamout, dynamic_sol,
3663 GENX(3DSTATE_STREAMOUT_length));
3664 }
3665 } else {
3666 if (dirty & IRIS_DIRTY_STREAMOUT) {
3667 iris_emit_cmd(batch, GENX(3DSTATE_STREAMOUT), sol);
3668 }
3669 }
3670
3671 if (dirty & IRIS_DIRTY_CLIP) {
3672 struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
3673 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3674
3675 uint32_t dynamic_clip[GENX(3DSTATE_CLIP_length)];
3676 iris_pack_command(GENX(3DSTATE_CLIP), &dynamic_clip, cl) {
3677 if (wm_prog_data->barycentric_interp_modes &
3678 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS)
3679 cl.NonPerspectiveBarycentricEnable = true;
3680
3681 cl.ForceZeroRTAIndexEnable = cso_fb->layers == 0;
3682 cl.MaximumVPIndex = ice->state.num_viewports - 1;
3683 }
3684 iris_emit_merge(batch, cso_rast->clip, dynamic_clip,
3685 ARRAY_SIZE(cso_rast->clip));
3686 }
3687
3688 if (dirty & IRIS_DIRTY_RASTER) {
3689 struct iris_rasterizer_state *cso = ice->state.cso_rast;
3690 iris_batch_emit(batch, cso->raster, sizeof(cso->raster));
3691 iris_batch_emit(batch, cso->sf, sizeof(cso->sf));
3692
3693 }
3694
3695 /* XXX: FS program updates needs to flag IRIS_DIRTY_WM */
3696 if (dirty & IRIS_DIRTY_WM) {
3697 struct iris_rasterizer_state *cso = ice->state.cso_rast;
3698 uint32_t dynamic_wm[GENX(3DSTATE_WM_length)];
3699
3700 iris_pack_command(GENX(3DSTATE_WM), &dynamic_wm, wm) {
3701 wm.BarycentricInterpolationMode =
3702 wm_prog_data->barycentric_interp_modes;
3703
3704 if (wm_prog_data->early_fragment_tests)
3705 wm.EarlyDepthStencilControl = EDSC_PREPS;
3706 else if (wm_prog_data->has_side_effects)
3707 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
3708 }
3709 iris_emit_merge(batch, cso->wm, dynamic_wm, ARRAY_SIZE(cso->wm));
3710 }
3711
3712 if (dirty & IRIS_DIRTY_SBE) {
3713 iris_emit_sbe(batch, ice);
3714 }
3715
3716 if (dirty & IRIS_DIRTY_PS_BLEND) {
3717 struct iris_blend_state *cso_blend = ice->state.cso_blend;
3718 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
3719 uint32_t dynamic_pb[GENX(3DSTATE_PS_BLEND_length)];
3720 iris_pack_command(GENX(3DSTATE_PS_BLEND), &dynamic_pb, pb) {
3721 pb.HasWriteableRT = true; // XXX: comes from somewhere :(
3722 pb.AlphaTestEnable = cso_zsa->alpha.enabled;
3723 }
3724
3725 iris_emit_merge(batch, cso_blend->ps_blend, dynamic_pb,
3726 ARRAY_SIZE(cso_blend->ps_blend));
3727 }
3728
3729 if (dirty & IRIS_DIRTY_WM_DEPTH_STENCIL) {
3730 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
3731 struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
3732
3733 uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
3734 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
3735 wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
3736 wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
3737 }
3738 iris_emit_merge(batch, cso->wmds, stencil_refs, ARRAY_SIZE(cso->wmds));
3739 }
3740
3741 if (dirty & IRIS_DIRTY_SCISSOR_RECT) {
3742 uint32_t scissor_offset =
3743 emit_state(batch, ice->state.dynamic_uploader,
3744 &ice->state.last_res.scissor,
3745 ice->state.scissors,
3746 sizeof(struct pipe_scissor_state) *
3747 ice->state.num_viewports, 32);
3748
3749 iris_emit_cmd(batch, GENX(3DSTATE_SCISSOR_STATE_POINTERS), ptr) {
3750 ptr.ScissorRectPointer = scissor_offset;
3751 }
3752 }
3753
3754 if (dirty & IRIS_DIRTY_DEPTH_BUFFER) {
3755 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
3756 struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
3757
3758 iris_batch_emit(batch, cso_z->packets, sizeof(cso_z->packets));
3759
3760 if (cso_fb->zsbuf) {
3761 struct iris_resource *zres = (void *) cso_fb->zsbuf->texture;
3762 // XXX: depth might not be writable...
3763 iris_use_pinned_bo(batch, zres->bo, true);
3764 }
3765 }
3766
3767 if (dirty & IRIS_DIRTY_POLYGON_STIPPLE) {
3768 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_PATTERN), poly) {
3769 for (int i = 0; i < 32; i++) {
3770 poly.PatternRow[i] = ice->state.poly_stipple.stipple[i];
3771 }
3772 }
3773 }
3774
3775 if (dirty & IRIS_DIRTY_LINE_STIPPLE) {
3776 struct iris_rasterizer_state *cso = ice->state.cso_rast;
3777 iris_batch_emit(batch, cso->line_stipple, sizeof(cso->line_stipple));
3778 }
3779
3780 if (dirty & IRIS_DIRTY_VF_TOPOLOGY) {
3781 iris_emit_cmd(batch, GENX(3DSTATE_VF_TOPOLOGY), topo) {
3782 topo.PrimitiveTopologyType =
3783 translate_prim_type(draw->mode, draw->vertices_per_patch);
3784 }
3785 }
3786
3787 if (dirty & IRIS_DIRTY_VERTEX_BUFFERS) {
3788 struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
3789 const unsigned vb_dwords = GENX(VERTEX_BUFFER_STATE_length);
3790
3791 if (cso->num_buffers > 0) {
3792 iris_batch_emit(batch, cso->vertex_buffers, sizeof(uint32_t) *
3793 (1 + vb_dwords * cso->num_buffers));
3794
3795 for (unsigned i = 0; i < cso->num_buffers; i++) {
3796 struct iris_resource *res = (void *) cso->resources[i];
3797 iris_use_pinned_bo(batch, res->bo, false);
3798 }
3799 }
3800 }
3801
3802 if (dirty & IRIS_DIRTY_VERTEX_ELEMENTS) {
3803 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
3804 const unsigned entries = MAX2(cso->count, 1);
3805 iris_batch_emit(batch, cso->vertex_elements, sizeof(uint32_t) *
3806 (1 + entries * GENX(VERTEX_ELEMENT_STATE_length)));
3807 iris_batch_emit(batch, cso->vf_instancing, sizeof(uint32_t) *
3808 entries * GENX(3DSTATE_VF_INSTANCING_length));
3809 }
3810
3811 if (dirty & IRIS_DIRTY_VF_SGVS) {
3812 const struct brw_vs_prog_data *vs_prog_data = (void *)
3813 ice->shaders.prog[MESA_SHADER_VERTEX]->prog_data;
3814 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
3815
3816 iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS), sgv) {
3817 if (vs_prog_data->uses_vertexid) {
3818 sgv.VertexIDEnable = true;
3819 sgv.VertexIDComponentNumber = 2;
3820 sgv.VertexIDElementOffset = cso->count;
3821 }
3822
3823 if (vs_prog_data->uses_instanceid) {
3824 sgv.InstanceIDEnable = true;
3825 sgv.InstanceIDComponentNumber = 3;
3826 sgv.InstanceIDElementOffset = cso->count;
3827 }
3828 }
3829 }
3830
3831 if (dirty & IRIS_DIRTY_VF) {
3832 iris_emit_cmd(batch, GENX(3DSTATE_VF), vf) {
3833 if (draw->primitive_restart) {
3834 vf.IndexedDrawCutIndexEnable = true;
3835 vf.CutIndex = draw->restart_index;
3836 }
3837 }
3838 }
3839
3840 // XXX: Gen8 - PMA fix
3841 }
3842
3843 static void
3844 iris_upload_render_state(struct iris_context *ice,
3845 struct iris_batch *batch,
3846 const struct pipe_draw_info *draw)
3847 {
3848 /* Always pin the binder. If we're emitting new binding table pointers,
3849 * we need it. If not, we're probably inheriting old tables via the
3850 * context, and need it anyway. Since true zero-bindings cases are
3851 * practically non-existent, just pin it and avoid last_res tracking.
3852 */
3853 iris_use_pinned_bo(batch, ice->state.binder.bo, false);
3854
3855 iris_upload_dirty_render_state(ice, batch, draw);
3856
3857 if (draw->index_size > 0) {
3858 struct iris_resource *res = NULL;
3859 unsigned offset;
3860
3861 if (draw->has_user_indices) {
3862 u_upload_data(ice->ctx.stream_uploader, 0,
3863 draw->count * draw->index_size, 4, draw->index.user,
3864 &offset, (struct pipe_resource **) &res);
3865 } else {
3866 res = (struct iris_resource *) draw->index.resource;
3867 offset = 0;
3868 }
3869
3870 iris_emit_cmd(batch, GENX(3DSTATE_INDEX_BUFFER), ib) {
3871 ib.IndexFormat = draw->index_size >> 1;
3872 ib.MOCS = MOCS_WB;
3873 ib.BufferSize = res->bo->size;
3874 ib.BufferStartingAddress = ro_bo(res->bo, offset);
3875 }
3876 }
3877
3878 #define _3DPRIM_END_OFFSET 0x2420
3879 #define _3DPRIM_START_VERTEX 0x2430
3880 #define _3DPRIM_VERTEX_COUNT 0x2434
3881 #define _3DPRIM_INSTANCE_COUNT 0x2438
3882 #define _3DPRIM_START_INSTANCE 0x243C
3883 #define _3DPRIM_BASE_VERTEX 0x2440
3884
3885 if (draw->indirect) {
3886 /* We don't support this MultidrawIndirect. */
3887 assert(!draw->indirect->indirect_draw_count);
3888
3889 struct iris_bo *bo = iris_resource_bo(draw->indirect->buffer);
3890 assert(bo);
3891
3892 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3893 lrm.RegisterAddress = _3DPRIM_VERTEX_COUNT;
3894 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 0);
3895 }
3896 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3897 lrm.RegisterAddress = _3DPRIM_INSTANCE_COUNT;
3898 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 4);
3899 }
3900 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3901 lrm.RegisterAddress = _3DPRIM_START_VERTEX;
3902 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 8);
3903 }
3904 if (draw->index_size) {
3905 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3906 lrm.RegisterAddress = _3DPRIM_BASE_VERTEX;
3907 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 12);
3908 }
3909 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3910 lrm.RegisterAddress = _3DPRIM_START_INSTANCE;
3911 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 16);
3912 }
3913 } else {
3914 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3915 lrm.RegisterAddress = _3DPRIM_START_INSTANCE;
3916 lrm.MemoryAddress = ro_bo(bo, draw->indirect->offset + 12);
3917 }
3918 iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
3919 lri.RegisterOffset = _3DPRIM_BASE_VERTEX;
3920 lri.DataDWord = 0;
3921 }
3922 }
3923 }
3924
3925 iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
3926 prim.StartInstanceLocation = draw->start_instance;
3927 prim.InstanceCount = draw->instance_count;
3928 prim.VertexCountPerInstance = draw->count;
3929 prim.VertexAccessType = draw->index_size > 0 ? RANDOM : SEQUENTIAL;
3930
3931 // XXX: this is probably bonkers.
3932 prim.StartVertexLocation = draw->start;
3933
3934 prim.IndirectParameterEnable = draw->indirect != NULL;
3935
3936 if (draw->index_size) {
3937 prim.BaseVertexLocation += draw->index_bias;
3938 } else {
3939 prim.StartVertexLocation += draw->index_bias;
3940 }
3941
3942 //prim.BaseVertexLocation = ...;
3943 }
3944
3945 if (!batch->contains_draw) {
3946 iris_restore_context_saved_bos(ice, batch, draw);
3947 batch->contains_draw = true;
3948 }
3949 }
3950
3951 /**
3952 * State module teardown.
3953 */
3954 static void
3955 iris_destroy_state(struct iris_context *ice)
3956 {
3957 iris_free_vertex_buffers(&ice->state.genx->vertex_buffers);
3958
3959 // XXX: unreference resources/surfaces.
3960 for (unsigned i = 0; i < ice->state.framebuffer.nr_cbufs; i++) {
3961 pipe_surface_reference(&ice->state.framebuffer.cbufs[i], NULL);
3962 }
3963 pipe_surface_reference(&ice->state.framebuffer.zsbuf, NULL);
3964
3965 for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
3966 struct iris_shader_state *shs = &ice->state.shaders[stage];
3967 pipe_resource_reference(&shs->sampler_table.res, NULL);
3968 }
3969 free(ice->state.genx);
3970
3971 pipe_resource_reference(&ice->state.last_res.cc_vp, NULL);
3972 pipe_resource_reference(&ice->state.last_res.sf_cl_vp, NULL);
3973 pipe_resource_reference(&ice->state.last_res.color_calc, NULL);
3974 pipe_resource_reference(&ice->state.last_res.scissor, NULL);
3975 pipe_resource_reference(&ice->state.last_res.blend, NULL);
3976 }
3977
3978 /* ------------------------------------------------------------------- */
3979
3980 static unsigned
3981 flags_to_post_sync_op(uint32_t flags)
3982 {
3983 if (flags & PIPE_CONTROL_WRITE_IMMEDIATE)
3984 return WriteImmediateData;
3985
3986 if (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT)
3987 return WritePSDepthCount;
3988
3989 if (flags & PIPE_CONTROL_WRITE_TIMESTAMP)
3990 return WriteTimestamp;
3991
3992 return 0;
3993 }
3994
3995 /**
3996 * Do the given flags have a Post Sync or LRI Post Sync operation?
3997 */
3998 static enum pipe_control_flags
3999 get_post_sync_flags(enum pipe_control_flags flags)
4000 {
4001 flags &= PIPE_CONTROL_WRITE_IMMEDIATE |
4002 PIPE_CONTROL_WRITE_DEPTH_COUNT |
4003 PIPE_CONTROL_WRITE_TIMESTAMP |
4004 PIPE_CONTROL_LRI_POST_SYNC_OP;
4005
4006 /* Only one "Post Sync Op" is allowed, and it's mutually exclusive with
4007 * "LRI Post Sync Operation". So more than one bit set would be illegal.
4008 */
4009 assert(util_bitcount(flags) <= 1);
4010
4011 return flags;
4012 }
4013
4014 // XXX: compute support
4015 #define IS_COMPUTE_PIPELINE(batch) (batch->engine != I915_EXEC_RENDER)
4016
4017 /**
4018 * Emit a series of PIPE_CONTROL commands, taking into account any
4019 * workarounds necessary to actually accomplish the caller's request.
4020 *
4021 * Unless otherwise noted, spec quotations in this function come from:
4022 *
4023 * Synchronization of the 3D Pipeline > PIPE_CONTROL Command > Programming
4024 * Restrictions for PIPE_CONTROL.
4025 *
4026 * You should not use this function directly. Use the helpers in
4027 * iris_pipe_control.c instead, which may split the pipe control further.
4028 */
4029 static void
4030 iris_emit_raw_pipe_control(struct iris_batch *batch, uint32_t flags,
4031 struct iris_bo *bo, uint32_t offset, uint64_t imm)
4032 {
4033 UNUSED const struct gen_device_info *devinfo = &batch->screen->devinfo;
4034 enum pipe_control_flags post_sync_flags = get_post_sync_flags(flags);
4035 enum pipe_control_flags non_lri_post_sync_flags =
4036 post_sync_flags & ~PIPE_CONTROL_LRI_POST_SYNC_OP;
4037
4038 /* Recursive PIPE_CONTROL workarounds --------------------------------
4039 * (http://knowyourmeme.com/memes/xzibit-yo-dawg)
4040 *
4041 * We do these first because we want to look at the original operation,
4042 * rather than any workarounds we set.
4043 */
4044 if (GEN_GEN == 9 && (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE)) {
4045 /* The PIPE_CONTROL "VF Cache Invalidation Enable" bit description
4046 * lists several workarounds:
4047 *
4048 * "Project: SKL, KBL, BXT
4049 *
4050 * If the VF Cache Invalidation Enable is set to a 1 in a
4051 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields
4052 * sets to 0, with the VF Cache Invalidation Enable set to 0
4053 * needs to be sent prior to the PIPE_CONTROL with VF Cache
4054 * Invalidation Enable set to a 1."
4055 */
4056 iris_emit_raw_pipe_control(batch, 0, NULL, 0, 0);
4057 }
4058
4059 if (GEN_GEN == 9 && IS_COMPUTE_PIPELINE(batch) && post_sync_flags) {
4060 /* Project: SKL / Argument: LRI Post Sync Operation [23]
4061 *
4062 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
4063 * programmed prior to programming a PIPECONTROL command with "LRI
4064 * Post Sync Operation" in GPGPU mode of operation (i.e when
4065 * PIPELINE_SELECT command is set to GPGPU mode of operation)."
4066 *
4067 * The same text exists a few rows below for Post Sync Op.
4068 */
4069 iris_emit_raw_pipe_control(batch, PIPE_CONTROL_CS_STALL, bo, offset, imm);
4070 }
4071
4072 if (GEN_GEN == 10 && (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH)) {
4073 /* Cannonlake:
4074 * "Before sending a PIPE_CONTROL command with bit 12 set, SW must issue
4075 * another PIPE_CONTROL with Render Target Cache Flush Enable (bit 12)
4076 * = 0 and Pipe Control Flush Enable (bit 7) = 1"
4077 */
4078 iris_emit_raw_pipe_control(batch, PIPE_CONTROL_FLUSH_ENABLE, bo,
4079 offset, imm);
4080 }
4081
4082 /* "Flush Types" workarounds ---------------------------------------------
4083 * We do these now because they may add post-sync operations or CS stalls.
4084 */
4085
4086 if (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) {
4087 /* Project: BDW, SKL+ (stopping at CNL) / Argument: VF Invalidate
4088 *
4089 * "'Post Sync Operation' must be enabled to 'Write Immediate Data' or
4090 * 'Write PS Depth Count' or 'Write Timestamp'."
4091 */
4092 if (!bo) {
4093 flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
4094 post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
4095 non_lri_post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
4096 bo = batch->screen->workaround_bo;
4097 }
4098 }
4099
4100 /* #1130 from Gen10 workarounds page:
4101 *
4102 * "Enable Depth Stall on every Post Sync Op if Render target Cache
4103 * Flush is not enabled in same PIPE CONTROL and Enable Pixel score
4104 * board stall if Render target cache flush is enabled."
4105 *
4106 * Applicable to CNL B0 and C0 steppings only.
4107 *
4108 * The wording here is unclear, and this workaround doesn't look anything
4109 * like the internal bug report recommendations, but leave it be for now...
4110 */
4111 if (GEN_GEN == 10) {
4112 if (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH) {
4113 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
4114 } else if (flags & non_lri_post_sync_flags) {
4115 flags |= PIPE_CONTROL_DEPTH_STALL;
4116 }
4117 }
4118
4119 if (flags & PIPE_CONTROL_DEPTH_STALL) {
4120 /* From the PIPE_CONTROL instruction table, bit 13 (Depth Stall Enable):
4121 *
4122 * "This bit must be DISABLED for operations other than writing
4123 * PS_DEPTH_COUNT."
4124 *
4125 * This seems like nonsense. An Ivybridge workaround requires us to
4126 * emit a PIPE_CONTROL with a depth stall and write immediate post-sync
4127 * operation. Gen8+ requires us to emit depth stalls and depth cache
4128 * flushes together. So, it's hard to imagine this means anything other
4129 * than "we originally intended this to be used for PS_DEPTH_COUNT".
4130 *
4131 * We ignore the supposed restriction and do nothing.
4132 */
4133 }
4134
4135 if (flags & (PIPE_CONTROL_RENDER_TARGET_FLUSH |
4136 PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
4137 /* From the PIPE_CONTROL instruction table, bit 12 and bit 1:
4138 *
4139 * "This bit must be DISABLED for End-of-pipe (Read) fences,
4140 * PS_DEPTH_COUNT or TIMESTAMP queries."
4141 *
4142 * TODO: Implement end-of-pipe checking.
4143 */
4144 assert(!(post_sync_flags & (PIPE_CONTROL_WRITE_DEPTH_COUNT |
4145 PIPE_CONTROL_WRITE_TIMESTAMP)));
4146 }
4147
4148 if (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD) {
4149 /* From the PIPE_CONTROL instruction table, bit 1:
4150 *
4151 * "This bit is ignored if Depth Stall Enable is set.
4152 * Further, the render cache is not flushed even if Write Cache
4153 * Flush Enable bit is set."
4154 *
4155 * We assert that the caller doesn't do this combination, to try and
4156 * prevent mistakes. It shouldn't hurt the GPU, though.
4157 */
4158 assert(!(flags & (PIPE_CONTROL_DEPTH_STALL |
4159 PIPE_CONTROL_RENDER_TARGET_FLUSH)));
4160 }
4161
4162 /* PIPE_CONTROL page workarounds ------------------------------------- */
4163
4164 if (GEN_GEN <= 8 && (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE)) {
4165 /* From the PIPE_CONTROL page itself:
4166 *
4167 * "IVB, HSW, BDW
4168 * Restriction: Pipe_control with CS-stall bit set must be issued
4169 * before a pipe-control command that has the State Cache
4170 * Invalidate bit set."
4171 */
4172 flags |= PIPE_CONTROL_CS_STALL;
4173 }
4174
4175 if (flags & PIPE_CONTROL_FLUSH_LLC) {
4176 /* From the PIPE_CONTROL instruction table, bit 26 (Flush LLC):
4177 *
4178 * "Project: ALL
4179 * SW must always program Post-Sync Operation to "Write Immediate
4180 * Data" when Flush LLC is set."
4181 *
4182 * For now, we just require the caller to do it.
4183 */
4184 assert(flags & PIPE_CONTROL_WRITE_IMMEDIATE);
4185 }
4186
4187 /* "Post-Sync Operation" workarounds -------------------------------- */
4188
4189 /* Project: All / Argument: Global Snapshot Count Reset [19]
4190 *
4191 * "This bit must not be exercised on any product.
4192 * Requires stall bit ([20] of DW1) set."
4193 *
4194 * We don't use this, so we just assert that it isn't used. The
4195 * PIPE_CONTROL instruction page indicates that they intended this
4196 * as a debug feature and don't think it is useful in production,
4197 * but it may actually be usable, should we ever want to.
4198 */
4199 assert((flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) == 0);
4200
4201 if (flags & (PIPE_CONTROL_MEDIA_STATE_CLEAR |
4202 PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE)) {
4203 /* Project: All / Arguments:
4204 *
4205 * - Generic Media State Clear [16]
4206 * - Indirect State Pointers Disable [16]
4207 *
4208 * "Requires stall bit ([20] of DW1) set."
4209 *
4210 * Also, the PIPE_CONTROL instruction table, bit 16 (Generic Media
4211 * State Clear) says:
4212 *
4213 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
4214 * programmed prior to programming a PIPECONTROL command with "Media
4215 * State Clear" set in GPGPU mode of operation"
4216 *
4217 * This is a subset of the earlier rule, so there's nothing to do.
4218 */
4219 flags |= PIPE_CONTROL_CS_STALL;
4220 }
4221
4222 if (flags & PIPE_CONTROL_STORE_DATA_INDEX) {
4223 /* Project: All / Argument: Store Data Index
4224 *
4225 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
4226 * than '0'."
4227 *
4228 * For now, we just assert that the caller does this. We might want to
4229 * automatically add a write to the workaround BO...
4230 */
4231 assert(non_lri_post_sync_flags != 0);
4232 }
4233
4234 if (flags & PIPE_CONTROL_SYNC_GFDT) {
4235 /* Project: All / Argument: Sync GFDT
4236 *
4237 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
4238 * than '0' or 0x2520[13] must be set."
4239 *
4240 * For now, we just assert that the caller does this.
4241 */
4242 assert(non_lri_post_sync_flags != 0);
4243 }
4244
4245 if (flags & PIPE_CONTROL_TLB_INVALIDATE) {
4246 /* Project: IVB+ / Argument: TLB inv
4247 *
4248 * "Requires stall bit ([20] of DW1) set."
4249 *
4250 * Also, from the PIPE_CONTROL instruction table:
4251 *
4252 * "Project: SKL+
4253 * Post Sync Operation or CS stall must be set to ensure a TLB
4254 * invalidation occurs. Otherwise no cycle will occur to the TLB
4255 * cache to invalidate."
4256 *
4257 * This is not a subset of the earlier rule, so there's nothing to do.
4258 */
4259 flags |= PIPE_CONTROL_CS_STALL;
4260 }
4261
4262 if (GEN_GEN == 9 && devinfo->gt == 4) {
4263 /* TODO: The big Skylake GT4 post sync op workaround */
4264 }
4265
4266 /* "GPGPU specific workarounds" (both post-sync and flush) ------------ */
4267
4268 if (IS_COMPUTE_PIPELINE(batch)) {
4269 if (GEN_GEN >= 9 && (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE)) {
4270 /* Project: SKL+ / Argument: Tex Invalidate
4271 * "Requires stall bit ([20] of DW) set for all GPGPU Workloads."
4272 */
4273 flags |= PIPE_CONTROL_CS_STALL;
4274 }
4275
4276 if (GEN_GEN == 8 && (post_sync_flags ||
4277 (flags & (PIPE_CONTROL_NOTIFY_ENABLE |
4278 PIPE_CONTROL_DEPTH_STALL |
4279 PIPE_CONTROL_RENDER_TARGET_FLUSH |
4280 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
4281 PIPE_CONTROL_DATA_CACHE_FLUSH)))) {
4282 /* Project: BDW / Arguments:
4283 *
4284 * - LRI Post Sync Operation [23]
4285 * - Post Sync Op [15:14]
4286 * - Notify En [8]
4287 * - Depth Stall [13]
4288 * - Render Target Cache Flush [12]
4289 * - Depth Cache Flush [0]
4290 * - DC Flush Enable [5]
4291 *
4292 * "Requires stall bit ([20] of DW) set for all GPGPU and Media
4293 * Workloads."
4294 */
4295 flags |= PIPE_CONTROL_CS_STALL;
4296
4297 /* Also, from the PIPE_CONTROL instruction table, bit 20:
4298 *
4299 * "Project: BDW
4300 * This bit must be always set when PIPE_CONTROL command is
4301 * programmed by GPGPU and MEDIA workloads, except for the cases
4302 * when only Read Only Cache Invalidation bits are set (State
4303 * Cache Invalidation Enable, Instruction cache Invalidation
4304 * Enable, Texture Cache Invalidation Enable, Constant Cache
4305 * Invalidation Enable). This is to WA FFDOP CG issue, this WA
4306 * need not implemented when FF_DOP_CG is disable via "Fixed
4307 * Function DOP Clock Gate Disable" bit in RC_PSMI_CTRL register."
4308 *
4309 * It sounds like we could avoid CS stalls in some cases, but we
4310 * don't currently bother. This list isn't exactly the list above,
4311 * either...
4312 */
4313 }
4314 }
4315
4316 /* "Stall" workarounds ----------------------------------------------
4317 * These have to come after the earlier ones because we may have added
4318 * some additional CS stalls above.
4319 */
4320
4321 if (GEN_GEN < 9 && (flags & PIPE_CONTROL_CS_STALL)) {
4322 /* Project: PRE-SKL, VLV, CHV
4323 *
4324 * "[All Stepping][All SKUs]:
4325 *
4326 * One of the following must also be set:
4327 *
4328 * - Render Target Cache Flush Enable ([12] of DW1)
4329 * - Depth Cache Flush Enable ([0] of DW1)
4330 * - Stall at Pixel Scoreboard ([1] of DW1)
4331 * - Depth Stall ([13] of DW1)
4332 * - Post-Sync Operation ([13] of DW1)
4333 * - DC Flush Enable ([5] of DW1)"
4334 *
4335 * If we don't already have one of those bits set, we choose to add
4336 * "Stall at Pixel Scoreboard". Some of the other bits require a
4337 * CS stall as a workaround (see above), which would send us into
4338 * an infinite recursion of PIPE_CONTROLs. "Stall at Pixel Scoreboard"
4339 * appears to be safe, so we choose that.
4340 */
4341 const uint32_t wa_bits = PIPE_CONTROL_RENDER_TARGET_FLUSH |
4342 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
4343 PIPE_CONTROL_WRITE_IMMEDIATE |
4344 PIPE_CONTROL_WRITE_DEPTH_COUNT |
4345 PIPE_CONTROL_WRITE_TIMESTAMP |
4346 PIPE_CONTROL_STALL_AT_SCOREBOARD |
4347 PIPE_CONTROL_DEPTH_STALL |
4348 PIPE_CONTROL_DATA_CACHE_FLUSH;
4349 if (!(flags & wa_bits))
4350 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
4351 }
4352
4353 /* Emit --------------------------------------------------------------- */
4354
4355 iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
4356 pc.LRIPostSyncOperation = NoLRIOperation;
4357 pc.PipeControlFlushEnable = flags & PIPE_CONTROL_FLUSH_ENABLE;
4358 pc.DCFlushEnable = flags & PIPE_CONTROL_DATA_CACHE_FLUSH;
4359 pc.StoreDataIndex = 0;
4360 pc.CommandStreamerStallEnable = flags & PIPE_CONTROL_CS_STALL;
4361 pc.GlobalSnapshotCountReset =
4362 flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET;
4363 pc.TLBInvalidate = flags & PIPE_CONTROL_TLB_INVALIDATE;
4364 pc.GenericMediaStateClear = flags & PIPE_CONTROL_MEDIA_STATE_CLEAR;
4365 pc.StallAtPixelScoreboard = flags & PIPE_CONTROL_STALL_AT_SCOREBOARD;
4366 pc.RenderTargetCacheFlushEnable =
4367 flags & PIPE_CONTROL_RENDER_TARGET_FLUSH;
4368 pc.DepthCacheFlushEnable = flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH;
4369 pc.StateCacheInvalidationEnable =
4370 flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE;
4371 pc.VFCacheInvalidationEnable = flags & PIPE_CONTROL_VF_CACHE_INVALIDATE;
4372 pc.ConstantCacheInvalidationEnable =
4373 flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE;
4374 pc.PostSyncOperation = flags_to_post_sync_op(flags);
4375 pc.DepthStallEnable = flags & PIPE_CONTROL_DEPTH_STALL;
4376 pc.InstructionCacheInvalidateEnable =
4377 flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE;
4378 pc.NotifyEnable = flags & PIPE_CONTROL_NOTIFY_ENABLE;
4379 pc.IndirectStatePointersDisable =
4380 flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE;
4381 pc.TextureCacheInvalidationEnable =
4382 flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
4383 pc.Address = ro_bo(bo, offset);
4384 pc.ImmediateData = imm;
4385 }
4386 }
4387
4388 void
4389 genX(init_state)(struct iris_context *ice)
4390 {
4391 struct pipe_context *ctx = &ice->ctx;
4392 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
4393
4394 ctx->create_blend_state = iris_create_blend_state;
4395 ctx->create_depth_stencil_alpha_state = iris_create_zsa_state;
4396 ctx->create_rasterizer_state = iris_create_rasterizer_state;
4397 ctx->create_sampler_state = iris_create_sampler_state;
4398 ctx->create_sampler_view = iris_create_sampler_view;
4399 ctx->create_surface = iris_create_surface;
4400 ctx->create_vertex_elements_state = iris_create_vertex_elements;
4401 ctx->create_compute_state = iris_create_compute_state;
4402 ctx->bind_blend_state = iris_bind_blend_state;
4403 ctx->bind_depth_stencil_alpha_state = iris_bind_zsa_state;
4404 ctx->bind_sampler_states = iris_bind_sampler_states;
4405 ctx->bind_rasterizer_state = iris_bind_rasterizer_state;
4406 ctx->bind_vertex_elements_state = iris_bind_vertex_elements_state;
4407 ctx->bind_compute_state = iris_bind_compute_state;
4408 ctx->delete_blend_state = iris_delete_state;
4409 ctx->delete_depth_stencil_alpha_state = iris_delete_state;
4410 ctx->delete_fs_state = iris_delete_state;
4411 ctx->delete_rasterizer_state = iris_delete_state;
4412 ctx->delete_sampler_state = iris_delete_state;
4413 ctx->delete_vertex_elements_state = iris_delete_state;
4414 ctx->delete_compute_state = iris_delete_state;
4415 ctx->delete_tcs_state = iris_delete_state;
4416 ctx->delete_tes_state = iris_delete_state;
4417 ctx->delete_gs_state = iris_delete_state;
4418 ctx->delete_vs_state = iris_delete_state;
4419 ctx->set_blend_color = iris_set_blend_color;
4420 ctx->set_clip_state = iris_set_clip_state;
4421 ctx->set_constant_buffer = iris_set_constant_buffer;
4422 ctx->set_shader_buffers = iris_set_shader_buffers;
4423 ctx->set_sampler_views = iris_set_sampler_views;
4424 ctx->set_framebuffer_state = iris_set_framebuffer_state;
4425 ctx->set_polygon_stipple = iris_set_polygon_stipple;
4426 ctx->set_sample_mask = iris_set_sample_mask;
4427 ctx->set_scissor_states = iris_set_scissor_states;
4428 ctx->set_stencil_ref = iris_set_stencil_ref;
4429 ctx->set_vertex_buffers = iris_set_vertex_buffers;
4430 ctx->set_viewport_states = iris_set_viewport_states;
4431 ctx->sampler_view_destroy = iris_sampler_view_destroy;
4432 ctx->surface_destroy = iris_surface_destroy;
4433 ctx->draw_vbo = iris_draw_vbo;
4434 ctx->launch_grid = iris_launch_grid;
4435 ctx->create_stream_output_target = iris_create_stream_output_target;
4436 ctx->stream_output_target_destroy = iris_stream_output_target_destroy;
4437 ctx->set_stream_output_targets = iris_set_stream_output_targets;
4438
4439 ice->vtbl.destroy_state = iris_destroy_state;
4440 ice->vtbl.init_render_context = iris_init_render_context;
4441 ice->vtbl.upload_render_state = iris_upload_render_state;
4442 ice->vtbl.update_surface_base_address = iris_update_surface_base_address;
4443 ice->vtbl.emit_raw_pipe_control = iris_emit_raw_pipe_control;
4444 ice->vtbl.derived_program_state_size = iris_derived_program_state_size;
4445 ice->vtbl.store_derived_program_state = iris_store_derived_program_state;
4446 ice->vtbl.create_so_decl_list = iris_create_so_decl_list;
4447 ice->vtbl.populate_vs_key = iris_populate_vs_key;
4448 ice->vtbl.populate_tcs_key = iris_populate_tcs_key;
4449 ice->vtbl.populate_tes_key = iris_populate_tes_key;
4450 ice->vtbl.populate_gs_key = iris_populate_gs_key;
4451 ice->vtbl.populate_fs_key = iris_populate_fs_key;
4452
4453 ice->state.dirty = ~0ull;
4454
4455 ice->state.sample_mask = 0xffff;
4456 ice->state.num_viewports = 1;
4457 ice->state.genx = calloc(1, sizeof(struct iris_genx_state));
4458
4459 /* Make a 1x1x1 null surface for unbound textures */
4460 void *null_surf_map =
4461 upload_state(ice->state.surface_uploader, &ice->state.unbound_tex,
4462 4 * GENX(RENDER_SURFACE_STATE_length), 64);
4463 isl_null_fill_state(&screen->isl_dev, null_surf_map, isl_extent3d(1, 1, 1));
4464 ice->state.unbound_tex.offset +=
4465 iris_bo_offset_from_base_address(iris_resource_bo(ice->state.unbound_tex.res));
4466 }