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