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