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