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