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