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