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