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