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