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