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