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