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