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