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