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