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