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