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