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