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