iris: disable __gen_validate_value in release mode
[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 * on the rights to use, copy, modify, merge, publish, distribute, sub
8 * license, and/or sell copies of the Software, and to permit persons to whom
9 * the Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE.
22 */
23 #include <stdio.h>
24 #include <errno.h>
25
26 #if HAVE_VALGRIND
27 #include <valgrind.h>
28 #include <memcheck.h>
29 #define VG(x) x
30 #ifndef NDEBUG
31 #define __gen_validate_value(x) VALGRIND_CHECK_MEM_IS_DEFINED(&(x), sizeof(x))
32 #endif
33 #else
34 #define VG(x)
35 #endif
36
37 #include "pipe/p_defines.h"
38 #include "pipe/p_state.h"
39 #include "pipe/p_context.h"
40 #include "pipe/p_screen.h"
41 #include "util/u_inlines.h"
42 #include "util/u_format.h"
43 #include "util/u_framebuffer.h"
44 #include "util/u_transfer.h"
45 #include "util/u_upload_mgr.h"
46 #include "i915_drm.h"
47 #include "nir.h"
48 #include "intel/compiler/brw_compiler.h"
49 #include "intel/common/gen_l3_config.h"
50 #include "intel/common/gen_sample_positions.h"
51 #include "iris_batch.h"
52 #include "iris_context.h"
53 #include "iris_pipe.h"
54 #include "iris_resource.h"
55
56 #define __gen_address_type struct iris_address
57 #define __gen_user_data struct iris_batch
58
59 #define ARRAY_BYTES(x) (sizeof(uint32_t) * ARRAY_SIZE(x))
60
61 static uint64_t
62 __gen_combine_address(struct iris_batch *batch, void *location,
63 struct iris_address addr, uint32_t delta)
64 {
65 uint64_t result = addr.offset + delta;
66
67 if (addr.bo) {
68 iris_use_pinned_bo(batch, addr.bo, addr.write);
69 /* Assume this is a general address, not relative to a base. */
70 result += addr.bo->gtt_offset;
71 }
72
73 return result;
74 }
75
76 #define __genxml_cmd_length(cmd) cmd ## _length
77 #define __genxml_cmd_length_bias(cmd) cmd ## _length_bias
78 #define __genxml_cmd_header(cmd) cmd ## _header
79 #define __genxml_cmd_pack(cmd) cmd ## _pack
80
81 #define _iris_pack_command(batch, cmd, dst, name) \
82 for (struct cmd name = { __genxml_cmd_header(cmd) }, \
83 *_dst = (void *)(dst); __builtin_expect(_dst != NULL, 1); \
84 ({ __genxml_cmd_pack(cmd)(batch, (void *)_dst, &name); \
85 _dst = NULL; \
86 }))
87
88 #define iris_pack_command(cmd, dst, name) \
89 _iris_pack_command(NULL, cmd, dst, name)
90
91 #define iris_pack_state(cmd, dst, name) \
92 for (struct cmd name = {}, \
93 *_dst = (void *)(dst); __builtin_expect(_dst != NULL, 1); \
94 __genxml_cmd_pack(cmd)(NULL, (void *)_dst, &name), \
95 _dst = NULL)
96
97 #define iris_emit_cmd(batch, cmd, name) \
98 _iris_pack_command(batch, cmd, iris_get_command_space(batch, 4 * __genxml_cmd_length(cmd)), name)
99
100 #define iris_emit_merge(batch, dwords0, dwords1, num_dwords) \
101 do { \
102 uint32_t *dw = iris_get_command_space(batch, 4 * num_dwords); \
103 for (uint32_t i = 0; i < num_dwords; i++) \
104 dw[i] = (dwords0)[i] | (dwords1)[i]; \
105 VG(VALGRIND_CHECK_MEM_IS_DEFINED(dw, num_dwords)); \
106 } while (0)
107
108 #include "genxml/genX_pack.h"
109 #include "genxml/gen_macros.h"
110 #include "genxml/genX_bits.h"
111
112 #define MOCS_WB (2 << 1)
113
114 UNUSED static void pipe_asserts()
115 {
116 #define PIPE_ASSERT(x) STATIC_ASSERT((int)x)
117
118 /* pipe_logicop happens to match the hardware. */
119 PIPE_ASSERT(PIPE_LOGICOP_CLEAR == LOGICOP_CLEAR);
120 PIPE_ASSERT(PIPE_LOGICOP_NOR == LOGICOP_NOR);
121 PIPE_ASSERT(PIPE_LOGICOP_AND_INVERTED == LOGICOP_AND_INVERTED);
122 PIPE_ASSERT(PIPE_LOGICOP_COPY_INVERTED == LOGICOP_COPY_INVERTED);
123 PIPE_ASSERT(PIPE_LOGICOP_AND_REVERSE == LOGICOP_AND_REVERSE);
124 PIPE_ASSERT(PIPE_LOGICOP_INVERT == LOGICOP_INVERT);
125 PIPE_ASSERT(PIPE_LOGICOP_XOR == LOGICOP_XOR);
126 PIPE_ASSERT(PIPE_LOGICOP_NAND == LOGICOP_NAND);
127 PIPE_ASSERT(PIPE_LOGICOP_AND == LOGICOP_AND);
128 PIPE_ASSERT(PIPE_LOGICOP_EQUIV == LOGICOP_EQUIV);
129 PIPE_ASSERT(PIPE_LOGICOP_NOOP == LOGICOP_NOOP);
130 PIPE_ASSERT(PIPE_LOGICOP_OR_INVERTED == LOGICOP_OR_INVERTED);
131 PIPE_ASSERT(PIPE_LOGICOP_COPY == LOGICOP_COPY);
132 PIPE_ASSERT(PIPE_LOGICOP_OR_REVERSE == LOGICOP_OR_REVERSE);
133 PIPE_ASSERT(PIPE_LOGICOP_OR == LOGICOP_OR);
134 PIPE_ASSERT(PIPE_LOGICOP_SET == LOGICOP_SET);
135
136 /* pipe_blend_func happens to match the hardware. */
137 PIPE_ASSERT(PIPE_BLENDFACTOR_ONE == BLENDFACTOR_ONE);
138 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_COLOR == BLENDFACTOR_SRC_COLOR);
139 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA == BLENDFACTOR_SRC_ALPHA);
140 PIPE_ASSERT(PIPE_BLENDFACTOR_DST_ALPHA == BLENDFACTOR_DST_ALPHA);
141 PIPE_ASSERT(PIPE_BLENDFACTOR_DST_COLOR == BLENDFACTOR_DST_COLOR);
142 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE == BLENDFACTOR_SRC_ALPHA_SATURATE);
143 PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_COLOR == BLENDFACTOR_CONST_COLOR);
144 PIPE_ASSERT(PIPE_BLENDFACTOR_CONST_ALPHA == BLENDFACTOR_CONST_ALPHA);
145 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_COLOR == BLENDFACTOR_SRC1_COLOR);
146 PIPE_ASSERT(PIPE_BLENDFACTOR_SRC1_ALPHA == BLENDFACTOR_SRC1_ALPHA);
147 PIPE_ASSERT(PIPE_BLENDFACTOR_ZERO == BLENDFACTOR_ZERO);
148 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_COLOR == BLENDFACTOR_INV_SRC_COLOR);
149 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC_ALPHA == BLENDFACTOR_INV_SRC_ALPHA);
150 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_ALPHA == BLENDFACTOR_INV_DST_ALPHA);
151 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_DST_COLOR == BLENDFACTOR_INV_DST_COLOR);
152 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_COLOR == BLENDFACTOR_INV_CONST_COLOR);
153 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_CONST_ALPHA == BLENDFACTOR_INV_CONST_ALPHA);
154 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_COLOR == BLENDFACTOR_INV_SRC1_COLOR);
155 PIPE_ASSERT(PIPE_BLENDFACTOR_INV_SRC1_ALPHA == BLENDFACTOR_INV_SRC1_ALPHA);
156
157 /* pipe_blend_func happens to match the hardware. */
158 PIPE_ASSERT(PIPE_BLEND_ADD == BLENDFUNCTION_ADD);
159 PIPE_ASSERT(PIPE_BLEND_SUBTRACT == BLENDFUNCTION_SUBTRACT);
160 PIPE_ASSERT(PIPE_BLEND_REVERSE_SUBTRACT == BLENDFUNCTION_REVERSE_SUBTRACT);
161 PIPE_ASSERT(PIPE_BLEND_MIN == BLENDFUNCTION_MIN);
162 PIPE_ASSERT(PIPE_BLEND_MAX == BLENDFUNCTION_MAX);
163
164 /* pipe_stencil_op happens to match the hardware. */
165 PIPE_ASSERT(PIPE_STENCIL_OP_KEEP == STENCILOP_KEEP);
166 PIPE_ASSERT(PIPE_STENCIL_OP_ZERO == STENCILOP_ZERO);
167 PIPE_ASSERT(PIPE_STENCIL_OP_REPLACE == STENCILOP_REPLACE);
168 PIPE_ASSERT(PIPE_STENCIL_OP_INCR == STENCILOP_INCRSAT);
169 PIPE_ASSERT(PIPE_STENCIL_OP_DECR == STENCILOP_DECRSAT);
170 PIPE_ASSERT(PIPE_STENCIL_OP_INCR_WRAP == STENCILOP_INCR);
171 PIPE_ASSERT(PIPE_STENCIL_OP_DECR_WRAP == STENCILOP_DECR);
172 PIPE_ASSERT(PIPE_STENCIL_OP_INVERT == STENCILOP_INVERT);
173
174 /* pipe_sprite_coord_mode happens to match 3DSTATE_SBE */
175 PIPE_ASSERT(PIPE_SPRITE_COORD_UPPER_LEFT == UPPERLEFT);
176 PIPE_ASSERT(PIPE_SPRITE_COORD_LOWER_LEFT == LOWERLEFT);
177 #undef PIPE_ASSERT
178 }
179
180 static unsigned
181 translate_prim_type(enum pipe_prim_type prim, uint8_t verts_per_patch)
182 {
183 static const unsigned map[] = {
184 [PIPE_PRIM_POINTS] = _3DPRIM_POINTLIST,
185 [PIPE_PRIM_LINES] = _3DPRIM_LINELIST,
186 [PIPE_PRIM_LINE_LOOP] = _3DPRIM_LINELOOP,
187 [PIPE_PRIM_LINE_STRIP] = _3DPRIM_LINESTRIP,
188 [PIPE_PRIM_TRIANGLES] = _3DPRIM_TRILIST,
189 [PIPE_PRIM_TRIANGLE_STRIP] = _3DPRIM_TRISTRIP,
190 [PIPE_PRIM_TRIANGLE_FAN] = _3DPRIM_TRIFAN,
191 [PIPE_PRIM_QUADS] = _3DPRIM_QUADLIST,
192 [PIPE_PRIM_QUAD_STRIP] = _3DPRIM_QUADSTRIP,
193 [PIPE_PRIM_POLYGON] = _3DPRIM_POLYGON,
194 [PIPE_PRIM_LINES_ADJACENCY] = _3DPRIM_LINELIST_ADJ,
195 [PIPE_PRIM_LINE_STRIP_ADJACENCY] = _3DPRIM_LINESTRIP_ADJ,
196 [PIPE_PRIM_TRIANGLES_ADJACENCY] = _3DPRIM_TRILIST_ADJ,
197 [PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY] = _3DPRIM_TRISTRIP_ADJ,
198 [PIPE_PRIM_PATCHES] = _3DPRIM_PATCHLIST_1 - 1,
199 };
200
201 return map[prim] + (prim == PIPE_PRIM_PATCHES ? verts_per_patch : 0);
202 }
203
204 static unsigned
205 translate_compare_func(enum pipe_compare_func pipe_func)
206 {
207 static const unsigned map[] = {
208 [PIPE_FUNC_NEVER] = COMPAREFUNCTION_NEVER,
209 [PIPE_FUNC_LESS] = COMPAREFUNCTION_LESS,
210 [PIPE_FUNC_EQUAL] = COMPAREFUNCTION_EQUAL,
211 [PIPE_FUNC_LEQUAL] = COMPAREFUNCTION_LEQUAL,
212 [PIPE_FUNC_GREATER] = COMPAREFUNCTION_GREATER,
213 [PIPE_FUNC_NOTEQUAL] = COMPAREFUNCTION_NOTEQUAL,
214 [PIPE_FUNC_GEQUAL] = COMPAREFUNCTION_GEQUAL,
215 [PIPE_FUNC_ALWAYS] = COMPAREFUNCTION_ALWAYS,
216 };
217 return map[pipe_func];
218 }
219
220 static unsigned
221 translate_shadow_func(enum pipe_compare_func pipe_func)
222 {
223 /* Gallium specifies the result of shadow comparisons as:
224 *
225 * 1 if ref <op> texel,
226 * 0 otherwise.
227 *
228 * The hardware does:
229 *
230 * 0 if texel <op> ref,
231 * 1 otherwise.
232 *
233 * So we need to flip the operator and also negate.
234 */
235 static const unsigned map[] = {
236 [PIPE_FUNC_NEVER] = PREFILTEROPALWAYS,
237 [PIPE_FUNC_LESS] = PREFILTEROPLEQUAL,
238 [PIPE_FUNC_EQUAL] = PREFILTEROPNOTEQUAL,
239 [PIPE_FUNC_LEQUAL] = PREFILTEROPLESS,
240 [PIPE_FUNC_GREATER] = PREFILTEROPGEQUAL,
241 [PIPE_FUNC_NOTEQUAL] = PREFILTEROPEQUAL,
242 [PIPE_FUNC_GEQUAL] = PREFILTEROPGREATER,
243 [PIPE_FUNC_ALWAYS] = PREFILTEROPNEVER,
244 };
245 return map[pipe_func];
246 }
247
248 static unsigned
249 translate_cull_mode(unsigned pipe_face)
250 {
251 static const unsigned map[4] = {
252 [PIPE_FACE_NONE] = CULLMODE_NONE,
253 [PIPE_FACE_FRONT] = CULLMODE_FRONT,
254 [PIPE_FACE_BACK] = CULLMODE_BACK,
255 [PIPE_FACE_FRONT_AND_BACK] = CULLMODE_BOTH,
256 };
257 return map[pipe_face];
258 }
259
260 static unsigned
261 translate_fill_mode(unsigned pipe_polymode)
262 {
263 static const unsigned map[4] = {
264 [PIPE_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
265 [PIPE_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
266 [PIPE_POLYGON_MODE_POINT] = FILL_MODE_POINT,
267 [PIPE_POLYGON_MODE_FILL_RECTANGLE] = FILL_MODE_SOLID,
268 };
269 return map[pipe_polymode];
270 }
271
272 static struct iris_address
273 ro_bo(struct iris_bo *bo, uint64_t offset)
274 {
275 /* Not for CSOs! */
276 return (struct iris_address) { .bo = bo, .offset = offset };
277 }
278
279 static uint32_t *
280 stream_state(struct iris_batch *batch,
281 struct u_upload_mgr *uploader,
282 unsigned size,
283 unsigned alignment,
284 uint32_t *out_offset)
285 {
286 struct pipe_resource *res = NULL;
287 void *ptr = NULL;
288
289 u_upload_alloc(uploader, 0, size, alignment, out_offset, &res, &ptr);
290
291 struct iris_bo *bo = iris_resource_bo(res);
292 iris_use_pinned_bo(batch, bo, false);
293
294 *out_offset += iris_bo_offset_from_base_address(bo);
295
296 pipe_resource_reference(&res, NULL);
297
298 return ptr;
299 }
300
301 static uint32_t
302 emit_state(struct iris_batch *batch,
303 struct u_upload_mgr *uploader,
304 const void *data,
305 unsigned size,
306 unsigned alignment)
307 {
308 unsigned offset = 0;
309 uint32_t *map = stream_state(batch, uploader, size, alignment, &offset);
310
311 if (map)
312 memcpy(map, data, size);
313
314 return offset;
315 }
316
317 static void
318 iris_init_render_context(struct iris_screen *screen,
319 struct iris_batch *batch,
320 struct iris_vtable *vtbl,
321 struct pipe_debug_callback *dbg)
322 {
323 iris_init_batch(batch, screen, vtbl, dbg, I915_EXEC_RENDER);
324
325 /* XXX: PIPE_CONTROLs */
326
327 iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
328 #if 0
329 // XXX: MOCS is stupid for this.
330 sba.GeneralStateMemoryObjectControlState = MOCS_WB;
331 sba.StatelessDataPortAccessMemoryObjectControlState = MOCS_WB;
332 sba.SurfaceStateMemoryObjectControlState = MOCS_WB;
333 sba.DynamicStateMemoryObjectControlState = MOCS_WB;
334 sba.IndirectObjectMemoryObjectControlState = MOCS_WB;
335 sba.InstructionMemoryObjectControlState = MOCS_WB;
336 sba.BindlessSurfaceStateMemoryObjectControlState = MOCS_WB;
337 #endif
338
339 sba.GeneralStateBaseAddressModifyEnable = true;
340 sba.SurfaceStateBaseAddressModifyEnable = true;
341 sba.DynamicStateBaseAddressModifyEnable = true;
342 sba.IndirectObjectBaseAddressModifyEnable = true;
343 sba.InstructionBaseAddressModifyEnable = true;
344 sba.GeneralStateBufferSizeModifyEnable = true;
345 sba.DynamicStateBufferSizeModifyEnable = true;
346 sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
347 sba.IndirectObjectBufferSizeModifyEnable = true;
348 sba.InstructionBuffersizeModifyEnable = true;
349
350 sba.InstructionBaseAddress = ro_bo(NULL, IRIS_MEMZONE_SHADER_START);
351 sba.SurfaceStateBaseAddress = ro_bo(NULL, IRIS_MEMZONE_SURFACE_START);
352 sba.DynamicStateBaseAddress = ro_bo(NULL, IRIS_MEMZONE_DYNAMIC_START);
353
354 sba.GeneralStateBufferSize = 0xfffff;
355 sba.IndirectObjectBufferSize = 0xfffff;
356 sba.InstructionBufferSize = 0xfffff;
357 sba.DynamicStateBufferSize = 0xfffff;
358 }
359
360 iris_emit_cmd(batch, GENX(3DSTATE_DRAWING_RECTANGLE), rect) {
361 rect.ClippedDrawingRectangleXMax = UINT16_MAX;
362 rect.ClippedDrawingRectangleYMax = UINT16_MAX;
363 }
364 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_PATTERN), pat) {
365 GEN_SAMPLE_POS_1X(pat._1xSample);
366 GEN_SAMPLE_POS_2X(pat._2xSample);
367 GEN_SAMPLE_POS_4X(pat._4xSample);
368 GEN_SAMPLE_POS_8X(pat._8xSample);
369 GEN_SAMPLE_POS_16X(pat._16xSample);
370 }
371 iris_emit_cmd(batch, GENX(3DSTATE_AA_LINE_PARAMETERS), foo);
372 iris_emit_cmd(batch, GENX(3DSTATE_WM_CHROMAKEY), foo);
373 iris_emit_cmd(batch, GENX(3DSTATE_WM_HZ_OP), foo);
374 /* XXX: may need to set an offset for origin-UL framebuffers */
375 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_OFFSET), foo);
376
377 /* Just assign a static partitioning. */
378 for (int i = 0; i <= MESA_SHADER_FRAGMENT; i++) {
379 iris_emit_cmd(batch, GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
380 alloc._3DCommandSubOpcode = 18 + i;
381 alloc.ConstantBufferOffset = 6 * i;
382 alloc.ConstantBufferSize = i == MESA_SHADER_FRAGMENT ? 8 : 6;
383 }
384 }
385 }
386
387 static void
388 iris_launch_grid(struct pipe_context *ctx, const struct pipe_grid_info *info)
389 {
390 }
391
392 static void
393 iris_set_blend_color(struct pipe_context *ctx,
394 const struct pipe_blend_color *state)
395 {
396 struct iris_context *ice = (struct iris_context *) ctx;
397
398 memcpy(&ice->state.blend_color, state, sizeof(struct pipe_blend_color));
399 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
400 }
401
402 struct iris_blend_state {
403 uint32_t ps_blend[GENX(3DSTATE_PS_BLEND_length)];
404 uint32_t blend_state[GENX(BLEND_STATE_length) +
405 BRW_MAX_DRAW_BUFFERS * GENX(BLEND_STATE_ENTRY_length)];
406
407 bool alpha_to_coverage; /* for shader key */
408 };
409
410 static void *
411 iris_create_blend_state(struct pipe_context *ctx,
412 const struct pipe_blend_state *state)
413 {
414 struct iris_blend_state *cso = malloc(sizeof(struct iris_blend_state));
415 uint32_t *blend_state = cso->blend_state;
416
417 cso->alpha_to_coverage = state->alpha_to_coverage;
418
419 iris_pack_command(GENX(3DSTATE_PS_BLEND), cso->ps_blend, pb) {
420 /* pb.HasWriteableRT is filled in at draw time. */
421 /* pb.AlphaTestEnable is filled in at draw time. */
422 pb.AlphaToCoverageEnable = state->alpha_to_coverage;
423 pb.IndependentAlphaBlendEnable = state->independent_blend_enable;
424
425 pb.ColorBufferBlendEnable = state->rt[0].blend_enable;
426
427 pb.SourceBlendFactor = state->rt[0].rgb_src_factor;
428 pb.SourceAlphaBlendFactor = state->rt[0].alpha_func;
429 pb.DestinationBlendFactor = state->rt[0].rgb_dst_factor;
430 pb.DestinationAlphaBlendFactor = state->rt[0].alpha_dst_factor;
431 }
432
433 iris_pack_state(GENX(BLEND_STATE), blend_state, bs) {
434 bs.AlphaToCoverageEnable = state->alpha_to_coverage;
435 bs.IndependentAlphaBlendEnable = state->independent_blend_enable;
436 bs.AlphaToOneEnable = state->alpha_to_one;
437 bs.AlphaToCoverageDitherEnable = state->alpha_to_coverage;
438 bs.ColorDitherEnable = state->dither;
439 /* bl.AlphaTestEnable and bs.AlphaTestFunction are filled in later. */
440 }
441
442 blend_state += GENX(BLEND_STATE_length);
443
444 for (int i = 0; i < BRW_MAX_DRAW_BUFFERS; i++) {
445 iris_pack_state(GENX(BLEND_STATE_ENTRY), blend_state, be) {
446 be.LogicOpEnable = state->logicop_enable;
447 be.LogicOpFunction = state->logicop_func;
448
449 be.PreBlendSourceOnlyClampEnable = false;
450 be.ColorClampRange = COLORCLAMP_RTFORMAT;
451 be.PreBlendColorClampEnable = true;
452 be.PostBlendColorClampEnable = true;
453
454 be.ColorBufferBlendEnable = state->rt[i].blend_enable;
455
456 be.ColorBlendFunction = state->rt[i].rgb_func;
457 be.AlphaBlendFunction = state->rt[i].alpha_func;
458 be.SourceBlendFactor = state->rt[i].rgb_src_factor;
459 be.SourceAlphaBlendFactor = state->rt[i].alpha_func;
460 be.DestinationBlendFactor = state->rt[i].rgb_dst_factor;
461 be.DestinationAlphaBlendFactor = state->rt[i].alpha_dst_factor;
462
463 be.WriteDisableRed = !(state->rt[i].colormask & PIPE_MASK_R);
464 be.WriteDisableGreen = !(state->rt[i].colormask & PIPE_MASK_G);
465 be.WriteDisableBlue = !(state->rt[i].colormask & PIPE_MASK_B);
466 be.WriteDisableAlpha = !(state->rt[i].colormask & PIPE_MASK_A);
467 }
468 blend_state += GENX(BLEND_STATE_ENTRY_length);
469 }
470
471 return cso;
472 }
473
474 static void
475 iris_bind_blend_state(struct pipe_context *ctx, void *state)
476 {
477 struct iris_context *ice = (struct iris_context *) ctx;
478 ice->state.cso_blend = state;
479 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
480 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
481 }
482
483 struct iris_depth_stencil_alpha_state {
484 uint32_t wmds[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
485 uint32_t cc_vp[GENX(CC_VIEWPORT_length)];
486
487 struct pipe_alpha_state alpha; /* to BLEND_STATE, 3DSTATE_PS_BLEND */
488 };
489
490 static void *
491 iris_create_zsa_state(struct pipe_context *ctx,
492 const struct pipe_depth_stencil_alpha_state *state)
493 {
494 struct iris_depth_stencil_alpha_state *cso =
495 malloc(sizeof(struct iris_depth_stencil_alpha_state));
496
497 cso->alpha = state->alpha;
498
499 bool two_sided_stencil = state->stencil[1].enabled;
500
501 /* The state tracker needs to optimize away EQUAL writes for us. */
502 assert(!(state->depth.func == PIPE_FUNC_EQUAL && state->depth.writemask));
503
504 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), cso->wmds, wmds) {
505 wmds.StencilFailOp = state->stencil[0].fail_op;
506 wmds.StencilPassDepthFailOp = state->stencil[0].zfail_op;
507 wmds.StencilPassDepthPassOp = state->stencil[0].zpass_op;
508 wmds.StencilTestFunction =
509 translate_compare_func(state->stencil[0].func);
510 wmds.BackfaceStencilFailOp = state->stencil[1].fail_op;
511 wmds.BackfaceStencilPassDepthFailOp = state->stencil[1].zfail_op;
512 wmds.BackfaceStencilPassDepthPassOp = state->stencil[1].zpass_op;
513 wmds.BackfaceStencilTestFunction =
514 translate_compare_func(state->stencil[1].func);
515 wmds.DepthTestFunction = translate_compare_func(state->depth.func);
516 wmds.DoubleSidedStencilEnable = two_sided_stencil;
517 wmds.StencilTestEnable = state->stencil[0].enabled;
518 wmds.StencilBufferWriteEnable =
519 state->stencil[0].writemask != 0 ||
520 (two_sided_stencil && state->stencil[1].writemask != 0);
521 wmds.DepthTestEnable = state->depth.enabled;
522 wmds.DepthBufferWriteEnable = state->depth.writemask;
523 wmds.StencilTestMask = state->stencil[0].valuemask;
524 wmds.StencilWriteMask = state->stencil[0].writemask;
525 wmds.BackfaceStencilTestMask = state->stencil[1].valuemask;
526 wmds.BackfaceStencilWriteMask = state->stencil[1].writemask;
527 /* wmds.[Backface]StencilReferenceValue are merged later */
528 }
529
530 iris_pack_state(GENX(CC_VIEWPORT), cso->cc_vp, ccvp) {
531 ccvp.MinimumDepth = state->depth.bounds_min;
532 ccvp.MaximumDepth = state->depth.bounds_max;
533 }
534
535 return cso;
536 }
537
538 static void
539 iris_bind_zsa_state(struct pipe_context *ctx, void *state)
540 {
541 struct iris_context *ice = (struct iris_context *) ctx;
542 struct iris_depth_stencil_alpha_state *old_cso = ice->state.cso_zsa;
543 struct iris_depth_stencil_alpha_state *new_cso = state;
544
545 if (new_cso) {
546 if (!old_cso || old_cso->alpha.ref_value != new_cso->alpha.ref_value) {
547 ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
548 }
549 }
550
551 ice->state.cso_zsa = new_cso;
552 ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
553 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
554 }
555
556 struct iris_rasterizer_state {
557 uint32_t sf[GENX(3DSTATE_SF_length)];
558 uint32_t clip[GENX(3DSTATE_CLIP_length)];
559 uint32_t raster[GENX(3DSTATE_RASTER_length)];
560 uint32_t wm[GENX(3DSTATE_WM_length)];
561 uint32_t line_stipple[GENX(3DSTATE_LINE_STIPPLE_length)];
562
563 bool flatshade; /* for shader state */
564 bool clamp_fragment_color; /* for shader state */
565 bool light_twoside; /* for shader state */
566 bool rasterizer_discard; /* for 3DSTATE_STREAMOUT */
567 bool half_pixel_center; /* for 3DSTATE_MULTISAMPLE */
568 enum pipe_sprite_coord_mode sprite_coord_mode; /* PIPE_SPRITE_* */
569 uint16_t sprite_coord_enable;
570 };
571
572 static void *
573 iris_create_rasterizer_state(struct pipe_context *ctx,
574 const struct pipe_rasterizer_state *state)
575 {
576 struct iris_rasterizer_state *cso =
577 malloc(sizeof(struct iris_rasterizer_state));
578
579 #if 0
580 point_quad_rasterization -> SBE?
581
582 not necessary?
583 {
584 poly_smooth
585 force_persample_interp - ?
586 bottom_edge_rule
587
588 offset_units_unscaled - cap not exposed
589 }
590 #endif
591
592 cso->flatshade = state->flatshade;
593 cso->clamp_fragment_color = state->clamp_fragment_color;
594 cso->light_twoside = state->light_twoside;
595 cso->rasterizer_discard = state->rasterizer_discard;
596 cso->half_pixel_center = state->half_pixel_center;
597 cso->sprite_coord_mode = state->sprite_coord_mode;
598 cso->sprite_coord_enable = state->sprite_coord_enable;
599
600 iris_pack_command(GENX(3DSTATE_SF), cso->sf, sf) {
601 sf.StatisticsEnable = true;
602 sf.ViewportTransformEnable = true;
603 sf.AALineDistanceMode = AALINEDISTANCE_TRUE;
604 sf.LineEndCapAntialiasingRegionWidth =
605 state->line_smooth ? _10pixels : _05pixels;
606 sf.LastPixelEnable = state->line_last_pixel;
607 sf.LineWidth = state->line_width;
608 sf.SmoothPointEnable = state->point_smooth;
609 sf.PointWidthSource = state->point_size_per_vertex ? Vertex : State;
610 sf.PointWidth = state->point_size;
611
612 if (state->flatshade_first) {
613 sf.TriangleStripListProvokingVertexSelect = 2;
614 sf.TriangleFanProvokingVertexSelect = 2;
615 sf.LineStripListProvokingVertexSelect = 1;
616 } else {
617 sf.TriangleFanProvokingVertexSelect = 1;
618 }
619 }
620
621 /* COMPLETE! */
622 iris_pack_command(GENX(3DSTATE_RASTER), cso->raster, rr) {
623 rr.FrontWinding = state->front_ccw ? CounterClockwise : Clockwise;
624 rr.CullMode = translate_cull_mode(state->cull_face);
625 rr.FrontFaceFillMode = translate_fill_mode(state->fill_front);
626 rr.BackFaceFillMode = translate_fill_mode(state->fill_back);
627 rr.DXMultisampleRasterizationEnable = state->multisample;
628 rr.GlobalDepthOffsetEnableSolid = state->offset_tri;
629 rr.GlobalDepthOffsetEnableWireframe = state->offset_line;
630 rr.GlobalDepthOffsetEnablePoint = state->offset_point;
631 rr.GlobalDepthOffsetConstant = state->offset_units;
632 rr.GlobalDepthOffsetScale = state->offset_scale;
633 rr.GlobalDepthOffsetClamp = state->offset_clamp;
634 rr.SmoothPointEnable = state->point_smooth;
635 rr.AntialiasingEnable = state->line_smooth;
636 rr.ScissorRectangleEnable = state->scissor;
637 rr.ViewportZNearClipTestEnable = state->depth_clip_near;
638 rr.ViewportZFarClipTestEnable = state->depth_clip_far;
639 //rr.ConservativeRasterizationEnable = not yet supported by Gallium...
640 }
641
642 iris_pack_command(GENX(3DSTATE_CLIP), cso->clip, cl) {
643 /* cl.NonPerspectiveBarycentricEnable is filled in at draw time from
644 * the FS program; cl.ForceZeroRTAIndexEnable is filled in from the FB.
645 */
646 cl.StatisticsEnable = true;
647 cl.EarlyCullEnable = true;
648 cl.UserClipDistanceClipTestEnableBitmask = state->clip_plane_enable;
649 cl.ForceUserClipDistanceClipTestEnableBitmask = true;
650 cl.APIMode = state->clip_halfz ? APIMODE_D3D : APIMODE_OGL;
651 cl.GuardbandClipTestEnable = true;
652 cl.ClipMode = CLIPMODE_NORMAL;
653 cl.ClipEnable = true;
654 cl.ViewportXYClipTestEnable = state->point_tri_clip;
655 cl.MinimumPointWidth = 0.125;
656 cl.MaximumPointWidth = 255.875;
657
658 if (state->flatshade_first) {
659 cl.TriangleStripListProvokingVertexSelect = 2;
660 cl.TriangleFanProvokingVertexSelect = 2;
661 cl.LineStripListProvokingVertexSelect = 1;
662 } else {
663 cl.TriangleFanProvokingVertexSelect = 1;
664 }
665 }
666
667 iris_pack_command(GENX(3DSTATE_WM), cso->wm, wm) {
668 /* wm.BarycentricInterpolationMode and wm.EarlyDepthStencilControl are
669 * filled in at draw time from the FS program.
670 */
671 wm.LineAntialiasingRegionWidth = _10pixels;
672 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
673 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
674 wm.StatisticsEnable = true;
675 wm.LineStippleEnable = state->line_stipple_enable;
676 wm.PolygonStippleEnable = state->poly_stipple_enable;
677 }
678
679 /* Remap from 0..255 back to 1..256 */
680 const unsigned line_stipple_factor = state->line_stipple_factor + 1;
681
682 iris_pack_command(GENX(3DSTATE_LINE_STIPPLE), cso->line_stipple, line) {
683 line.LineStipplePattern = state->line_stipple_pattern;
684 line.LineStippleInverseRepeatCount = 1.0f / line_stipple_factor;
685 line.LineStippleRepeatCount = line_stipple_factor;
686 }
687
688 return cso;
689 }
690
691 static void
692 iris_bind_rasterizer_state(struct pipe_context *ctx, void *state)
693 {
694 struct iris_context *ice = (struct iris_context *) ctx;
695 struct iris_rasterizer_state *old_cso = ice->state.cso_rast;
696 struct iris_rasterizer_state *new_cso = state;
697
698 if (new_cso) {
699 /* Try to avoid re-emitting 3DSTATE_LINE_STIPPLE, it's non-pipelined */
700 if (!old_cso || memcmp(old_cso->line_stipple, new_cso->line_stipple,
701 sizeof(old_cso->line_stipple)) != 0) {
702 ice->state.dirty |= IRIS_DIRTY_LINE_STIPPLE;
703 }
704
705 if (!old_cso ||
706 old_cso->half_pixel_center != new_cso->half_pixel_center) {
707 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
708 }
709 }
710
711 ice->state.cso_rast = new_cso;
712 ice->state.dirty |= IRIS_DIRTY_RASTER;
713 }
714
715 static uint32_t
716 translate_wrap(unsigned pipe_wrap)
717 {
718 static const unsigned map[] = {
719 [PIPE_TEX_WRAP_REPEAT] = TCM_WRAP,
720 [PIPE_TEX_WRAP_CLAMP] = TCM_HALF_BORDER,
721 [PIPE_TEX_WRAP_CLAMP_TO_EDGE] = TCM_CLAMP,
722 [PIPE_TEX_WRAP_CLAMP_TO_BORDER] = TCM_CLAMP_BORDER,
723 [PIPE_TEX_WRAP_MIRROR_REPEAT] = TCM_MIRROR,
724 [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE] = TCM_MIRROR_ONCE,
725 [PIPE_TEX_WRAP_MIRROR_CLAMP] = -1, // XXX: ???
726 [PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER] = -1, // XXX: ???
727 };
728 return map[pipe_wrap];
729 }
730
731 /**
732 * Return true if the given wrap mode requires the border color to exist.
733 */
734 static bool
735 wrap_mode_needs_border_color(unsigned wrap_mode)
736 {
737 return wrap_mode == TCM_CLAMP_BORDER || wrap_mode == TCM_HALF_BORDER;
738 }
739
740 static unsigned
741 translate_mip_filter(enum pipe_tex_mipfilter pipe_mip)
742 {
743 static const unsigned map[] = {
744 [PIPE_TEX_MIPFILTER_NEAREST] = MIPFILTER_NEAREST,
745 [PIPE_TEX_MIPFILTER_LINEAR] = MIPFILTER_LINEAR,
746 [PIPE_TEX_MIPFILTER_NONE] = MIPFILTER_NONE,
747 };
748 return map[pipe_mip];
749 }
750
751 struct iris_sampler_state {
752 struct pipe_sampler_state base;
753
754 bool needs_border_color;
755
756 uint32_t sampler_state[GENX(SAMPLER_STATE_length)];
757 };
758
759 static void *
760 iris_create_sampler_state(struct pipe_context *pctx,
761 const struct pipe_sampler_state *state)
762 {
763 struct iris_sampler_state *cso = CALLOC_STRUCT(iris_sampler_state);
764
765 if (!cso)
766 return NULL;
767
768 STATIC_ASSERT(PIPE_TEX_FILTER_NEAREST == MAPFILTER_NEAREST);
769 STATIC_ASSERT(PIPE_TEX_FILTER_LINEAR == MAPFILTER_LINEAR);
770
771 unsigned wrap_s = translate_wrap(state->wrap_s);
772 unsigned wrap_t = translate_wrap(state->wrap_t);
773 unsigned wrap_r = translate_wrap(state->wrap_r);
774
775 cso->needs_border_color = wrap_mode_needs_border_color(wrap_s) ||
776 wrap_mode_needs_border_color(wrap_t) ||
777 wrap_mode_needs_border_color(wrap_r);
778
779 iris_pack_state(GENX(SAMPLER_STATE), cso->sampler_state, samp) {
780 samp.TCXAddressControlMode = wrap_s;
781 samp.TCYAddressControlMode = wrap_t;
782 samp.TCZAddressControlMode = wrap_r;
783 samp.CubeSurfaceControlMode = state->seamless_cube_map;
784 samp.NonnormalizedCoordinateEnable = !state->normalized_coords;
785 samp.MinModeFilter = state->min_img_filter;
786 samp.MagModeFilter = state->mag_img_filter;
787 samp.MipModeFilter = translate_mip_filter(state->min_mip_filter);
788 samp.MaximumAnisotropy = RATIO21;
789
790 if (state->max_anisotropy >= 2) {
791 if (state->min_img_filter == PIPE_TEX_FILTER_LINEAR) {
792 samp.MinModeFilter = MAPFILTER_ANISOTROPIC;
793 samp.AnisotropicAlgorithm = EWAApproximation;
794 }
795
796 if (state->mag_img_filter == PIPE_TEX_FILTER_LINEAR)
797 samp.MagModeFilter = MAPFILTER_ANISOTROPIC;
798
799 samp.MaximumAnisotropy =
800 MIN2((state->max_anisotropy - 2) / 2, RATIO161);
801 }
802
803 /* Set address rounding bits if not using nearest filtering. */
804 if (state->min_img_filter != PIPE_TEX_FILTER_NEAREST) {
805 samp.UAddressMinFilterRoundingEnable = true;
806 samp.VAddressMinFilterRoundingEnable = true;
807 samp.RAddressMinFilterRoundingEnable = true;
808 }
809
810 if (state->mag_img_filter != PIPE_TEX_FILTER_NEAREST) {
811 samp.UAddressMagFilterRoundingEnable = true;
812 samp.VAddressMagFilterRoundingEnable = true;
813 samp.RAddressMagFilterRoundingEnable = true;
814 }
815
816 if (state->compare_mode == PIPE_TEX_COMPARE_R_TO_TEXTURE)
817 samp.ShadowFunction = translate_shadow_func(state->compare_func);
818
819 const float hw_max_lod = GEN_GEN >= 7 ? 14 : 13;
820
821 samp.LODPreClampMode = CLAMP_MODE_OGL;
822 samp.MinLOD = CLAMP(state->min_lod, 0, hw_max_lod);
823 samp.MaxLOD = CLAMP(state->max_lod, 0, hw_max_lod);
824 samp.TextureLODBias = CLAMP(state->lod_bias, -16, 15);
825
826 //samp.BorderColorPointer = <<comes from elsewhere>>
827 }
828
829 return cso;
830 }
831
832 static void
833 iris_bind_sampler_states(struct pipe_context *ctx,
834 enum pipe_shader_type p_stage,
835 unsigned start, unsigned count,
836 void **states)
837 {
838 struct iris_context *ice = (struct iris_context *) ctx;
839 gl_shader_stage stage = stage_from_pipe(p_stage);
840
841 assert(start + count <= IRIS_MAX_TEXTURE_SAMPLERS);
842
843 /* Assemble the SAMPLER_STATEs into a contiguous chunk of memory
844 * relative to Dynamic State Base Address.
845 */
846 void *map = NULL;
847 u_upload_alloc(ice->state.dynamic_uploader, 0,
848 count * 4 * GENX(SAMPLER_STATE_length), 32,
849 &ice->state.sampler_table_offset[stage],
850 &ice->state.sampler_table_resource[stage],
851 &map);
852 if (unlikely(!map))
853 return;
854
855 struct pipe_resource *res = ice->state.sampler_table_resource[stage];
856 ice->state.sampler_table_offset[stage] +=
857 iris_bo_offset_from_base_address(iris_resource_bo(res));
858
859 for (int i = 0; i < count; i++) {
860 struct iris_sampler_state *state = states[i];
861
862 /* Save a pointer to the iris_sampler_state, a few fields need
863 * to inform draw-time decisions.
864 */
865 ice->state.samplers[stage][start + i] = state;
866
867 if (state)
868 memcpy(map, state->sampler_state, 4 * GENX(SAMPLER_STATE_length));
869
870 map += GENX(SAMPLER_STATE_length);
871 }
872
873 ice->state.num_samplers[stage] = count;
874
875 ice->state.dirty |= IRIS_DIRTY_SAMPLER_STATES_VS << stage;
876 }
877
878 struct iris_sampler_view {
879 struct pipe_sampler_view pipe;
880 struct isl_view view;
881
882 /** The resource (BO) holding our SURFACE_STATE. */
883 struct pipe_resource *surface_state_resource;
884 unsigned surface_state_offset;
885
886 //uint32_t surface_state[GENX(RENDER_SURFACE_STATE_length)];
887 };
888
889 /**
890 * Convert an swizzle enumeration (i.e. PIPE_SWIZZLE_X) to one of the Gen7.5+
891 * "Shader Channel Select" enumerations (i.e. HSW_SCS_RED). The mappings are
892 *
893 * SWIZZLE_X, SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_W, SWIZZLE_ZERO, SWIZZLE_ONE
894 * 0 1 2 3 4 5
895 * 4 5 6 7 0 1
896 * SCS_RED, SCS_GREEN, SCS_BLUE, SCS_ALPHA, SCS_ZERO, SCS_ONE
897 *
898 * which is simply adding 4 then modding by 8 (or anding with 7).
899 *
900 * We then may need to apply workarounds for textureGather hardware bugs.
901 */
902 static enum isl_channel_select
903 pipe_swizzle_to_isl_channel(enum pipe_swizzle swizzle)
904 {
905 return (swizzle + 4) & 7;
906 }
907
908 static struct pipe_sampler_view *
909 iris_create_sampler_view(struct pipe_context *ctx,
910 struct pipe_resource *tex,
911 const struct pipe_sampler_view *tmpl)
912 {
913 struct iris_context *ice = (struct iris_context *) ctx;
914 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
915 struct iris_resource *itex = (struct iris_resource *) tex;
916 struct iris_sampler_view *isv = calloc(1, sizeof(struct iris_sampler_view));
917
918 if (!isv)
919 return NULL;
920
921 /* initialize base object */
922 isv->pipe = *tmpl;
923 isv->pipe.context = ctx;
924 isv->pipe.texture = NULL;
925 pipe_reference_init(&isv->pipe.reference, 1);
926 pipe_resource_reference(&isv->pipe.texture, tex);
927
928 /* XXX: do we need brw_get_texture_swizzle hacks here? */
929
930 isv->view = (struct isl_view) {
931 .format = iris_isl_format_for_pipe_format(tmpl->format),
932 .base_level = tmpl->u.tex.first_level,
933 .levels = tmpl->u.tex.last_level - tmpl->u.tex.first_level + 1,
934 .base_array_layer = tmpl->u.tex.first_layer,
935 .array_len = tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1,
936 .swizzle = (struct isl_swizzle) {
937 .r = pipe_swizzle_to_isl_channel(tmpl->swizzle_r),
938 .g = pipe_swizzle_to_isl_channel(tmpl->swizzle_g),
939 .b = pipe_swizzle_to_isl_channel(tmpl->swizzle_b),
940 .a = pipe_swizzle_to_isl_channel(tmpl->swizzle_a),
941 },
942 .usage = ISL_SURF_USAGE_TEXTURE_BIT,
943 };
944
945 void *map = NULL;
946 u_upload_alloc(ice->state.surface_uploader, 0,
947 4 * GENX(RENDER_SURFACE_STATE_length), 64,
948 &isv->surface_state_offset,
949 &isv->surface_state_resource,
950 &map);
951 if (!unlikely(map))
952 return NULL;
953
954 struct iris_bo *state_bo = iris_resource_bo(isv->surface_state_resource);
955 isv->surface_state_offset += iris_bo_offset_from_base_address(state_bo);
956
957 isl_surf_fill_state(&screen->isl_dev, map,
958 .surf = &itex->surf, .view = &isv->view,
959 .mocs = MOCS_WB,
960 .address = itex->bo->gtt_offset);
961 // .aux_surf =
962 // .clear_color = clear_color,
963
964 return &isv->pipe;
965 }
966
967 struct iris_surface {
968 struct pipe_surface pipe;
969 struct isl_view view;
970
971 /** The resource (BO) holding our SURFACE_STATE. */
972 struct pipe_resource *surface_state_resource;
973 unsigned surface_state_offset;
974
975 // uint32_t surface_state[GENX(RENDER_SURFACE_STATE_length)];
976 };
977
978 static struct pipe_surface *
979 iris_create_surface(struct pipe_context *ctx,
980 struct pipe_resource *tex,
981 const struct pipe_surface *tmpl)
982 {
983 struct iris_context *ice = (struct iris_context *) ctx;
984 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
985 struct iris_surface *surf = calloc(1, sizeof(struct iris_surface));
986 struct pipe_surface *psurf = &surf->pipe;
987 struct iris_resource *res = (struct iris_resource *) tex;
988
989 if (!surf)
990 return NULL;
991
992 pipe_reference_init(&psurf->reference, 1);
993 pipe_resource_reference(&psurf->texture, tex);
994 psurf->context = ctx;
995 psurf->format = tmpl->format;
996 psurf->width = tex->width0;
997 psurf->height = tex->height0;
998 psurf->texture = tex;
999 psurf->u.tex.first_layer = tmpl->u.tex.first_layer;
1000 psurf->u.tex.last_layer = tmpl->u.tex.last_layer;
1001 psurf->u.tex.level = tmpl->u.tex.level;
1002
1003 unsigned usage = 0;
1004 if (tmpl->writable)
1005 usage = ISL_SURF_USAGE_STORAGE_BIT;
1006 else if (util_format_is_depth_or_stencil(tmpl->format))
1007 usage = ISL_SURF_USAGE_DEPTH_BIT;
1008 else
1009 usage = ISL_SURF_USAGE_RENDER_TARGET_BIT;
1010
1011 surf->view = (struct isl_view) {
1012 .format = iris_isl_format_for_pipe_format(tmpl->format),
1013 .base_level = tmpl->u.tex.level,
1014 .levels = 1,
1015 .base_array_layer = tmpl->u.tex.first_layer,
1016 .array_len = tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1,
1017 .swizzle = ISL_SWIZZLE_IDENTITY,
1018 .usage = usage,
1019 };
1020
1021 /* Bail early for depth/stencil */
1022 if (res->surf.usage & (ISL_SURF_USAGE_DEPTH_BIT |
1023 ISL_SURF_USAGE_STENCIL_BIT))
1024 return psurf;
1025
1026 void *map = NULL;
1027 u_upload_alloc(ice->state.surface_uploader, 0,
1028 4 * GENX(RENDER_SURFACE_STATE_length), 64,
1029 &surf->surface_state_offset,
1030 &surf->surface_state_resource,
1031 &map);
1032 if (!unlikely(map))
1033 return NULL;
1034
1035 struct iris_bo *state_bo = iris_resource_bo(surf->surface_state_resource);
1036 surf->surface_state_offset += iris_bo_offset_from_base_address(state_bo);
1037
1038 isl_surf_fill_state(&screen->isl_dev, map,
1039 .surf = &res->surf, .view = &surf->view,
1040 .mocs = MOCS_WB,
1041 .address = res->bo->gtt_offset);
1042 // .aux_surf =
1043 // .clear_color = clear_color,
1044
1045 return psurf;
1046 }
1047
1048 static void
1049 iris_set_sampler_views(struct pipe_context *ctx,
1050 enum pipe_shader_type p_stage,
1051 unsigned start, unsigned count,
1052 struct pipe_sampler_view **views)
1053 {
1054 struct iris_context *ice = (struct iris_context *) ctx;
1055 gl_shader_stage stage = stage_from_pipe(p_stage);
1056
1057 unsigned i;
1058 for (i = 0; i < count; i++) {
1059 pipe_sampler_view_reference((struct pipe_sampler_view **)
1060 &ice->state.textures[stage][i], views[i]);
1061 }
1062 for (; i < ice->state.num_textures[stage]; i++) {
1063 pipe_sampler_view_reference((struct pipe_sampler_view **)
1064 &ice->state.textures[stage][i], NULL);
1065 }
1066
1067 ice->state.num_textures[stage] = count;
1068
1069 // XXX: ice->state.dirty |= (IRIS_DIRTY_BINDING_TABLE_VS << stage);
1070 }
1071
1072 static void
1073 iris_set_clip_state(struct pipe_context *ctx,
1074 const struct pipe_clip_state *state)
1075 {
1076 }
1077
1078 static void
1079 iris_set_polygon_stipple(struct pipe_context *ctx,
1080 const struct pipe_poly_stipple *state)
1081 {
1082 struct iris_context *ice = (struct iris_context *) ctx;
1083 memcpy(&ice->state.poly_stipple, state, sizeof(*state));
1084 ice->state.dirty |= IRIS_DIRTY_POLYGON_STIPPLE;
1085 }
1086
1087 static void
1088 iris_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
1089 {
1090 struct iris_context *ice = (struct iris_context *) ctx;
1091
1092 ice->state.sample_mask = sample_mask;
1093 ice->state.dirty |= IRIS_DIRTY_SAMPLE_MASK;
1094 }
1095
1096 static void
1097 iris_set_scissor_states(struct pipe_context *ctx,
1098 unsigned start_slot,
1099 unsigned num_scissors,
1100 const struct pipe_scissor_state *states)
1101 {
1102 struct iris_context *ice = (struct iris_context *) ctx;
1103
1104 ice->state.num_scissors = num_scissors;
1105
1106 for (unsigned i = 0; i < num_scissors; i++) {
1107 ice->state.scissors[start_slot + i] = states[i];
1108 }
1109
1110 ice->state.dirty |= IRIS_DIRTY_SCISSOR_RECT;
1111 }
1112
1113 static void
1114 iris_set_stencil_ref(struct pipe_context *ctx,
1115 const struct pipe_stencil_ref *state)
1116 {
1117 struct iris_context *ice = (struct iris_context *) ctx;
1118 memcpy(&ice->state.stencil_ref, state, sizeof(*state));
1119 ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
1120 }
1121
1122
1123 struct iris_viewport_state {
1124 uint32_t sf_cl_vp[GENX(SF_CLIP_VIEWPORT_length) * IRIS_MAX_VIEWPORTS];
1125 };
1126
1127 static float
1128 viewport_extent(const struct pipe_viewport_state *state, int axis, float sign)
1129 {
1130 return copysignf(state->scale[axis], sign) + state->translate[axis];
1131 }
1132
1133 #if 0
1134 static void
1135 calculate_guardband_size(uint32_t fb_width, uint32_t fb_height,
1136 float m00, float m11, float m30, float m31,
1137 float *xmin, float *xmax,
1138 float *ymin, float *ymax)
1139 {
1140 /* According to the "Vertex X,Y Clamping and Quantization" section of the
1141 * Strips and Fans documentation:
1142 *
1143 * "The vertex X and Y screen-space coordinates are also /clamped/ to the
1144 * fixed-point "guardband" range supported by the rasterization hardware"
1145 *
1146 * and
1147 *
1148 * "In almost all circumstances, if an object’s vertices are actually
1149 * modified by this clamping (i.e., had X or Y coordinates outside of
1150 * the guardband extent the rendered object will not match the intended
1151 * result. Therefore software should take steps to ensure that this does
1152 * not happen - e.g., by clipping objects such that they do not exceed
1153 * these limits after the Drawing Rectangle is applied."
1154 *
1155 * I believe the fundamental restriction is that the rasterizer (in
1156 * the SF/WM stages) have a limit on the number of pixels that can be
1157 * rasterized. We need to ensure any coordinates beyond the rasterizer
1158 * limit are handled by the clipper. So effectively that limit becomes
1159 * the clipper's guardband size.
1160 *
1161 * It goes on to say:
1162 *
1163 * "In addition, in order to be correctly rendered, objects must have a
1164 * screenspace bounding box not exceeding 8K in the X or Y direction.
1165 * This additional restriction must also be comprehended by software,
1166 * i.e., enforced by use of clipping."
1167 *
1168 * This makes no sense. Gen7+ hardware supports 16K render targets,
1169 * and you definitely need to be able to draw polygons that fill the
1170 * surface. Our assumption is that the rasterizer was limited to 8K
1171 * on Sandybridge, which only supports 8K surfaces, and it was actually
1172 * increased to 16K on Ivybridge and later.
1173 *
1174 * So, limit the guardband to 16K on Gen7+ and 8K on Sandybridge.
1175 */
1176 const float gb_size = GEN_GEN >= 7 ? 16384.0f : 8192.0f;
1177
1178 if (m00 != 0 && m11 != 0) {
1179 /* First, we compute the screen-space render area */
1180 const float ss_ra_xmin = MIN3( 0, m30 + m00, m30 - m00);
1181 const float ss_ra_xmax = MAX3( fb_width, m30 + m00, m30 - m00);
1182 const float ss_ra_ymin = MIN3( 0, m31 + m11, m31 - m11);
1183 const float ss_ra_ymax = MAX3(fb_height, m31 + m11, m31 - m11);
1184
1185 /* We want the guardband to be centered on that */
1186 const float ss_gb_xmin = (ss_ra_xmin + ss_ra_xmax) / 2 - gb_size;
1187 const float ss_gb_xmax = (ss_ra_xmin + ss_ra_xmax) / 2 + gb_size;
1188 const float ss_gb_ymin = (ss_ra_ymin + ss_ra_ymax) / 2 - gb_size;
1189 const float ss_gb_ymax = (ss_ra_ymin + ss_ra_ymax) / 2 + gb_size;
1190
1191 /* Now we need it in native device coordinates */
1192 const float ndc_gb_xmin = (ss_gb_xmin - m30) / m00;
1193 const float ndc_gb_xmax = (ss_gb_xmax - m30) / m00;
1194 const float ndc_gb_ymin = (ss_gb_ymin - m31) / m11;
1195 const float ndc_gb_ymax = (ss_gb_ymax - m31) / m11;
1196
1197 /* Thanks to Y-flipping and ORIGIN_UPPER_LEFT, the Y coordinates may be
1198 * flipped upside-down. X should be fine though.
1199 */
1200 assert(ndc_gb_xmin <= ndc_gb_xmax);
1201 *xmin = ndc_gb_xmin;
1202 *xmax = ndc_gb_xmax;
1203 *ymin = MIN2(ndc_gb_ymin, ndc_gb_ymax);
1204 *ymax = MAX2(ndc_gb_ymin, ndc_gb_ymax);
1205 } else {
1206 /* The viewport scales to 0, so nothing will be rendered. */
1207 *xmin = 0.0f;
1208 *xmax = 0.0f;
1209 *ymin = 0.0f;
1210 *ymax = 0.0f;
1211 }
1212 }
1213 #endif
1214
1215 static void
1216 iris_set_viewport_states(struct pipe_context *ctx,
1217 unsigned start_slot,
1218 unsigned num_viewports,
1219 const struct pipe_viewport_state *state)
1220 {
1221 struct iris_context *ice = (struct iris_context *) ctx;
1222 struct iris_viewport_state *cso =
1223 malloc(sizeof(struct iris_viewport_state));
1224 uint32_t *vp_map = &cso->sf_cl_vp[start_slot];
1225
1226 // XXX: sf_cl_vp is only big enough for one slot, we don't iterate right
1227 for (unsigned i = 0; i < num_viewports; i++) {
1228 iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
1229 vp.ViewportMatrixElementm00 = state[i].scale[0];
1230 vp.ViewportMatrixElementm11 = state[i].scale[1];
1231 vp.ViewportMatrixElementm22 = state[i].scale[2];
1232 vp.ViewportMatrixElementm30 = state[i].translate[0];
1233 vp.ViewportMatrixElementm31 = state[i].translate[1];
1234 vp.ViewportMatrixElementm32 = state[i].translate[2];
1235 /* XXX: in i965 this is computed based on the drawbuffer size,
1236 * but we don't have that here...
1237 */
1238 vp.XMinClipGuardband = -1.0;
1239 vp.XMaxClipGuardband = 1.0;
1240 vp.YMinClipGuardband = -1.0;
1241 vp.YMaxClipGuardband = 1.0;
1242 vp.XMinViewPort = viewport_extent(&state[i], 0, -1.0f);
1243 vp.XMaxViewPort = viewport_extent(&state[i], 0, 1.0f) - 1;
1244 vp.YMinViewPort = viewport_extent(&state[i], 1, -1.0f);
1245 vp.YMaxViewPort = viewport_extent(&state[i], 1, 1.0f) - 1;
1246 }
1247
1248 vp_map += GENX(SF_CLIP_VIEWPORT_length);
1249 }
1250
1251 ice->state.cso_vp = cso;
1252 ice->state.num_viewports = num_viewports;
1253 ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
1254 }
1255
1256 struct iris_depth_buffer_state
1257 {
1258 uint32_t packets[GENX(3DSTATE_DEPTH_BUFFER_length) +
1259 GENX(3DSTATE_STENCIL_BUFFER_length) +
1260 GENX(3DSTATE_HIER_DEPTH_BUFFER_length) +
1261 GENX(3DSTATE_CLEAR_PARAMS_length)];
1262 };
1263
1264 static void
1265 iris_set_framebuffer_state(struct pipe_context *ctx,
1266 const struct pipe_framebuffer_state *state)
1267 {
1268 struct iris_context *ice = (struct iris_context *) ctx;
1269 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1270 struct isl_device *isl_dev = &screen->isl_dev;
1271 struct pipe_framebuffer_state *cso = &ice->state.framebuffer;
1272
1273 if (cso->samples != state->samples) {
1274 ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
1275 }
1276
1277 if (cso->nr_cbufs != state->nr_cbufs) {
1278 ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
1279 }
1280
1281 util_copy_framebuffer_state(cso, state);
1282
1283 struct iris_depth_buffer_state *cso_z =
1284 malloc(sizeof(struct iris_depth_buffer_state));
1285
1286 struct isl_view view = {
1287 /* Some nice defaults */
1288 .base_level = 0,
1289 .levels = 1,
1290 .base_array_layer = 0,
1291 .array_len = 1,
1292 .swizzle = ISL_SWIZZLE_IDENTITY,
1293 };
1294
1295 struct isl_depth_stencil_hiz_emit_info info = {
1296 .view = &view,
1297 .mocs = MOCS_WB,
1298 };
1299
1300 struct iris_resource *zres =
1301 (void *) (cso->zsbuf ? cso->zsbuf->texture : NULL);
1302
1303 if (zres) {
1304 view.usage |= ISL_SURF_USAGE_DEPTH_BIT;
1305
1306 info.depth_surf = &zres->surf;
1307 info.depth_address = zres->bo->gtt_offset;
1308
1309 view.format = zres->surf.format;
1310
1311 view.base_level = cso->zsbuf->u.tex.level;
1312 view.base_array_layer = cso->zsbuf->u.tex.first_layer;
1313 view.array_len =
1314 cso->zsbuf->u.tex.last_layer - cso->zsbuf->u.tex.first_layer + 1;
1315
1316 info.hiz_usage = ISL_AUX_USAGE_NONE;
1317 }
1318
1319 #if 0
1320 if (stencil_mt) {
1321 view.usage |= ISL_SURF_USAGE_STENCIL_BIT;
1322 info.stencil_surf = &stencil_mt->surf;
1323
1324 if (!depth_mt) {
1325 view.base_level = stencil_irb->mt_level - stencil_irb->mt->first_level;
1326 view.base_array_layer = stencil_irb->mt_layer;
1327 view.array_len = MAX2(stencil_irb->layer_count, 1);
1328 view.format = stencil_mt->surf.format;
1329 }
1330
1331 uint32_t stencil_offset = 0;
1332 info.stencil_address = stencil_mt->bo->gtt_offset + stencil_mt->offset;
1333 }
1334 #endif
1335
1336 isl_emit_depth_stencil_hiz_s(isl_dev, cso_z->packets, &info);
1337
1338 ice->state.cso_depthbuffer = cso_z;
1339 ice->state.dirty |= IRIS_DIRTY_DEPTH_BUFFER;
1340 }
1341
1342 static void
1343 iris_set_constant_buffer(struct pipe_context *ctx,
1344 enum pipe_shader_type p_stage, unsigned index,
1345 const struct pipe_constant_buffer *input)
1346 {
1347 struct iris_context *ice = (struct iris_context *) ctx;
1348 struct iris_screen *screen = (struct iris_screen *)ctx->screen;
1349 gl_shader_stage stage = stage_from_pipe(p_stage);
1350 struct iris_shader_state *shs = &ice->shaders.state[stage];
1351 struct iris_const_buffer *cbuf = &shs->constbuf[index];
1352
1353 if (input && (input->buffer || input->user_buffer)) {
1354 if (input->user_buffer) {
1355 u_upload_data(ctx->const_uploader, 0, input->buffer_size, 32,
1356 input->user_buffer, &cbuf->offset, &cbuf->resource);
1357 } else {
1358 pipe_resource_reference(&cbuf->resource, input->buffer);
1359 }
1360
1361 void *map = NULL;
1362 // XXX: these are not retained forever, use a separate uploader?
1363 u_upload_alloc(ice->state.surface_uploader, 0,
1364 4 * GENX(RENDER_SURFACE_STATE_length), 64,
1365 &cbuf->surface_state_offset,
1366 &cbuf->surface_state_resource,
1367 &map);
1368 if (!unlikely(map)) {
1369 pipe_resource_reference(&cbuf->resource, NULL);
1370 return;
1371 }
1372
1373 struct iris_resource *res = (void *) cbuf->resource;
1374 struct iris_bo *surf_bo = iris_resource_bo(cbuf->surface_state_resource);
1375 cbuf->surface_state_offset += iris_bo_offset_from_base_address(surf_bo);
1376
1377 isl_buffer_fill_state(&screen->isl_dev, map,
1378 .address = res->bo->gtt_offset + cbuf->offset,
1379 .size_B = input->buffer_size,
1380 .format = ISL_FORMAT_R32G32B32A32_FLOAT,
1381 .stride_B = 1,
1382 .mocs = MOCS_WB)
1383 } else {
1384 pipe_resource_reference(&cbuf->resource, NULL);
1385 pipe_resource_reference(&cbuf->surface_state_resource, NULL);
1386 }
1387 }
1388
1389 static void
1390 iris_sampler_view_destroy(struct pipe_context *ctx,
1391 struct pipe_sampler_view *state)
1392 {
1393 struct iris_sampler_view *isv = (void *) state;
1394 pipe_resource_reference(&state->texture, NULL);
1395 pipe_resource_reference(&isv->surface_state_resource, NULL);
1396 free(isv);
1397 }
1398
1399
1400 static void
1401 iris_surface_destroy(struct pipe_context *ctx, struct pipe_surface *p_surf)
1402 {
1403 struct iris_surface *surf = (void *) p_surf;
1404 pipe_resource_reference(&p_surf->texture, NULL);
1405 pipe_resource_reference(&surf->surface_state_resource, NULL);
1406 free(surf);
1407 }
1408
1409 static void
1410 iris_delete_state(struct pipe_context *ctx, void *state)
1411 {
1412 free(state);
1413 }
1414
1415 struct iris_vertex_buffer_state {
1416 uint32_t vertex_buffers[1 + 33 * GENX(VERTEX_BUFFER_STATE_length)];
1417 struct iris_bo *bos[33];
1418 unsigned num_buffers;
1419 };
1420
1421 static void
1422 iris_free_vertex_buffers(struct iris_vertex_buffer_state *cso)
1423 {
1424 if (cso) {
1425 for (unsigned i = 0; i < cso->num_buffers; i++)
1426 iris_bo_unreference(cso->bos[i]);
1427 free(cso);
1428 }
1429 }
1430
1431 static void
1432 iris_set_vertex_buffers(struct pipe_context *ctx,
1433 unsigned start_slot, unsigned count,
1434 const struct pipe_vertex_buffer *buffers)
1435 {
1436 struct iris_context *ice = (struct iris_context *) ctx;
1437 struct iris_vertex_buffer_state *cso =
1438 malloc(sizeof(struct iris_vertex_buffer_state));
1439
1440 /* If there are no buffers, do nothing. We can leave the stale
1441 * 3DSTATE_VERTEX_BUFFERS in place - as long as there are no vertex
1442 * elements that point to them, it should be fine.
1443 */
1444 if (!buffers)
1445 return;
1446
1447 iris_free_vertex_buffers(ice->state.cso_vertex_buffers);
1448
1449 cso->num_buffers = count;
1450
1451 iris_pack_command(GENX(3DSTATE_VERTEX_BUFFERS), cso->vertex_buffers, vb) {
1452 vb.DWordLength = 4 * cso->num_buffers - 1;
1453 }
1454
1455 uint32_t *vb_pack_dest = &cso->vertex_buffers[1];
1456
1457 for (unsigned i = 0; i < count; i++) {
1458 assert(!buffers[i].is_user_buffer);
1459
1460 struct iris_resource *res = (void *) buffers[i].buffer.resource;
1461 iris_bo_reference(res->bo);
1462 cso->bos[i] = res->bo;
1463
1464 iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
1465 vb.VertexBufferIndex = start_slot + i;
1466 vb.MOCS = MOCS_WB;
1467 vb.AddressModifyEnable = true;
1468 vb.BufferPitch = buffers[i].stride;
1469 vb.BufferSize = res->bo->size;
1470 vb.BufferStartingAddress =
1471 ro_bo(NULL, res->bo->gtt_offset + buffers[i].buffer_offset);
1472 }
1473
1474 vb_pack_dest += GENX(VERTEX_BUFFER_STATE_length);
1475 }
1476
1477 ice->state.cso_vertex_buffers = cso;
1478 ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
1479 }
1480
1481 struct iris_vertex_element_state {
1482 uint32_t vertex_elements[1 + 33 * GENX(VERTEX_ELEMENT_STATE_length)];
1483 uint32_t vf_instancing[33 * GENX(3DSTATE_VF_INSTANCING_length)];
1484 unsigned count;
1485 };
1486
1487 static void *
1488 iris_create_vertex_elements(struct pipe_context *ctx,
1489 unsigned count,
1490 const struct pipe_vertex_element *state)
1491 {
1492 struct iris_vertex_element_state *cso =
1493 malloc(sizeof(struct iris_vertex_element_state));
1494
1495 cso->count = count;
1496
1497 /* TODO:
1498 * - create edge flag one
1499 * - create SGV ones
1500 * - if those are necessary, use count + 1/2/3... OR in the length
1501 */
1502 iris_pack_command(GENX(3DSTATE_VERTEX_ELEMENTS), cso->vertex_elements, ve) {
1503 ve.DWordLength =
1504 1 + GENX(VERTEX_ELEMENT_STATE_length) * MAX2(count, 1) - 2;
1505 }
1506
1507 uint32_t *ve_pack_dest = &cso->vertex_elements[1];
1508 uint32_t *vfi_pack_dest = cso->vf_instancing;
1509
1510 for (int i = 0; i < count; i++) {
1511 enum isl_format isl_format =
1512 iris_isl_format_for_pipe_format(state[i].src_format);
1513 unsigned comp[4] = { VFCOMP_STORE_SRC, VFCOMP_STORE_SRC,
1514 VFCOMP_STORE_SRC, VFCOMP_STORE_SRC };
1515
1516 switch (isl_format_get_num_channels(isl_format)) {
1517 case 0: comp[0] = VFCOMP_STORE_0;
1518 case 1: comp[1] = VFCOMP_STORE_0;
1519 case 2: comp[2] = VFCOMP_STORE_0;
1520 case 3:
1521 comp[3] = isl_format_has_int_channel(isl_format) ? VFCOMP_STORE_1_INT
1522 : VFCOMP_STORE_1_FP;
1523 break;
1524 }
1525 iris_pack_state(GENX(VERTEX_ELEMENT_STATE), ve_pack_dest, ve) {
1526 ve.VertexBufferIndex = state[i].vertex_buffer_index;
1527 ve.Valid = true;
1528 ve.SourceElementOffset = state[i].src_offset;
1529 ve.SourceElementFormat = isl_format;
1530 ve.Component0Control = comp[0];
1531 ve.Component1Control = comp[1];
1532 ve.Component2Control = comp[2];
1533 ve.Component3Control = comp[3];
1534 }
1535
1536 iris_pack_command(GENX(3DSTATE_VF_INSTANCING), vfi_pack_dest, vi) {
1537 vi.VertexElementIndex = i;
1538 vi.InstancingEnable = state[i].instance_divisor > 0;
1539 vi.InstanceDataStepRate = state[i].instance_divisor;
1540 }
1541
1542 ve_pack_dest += GENX(VERTEX_ELEMENT_STATE_length);
1543 vfi_pack_dest += GENX(3DSTATE_VF_INSTANCING_length);
1544 }
1545
1546 return cso;
1547 }
1548
1549 static void
1550 iris_bind_vertex_elements_state(struct pipe_context *ctx, void *state)
1551 {
1552 struct iris_context *ice = (struct iris_context *) ctx;
1553
1554 ice->state.cso_vertex_elements = state;
1555 ice->state.dirty |= IRIS_DIRTY_VERTEX_ELEMENTS;
1556 }
1557
1558 static void *
1559 iris_create_compute_state(struct pipe_context *ctx,
1560 const struct pipe_compute_state *state)
1561 {
1562 return malloc(1);
1563 }
1564
1565 static struct pipe_stream_output_target *
1566 iris_create_stream_output_target(struct pipe_context *ctx,
1567 struct pipe_resource *res,
1568 unsigned buffer_offset,
1569 unsigned buffer_size)
1570 {
1571 struct pipe_stream_output_target *t =
1572 CALLOC_STRUCT(pipe_stream_output_target);
1573 if (!t)
1574 return NULL;
1575
1576 pipe_reference_init(&t->reference, 1);
1577 pipe_resource_reference(&t->buffer, res);
1578 t->buffer_offset = buffer_offset;
1579 t->buffer_size = buffer_size;
1580 return t;
1581 }
1582
1583 static void
1584 iris_stream_output_target_destroy(struct pipe_context *ctx,
1585 struct pipe_stream_output_target *t)
1586 {
1587 pipe_resource_reference(&t->buffer, NULL);
1588 free(t);
1589 }
1590
1591 static void
1592 iris_set_stream_output_targets(struct pipe_context *ctx,
1593 unsigned num_targets,
1594 struct pipe_stream_output_target **targets,
1595 const unsigned *offsets)
1596 {
1597 }
1598
1599 static void
1600 iris_compute_sbe_urb_read_interval(uint64_t fs_input_slots,
1601 const struct brw_vue_map *last_vue_map,
1602 bool two_sided_color,
1603 unsigned *out_offset,
1604 unsigned *out_length)
1605 {
1606 /* The compiler computes the first URB slot without considering COL/BFC
1607 * swizzling (because it doesn't know whether it's enabled), so we need
1608 * to do that here too. This may result in a smaller offset, which
1609 * should be safe.
1610 */
1611 const unsigned first_slot =
1612 brw_compute_first_urb_slot_required(fs_input_slots, last_vue_map);
1613
1614 /* This becomes the URB read offset (counted in pairs of slots). */
1615 assert(first_slot % 2 == 0);
1616 *out_offset = first_slot / 2;
1617
1618 /* We need to adjust the inputs read to account for front/back color
1619 * swizzling, as it can make the URB length longer.
1620 */
1621 for (int c = 0; c <= 1; c++) {
1622 if (fs_input_slots & (VARYING_BIT_COL0 << c)) {
1623 /* If two sided color is enabled, the fragment shader's gl_Color
1624 * (COL0) input comes from either the gl_FrontColor (COL0) or
1625 * gl_BackColor (BFC0) input varyings. Mark BFC as used, too.
1626 */
1627 if (two_sided_color)
1628 fs_input_slots |= (VARYING_BIT_BFC0 << c);
1629
1630 /* If front color isn't written, we opt to give them back color
1631 * instead of an undefined value. Switch from COL to BFC.
1632 */
1633 if (last_vue_map->varying_to_slot[VARYING_SLOT_COL0 + c] == -1) {
1634 fs_input_slots &= ~(VARYING_BIT_COL0 << c);
1635 fs_input_slots |= (VARYING_BIT_BFC0 << c);
1636 }
1637 }
1638 }
1639
1640 /* Compute the minimum URB Read Length necessary for the FS inputs.
1641 *
1642 * From the Sandy Bridge PRM, Volume 2, Part 1, documentation for
1643 * 3DSTATE_SF DWord 1 bits 15:11, "Vertex URB Entry Read Length":
1644 *
1645 * "This field should be set to the minimum length required to read the
1646 * maximum source attribute. The maximum source attribute is indicated
1647 * by the maximum value of the enabled Attribute # Source Attribute if
1648 * Attribute Swizzle Enable is set, Number of Output Attributes-1 if
1649 * enable is not set.
1650 * read_length = ceiling((max_source_attr + 1) / 2)
1651 *
1652 * [errata] Corruption/Hang possible if length programmed larger than
1653 * recommended"
1654 *
1655 * Similar text exists for Ivy Bridge.
1656 *
1657 * We find the last URB slot that's actually read by the FS.
1658 */
1659 unsigned last_read_slot = last_vue_map->num_slots - 1;
1660 while (last_read_slot > first_slot && !(fs_input_slots &
1661 (1ull << last_vue_map->slot_to_varying[last_read_slot])))
1662 --last_read_slot;
1663
1664 /* The URB read length is the difference of the two, counted in pairs. */
1665 *out_length = DIV_ROUND_UP(last_read_slot - first_slot + 1, 2);
1666 }
1667
1668 static void
1669 iris_emit_sbe(struct iris_batch *batch, const struct iris_context *ice)
1670 {
1671 const struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
1672 const struct brw_wm_prog_data *wm_prog_data = (void *)
1673 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
1674 struct pipe_shader_state *p_fs =
1675 (void *) ice->shaders.uncompiled[MESA_SHADER_FRAGMENT];
1676 assert(p_fs->type == PIPE_SHADER_IR_NIR);
1677 nir_shader *fs_nir = p_fs->ir.nir;
1678
1679 unsigned urb_read_offset, urb_read_length;
1680 iris_compute_sbe_urb_read_interval(fs_nir->info.inputs_read,
1681 ice->shaders.last_vue_map,
1682 cso_rast->light_twoside,
1683 &urb_read_offset, &urb_read_length);
1684
1685 iris_emit_cmd(batch, GENX(3DSTATE_SBE), sbe) {
1686 sbe.AttributeSwizzleEnable = true;
1687 sbe.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
1688 sbe.PointSpriteTextureCoordinateOrigin = cso_rast->sprite_coord_mode;
1689 sbe.VertexURBEntryReadOffset = urb_read_offset;
1690 sbe.VertexURBEntryReadLength = urb_read_length;
1691 sbe.ForceVertexURBEntryReadOffset = true;
1692 sbe.ForceVertexURBEntryReadLength = true;
1693 sbe.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
1694
1695 for (int i = 0; i < 32; i++) {
1696 sbe.AttributeActiveComponentFormat[i] = ACTIVE_COMPONENT_XYZW;
1697 }
1698 }
1699 }
1700
1701 static void
1702 iris_bind_compute_state(struct pipe_context *ctx, void *state)
1703 {
1704 }
1705
1706 static void
1707 iris_populate_sampler_key(const struct iris_context *ice,
1708 struct brw_sampler_prog_key_data *key)
1709 {
1710 for (int i = 0; i < MAX_SAMPLERS; i++) {
1711 key->swizzles[i] = 0x688; /* XYZW */
1712 }
1713 }
1714
1715 static void
1716 iris_populate_vs_key(const struct iris_context *ice,
1717 struct brw_vs_prog_key *key)
1718 {
1719 memset(key, 0, sizeof(*key));
1720 iris_populate_sampler_key(ice, &key->tex);
1721 }
1722
1723 static void
1724 iris_populate_tcs_key(const struct iris_context *ice,
1725 struct brw_tcs_prog_key *key)
1726 {
1727 memset(key, 0, sizeof(*key));
1728 iris_populate_sampler_key(ice, &key->tex);
1729 }
1730
1731 static void
1732 iris_populate_tes_key(const struct iris_context *ice,
1733 struct brw_tes_prog_key *key)
1734 {
1735 memset(key, 0, sizeof(*key));
1736 iris_populate_sampler_key(ice, &key->tex);
1737 }
1738
1739 static void
1740 iris_populate_gs_key(const struct iris_context *ice,
1741 struct brw_gs_prog_key *key)
1742 {
1743 memset(key, 0, sizeof(*key));
1744 iris_populate_sampler_key(ice, &key->tex);
1745 }
1746
1747 static void
1748 iris_populate_fs_key(const struct iris_context *ice,
1749 struct brw_wm_prog_key *key)
1750 {
1751 memset(key, 0, sizeof(*key));
1752 iris_populate_sampler_key(ice, &key->tex);
1753
1754 /* XXX: dirty flags? */
1755 const struct pipe_framebuffer_state *fb = &ice->state.framebuffer;
1756 const struct iris_depth_stencil_alpha_state *zsa = ice->state.cso_zsa;
1757 const struct iris_rasterizer_state *rast = ice->state.cso_rast;
1758 const struct iris_blend_state *blend = ice->state.cso_blend;
1759
1760 key->nr_color_regions = fb->nr_cbufs;
1761
1762 key->clamp_fragment_color = rast->clamp_fragment_color;
1763
1764 key->replicate_alpha = fb->nr_cbufs > 1 &&
1765 (zsa->alpha.enabled || blend->alpha_to_coverage);
1766
1767 // key->force_dual_color_blend for unigine
1768 #if 0
1769 if (cso_rast->multisample) {
1770 key->persample_interp =
1771 ctx->Multisample.SampleShading &&
1772 (ctx->Multisample.MinSampleShadingValue *
1773 _mesa_geometric_samples(ctx->DrawBuffer) > 1);
1774
1775 key->multisample_fbo = fb->samples > 1;
1776 }
1777 #endif
1778
1779 key->coherent_fb_fetch = true;
1780 }
1781
1782 //pkt.SamplerCount = \
1783 //DIV_ROUND_UP(CLAMP(stage_state->sampler_count, 0, 16), 4); \
1784 //pkt.PerThreadScratchSpace = prog_data->total_scratch == 0 ? 0 : \
1785 //ffs(stage_state->per_thread_scratch) - 11; \
1786
1787 static uint64_t
1788 KSP(const struct iris_compiled_shader *shader)
1789 {
1790 struct iris_resource *res = (void *) shader->buffer;
1791 return res->bo->gtt_offset + shader->offset;
1792 }
1793
1794 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix) \
1795 pkt.KernelStartPointer = KSP(shader); \
1796 pkt.BindingTableEntryCount = prog_data->binding_table.size_bytes / 4; \
1797 pkt.FloatingPointMode = prog_data->use_alt_mode; \
1798 \
1799 pkt.DispatchGRFStartRegisterForURBData = \
1800 prog_data->dispatch_grf_start_reg; \
1801 pkt.prefix##URBEntryReadLength = vue_prog_data->urb_read_length; \
1802 pkt.prefix##URBEntryReadOffset = 0; \
1803 \
1804 pkt.StatisticsEnable = true; \
1805 pkt.Enable = true;
1806
1807 static void
1808 iris_set_vs_state(const struct gen_device_info *devinfo,
1809 struct iris_compiled_shader *shader)
1810 {
1811 struct brw_stage_prog_data *prog_data = shader->prog_data;
1812 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
1813
1814 iris_pack_command(GENX(3DSTATE_VS), shader->derived_data, vs) {
1815 INIT_THREAD_DISPATCH_FIELDS(vs, Vertex);
1816 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1817 vs.SIMD8DispatchEnable = true;
1818 vs.UserClipDistanceCullTestEnableBitmask =
1819 vue_prog_data->cull_distance_mask;
1820 }
1821 }
1822
1823 static void
1824 iris_set_tcs_state(const struct gen_device_info *devinfo,
1825 struct iris_compiled_shader *shader)
1826 {
1827 struct brw_stage_prog_data *prog_data = shader->prog_data;
1828 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
1829 struct brw_tcs_prog_data *tcs_prog_data = (void *) prog_data;
1830
1831 iris_pack_command(GENX(3DSTATE_HS), shader->derived_data, hs) {
1832 INIT_THREAD_DISPATCH_FIELDS(hs, Vertex);
1833
1834 hs.InstanceCount = tcs_prog_data->instances - 1;
1835 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
1836 hs.IncludeVertexHandles = true;
1837 }
1838 }
1839
1840 static void
1841 iris_set_tes_state(const struct gen_device_info *devinfo,
1842 struct iris_compiled_shader *shader)
1843 {
1844 struct brw_stage_prog_data *prog_data = shader->prog_data;
1845 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
1846 struct brw_tes_prog_data *tes_prog_data = (void *) prog_data;
1847
1848 uint32_t *te_state = (void *) shader->derived_data;
1849 uint32_t *ds_state = te_state + GENX(3DSTATE_TE_length);
1850
1851 iris_pack_command(GENX(3DSTATE_TE), te_state, te) {
1852 te.Partitioning = tes_prog_data->partitioning;
1853 te.OutputTopology = tes_prog_data->output_topology;
1854 te.TEDomain = tes_prog_data->domain;
1855 te.TEEnable = true;
1856 te.MaximumTessellationFactorOdd = 63.0;
1857 te.MaximumTessellationFactorNotOdd = 64.0;
1858 }
1859
1860 iris_pack_command(GENX(3DSTATE_DS), ds_state, ds) {
1861 INIT_THREAD_DISPATCH_FIELDS(ds, Patch);
1862
1863 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
1864 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
1865 ds.ComputeWCoordinateEnable =
1866 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
1867
1868 ds.UserClipDistanceCullTestEnableBitmask =
1869 vue_prog_data->cull_distance_mask;
1870 }
1871
1872 }
1873
1874 static void
1875 iris_set_gs_state(const struct gen_device_info *devinfo,
1876 struct iris_compiled_shader *shader)
1877 {
1878 struct brw_stage_prog_data *prog_data = shader->prog_data;
1879 struct brw_vue_prog_data *vue_prog_data = (void *) prog_data;
1880 struct brw_gs_prog_data *gs_prog_data = (void *) prog_data;
1881
1882 iris_pack_command(GENX(3DSTATE_GS), shader->derived_data, gs) {
1883 INIT_THREAD_DISPATCH_FIELDS(gs, Vertex);
1884
1885 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1886 gs.OutputTopology = gs_prog_data->output_topology;
1887 gs.ControlDataHeaderSize =
1888 gs_prog_data->control_data_header_size_hwords;
1889 gs.InstanceControl = gs_prog_data->invocations - 1;
1890 gs.DispatchMode = SIMD8;
1891 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
1892 gs.ControlDataFormat = gs_prog_data->control_data_format;
1893 gs.ReorderMode = TRAILING;
1894 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1895 gs.MaximumNumberofThreads =
1896 GEN_GEN == 8 ? (devinfo->max_gs_threads / 2 - 1)
1897 : (devinfo->max_gs_threads - 1);
1898
1899 if (gs_prog_data->static_vertex_count != -1) {
1900 gs.StaticOutput = true;
1901 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count;
1902 }
1903 gs.IncludeVertexHandles = vue_prog_data->include_vue_handles;
1904
1905 gs.UserClipDistanceCullTestEnableBitmask =
1906 vue_prog_data->cull_distance_mask;
1907
1908 const int urb_entry_write_offset = 1;
1909 const uint32_t urb_entry_output_length =
1910 DIV_ROUND_UP(vue_prog_data->vue_map.num_slots, 2) -
1911 urb_entry_write_offset;
1912
1913 gs.VertexURBEntryOutputReadOffset = urb_entry_write_offset;
1914 gs.VertexURBEntryOutputLength = MAX2(urb_entry_output_length, 1);
1915 }
1916 }
1917
1918 static void
1919 iris_set_fs_state(const struct gen_device_info *devinfo,
1920 struct iris_compiled_shader *shader)
1921 {
1922 struct brw_stage_prog_data *prog_data = shader->prog_data;
1923 struct brw_wm_prog_data *wm_prog_data = (void *) shader->prog_data;
1924
1925 uint32_t *ps_state = (void *) shader->derived_data;
1926 uint32_t *psx_state = ps_state + GENX(3DSTATE_PS_length);
1927
1928 iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
1929 ps.VectorMaskEnable = true;
1930 //ps.SamplerCount = ...
1931 ps.BindingTableEntryCount = prog_data->binding_table.size_bytes / 4;
1932 ps.FloatingPointMode = prog_data->use_alt_mode;
1933 ps.MaximumNumberofThreadsPerPSD = 64 - (GEN_GEN == 8 ? 2 : 1);
1934
1935 ps.PushConstantEnable = prog_data->nr_params > 0 ||
1936 prog_data->ubo_ranges[0].length > 0;
1937
1938 /* From the documentation for this packet:
1939 * "If the PS kernel does not need the Position XY Offsets to
1940 * compute a Position Value, then this field should be programmed
1941 * to POSOFFSET_NONE."
1942 *
1943 * "SW Recommendation: If the PS kernel needs the Position Offsets
1944 * to compute a Position XY value, this field should match Position
1945 * ZW Interpolation Mode to ensure a consistent position.xyzw
1946 * computation."
1947 *
1948 * We only require XY sample offsets. So, this recommendation doesn't
1949 * look useful at the moment. We might need this in future.
1950 */
1951 ps.PositionXYOffsetSelect =
1952 wm_prog_data->uses_pos_offset ? POSOFFSET_SAMPLE : POSOFFSET_NONE;
1953 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1954 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1955 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
1956
1957 // XXX: Disable SIMD32 with 16x MSAA
1958
1959 ps.DispatchGRFStartRegisterForConstantSetupData0 =
1960 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
1961 ps.DispatchGRFStartRegisterForConstantSetupData1 =
1962 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
1963 ps.DispatchGRFStartRegisterForConstantSetupData2 =
1964 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
1965
1966 ps.KernelStartPointer0 =
1967 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
1968 ps.KernelStartPointer1 =
1969 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
1970 ps.KernelStartPointer2 =
1971 KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
1972 }
1973
1974 iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
1975 psx.PixelShaderValid = true;
1976 psx.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1977 psx.PixelShaderKillsPixel = wm_prog_data->uses_kill;
1978 psx.AttributeEnable = wm_prog_data->num_varying_inputs != 0;
1979 psx.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1980 psx.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1981 psx.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
1982
1983 if (wm_prog_data->uses_sample_mask) {
1984 /* TODO: conservative rasterization */
1985 if (wm_prog_data->post_depth_coverage)
1986 psx.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
1987 else
1988 psx.InputCoverageMaskState = ICMS_NORMAL;
1989 }
1990
1991 psx.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1992 psx.PixelShaderPullsBary = wm_prog_data->pulls_bary;
1993 psx.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
1994
1995 // XXX: UAV bit
1996 }
1997 }
1998
1999 static unsigned
2000 iris_derived_program_state_size(enum iris_program_cache_id cache_id)
2001 {
2002 assert(cache_id <= IRIS_CACHE_BLORP);
2003
2004 static const unsigned dwords[] = {
2005 [IRIS_CACHE_VS] = GENX(3DSTATE_VS_length),
2006 [IRIS_CACHE_TCS] = GENX(3DSTATE_HS_length),
2007 [IRIS_CACHE_TES] = GENX(3DSTATE_TE_length) + GENX(3DSTATE_DS_length),
2008 [IRIS_CACHE_GS] = GENX(3DSTATE_GS_length),
2009 [IRIS_CACHE_FS] =
2010 GENX(3DSTATE_PS_length) + GENX(3DSTATE_PS_EXTRA_length),
2011 [IRIS_CACHE_CS] = 0,
2012 [IRIS_CACHE_BLORP] = 0,
2013 };
2014
2015 return sizeof(uint32_t) * dwords[cache_id];
2016 }
2017
2018 static void
2019 iris_set_derived_program_state(const struct gen_device_info *devinfo,
2020 enum iris_program_cache_id cache_id,
2021 struct iris_compiled_shader *shader)
2022 {
2023 switch (cache_id) {
2024 case IRIS_CACHE_VS:
2025 iris_set_vs_state(devinfo, shader);
2026 break;
2027 case IRIS_CACHE_TCS:
2028 iris_set_tcs_state(devinfo, shader);
2029 break;
2030 case IRIS_CACHE_TES:
2031 iris_set_tes_state(devinfo, shader);
2032 break;
2033 case IRIS_CACHE_GS:
2034 iris_set_gs_state(devinfo, shader);
2035 break;
2036 case IRIS_CACHE_FS:
2037 iris_set_fs_state(devinfo, shader);
2038 break;
2039 case IRIS_CACHE_CS:
2040 case IRIS_CACHE_BLORP:
2041 break;
2042 default:
2043 break;
2044 }
2045 }
2046
2047 static void
2048 iris_upload_urb_config(struct iris_context *ice, struct iris_batch *batch)
2049 {
2050 const struct gen_device_info *devinfo = &batch->screen->devinfo;
2051 const unsigned push_size_kB = 32;
2052 unsigned entries[4];
2053 unsigned start[4];
2054 unsigned size[4];
2055
2056 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
2057 if (!ice->shaders.prog[i]) {
2058 size[i] = 1;
2059 } else {
2060 struct brw_vue_prog_data *vue_prog_data =
2061 (void *) ice->shaders.prog[i]->prog_data;
2062 size[i] = vue_prog_data->urb_entry_size;
2063 }
2064 assert(size[i] != 0);
2065 }
2066
2067 gen_get_urb_config(devinfo, 1024 * push_size_kB,
2068 1024 * ice->shaders.urb_size,
2069 ice->shaders.prog[MESA_SHADER_TESS_EVAL] != NULL,
2070 ice->shaders.prog[MESA_SHADER_GEOMETRY] != NULL,
2071 size, entries, start);
2072
2073 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
2074 iris_emit_cmd(batch, GENX(3DSTATE_URB_VS), urb) {
2075 urb._3DCommandSubOpcode += i;
2076 urb.VSURBStartingAddress = start[i];
2077 urb.VSURBEntryAllocationSize = size[i] - 1;
2078 urb.VSNumberofURBEntries = entries[i];
2079 }
2080 }
2081 }
2082
2083 static const uint32_t push_constant_opcodes[] = {
2084 [MESA_SHADER_VERTEX] = 21,
2085 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2086 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2087 [MESA_SHADER_GEOMETRY] = 22,
2088 [MESA_SHADER_FRAGMENT] = 23,
2089 [MESA_SHADER_COMPUTE] = 0,
2090 };
2091
2092 /**
2093 * Add a surface to the validation list, as well as the buffer containing
2094 * the corresponding SURFACE_STATE.
2095 *
2096 * Returns the binding table entry (offset to SURFACE_STATE).
2097 */
2098 static uint32_t
2099 use_surface(struct iris_batch *batch,
2100 struct pipe_surface *p_surf,
2101 bool writeable)
2102 {
2103 struct iris_surface *surf = (void *) p_surf;
2104 struct iris_resource *res = (void *) p_surf->texture;
2105 struct iris_resource *state_res = (void *) surf->surface_state_resource;
2106 iris_use_pinned_bo(batch, res->bo, writeable);
2107 iris_use_pinned_bo(batch, state_res->bo, false);
2108
2109 return surf->surface_state_offset;
2110 }
2111
2112 static uint32_t
2113 use_sampler_view(struct iris_batch *batch, struct iris_sampler_view *isv)
2114 {
2115 struct iris_resource *res = (void *) isv->pipe.texture;
2116 struct iris_resource *state_res = (void *) isv->surface_state_resource;
2117 iris_use_pinned_bo(batch, res->bo, false);
2118 iris_use_pinned_bo(batch, state_res->bo, false);
2119
2120 return isv->surface_state_offset;
2121 }
2122
2123 static uint32_t
2124 use_const_buffer(struct iris_batch *batch, struct iris_const_buffer *cbuf)
2125 {
2126 struct iris_resource *res = (void *) cbuf->resource;
2127 struct iris_resource *state_res = (void *) cbuf->surface_state_resource;
2128 iris_use_pinned_bo(batch, res->bo, false);
2129 iris_use_pinned_bo(batch, state_res->bo, false);
2130
2131 return cbuf->surface_state_offset;
2132 }
2133
2134 static void
2135 iris_populate_binding_table(struct iris_context *ice,
2136 struct iris_batch *batch,
2137 gl_shader_stage stage)
2138 {
2139 const struct iris_binder *binder = &batch->binder;
2140 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
2141 if (!shader)
2142 return;
2143
2144 // Surfaces:
2145 // - pull constants
2146 // - ubos/ssbos/abos
2147 // - images
2148 // - textures
2149 // - render targets - write and read
2150
2151 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
2152 uint32_t *bt_map = binder->map + binder->bt_offset[stage];
2153 int s = 0;
2154
2155 if (stage == MESA_SHADER_FRAGMENT) {
2156 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
2157 for (unsigned i = 0; i < cso_fb->nr_cbufs; i++) {
2158 bt_map[s++] = use_surface(batch, cso_fb->cbufs[i], true);
2159 }
2160 }
2161
2162 //assert(prog_data->binding_table.texture_start ==
2163 //(ice->state.num_textures[stage] ? s : 0xd0d0d0d0));
2164
2165 for (int i = 0; i < ice->state.num_textures[stage]; i++) {
2166 struct iris_sampler_view *view = ice->state.textures[stage][i];
2167 bt_map[s++] = use_sampler_view(batch, view);
2168 }
2169
2170 // XXX: want the number of BTE's to shorten this loop
2171 struct iris_shader_state *shs = &ice->shaders.state[stage];
2172 for (int i = 0; i < PIPE_MAX_CONSTANT_BUFFERS; i++) {
2173 struct iris_const_buffer *cbuf = &shs->constbuf[i];
2174 if (!cbuf->surface_state_resource)
2175 break;
2176
2177 bt_map[s++] = use_const_buffer(batch, cbuf);
2178 }
2179 #if 0
2180 // XXX: not implemented yet
2181 assert(prog_data->binding_table.pull_constants_start == 0xd0d0d0d0);
2182 assert(prog_data->binding_table.ubo_start == 0xd0d0d0d0);
2183 assert(prog_data->binding_table.ssbo_start == 0xd0d0d0d0);
2184 assert(prog_data->binding_table.image_start == 0xd0d0d0d0);
2185 assert(prog_data->binding_table.shader_time_start == 0xd0d0d0d0);
2186 //assert(prog_data->binding_table.plane_start[1] == 0xd0d0d0d0);
2187 //assert(prog_data->binding_table.plane_start[2] == 0xd0d0d0d0);
2188 #endif
2189 }
2190
2191 static void
2192 iris_upload_render_state(struct iris_context *ice,
2193 struct iris_batch *batch,
2194 const struct pipe_draw_info *draw)
2195 {
2196 const uint64_t dirty =
2197 unlikely(INTEL_DEBUG & DEBUG_REEMIT) ? ~0ull : ice->state.dirty;
2198
2199 struct brw_wm_prog_data *wm_prog_data = (void *)
2200 ice->shaders.prog[MESA_SHADER_FRAGMENT]->prog_data;
2201
2202 if (dirty & IRIS_DIRTY_CC_VIEWPORT) {
2203 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
2204 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_CC), ptr) {
2205 ptr.CCViewportPointer =
2206 emit_state(batch, ice->state.dynamic_uploader,
2207 cso->cc_vp, sizeof(cso->cc_vp), 32);
2208 }
2209 }
2210
2211 if (dirty & IRIS_DIRTY_SF_CL_VIEWPORT) {
2212 struct iris_viewport_state *cso = ice->state.cso_vp;
2213 iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
2214 ptr.SFClipViewportPointer =
2215 emit_state(batch, ice->state.dynamic_uploader, cso->sf_cl_vp,
2216 4 * GENX(SF_CLIP_VIEWPORT_length) *
2217 ice->state.num_viewports, 64);
2218 }
2219 }
2220
2221 /* XXX: L3 State */
2222
2223 if (dirty & IRIS_DIRTY_URB) {
2224 iris_upload_urb_config(ice, batch);
2225 }
2226
2227 if (dirty & IRIS_DIRTY_BLEND_STATE) {
2228 struct iris_blend_state *cso_blend = ice->state.cso_blend;
2229 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
2230 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
2231 const int num_dwords = 4 * (GENX(BLEND_STATE_length) +
2232 cso_fb->nr_cbufs * GENX(BLEND_STATE_ENTRY_length));
2233 uint32_t blend_offset;
2234 uint32_t *blend_map =
2235 stream_state(batch, ice->state.dynamic_uploader, 4 * num_dwords, 64,
2236 &blend_offset);
2237
2238 uint32_t blend_state_header;
2239 iris_pack_state(GENX(BLEND_STATE), &blend_state_header, bs) {
2240 bs.AlphaTestEnable = cso_zsa->alpha.enabled;
2241 bs.AlphaTestFunction = translate_compare_func(cso_zsa->alpha.func);
2242 }
2243
2244 blend_map[0] = blend_state_header | cso_blend->blend_state[0];
2245 memcpy(&blend_map[1], &cso_blend->blend_state[1],
2246 sizeof(cso_blend->blend_state) - sizeof(uint32_t));
2247
2248 iris_emit_cmd(batch, GENX(3DSTATE_BLEND_STATE_POINTERS), ptr) {
2249 ptr.BlendStatePointer = blend_offset;
2250 ptr.BlendStatePointerValid = true;
2251 }
2252 }
2253
2254 if (dirty & IRIS_DIRTY_COLOR_CALC_STATE) {
2255 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
2256 uint32_t cc_offset;
2257 void *cc_map =
2258 stream_state(batch, ice->state.dynamic_uploader,
2259 sizeof(uint32_t) * GENX(COLOR_CALC_STATE_length),
2260 64, &cc_offset);
2261 iris_pack_state(GENX(COLOR_CALC_STATE), cc_map, cc) {
2262 cc.AlphaTestFormat = ALPHATEST_FLOAT32;
2263 cc.AlphaReferenceValueAsFLOAT32 = cso->alpha.ref_value;
2264 cc.BlendConstantColorRed = ice->state.blend_color.color[0];
2265 cc.BlendConstantColorGreen = ice->state.blend_color.color[1];
2266 cc.BlendConstantColorBlue = ice->state.blend_color.color[2];
2267 cc.BlendConstantColorAlpha = ice->state.blend_color.color[3];
2268 }
2269 iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
2270 ptr.ColorCalcStatePointer = cc_offset;
2271 ptr.ColorCalcStatePointerValid = true;
2272 }
2273 }
2274
2275 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
2276 // XXX: wrong dirty tracking...
2277 if (!(dirty & (IRIS_DIRTY_CONSTANTS_VS << stage)))
2278 continue;
2279
2280 struct iris_shader_state *shs = &ice->shaders.state[stage];
2281 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
2282
2283 if (!shader)
2284 continue;
2285
2286 struct brw_stage_prog_data *prog_data = (void *) shader->prog_data;
2287
2288 iris_emit_cmd(batch, GENX(3DSTATE_CONSTANT_VS), pkt) {
2289 pkt._3DCommandSubOpcode = push_constant_opcodes[stage];
2290 if (prog_data) {
2291 /* The Skylake PRM contains the following restriction:
2292 *
2293 * "The driver must ensure The following case does not occur
2294 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
2295 * buffer 3 read length equal to zero committed followed by a
2296 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
2297 * zero committed."
2298 *
2299 * To avoid this, we program the buffers in the highest slots.
2300 * This way, slot 0 is only used if slot 3 is also used.
2301 */
2302 int n = 3;
2303
2304 for (int i = 3; i >= 0; i--) {
2305 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2306
2307 if (range->length == 0)
2308 continue;
2309
2310 // XXX: is range->block a constbuf index? it would be nice
2311 struct iris_const_buffer *cbuf = &shs->constbuf[range->block];
2312 struct iris_resource *res = (void *) cbuf->resource;
2313
2314 assert(cbuf->offset % 32 == 0);
2315
2316 pkt.ConstantBody.ReadLength[n] = range->length;
2317 pkt.ConstantBody.Buffer[n] =
2318 ro_bo(res->bo, range->start * 32 + cbuf->offset);
2319 n--;
2320 }
2321 }
2322 }
2323 }
2324
2325 if (1) { // XXX: DIRTY BINDINGS
2326 const struct iris_binder *binder = &batch->binder;
2327
2328 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
2329 iris_emit_cmd(batch, GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), ptr) {
2330 ptr._3DCommandSubOpcode = 38 + stage;
2331 ptr.PointertoVSBindingTable = binder->bt_offset[stage];
2332 }
2333 }
2334
2335 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
2336 iris_populate_binding_table(ice, batch, stage);
2337 }
2338 }
2339
2340 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
2341 if (!(dirty & (IRIS_DIRTY_SAMPLER_STATES_VS << stage)) ||
2342 !ice->shaders.prog[stage])
2343 continue;
2344
2345 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ptr) {
2346 ptr._3DCommandSubOpcode = 43 + stage;
2347 ptr.PointertoVSSamplerState = ice->state.sampler_table_offset[stage];
2348 }
2349 }
2350
2351 if (dirty & IRIS_DIRTY_MULTISAMPLE) {
2352 iris_emit_cmd(batch, GENX(3DSTATE_MULTISAMPLE), ms) {
2353 ms.PixelLocation =
2354 ice->state.cso_rast->half_pixel_center ? CENTER : UL_CORNER;
2355 if (ice->state.framebuffer.samples > 0)
2356 ms.NumberofMultisamples = ffs(ice->state.framebuffer.samples) - 1;
2357 }
2358 }
2359
2360 if (dirty & IRIS_DIRTY_SAMPLE_MASK) {
2361 iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_MASK), ms) {
2362 ms.SampleMask = MAX2(ice->state.sample_mask, 1);
2363 }
2364 }
2365
2366 for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
2367 if (!(dirty & (IRIS_DIRTY_VS << stage)))
2368 continue;
2369
2370 struct iris_compiled_shader *shader = ice->shaders.prog[stage];
2371
2372 if (shader) {
2373 struct iris_resource *cache = (void *) shader->buffer;
2374 iris_use_pinned_bo(batch, cache->bo, false);
2375 iris_batch_emit(batch, shader->derived_data,
2376 iris_derived_program_state_size(stage));
2377 } else {
2378 if (stage == MESA_SHADER_TESS_EVAL) {
2379 iris_emit_cmd(batch, GENX(3DSTATE_HS), hs);
2380 iris_emit_cmd(batch, GENX(3DSTATE_TE), te);
2381 iris_emit_cmd(batch, GENX(3DSTATE_DS), ds);
2382 } else if (stage == MESA_SHADER_GEOMETRY) {
2383 iris_emit_cmd(batch, GENX(3DSTATE_GS), gs);
2384 }
2385 }
2386 }
2387
2388 // XXX: SOL:
2389 // 3DSTATE_STREAMOUT
2390 // 3DSTATE_SO_BUFFER
2391 // 3DSTATE_SO_DECL_LIST
2392
2393 if (dirty & IRIS_DIRTY_CLIP) {
2394 struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
2395 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
2396
2397 uint32_t dynamic_clip[GENX(3DSTATE_CLIP_length)];
2398 iris_pack_command(GENX(3DSTATE_CLIP), &dynamic_clip, cl) {
2399 if (wm_prog_data->barycentric_interp_modes &
2400 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS)
2401 cl.NonPerspectiveBarycentricEnable = true;
2402
2403 cl.ForceZeroRTAIndexEnable = cso_fb->layers == 0;
2404 }
2405 iris_emit_merge(batch, cso_rast->clip, dynamic_clip,
2406 ARRAY_SIZE(cso_rast->clip));
2407 }
2408
2409 if (dirty & IRIS_DIRTY_RASTER) {
2410 struct iris_rasterizer_state *cso = ice->state.cso_rast;
2411 iris_batch_emit(batch, cso->raster, sizeof(cso->raster));
2412 iris_batch_emit(batch, cso->sf, sizeof(cso->sf));
2413
2414 }
2415
2416 if (dirty & (IRIS_DIRTY_RASTER | IRIS_DIRTY_FS)) {
2417 struct iris_rasterizer_state *cso = ice->state.cso_rast;
2418 uint32_t dynamic_wm[GENX(3DSTATE_WM_length)];
2419
2420 iris_pack_command(GENX(3DSTATE_WM), &dynamic_wm, wm) {
2421 wm.BarycentricInterpolationMode =
2422 wm_prog_data->barycentric_interp_modes;
2423
2424 if (wm_prog_data->early_fragment_tests)
2425 wm.EarlyDepthStencilControl = EDSC_PREPS;
2426 else if (wm_prog_data->has_side_effects)
2427 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
2428 }
2429 iris_emit_merge(batch, cso->wm, dynamic_wm, ARRAY_SIZE(cso->wm));
2430 }
2431
2432 if (1) {
2433 // XXX: 3DSTATE_SBE, 3DSTATE_SBE_SWIZ
2434 // -> iris_raster_state (point sprite texture coordinate origin)
2435 // -> bunch of shader state...
2436 iris_emit_sbe(batch, ice);
2437 iris_emit_cmd(batch, GENX(3DSTATE_SBE_SWIZ), sbe) {
2438 }
2439 }
2440
2441 if (dirty & IRIS_DIRTY_PS_BLEND) {
2442 struct iris_blend_state *cso_blend = ice->state.cso_blend;
2443 struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
2444 uint32_t dynamic_pb[GENX(3DSTATE_PS_BLEND_length)];
2445 iris_pack_command(GENX(3DSTATE_PS_BLEND), &dynamic_pb, pb) {
2446 pb.HasWriteableRT = true; // XXX: comes from somewhere :(
2447 pb.AlphaTestEnable = cso_zsa->alpha.enabled;
2448 }
2449
2450 iris_emit_merge(batch, cso_blend->ps_blend, dynamic_pb,
2451 ARRAY_SIZE(cso_blend->ps_blend));
2452 }
2453
2454 if (dirty & IRIS_DIRTY_WM_DEPTH_STENCIL) {
2455 struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
2456 struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
2457
2458 uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
2459 iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
2460 wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
2461 wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
2462 }
2463 iris_emit_merge(batch, cso->wmds, stencil_refs, ARRAY_SIZE(cso->wmds));
2464 }
2465
2466 if (dirty & IRIS_DIRTY_SCISSOR) {
2467 // XXX: allocate at set_scissor time?
2468 uint32_t scissor_offset = ice->state.num_scissors == 0 ? 0 :
2469 emit_state(batch, ice->state.dynamic_uploader, ice->state.scissors,
2470 sizeof(struct pipe_scissor_state) *
2471 ice->state.num_scissors, 32);
2472
2473 iris_emit_cmd(batch, GENX(3DSTATE_SCISSOR_STATE_POINTERS), ptr) {
2474 ptr.ScissorRectPointer = scissor_offset;
2475 }
2476 }
2477
2478 if (dirty & IRIS_DIRTY_DEPTH_BUFFER) {
2479 struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
2480 struct iris_depth_buffer_state *cso_z = ice->state.cso_depthbuffer;
2481
2482 iris_batch_emit(batch, cso_z->packets, sizeof(cso_z->packets));
2483
2484 if (cso_fb->zsbuf) {
2485 struct iris_resource *zres = (void *) cso_fb->zsbuf->texture;
2486 // XXX: depth might not be writable...
2487 iris_use_pinned_bo(batch, zres->bo, true);
2488 }
2489 }
2490
2491 if (dirty & IRIS_DIRTY_POLYGON_STIPPLE) {
2492 iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_PATTERN), poly) {
2493 for (int i = 0; i < 32; i++) {
2494 poly.PatternRow[i] = ice->state.poly_stipple.stipple[i];
2495 }
2496 }
2497 }
2498
2499 if (dirty & IRIS_DIRTY_LINE_STIPPLE) {
2500 struct iris_rasterizer_state *cso = ice->state.cso_rast;
2501 iris_batch_emit(batch, cso->line_stipple, sizeof(cso->line_stipple));
2502 }
2503
2504 if (1) {
2505 iris_emit_cmd(batch, GENX(3DSTATE_VF_TOPOLOGY), topo) {
2506 topo.PrimitiveTopologyType =
2507 translate_prim_type(draw->mode, draw->vertices_per_patch);
2508 }
2509 }
2510
2511 if (draw->index_size > 0) {
2512 struct iris_resource *res = (struct iris_resource *)draw->index.resource;
2513
2514 assert(!draw->has_user_indices);
2515
2516 iris_emit_cmd(batch, GENX(3DSTATE_INDEX_BUFFER), ib) {
2517 ib.IndexFormat = draw->index_size >> 1;
2518 ib.MOCS = MOCS_WB;
2519 ib.BufferSize = res->bo->size;
2520 ib.BufferStartingAddress = ro_bo(res->bo, 0);
2521 }
2522 }
2523
2524 if (dirty & IRIS_DIRTY_VERTEX_BUFFERS) {
2525 struct iris_vertex_buffer_state *cso = ice->state.cso_vertex_buffers;
2526
2527 STATIC_ASSERT(GENX(VERTEX_BUFFER_STATE_length) == 4);
2528 STATIC_ASSERT((GENX(VERTEX_BUFFER_STATE_BufferStartingAddress_bits) % 32) == 0);
2529
2530 iris_batch_emit(batch, cso->vertex_buffers,
2531 sizeof(uint32_t) * (1 + 4 * cso->num_buffers));
2532
2533 for (unsigned i = 0; i < cso->num_buffers; i++) {
2534 iris_use_pinned_bo(batch, cso->bos[i], false);
2535 }
2536 }
2537
2538 if (dirty & IRIS_DIRTY_VERTEX_ELEMENTS) {
2539 struct iris_vertex_element_state *cso = ice->state.cso_vertex_elements;
2540 iris_batch_emit(batch, cso->vertex_elements, sizeof(uint32_t) *
2541 (1 + cso->count * GENX(VERTEX_ELEMENT_STATE_length)));
2542 iris_batch_emit(batch, cso->vf_instancing, sizeof(uint32_t) *
2543 cso->count * GENX(3DSTATE_VF_INSTANCING_length));
2544 for (int i = 0; i < cso->count; i++) {
2545 /* TODO: vertexid, instanceid support */
2546 iris_emit_cmd(batch, GENX(3DSTATE_VF_SGVS), sgvs);
2547 }
2548 }
2549
2550 if (1) {
2551 iris_emit_cmd(batch, GENX(3DSTATE_VF), vf) {
2552 if (draw->primitive_restart) {
2553 vf.IndexedDrawCutIndexEnable = true;
2554 vf.CutIndex = draw->restart_index;
2555 }
2556 }
2557 }
2558
2559 // XXX: Gen8 - PMA fix
2560
2561 assert(!draw->indirect); // XXX: indirect support
2562
2563 iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
2564 prim.StartInstanceLocation = draw->start_instance;
2565 prim.InstanceCount = draw->instance_count;
2566 prim.VertexCountPerInstance = draw->count;
2567 prim.VertexAccessType = draw->index_size > 0 ? RANDOM : SEQUENTIAL;
2568
2569 // XXX: this is probably bonkers.
2570 prim.StartVertexLocation = draw->start;
2571
2572 if (draw->index_size) {
2573 prim.BaseVertexLocation += draw->index_bias;
2574 } else {
2575 prim.StartVertexLocation += draw->index_bias;
2576 }
2577
2578 //prim.BaseVertexLocation = ...;
2579 }
2580 }
2581
2582 static void
2583 iris_destroy_state(struct iris_context *ice)
2584 {
2585 // XXX: unreference resources/surfaces.
2586 for (unsigned i = 0; i < ice->state.framebuffer.nr_cbufs; i++) {
2587 pipe_surface_reference(&ice->state.framebuffer.cbufs[i], NULL);
2588 }
2589 pipe_surface_reference(&ice->state.framebuffer.zsbuf, NULL);
2590 }
2591
2592 static unsigned
2593 flags_to_post_sync_op(uint32_t flags)
2594 {
2595 if (flags & PIPE_CONTROL_WRITE_IMMEDIATE)
2596 return WriteImmediateData;
2597
2598 if (flags & PIPE_CONTROL_WRITE_DEPTH_COUNT)
2599 return WritePSDepthCount;
2600
2601 if (flags & PIPE_CONTROL_WRITE_TIMESTAMP)
2602 return WriteTimestamp;
2603
2604 return 0;
2605 }
2606
2607 /**
2608 * Do the given flags have a Post Sync or LRI Post Sync operation?
2609 */
2610 static enum pipe_control_flags
2611 get_post_sync_flags(enum pipe_control_flags flags)
2612 {
2613 flags &= PIPE_CONTROL_WRITE_IMMEDIATE |
2614 PIPE_CONTROL_WRITE_DEPTH_COUNT |
2615 PIPE_CONTROL_WRITE_TIMESTAMP |
2616 PIPE_CONTROL_LRI_POST_SYNC_OP;
2617
2618 /* Only one "Post Sync Op" is allowed, and it's mutually exclusive with
2619 * "LRI Post Sync Operation". So more than one bit set would be illegal.
2620 */
2621 assert(util_bitcount(flags) <= 1);
2622
2623 return flags;
2624 }
2625
2626 // XXX: compute support
2627 #define IS_COMPUTE_PIPELINE(batch) (batch->ring != I915_EXEC_RENDER)
2628
2629 /**
2630 * Emit a series of PIPE_CONTROL commands, taking into account any
2631 * workarounds necessary to actually accomplish the caller's request.
2632 *
2633 * Unless otherwise noted, spec quotations in this function come from:
2634 *
2635 * Synchronization of the 3D Pipeline > PIPE_CONTROL Command > Programming
2636 * Restrictions for PIPE_CONTROL.
2637 */
2638 static void
2639 iris_emit_raw_pipe_control(struct iris_batch *batch, uint32_t flags,
2640 struct iris_bo *bo, uint32_t offset, uint64_t imm)
2641 {
2642 UNUSED const struct gen_device_info *devinfo = &batch->screen->devinfo;
2643 enum pipe_control_flags post_sync_flags = get_post_sync_flags(flags);
2644 enum pipe_control_flags non_lri_post_sync_flags =
2645 post_sync_flags & ~PIPE_CONTROL_LRI_POST_SYNC_OP;
2646
2647 /* Recursive PIPE_CONTROL workarounds --------------------------------
2648 * (http://knowyourmeme.com/memes/xzibit-yo-dawg)
2649 *
2650 * We do these first because we want to look at the original operation,
2651 * rather than any workarounds we set.
2652 */
2653 if (GEN_GEN == 9 && (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE)) {
2654 /* The PIPE_CONTROL "VF Cache Invalidation Enable" bit description
2655 * lists several workarounds:
2656 *
2657 * "Project: SKL, KBL, BXT
2658 *
2659 * If the VF Cache Invalidation Enable is set to a 1 in a
2660 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields
2661 * sets to 0, with the VF Cache Invalidation Enable set to 0
2662 * needs to be sent prior to the PIPE_CONTROL with VF Cache
2663 * Invalidation Enable set to a 1."
2664 */
2665 iris_emit_raw_pipe_control(batch, 0, NULL, 0, 0);
2666 }
2667
2668 if (GEN_GEN == 9 && IS_COMPUTE_PIPELINE(batch) && post_sync_flags) {
2669 /* Project: SKL / Argument: LRI Post Sync Operation [23]
2670 *
2671 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
2672 * programmed prior to programming a PIPECONTROL command with "LRI
2673 * Post Sync Operation" in GPGPU mode of operation (i.e when
2674 * PIPELINE_SELECT command is set to GPGPU mode of operation)."
2675 *
2676 * The same text exists a few rows below for Post Sync Op.
2677 */
2678 iris_emit_raw_pipe_control(batch, PIPE_CONTROL_CS_STALL, bo, offset, imm);
2679 }
2680
2681 if (GEN_GEN == 10 && (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH)) {
2682 /* Cannonlake:
2683 * "Before sending a PIPE_CONTROL command with bit 12 set, SW must issue
2684 * another PIPE_CONTROL with Render Target Cache Flush Enable (bit 12)
2685 * = 0 and Pipe Control Flush Enable (bit 7) = 1"
2686 */
2687 iris_emit_raw_pipe_control(batch, PIPE_CONTROL_FLUSH_ENABLE, bo,
2688 offset, imm);
2689 }
2690
2691 /* "Flush Types" workarounds ---------------------------------------------
2692 * We do these now because they may add post-sync operations or CS stalls.
2693 */
2694
2695 if (flags & PIPE_CONTROL_VF_CACHE_INVALIDATE) {
2696 /* Project: BDW, SKL+ (stopping at CNL) / Argument: VF Invalidate
2697 *
2698 * "'Post Sync Operation' must be enabled to 'Write Immediate Data' or
2699 * 'Write PS Depth Count' or 'Write Timestamp'."
2700 */
2701 if (!bo) {
2702 flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
2703 post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
2704 non_lri_post_sync_flags |= PIPE_CONTROL_WRITE_IMMEDIATE;
2705 bo = batch->screen->workaround_bo;
2706 }
2707 }
2708
2709 /* #1130 from Gen10 workarounds page:
2710 *
2711 * "Enable Depth Stall on every Post Sync Op if Render target Cache
2712 * Flush is not enabled in same PIPE CONTROL and Enable Pixel score
2713 * board stall if Render target cache flush is enabled."
2714 *
2715 * Applicable to CNL B0 and C0 steppings only.
2716 *
2717 * The wording here is unclear, and this workaround doesn't look anything
2718 * like the internal bug report recommendations, but leave it be for now...
2719 */
2720 if (GEN_GEN == 10) {
2721 if (flags & PIPE_CONTROL_RENDER_TARGET_FLUSH) {
2722 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
2723 } else if (flags & non_lri_post_sync_flags) {
2724 flags |= PIPE_CONTROL_DEPTH_STALL;
2725 }
2726 }
2727
2728 if (flags & PIPE_CONTROL_DEPTH_STALL) {
2729 /* From the PIPE_CONTROL instruction table, bit 13 (Depth Stall Enable):
2730 *
2731 * "This bit must be DISABLED for operations other than writing
2732 * PS_DEPTH_COUNT."
2733 *
2734 * This seems like nonsense. An Ivybridge workaround requires us to
2735 * emit a PIPE_CONTROL with a depth stall and write immediate post-sync
2736 * operation. Gen8+ requires us to emit depth stalls and depth cache
2737 * flushes together. So, it's hard to imagine this means anything other
2738 * than "we originally intended this to be used for PS_DEPTH_COUNT".
2739 *
2740 * We ignore the supposed restriction and do nothing.
2741 */
2742 }
2743
2744 if (flags & (PIPE_CONTROL_RENDER_TARGET_FLUSH |
2745 PIPE_CONTROL_STALL_AT_SCOREBOARD)) {
2746 /* From the PIPE_CONTROL instruction table, bit 12 and bit 1:
2747 *
2748 * "This bit must be DISABLED for End-of-pipe (Read) fences,
2749 * PS_DEPTH_COUNT or TIMESTAMP queries."
2750 *
2751 * TODO: Implement end-of-pipe checking.
2752 */
2753 assert(!(post_sync_flags & (PIPE_CONTROL_WRITE_DEPTH_COUNT |
2754 PIPE_CONTROL_WRITE_TIMESTAMP)));
2755 }
2756
2757 if (flags & PIPE_CONTROL_STALL_AT_SCOREBOARD) {
2758 /* From the PIPE_CONTROL instruction table, bit 1:
2759 *
2760 * "This bit is ignored if Depth Stall Enable is set.
2761 * Further, the render cache is not flushed even if Write Cache
2762 * Flush Enable bit is set."
2763 *
2764 * We assert that the caller doesn't do this combination, to try and
2765 * prevent mistakes. It shouldn't hurt the GPU, though.
2766 */
2767 assert(!(flags & (PIPE_CONTROL_DEPTH_STALL |
2768 PIPE_CONTROL_RENDER_TARGET_FLUSH)));
2769 }
2770
2771 /* PIPE_CONTROL page workarounds ------------------------------------- */
2772
2773 if (GEN_GEN <= 8 && (flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE)) {
2774 /* From the PIPE_CONTROL page itself:
2775 *
2776 * "IVB, HSW, BDW
2777 * Restriction: Pipe_control with CS-stall bit set must be issued
2778 * before a pipe-control command that has the State Cache
2779 * Invalidate bit set."
2780 */
2781 flags |= PIPE_CONTROL_CS_STALL;
2782 }
2783
2784 if (flags & PIPE_CONTROL_FLUSH_LLC) {
2785 /* From the PIPE_CONTROL instruction table, bit 26 (Flush LLC):
2786 *
2787 * "Project: ALL
2788 * SW must always program Post-Sync Operation to "Write Immediate
2789 * Data" when Flush LLC is set."
2790 *
2791 * For now, we just require the caller to do it.
2792 */
2793 assert(flags & PIPE_CONTROL_WRITE_IMMEDIATE);
2794 }
2795
2796 /* "Post-Sync Operation" workarounds -------------------------------- */
2797
2798 /* Project: All / Argument: Global Snapshot Count Reset [19]
2799 *
2800 * "This bit must not be exercised on any product.
2801 * Requires stall bit ([20] of DW1) set."
2802 *
2803 * We don't use this, so we just assert that it isn't used. The
2804 * PIPE_CONTROL instruction page indicates that they intended this
2805 * as a debug feature and don't think it is useful in production,
2806 * but it may actually be usable, should we ever want to.
2807 */
2808 assert((flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET) == 0);
2809
2810 if (flags & (PIPE_CONTROL_MEDIA_STATE_CLEAR |
2811 PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE)) {
2812 /* Project: All / Arguments:
2813 *
2814 * - Generic Media State Clear [16]
2815 * - Indirect State Pointers Disable [16]
2816 *
2817 * "Requires stall bit ([20] of DW1) set."
2818 *
2819 * Also, the PIPE_CONTROL instruction table, bit 16 (Generic Media
2820 * State Clear) says:
2821 *
2822 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
2823 * programmed prior to programming a PIPECONTROL command with "Media
2824 * State Clear" set in GPGPU mode of operation"
2825 *
2826 * This is a subset of the earlier rule, so there's nothing to do.
2827 */
2828 flags |= PIPE_CONTROL_CS_STALL;
2829 }
2830
2831 if (flags & PIPE_CONTROL_STORE_DATA_INDEX) {
2832 /* Project: All / Argument: Store Data Index
2833 *
2834 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
2835 * than '0'."
2836 *
2837 * For now, we just assert that the caller does this. We might want to
2838 * automatically add a write to the workaround BO...
2839 */
2840 assert(non_lri_post_sync_flags != 0);
2841 }
2842
2843 if (flags & PIPE_CONTROL_SYNC_GFDT) {
2844 /* Project: All / Argument: Sync GFDT
2845 *
2846 * "Post-Sync Operation ([15:14] of DW1) must be set to something other
2847 * than '0' or 0x2520[13] must be set."
2848 *
2849 * For now, we just assert that the caller does this.
2850 */
2851 assert(non_lri_post_sync_flags != 0);
2852 }
2853
2854 if (flags & PIPE_CONTROL_TLB_INVALIDATE) {
2855 /* Project: IVB+ / Argument: TLB inv
2856 *
2857 * "Requires stall bit ([20] of DW1) set."
2858 *
2859 * Also, from the PIPE_CONTROL instruction table:
2860 *
2861 * "Project: SKL+
2862 * Post Sync Operation or CS stall must be set to ensure a TLB
2863 * invalidation occurs. Otherwise no cycle will occur to the TLB
2864 * cache to invalidate."
2865 *
2866 * This is not a subset of the earlier rule, so there's nothing to do.
2867 */
2868 flags |= PIPE_CONTROL_CS_STALL;
2869 }
2870
2871 if (GEN_GEN == 9 && devinfo->gt == 4) {
2872 /* TODO: The big Skylake GT4 post sync op workaround */
2873 }
2874
2875 /* "GPGPU specific workarounds" (both post-sync and flush) ------------ */
2876
2877 if (IS_COMPUTE_PIPELINE(batch)) {
2878 if (GEN_GEN >= 9 && (flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE)) {
2879 /* Project: SKL+ / Argument: Tex Invalidate
2880 * "Requires stall bit ([20] of DW) set for all GPGPU Workloads."
2881 */
2882 flags |= PIPE_CONTROL_CS_STALL;
2883 }
2884
2885 if (GEN_GEN == 8 && (post_sync_flags ||
2886 (flags & (PIPE_CONTROL_NOTIFY_ENABLE |
2887 PIPE_CONTROL_DEPTH_STALL |
2888 PIPE_CONTROL_RENDER_TARGET_FLUSH |
2889 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
2890 PIPE_CONTROL_DATA_CACHE_FLUSH)))) {
2891 /* Project: BDW / Arguments:
2892 *
2893 * - LRI Post Sync Operation [23]
2894 * - Post Sync Op [15:14]
2895 * - Notify En [8]
2896 * - Depth Stall [13]
2897 * - Render Target Cache Flush [12]
2898 * - Depth Cache Flush [0]
2899 * - DC Flush Enable [5]
2900 *
2901 * "Requires stall bit ([20] of DW) set for all GPGPU and Media
2902 * Workloads."
2903 */
2904 flags |= PIPE_CONTROL_CS_STALL;
2905
2906 /* Also, from the PIPE_CONTROL instruction table, bit 20:
2907 *
2908 * "Project: BDW
2909 * This bit must be always set when PIPE_CONTROL command is
2910 * programmed by GPGPU and MEDIA workloads, except for the cases
2911 * when only Read Only Cache Invalidation bits are set (State
2912 * Cache Invalidation Enable, Instruction cache Invalidation
2913 * Enable, Texture Cache Invalidation Enable, Constant Cache
2914 * Invalidation Enable). This is to WA FFDOP CG issue, this WA
2915 * need not implemented when FF_DOP_CG is disable via "Fixed
2916 * Function DOP Clock Gate Disable" bit in RC_PSMI_CTRL register."
2917 *
2918 * It sounds like we could avoid CS stalls in some cases, but we
2919 * don't currently bother. This list isn't exactly the list above,
2920 * either...
2921 */
2922 }
2923 }
2924
2925 /* "Stall" workarounds ----------------------------------------------
2926 * These have to come after the earlier ones because we may have added
2927 * some additional CS stalls above.
2928 */
2929
2930 if (GEN_GEN < 9 && (flags & PIPE_CONTROL_CS_STALL)) {
2931 /* Project: PRE-SKL, VLV, CHV
2932 *
2933 * "[All Stepping][All SKUs]:
2934 *
2935 * One of the following must also be set:
2936 *
2937 * - Render Target Cache Flush Enable ([12] of DW1)
2938 * - Depth Cache Flush Enable ([0] of DW1)
2939 * - Stall at Pixel Scoreboard ([1] of DW1)
2940 * - Depth Stall ([13] of DW1)
2941 * - Post-Sync Operation ([13] of DW1)
2942 * - DC Flush Enable ([5] of DW1)"
2943 *
2944 * If we don't already have one of those bits set, we choose to add
2945 * "Stall at Pixel Scoreboard". Some of the other bits require a
2946 * CS stall as a workaround (see above), which would send us into
2947 * an infinite recursion of PIPE_CONTROLs. "Stall at Pixel Scoreboard"
2948 * appears to be safe, so we choose that.
2949 */
2950 const uint32_t wa_bits = PIPE_CONTROL_RENDER_TARGET_FLUSH |
2951 PIPE_CONTROL_DEPTH_CACHE_FLUSH |
2952 PIPE_CONTROL_WRITE_IMMEDIATE |
2953 PIPE_CONTROL_WRITE_DEPTH_COUNT |
2954 PIPE_CONTROL_WRITE_TIMESTAMP |
2955 PIPE_CONTROL_STALL_AT_SCOREBOARD |
2956 PIPE_CONTROL_DEPTH_STALL |
2957 PIPE_CONTROL_DATA_CACHE_FLUSH;
2958 if (!(flags & wa_bits))
2959 flags |= PIPE_CONTROL_STALL_AT_SCOREBOARD;
2960 }
2961
2962 /* Emit --------------------------------------------------------------- */
2963
2964 iris_emit_cmd(batch, GENX(PIPE_CONTROL), pc) {
2965 pc.LRIPostSyncOperation = NoLRIOperation;
2966 pc.PipeControlFlushEnable = flags & PIPE_CONTROL_FLUSH_ENABLE;
2967 pc.DCFlushEnable = flags & PIPE_CONTROL_DATA_CACHE_FLUSH;
2968 pc.StoreDataIndex = 0;
2969 pc.CommandStreamerStallEnable = flags & PIPE_CONTROL_CS_STALL;
2970 pc.GlobalSnapshotCountReset =
2971 flags & PIPE_CONTROL_GLOBAL_SNAPSHOT_COUNT_RESET;
2972 pc.TLBInvalidate = flags & PIPE_CONTROL_TLB_INVALIDATE;
2973 pc.GenericMediaStateClear = flags & PIPE_CONTROL_MEDIA_STATE_CLEAR;
2974 pc.StallAtPixelScoreboard = flags & PIPE_CONTROL_STALL_AT_SCOREBOARD;
2975 pc.RenderTargetCacheFlushEnable =
2976 flags & PIPE_CONTROL_RENDER_TARGET_FLUSH;
2977 pc.DepthCacheFlushEnable = flags & PIPE_CONTROL_DEPTH_CACHE_FLUSH;
2978 pc.StateCacheInvalidationEnable =
2979 flags & PIPE_CONTROL_STATE_CACHE_INVALIDATE;
2980 pc.VFCacheInvalidationEnable = flags & PIPE_CONTROL_VF_CACHE_INVALIDATE;
2981 pc.ConstantCacheInvalidationEnable =
2982 flags & PIPE_CONTROL_CONST_CACHE_INVALIDATE;
2983 pc.PostSyncOperation = flags_to_post_sync_op(flags);
2984 pc.DepthStallEnable = flags & PIPE_CONTROL_DEPTH_STALL;
2985 pc.InstructionCacheInvalidateEnable =
2986 flags & PIPE_CONTROL_INSTRUCTION_INVALIDATE;
2987 pc.NotifyEnable = flags & PIPE_CONTROL_NOTIFY_ENABLE;
2988 pc.IndirectStatePointersDisable =
2989 flags & PIPE_CONTROL_INDIRECT_STATE_POINTERS_DISABLE;
2990 pc.TextureCacheInvalidationEnable =
2991 flags & PIPE_CONTROL_TEXTURE_CACHE_INVALIDATE;
2992 pc.Address = ro_bo(bo, offset);
2993 pc.ImmediateData = imm;
2994 }
2995 }
2996
2997 void
2998 genX(init_state)(struct iris_context *ice)
2999 {
3000 struct pipe_context *ctx = &ice->ctx;
3001
3002 ctx->create_blend_state = iris_create_blend_state;
3003 ctx->create_depth_stencil_alpha_state = iris_create_zsa_state;
3004 ctx->create_rasterizer_state = iris_create_rasterizer_state;
3005 ctx->create_sampler_state = iris_create_sampler_state;
3006 ctx->create_sampler_view = iris_create_sampler_view;
3007 ctx->create_surface = iris_create_surface;
3008 ctx->create_vertex_elements_state = iris_create_vertex_elements;
3009 ctx->create_compute_state = iris_create_compute_state;
3010 ctx->bind_blend_state = iris_bind_blend_state;
3011 ctx->bind_depth_stencil_alpha_state = iris_bind_zsa_state;
3012 ctx->bind_sampler_states = iris_bind_sampler_states;
3013 ctx->bind_rasterizer_state = iris_bind_rasterizer_state;
3014 ctx->bind_vertex_elements_state = iris_bind_vertex_elements_state;
3015 ctx->bind_compute_state = iris_bind_compute_state;
3016 ctx->delete_blend_state = iris_delete_state;
3017 ctx->delete_depth_stencil_alpha_state = iris_delete_state;
3018 ctx->delete_fs_state = iris_delete_state;
3019 ctx->delete_rasterizer_state = iris_delete_state;
3020 ctx->delete_sampler_state = iris_delete_state;
3021 ctx->delete_vertex_elements_state = iris_delete_state;
3022 ctx->delete_compute_state = iris_delete_state;
3023 ctx->delete_tcs_state = iris_delete_state;
3024 ctx->delete_tes_state = iris_delete_state;
3025 ctx->delete_gs_state = iris_delete_state;
3026 ctx->delete_vs_state = iris_delete_state;
3027 ctx->set_blend_color = iris_set_blend_color;
3028 ctx->set_clip_state = iris_set_clip_state;
3029 ctx->set_constant_buffer = iris_set_constant_buffer;
3030 ctx->set_sampler_views = iris_set_sampler_views;
3031 ctx->set_framebuffer_state = iris_set_framebuffer_state;
3032 ctx->set_polygon_stipple = iris_set_polygon_stipple;
3033 ctx->set_sample_mask = iris_set_sample_mask;
3034 ctx->set_scissor_states = iris_set_scissor_states;
3035 ctx->set_stencil_ref = iris_set_stencil_ref;
3036 ctx->set_vertex_buffers = iris_set_vertex_buffers;
3037 ctx->set_viewport_states = iris_set_viewport_states;
3038 ctx->sampler_view_destroy = iris_sampler_view_destroy;
3039 ctx->surface_destroy = iris_surface_destroy;
3040 ctx->draw_vbo = iris_draw_vbo;
3041 ctx->launch_grid = iris_launch_grid;
3042 ctx->create_stream_output_target = iris_create_stream_output_target;
3043 ctx->stream_output_target_destroy = iris_stream_output_target_destroy;
3044 ctx->set_stream_output_targets = iris_set_stream_output_targets;
3045
3046 ice->vtbl.destroy_state = iris_destroy_state;
3047 ice->vtbl.init_render_context = iris_init_render_context;
3048 ice->vtbl.upload_render_state = iris_upload_render_state;
3049 ice->vtbl.emit_raw_pipe_control = iris_emit_raw_pipe_control;
3050 ice->vtbl.derived_program_state_size = iris_derived_program_state_size;
3051 ice->vtbl.set_derived_program_state = iris_set_derived_program_state;
3052 ice->vtbl.populate_vs_key = iris_populate_vs_key;
3053 ice->vtbl.populate_tcs_key = iris_populate_tcs_key;
3054 ice->vtbl.populate_tes_key = iris_populate_tes_key;
3055 ice->vtbl.populate_gs_key = iris_populate_gs_key;
3056 ice->vtbl.populate_fs_key = iris_populate_fs_key;
3057
3058 ice->state.dirty = ~0ull;
3059 }