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