i965: Fix alpha to one with dual color blending.
[mesa.git] / src / mesa / drivers / dri / i965 / genX_state_upload.c
1 /*
2 * Copyright © 2017 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (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 NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25
26 #include "common/gen_device_info.h"
27 #include "common/gen_sample_positions.h"
28 #include "genxml/gen_macros.h"
29
30 #include "main/bufferobj.h"
31 #include "main/context.h"
32 #include "main/enums.h"
33 #include "main/macros.h"
34
35 #include "brw_context.h"
36 #if GEN_GEN == 6
37 #include "brw_defines.h"
38 #endif
39 #include "brw_draw.h"
40 #include "brw_multisample_state.h"
41 #include "brw_state.h"
42 #include "brw_wm.h"
43 #include "brw_util.h"
44
45 #include "intel_batchbuffer.h"
46 #include "intel_buffer_objects.h"
47 #include "intel_fbo.h"
48
49 #include "main/enums.h"
50 #include "main/fbobject.h"
51 #include "main/framebuffer.h"
52 #include "main/glformats.h"
53 #include "main/shaderapi.h"
54 #include "main/stencil.h"
55 #include "main/transformfeedback.h"
56 #include "main/varray.h"
57 #include "main/viewport.h"
58
59 UNUSED static void *
60 emit_dwords(struct brw_context *brw, unsigned n)
61 {
62 intel_batchbuffer_begin(brw, n, RENDER_RING);
63 uint32_t *map = brw->batch.map_next;
64 brw->batch.map_next += n;
65 intel_batchbuffer_advance(brw);
66 return map;
67 }
68
69 struct brw_address {
70 struct brw_bo *bo;
71 uint32_t read_domains;
72 uint32_t write_domain;
73 uint32_t offset;
74 };
75
76 static uint64_t
77 emit_reloc(struct brw_context *brw,
78 void *location, struct brw_address address, uint32_t delta)
79 {
80 uint32_t offset = (char *) location - (char *) brw->batch.map;
81
82 return brw_emit_reloc(&brw->batch, offset, address.bo,
83 address.offset + delta,
84 address.read_domains,
85 address.write_domain);
86 }
87
88 #define __gen_address_type struct brw_address
89 #define __gen_user_data struct brw_context
90
91 static uint64_t
92 __gen_combine_address(struct brw_context *brw, void *location,
93 struct brw_address address, uint32_t delta)
94 {
95 if (address.bo == NULL) {
96 return address.offset + delta;
97 } else {
98 return emit_reloc(brw, location, address, delta);
99 }
100 }
101
102 static inline struct brw_address
103 render_bo(struct brw_bo *bo, uint32_t offset)
104 {
105 return (struct brw_address) {
106 .bo = bo,
107 .offset = offset,
108 .read_domains = I915_GEM_DOMAIN_RENDER,
109 .write_domain = I915_GEM_DOMAIN_RENDER,
110 };
111 }
112
113 static inline struct brw_address
114 render_ro_bo(struct brw_bo *bo, uint32_t offset)
115 {
116 return (struct brw_address) {
117 .bo = bo,
118 .offset = offset,
119 .read_domains = I915_GEM_DOMAIN_RENDER,
120 .write_domain = 0,
121 };
122 }
123
124 static inline struct brw_address
125 instruction_bo(struct brw_bo *bo, uint32_t offset)
126 {
127 return (struct brw_address) {
128 .bo = bo,
129 .offset = offset,
130 .read_domains = I915_GEM_DOMAIN_INSTRUCTION,
131 .write_domain = I915_GEM_DOMAIN_INSTRUCTION,
132 };
133 }
134
135 static inline struct brw_address
136 instruction_ro_bo(struct brw_bo *bo, uint32_t offset)
137 {
138 return (struct brw_address) {
139 .bo = bo,
140 .offset = offset,
141 .read_domains = I915_GEM_DOMAIN_INSTRUCTION,
142 .write_domain = 0,
143 };
144 }
145
146 static inline struct brw_address
147 vertex_bo(struct brw_bo *bo, uint32_t offset)
148 {
149 return (struct brw_address) {
150 .bo = bo,
151 .offset = offset,
152 .read_domains = I915_GEM_DOMAIN_VERTEX,
153 .write_domain = 0,
154 };
155 }
156
157 #include "genxml/genX_pack.h"
158
159 #define _brw_cmd_length(cmd) cmd ## _length
160 #define _brw_cmd_length_bias(cmd) cmd ## _length_bias
161 #define _brw_cmd_header(cmd) cmd ## _header
162 #define _brw_cmd_pack(cmd) cmd ## _pack
163
164 #define brw_batch_emit(brw, cmd, name) \
165 for (struct cmd name = { _brw_cmd_header(cmd) }, \
166 *_dst = emit_dwords(brw, _brw_cmd_length(cmd)); \
167 __builtin_expect(_dst != NULL, 1); \
168 _brw_cmd_pack(cmd)(brw, (void *)_dst, &name), \
169 _dst = NULL)
170
171 #define brw_batch_emitn(brw, cmd, n, ...) ({ \
172 uint32_t *_dw = emit_dwords(brw, n); \
173 struct cmd template = { \
174 _brw_cmd_header(cmd), \
175 .DWordLength = n - _brw_cmd_length_bias(cmd), \
176 __VA_ARGS__ \
177 }; \
178 _brw_cmd_pack(cmd)(brw, _dw, &template); \
179 _dw + 1; /* Array starts at dw[1] */ \
180 })
181
182 #define brw_state_emit(brw, cmd, align, offset, name) \
183 for (struct cmd name = { 0, }, \
184 *_dst = brw_state_batch(brw, _brw_cmd_length(cmd) * 4, \
185 align, offset); \
186 __builtin_expect(_dst != NULL, 1); \
187 _brw_cmd_pack(cmd)(brw, (void *)_dst, &name), \
188 _dst = NULL)
189
190 /**
191 * Polygon stipple packet
192 */
193 static void
194 genX(upload_polygon_stipple)(struct brw_context *brw)
195 {
196 struct gl_context *ctx = &brw->ctx;
197
198 /* _NEW_POLYGON */
199 if (!ctx->Polygon.StippleFlag)
200 return;
201
202 brw_batch_emit(brw, GENX(3DSTATE_POLY_STIPPLE_PATTERN), poly) {
203 /* Polygon stipple is provided in OpenGL order, i.e. bottom
204 * row first. If we're rendering to a window (i.e. the
205 * default frame buffer object, 0), then we need to invert
206 * it to match our pixel layout. But if we're rendering
207 * to a FBO (i.e. any named frame buffer object), we *don't*
208 * need to invert - we already match the layout.
209 */
210 if (_mesa_is_winsys_fbo(ctx->DrawBuffer)) {
211 for (unsigned i = 0; i < 32; i++)
212 poly.PatternRow[i] = ctx->PolygonStipple[31 - i]; /* invert */
213 } else {
214 for (unsigned i = 0; i < 32; i++)
215 poly.PatternRow[i] = ctx->PolygonStipple[i];
216 }
217 }
218 }
219
220 static const struct brw_tracked_state genX(polygon_stipple) = {
221 .dirty = {
222 .mesa = _NEW_POLYGON |
223 _NEW_POLYGONSTIPPLE,
224 .brw = BRW_NEW_CONTEXT,
225 },
226 .emit = genX(upload_polygon_stipple),
227 };
228
229 /**
230 * Polygon stipple offset packet
231 */
232 static void
233 genX(upload_polygon_stipple_offset)(struct brw_context *brw)
234 {
235 struct gl_context *ctx = &brw->ctx;
236
237 /* _NEW_POLYGON */
238 if (!ctx->Polygon.StippleFlag)
239 return;
240
241 brw_batch_emit(brw, GENX(3DSTATE_POLY_STIPPLE_OFFSET), poly) {
242 /* _NEW_BUFFERS
243 *
244 * If we're drawing to a system window we have to invert the Y axis
245 * in order to match the OpenGL pixel coordinate system, and our
246 * offset must be matched to the window position. If we're drawing
247 * to a user-created FBO then our native pixel coordinate system
248 * works just fine, and there's no window system to worry about.
249 */
250 if (_mesa_is_winsys_fbo(ctx->DrawBuffer)) {
251 poly.PolygonStippleYOffset =
252 (32 - (_mesa_geometric_height(ctx->DrawBuffer) & 31)) & 31;
253 }
254 }
255 }
256
257 static const struct brw_tracked_state genX(polygon_stipple_offset) = {
258 .dirty = {
259 .mesa = _NEW_BUFFERS |
260 _NEW_POLYGON,
261 .brw = BRW_NEW_CONTEXT,
262 },
263 .emit = genX(upload_polygon_stipple_offset),
264 };
265
266 /**
267 * Line stipple packet
268 */
269 static void
270 genX(upload_line_stipple)(struct brw_context *brw)
271 {
272 struct gl_context *ctx = &brw->ctx;
273
274 if (!ctx->Line.StippleFlag)
275 return;
276
277 brw_batch_emit(brw, GENX(3DSTATE_LINE_STIPPLE), line) {
278 line.LineStipplePattern = ctx->Line.StipplePattern;
279
280 line.LineStippleInverseRepeatCount = 1.0f / ctx->Line.StippleFactor;
281 line.LineStippleRepeatCount = ctx->Line.StippleFactor;
282 }
283 }
284
285 static const struct brw_tracked_state genX(line_stipple) = {
286 .dirty = {
287 .mesa = _NEW_LINE,
288 .brw = BRW_NEW_CONTEXT,
289 },
290 .emit = genX(upload_line_stipple),
291 };
292
293 /* Constant single cliprect for framebuffer object or DRI2 drawing */
294 static void
295 genX(upload_drawing_rect)(struct brw_context *brw)
296 {
297 struct gl_context *ctx = &brw->ctx;
298 const struct gl_framebuffer *fb = ctx->DrawBuffer;
299 const unsigned int fb_width = _mesa_geometric_width(fb);
300 const unsigned int fb_height = _mesa_geometric_height(fb);
301
302 brw_batch_emit(brw, GENX(3DSTATE_DRAWING_RECTANGLE), rect) {
303 rect.ClippedDrawingRectangleXMax = fb_width - 1;
304 rect.ClippedDrawingRectangleYMax = fb_height - 1;
305 }
306 }
307
308 static const struct brw_tracked_state genX(drawing_rect) = {
309 .dirty = {
310 .mesa = _NEW_BUFFERS,
311 .brw = BRW_NEW_BLORP |
312 BRW_NEW_CONTEXT,
313 },
314 .emit = genX(upload_drawing_rect),
315 };
316
317 static uint32_t *
318 genX(emit_vertex_buffer_state)(struct brw_context *brw,
319 uint32_t *dw,
320 unsigned buffer_nr,
321 struct brw_bo *bo,
322 unsigned start_offset,
323 unsigned end_offset,
324 unsigned stride,
325 unsigned step_rate)
326 {
327 struct GENX(VERTEX_BUFFER_STATE) buf_state = {
328 .VertexBufferIndex = buffer_nr,
329 .BufferPitch = stride,
330 .BufferStartingAddress = vertex_bo(bo, start_offset),
331 #if GEN_GEN >= 8
332 .BufferSize = end_offset - start_offset,
333 #endif
334
335 #if GEN_GEN >= 7
336 .AddressModifyEnable = true,
337 #endif
338
339 #if GEN_GEN < 8
340 .BufferAccessType = step_rate ? INSTANCEDATA : VERTEXDATA,
341 .InstanceDataStepRate = step_rate,
342 #if GEN_GEN >= 5
343 .EndAddress = vertex_bo(bo, end_offset - 1),
344 #endif
345 #endif
346
347 #if GEN_GEN == 9
348 .VertexBufferMOCS = SKL_MOCS_WB,
349 #elif GEN_GEN == 8
350 .VertexBufferMOCS = BDW_MOCS_WB,
351 #elif GEN_GEN == 7
352 .VertexBufferMOCS = GEN7_MOCS_L3,
353 #endif
354 };
355
356 GENX(VERTEX_BUFFER_STATE_pack)(brw, dw, &buf_state);
357 return dw + GENX(VERTEX_BUFFER_STATE_length);
358 }
359
360 UNUSED static bool
361 is_passthru_format(uint32_t format)
362 {
363 switch (format) {
364 case ISL_FORMAT_R64_PASSTHRU:
365 case ISL_FORMAT_R64G64_PASSTHRU:
366 case ISL_FORMAT_R64G64B64_PASSTHRU:
367 case ISL_FORMAT_R64G64B64A64_PASSTHRU:
368 return true;
369 default:
370 return false;
371 }
372 }
373
374 UNUSED static int
375 uploads_needed(uint32_t format)
376 {
377 if (!is_passthru_format(format))
378 return 1;
379
380 switch (format) {
381 case ISL_FORMAT_R64_PASSTHRU:
382 case ISL_FORMAT_R64G64_PASSTHRU:
383 return 1;
384 case ISL_FORMAT_R64G64B64_PASSTHRU:
385 case ISL_FORMAT_R64G64B64A64_PASSTHRU:
386 return 2;
387 default:
388 unreachable("not reached");
389 }
390 }
391
392 /*
393 * Returns the format that we are finally going to use when upload a vertex
394 * element. It will only change if we are using *64*PASSTHRU formats, as for
395 * gen < 8 they need to be splitted on two *32*FLOAT formats.
396 *
397 * @upload points in which upload we are. Valid values are [0,1]
398 */
399 static uint32_t
400 downsize_format_if_needed(uint32_t format,
401 int upload)
402 {
403 assert(upload == 0 || upload == 1);
404
405 if (!is_passthru_format(format))
406 return format;
407
408 switch (format) {
409 case ISL_FORMAT_R64_PASSTHRU:
410 return ISL_FORMAT_R32G32_FLOAT;
411 case ISL_FORMAT_R64G64_PASSTHRU:
412 return ISL_FORMAT_R32G32B32A32_FLOAT;
413 case ISL_FORMAT_R64G64B64_PASSTHRU:
414 return !upload ? ISL_FORMAT_R32G32B32A32_FLOAT
415 : ISL_FORMAT_R32G32_FLOAT;
416 case ISL_FORMAT_R64G64B64A64_PASSTHRU:
417 return ISL_FORMAT_R32G32B32A32_FLOAT;
418 default:
419 unreachable("not reached");
420 }
421 }
422
423 /*
424 * Returns the number of componentes associated with a format that is used on
425 * a 64 to 32 format split. See downsize_format()
426 */
427 static int
428 upload_format_size(uint32_t upload_format)
429 {
430 switch (upload_format) {
431 case ISL_FORMAT_R32G32_FLOAT:
432 return 2;
433 case ISL_FORMAT_R32G32B32A32_FLOAT:
434 return 4;
435 default:
436 unreachable("not reached");
437 }
438 }
439
440 static void
441 genX(emit_vertices)(struct brw_context *brw)
442 {
443 uint32_t *dw;
444
445 brw_prepare_vertices(brw);
446 brw_prepare_shader_draw_parameters(brw);
447
448 #if GEN_GEN < 6
449 brw_emit_query_begin(brw);
450 #endif
451
452 const struct brw_vs_prog_data *vs_prog_data =
453 brw_vs_prog_data(brw->vs.base.prog_data);
454
455 #if GEN_GEN >= 8
456 struct gl_context *ctx = &brw->ctx;
457 const bool uses_edge_flag = (ctx->Polygon.FrontMode != GL_FILL ||
458 ctx->Polygon.BackMode != GL_FILL);
459
460 if (vs_prog_data->uses_vertexid || vs_prog_data->uses_instanceid) {
461 unsigned vue = brw->vb.nr_enabled;
462
463 /* The element for the edge flags must always be last, so we have to
464 * insert the SGVS before it in that case.
465 */
466 if (uses_edge_flag) {
467 assert(vue > 0);
468 vue--;
469 }
470
471 WARN_ONCE(vue >= 33,
472 "Trying to insert VID/IID past 33rd vertex element, "
473 "need to reorder the vertex attrbutes.");
474
475 brw_batch_emit(brw, GENX(3DSTATE_VF_SGVS), vfs) {
476 if (vs_prog_data->uses_vertexid) {
477 vfs.VertexIDEnable = true;
478 vfs.VertexIDComponentNumber = 2;
479 vfs.VertexIDElementOffset = vue;
480 }
481
482 if (vs_prog_data->uses_instanceid) {
483 vfs.InstanceIDEnable = true;
484 vfs.InstanceIDComponentNumber = 3;
485 vfs.InstanceIDElementOffset = vue;
486 }
487 }
488
489 brw_batch_emit(brw, GENX(3DSTATE_VF_INSTANCING), vfi) {
490 vfi.InstancingEnable = true;
491 vfi.VertexElementIndex = vue;
492 }
493 } else {
494 brw_batch_emit(brw, GENX(3DSTATE_VF_SGVS), vfs);
495 }
496
497 /* Normally we don't need an element for the SGVS attribute because the
498 * 3DSTATE_VF_SGVS instruction lets you store the generated attribute in an
499 * element that is past the list in 3DSTATE_VERTEX_ELEMENTS. However if
500 * we're using draw parameters then we need an element for the those
501 * values. Additionally if there is an edge flag element then the SGVS
502 * can't be inserted past that so we need a dummy element to ensure that
503 * the edge flag is the last one.
504 */
505 const bool needs_sgvs_element = (vs_prog_data->uses_basevertex ||
506 vs_prog_data->uses_baseinstance ||
507 ((vs_prog_data->uses_instanceid ||
508 vs_prog_data->uses_vertexid)
509 && uses_edge_flag));
510 #else
511 const bool needs_sgvs_element = (vs_prog_data->uses_basevertex ||
512 vs_prog_data->uses_baseinstance ||
513 vs_prog_data->uses_instanceid ||
514 vs_prog_data->uses_vertexid);
515 #endif
516 unsigned nr_elements =
517 brw->vb.nr_enabled + needs_sgvs_element + vs_prog_data->uses_drawid;
518
519 #if GEN_GEN < 8
520 /* If any of the formats of vb.enabled needs more that one upload, we need
521 * to add it to nr_elements
522 */
523 for (unsigned i = 0; i < brw->vb.nr_enabled; i++) {
524 struct brw_vertex_element *input = brw->vb.enabled[i];
525 uint32_t format = brw_get_vertex_surface_type(brw, input->glarray);
526
527 if (uploads_needed(format) > 1)
528 nr_elements++;
529 }
530 #endif
531
532 /* If the VS doesn't read any inputs (calculating vertex position from
533 * a state variable for some reason, for example), emit a single pad
534 * VERTEX_ELEMENT struct and bail.
535 *
536 * The stale VB state stays in place, but they don't do anything unless
537 * a VE loads from them.
538 */
539 if (nr_elements == 0) {
540 dw = brw_batch_emitn(brw, GENX(3DSTATE_VERTEX_ELEMENTS),
541 1 + GENX(VERTEX_ELEMENT_STATE_length));
542 struct GENX(VERTEX_ELEMENT_STATE) elem = {
543 .Valid = true,
544 .SourceElementFormat = ISL_FORMAT_R32G32B32A32_FLOAT,
545 .Component0Control = VFCOMP_STORE_0,
546 .Component1Control = VFCOMP_STORE_0,
547 .Component2Control = VFCOMP_STORE_0,
548 .Component3Control = VFCOMP_STORE_1_FP,
549 };
550 GENX(VERTEX_ELEMENT_STATE_pack)(brw, dw, &elem);
551 return;
552 }
553
554 /* Now emit 3DSTATE_VERTEX_BUFFERS and 3DSTATE_VERTEX_ELEMENTS packets. */
555 const bool uses_draw_params =
556 vs_prog_data->uses_basevertex ||
557 vs_prog_data->uses_baseinstance;
558 const unsigned nr_buffers = brw->vb.nr_buffers +
559 uses_draw_params + vs_prog_data->uses_drawid;
560
561 if (nr_buffers) {
562 assert(nr_buffers <= (GEN_GEN >= 6 ? 33 : 17));
563
564 dw = brw_batch_emitn(brw, GENX(3DSTATE_VERTEX_BUFFERS),
565 1 + GENX(VERTEX_BUFFER_STATE_length) * nr_buffers);
566
567 for (unsigned i = 0; i < brw->vb.nr_buffers; i++) {
568 const struct brw_vertex_buffer *buffer = &brw->vb.buffers[i];
569 /* Prior to Haswell and Bay Trail we have to use 4-component formats
570 * to fake 3-component ones. In particular, we do this for
571 * half-float and 8 and 16-bit integer formats. This means that the
572 * vertex element may poke over the end of the buffer by 2 bytes.
573 */
574 const unsigned padding =
575 (GEN_GEN <= 7 && !brw->is_baytrail && !brw->is_haswell) * 2;
576 const unsigned end = buffer->offset + buffer->size + padding;
577 dw = genX(emit_vertex_buffer_state)(brw, dw, i, buffer->bo,
578 buffer->offset,
579 end,
580 buffer->stride,
581 buffer->step_rate);
582 }
583
584 if (uses_draw_params) {
585 dw = genX(emit_vertex_buffer_state)(brw, dw, brw->vb.nr_buffers,
586 brw->draw.draw_params_bo,
587 brw->draw.draw_params_offset,
588 brw->draw.draw_params_bo->size,
589 0 /* stride */,
590 0 /* step rate */);
591 }
592
593 if (vs_prog_data->uses_drawid) {
594 dw = genX(emit_vertex_buffer_state)(brw, dw, brw->vb.nr_buffers + 1,
595 brw->draw.draw_id_bo,
596 brw->draw.draw_id_offset,
597 brw->draw.draw_id_bo->size,
598 0 /* stride */,
599 0 /* step rate */);
600 }
601 }
602
603 /* The hardware allows one more VERTEX_ELEMENTS than VERTEX_BUFFERS,
604 * presumably for VertexID/InstanceID.
605 */
606 #if GEN_GEN >= 6
607 assert(nr_elements <= 34);
608 const struct brw_vertex_element *gen6_edgeflag_input = NULL;
609 #else
610 assert(nr_elements <= 18);
611 #endif
612
613 dw = brw_batch_emitn(brw, GENX(3DSTATE_VERTEX_ELEMENTS),
614 1 + GENX(VERTEX_ELEMENT_STATE_length) * nr_elements);
615 unsigned i;
616 for (i = 0; i < brw->vb.nr_enabled; i++) {
617 const struct brw_vertex_element *input = brw->vb.enabled[i];
618 uint32_t format = brw_get_vertex_surface_type(brw, input->glarray);
619 uint32_t comp0 = VFCOMP_STORE_SRC;
620 uint32_t comp1 = VFCOMP_STORE_SRC;
621 uint32_t comp2 = VFCOMP_STORE_SRC;
622 uint32_t comp3 = VFCOMP_STORE_SRC;
623 const unsigned num_uploads = GEN_GEN < 8 ? uploads_needed(format) : 1;
624
625 #if GEN_GEN >= 8
626 /* From the BDW PRM, Volume 2d, page 588 (VERTEX_ELEMENT_STATE):
627 * "Any SourceElementFormat of *64*_PASSTHRU cannot be used with an
628 * element which has edge flag enabled."
629 */
630 assert(!(is_passthru_format(format) && uses_edge_flag));
631 #endif
632
633 /* The gen4 driver expects edgeflag to come in as a float, and passes
634 * that float on to the tests in the clipper. Mesa's current vertex
635 * attribute value for EdgeFlag is stored as a float, which works out.
636 * glEdgeFlagPointer, on the other hand, gives us an unnormalized
637 * integer ubyte. Just rewrite that to convert to a float.
638 *
639 * Gen6+ passes edgeflag as sideband along with the vertex, instead
640 * of in the VUE. We have to upload it sideband as the last vertex
641 * element according to the B-Spec.
642 */
643 #if GEN_GEN >= 6
644 if (input == &brw->vb.inputs[VERT_ATTRIB_EDGEFLAG]) {
645 gen6_edgeflag_input = input;
646 continue;
647 }
648 #endif
649
650 for (unsigned c = 0; c < num_uploads; c++) {
651 const uint32_t upload_format = GEN_GEN >= 8 ? format :
652 downsize_format_if_needed(format, c);
653 /* If we need more that one upload, the offset stride would be 128
654 * bits (16 bytes), as for previous uploads we are using the full
655 * entry. */
656 const unsigned offset = input->offset + c * 16;
657
658 const int size = (GEN_GEN < 8 && is_passthru_format(format)) ?
659 upload_format_size(upload_format) : input->glarray->Size;
660
661 switch (size) {
662 case 0: comp0 = VFCOMP_STORE_0;
663 case 1: comp1 = VFCOMP_STORE_0;
664 case 2: comp2 = VFCOMP_STORE_0;
665 case 3:
666 if (GEN_GEN >= 8 && input->glarray->Doubles) {
667 comp3 = VFCOMP_STORE_0;
668 } else if (input->glarray->Integer) {
669 comp3 = VFCOMP_STORE_1_INT;
670 } else {
671 comp3 = VFCOMP_STORE_1_FP;
672 }
673
674 break;
675 }
676
677 #if GEN_GEN >= 8
678 /* From the BDW PRM, Volume 2d, page 586 (VERTEX_ELEMENT_STATE):
679 *
680 * "When SourceElementFormat is set to one of the *64*_PASSTHRU
681 * formats, 64-bit components are stored in the URB without any
682 * conversion. In this case, vertex elements must be written as 128
683 * or 256 bits, with VFCOMP_STORE_0 being used to pad the output as
684 * required. E.g., if R64_PASSTHRU is used to copy a 64-bit Red
685 * component into the URB, Component 1 must be specified as
686 * VFCOMP_STORE_0 (with Components 2,3 set to VFCOMP_NOSTORE) in
687 * order to output a 128-bit vertex element, or Components 1-3 must
688 * be specified as VFCOMP_STORE_0 in order to output a 256-bit vertex
689 * element. Likewise, use of R64G64B64_PASSTHRU requires Component 3
690 * to be specified as VFCOMP_STORE_0 in order to output a 256-bit
691 * vertex element."
692 */
693 if (input->glarray->Doubles && !input->is_dual_slot) {
694 /* Store vertex elements which correspond to double and dvec2 vertex
695 * shader inputs as 128-bit vertex elements, instead of 256-bits.
696 */
697 comp2 = VFCOMP_NOSTORE;
698 comp3 = VFCOMP_NOSTORE;
699 }
700 #endif
701
702 struct GENX(VERTEX_ELEMENT_STATE) elem_state = {
703 .VertexBufferIndex = input->buffer,
704 .Valid = true,
705 .SourceElementFormat = upload_format,
706 .SourceElementOffset = offset,
707 .Component0Control = comp0,
708 .Component1Control = comp1,
709 .Component2Control = comp2,
710 .Component3Control = comp3,
711 #if GEN_GEN < 5
712 .DestinationElementOffset = i * 4,
713 #endif
714 };
715
716 GENX(VERTEX_ELEMENT_STATE_pack)(brw, dw, &elem_state);
717 dw += GENX(VERTEX_ELEMENT_STATE_length);
718 }
719 }
720
721 if (needs_sgvs_element) {
722 struct GENX(VERTEX_ELEMENT_STATE) elem_state = {
723 .Valid = true,
724 .Component0Control = VFCOMP_STORE_0,
725 .Component1Control = VFCOMP_STORE_0,
726 .Component2Control = VFCOMP_STORE_0,
727 .Component3Control = VFCOMP_STORE_0,
728 #if GEN_GEN < 5
729 .DestinationElementOffset = i * 4,
730 #endif
731 };
732
733 #if GEN_GEN >= 8
734 if (vs_prog_data->uses_basevertex ||
735 vs_prog_data->uses_baseinstance) {
736 elem_state.VertexBufferIndex = brw->vb.nr_buffers;
737 elem_state.SourceElementFormat = ISL_FORMAT_R32G32_UINT;
738 elem_state.Component0Control = VFCOMP_STORE_SRC;
739 elem_state.Component1Control = VFCOMP_STORE_SRC;
740 }
741 #else
742 elem_state.VertexBufferIndex = brw->vb.nr_buffers;
743 elem_state.SourceElementFormat = ISL_FORMAT_R32G32_UINT;
744 if (vs_prog_data->uses_basevertex)
745 elem_state.Component0Control = VFCOMP_STORE_SRC;
746
747 if (vs_prog_data->uses_baseinstance)
748 elem_state.Component1Control = VFCOMP_STORE_SRC;
749
750 if (vs_prog_data->uses_vertexid)
751 elem_state.Component2Control = VFCOMP_STORE_VID;
752
753 if (vs_prog_data->uses_instanceid)
754 elem_state.Component3Control = VFCOMP_STORE_IID;
755 #endif
756
757 GENX(VERTEX_ELEMENT_STATE_pack)(brw, dw, &elem_state);
758 dw += GENX(VERTEX_ELEMENT_STATE_length);
759 }
760
761 if (vs_prog_data->uses_drawid) {
762 struct GENX(VERTEX_ELEMENT_STATE) elem_state = {
763 .Valid = true,
764 .VertexBufferIndex = brw->vb.nr_buffers + 1,
765 .SourceElementFormat = ISL_FORMAT_R32_UINT,
766 .Component0Control = VFCOMP_STORE_SRC,
767 .Component1Control = VFCOMP_STORE_0,
768 .Component2Control = VFCOMP_STORE_0,
769 .Component3Control = VFCOMP_STORE_0,
770 #if GEN_GEN < 5
771 .DestinationElementOffset = i * 4,
772 #endif
773 };
774
775 GENX(VERTEX_ELEMENT_STATE_pack)(brw, dw, &elem_state);
776 dw += GENX(VERTEX_ELEMENT_STATE_length);
777 }
778
779 #if GEN_GEN >= 6
780 if (gen6_edgeflag_input) {
781 const uint32_t format =
782 brw_get_vertex_surface_type(brw, gen6_edgeflag_input->glarray);
783
784 struct GENX(VERTEX_ELEMENT_STATE) elem_state = {
785 .Valid = true,
786 .VertexBufferIndex = gen6_edgeflag_input->buffer,
787 .EdgeFlagEnable = true,
788 .SourceElementFormat = format,
789 .SourceElementOffset = gen6_edgeflag_input->offset,
790 .Component0Control = VFCOMP_STORE_SRC,
791 .Component1Control = VFCOMP_STORE_0,
792 .Component2Control = VFCOMP_STORE_0,
793 .Component3Control = VFCOMP_STORE_0,
794 };
795
796 GENX(VERTEX_ELEMENT_STATE_pack)(brw, dw, &elem_state);
797 dw += GENX(VERTEX_ELEMENT_STATE_length);
798 }
799 #endif
800
801 #if GEN_GEN >= 8
802 for (unsigned i = 0, j = 0; i < brw->vb.nr_enabled; i++) {
803 const struct brw_vertex_element *input = brw->vb.enabled[i];
804 const struct brw_vertex_buffer *buffer = &brw->vb.buffers[input->buffer];
805 unsigned element_index;
806
807 /* The edge flag element is reordered to be the last one in the code
808 * above so we need to compensate for that in the element indices used
809 * below.
810 */
811 if (input == gen6_edgeflag_input)
812 element_index = nr_elements - 1;
813 else
814 element_index = j++;
815
816 brw_batch_emit(brw, GENX(3DSTATE_VF_INSTANCING), vfi) {
817 vfi.VertexElementIndex = element_index;
818 vfi.InstancingEnable = buffer->step_rate != 0;
819 vfi.InstanceDataStepRate = buffer->step_rate;
820 }
821 }
822
823 if (vs_prog_data->uses_drawid) {
824 const unsigned element = brw->vb.nr_enabled + needs_sgvs_element;
825
826 brw_batch_emit(brw, GENX(3DSTATE_VF_INSTANCING), vfi) {
827 vfi.VertexElementIndex = element;
828 }
829 }
830 #endif
831 }
832
833 static const struct brw_tracked_state genX(vertices) = {
834 .dirty = {
835 .mesa = _NEW_POLYGON,
836 .brw = BRW_NEW_BATCH |
837 BRW_NEW_BLORP |
838 BRW_NEW_VERTICES |
839 BRW_NEW_VS_PROG_DATA,
840 },
841 .emit = genX(emit_vertices),
842 };
843
844 static void
845 genX(emit_index_buffer)(struct brw_context *brw)
846 {
847 const struct _mesa_index_buffer *index_buffer = brw->ib.ib;
848
849 if (index_buffer == NULL)
850 return;
851
852 brw_batch_emit(brw, GENX(3DSTATE_INDEX_BUFFER), ib) {
853 #if GEN_GEN < 8 && !GEN_IS_HASWELL
854 ib.CutIndexEnable = brw->prim_restart.enable_cut_index;
855 #endif
856 ib.IndexFormat = brw_get_index_type(index_buffer->index_size);
857 ib.BufferStartingAddress = vertex_bo(brw->ib.bo, 0);
858 #if GEN_GEN >= 8
859 ib.IndexBufferMOCS = GEN_GEN >= 9 ? SKL_MOCS_WB : BDW_MOCS_WB;
860 ib.BufferSize = brw->ib.size;
861 #else
862 ib.BufferEndingAddress = vertex_bo(brw->ib.bo, brw->ib.size - 1);
863 #endif
864 }
865 }
866
867 static const struct brw_tracked_state genX(index_buffer) = {
868 .dirty = {
869 .mesa = 0,
870 .brw = BRW_NEW_BATCH |
871 BRW_NEW_BLORP |
872 BRW_NEW_INDEX_BUFFER,
873 },
874 .emit = genX(emit_index_buffer),
875 };
876
877 #if GEN_IS_HASWELL || GEN_GEN >= 8
878 static void
879 genX(upload_cut_index)(struct brw_context *brw)
880 {
881 const struct gl_context *ctx = &brw->ctx;
882
883 brw_batch_emit(brw, GENX(3DSTATE_VF), vf) {
884 if (ctx->Array._PrimitiveRestart && brw->ib.ib) {
885 vf.IndexedDrawCutIndexEnable = true;
886 vf.CutIndex = _mesa_primitive_restart_index(ctx, brw->ib.index_size);
887 }
888 }
889 }
890
891 const struct brw_tracked_state genX(cut_index) = {
892 .dirty = {
893 .mesa = _NEW_TRANSFORM,
894 .brw = BRW_NEW_INDEX_BUFFER,
895 },
896 .emit = genX(upload_cut_index),
897 };
898 #endif
899
900 #if GEN_GEN >= 6
901 /**
902 * Determine the appropriate attribute override value to store into the
903 * 3DSTATE_SF structure for a given fragment shader attribute. The attribute
904 * override value contains two pieces of information: the location of the
905 * attribute in the VUE (relative to urb_entry_read_offset, see below), and a
906 * flag indicating whether to "swizzle" the attribute based on the direction
907 * the triangle is facing.
908 *
909 * If an attribute is "swizzled", then the given VUE location is used for
910 * front-facing triangles, and the VUE location that immediately follows is
911 * used for back-facing triangles. We use this to implement the mapping from
912 * gl_FrontColor/gl_BackColor to gl_Color.
913 *
914 * urb_entry_read_offset is the offset into the VUE at which the SF unit is
915 * being instructed to begin reading attribute data. It can be set to a
916 * nonzero value to prevent the SF unit from wasting time reading elements of
917 * the VUE that are not needed by the fragment shader. It is measured in
918 * 256-bit increments.
919 */
920 static void
921 genX(get_attr_override)(struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) *attr,
922 const struct brw_vue_map *vue_map,
923 int urb_entry_read_offset, int fs_attr,
924 bool two_side_color, uint32_t *max_source_attr)
925 {
926 /* Find the VUE slot for this attribute. */
927 int slot = vue_map->varying_to_slot[fs_attr];
928
929 /* Viewport and Layer are stored in the VUE header. We need to override
930 * them to zero if earlier stages didn't write them, as GL requires that
931 * they read back as zero when not explicitly set.
932 */
933 if (fs_attr == VARYING_SLOT_VIEWPORT || fs_attr == VARYING_SLOT_LAYER) {
934 attr->ComponentOverrideX = true;
935 attr->ComponentOverrideW = true;
936 attr->ConstantSource = CONST_0000;
937
938 if (!(vue_map->slots_valid & VARYING_BIT_LAYER))
939 attr->ComponentOverrideY = true;
940 if (!(vue_map->slots_valid & VARYING_BIT_VIEWPORT))
941 attr->ComponentOverrideZ = true;
942
943 return;
944 }
945
946 /* If there was only a back color written but not front, use back
947 * as the color instead of undefined
948 */
949 if (slot == -1 && fs_attr == VARYING_SLOT_COL0)
950 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC0];
951 if (slot == -1 && fs_attr == VARYING_SLOT_COL1)
952 slot = vue_map->varying_to_slot[VARYING_SLOT_BFC1];
953
954 if (slot == -1) {
955 /* This attribute does not exist in the VUE--that means that the vertex
956 * shader did not write to it. This means that either:
957 *
958 * (a) This attribute is a texture coordinate, and it is going to be
959 * replaced with point coordinates (as a consequence of a call to
960 * glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE)), so the
961 * hardware will ignore whatever attribute override we supply.
962 *
963 * (b) This attribute is read by the fragment shader but not written by
964 * the vertex shader, so its value is undefined. Therefore the
965 * attribute override we supply doesn't matter.
966 *
967 * (c) This attribute is gl_PrimitiveID, and it wasn't written by the
968 * previous shader stage.
969 *
970 * Note that we don't have to worry about the cases where the attribute
971 * is gl_PointCoord or is undergoing point sprite coordinate
972 * replacement, because in those cases, this function isn't called.
973 *
974 * In case (c), we need to program the attribute overrides so that the
975 * primitive ID will be stored in this slot. In every other case, the
976 * attribute override we supply doesn't matter. So just go ahead and
977 * program primitive ID in every case.
978 */
979 attr->ComponentOverrideW = true;
980 attr->ComponentOverrideX = true;
981 attr->ComponentOverrideY = true;
982 attr->ComponentOverrideZ = true;
983 attr->ConstantSource = PRIM_ID;
984 return;
985 }
986
987 /* Compute the location of the attribute relative to urb_entry_read_offset.
988 * Each increment of urb_entry_read_offset represents a 256-bit value, so
989 * it counts for two 128-bit VUE slots.
990 */
991 int source_attr = slot - 2 * urb_entry_read_offset;
992 assert(source_attr >= 0 && source_attr < 32);
993
994 /* If we are doing two-sided color, and the VUE slot following this one
995 * represents a back-facing color, then we need to instruct the SF unit to
996 * do back-facing swizzling.
997 */
998 bool swizzling = two_side_color &&
999 ((vue_map->slot_to_varying[slot] == VARYING_SLOT_COL0 &&
1000 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC0) ||
1001 (vue_map->slot_to_varying[slot] == VARYING_SLOT_COL1 &&
1002 vue_map->slot_to_varying[slot+1] == VARYING_SLOT_BFC1));
1003
1004 /* Update max_source_attr. If swizzling, the SF will read this slot + 1. */
1005 if (*max_source_attr < source_attr + swizzling)
1006 *max_source_attr = source_attr + swizzling;
1007
1008 attr->SourceAttribute = source_attr;
1009 if (swizzling)
1010 attr->SwizzleSelect = INPUTATTR_FACING;
1011 }
1012
1013
1014 static void
1015 genX(calculate_attr_overrides)(const struct brw_context *brw,
1016 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) *attr_overrides,
1017 uint32_t *point_sprite_enables,
1018 uint32_t *urb_entry_read_length,
1019 uint32_t *urb_entry_read_offset)
1020 {
1021 const struct gl_context *ctx = &brw->ctx;
1022
1023 /* _NEW_POINT */
1024 const struct gl_point_attrib *point = &ctx->Point;
1025
1026 /* BRW_NEW_FS_PROG_DATA */
1027 const struct brw_wm_prog_data *wm_prog_data =
1028 brw_wm_prog_data(brw->wm.base.prog_data);
1029 uint32_t max_source_attr = 0;
1030
1031 *point_sprite_enables = 0;
1032
1033 /* BRW_NEW_FRAGMENT_PROGRAM
1034 *
1035 * If the fragment shader reads VARYING_SLOT_LAYER, then we need to pass in
1036 * the full vertex header. Otherwise, we can program the SF to start
1037 * reading at an offset of 1 (2 varying slots) to skip unnecessary data:
1038 * - VARYING_SLOT_PSIZ and BRW_VARYING_SLOT_NDC on gen4-5
1039 * - VARYING_SLOT_{PSIZ,LAYER} and VARYING_SLOT_POS on gen6+
1040 */
1041
1042 bool fs_needs_vue_header = brw->fragment_program->info.inputs_read &
1043 (VARYING_BIT_LAYER | VARYING_BIT_VIEWPORT);
1044
1045 *urb_entry_read_offset = fs_needs_vue_header ? 0 : 1;
1046
1047 /* From the Ivybridge PRM, Vol 2 Part 1, 3DSTATE_SBE,
1048 * description of dw10 Point Sprite Texture Coordinate Enable:
1049 *
1050 * "This field must be programmed to zero when non-point primitives
1051 * are rendered."
1052 *
1053 * The SandyBridge PRM doesn't explicitly say that point sprite enables
1054 * must be programmed to zero when rendering non-point primitives, but
1055 * the IvyBridge PRM does, and if we don't, we get garbage.
1056 *
1057 * This is not required on Haswell, as the hardware ignores this state
1058 * when drawing non-points -- although we do still need to be careful to
1059 * correctly set the attr overrides.
1060 *
1061 * _NEW_POLYGON
1062 * BRW_NEW_PRIMITIVE | BRW_NEW_GS_PROG_DATA | BRW_NEW_TES_PROG_DATA
1063 */
1064 bool drawing_points = brw_is_drawing_points(brw);
1065
1066 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
1067 int input_index = wm_prog_data->urb_setup[attr];
1068
1069 if (input_index < 0)
1070 continue;
1071
1072 /* _NEW_POINT */
1073 bool point_sprite = false;
1074 if (drawing_points) {
1075 if (point->PointSprite &&
1076 (attr >= VARYING_SLOT_TEX0 && attr <= VARYING_SLOT_TEX7) &&
1077 (point->CoordReplace & (1u << (attr - VARYING_SLOT_TEX0)))) {
1078 point_sprite = true;
1079 }
1080
1081 if (attr == VARYING_SLOT_PNTC)
1082 point_sprite = true;
1083
1084 if (point_sprite)
1085 *point_sprite_enables |= (1 << input_index);
1086 }
1087
1088 /* BRW_NEW_VUE_MAP_GEOM_OUT | _NEW_LIGHT | _NEW_PROGRAM */
1089 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) attribute = { 0 };
1090
1091 if (!point_sprite) {
1092 genX(get_attr_override)(&attribute,
1093 &brw->vue_map_geom_out,
1094 *urb_entry_read_offset, attr,
1095 brw->ctx.VertexProgram._TwoSideEnabled,
1096 &max_source_attr);
1097 }
1098
1099 /* The hardware can only do the overrides on 16 overrides at a
1100 * time, and the other up to 16 have to be lined up so that the
1101 * input index = the output index. We'll need to do some
1102 * tweaking to make sure that's the case.
1103 */
1104 if (input_index < 16)
1105 attr_overrides[input_index] = attribute;
1106 else
1107 assert(attribute.SourceAttribute == input_index);
1108 }
1109
1110 /* From the Sandy Bridge PRM, Volume 2, Part 1, documentation for
1111 * 3DSTATE_SF DWord 1 bits 15:11, "Vertex URB Entry Read Length":
1112 *
1113 * "This field should be set to the minimum length required to read the
1114 * maximum source attribute. The maximum source attribute is indicated
1115 * by the maximum value of the enabled Attribute # Source Attribute if
1116 * Attribute Swizzle Enable is set, Number of Output Attributes-1 if
1117 * enable is not set.
1118 * read_length = ceiling((max_source_attr + 1) / 2)
1119 *
1120 * [errata] Corruption/Hang possible if length programmed larger than
1121 * recommended"
1122 *
1123 * Similar text exists for Ivy Bridge.
1124 */
1125 *urb_entry_read_length = DIV_ROUND_UP(max_source_attr + 1, 2);
1126 }
1127 #endif
1128
1129 /* ---------------------------------------------------------------------- */
1130
1131 #if GEN_GEN >= 6
1132 static void
1133 genX(upload_depth_stencil_state)(struct brw_context *brw)
1134 {
1135 struct gl_context *ctx = &brw->ctx;
1136
1137 /* _NEW_BUFFERS */
1138 struct intel_renderbuffer *depth_irb =
1139 intel_get_renderbuffer(ctx->DrawBuffer, BUFFER_DEPTH);
1140
1141 /* _NEW_DEPTH */
1142 struct gl_depthbuffer_attrib *depth = &ctx->Depth;
1143
1144 /* _NEW_STENCIL */
1145 struct gl_stencil_attrib *stencil = &ctx->Stencil;
1146 const int b = stencil->_BackFace;
1147
1148 #if GEN_GEN >= 8
1149 brw_batch_emit(brw, GENX(3DSTATE_WM_DEPTH_STENCIL), wmds) {
1150 #else
1151 uint32_t ds_offset;
1152 brw_state_emit(brw, GENX(DEPTH_STENCIL_STATE), 64, &ds_offset, wmds) {
1153 #endif
1154 if (depth->Test && depth_irb) {
1155 wmds.DepthTestEnable = true;
1156 wmds.DepthBufferWriteEnable = brw_depth_writes_enabled(brw);
1157 wmds.DepthTestFunction = intel_translate_compare_func(depth->Func);
1158 }
1159
1160 if (stencil->_Enabled) {
1161 wmds.StencilTestEnable = true;
1162 wmds.StencilWriteMask = stencil->WriteMask[0] & 0xff;
1163 wmds.StencilTestMask = stencil->ValueMask[0] & 0xff;
1164
1165 wmds.StencilTestFunction =
1166 intel_translate_compare_func(stencil->Function[0]);
1167 wmds.StencilFailOp =
1168 intel_translate_stencil_op(stencil->FailFunc[0]);
1169 wmds.StencilPassDepthPassOp =
1170 intel_translate_stencil_op(stencil->ZPassFunc[0]);
1171 wmds.StencilPassDepthFailOp =
1172 intel_translate_stencil_op(stencil->ZFailFunc[0]);
1173
1174 wmds.StencilBufferWriteEnable = stencil->_WriteEnabled;
1175
1176 if (stencil->_TestTwoSide) {
1177 wmds.DoubleSidedStencilEnable = true;
1178 wmds.BackfaceStencilWriteMask = stencil->WriteMask[b] & 0xff;
1179 wmds.BackfaceStencilTestMask = stencil->ValueMask[b] & 0xff;
1180
1181 wmds.BackfaceStencilTestFunction =
1182 intel_translate_compare_func(stencil->Function[b]);
1183 wmds.BackfaceStencilFailOp =
1184 intel_translate_stencil_op(stencil->FailFunc[b]);
1185 wmds.BackfaceStencilPassDepthPassOp =
1186 intel_translate_stencil_op(stencil->ZPassFunc[b]);
1187 wmds.BackfaceStencilPassDepthFailOp =
1188 intel_translate_stencil_op(stencil->ZFailFunc[b]);
1189 }
1190
1191 #if GEN_GEN >= 9
1192 wmds.StencilReferenceValue = _mesa_get_stencil_ref(ctx, 0);
1193 wmds.BackfaceStencilReferenceValue = _mesa_get_stencil_ref(ctx, b);
1194 #endif
1195 }
1196 }
1197
1198 #if GEN_GEN == 6
1199 brw_batch_emit(brw, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
1200 ptr.PointertoDEPTH_STENCIL_STATE = ds_offset;
1201 ptr.DEPTH_STENCIL_STATEChange = true;
1202 }
1203 #elif GEN_GEN == 7
1204 brw_batch_emit(brw, GENX(3DSTATE_DEPTH_STENCIL_STATE_POINTERS), ptr) {
1205 ptr.PointertoDEPTH_STENCIL_STATE = ds_offset;
1206 }
1207 #endif
1208 }
1209
1210 static const struct brw_tracked_state genX(depth_stencil_state) = {
1211 .dirty = {
1212 .mesa = _NEW_BUFFERS |
1213 _NEW_DEPTH |
1214 _NEW_STENCIL,
1215 .brw = BRW_NEW_BLORP |
1216 (GEN_GEN >= 8 ? BRW_NEW_CONTEXT
1217 : BRW_NEW_BATCH |
1218 BRW_NEW_STATE_BASE_ADDRESS),
1219 },
1220 .emit = genX(upload_depth_stencil_state),
1221 };
1222 #endif
1223
1224 /* ---------------------------------------------------------------------- */
1225
1226 #if GEN_GEN >= 6
1227 static void
1228 genX(upload_clip_state)(struct brw_context *brw)
1229 {
1230 struct gl_context *ctx = &brw->ctx;
1231
1232 /* _NEW_BUFFERS */
1233 struct gl_framebuffer *fb = ctx->DrawBuffer;
1234
1235 /* BRW_NEW_FS_PROG_DATA */
1236 struct brw_wm_prog_data *wm_prog_data =
1237 brw_wm_prog_data(brw->wm.base.prog_data);
1238
1239 brw_batch_emit(brw, GENX(3DSTATE_CLIP), clip) {
1240 clip.StatisticsEnable = !brw->meta_in_progress;
1241
1242 if (wm_prog_data->barycentric_interp_modes &
1243 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS)
1244 clip.NonPerspectiveBarycentricEnable = true;
1245
1246 #if GEN_GEN >= 7
1247 clip.EarlyCullEnable = true;
1248 #endif
1249
1250 #if GEN_GEN == 7
1251 clip.FrontWinding = ctx->Polygon._FrontBit == _mesa_is_user_fbo(fb);
1252
1253 if (ctx->Polygon.CullFlag) {
1254 switch (ctx->Polygon.CullFaceMode) {
1255 case GL_FRONT:
1256 clip.CullMode = CULLMODE_FRONT;
1257 break;
1258 case GL_BACK:
1259 clip.CullMode = CULLMODE_BACK;
1260 break;
1261 case GL_FRONT_AND_BACK:
1262 clip.CullMode = CULLMODE_BOTH;
1263 break;
1264 default:
1265 unreachable("Should not get here: invalid CullFlag");
1266 }
1267 } else {
1268 clip.CullMode = CULLMODE_NONE;
1269 }
1270 #endif
1271
1272 #if GEN_GEN < 8
1273 clip.UserClipDistanceCullTestEnableBitmask =
1274 brw_vue_prog_data(brw->vs.base.prog_data)->cull_distance_mask;
1275
1276 clip.ViewportZClipTestEnable = !ctx->Transform.DepthClamp;
1277 #endif
1278
1279 /* _NEW_LIGHT */
1280 if (ctx->Light.ProvokingVertex == GL_FIRST_VERTEX_CONVENTION) {
1281 clip.TriangleStripListProvokingVertexSelect = 0;
1282 clip.TriangleFanProvokingVertexSelect = 1;
1283 clip.LineStripListProvokingVertexSelect = 0;
1284 } else {
1285 clip.TriangleStripListProvokingVertexSelect = 2;
1286 clip.TriangleFanProvokingVertexSelect = 2;
1287 clip.LineStripListProvokingVertexSelect = 1;
1288 }
1289
1290 /* _NEW_TRANSFORM */
1291 clip.UserClipDistanceClipTestEnableBitmask =
1292 ctx->Transform.ClipPlanesEnabled;
1293
1294 #if GEN_GEN >= 8
1295 clip.ForceUserClipDistanceClipTestEnableBitmask = true;
1296 #endif
1297
1298 if (ctx->Transform.ClipDepthMode == GL_ZERO_TO_ONE)
1299 clip.APIMode = APIMODE_D3D;
1300 else
1301 clip.APIMode = APIMODE_OGL;
1302
1303 clip.GuardbandClipTestEnable = true;
1304
1305 /* BRW_NEW_VIEWPORT_COUNT */
1306 const unsigned viewport_count = brw->clip.viewport_count;
1307
1308 if (ctx->RasterDiscard) {
1309 clip.ClipMode = CLIPMODE_REJECT_ALL;
1310 #if GEN_GEN == 6
1311 perf_debug("Rasterizer discard is currently implemented via the "
1312 "clipper; having the GS not write primitives would "
1313 "likely be faster.\n");
1314 #endif
1315 } else {
1316 clip.ClipMode = CLIPMODE_NORMAL;
1317 }
1318
1319 clip.ClipEnable = brw->primitive != _3DPRIM_RECTLIST;
1320
1321 /* _NEW_POLYGON,
1322 * BRW_NEW_GEOMETRY_PROGRAM | BRW_NEW_TES_PROG_DATA | BRW_NEW_PRIMITIVE
1323 */
1324 if (!brw_is_drawing_points(brw) && !brw_is_drawing_lines(brw))
1325 clip.ViewportXYClipTestEnable = true;
1326
1327 clip.MinimumPointWidth = 0.125;
1328 clip.MaximumPointWidth = 255.875;
1329 clip.MaximumVPIndex = viewport_count - 1;
1330 if (_mesa_geometric_layers(fb) == 0)
1331 clip.ForceZeroRTAIndexEnable = true;
1332 }
1333 }
1334
1335 static const struct brw_tracked_state genX(clip_state) = {
1336 .dirty = {
1337 .mesa = _NEW_BUFFERS |
1338 _NEW_LIGHT |
1339 _NEW_POLYGON |
1340 _NEW_TRANSFORM,
1341 .brw = BRW_NEW_BLORP |
1342 BRW_NEW_CONTEXT |
1343 BRW_NEW_FS_PROG_DATA |
1344 BRW_NEW_GS_PROG_DATA |
1345 BRW_NEW_VS_PROG_DATA |
1346 BRW_NEW_META_IN_PROGRESS |
1347 BRW_NEW_PRIMITIVE |
1348 BRW_NEW_RASTERIZER_DISCARD |
1349 BRW_NEW_TES_PROG_DATA |
1350 BRW_NEW_VIEWPORT_COUNT,
1351 },
1352 .emit = genX(upload_clip_state),
1353 };
1354 #endif
1355
1356 /* ---------------------------------------------------------------------- */
1357
1358 #if GEN_GEN >= 6
1359 static void
1360 genX(upload_sf)(struct brw_context *brw)
1361 {
1362 struct gl_context *ctx = &brw->ctx;
1363 float point_size;
1364
1365 #if GEN_GEN <= 7
1366 /* _NEW_BUFFERS */
1367 bool render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
1368 const bool multisampled_fbo = _mesa_geometric_samples(ctx->DrawBuffer) > 1;
1369 #endif
1370
1371 brw_batch_emit(brw, GENX(3DSTATE_SF), sf) {
1372 sf.StatisticsEnable = true;
1373 sf.ViewportTransformEnable = true;
1374
1375 #if GEN_GEN == 7
1376 /* _NEW_BUFFERS */
1377 sf.DepthBufferSurfaceFormat = brw_depthbuffer_format(brw);
1378 #endif
1379
1380 #if GEN_GEN <= 7
1381 /* _NEW_POLYGON */
1382 sf.FrontWinding = ctx->Polygon._FrontBit == render_to_fbo;
1383 sf.GlobalDepthOffsetEnableSolid = ctx->Polygon.OffsetFill;
1384 sf.GlobalDepthOffsetEnableWireframe = ctx->Polygon.OffsetLine;
1385 sf.GlobalDepthOffsetEnablePoint = ctx->Polygon.OffsetPoint;
1386
1387 switch (ctx->Polygon.FrontMode) {
1388 case GL_FILL:
1389 sf.FrontFaceFillMode = FILL_MODE_SOLID;
1390 break;
1391 case GL_LINE:
1392 sf.FrontFaceFillMode = FILL_MODE_WIREFRAME;
1393 break;
1394 case GL_POINT:
1395 sf.FrontFaceFillMode = FILL_MODE_POINT;
1396 break;
1397 default:
1398 unreachable("not reached");
1399 }
1400
1401 switch (ctx->Polygon.BackMode) {
1402 case GL_FILL:
1403 sf.BackFaceFillMode = FILL_MODE_SOLID;
1404 break;
1405 case GL_LINE:
1406 sf.BackFaceFillMode = FILL_MODE_WIREFRAME;
1407 break;
1408 case GL_POINT:
1409 sf.BackFaceFillMode = FILL_MODE_POINT;
1410 break;
1411 default:
1412 unreachable("not reached");
1413 }
1414
1415 sf.ScissorRectangleEnable = true;
1416
1417 if (ctx->Polygon.CullFlag) {
1418 switch (ctx->Polygon.CullFaceMode) {
1419 case GL_FRONT:
1420 sf.CullMode = CULLMODE_FRONT;
1421 break;
1422 case GL_BACK:
1423 sf.CullMode = CULLMODE_BACK;
1424 break;
1425 case GL_FRONT_AND_BACK:
1426 sf.CullMode = CULLMODE_BOTH;
1427 break;
1428 default:
1429 unreachable("not reached");
1430 }
1431 } else {
1432 sf.CullMode = CULLMODE_NONE;
1433 }
1434
1435 #if GEN_IS_HASWELL
1436 sf.LineStippleEnable = ctx->Line.StippleFlag;
1437 #endif
1438
1439 if (multisampled_fbo && ctx->Multisample.Enabled)
1440 sf.MultisampleRasterizationMode = MSRASTMODE_ON_PATTERN;
1441
1442 sf.GlobalDepthOffsetConstant = ctx->Polygon.OffsetUnits * 2;
1443 sf.GlobalDepthOffsetScale = ctx->Polygon.OffsetFactor;
1444 sf.GlobalDepthOffsetClamp = ctx->Polygon.OffsetClamp;
1445 #endif
1446
1447 /* _NEW_LINE */
1448 #if GEN_GEN == 8
1449 if (brw->is_cherryview)
1450 sf.CHVLineWidth = brw_get_line_width(brw);
1451 else
1452 sf.LineWidth = brw_get_line_width(brw);
1453 #else
1454 sf.LineWidth = brw_get_line_width(brw);
1455 #endif
1456
1457 if (ctx->Line.SmoothFlag) {
1458 sf.LineEndCapAntialiasingRegionWidth = _10pixels;
1459 #if GEN_GEN <= 7
1460 sf.AntiAliasingEnable = true;
1461 #endif
1462 }
1463
1464 /* _NEW_POINT - Clamp to ARB_point_parameters user limits */
1465 point_size = CLAMP(ctx->Point.Size, ctx->Point.MinSize, ctx->Point.MaxSize);
1466 /* Clamp to the hardware limits */
1467 sf.PointWidth = CLAMP(point_size, 0.125f, 255.875f);
1468
1469 /* _NEW_PROGRAM | _NEW_POINT, BRW_NEW_VUE_MAP_GEOM_OUT */
1470 if (use_state_point_size(brw))
1471 sf.PointWidthSource = State;
1472
1473 #if GEN_GEN >= 8
1474 /* _NEW_POINT | _NEW_MULTISAMPLE */
1475 if ((ctx->Point.SmoothFlag || _mesa_is_multisample_enabled(ctx)) &&
1476 !ctx->Point.PointSprite)
1477 sf.SmoothPointEnable = true;
1478 #endif
1479
1480 sf.AALineDistanceMode = AALINEDISTANCE_TRUE;
1481
1482 /* _NEW_LIGHT */
1483 if (ctx->Light.ProvokingVertex != GL_FIRST_VERTEX_CONVENTION) {
1484 sf.TriangleStripListProvokingVertexSelect = 2;
1485 sf.TriangleFanProvokingVertexSelect = 2;
1486 sf.LineStripListProvokingVertexSelect = 1;
1487 } else {
1488 sf.TriangleFanProvokingVertexSelect = 1;
1489 }
1490
1491 #if GEN_GEN == 6
1492 /* BRW_NEW_FS_PROG_DATA */
1493 const struct brw_wm_prog_data *wm_prog_data =
1494 brw_wm_prog_data(brw->wm.base.prog_data);
1495
1496 sf.AttributeSwizzleEnable = true;
1497 sf.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
1498
1499 /*
1500 * Window coordinates in an FBO are inverted, which means point
1501 * sprite origin must be inverted, too.
1502 */
1503 if ((ctx->Point.SpriteOrigin == GL_LOWER_LEFT) != render_to_fbo) {
1504 sf.PointSpriteTextureCoordinateOrigin = LOWERLEFT;
1505 } else {
1506 sf.PointSpriteTextureCoordinateOrigin = UPPERLEFT;
1507 }
1508
1509 /* BRW_NEW_VUE_MAP_GEOM_OUT | BRW_NEW_FRAGMENT_PROGRAM |
1510 * _NEW_POINT | _NEW_LIGHT | _NEW_PROGRAM | BRW_NEW_FS_PROG_DATA
1511 */
1512 uint32_t urb_entry_read_length;
1513 uint32_t urb_entry_read_offset;
1514 uint32_t point_sprite_enables;
1515 genX(calculate_attr_overrides)(brw, sf.Attribute, &point_sprite_enables,
1516 &urb_entry_read_length,
1517 &urb_entry_read_offset);
1518 sf.VertexURBEntryReadLength = urb_entry_read_length;
1519 sf.VertexURBEntryReadOffset = urb_entry_read_offset;
1520 sf.PointSpriteTextureCoordinateEnable = point_sprite_enables;
1521 sf.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
1522 #endif
1523 }
1524 }
1525
1526 static const struct brw_tracked_state genX(sf_state) = {
1527 .dirty = {
1528 .mesa = _NEW_LIGHT |
1529 _NEW_LINE |
1530 _NEW_MULTISAMPLE |
1531 _NEW_POINT |
1532 _NEW_PROGRAM |
1533 (GEN_GEN <= 7 ? _NEW_BUFFERS | _NEW_POLYGON : 0),
1534 .brw = BRW_NEW_BLORP |
1535 BRW_NEW_CONTEXT |
1536 BRW_NEW_VUE_MAP_GEOM_OUT |
1537 (GEN_GEN <= 7 ? BRW_NEW_GS_PROG_DATA |
1538 BRW_NEW_PRIMITIVE |
1539 BRW_NEW_TES_PROG_DATA
1540 : 0) |
1541 (GEN_GEN == 6 ? BRW_NEW_FS_PROG_DATA |
1542 BRW_NEW_FRAGMENT_PROGRAM
1543 : 0),
1544 },
1545 .emit = genX(upload_sf),
1546 };
1547 #endif
1548
1549 /* ---------------------------------------------------------------------- */
1550
1551 #if GEN_GEN >= 6
1552 static void
1553 genX(upload_wm)(struct brw_context *brw)
1554 {
1555 struct gl_context *ctx = &brw->ctx;
1556
1557 /* BRW_NEW_FS_PROG_DATA */
1558 const struct brw_wm_prog_data *wm_prog_data =
1559 brw_wm_prog_data(brw->wm.base.prog_data);
1560
1561 UNUSED bool writes_depth =
1562 wm_prog_data->computed_depth_mode != BRW_PSCDEPTH_OFF;
1563
1564 #if GEN_GEN < 7
1565 const struct brw_stage_state *stage_state = &brw->wm.base;
1566 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1567
1568 /* We can't fold this into gen6_upload_wm_push_constants(), because
1569 * according to the SNB PRM, vol 2 part 1 section 7.2.2
1570 * (3DSTATE_CONSTANT_PS [DevSNB]):
1571 *
1572 * "[DevSNB]: This packet must be followed by WM_STATE."
1573 */
1574 brw_batch_emit(brw, GENX(3DSTATE_CONSTANT_PS), wmcp) {
1575 if (wm_prog_data->base.nr_params != 0) {
1576 wmcp.Buffer0Valid = true;
1577 /* Pointer to the WM constant buffer. Covered by the set of
1578 * state flags from gen6_upload_wm_push_constants.
1579 */
1580 wmcp.PointertoPSConstantBuffer0 = stage_state->push_const_offset;
1581 wmcp.PSConstantBuffer0ReadLength = stage_state->push_const_size - 1;
1582 }
1583 }
1584 #endif
1585
1586 brw_batch_emit(brw, GENX(3DSTATE_WM), wm) {
1587 wm.StatisticsEnable = true;
1588 wm.LineAntialiasingRegionWidth = _10pixels;
1589 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1590
1591 #if GEN_GEN < 7
1592 if (wm_prog_data->base.use_alt_mode)
1593 wm.FloatingPointMode = Alternate;
1594
1595 wm.SamplerCount = DIV_ROUND_UP(stage_state->sampler_count, 4);
1596 wm.BindingTableEntryCount = wm_prog_data->base.binding_table.size_bytes / 4;
1597 wm.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1598 wm._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1599 wm._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1600 wm.DispatchGRFStartRegisterForConstantSetupData0 =
1601 wm_prog_data->base.dispatch_grf_start_reg;
1602 wm.DispatchGRFStartRegisterForConstantSetupData2 =
1603 wm_prog_data->dispatch_grf_start_reg_2;
1604 wm.KernelStartPointer0 = stage_state->prog_offset;
1605 wm.KernelStartPointer2 = stage_state->prog_offset +
1606 wm_prog_data->prog_offset_2;
1607 wm.DualSourceBlendEnable =
1608 wm_prog_data->dual_src_blend && (ctx->Color.BlendEnabled & 1) &&
1609 ctx->Color.Blend[0]._UsesDualSrc;
1610 wm.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1611 wm.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
1612
1613 /* From the SNB PRM, volume 2 part 1, page 281:
1614 * "If the PS kernel does not need the Position XY Offsets
1615 * to compute a Position XY value, then this field should be
1616 * programmed to POSOFFSET_NONE."
1617 *
1618 * "SW Recommendation: If the PS kernel needs the Position Offsets
1619 * to compute a Position XY value, this field should match Position
1620 * ZW Interpolation Mode to ensure a consistent position.xyzw
1621 * computation."
1622 * We only require XY sample offsets. So, this recommendation doesn't
1623 * look useful at the moment. We might need this in future.
1624 */
1625 if (wm_prog_data->uses_pos_offset)
1626 wm.PositionXYOffsetSelect = POSOFFSET_SAMPLE;
1627 else
1628 wm.PositionXYOffsetSelect = POSOFFSET_NONE;
1629
1630 if (wm_prog_data->base.total_scratch) {
1631 wm.ScratchSpaceBasePointer =
1632 render_bo(stage_state->scratch_bo,
1633 ffs(stage_state->per_thread_scratch) - 11);
1634 }
1635
1636 wm.PixelShaderComputedDepth = writes_depth;
1637 #endif
1638
1639 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1640
1641 /* _NEW_LINE */
1642 wm.LineStippleEnable = ctx->Line.StippleFlag;
1643
1644 /* _NEW_POLYGON */
1645 wm.PolygonStippleEnable = ctx->Polygon.StippleFlag;
1646 wm.BarycentricInterpolationMode = wm_prog_data->barycentric_interp_modes;
1647
1648 #if GEN_GEN < 8
1649 /* _NEW_BUFFERS */
1650 const bool multisampled_fbo = _mesa_geometric_samples(ctx->DrawBuffer) > 1;
1651
1652 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1653 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1654 if (wm_prog_data->uses_kill ||
1655 _mesa_is_alpha_test_enabled(ctx) ||
1656 _mesa_is_alpha_to_coverage_enabled(ctx) ||
1657 wm_prog_data->uses_omask) {
1658 wm.PixelShaderKillsPixel = true;
1659 }
1660
1661 /* _NEW_BUFFERS | _NEW_COLOR */
1662 if (brw_color_buffer_write_enabled(brw) || writes_depth ||
1663 wm_prog_data->has_side_effects || wm.PixelShaderKillsPixel) {
1664 wm.ThreadDispatchEnable = true;
1665 }
1666 if (multisampled_fbo) {
1667 /* _NEW_MULTISAMPLE */
1668 if (ctx->Multisample.Enabled)
1669 wm.MultisampleRasterizationMode = MSRASTMODE_ON_PATTERN;
1670 else
1671 wm.MultisampleRasterizationMode = MSRASTMODE_OFF_PIXEL;
1672
1673 if (wm_prog_data->persample_dispatch)
1674 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1675 else
1676 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1677 } else {
1678 wm.MultisampleRasterizationMode = MSRASTMODE_OFF_PIXEL;
1679 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1680 }
1681
1682 #if GEN_GEN >= 7
1683 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1684 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1685 #endif
1686
1687 /* The "UAV access enable" bits are unnecessary on HSW because they only
1688 * seem to have an effect on the HW-assisted coherency mechanism which we
1689 * don't need, and the rasterization-related UAV_ONLY flag and the
1690 * DISPATCH_ENABLE bit can be set independently from it.
1691 * C.f. gen8_upload_ps_extra().
1692 *
1693 * BRW_NEW_FRAGMENT_PROGRAM | BRW_NEW_FS_PROG_DATA | _NEW_BUFFERS |
1694 * _NEW_COLOR
1695 */
1696 #if GEN_IS_HASWELL
1697 if (!(brw_color_buffer_write_enabled(brw) || writes_depth) &&
1698 wm_prog_data->has_side_effects)
1699 wm.PSUAVonly = ON;
1700 #endif
1701 #endif
1702
1703 #if GEN_GEN >= 7
1704 /* BRW_NEW_FS_PROG_DATA */
1705 if (wm_prog_data->early_fragment_tests)
1706 wm.EarlyDepthStencilControl = EDSC_PREPS;
1707 else if (wm_prog_data->has_side_effects)
1708 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1709 #endif
1710 }
1711 }
1712
1713 static const struct brw_tracked_state genX(wm_state) = {
1714 .dirty = {
1715 .mesa = _NEW_LINE |
1716 _NEW_POLYGON |
1717 (GEN_GEN < 8 ? _NEW_BUFFERS |
1718 _NEW_COLOR |
1719 _NEW_MULTISAMPLE :
1720 0) |
1721 (GEN_GEN < 7 ? _NEW_PROGRAM_CONSTANTS : 0),
1722 .brw = BRW_NEW_BLORP |
1723 BRW_NEW_FS_PROG_DATA |
1724 (GEN_GEN < 7 ? BRW_NEW_BATCH : BRW_NEW_CONTEXT),
1725 },
1726 .emit = genX(upload_wm),
1727 };
1728 #endif
1729
1730 /* ---------------------------------------------------------------------- */
1731
1732 #if GEN_GEN == 4
1733 static inline struct brw_address
1734 KSP(struct brw_context *brw, uint32_t offset)
1735 {
1736 return instruction_bo(brw->cache.bo, offset);
1737 }
1738 #else
1739 static inline uint32_t
1740 KSP(struct brw_context *brw, uint32_t offset)
1741 {
1742 return offset;
1743 }
1744 #endif
1745
1746 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix) \
1747 pkt.KernelStartPointer = KSP(brw, stage_state->prog_offset); \
1748 pkt.SamplerCount = \
1749 DIV_ROUND_UP(CLAMP(stage_state->sampler_count, 0, 16), 4); \
1750 pkt.BindingTableEntryCount = \
1751 stage_prog_data->binding_table.size_bytes / 4; \
1752 pkt.FloatingPointMode = stage_prog_data->use_alt_mode; \
1753 \
1754 if (stage_prog_data->total_scratch) { \
1755 pkt.ScratchSpaceBasePointer = \
1756 render_bo(stage_state->scratch_bo, 0); \
1757 pkt.PerThreadScratchSpace = \
1758 ffs(stage_state->per_thread_scratch) - 11; \
1759 } \
1760 \
1761 pkt.DispatchGRFStartRegisterForURBData = \
1762 stage_prog_data->dispatch_grf_start_reg; \
1763 pkt.prefix##URBEntryReadLength = vue_prog_data->urb_read_length; \
1764 pkt.prefix##URBEntryReadOffset = 0; \
1765 \
1766 pkt.StatisticsEnable = true; \
1767 pkt.Enable = true;
1768
1769 static void
1770 genX(upload_vs_state)(struct brw_context *brw)
1771 {
1772 UNUSED struct gl_context *ctx = &brw->ctx;
1773 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1774 struct brw_stage_state *stage_state = &brw->vs.base;
1775
1776 /* BRW_NEW_VS_PROG_DATA */
1777 const struct brw_vue_prog_data *vue_prog_data =
1778 brw_vue_prog_data(brw->vs.base.prog_data);
1779 const struct brw_stage_prog_data *stage_prog_data = &vue_prog_data->base;
1780
1781 assert(vue_prog_data->dispatch_mode == DISPATCH_MODE_SIMD8 ||
1782 vue_prog_data->dispatch_mode == DISPATCH_MODE_4X2_DUAL_OBJECT);
1783
1784 #if GEN_GEN == 6
1785 /* From the BSpec, 3D Pipeline > Geometry > Vertex Shader > State,
1786 * 3DSTATE_VS, Dword 5.0 "VS Function Enable":
1787 *
1788 * [DevSNB] A pipeline flush must be programmed prior to a 3DSTATE_VS
1789 * command that causes the VS Function Enable to toggle. Pipeline
1790 * flush can be executed by sending a PIPE_CONTROL command with CS
1791 * stall bit set and a post sync operation.
1792 *
1793 * We've already done such a flush at the start of state upload, so we
1794 * don't need to do another one here.
1795 */
1796 brw_batch_emit(brw, GENX(3DSTATE_CONSTANT_VS), cvs) {
1797 if (stage_state->push_const_size != 0) {
1798 cvs.Buffer0Valid = true;
1799 cvs.PointertoVSConstantBuffer0 = stage_state->push_const_offset;
1800 cvs.VSConstantBuffer0ReadLength = stage_state->push_const_size - 1;
1801 }
1802 }
1803 #endif
1804
1805 if (GEN_GEN == 7 && devinfo->is_ivybridge)
1806 gen7_emit_vs_workaround_flush(brw);
1807
1808 #if GEN_GEN >= 6
1809 brw_batch_emit(brw, GENX(3DSTATE_VS), vs) {
1810 #else
1811 ctx->NewDriverState |= BRW_NEW_GEN4_UNIT_STATE;
1812 brw_state_emit(brw, GENX(VS_STATE), 32, &stage_state->state_offset, vs) {
1813 #endif
1814 INIT_THREAD_DISPATCH_FIELDS(vs, Vertex);
1815
1816 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1817
1818 #if GEN_GEN < 6
1819 vs.GRFRegisterCount = DIV_ROUND_UP(vue_prog_data->total_grf, 16) - 1;
1820 vs.ConstantURBEntryReadLength = stage_prog_data->curb_read_length;
1821 vs.ConstantURBEntryReadOffset = brw->curbe.vs_start * 2;
1822
1823 vs.NumberofURBEntries = brw->urb.nr_vs_entries >> (GEN_GEN == 5 ? 2 : 0);
1824 vs.URBEntryAllocationSize = brw->urb.vsize - 1;
1825
1826 vs.MaximumNumberofThreads =
1827 CLAMP(brw->urb.nr_vs_entries / 2, 1, devinfo->max_vs_threads) - 1;
1828
1829 vs.StatisticsEnable = false;
1830 vs.SamplerStatePointer =
1831 instruction_ro_bo(brw->batch.bo, stage_state->sampler_offset);
1832 #endif
1833
1834 #if GEN_GEN == 5
1835 /* Force single program flow on Ironlake. We cannot reliably get
1836 * all applications working without it. See:
1837 * https://bugs.freedesktop.org/show_bug.cgi?id=29172
1838 *
1839 * The most notable and reliably failing application is the Humus
1840 * demo "CelShading"
1841 */
1842 vs.SingleProgramFlow = true;
1843 vs.SamplerCount = 0; /* hardware requirement */
1844 #endif
1845
1846 #if GEN_GEN >= 8
1847 vs.SIMD8DispatchEnable =
1848 vue_prog_data->dispatch_mode == DISPATCH_MODE_SIMD8;
1849
1850 vs.UserClipDistanceCullTestEnableBitmask =
1851 vue_prog_data->cull_distance_mask;
1852 #endif
1853 }
1854
1855 #if GEN_GEN == 6
1856 /* Based on my reading of the simulator, the VS constants don't get
1857 * pulled into the VS FF unit until an appropriate pipeline flush
1858 * happens, and instead the 3DSTATE_CONSTANT_VS packet just adds
1859 * references to them into a little FIFO. The flushes are common,
1860 * but don't reliably happen between this and a 3DPRIMITIVE, causing
1861 * the primitive to use the wrong constants. Then the FIFO
1862 * containing the constant setup gets added to again on the next
1863 * constants change, and eventually when a flush does happen the
1864 * unit is overwhelmed by constant changes and dies.
1865 *
1866 * To avoid this, send a PIPE_CONTROL down the line that will
1867 * update the unit immediately loading the constants. The flush
1868 * type bits here were those set by the STATE_BASE_ADDRESS whose
1869 * move in a82a43e8d99e1715dd11c9c091b5ab734079b6a6 triggered the
1870 * bug reports that led to this workaround, and may be more than
1871 * what is strictly required to avoid the issue.
1872 */
1873 brw_emit_pipe_control_flush(brw,
1874 PIPE_CONTROL_DEPTH_STALL |
1875 PIPE_CONTROL_INSTRUCTION_INVALIDATE |
1876 PIPE_CONTROL_STATE_CACHE_INVALIDATE);
1877 #endif
1878 }
1879
1880 static const struct brw_tracked_state genX(vs_state) = {
1881 .dirty = {
1882 .mesa = (GEN_GEN == 6 ? (_NEW_PROGRAM_CONSTANTS | _NEW_TRANSFORM) : 0),
1883 .brw = BRW_NEW_BATCH |
1884 BRW_NEW_BLORP |
1885 BRW_NEW_CONTEXT |
1886 BRW_NEW_VS_PROG_DATA |
1887 (GEN_GEN == 6 ? BRW_NEW_VERTEX_PROGRAM : 0) |
1888 (GEN_GEN <= 5 ? BRW_NEW_PUSH_CONSTANT_ALLOCATION |
1889 BRW_NEW_PROGRAM_CACHE |
1890 BRW_NEW_SAMPLER_STATE_TABLE |
1891 BRW_NEW_URB_FENCE
1892 : 0),
1893 },
1894 .emit = genX(upload_vs_state),
1895 };
1896
1897 /* ---------------------------------------------------------------------- */
1898
1899 static void
1900 genX(upload_cc_viewport)(struct brw_context *brw)
1901 {
1902 struct gl_context *ctx = &brw->ctx;
1903
1904 /* BRW_NEW_VIEWPORT_COUNT */
1905 const unsigned viewport_count = brw->clip.viewport_count;
1906
1907 struct GENX(CC_VIEWPORT) ccv;
1908 uint32_t cc_vp_offset;
1909 uint32_t *cc_map =
1910 brw_state_batch(brw, 4 * GENX(CC_VIEWPORT_length) * viewport_count,
1911 32, &cc_vp_offset);
1912
1913 for (unsigned i = 0; i < viewport_count; i++) {
1914 /* _NEW_VIEWPORT | _NEW_TRANSFORM */
1915 const struct gl_viewport_attrib *vp = &ctx->ViewportArray[i];
1916 if (ctx->Transform.DepthClamp) {
1917 ccv.MinimumDepth = MIN2(vp->Near, vp->Far);
1918 ccv.MaximumDepth = MAX2(vp->Near, vp->Far);
1919 } else {
1920 ccv.MinimumDepth = 0.0;
1921 ccv.MaximumDepth = 1.0;
1922 }
1923 GENX(CC_VIEWPORT_pack)(NULL, cc_map, &ccv);
1924 cc_map += GENX(CC_VIEWPORT_length);
1925 }
1926
1927 #if GEN_GEN >= 7
1928 brw_batch_emit(brw, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_CC), ptr) {
1929 ptr.CCViewportPointer = cc_vp_offset;
1930 }
1931 #elif GEN_GEN == 6
1932 brw_batch_emit(brw, GENX(3DSTATE_VIEWPORT_STATE_POINTERS), vp) {
1933 vp.CCViewportStateChange = 1;
1934 vp.PointertoCC_VIEWPORT = cc_vp_offset;
1935 }
1936 #else
1937 brw->cc.vp_offset = cc_vp_offset;
1938 ctx->NewDriverState |= BRW_NEW_CC_VP;
1939 #endif
1940 }
1941
1942 const struct brw_tracked_state genX(cc_vp) = {
1943 .dirty = {
1944 .mesa = _NEW_TRANSFORM |
1945 _NEW_VIEWPORT,
1946 .brw = BRW_NEW_BATCH |
1947 BRW_NEW_BLORP |
1948 BRW_NEW_VIEWPORT_COUNT,
1949 },
1950 .emit = genX(upload_cc_viewport)
1951 };
1952
1953 /* ---------------------------------------------------------------------- */
1954
1955 static inline void
1956 set_scissor_bits(const struct gl_context *ctx, int i,
1957 bool render_to_fbo, unsigned fb_width, unsigned fb_height,
1958 struct GENX(SCISSOR_RECT) *sc)
1959 {
1960 int bbox[4];
1961
1962 bbox[0] = MAX2(ctx->ViewportArray[i].X, 0);
1963 bbox[1] = MIN2(bbox[0] + ctx->ViewportArray[i].Width, fb_width);
1964 bbox[2] = MAX2(ctx->ViewportArray[i].Y, 0);
1965 bbox[3] = MIN2(bbox[2] + ctx->ViewportArray[i].Height, fb_height);
1966 _mesa_intersect_scissor_bounding_box(ctx, i, bbox);
1967
1968 if (bbox[0] == bbox[1] || bbox[2] == bbox[3]) {
1969 /* If the scissor was out of bounds and got clamped to 0 width/height
1970 * at the bounds, the subtraction of 1 from maximums could produce a
1971 * negative number and thus not clip anything. Instead, just provide
1972 * a min > max scissor inside the bounds, which produces the expected
1973 * no rendering.
1974 */
1975 sc->ScissorRectangleXMin = 1;
1976 sc->ScissorRectangleXMax = 0;
1977 sc->ScissorRectangleYMin = 1;
1978 sc->ScissorRectangleYMax = 0;
1979 } else if (render_to_fbo) {
1980 /* texmemory: Y=0=bottom */
1981 sc->ScissorRectangleXMin = bbox[0];
1982 sc->ScissorRectangleXMax = bbox[1] - 1;
1983 sc->ScissorRectangleYMin = bbox[2];
1984 sc->ScissorRectangleYMax = bbox[3] - 1;
1985 } else {
1986 /* memory: Y=0=top */
1987 sc->ScissorRectangleXMin = bbox[0];
1988 sc->ScissorRectangleXMax = bbox[1] - 1;
1989 sc->ScissorRectangleYMin = fb_height - bbox[3];
1990 sc->ScissorRectangleYMax = fb_height - bbox[2] - 1;
1991 }
1992 }
1993
1994 #if GEN_GEN >= 6
1995 static void
1996 genX(upload_scissor_state)(struct brw_context *brw)
1997 {
1998 struct gl_context *ctx = &brw->ctx;
1999 const bool render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
2000 struct GENX(SCISSOR_RECT) scissor;
2001 uint32_t scissor_state_offset;
2002 const unsigned int fb_width = _mesa_geometric_width(ctx->DrawBuffer);
2003 const unsigned int fb_height = _mesa_geometric_height(ctx->DrawBuffer);
2004 uint32_t *scissor_map;
2005
2006 /* BRW_NEW_VIEWPORT_COUNT */
2007 const unsigned viewport_count = brw->clip.viewport_count;
2008
2009 scissor_map = brw_state_batch(
2010 brw, GENX(SCISSOR_RECT_length) * sizeof(uint32_t) * viewport_count,
2011 32, &scissor_state_offset);
2012
2013 /* _NEW_SCISSOR | _NEW_BUFFERS | _NEW_VIEWPORT */
2014
2015 /* The scissor only needs to handle the intersection of drawable and
2016 * scissor rect. Clipping to the boundaries of static shared buffers
2017 * for front/back/depth is covered by looping over cliprects in brw_draw.c.
2018 *
2019 * Note that the hardware's coordinates are inclusive, while Mesa's min is
2020 * inclusive but max is exclusive.
2021 */
2022 for (unsigned i = 0; i < viewport_count; i++) {
2023 set_scissor_bits(ctx, i, render_to_fbo, fb_width, fb_height, &scissor);
2024 GENX(SCISSOR_RECT_pack)(
2025 NULL, scissor_map + i * GENX(SCISSOR_RECT_length), &scissor);
2026 }
2027
2028 brw_batch_emit(brw, GENX(3DSTATE_SCISSOR_STATE_POINTERS), ptr) {
2029 ptr.ScissorRectPointer = scissor_state_offset;
2030 }
2031 }
2032
2033 static const struct brw_tracked_state genX(scissor_state) = {
2034 .dirty = {
2035 .mesa = _NEW_BUFFERS |
2036 _NEW_SCISSOR |
2037 _NEW_VIEWPORT,
2038 .brw = BRW_NEW_BATCH |
2039 BRW_NEW_BLORP |
2040 BRW_NEW_VIEWPORT_COUNT,
2041 },
2042 .emit = genX(upload_scissor_state),
2043 };
2044 #endif
2045
2046 /* ---------------------------------------------------------------------- */
2047
2048 static void
2049 brw_calculate_guardband_size(uint32_t fb_width, uint32_t fb_height,
2050 float m00, float m11, float m30, float m31,
2051 float *xmin, float *xmax,
2052 float *ymin, float *ymax)
2053 {
2054 /* According to the "Vertex X,Y Clamping and Quantization" section of the
2055 * Strips and Fans documentation:
2056 *
2057 * "The vertex X and Y screen-space coordinates are also /clamped/ to the
2058 * fixed-point "guardband" range supported by the rasterization hardware"
2059 *
2060 * and
2061 *
2062 * "In almost all circumstances, if an object’s vertices are actually
2063 * modified by this clamping (i.e., had X or Y coordinates outside of
2064 * the guardband extent the rendered object will not match the intended
2065 * result. Therefore software should take steps to ensure that this does
2066 * not happen - e.g., by clipping objects such that they do not exceed
2067 * these limits after the Drawing Rectangle is applied."
2068 *
2069 * I believe the fundamental restriction is that the rasterizer (in
2070 * the SF/WM stages) have a limit on the number of pixels that can be
2071 * rasterized. We need to ensure any coordinates beyond the rasterizer
2072 * limit are handled by the clipper. So effectively that limit becomes
2073 * the clipper's guardband size.
2074 *
2075 * It goes on to say:
2076 *
2077 * "In addition, in order to be correctly rendered, objects must have a
2078 * screenspace bounding box not exceeding 8K in the X or Y direction.
2079 * This additional restriction must also be comprehended by software,
2080 * i.e., enforced by use of clipping."
2081 *
2082 * This makes no sense. Gen7+ hardware supports 16K render targets,
2083 * and you definitely need to be able to draw polygons that fill the
2084 * surface. Our assumption is that the rasterizer was limited to 8K
2085 * on Sandybridge, which only supports 8K surfaces, and it was actually
2086 * increased to 16K on Ivybridge and later.
2087 *
2088 * So, limit the guardband to 16K on Gen7+ and 8K on Sandybridge.
2089 */
2090 const float gb_size = GEN_GEN >= 7 ? 16384.0f : 8192.0f;
2091
2092 if (m00 != 0 && m11 != 0) {
2093 /* First, we compute the screen-space render area */
2094 const float ss_ra_xmin = MIN3( 0, m30 + m00, m30 - m00);
2095 const float ss_ra_xmax = MAX3( fb_width, m30 + m00, m30 - m00);
2096 const float ss_ra_ymin = MIN3( 0, m31 + m11, m31 - m11);
2097 const float ss_ra_ymax = MAX3(fb_height, m31 + m11, m31 - m11);
2098
2099 /* We want the guardband to be centered on that */
2100 const float ss_gb_xmin = (ss_ra_xmin + ss_ra_xmax) / 2 - gb_size;
2101 const float ss_gb_xmax = (ss_ra_xmin + ss_ra_xmax) / 2 + gb_size;
2102 const float ss_gb_ymin = (ss_ra_ymin + ss_ra_ymax) / 2 - gb_size;
2103 const float ss_gb_ymax = (ss_ra_ymin + ss_ra_ymax) / 2 + gb_size;
2104
2105 /* Now we need it in native device coordinates */
2106 const float ndc_gb_xmin = (ss_gb_xmin - m30) / m00;
2107 const float ndc_gb_xmax = (ss_gb_xmax - m30) / m00;
2108 const float ndc_gb_ymin = (ss_gb_ymin - m31) / m11;
2109 const float ndc_gb_ymax = (ss_gb_ymax - m31) / m11;
2110
2111 /* Thanks to Y-flipping and ORIGIN_UPPER_LEFT, the Y coordinates may be
2112 * flipped upside-down. X should be fine though.
2113 */
2114 assert(ndc_gb_xmin <= ndc_gb_xmax);
2115 *xmin = ndc_gb_xmin;
2116 *xmax = ndc_gb_xmax;
2117 *ymin = MIN2(ndc_gb_ymin, ndc_gb_ymax);
2118 *ymax = MAX2(ndc_gb_ymin, ndc_gb_ymax);
2119 } else {
2120 /* The viewport scales to 0, so nothing will be rendered. */
2121 *xmin = 0.0f;
2122 *xmax = 0.0f;
2123 *ymin = 0.0f;
2124 *ymax = 0.0f;
2125 }
2126 }
2127
2128 static void
2129 genX(upload_sf_clip_viewport)(struct brw_context *brw)
2130 {
2131 struct gl_context *ctx = &brw->ctx;
2132 float y_scale, y_bias;
2133
2134 /* BRW_NEW_VIEWPORT_COUNT */
2135 const unsigned viewport_count = brw->clip.viewport_count;
2136
2137 /* _NEW_BUFFERS */
2138 const bool render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
2139 const uint32_t fb_width = (float)_mesa_geometric_width(ctx->DrawBuffer);
2140 const uint32_t fb_height = (float)_mesa_geometric_height(ctx->DrawBuffer);
2141
2142 #if GEN_GEN >= 7
2143 #define clv sfv
2144 struct GENX(SF_CLIP_VIEWPORT) sfv;
2145 uint32_t sf_clip_vp_offset;
2146 uint32_t *sf_clip_map =
2147 brw_state_batch(brw, GENX(SF_CLIP_VIEWPORT_length) * 4 * viewport_count,
2148 64, &sf_clip_vp_offset);
2149 #else
2150 struct GENX(SF_VIEWPORT) sfv;
2151 struct GENX(CLIP_VIEWPORT) clv;
2152 uint32_t sf_vp_offset, clip_vp_offset;
2153 uint32_t *sf_map =
2154 brw_state_batch(brw, GENX(SF_VIEWPORT_length) * 4 * viewport_count,
2155 32, &sf_vp_offset);
2156 uint32_t *clip_map =
2157 brw_state_batch(brw, GENX(CLIP_VIEWPORT_length) * 4 * viewport_count,
2158 32, &clip_vp_offset);
2159 #endif
2160
2161 /* _NEW_BUFFERS */
2162 if (render_to_fbo) {
2163 y_scale = 1.0;
2164 y_bias = 0;
2165 } else {
2166 y_scale = -1.0;
2167 y_bias = (float)fb_height;
2168 }
2169
2170 for (unsigned i = 0; i < brw->clip.viewport_count; i++) {
2171 /* _NEW_VIEWPORT: Guardband Clipping */
2172 float scale[3], translate[3], gb_xmin, gb_xmax, gb_ymin, gb_ymax;
2173 _mesa_get_viewport_xform(ctx, i, scale, translate);
2174
2175 sfv.ViewportMatrixElementm00 = scale[0];
2176 sfv.ViewportMatrixElementm11 = scale[1] * y_scale,
2177 sfv.ViewportMatrixElementm22 = scale[2],
2178 sfv.ViewportMatrixElementm30 = translate[0],
2179 sfv.ViewportMatrixElementm31 = translate[1] * y_scale + y_bias,
2180 sfv.ViewportMatrixElementm32 = translate[2],
2181 brw_calculate_guardband_size(fb_width, fb_height,
2182 sfv.ViewportMatrixElementm00,
2183 sfv.ViewportMatrixElementm11,
2184 sfv.ViewportMatrixElementm30,
2185 sfv.ViewportMatrixElementm31,
2186 &gb_xmin, &gb_xmax, &gb_ymin, &gb_ymax);
2187
2188
2189 clv.XMinClipGuardband = gb_xmin;
2190 clv.XMaxClipGuardband = gb_xmax;
2191 clv.YMinClipGuardband = gb_ymin;
2192 clv.YMaxClipGuardband = gb_ymax;
2193
2194 #if GEN_GEN < 6
2195 set_scissor_bits(ctx, i, render_to_fbo, fb_width, fb_height,
2196 &sfv.ScissorRectangle);
2197 #elif GEN_GEN >= 8
2198 /* _NEW_VIEWPORT | _NEW_BUFFERS: Screen Space Viewport
2199 * The hardware will take the intersection of the drawing rectangle,
2200 * scissor rectangle, and the viewport extents. We don't need to be
2201 * smart, and can therefore just program the viewport extents.
2202 */
2203 const float viewport_Xmax =
2204 ctx->ViewportArray[i].X + ctx->ViewportArray[i].Width;
2205 const float viewport_Ymax =
2206 ctx->ViewportArray[i].Y + ctx->ViewportArray[i].Height;
2207
2208 if (render_to_fbo) {
2209 sfv.XMinViewPort = ctx->ViewportArray[i].X;
2210 sfv.XMaxViewPort = viewport_Xmax - 1;
2211 sfv.YMinViewPort = ctx->ViewportArray[i].Y;
2212 sfv.YMaxViewPort = viewport_Ymax - 1;
2213 } else {
2214 sfv.XMinViewPort = ctx->ViewportArray[i].X;
2215 sfv.XMaxViewPort = viewport_Xmax - 1;
2216 sfv.YMinViewPort = fb_height - viewport_Ymax;
2217 sfv.YMaxViewPort = fb_height - ctx->ViewportArray[i].Y - 1;
2218 }
2219 #endif
2220
2221 #if GEN_GEN >= 7
2222 GENX(SF_CLIP_VIEWPORT_pack)(NULL, sf_clip_map, &sfv);
2223 sf_clip_map += GENX(SF_CLIP_VIEWPORT_length);
2224 #else
2225 GENX(SF_VIEWPORT_pack)(NULL, sf_map, &sfv);
2226 GENX(CLIP_VIEWPORT_pack)(NULL, clip_map, &clv);
2227 sf_map += GENX(SF_VIEWPORT_length);
2228 clip_map += GENX(CLIP_VIEWPORT_length);
2229 #endif
2230 }
2231
2232 #if GEN_GEN >= 7
2233 brw_batch_emit(brw, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
2234 ptr.SFClipViewportPointer = sf_clip_vp_offset;
2235 }
2236 #elif GEN_GEN == 6
2237 brw_batch_emit(brw, GENX(3DSTATE_VIEWPORT_STATE_POINTERS), vp) {
2238 vp.SFViewportStateChange = 1;
2239 vp.CLIPViewportStateChange = 1;
2240 vp.PointertoCLIP_VIEWPORT = clip_vp_offset;
2241 vp.PointertoSF_VIEWPORT = sf_vp_offset;
2242 }
2243 #else
2244 brw->sf.vp_offset = sf_vp_offset;
2245 brw->clip.vp_offset = clip_vp_offset;
2246 brw->ctx.NewDriverState |= BRW_NEW_SF_VP | BRW_NEW_CLIP_VP;
2247 #endif
2248 }
2249
2250 static const struct brw_tracked_state genX(sf_clip_viewport) = {
2251 .dirty = {
2252 .mesa = _NEW_BUFFERS |
2253 _NEW_VIEWPORT |
2254 (GEN_GEN <= 5 ? _NEW_SCISSOR : 0),
2255 .brw = BRW_NEW_BATCH |
2256 BRW_NEW_BLORP |
2257 BRW_NEW_VIEWPORT_COUNT,
2258 },
2259 .emit = genX(upload_sf_clip_viewport),
2260 };
2261
2262 /* ---------------------------------------------------------------------- */
2263
2264 #if GEN_GEN >= 6
2265 static void
2266 genX(upload_gs_state)(struct brw_context *brw)
2267 {
2268 const struct gen_device_info *devinfo = &brw->screen->devinfo;
2269 const struct brw_stage_state *stage_state = &brw->gs.base;
2270 /* BRW_NEW_GEOMETRY_PROGRAM */
2271 bool active = brw->geometry_program;
2272
2273 /* BRW_NEW_GS_PROG_DATA */
2274 struct brw_stage_prog_data *stage_prog_data = stage_state->prog_data;
2275 const struct brw_vue_prog_data *vue_prog_data =
2276 brw_vue_prog_data(stage_prog_data);
2277 #if GEN_GEN >= 7
2278 const struct brw_gs_prog_data *gs_prog_data =
2279 brw_gs_prog_data(stage_prog_data);
2280 #endif
2281
2282 #if GEN_GEN < 7
2283 brw_batch_emit(brw, GENX(3DSTATE_CONSTANT_GS), cgs) {
2284 if (active && stage_state->push_const_size != 0) {
2285 cgs.Buffer0Valid = true;
2286 cgs.PointertoGSConstantBuffer0 = stage_state->push_const_offset;
2287 cgs.GSConstantBuffer0ReadLength = stage_state->push_const_size - 1;
2288 }
2289 }
2290 #endif
2291
2292 #if GEN_GEN == 7 && !GEN_IS_HASWELL
2293 /**
2294 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
2295 * Geometry > Geometry Shader > State:
2296 *
2297 * "Note: Because of corruption in IVB:GT2, software needs to flush the
2298 * whole fixed function pipeline when the GS enable changes value in
2299 * the 3DSTATE_GS."
2300 *
2301 * The hardware architects have clarified that in this context "flush the
2302 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
2303 * Stall" bit set.
2304 */
2305 if (brw->gt == 2 && brw->gs.enabled != active)
2306 gen7_emit_cs_stall_flush(brw);
2307 #endif
2308
2309 if (active) {
2310 brw_batch_emit(brw, GENX(3DSTATE_GS), gs) {
2311 INIT_THREAD_DISPATCH_FIELDS(gs, Vertex);
2312
2313 #if GEN_GEN >= 7
2314 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
2315 gs.OutputTopology = gs_prog_data->output_topology;
2316 gs.ControlDataHeaderSize =
2317 gs_prog_data->control_data_header_size_hwords;
2318
2319 gs.InstanceControl = gs_prog_data->invocations - 1;
2320 gs.DispatchMode = vue_prog_data->dispatch_mode;
2321
2322 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
2323
2324 gs.ControlDataFormat = gs_prog_data->control_data_format;
2325 #endif
2326
2327 /* Note: the meaning of the GEN7_GS_REORDER_TRAILING bit changes between
2328 * Ivy Bridge and Haswell.
2329 *
2330 * On Ivy Bridge, setting this bit causes the vertices of a triangle
2331 * strip to be delivered to the geometry shader in an order that does
2332 * not strictly follow the OpenGL spec, but preserves triangle
2333 * orientation. For example, if the vertices are (1, 2, 3, 4, 5), then
2334 * the geometry shader sees triangles:
2335 *
2336 * (1, 2, 3), (2, 4, 3), (3, 4, 5)
2337 *
2338 * (Clearing the bit is even worse, because it fails to preserve
2339 * orientation).
2340 *
2341 * Triangle strips with adjacency always ordered in a way that preserves
2342 * triangle orientation but does not strictly follow the OpenGL spec,
2343 * regardless of the setting of this bit.
2344 *
2345 * On Haswell, both triangle strips and triangle strips with adjacency
2346 * are always ordered in a way that preserves triangle orientation.
2347 * Setting this bit causes the ordering to strictly follow the OpenGL
2348 * spec.
2349 *
2350 * So in either case we want to set the bit. Unfortunately on Ivy
2351 * Bridge this will get the order close to correct but not perfect.
2352 */
2353 gs.ReorderMode = TRAILING;
2354 gs.MaximumNumberofThreads =
2355 GEN_GEN == 8 ? (devinfo->max_gs_threads / 2 - 1)
2356 : (devinfo->max_gs_threads - 1);
2357
2358 #if GEN_GEN < 7
2359 gs.SOStatisticsEnable = true;
2360 gs.RenderingEnabled = 1;
2361 if (brw->geometry_program->info.has_transform_feedback_varyings)
2362 gs.SVBIPayloadEnable = true;
2363
2364 /* GEN6_GS_SPF_MODE and GEN6_GS_VECTOR_MASK_ENABLE are enabled as it
2365 * was previously done for gen6.
2366 *
2367 * TODO: test with both disabled to see if the HW is behaving
2368 * as expected, like in gen7.
2369 */
2370 gs.SingleProgramFlow = true;
2371 gs.VectorMaskEnable = true;
2372 #endif
2373
2374 #if GEN_GEN >= 8
2375 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
2376
2377 if (gs_prog_data->static_vertex_count != -1) {
2378 gs.StaticOutput = true;
2379 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count;
2380 }
2381 gs.IncludeVertexHandles = vue_prog_data->include_vue_handles;
2382
2383 gs.UserClipDistanceCullTestEnableBitmask =
2384 vue_prog_data->cull_distance_mask;
2385
2386 const int urb_entry_write_offset = 1;
2387 const uint32_t urb_entry_output_length =
2388 DIV_ROUND_UP(vue_prog_data->vue_map.num_slots, 2) -
2389 urb_entry_write_offset;
2390
2391 gs.VertexURBEntryOutputReadOffset = urb_entry_write_offset;
2392 gs.VertexURBEntryOutputLength = MAX2(urb_entry_output_length, 1);
2393 #endif
2394 }
2395 #if GEN_GEN < 7
2396 } else if (brw->ff_gs.prog_active) {
2397 /* In gen6, transform feedback for the VS stage is done with an ad-hoc GS
2398 * program. This function provides the needed 3DSTATE_GS for this.
2399 */
2400 upload_gs_state_for_tf(brw);
2401 #endif
2402 } else {
2403 brw_batch_emit(brw, GENX(3DSTATE_GS), gs) {
2404 gs.StatisticsEnable = true;
2405 #if GEN_GEN < 7
2406 gs.RenderingEnabled = true;
2407 #endif
2408
2409 #if GEN_GEN < 8
2410 gs.DispatchGRFStartRegisterForURBData = 1;
2411 #if GEN_GEN >= 7
2412 gs.IncludeVertexHandles = true;
2413 #endif
2414 #endif
2415 }
2416 }
2417 #if GEN_GEN < 7
2418 brw->gs.enabled = active;
2419 #endif
2420 }
2421
2422 static const struct brw_tracked_state genX(gs_state) = {
2423 .dirty = {
2424 .mesa = (GEN_GEN < 7 ? _NEW_PROGRAM_CONSTANTS : 0),
2425 .brw = BRW_NEW_BATCH |
2426 BRW_NEW_BLORP |
2427 BRW_NEW_CONTEXT |
2428 BRW_NEW_GEOMETRY_PROGRAM |
2429 BRW_NEW_GS_PROG_DATA |
2430 (GEN_GEN < 7 ? BRW_NEW_FF_GS_PROG_DATA : 0),
2431 },
2432 .emit = genX(upload_gs_state),
2433 };
2434 #endif
2435
2436 /* ---------------------------------------------------------------------- */
2437
2438 UNUSED static GLenum
2439 fix_dual_blend_alpha_to_one(GLenum function)
2440 {
2441 switch (function) {
2442 case GL_SRC1_ALPHA:
2443 return GL_ONE;
2444
2445 case GL_ONE_MINUS_SRC1_ALPHA:
2446 return GL_ZERO;
2447 }
2448
2449 return function;
2450 }
2451
2452 #define blend_factor(x) brw_translate_blend_factor(x)
2453 #define blend_eqn(x) brw_translate_blend_equation(x)
2454
2455 #if GEN_GEN >= 6
2456 static void
2457 genX(upload_blend_state)(struct brw_context *brw)
2458 {
2459 struct gl_context *ctx = &brw->ctx;
2460 int size;
2461
2462 /* We need at least one BLEND_STATE written, because we might do
2463 * thread dispatch even if _NumColorDrawBuffers is 0 (for example
2464 * for computed depth or alpha test), which will do an FB write
2465 * with render target 0, which will reference BLEND_STATE[0] for
2466 * alpha test enable.
2467 */
2468 int nr_draw_buffers = ctx->DrawBuffer->_NumColorDrawBuffers;
2469 if (nr_draw_buffers == 0 && ctx->Color.AlphaEnabled)
2470 nr_draw_buffers = 1;
2471
2472 size = GENX(BLEND_STATE_ENTRY_length) * 4 * nr_draw_buffers;
2473 #if GEN_GEN >= 8
2474 size += GENX(BLEND_STATE_length) * 4;
2475 #endif
2476
2477 uint32_t *blend_map;
2478 blend_map = brw_state_batch(brw, size, 64, &brw->cc.blend_state_offset);
2479
2480 #if GEN_GEN >= 8
2481 struct GENX(BLEND_STATE) blend = { 0 };
2482 {
2483 #else
2484 for (int i = 0; i < nr_draw_buffers; i++) {
2485 struct GENX(BLEND_STATE_ENTRY) entry = { 0 };
2486 #define blend entry
2487 #endif
2488 /* OpenGL specification 3.3 (page 196), section 4.1.3 says:
2489 * "If drawbuffer zero is not NONE and the buffer it references has an
2490 * integer format, the SAMPLE_ALPHA_TO_COVERAGE and SAMPLE_ALPHA_TO_ONE
2491 * operations are skipped."
2492 */
2493 if (!(ctx->DrawBuffer->_IntegerBuffers & 0x1)) {
2494 /* _NEW_MULTISAMPLE */
2495 if (_mesa_is_multisample_enabled(ctx)) {
2496 if (ctx->Multisample.SampleAlphaToCoverage) {
2497 blend.AlphaToCoverageEnable = true;
2498 blend.AlphaToCoverageDitherEnable = GEN_GEN >= 7;
2499 }
2500 if (ctx->Multisample.SampleAlphaToOne)
2501 blend.AlphaToOneEnable = true;
2502 }
2503
2504 /* _NEW_COLOR */
2505 if (ctx->Color.AlphaEnabled) {
2506 blend.AlphaTestEnable = true;
2507 blend.AlphaTestFunction =
2508 intel_translate_compare_func(ctx->Color.AlphaFunc);
2509 }
2510
2511 if (ctx->Color.DitherFlag) {
2512 blend.ColorDitherEnable = true;
2513 }
2514 }
2515
2516 #if GEN_GEN >= 8
2517 for (int i = 0; i < nr_draw_buffers; i++) {
2518 struct GENX(BLEND_STATE_ENTRY) entry = { 0 };
2519 #else
2520 {
2521 #endif
2522
2523 /* _NEW_BUFFERS */
2524 struct gl_renderbuffer *rb = ctx->DrawBuffer->_ColorDrawBuffers[i];
2525
2526 /* Used for implementing the following bit of GL_EXT_texture_integer:
2527 * "Per-fragment operations that require floating-point color
2528 * components, including multisample alpha operations, alpha test,
2529 * blending, and dithering, have no effect when the corresponding
2530 * colors are written to an integer color buffer."
2531 */
2532 bool integer = ctx->DrawBuffer->_IntegerBuffers & (0x1 << i);
2533
2534 /* _NEW_COLOR */
2535 if (ctx->Color.ColorLogicOpEnabled) {
2536 GLenum rb_type = rb ? _mesa_get_format_datatype(rb->Format)
2537 : GL_UNSIGNED_NORMALIZED;
2538 WARN_ONCE(ctx->Color.LogicOp != GL_COPY &&
2539 rb_type != GL_UNSIGNED_NORMALIZED &&
2540 rb_type != GL_FLOAT, "Ignoring %s logic op on %s "
2541 "renderbuffer\n",
2542 _mesa_enum_to_string(ctx->Color.LogicOp),
2543 _mesa_enum_to_string(rb_type));
2544 if (GEN_GEN >= 8 || rb_type == GL_UNSIGNED_NORMALIZED) {
2545 entry.LogicOpEnable = true;
2546 entry.LogicOpFunction =
2547 intel_translate_logic_op(ctx->Color.LogicOp);
2548 }
2549 } else if (ctx->Color.BlendEnabled & (1 << i) && !integer &&
2550 !ctx->Color._AdvancedBlendMode) {
2551 GLenum eqRGB = ctx->Color.Blend[i].EquationRGB;
2552 GLenum eqA = ctx->Color.Blend[i].EquationA;
2553 GLenum srcRGB = ctx->Color.Blend[i].SrcRGB;
2554 GLenum dstRGB = ctx->Color.Blend[i].DstRGB;
2555 GLenum srcA = ctx->Color.Blend[i].SrcA;
2556 GLenum dstA = ctx->Color.Blend[i].DstA;
2557
2558 if (eqRGB == GL_MIN || eqRGB == GL_MAX)
2559 srcRGB = dstRGB = GL_ONE;
2560
2561 if (eqA == GL_MIN || eqA == GL_MAX)
2562 srcA = dstA = GL_ONE;
2563
2564 /* Due to hardware limitations, the destination may have information
2565 * in an alpha channel even when the format specifies no alpha
2566 * channel. In order to avoid getting any incorrect blending due to
2567 * that alpha channel, coerce the blend factors to values that will
2568 * not read the alpha channel, but will instead use the correct
2569 * implicit value for alpha.
2570 */
2571 if (rb && !_mesa_base_format_has_channel(rb->_BaseFormat,
2572 GL_TEXTURE_ALPHA_TYPE)) {
2573 srcRGB = brw_fix_xRGB_alpha(srcRGB);
2574 srcA = brw_fix_xRGB_alpha(srcA);
2575 dstRGB = brw_fix_xRGB_alpha(dstRGB);
2576 dstA = brw_fix_xRGB_alpha(dstA);
2577 }
2578
2579 /* From the BLEND_STATE docs, DWord 0, Bit 29 (AlphaToOne Enable):
2580 * "If Dual Source Blending is enabled, this bit must be disabled."
2581 *
2582 * We override SRC1_ALPHA to ONE and ONE_MINUS_SRC1_ALPHA to ZERO,
2583 * and leave it enabled anyway.
2584 */
2585 if (ctx->Color.Blend[i]._UsesDualSrc && blend.AlphaToOneEnable) {
2586 srcRGB = fix_dual_blend_alpha_to_one(srcRGB);
2587 srcA = fix_dual_blend_alpha_to_one(srcA);
2588 dstRGB = fix_dual_blend_alpha_to_one(dstRGB);
2589 dstA = fix_dual_blend_alpha_to_one(dstA);
2590 }
2591
2592 entry.ColorBufferBlendEnable = true;
2593 entry.DestinationBlendFactor = blend_factor(dstRGB);
2594 entry.SourceBlendFactor = blend_factor(srcRGB);
2595 entry.DestinationAlphaBlendFactor = blend_factor(dstA);
2596 entry.SourceAlphaBlendFactor = blend_factor(srcA);
2597 entry.ColorBlendFunction = blend_eqn(eqRGB);
2598 entry.AlphaBlendFunction = blend_eqn(eqA);
2599
2600 if (srcA != srcRGB || dstA != dstRGB || eqA != eqRGB)
2601 blend.IndependentAlphaBlendEnable = true;
2602 }
2603
2604 /* See section 8.1.6 "Pre-Blend Color Clamping" of the
2605 * SandyBridge PRM Volume 2 Part 1 for HW requirements.
2606 *
2607 * We do our ARB_color_buffer_float CLAMP_FRAGMENT_COLOR
2608 * clamping in the fragment shader. For its clamping of
2609 * blending, the spec says:
2610 *
2611 * "RESOLVED: For fixed-point color buffers, the inputs and
2612 * the result of the blending equation are clamped. For
2613 * floating-point color buffers, no clamping occurs."
2614 *
2615 * So, generally, we want clamping to the render target's range.
2616 * And, good news, the hardware tables for both pre- and
2617 * post-blend color clamping are either ignored, or any are
2618 * allowed, or clamping is required but RT range clamping is a
2619 * valid option.
2620 */
2621 entry.PreBlendColorClampEnable = true;
2622 entry.PostBlendColorClampEnable = true;
2623 entry.ColorClampRange = COLORCLAMP_RTFORMAT;
2624
2625 entry.WriteDisableRed = !ctx->Color.ColorMask[i][0];
2626 entry.WriteDisableGreen = !ctx->Color.ColorMask[i][1];
2627 entry.WriteDisableBlue = !ctx->Color.ColorMask[i][2];
2628 entry.WriteDisableAlpha = !ctx->Color.ColorMask[i][3];
2629
2630 #if GEN_GEN >= 8
2631 GENX(BLEND_STATE_ENTRY_pack)(NULL, &blend_map[1 + i * 2], &entry);
2632 #else
2633 GENX(BLEND_STATE_ENTRY_pack)(NULL, &blend_map[i * 2], &entry);
2634 #endif
2635 }
2636 }
2637
2638 #if GEN_GEN >= 8
2639 GENX(BLEND_STATE_pack)(NULL, blend_map, &blend);
2640 #endif
2641
2642 #if GEN_GEN < 7
2643 brw_batch_emit(brw, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
2644 ptr.PointertoBLEND_STATE = brw->cc.blend_state_offset;
2645 ptr.BLEND_STATEChange = true;
2646 }
2647 #else
2648 brw_batch_emit(brw, GENX(3DSTATE_BLEND_STATE_POINTERS), ptr) {
2649 ptr.BlendStatePointer = brw->cc.blend_state_offset;
2650 #if GEN_GEN >= 8
2651 ptr.BlendStatePointerValid = true;
2652 #endif
2653 }
2654 #endif
2655 }
2656
2657 static const struct brw_tracked_state genX(blend_state) = {
2658 .dirty = {
2659 .mesa = _NEW_BUFFERS |
2660 _NEW_COLOR |
2661 _NEW_MULTISAMPLE,
2662 .brw = BRW_NEW_BATCH |
2663 BRW_NEW_BLORP |
2664 BRW_NEW_STATE_BASE_ADDRESS,
2665 },
2666 .emit = genX(upload_blend_state),
2667 };
2668 #endif
2669
2670 /* ---------------------------------------------------------------------- */
2671
2672 #if GEN_GEN >= 7
2673 UNUSED static const uint32_t push_constant_opcodes[] = {
2674 [MESA_SHADER_VERTEX] = 21,
2675 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2676 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2677 [MESA_SHADER_GEOMETRY] = 22,
2678 [MESA_SHADER_FRAGMENT] = 23,
2679 [MESA_SHADER_COMPUTE] = 0,
2680 };
2681
2682 static void
2683 upload_constant_state(struct brw_context *brw,
2684 struct brw_stage_state *stage_state,
2685 bool active, uint32_t stage)
2686 {
2687 UNUSED uint32_t mocs = GEN_GEN < 8 ? GEN7_MOCS_L3 : 0;
2688 active = active && stage_state->push_const_size != 0;
2689
2690 brw_batch_emit(brw, GENX(3DSTATE_CONSTANT_VS), pkt) {
2691 pkt._3DCommandSubOpcode = push_constant_opcodes[stage];
2692 if (active) {
2693 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2694 pkt.ConstantBody.ReadLength[2] = stage_state->push_const_size;
2695 pkt.ConstantBody.Buffer[2] =
2696 render_ro_bo(brw->curbe.curbe_bo, stage_state->push_const_offset);
2697 #else
2698 pkt.ConstantBody.ReadLength[0] = stage_state->push_const_size;
2699 pkt.ConstantBody.Buffer[0].offset =
2700 stage_state->push_const_offset | mocs;
2701 #endif
2702 }
2703 }
2704
2705 brw->ctx.NewDriverState |= GEN_GEN >= 9 ? BRW_NEW_SURFACES : 0;
2706 }
2707 #endif
2708
2709 #if GEN_GEN >= 6
2710 static void
2711 genX(upload_vs_push_constants)(struct brw_context *brw)
2712 {
2713 struct brw_stage_state *stage_state = &brw->vs.base;
2714
2715 /* _BRW_NEW_VERTEX_PROGRAM */
2716 const struct brw_program *vp = brw_program_const(brw->vertex_program);
2717 /* BRW_NEW_VS_PROG_DATA */
2718 const struct brw_stage_prog_data *prog_data = brw->vs.base.prog_data;
2719
2720 _mesa_shader_write_subroutine_indices(&brw->ctx, MESA_SHADER_VERTEX);
2721 gen6_upload_push_constants(brw, &vp->program, prog_data, stage_state);
2722
2723 #if GEN_GEN >= 7
2724 if (GEN_GEN == 7 && !GEN_IS_HASWELL && !brw->is_baytrail)
2725 gen7_emit_vs_workaround_flush(brw);
2726
2727 upload_constant_state(brw, stage_state, true /* active */,
2728 MESA_SHADER_VERTEX);
2729 #endif
2730 }
2731
2732 static const struct brw_tracked_state genX(vs_push_constants) = {
2733 .dirty = {
2734 .mesa = _NEW_PROGRAM_CONSTANTS |
2735 _NEW_TRANSFORM,
2736 .brw = BRW_NEW_BATCH |
2737 BRW_NEW_BLORP |
2738 BRW_NEW_PUSH_CONSTANT_ALLOCATION |
2739 BRW_NEW_VERTEX_PROGRAM |
2740 BRW_NEW_VS_PROG_DATA,
2741 },
2742 .emit = genX(upload_vs_push_constants),
2743 };
2744
2745 static void
2746 genX(upload_gs_push_constants)(struct brw_context *brw)
2747 {
2748 struct brw_stage_state *stage_state = &brw->gs.base;
2749
2750 /* BRW_NEW_GEOMETRY_PROGRAM */
2751 const struct brw_program *gp = brw_program_const(brw->geometry_program);
2752
2753 if (gp) {
2754 /* BRW_NEW_GS_PROG_DATA */
2755 struct brw_stage_prog_data *prog_data = brw->gs.base.prog_data;
2756
2757 _mesa_shader_write_subroutine_indices(&brw->ctx, MESA_SHADER_GEOMETRY);
2758 gen6_upload_push_constants(brw, &gp->program, prog_data, stage_state);
2759 }
2760
2761 #if GEN_GEN >= 7
2762 upload_constant_state(brw, stage_state, gp, MESA_SHADER_GEOMETRY);
2763 #endif
2764 }
2765
2766 static const struct brw_tracked_state genX(gs_push_constants) = {
2767 .dirty = {
2768 .mesa = _NEW_PROGRAM_CONSTANTS |
2769 _NEW_TRANSFORM,
2770 .brw = BRW_NEW_BATCH |
2771 BRW_NEW_BLORP |
2772 BRW_NEW_GEOMETRY_PROGRAM |
2773 BRW_NEW_GS_PROG_DATA |
2774 BRW_NEW_PUSH_CONSTANT_ALLOCATION,
2775 },
2776 .emit = genX(upload_gs_push_constants),
2777 };
2778
2779 static void
2780 genX(upload_wm_push_constants)(struct brw_context *brw)
2781 {
2782 struct brw_stage_state *stage_state = &brw->wm.base;
2783 /* BRW_NEW_FRAGMENT_PROGRAM */
2784 const struct brw_program *fp = brw_program_const(brw->fragment_program);
2785 /* BRW_NEW_FS_PROG_DATA */
2786 const struct brw_stage_prog_data *prog_data = brw->wm.base.prog_data;
2787
2788 _mesa_shader_write_subroutine_indices(&brw->ctx, MESA_SHADER_FRAGMENT);
2789
2790 gen6_upload_push_constants(brw, &fp->program, prog_data, stage_state);
2791
2792 #if GEN_GEN >= 7
2793 upload_constant_state(brw, stage_state, true, MESA_SHADER_FRAGMENT);
2794 #endif
2795 }
2796
2797 static const struct brw_tracked_state genX(wm_push_constants) = {
2798 .dirty = {
2799 .mesa = _NEW_PROGRAM_CONSTANTS,
2800 .brw = BRW_NEW_BATCH |
2801 BRW_NEW_BLORP |
2802 BRW_NEW_FRAGMENT_PROGRAM |
2803 BRW_NEW_FS_PROG_DATA |
2804 BRW_NEW_PUSH_CONSTANT_ALLOCATION,
2805 },
2806 .emit = genX(upload_wm_push_constants),
2807 };
2808 #endif
2809
2810 /* ---------------------------------------------------------------------- */
2811
2812 #if GEN_GEN >= 6
2813 static unsigned
2814 genX(determine_sample_mask)(struct brw_context *brw)
2815 {
2816 struct gl_context *ctx = &brw->ctx;
2817 float coverage = 1.0f;
2818 float coverage_invert = false;
2819 unsigned sample_mask = ~0u;
2820
2821 /* BRW_NEW_NUM_SAMPLES */
2822 unsigned num_samples = brw->num_samples;
2823
2824 if (_mesa_is_multisample_enabled(ctx)) {
2825 if (ctx->Multisample.SampleCoverage) {
2826 coverage = ctx->Multisample.SampleCoverageValue;
2827 coverage_invert = ctx->Multisample.SampleCoverageInvert;
2828 }
2829 if (ctx->Multisample.SampleMask) {
2830 sample_mask = ctx->Multisample.SampleMaskValue;
2831 }
2832 }
2833
2834 if (num_samples > 1) {
2835 int coverage_int = (int) (num_samples * coverage + 0.5f);
2836 uint32_t coverage_bits = (1 << coverage_int) - 1;
2837 if (coverage_invert)
2838 coverage_bits ^= (1 << num_samples) - 1;
2839 return coverage_bits & sample_mask;
2840 } else {
2841 return 1;
2842 }
2843 }
2844
2845 static void
2846 genX(emit_3dstate_multisample2)(struct brw_context *brw,
2847 unsigned num_samples)
2848 {
2849 assert(brw->num_samples <= 16);
2850
2851 unsigned log2_samples = ffs(MAX2(num_samples, 1)) - 1;
2852
2853 brw_batch_emit(brw, GENX(3DSTATE_MULTISAMPLE), multi) {
2854 multi.PixelLocation = CENTER;
2855 multi.NumberofMultisamples = log2_samples;
2856 #if GEN_GEN == 6
2857 GEN_SAMPLE_POS_4X(multi.Sample);
2858 #elif GEN_GEN == 7
2859 switch (num_samples) {
2860 case 1:
2861 GEN_SAMPLE_POS_1X(multi.Sample);
2862 break;
2863 case 2:
2864 GEN_SAMPLE_POS_2X(multi.Sample);
2865 break;
2866 case 4:
2867 GEN_SAMPLE_POS_4X(multi.Sample);
2868 break;
2869 case 8:
2870 GEN_SAMPLE_POS_8X(multi.Sample);
2871 break;
2872 default:
2873 break;
2874 }
2875 #endif
2876 }
2877 }
2878
2879 static void
2880 genX(upload_multisample_state)(struct brw_context *brw)
2881 {
2882 genX(emit_3dstate_multisample2)(brw, brw->num_samples);
2883
2884 brw_batch_emit(brw, GENX(3DSTATE_SAMPLE_MASK), sm) {
2885 sm.SampleMask = genX(determine_sample_mask)(brw);
2886 }
2887 }
2888
2889 static const struct brw_tracked_state genX(multisample_state) = {
2890 .dirty = {
2891 .mesa = _NEW_MULTISAMPLE,
2892 .brw = BRW_NEW_BLORP |
2893 BRW_NEW_CONTEXT |
2894 BRW_NEW_NUM_SAMPLES,
2895 },
2896 .emit = genX(upload_multisample_state)
2897 };
2898 #endif
2899
2900 /* ---------------------------------------------------------------------- */
2901
2902 #if GEN_GEN >= 6
2903 static void
2904 genX(upload_color_calc_state)(struct brw_context *brw)
2905 {
2906 struct gl_context *ctx = &brw->ctx;
2907
2908 brw_state_emit(brw, GENX(COLOR_CALC_STATE), 64, &brw->cc.state_offset, cc) {
2909 /* _NEW_COLOR */
2910 cc.AlphaTestFormat = ALPHATEST_UNORM8;
2911 UNCLAMPED_FLOAT_TO_UBYTE(cc.AlphaReferenceValueAsUNORM8,
2912 ctx->Color.AlphaRef);
2913
2914 #if GEN_GEN < 9
2915 /* _NEW_STENCIL */
2916 cc.StencilReferenceValue = _mesa_get_stencil_ref(ctx, 0);
2917 cc.BackfaceStencilReferenceValue =
2918 _mesa_get_stencil_ref(ctx, ctx->Stencil._BackFace);
2919 #endif
2920
2921 /* _NEW_COLOR */
2922 cc.BlendConstantColorRed = ctx->Color.BlendColorUnclamped[0];
2923 cc.BlendConstantColorGreen = ctx->Color.BlendColorUnclamped[1];
2924 cc.BlendConstantColorBlue = ctx->Color.BlendColorUnclamped[2];
2925 cc.BlendConstantColorAlpha = ctx->Color.BlendColorUnclamped[3];
2926 }
2927
2928 brw_batch_emit(brw, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
2929 ptr.ColorCalcStatePointer = brw->cc.state_offset;
2930 #if GEN_GEN != 7
2931 ptr.ColorCalcStatePointerValid = true;
2932 #endif
2933 }
2934 }
2935
2936 static const struct brw_tracked_state genX(color_calc_state) = {
2937 .dirty = {
2938 .mesa = _NEW_COLOR |
2939 _NEW_STENCIL,
2940 .brw = BRW_NEW_BATCH |
2941 BRW_NEW_BLORP |
2942 BRW_NEW_CC_STATE |
2943 BRW_NEW_STATE_BASE_ADDRESS,
2944 },
2945 .emit = genX(upload_color_calc_state),
2946 };
2947
2948 #endif
2949
2950 /* ---------------------------------------------------------------------- */
2951
2952 #if GEN_GEN >= 7
2953 static void
2954 genX(upload_sbe)(struct brw_context *brw)
2955 {
2956 struct gl_context *ctx = &brw->ctx;
2957 /* BRW_NEW_FS_PROG_DATA */
2958 const struct brw_wm_prog_data *wm_prog_data =
2959 brw_wm_prog_data(brw->wm.base.prog_data);
2960 #if GEN_GEN >= 8
2961 struct GENX(SF_OUTPUT_ATTRIBUTE_DETAIL) attr_overrides[16] = { { 0 } };
2962 #else
2963 #define attr_overrides sbe.Attribute
2964 #endif
2965 uint32_t urb_entry_read_length;
2966 uint32_t urb_entry_read_offset;
2967 uint32_t point_sprite_enables;
2968
2969 brw_batch_emit(brw, GENX(3DSTATE_SBE), sbe) {
2970 sbe.AttributeSwizzleEnable = true;
2971 sbe.NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs;
2972
2973 /* _NEW_BUFFERS */
2974 bool render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
2975
2976 /* _NEW_POINT
2977 *
2978 * Window coordinates in an FBO are inverted, which means point
2979 * sprite origin must be inverted.
2980 */
2981 if ((ctx->Point.SpriteOrigin == GL_LOWER_LEFT) != render_to_fbo)
2982 sbe.PointSpriteTextureCoordinateOrigin = LOWERLEFT;
2983 else
2984 sbe.PointSpriteTextureCoordinateOrigin = UPPERLEFT;
2985
2986 /* _NEW_POINT | _NEW_LIGHT | _NEW_PROGRAM,
2987 * BRW_NEW_FS_PROG_DATA | BRW_NEW_FRAGMENT_PROGRAM |
2988 * BRW_NEW_GS_PROG_DATA | BRW_NEW_PRIMITIVE | BRW_NEW_TES_PROG_DATA |
2989 * BRW_NEW_VUE_MAP_GEOM_OUT
2990 */
2991 genX(calculate_attr_overrides)(brw,
2992 attr_overrides,
2993 &point_sprite_enables,
2994 &urb_entry_read_length,
2995 &urb_entry_read_offset);
2996
2997 /* Typically, the URB entry read length and offset should be programmed
2998 * in 3DSTATE_VS and 3DSTATE_GS; SBE inherits it from the last active
2999 * stage which produces geometry. However, we don't know the proper
3000 * value until we call calculate_attr_overrides().
3001 *
3002 * To fit with our existing code, we override the inherited values and
3003 * specify it here directly, as we did on previous generations.
3004 */
3005 sbe.VertexURBEntryReadLength = urb_entry_read_length;
3006 sbe.VertexURBEntryReadOffset = urb_entry_read_offset;
3007 sbe.PointSpriteTextureCoordinateEnable = point_sprite_enables;
3008 sbe.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
3009
3010 #if GEN_GEN >= 8
3011 sbe.ForceVertexURBEntryReadLength = true;
3012 sbe.ForceVertexURBEntryReadOffset = true;
3013 #endif
3014
3015 #if GEN_GEN >= 9
3016 /* prepare the active component dwords */
3017 int input_index = 0;
3018 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
3019 if (!(brw->fragment_program->info.inputs_read &
3020 BITFIELD64_BIT(attr))) {
3021 continue;
3022 }
3023
3024 assert(input_index < 32);
3025
3026 sbe.AttributeActiveComponentFormat[input_index] = ACTIVE_COMPONENT_XYZW;
3027 ++input_index;
3028 }
3029 #endif
3030 }
3031
3032 #if GEN_GEN >= 8
3033 brw_batch_emit(brw, GENX(3DSTATE_SBE_SWIZ), sbes) {
3034 for (int i = 0; i < 16; i++)
3035 sbes.Attribute[i] = attr_overrides[i];
3036 }
3037 #endif
3038
3039 #undef attr_overrides
3040 }
3041
3042 static const struct brw_tracked_state genX(sbe_state) = {
3043 .dirty = {
3044 .mesa = _NEW_BUFFERS |
3045 _NEW_LIGHT |
3046 _NEW_POINT |
3047 _NEW_POLYGON |
3048 _NEW_PROGRAM,
3049 .brw = BRW_NEW_BLORP |
3050 BRW_NEW_CONTEXT |
3051 BRW_NEW_FRAGMENT_PROGRAM |
3052 BRW_NEW_FS_PROG_DATA |
3053 BRW_NEW_GS_PROG_DATA |
3054 BRW_NEW_TES_PROG_DATA |
3055 BRW_NEW_VUE_MAP_GEOM_OUT |
3056 (GEN_GEN == 7 ? BRW_NEW_PRIMITIVE
3057 : 0),
3058 },
3059 .emit = genX(upload_sbe),
3060 };
3061 #endif
3062
3063 /* ---------------------------------------------------------------------- */
3064
3065 #if GEN_GEN >= 7
3066 /**
3067 * Outputs the 3DSTATE_SO_DECL_LIST command.
3068 *
3069 * The data output is a series of 64-bit entries containing a SO_DECL per
3070 * stream. We only have one stream of rendering coming out of the GS unit, so
3071 * we only emit stream 0 (low 16 bits) SO_DECLs.
3072 */
3073 static void
3074 genX(upload_3dstate_so_decl_list)(struct brw_context *brw,
3075 const struct brw_vue_map *vue_map)
3076 {
3077 struct gl_context *ctx = &brw->ctx;
3078 /* BRW_NEW_TRANSFORM_FEEDBACK */
3079 struct gl_transform_feedback_object *xfb_obj =
3080 ctx->TransformFeedback.CurrentObject;
3081 const struct gl_transform_feedback_info *linked_xfb_info =
3082 xfb_obj->program->sh.LinkedTransformFeedback;
3083 struct GENX(SO_DECL) so_decl[MAX_VERTEX_STREAMS][128];
3084 int buffer_mask[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
3085 int next_offset[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
3086 int decls[MAX_VERTEX_STREAMS] = {0, 0, 0, 0};
3087 int max_decls = 0;
3088 STATIC_ASSERT(ARRAY_SIZE(so_decl[0]) >= MAX_PROGRAM_OUTPUTS);
3089
3090 memset(so_decl, 0, sizeof(so_decl));
3091
3092 /* Construct the list of SO_DECLs to be emitted. The formatting of the
3093 * command feels strange -- each dword pair contains a SO_DECL per stream.
3094 */
3095 for (unsigned i = 0; i < linked_xfb_info->NumOutputs; i++) {
3096 const struct gl_transform_feedback_output *output =
3097 &linked_xfb_info->Outputs[i];
3098 const int buffer = output->OutputBuffer;
3099 const int varying = output->OutputRegister;
3100 const unsigned stream_id = output->StreamId;
3101 assert(stream_id < MAX_VERTEX_STREAMS);
3102
3103 buffer_mask[stream_id] |= 1 << buffer;
3104
3105 assert(vue_map->varying_to_slot[varying] >= 0);
3106
3107 /* Mesa doesn't store entries for gl_SkipComponents in the Outputs[]
3108 * array. Instead, it simply increments DstOffset for the following
3109 * input by the number of components that should be skipped.
3110 *
3111 * Our hardware is unusual in that it requires us to program SO_DECLs
3112 * for fake "hole" components, rather than simply taking the offset
3113 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
3114 * program as many size = 4 holes as we can, then a final hole to
3115 * accommodate the final 1, 2, or 3 remaining.
3116 */
3117 int skip_components = output->DstOffset - next_offset[buffer];
3118
3119 while (skip_components > 0) {
3120 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
3121 .HoleFlag = 1,
3122 .OutputBufferSlot = output->OutputBuffer,
3123 .ComponentMask = (1 << MIN2(skip_components, 4)) - 1,
3124 };
3125 skip_components -= 4;
3126 }
3127
3128 next_offset[buffer] = output->DstOffset + output->NumComponents;
3129
3130 so_decl[stream_id][decls[stream_id]++] = (struct GENX(SO_DECL)) {
3131 .OutputBufferSlot = output->OutputBuffer,
3132 .RegisterIndex = vue_map->varying_to_slot[varying],
3133 .ComponentMask =
3134 ((1 << output->NumComponents) - 1) << output->ComponentOffset,
3135 };
3136
3137 if (decls[stream_id] > max_decls)
3138 max_decls = decls[stream_id];
3139 }
3140
3141 uint32_t *dw;
3142 dw = brw_batch_emitn(brw, GENX(3DSTATE_SO_DECL_LIST), 3 + 2 * max_decls,
3143 .StreamtoBufferSelects0 = buffer_mask[0],
3144 .StreamtoBufferSelects1 = buffer_mask[1],
3145 .StreamtoBufferSelects2 = buffer_mask[2],
3146 .StreamtoBufferSelects3 = buffer_mask[3],
3147 .NumEntries0 = decls[0],
3148 .NumEntries1 = decls[1],
3149 .NumEntries2 = decls[2],
3150 .NumEntries3 = decls[3]);
3151
3152 for (int i = 0; i < max_decls; i++) {
3153 GENX(SO_DECL_ENTRY_pack)(
3154 brw, dw + 2 + i * 2,
3155 &(struct GENX(SO_DECL_ENTRY)) {
3156 .Stream0Decl = so_decl[0][i],
3157 .Stream1Decl = so_decl[1][i],
3158 .Stream2Decl = so_decl[2][i],
3159 .Stream3Decl = so_decl[3][i],
3160 });
3161 }
3162 }
3163
3164 static void
3165 genX(upload_3dstate_so_buffers)(struct brw_context *brw)
3166 {
3167 struct gl_context *ctx = &brw->ctx;
3168 /* BRW_NEW_TRANSFORM_FEEDBACK */
3169 struct gl_transform_feedback_object *xfb_obj =
3170 ctx->TransformFeedback.CurrentObject;
3171 #if GEN_GEN < 8
3172 const struct gl_transform_feedback_info *linked_xfb_info =
3173 xfb_obj->program->sh.LinkedTransformFeedback;
3174 #else
3175 struct brw_transform_feedback_object *brw_obj =
3176 (struct brw_transform_feedback_object *) xfb_obj;
3177 uint32_t mocs_wb = GEN_GEN >= 9 ? SKL_MOCS_WB : BDW_MOCS_WB;
3178 #endif
3179
3180 /* Set up the up to 4 output buffers. These are the ranges defined in the
3181 * gl_transform_feedback_object.
3182 */
3183 for (int i = 0; i < 4; i++) {
3184 struct intel_buffer_object *bufferobj =
3185 intel_buffer_object(xfb_obj->Buffers[i]);
3186
3187 if (!bufferobj) {
3188 brw_batch_emit(brw, GENX(3DSTATE_SO_BUFFER), sob) {
3189 sob.SOBufferIndex = i;
3190 }
3191 continue;
3192 }
3193
3194 uint32_t start = xfb_obj->Offset[i];
3195 assert(start % 4 == 0);
3196 uint32_t end = ALIGN(start + xfb_obj->Size[i], 4);
3197 struct brw_bo *bo =
3198 intel_bufferobj_buffer(brw, bufferobj, start, end - start);
3199 assert(end <= bo->size);
3200
3201 brw_batch_emit(brw, GENX(3DSTATE_SO_BUFFER), sob) {
3202 sob.SOBufferIndex = i;
3203
3204 sob.SurfaceBaseAddress = render_bo(bo, start);
3205 #if GEN_GEN < 8
3206 sob.SurfacePitch = linked_xfb_info->Buffers[i].Stride * 4;
3207 sob.SurfaceEndAddress = render_bo(bo, end);
3208 #else
3209 sob.SOBufferEnable = true;
3210 sob.StreamOffsetWriteEnable = true;
3211 sob.StreamOutputBufferOffsetAddressEnable = true;
3212 sob.SOBufferMOCS = mocs_wb;
3213
3214 sob.SurfaceSize = MAX2(xfb_obj->Size[i] / 4, 1) - 1;
3215 sob.StreamOutputBufferOffsetAddress =
3216 instruction_bo(brw_obj->offset_bo, i * sizeof(uint32_t));
3217
3218 if (brw_obj->zero_offsets) {
3219 /* Zero out the offset and write that to offset_bo */
3220 sob.StreamOffset = 0;
3221 } else {
3222 /* Use offset_bo as the "Stream Offset." */
3223 sob.StreamOffset = 0xFFFFFFFF;
3224 }
3225 #endif
3226 }
3227 }
3228
3229 #if GEN_GEN >= 8
3230 brw_obj->zero_offsets = false;
3231 #endif
3232 }
3233
3234 static inline bool
3235 query_active(struct gl_query_object *q)
3236 {
3237 return q && q->Active;
3238 }
3239
3240 static void
3241 genX(upload_3dstate_streamout)(struct brw_context *brw, bool active,
3242 const struct brw_vue_map *vue_map)
3243 {
3244 struct gl_context *ctx = &brw->ctx;
3245 /* BRW_NEW_TRANSFORM_FEEDBACK */
3246 struct gl_transform_feedback_object *xfb_obj =
3247 ctx->TransformFeedback.CurrentObject;
3248
3249 brw_batch_emit(brw, GENX(3DSTATE_STREAMOUT), sos) {
3250 if (active) {
3251 int urb_entry_read_offset = 0;
3252 int urb_entry_read_length = (vue_map->num_slots + 1) / 2 -
3253 urb_entry_read_offset;
3254
3255 sos.SOFunctionEnable = true;
3256 sos.SOStatisticsEnable = true;
3257
3258 /* BRW_NEW_RASTERIZER_DISCARD */
3259 if (ctx->RasterDiscard) {
3260 if (!query_active(ctx->Query.PrimitivesGenerated[0])) {
3261 sos.RenderingDisable = true;
3262 } else {
3263 perf_debug("Rasterizer discard with a GL_PRIMITIVES_GENERATED "
3264 "query active relies on the clipper.");
3265 }
3266 }
3267
3268 /* _NEW_LIGHT */
3269 if (ctx->Light.ProvokingVertex != GL_FIRST_VERTEX_CONVENTION)
3270 sos.ReorderMode = TRAILING;
3271
3272 #if GEN_GEN < 8
3273 sos.SOBufferEnable0 = xfb_obj->Buffers[0] != NULL;
3274 sos.SOBufferEnable1 = xfb_obj->Buffers[1] != NULL;
3275 sos.SOBufferEnable2 = xfb_obj->Buffers[2] != NULL;
3276 sos.SOBufferEnable3 = xfb_obj->Buffers[3] != NULL;
3277 #else
3278 const struct gl_transform_feedback_info *linked_xfb_info =
3279 xfb_obj->program->sh.LinkedTransformFeedback;
3280 /* Set buffer pitches; 0 means unbound. */
3281 if (xfb_obj->Buffers[0])
3282 sos.Buffer0SurfacePitch = linked_xfb_info->Buffers[0].Stride * 4;
3283 if (xfb_obj->Buffers[1])
3284 sos.Buffer1SurfacePitch = linked_xfb_info->Buffers[1].Stride * 4;
3285 if (xfb_obj->Buffers[2])
3286 sos.Buffer2SurfacePitch = linked_xfb_info->Buffers[2].Stride * 4;
3287 if (xfb_obj->Buffers[3])
3288 sos.Buffer3SurfacePitch = linked_xfb_info->Buffers[3].Stride * 4;
3289 #endif
3290
3291 /* We always read the whole vertex. This could be reduced at some
3292 * point by reading less and offsetting the register index in the
3293 * SO_DECLs.
3294 */
3295 sos.Stream0VertexReadOffset = urb_entry_read_offset;
3296 sos.Stream0VertexReadLength = urb_entry_read_length - 1;
3297 sos.Stream1VertexReadOffset = urb_entry_read_offset;
3298 sos.Stream1VertexReadLength = urb_entry_read_length - 1;
3299 sos.Stream2VertexReadOffset = urb_entry_read_offset;
3300 sos.Stream2VertexReadLength = urb_entry_read_length - 1;
3301 sos.Stream3VertexReadOffset = urb_entry_read_offset;
3302 sos.Stream3VertexReadLength = urb_entry_read_length - 1;
3303 }
3304 }
3305 }
3306
3307 static void
3308 genX(upload_sol)(struct brw_context *brw)
3309 {
3310 struct gl_context *ctx = &brw->ctx;
3311 /* BRW_NEW_TRANSFORM_FEEDBACK */
3312 bool active = _mesa_is_xfb_active_and_unpaused(ctx);
3313
3314 if (active) {
3315 genX(upload_3dstate_so_buffers)(brw);
3316
3317 /* BRW_NEW_VUE_MAP_GEOM_OUT */
3318 genX(upload_3dstate_so_decl_list)(brw, &brw->vue_map_geom_out);
3319 }
3320
3321 /* Finally, set up the SOL stage. This command must always follow updates to
3322 * the nonpipelined SOL state (3DSTATE_SO_BUFFER, 3DSTATE_SO_DECL_LIST) or
3323 * MMIO register updates (current performed by the kernel at each batch
3324 * emit).
3325 */
3326 genX(upload_3dstate_streamout)(brw, active, &brw->vue_map_geom_out);
3327 }
3328
3329 static const struct brw_tracked_state genX(sol_state) = {
3330 .dirty = {
3331 .mesa = _NEW_LIGHT,
3332 .brw = BRW_NEW_BATCH |
3333 BRW_NEW_BLORP |
3334 BRW_NEW_RASTERIZER_DISCARD |
3335 BRW_NEW_VUE_MAP_GEOM_OUT |
3336 BRW_NEW_TRANSFORM_FEEDBACK,
3337 },
3338 .emit = genX(upload_sol),
3339 };
3340 #endif
3341
3342 /* ---------------------------------------------------------------------- */
3343
3344 #if GEN_GEN >= 7
3345 static void
3346 genX(upload_ps)(struct brw_context *brw)
3347 {
3348 UNUSED const struct gl_context *ctx = &brw->ctx;
3349 UNUSED const struct gen_device_info *devinfo = &brw->screen->devinfo;
3350
3351 /* BRW_NEW_FS_PROG_DATA */
3352 const struct brw_wm_prog_data *prog_data =
3353 brw_wm_prog_data(brw->wm.base.prog_data);
3354 const struct brw_stage_state *stage_state = &brw->wm.base;
3355
3356 #if GEN_GEN < 8
3357 #endif
3358
3359 brw_batch_emit(brw, GENX(3DSTATE_PS), ps) {
3360 /* Initialize the execution mask with VMask. Otherwise, derivatives are
3361 * incorrect for subspans where some of the pixels are unlit. We believe
3362 * the bit just didn't take effect in previous generations.
3363 */
3364 ps.VectorMaskEnable = GEN_GEN >= 8;
3365
3366 ps.SamplerCount =
3367 DIV_ROUND_UP(CLAMP(stage_state->sampler_count, 0, 16), 4);
3368
3369 /* BRW_NEW_FS_PROG_DATA */
3370 ps.BindingTableEntryCount = prog_data->base.binding_table.size_bytes / 4;
3371
3372 if (prog_data->base.use_alt_mode)
3373 ps.FloatingPointMode = Alternate;
3374
3375 /* Haswell requires the sample mask to be set in this packet as well as
3376 * in 3DSTATE_SAMPLE_MASK; the values should match.
3377 */
3378
3379 /* _NEW_BUFFERS, _NEW_MULTISAMPLE */
3380 #if GEN_IS_HASWELL
3381 ps.SampleMask = genX(determine_sample_mask(brw));
3382 #endif
3383
3384 /* 3DSTATE_PS expects the number of threads per PSD, which is always 64;
3385 * it implicitly scales for different GT levels (which have some # of
3386 * PSDs).
3387 *
3388 * In Gen8 the format is U8-2 whereas in Gen9 it is U8-1.
3389 */
3390 #if GEN_GEN >= 9
3391 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
3392 #elif GEN_GEN >= 8
3393 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
3394 #else
3395 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
3396 #endif
3397
3398 if (prog_data->base.nr_params > 0)
3399 ps.PushConstantEnable = true;
3400
3401 #if GEN_GEN < 8
3402 /* From the IVB PRM, volume 2 part 1, page 287:
3403 * "This bit is inserted in the PS payload header and made available to
3404 * the DataPort (either via the message header or via header bypass) to
3405 * indicate that oMask data (one or two phases) is included in Render
3406 * Target Write messages. If present, the oMask data is used to mask off
3407 * samples."
3408 */
3409 ps.oMaskPresenttoRenderTarget = prog_data->uses_omask;
3410
3411 /* The hardware wedges if you have this bit set but don't turn on any
3412 * dual source blend factors.
3413 *
3414 * BRW_NEW_FS_PROG_DATA | _NEW_COLOR
3415 */
3416 ps.DualSourceBlendEnable = prog_data->dual_src_blend &&
3417 (ctx->Color.BlendEnabled & 1) &&
3418 ctx->Color.Blend[0]._UsesDualSrc;
3419
3420 /* BRW_NEW_FS_PROG_DATA */
3421 ps.AttributeEnable = (prog_data->num_varying_inputs != 0);
3422 #endif
3423
3424 /* From the documentation for this packet:
3425 * "If the PS kernel does not need the Position XY Offsets to
3426 * compute a Position Value, then this field should be programmed
3427 * to POSOFFSET_NONE."
3428 *
3429 * "SW Recommendation: If the PS kernel needs the Position Offsets
3430 * to compute a Position XY value, this field should match Position
3431 * ZW Interpolation Mode to ensure a consistent position.xyzw
3432 * computation."
3433 *
3434 * We only require XY sample offsets. So, this recommendation doesn't
3435 * look useful at the moment. We might need this in future.
3436 */
3437 if (prog_data->uses_pos_offset)
3438 ps.PositionXYOffsetSelect = POSOFFSET_SAMPLE;
3439 else
3440 ps.PositionXYOffsetSelect = POSOFFSET_NONE;
3441
3442 ps.RenderTargetFastClearEnable = brw->wm.fast_clear_op;
3443 ps._8PixelDispatchEnable = prog_data->dispatch_8;
3444 ps._16PixelDispatchEnable = prog_data->dispatch_16;
3445 ps.DispatchGRFStartRegisterForConstantSetupData0 =
3446 prog_data->base.dispatch_grf_start_reg;
3447 ps.DispatchGRFStartRegisterForConstantSetupData2 =
3448 prog_data->dispatch_grf_start_reg_2;
3449
3450 ps.KernelStartPointer0 = stage_state->prog_offset;
3451 ps.KernelStartPointer2 = stage_state->prog_offset +
3452 prog_data->prog_offset_2;
3453
3454 if (prog_data->base.total_scratch) {
3455 ps.ScratchSpaceBasePointer =
3456 render_bo(stage_state->scratch_bo,
3457 ffs(stage_state->per_thread_scratch) - 11);
3458 }
3459 }
3460 }
3461
3462 static const struct brw_tracked_state genX(ps_state) = {
3463 .dirty = {
3464 .mesa = _NEW_MULTISAMPLE |
3465 (GEN_GEN < 8 ? _NEW_BUFFERS |
3466 _NEW_COLOR
3467 : 0),
3468 .brw = BRW_NEW_BATCH |
3469 BRW_NEW_BLORP |
3470 BRW_NEW_FS_PROG_DATA,
3471 },
3472 .emit = genX(upload_ps),
3473 };
3474 #endif
3475
3476 /* ---------------------------------------------------------------------- */
3477
3478 #if GEN_GEN >= 7
3479 static void
3480 genX(upload_hs_state)(struct brw_context *brw)
3481 {
3482 const struct gen_device_info *devinfo = &brw->screen->devinfo;
3483 struct brw_stage_state *stage_state = &brw->tcs.base;
3484 struct brw_stage_prog_data *stage_prog_data = stage_state->prog_data;
3485 const struct brw_vue_prog_data *vue_prog_data =
3486 brw_vue_prog_data(stage_prog_data);
3487
3488 /* BRW_NEW_TES_PROG_DATA */
3489 struct brw_tcs_prog_data *tcs_prog_data =
3490 brw_tcs_prog_data(stage_prog_data);
3491
3492 if (!tcs_prog_data) {
3493 brw_batch_emit(brw, GENX(3DSTATE_HS), hs);
3494 } else {
3495 brw_batch_emit(brw, GENX(3DSTATE_HS), hs) {
3496 INIT_THREAD_DISPATCH_FIELDS(hs, Vertex);
3497
3498 hs.InstanceCount = tcs_prog_data->instances - 1;
3499 hs.IncludeVertexHandles = true;
3500
3501 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
3502 }
3503 }
3504 }
3505
3506 static const struct brw_tracked_state genX(hs_state) = {
3507 .dirty = {
3508 .mesa = 0,
3509 .brw = BRW_NEW_BATCH |
3510 BRW_NEW_BLORP |
3511 BRW_NEW_TCS_PROG_DATA |
3512 BRW_NEW_TESS_PROGRAMS,
3513 },
3514 .emit = genX(upload_hs_state),
3515 };
3516
3517 static void
3518 genX(upload_ds_state)(struct brw_context *brw)
3519 {
3520 const struct gen_device_info *devinfo = &brw->screen->devinfo;
3521 const struct brw_stage_state *stage_state = &brw->tes.base;
3522 struct brw_stage_prog_data *stage_prog_data = stage_state->prog_data;
3523
3524 /* BRW_NEW_TES_PROG_DATA */
3525 const struct brw_tes_prog_data *tes_prog_data =
3526 brw_tes_prog_data(stage_prog_data);
3527 const struct brw_vue_prog_data *vue_prog_data =
3528 brw_vue_prog_data(stage_prog_data);
3529
3530 if (!tes_prog_data) {
3531 brw_batch_emit(brw, GENX(3DSTATE_DS), ds);
3532 } else {
3533 brw_batch_emit(brw, GENX(3DSTATE_DS), ds) {
3534 INIT_THREAD_DISPATCH_FIELDS(ds, Patch);
3535
3536 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
3537 ds.ComputeWCoordinateEnable =
3538 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
3539
3540 #if GEN_GEN >= 8
3541 if (vue_prog_data->dispatch_mode == DISPATCH_MODE_SIMD8)
3542 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
3543 ds.UserClipDistanceCullTestEnableBitmask =
3544 vue_prog_data->cull_distance_mask;
3545 #endif
3546 }
3547 }
3548 }
3549
3550 static const struct brw_tracked_state genX(ds_state) = {
3551 .dirty = {
3552 .mesa = 0,
3553 .brw = BRW_NEW_BATCH |
3554 BRW_NEW_BLORP |
3555 BRW_NEW_TESS_PROGRAMS |
3556 BRW_NEW_TES_PROG_DATA,
3557 },
3558 .emit = genX(upload_ds_state),
3559 };
3560
3561 /* ---------------------------------------------------------------------- */
3562
3563 static void
3564 upload_te_state(struct brw_context *brw)
3565 {
3566 /* BRW_NEW_TESS_PROGRAMS */
3567 bool active = brw->tess_eval_program;
3568
3569 /* BRW_NEW_TES_PROG_DATA */
3570 const struct brw_tes_prog_data *tes_prog_data =
3571 brw_tes_prog_data(brw->tes.base.prog_data);
3572
3573 if (active) {
3574 brw_batch_emit(brw, GENX(3DSTATE_TE), te) {
3575 te.Partitioning = tes_prog_data->partitioning;
3576 te.OutputTopology = tes_prog_data->output_topology;
3577 te.TEDomain = tes_prog_data->domain;
3578 te.TEEnable = true;
3579 te.MaximumTessellationFactorOdd = 63.0;
3580 te.MaximumTessellationFactorNotOdd = 64.0;
3581 }
3582 } else {
3583 brw_batch_emit(brw, GENX(3DSTATE_TE), te);
3584 }
3585 }
3586
3587 static const struct brw_tracked_state genX(te_state) = {
3588 .dirty = {
3589 .mesa = 0,
3590 .brw = BRW_NEW_BLORP |
3591 BRW_NEW_CONTEXT |
3592 BRW_NEW_TES_PROG_DATA |
3593 BRW_NEW_TESS_PROGRAMS,
3594 },
3595 .emit = upload_te_state,
3596 };
3597
3598 /* ---------------------------------------------------------------------- */
3599
3600 static void
3601 genX(upload_tes_push_constants)(struct brw_context *brw)
3602 {
3603 struct brw_stage_state *stage_state = &brw->tes.base;
3604 /* BRW_NEW_TESS_PROGRAMS */
3605 const struct brw_program *tep = brw_program_const(brw->tess_eval_program);
3606
3607 if (tep) {
3608 /* BRW_NEW_TES_PROG_DATA */
3609 const struct brw_stage_prog_data *prog_data = brw->tes.base.prog_data;
3610 _mesa_shader_write_subroutine_indices(&brw->ctx, MESA_SHADER_TESS_EVAL);
3611 gen6_upload_push_constants(brw, &tep->program, prog_data, stage_state);
3612 }
3613
3614 upload_constant_state(brw, stage_state, tep, MESA_SHADER_TESS_EVAL);
3615 }
3616
3617 static const struct brw_tracked_state genX(tes_push_constants) = {
3618 .dirty = {
3619 .mesa = _NEW_PROGRAM_CONSTANTS,
3620 .brw = BRW_NEW_BATCH |
3621 BRW_NEW_BLORP |
3622 BRW_NEW_PUSH_CONSTANT_ALLOCATION |
3623 BRW_NEW_TESS_PROGRAMS |
3624 BRW_NEW_TES_PROG_DATA,
3625 },
3626 .emit = genX(upload_tes_push_constants),
3627 };
3628
3629 static void
3630 genX(upload_tcs_push_constants)(struct brw_context *brw)
3631 {
3632 struct brw_stage_state *stage_state = &brw->tcs.base;
3633 /* BRW_NEW_TESS_PROGRAMS */
3634 const struct brw_program *tcp = brw_program_const(brw->tess_ctrl_program);
3635 bool active = brw->tess_eval_program;
3636
3637 if (active) {
3638 /* BRW_NEW_TCS_PROG_DATA */
3639 const struct brw_stage_prog_data *prog_data = brw->tcs.base.prog_data;
3640
3641 _mesa_shader_write_subroutine_indices(&brw->ctx, MESA_SHADER_TESS_CTRL);
3642 gen6_upload_push_constants(brw, &tcp->program, prog_data, stage_state);
3643 }
3644
3645 upload_constant_state(brw, stage_state, active, MESA_SHADER_TESS_CTRL);
3646 }
3647
3648 static const struct brw_tracked_state genX(tcs_push_constants) = {
3649 .dirty = {
3650 .mesa = _NEW_PROGRAM_CONSTANTS,
3651 .brw = BRW_NEW_BATCH |
3652 BRW_NEW_BLORP |
3653 BRW_NEW_DEFAULT_TESS_LEVELS |
3654 BRW_NEW_PUSH_CONSTANT_ALLOCATION |
3655 BRW_NEW_TESS_PROGRAMS |
3656 BRW_NEW_TCS_PROG_DATA,
3657 },
3658 .emit = genX(upload_tcs_push_constants),
3659 };
3660
3661 #endif
3662
3663 /* ---------------------------------------------------------------------- */
3664
3665 #if GEN_GEN >= 7
3666 static void
3667 genX(upload_cs_state)(struct brw_context *brw)
3668 {
3669 if (!brw->cs.base.prog_data)
3670 return;
3671
3672 uint32_t offset;
3673 uint32_t *desc = (uint32_t*) brw_state_batch(
3674 brw, GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t), 64,
3675 &offset);
3676
3677 struct brw_stage_state *stage_state = &brw->cs.base;
3678 struct brw_stage_prog_data *prog_data = stage_state->prog_data;
3679 struct brw_cs_prog_data *cs_prog_data = brw_cs_prog_data(prog_data);
3680 const struct gen_device_info *devinfo = &brw->screen->devinfo;
3681
3682 if (INTEL_DEBUG & DEBUG_SHADER_TIME) {
3683 brw_emit_buffer_surface_state(
3684 brw, &stage_state->surf_offset[
3685 prog_data->binding_table.shader_time_start],
3686 brw->shader_time.bo, 0, ISL_FORMAT_RAW,
3687 brw->shader_time.bo->size, 1, true);
3688 }
3689
3690 uint32_t *bind = brw_state_batch(brw, prog_data->binding_table.size_bytes,
3691 32, &stage_state->bind_bo_offset);
3692
3693 brw_batch_emit(brw, GENX(MEDIA_VFE_STATE), vfe) {
3694 if (prog_data->total_scratch) {
3695 uint32_t bo_offset;
3696
3697 if (GEN_GEN >= 8) {
3698 /* Broadwell's Per Thread Scratch Space is in the range [0, 11]
3699 * where 0 = 1k, 1 = 2k, 2 = 4k, ..., 11 = 2M.
3700 */
3701 bo_offset = ffs(stage_state->per_thread_scratch) - 11;
3702 } else if (GEN_IS_HASWELL) {
3703 /* Haswell's Per Thread Scratch Space is in the range [0, 10]
3704 * where 0 = 2k, 1 = 4k, 2 = 8k, ..., 10 = 2M.
3705 */
3706 bo_offset = ffs(stage_state->per_thread_scratch) - 12;
3707 } else {
3708 /* Earlier platforms use the range [0, 11] to mean [1kB, 12kB]
3709 * where 0 = 1kB, 1 = 2kB, 2 = 3kB, ..., 11 = 12kB.
3710 */
3711 bo_offset = stage_state->per_thread_scratch / 1024 - 1;
3712 }
3713 vfe.ScratchSpaceBasePointer =
3714 render_bo(stage_state->scratch_bo, bo_offset);
3715 }
3716
3717 const uint32_t subslices = MAX2(brw->screen->subslice_total, 1);
3718 vfe.MaximumNumberofThreads = devinfo->max_cs_threads * subslices - 1;
3719 vfe.NumberofURBEntries = GEN_GEN >= 8 ? 2 : 0;
3720 vfe.ResetGatewayTimer =
3721 Resettingrelativetimerandlatchingtheglobaltimestamp;
3722 #if GEN_GEN < 9
3723 vfe.BypassGatewayControl = BypassingOpenGatewayCloseGatewayprotocol;
3724 #endif
3725 #if GEN_GEN == 7
3726 vfe.GPGPUMode = 1;
3727 #endif
3728
3729 /* We are uploading duplicated copies of push constant uniforms for each
3730 * thread. Although the local id data needs to vary per thread, it won't
3731 * change for other uniform data. Unfortunately this duplication is
3732 * required for gen7. As of Haswell, this duplication can be avoided,
3733 * but this older mechanism with duplicated data continues to work.
3734 *
3735 * FINISHME: As of Haswell, we could make use of the
3736 * INTERFACE_DESCRIPTOR_DATA "Cross-Thread Constant Data Read Length"
3737 * field to only store one copy of uniform data.
3738 *
3739 * FINISHME: Broadwell adds a new alternative "Indirect Payload Storage"
3740 * which is described in the GPGPU_WALKER command and in the Broadwell
3741 * PRM Volume 7: 3D Media GPGPU, under Media GPGPU Pipeline => Mode of
3742 * Operations => GPGPU Mode => Indirect Payload Storage.
3743 *
3744 * Note: The constant data is built in brw_upload_cs_push_constants
3745 * below.
3746 */
3747 vfe.URBEntryAllocationSize = GEN_GEN >= 8 ? 2 : 0;
3748
3749 const uint32_t vfe_curbe_allocation =
3750 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
3751 cs_prog_data->push.cross_thread.regs, 2);
3752 vfe.CURBEAllocationSize = vfe_curbe_allocation;
3753 }
3754
3755 if (cs_prog_data->push.total.size > 0) {
3756 brw_batch_emit(brw, GENX(MEDIA_CURBE_LOAD), curbe) {
3757 curbe.CURBETotalDataLength =
3758 ALIGN(cs_prog_data->push.total.size, 64);
3759 curbe.CURBEDataStartAddress = stage_state->push_const_offset;
3760 }
3761 }
3762
3763 /* BRW_NEW_SURFACES and BRW_NEW_*_CONSTBUF */
3764 memcpy(bind, stage_state->surf_offset,
3765 prog_data->binding_table.size_bytes);
3766 const struct GENX(INTERFACE_DESCRIPTOR_DATA) idd = {
3767 .KernelStartPointer = brw->cs.base.prog_offset,
3768 .SamplerStatePointer = stage_state->sampler_offset,
3769 .SamplerCount = DIV_ROUND_UP(stage_state->sampler_count, 4) >> 2,
3770 .BindingTablePointer = stage_state->bind_bo_offset,
3771 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
3772 .NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads,
3773 .SharedLocalMemorySize = encode_slm_size(devinfo->gen,
3774 prog_data->total_shared),
3775 .BarrierEnable = cs_prog_data->uses_barrier,
3776 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3777 .CrossThreadConstantDataReadLength =
3778 cs_prog_data->push.cross_thread.regs,
3779 #endif
3780 };
3781
3782 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(brw, desc, &idd);
3783
3784 brw_batch_emit(brw, GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), load) {
3785 load.InterfaceDescriptorTotalLength =
3786 GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
3787 load.InterfaceDescriptorDataStartAddress = offset;
3788 }
3789 }
3790
3791 static const struct brw_tracked_state genX(cs_state) = {
3792 .dirty = {
3793 .mesa = _NEW_PROGRAM_CONSTANTS,
3794 .brw = BRW_NEW_BATCH |
3795 BRW_NEW_BLORP |
3796 BRW_NEW_CS_PROG_DATA |
3797 BRW_NEW_SAMPLER_STATE_TABLE |
3798 BRW_NEW_SURFACES,
3799 },
3800 .emit = genX(upload_cs_state)
3801 };
3802
3803 #endif
3804
3805 /* ---------------------------------------------------------------------- */
3806
3807 #if GEN_GEN >= 8
3808 static void
3809 genX(upload_raster)(struct brw_context *brw)
3810 {
3811 struct gl_context *ctx = &brw->ctx;
3812
3813 /* _NEW_BUFFERS */
3814 bool render_to_fbo = _mesa_is_user_fbo(ctx->DrawBuffer);
3815
3816 /* _NEW_POLYGON */
3817 struct gl_polygon_attrib *polygon = &ctx->Polygon;
3818
3819 /* _NEW_POINT */
3820 struct gl_point_attrib *point = &ctx->Point;
3821
3822 brw_batch_emit(brw, GENX(3DSTATE_RASTER), raster) {
3823 if (polygon->_FrontBit == render_to_fbo)
3824 raster.FrontWinding = CounterClockwise;
3825
3826 if (polygon->CullFlag) {
3827 switch (polygon->CullFaceMode) {
3828 case GL_FRONT:
3829 raster.CullMode = CULLMODE_FRONT;
3830 break;
3831 case GL_BACK:
3832 raster.CullMode = CULLMODE_BACK;
3833 break;
3834 case GL_FRONT_AND_BACK:
3835 raster.CullMode = CULLMODE_BOTH;
3836 break;
3837 default:
3838 unreachable("not reached");
3839 }
3840 } else {
3841 raster.CullMode = CULLMODE_NONE;
3842 }
3843
3844 point->SmoothFlag = raster.SmoothPointEnable;
3845
3846 raster.DXMultisampleRasterizationEnable =
3847 _mesa_is_multisample_enabled(ctx);
3848
3849 raster.GlobalDepthOffsetEnableSolid = polygon->OffsetFill;
3850 raster.GlobalDepthOffsetEnableWireframe = polygon->OffsetLine;
3851 raster.GlobalDepthOffsetEnablePoint = polygon->OffsetPoint;
3852
3853 switch (polygon->FrontMode) {
3854 case GL_FILL:
3855 raster.FrontFaceFillMode = FILL_MODE_SOLID;
3856 break;
3857 case GL_LINE:
3858 raster.FrontFaceFillMode = FILL_MODE_WIREFRAME;
3859 break;
3860 case GL_POINT:
3861 raster.FrontFaceFillMode = FILL_MODE_POINT;
3862 break;
3863 default:
3864 unreachable("not reached");
3865 }
3866
3867 switch (polygon->BackMode) {
3868 case GL_FILL:
3869 raster.BackFaceFillMode = FILL_MODE_SOLID;
3870 break;
3871 case GL_LINE:
3872 raster.BackFaceFillMode = FILL_MODE_WIREFRAME;
3873 break;
3874 case GL_POINT:
3875 raster.BackFaceFillMode = FILL_MODE_POINT;
3876 break;
3877 default:
3878 unreachable("not reached");
3879 }
3880
3881 /* _NEW_LINE */
3882 raster.AntialiasingEnable = ctx->Line.SmoothFlag;
3883
3884 /* _NEW_SCISSOR */
3885 raster.ScissorRectangleEnable = ctx->Scissor.EnableFlags;
3886
3887 /* _NEW_TRANSFORM */
3888 if (!ctx->Transform.DepthClamp) {
3889 #if GEN_GEN >= 9
3890 raster.ViewportZFarClipTestEnable = true;
3891 raster.ViewportZNearClipTestEnable = true;
3892 #else
3893 raster.ViewportZClipTestEnable = true;
3894 #endif
3895 }
3896
3897 /* BRW_NEW_CONSERVATIVE_RASTERIZATION */
3898 #if GEN_GEN >= 9
3899 raster.ConservativeRasterizationEnable =
3900 ctx->IntelConservativeRasterization;
3901 #endif
3902
3903 raster.GlobalDepthOffsetClamp = polygon->OffsetClamp;
3904 raster.GlobalDepthOffsetScale = polygon->OffsetFactor;
3905
3906 raster.GlobalDepthOffsetConstant = polygon->OffsetUnits * 2;
3907 }
3908 }
3909
3910 static const struct brw_tracked_state genX(raster_state) = {
3911 .dirty = {
3912 .mesa = _NEW_BUFFERS |
3913 _NEW_LINE |
3914 _NEW_MULTISAMPLE |
3915 _NEW_POINT |
3916 _NEW_POLYGON |
3917 _NEW_SCISSOR |
3918 _NEW_TRANSFORM,
3919 .brw = BRW_NEW_BLORP |
3920 BRW_NEW_CONTEXT |
3921 BRW_NEW_CONSERVATIVE_RASTERIZATION,
3922 },
3923 .emit = genX(upload_raster),
3924 };
3925 #endif
3926
3927 /* ---------------------------------------------------------------------- */
3928
3929 #if GEN_GEN >= 8
3930 static void
3931 genX(upload_ps_extra)(struct brw_context *brw)
3932 {
3933 UNUSED struct gl_context *ctx = &brw->ctx;
3934
3935 const struct brw_wm_prog_data *prog_data =
3936 brw_wm_prog_data(brw->wm.base.prog_data);
3937
3938 brw_batch_emit(brw, GENX(3DSTATE_PS_EXTRA), psx) {
3939 psx.PixelShaderValid = true;
3940 psx.PixelShaderComputedDepthMode = prog_data->computed_depth_mode;
3941 psx.PixelShaderKillsPixel = prog_data->uses_kill;
3942 psx.AttributeEnable = prog_data->num_varying_inputs != 0;
3943 psx.PixelShaderUsesSourceDepth = prog_data->uses_src_depth;
3944 psx.PixelShaderUsesSourceW = prog_data->uses_src_w;
3945 psx.PixelShaderIsPerSample = prog_data->persample_dispatch;
3946
3947 /* _NEW_MULTISAMPLE | BRW_NEW_CONSERVATIVE_RASTERIZATION */
3948 if (prog_data->uses_sample_mask) {
3949 #if GEN_GEN >= 9
3950 if (prog_data->post_depth_coverage)
3951 psx.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
3952 else if (prog_data->inner_coverage && ctx->IntelConservativeRasterization)
3953 psx.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
3954 else
3955 psx.InputCoverageMaskState = ICMS_NORMAL;
3956 #else
3957 psx.PixelShaderUsesInputCoverageMask = true;
3958 #endif
3959 }
3960
3961 psx.oMaskPresenttoRenderTarget = prog_data->uses_omask;
3962 #if GEN_GEN >= 9
3963 psx.PixelShaderPullsBary = prog_data->pulls_bary;
3964 psx.PixelShaderComputesStencil = prog_data->computed_stencil;
3965 #endif
3966
3967 /* The stricter cross-primitive coherency guarantees that the hardware
3968 * gives us with the "Accesses UAV" bit set for at least one shader stage
3969 * and the "UAV coherency required" bit set on the 3DPRIMITIVE command
3970 * are redundant within the current image, atomic counter and SSBO GL
3971 * APIs, which all have very loose ordering and coherency requirements
3972 * and generally rely on the application to insert explicit barriers when
3973 * a shader invocation is expected to see the memory writes performed by
3974 * the invocations of some previous primitive. Regardless of the value
3975 * of "UAV coherency required", the "Accesses UAV" bits will implicitly
3976 * cause an in most cases useless DC flush when the lowermost stage with
3977 * the bit set finishes execution.
3978 *
3979 * It would be nice to disable it, but in some cases we can't because on
3980 * Gen8+ it also has an influence on rasterization via the PS UAV-only
3981 * signal (which could be set independently from the coherency mechanism
3982 * in the 3DSTATE_WM command on Gen7), and because in some cases it will
3983 * determine whether the hardware skips execution of the fragment shader
3984 * or not via the ThreadDispatchEnable signal. However if we know that
3985 * GEN8_PS_BLEND_HAS_WRITEABLE_RT is going to be set and
3986 * GEN8_PSX_PIXEL_SHADER_NO_RT_WRITE is not set it shouldn't make any
3987 * difference so we may just disable it here.
3988 *
3989 * Gen8 hardware tries to compute ThreadDispatchEnable for us but doesn't
3990 * take into account KillPixels when no depth or stencil writes are
3991 * enabled. In order for occlusion queries to work correctly with no
3992 * attachments, we need to force-enable here.
3993 *
3994 * BRW_NEW_FS_PROG_DATA | BRW_NEW_FRAGMENT_PROGRAM | _NEW_BUFFERS |
3995 * _NEW_COLOR
3996 */
3997 if ((prog_data->has_side_effects || prog_data->uses_kill) &&
3998 !brw_color_buffer_write_enabled(brw))
3999 psx.PixelShaderHasUAV = true;
4000 }
4001 }
4002
4003 const struct brw_tracked_state genX(ps_extra) = {
4004 .dirty = {
4005 .mesa = _NEW_BUFFERS | _NEW_COLOR,
4006 .brw = BRW_NEW_BLORP |
4007 BRW_NEW_CONTEXT |
4008 BRW_NEW_FRAGMENT_PROGRAM |
4009 BRW_NEW_FS_PROG_DATA |
4010 BRW_NEW_CONSERVATIVE_RASTERIZATION,
4011 },
4012 .emit = genX(upload_ps_extra),
4013 };
4014 #endif
4015
4016 /* ---------------------------------------------------------------------- */
4017
4018 #if GEN_GEN >= 8
4019 static void
4020 genX(upload_ps_blend)(struct brw_context *brw)
4021 {
4022 struct gl_context *ctx = &brw->ctx;
4023
4024 /* _NEW_BUFFERS */
4025 struct gl_renderbuffer *rb = ctx->DrawBuffer->_ColorDrawBuffers[0];
4026 const bool buffer0_is_integer = ctx->DrawBuffer->_IntegerBuffers & 0x1;
4027
4028 /* _NEW_COLOR */
4029 struct gl_colorbuffer_attrib *color = &ctx->Color;
4030
4031 brw_batch_emit(brw, GENX(3DSTATE_PS_BLEND), pb) {
4032 /* BRW_NEW_FRAGMENT_PROGRAM | _NEW_BUFFERS | _NEW_COLOR */
4033 pb.HasWriteableRT = brw_color_buffer_write_enabled(brw);
4034
4035 bool alpha_to_one = false;
4036
4037 if (!buffer0_is_integer) {
4038 /* _NEW_MULTISAMPLE */
4039
4040 if (_mesa_is_multisample_enabled(ctx)) {
4041 pb.AlphaToCoverageEnable = ctx->Multisample.SampleAlphaToCoverage;
4042 alpha_to_one = ctx->Multisample.SampleAlphaToOne;
4043 }
4044
4045 pb.AlphaTestEnable = color->AlphaEnabled;
4046 }
4047
4048 /* Used for implementing the following bit of GL_EXT_texture_integer:
4049 * "Per-fragment operations that require floating-point color
4050 * components, including multisample alpha operations, alpha test,
4051 * blending, and dithering, have no effect when the corresponding
4052 * colors are written to an integer color buffer."
4053 *
4054 * The OpenGL specification 3.3 (page 196), section 4.1.3 says:
4055 * "If drawbuffer zero is not NONE and the buffer it references has an
4056 * integer format, the SAMPLE_ALPHA_TO_COVERAGE and SAMPLE_ALPHA_TO_ONE
4057 * operations are skipped."
4058 */
4059 if (rb && !buffer0_is_integer && (color->BlendEnabled & 1)) {
4060 GLenum eqRGB = color->Blend[0].EquationRGB;
4061 GLenum eqA = color->Blend[0].EquationA;
4062 GLenum srcRGB = color->Blend[0].SrcRGB;
4063 GLenum dstRGB = color->Blend[0].DstRGB;
4064 GLenum srcA = color->Blend[0].SrcA;
4065 GLenum dstA = color->Blend[0].DstA;
4066
4067 if (eqRGB == GL_MIN || eqRGB == GL_MAX)
4068 srcRGB = dstRGB = GL_ONE;
4069
4070 if (eqA == GL_MIN || eqA == GL_MAX)
4071 srcA = dstA = GL_ONE;
4072
4073 /* Due to hardware limitations, the destination may have information
4074 * in an alpha channel even when the format specifies no alpha
4075 * channel. In order to avoid getting any incorrect blending due to
4076 * that alpha channel, coerce the blend factors to values that will
4077 * not read the alpha channel, but will instead use the correct
4078 * implicit value for alpha.
4079 */
4080 if (!_mesa_base_format_has_channel(rb->_BaseFormat,
4081 GL_TEXTURE_ALPHA_TYPE)) {
4082 srcRGB = brw_fix_xRGB_alpha(srcRGB);
4083 srcA = brw_fix_xRGB_alpha(srcA);
4084 dstRGB = brw_fix_xRGB_alpha(dstRGB);
4085 dstA = brw_fix_xRGB_alpha(dstA);
4086 }
4087
4088 /* Alpha to One doesn't work with Dual Color Blending. Override
4089 * SRC1_ALPHA to ONE and ONE_MINUS_SRC1_ALPHA to ZERO.
4090 */
4091 if (alpha_to_one && color->Blend[0]._UsesDualSrc) {
4092 srcRGB = fix_dual_blend_alpha_to_one(srcRGB);
4093 srcA = fix_dual_blend_alpha_to_one(srcA);
4094 dstRGB = fix_dual_blend_alpha_to_one(dstRGB);
4095 dstA = fix_dual_blend_alpha_to_one(dstA);
4096 }
4097
4098 pb.ColorBufferBlendEnable = true;
4099 pb.SourceAlphaBlendFactor = brw_translate_blend_factor(srcA);
4100 pb.DestinationAlphaBlendFactor = brw_translate_blend_factor(dstA);
4101 pb.SourceBlendFactor = brw_translate_blend_factor(srcRGB);
4102 pb.DestinationBlendFactor = brw_translate_blend_factor(dstRGB);
4103
4104 pb.IndependentAlphaBlendEnable =
4105 srcA != srcRGB || dstA != dstRGB || eqA != eqRGB;
4106 }
4107 }
4108 }
4109
4110 static const struct brw_tracked_state genX(ps_blend) = {
4111 .dirty = {
4112 .mesa = _NEW_BUFFERS |
4113 _NEW_COLOR |
4114 _NEW_MULTISAMPLE,
4115 .brw = BRW_NEW_BLORP |
4116 BRW_NEW_CONTEXT |
4117 BRW_NEW_FRAGMENT_PROGRAM,
4118 },
4119 .emit = genX(upload_ps_blend)
4120 };
4121 #endif
4122
4123 /* ---------------------------------------------------------------------- */
4124
4125 #if GEN_GEN >= 8
4126 static void
4127 genX(emit_vf_topology)(struct brw_context *brw)
4128 {
4129 brw_batch_emit(brw, GENX(3DSTATE_VF_TOPOLOGY), vftopo) {
4130 vftopo.PrimitiveTopologyType = brw->primitive;
4131 }
4132 }
4133
4134 static const struct brw_tracked_state genX(vf_topology) = {
4135 .dirty = {
4136 .mesa = 0,
4137 .brw = BRW_NEW_BLORP |
4138 BRW_NEW_PRIMITIVE,
4139 },
4140 .emit = genX(emit_vf_topology),
4141 };
4142 #endif
4143
4144 /* ---------------------------------------------------------------------- */
4145
4146 void
4147 genX(init_atoms)(struct brw_context *brw)
4148 {
4149 #if GEN_GEN < 6
4150 static const struct brw_tracked_state *render_atoms[] =
4151 {
4152 /* Once all the programs are done, we know how large urb entry
4153 * sizes need to be and can decide if we need to change the urb
4154 * layout.
4155 */
4156 &brw_curbe_offsets,
4157 &brw_recalculate_urb_fence,
4158
4159 &genX(cc_vp),
4160 &brw_cc_unit,
4161
4162 /* Surface state setup. Must come before the VS/WM unit. The binding
4163 * table upload must be last.
4164 */
4165 &brw_vs_pull_constants,
4166 &brw_wm_pull_constants,
4167 &brw_renderbuffer_surfaces,
4168 &brw_renderbuffer_read_surfaces,
4169 &brw_texture_surfaces,
4170 &brw_vs_binding_table,
4171 &brw_wm_binding_table,
4172
4173 &brw_fs_samplers,
4174 &brw_vs_samplers,
4175
4176 /* These set up state for brw_psp_urb_cbs */
4177 &brw_wm_unit,
4178 &genX(sf_clip_viewport),
4179 &brw_sf_unit,
4180 &genX(vs_state), /* always required, enabled or not */
4181 &brw_clip_unit,
4182 &brw_gs_unit,
4183
4184 /* Command packets:
4185 */
4186 &brw_invariant_state,
4187
4188 &brw_binding_table_pointers,
4189 &brw_blend_constant_color,
4190
4191 &brw_depthbuffer,
4192
4193 &genX(polygon_stipple),
4194 &genX(polygon_stipple_offset),
4195
4196 &genX(line_stipple),
4197
4198 &brw_psp_urb_cbs,
4199
4200 &genX(drawing_rect),
4201 &brw_indices, /* must come before brw_vertices */
4202 &genX(index_buffer),
4203 &genX(vertices),
4204
4205 &brw_constant_buffer
4206 };
4207 #elif GEN_GEN == 6
4208 static const struct brw_tracked_state *render_atoms[] =
4209 {
4210 &genX(sf_clip_viewport),
4211
4212 /* Command packets: */
4213
4214 &genX(cc_vp),
4215
4216 &gen6_urb,
4217 &genX(blend_state), /* must do before cc unit */
4218 &genX(color_calc_state), /* must do before cc unit */
4219 &genX(depth_stencil_state), /* must do before cc unit */
4220
4221 &genX(vs_push_constants), /* Before vs_state */
4222 &genX(gs_push_constants), /* Before gs_state */
4223 &genX(wm_push_constants), /* Before wm_state */
4224
4225 /* Surface state setup. Must come before the VS/WM unit. The binding
4226 * table upload must be last.
4227 */
4228 &brw_vs_pull_constants,
4229 &brw_vs_ubo_surfaces,
4230 &brw_gs_pull_constants,
4231 &brw_gs_ubo_surfaces,
4232 &brw_wm_pull_constants,
4233 &brw_wm_ubo_surfaces,
4234 &gen6_renderbuffer_surfaces,
4235 &brw_renderbuffer_read_surfaces,
4236 &brw_texture_surfaces,
4237 &gen6_sol_surface,
4238 &brw_vs_binding_table,
4239 &gen6_gs_binding_table,
4240 &brw_wm_binding_table,
4241
4242 &brw_fs_samplers,
4243 &brw_vs_samplers,
4244 &brw_gs_samplers,
4245 &gen6_sampler_state,
4246 &genX(multisample_state),
4247
4248 &genX(vs_state),
4249 &genX(gs_state),
4250 &genX(clip_state),
4251 &genX(sf_state),
4252 &genX(wm_state),
4253
4254 &genX(scissor_state),
4255
4256 &gen6_binding_table_pointers,
4257
4258 &brw_depthbuffer,
4259
4260 &genX(polygon_stipple),
4261 &genX(polygon_stipple_offset),
4262
4263 &genX(line_stipple),
4264
4265 &genX(drawing_rect),
4266
4267 &brw_indices, /* must come before brw_vertices */
4268 &genX(index_buffer),
4269 &genX(vertices),
4270 };
4271 #elif GEN_GEN == 7
4272 static const struct brw_tracked_state *render_atoms[] =
4273 {
4274 /* Command packets: */
4275
4276 &genX(cc_vp),
4277 &genX(sf_clip_viewport),
4278
4279 &gen7_l3_state,
4280 &gen7_push_constant_space,
4281 &gen7_urb,
4282 &genX(blend_state), /* must do before cc unit */
4283 &genX(color_calc_state), /* must do before cc unit */
4284 &genX(depth_stencil_state), /* must do before cc unit */
4285
4286 &brw_vs_image_surfaces, /* Before vs push/pull constants and binding table */
4287 &brw_tcs_image_surfaces, /* Before tcs push/pull constants and binding table */
4288 &brw_tes_image_surfaces, /* Before tes push/pull constants and binding table */
4289 &brw_gs_image_surfaces, /* Before gs push/pull constants and binding table */
4290 &brw_wm_image_surfaces, /* Before wm push/pull constants and binding table */
4291
4292 &genX(vs_push_constants), /* Before vs_state */
4293 &genX(tcs_push_constants),
4294 &genX(tes_push_constants),
4295 &genX(gs_push_constants), /* Before gs_state */
4296 &genX(wm_push_constants), /* Before wm_surfaces and constant_buffer */
4297
4298 /* Surface state setup. Must come before the VS/WM unit. The binding
4299 * table upload must be last.
4300 */
4301 &brw_vs_pull_constants,
4302 &brw_vs_ubo_surfaces,
4303 &brw_vs_abo_surfaces,
4304 &brw_tcs_pull_constants,
4305 &brw_tcs_ubo_surfaces,
4306 &brw_tcs_abo_surfaces,
4307 &brw_tes_pull_constants,
4308 &brw_tes_ubo_surfaces,
4309 &brw_tes_abo_surfaces,
4310 &brw_gs_pull_constants,
4311 &brw_gs_ubo_surfaces,
4312 &brw_gs_abo_surfaces,
4313 &brw_wm_pull_constants,
4314 &brw_wm_ubo_surfaces,
4315 &brw_wm_abo_surfaces,
4316 &gen6_renderbuffer_surfaces,
4317 &brw_renderbuffer_read_surfaces,
4318 &brw_texture_surfaces,
4319 &brw_vs_binding_table,
4320 &brw_tcs_binding_table,
4321 &brw_tes_binding_table,
4322 &brw_gs_binding_table,
4323 &brw_wm_binding_table,
4324
4325 &brw_fs_samplers,
4326 &brw_vs_samplers,
4327 &brw_tcs_samplers,
4328 &brw_tes_samplers,
4329 &brw_gs_samplers,
4330 &genX(multisample_state),
4331
4332 &genX(vs_state),
4333 &genX(hs_state),
4334 &genX(te_state),
4335 &genX(ds_state),
4336 &genX(gs_state),
4337 &genX(sol_state),
4338 &genX(clip_state),
4339 &genX(sbe_state),
4340 &genX(sf_state),
4341 &genX(wm_state),
4342 &genX(ps_state),
4343
4344 &genX(scissor_state),
4345
4346 &gen7_depthbuffer,
4347
4348 &genX(polygon_stipple),
4349 &genX(polygon_stipple_offset),
4350
4351 &genX(line_stipple),
4352
4353 &genX(drawing_rect),
4354
4355 &brw_indices, /* must come before brw_vertices */
4356 &genX(index_buffer),
4357 &genX(vertices),
4358
4359 #if GEN_IS_HASWELL
4360 &genX(cut_index),
4361 #endif
4362 };
4363 #elif GEN_GEN >= 8
4364 static const struct brw_tracked_state *render_atoms[] =
4365 {
4366 &genX(cc_vp),
4367 &genX(sf_clip_viewport),
4368
4369 &gen7_l3_state,
4370 &gen7_push_constant_space,
4371 &gen7_urb,
4372 &genX(blend_state),
4373 &genX(color_calc_state),
4374
4375 &brw_vs_image_surfaces, /* Before vs push/pull constants and binding table */
4376 &brw_tcs_image_surfaces, /* Before tcs push/pull constants and binding table */
4377 &brw_tes_image_surfaces, /* Before tes push/pull constants and binding table */
4378 &brw_gs_image_surfaces, /* Before gs push/pull constants and binding table */
4379 &brw_wm_image_surfaces, /* Before wm push/pull constants and binding table */
4380
4381 &genX(vs_push_constants), /* Before vs_state */
4382 &genX(tcs_push_constants),
4383 &genX(tes_push_constants),
4384 &genX(gs_push_constants), /* Before gs_state */
4385 &genX(wm_push_constants), /* Before wm_surfaces and constant_buffer */
4386
4387 /* Surface state setup. Must come before the VS/WM unit. The binding
4388 * table upload must be last.
4389 */
4390 &brw_vs_pull_constants,
4391 &brw_vs_ubo_surfaces,
4392 &brw_vs_abo_surfaces,
4393 &brw_tcs_pull_constants,
4394 &brw_tcs_ubo_surfaces,
4395 &brw_tcs_abo_surfaces,
4396 &brw_tes_pull_constants,
4397 &brw_tes_ubo_surfaces,
4398 &brw_tes_abo_surfaces,
4399 &brw_gs_pull_constants,
4400 &brw_gs_ubo_surfaces,
4401 &brw_gs_abo_surfaces,
4402 &brw_wm_pull_constants,
4403 &brw_wm_ubo_surfaces,
4404 &brw_wm_abo_surfaces,
4405 &gen6_renderbuffer_surfaces,
4406 &brw_renderbuffer_read_surfaces,
4407 &brw_texture_surfaces,
4408 &brw_vs_binding_table,
4409 &brw_tcs_binding_table,
4410 &brw_tes_binding_table,
4411 &brw_gs_binding_table,
4412 &brw_wm_binding_table,
4413
4414 &brw_fs_samplers,
4415 &brw_vs_samplers,
4416 &brw_tcs_samplers,
4417 &brw_tes_samplers,
4418 &brw_gs_samplers,
4419 &genX(multisample_state),
4420
4421 &genX(vs_state),
4422 &genX(hs_state),
4423 &genX(te_state),
4424 &genX(ds_state),
4425 &genX(gs_state),
4426 &genX(sol_state),
4427 &genX(clip_state),
4428 &genX(raster_state),
4429 &genX(sbe_state),
4430 &genX(sf_state),
4431 &genX(ps_blend),
4432 &genX(ps_extra),
4433 &genX(ps_state),
4434 &genX(depth_stencil_state),
4435 &genX(wm_state),
4436
4437 &genX(scissor_state),
4438
4439 &gen7_depthbuffer,
4440
4441 &genX(polygon_stipple),
4442 &genX(polygon_stipple_offset),
4443
4444 &genX(line_stipple),
4445
4446 &genX(drawing_rect),
4447
4448 &genX(vf_topology),
4449
4450 &brw_indices,
4451 &genX(index_buffer),
4452 &genX(vertices),
4453
4454 &genX(cut_index),
4455 &gen8_pma_fix,
4456 };
4457 #endif
4458
4459 STATIC_ASSERT(ARRAY_SIZE(render_atoms) <= ARRAY_SIZE(brw->render_atoms));
4460 brw_copy_pipeline_atoms(brw, BRW_RENDER_PIPELINE,
4461 render_atoms, ARRAY_SIZE(render_atoms));
4462
4463 #if GEN_GEN >= 7
4464 static const struct brw_tracked_state *compute_atoms[] =
4465 {
4466 &gen7_l3_state,
4467 &brw_cs_image_surfaces,
4468 &gen7_cs_push_constants,
4469 &brw_cs_pull_constants,
4470 &brw_cs_ubo_surfaces,
4471 &brw_cs_abo_surfaces,
4472 &brw_cs_texture_surfaces,
4473 &brw_cs_work_groups_surface,
4474 &brw_cs_samplers,
4475 &genX(cs_state),
4476 };
4477
4478 STATIC_ASSERT(ARRAY_SIZE(compute_atoms) <= ARRAY_SIZE(brw->compute_atoms));
4479 brw_copy_pipeline_atoms(brw, BRW_COMPUTE_PIPELINE,
4480 compute_atoms, ARRAY_SIZE(compute_atoms));
4481 #endif
4482 }