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