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