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