anv: Stop using cs_prog_data->threads
[mesa.git] / src / intel / vulkan / genX_pipeline.c
1 /*
2 * Copyright © 2015 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 "anv_private.h"
25
26 #include "genxml/gen_macros.h"
27 #include "genxml/genX_pack.h"
28
29 #include "common/gen_l3_config.h"
30 #include "common/gen_sample_positions.h"
31 #include "nir/nir_xfb_info.h"
32 #include "vk_util.h"
33 #include "vk_format_info.h"
34
35 static uint32_t
36 vertex_element_comp_control(enum isl_format format, unsigned comp)
37 {
38 uint8_t bits;
39 switch (comp) {
40 case 0: bits = isl_format_layouts[format].channels.r.bits; break;
41 case 1: bits = isl_format_layouts[format].channels.g.bits; break;
42 case 2: bits = isl_format_layouts[format].channels.b.bits; break;
43 case 3: bits = isl_format_layouts[format].channels.a.bits; break;
44 default: unreachable("Invalid component");
45 }
46
47 /*
48 * Take in account hardware restrictions when dealing with 64-bit floats.
49 *
50 * From Broadwell spec, command reference structures, page 586:
51 * "When SourceElementFormat is set to one of the *64*_PASSTHRU formats,
52 * 64-bit components are stored * in the URB without any conversion. In
53 * this case, vertex elements must be written as 128 or 256 bits, with
54 * VFCOMP_STORE_0 being used to pad the output as required. E.g., if
55 * R64_PASSTHRU is used to copy a 64-bit Red component into the URB,
56 * Component 1 must be specified as VFCOMP_STORE_0 (with Components 2,3
57 * set to VFCOMP_NOSTORE) in order to output a 128-bit vertex element, or
58 * Components 1-3 must be specified as VFCOMP_STORE_0 in order to output
59 * a 256-bit vertex element. Likewise, use of R64G64B64_PASSTHRU requires
60 * Component 3 to be specified as VFCOMP_STORE_0 in order to output a
61 * 256-bit vertex element."
62 */
63 if (bits) {
64 return VFCOMP_STORE_SRC;
65 } else if (comp >= 2 &&
66 !isl_format_layouts[format].channels.b.bits &&
67 isl_format_layouts[format].channels.r.type == ISL_RAW) {
68 /* When emitting 64-bit attributes, we need to write either 128 or 256
69 * bit chunks, using VFCOMP_NOSTORE when not writing the chunk, and
70 * VFCOMP_STORE_0 to pad the written chunk */
71 return VFCOMP_NOSTORE;
72 } else if (comp < 3 ||
73 isl_format_layouts[format].channels.r.type == ISL_RAW) {
74 /* Note we need to pad with value 0, not 1, due hardware restrictions
75 * (see comment above) */
76 return VFCOMP_STORE_0;
77 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
78 isl_format_layouts[format].channels.r.type == ISL_SINT) {
79 assert(comp == 3);
80 return VFCOMP_STORE_1_INT;
81 } else {
82 assert(comp == 3);
83 return VFCOMP_STORE_1_FP;
84 }
85 }
86
87 static void
88 emit_vertex_input(struct anv_graphics_pipeline *pipeline,
89 const VkPipelineVertexInputStateCreateInfo *info)
90 {
91 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
92
93 /* Pull inputs_read out of the VS prog data */
94 const uint64_t inputs_read = vs_prog_data->inputs_read;
95 const uint64_t double_inputs_read =
96 vs_prog_data->double_inputs_read & inputs_read;
97 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
98 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
99 const uint32_t elements_double = double_inputs_read >> VERT_ATTRIB_GENERIC0;
100 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
101 vs_prog_data->uses_instanceid ||
102 vs_prog_data->uses_firstvertex ||
103 vs_prog_data->uses_baseinstance;
104
105 uint32_t elem_count = __builtin_popcount(elements) -
106 __builtin_popcount(elements_double) / 2;
107
108 const uint32_t total_elems =
109 MAX2(1, elem_count + needs_svgs_elem + vs_prog_data->uses_drawid);
110
111 uint32_t *p;
112
113 const uint32_t num_dwords = 1 + total_elems * 2;
114 p = anv_batch_emitn(&pipeline->base.batch, num_dwords,
115 GENX(3DSTATE_VERTEX_ELEMENTS));
116 if (!p)
117 return;
118
119 for (uint32_t i = 0; i < total_elems; i++) {
120 /* The SKL docs for VERTEX_ELEMENT_STATE say:
121 *
122 * "All elements must be valid from Element[0] to the last valid
123 * element. (I.e. if Element[2] is valid then Element[1] and
124 * Element[0] must also be valid)."
125 *
126 * The SKL docs for 3D_Vertex_Component_Control say:
127 *
128 * "Don't store this component. (Not valid for Component 0, but can
129 * be used for Component 1-3)."
130 *
131 * So we can't just leave a vertex element blank and hope for the best.
132 * We have to tell the VF hardware to put something in it; so we just
133 * store a bunch of zero.
134 *
135 * TODO: Compact vertex elements so we never end up with holes.
136 */
137 struct GENX(VERTEX_ELEMENT_STATE) element = {
138 .Valid = true,
139 .Component0Control = VFCOMP_STORE_0,
140 .Component1Control = VFCOMP_STORE_0,
141 .Component2Control = VFCOMP_STORE_0,
142 .Component3Control = VFCOMP_STORE_0,
143 };
144 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + i * 2], &element);
145 }
146
147 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
148 const VkVertexInputAttributeDescription *desc =
149 &info->pVertexAttributeDescriptions[i];
150 enum isl_format format = anv_get_isl_format(&pipeline->base.device->info,
151 desc->format,
152 VK_IMAGE_ASPECT_COLOR_BIT,
153 VK_IMAGE_TILING_LINEAR);
154
155 assert(desc->binding < MAX_VBS);
156
157 if ((elements & (1 << desc->location)) == 0)
158 continue; /* Binding unused */
159
160 uint32_t slot =
161 __builtin_popcount(elements & ((1 << desc->location) - 1)) -
162 DIV_ROUND_UP(__builtin_popcount(elements_double &
163 ((1 << desc->location) -1)), 2);
164
165 struct GENX(VERTEX_ELEMENT_STATE) element = {
166 .VertexBufferIndex = desc->binding,
167 .Valid = true,
168 .SourceElementFormat = format,
169 .EdgeFlagEnable = false,
170 .SourceElementOffset = desc->offset,
171 .Component0Control = vertex_element_comp_control(format, 0),
172 .Component1Control = vertex_element_comp_control(format, 1),
173 .Component2Control = vertex_element_comp_control(format, 2),
174 .Component3Control = vertex_element_comp_control(format, 3),
175 };
176 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
177
178 #if GEN_GEN >= 8
179 /* On Broadwell and later, we have a separate VF_INSTANCING packet
180 * that controls instancing. On Haswell and prior, that's part of
181 * VERTEX_BUFFER_STATE which we emit later.
182 */
183 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
184 vfi.InstancingEnable = pipeline->vb[desc->binding].instanced;
185 vfi.VertexElementIndex = slot;
186 vfi.InstanceDataStepRate =
187 pipeline->vb[desc->binding].instance_divisor;
188 }
189 #endif
190 }
191
192 const uint32_t id_slot = elem_count;
193 if (needs_svgs_elem) {
194 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
195 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
196 * Control field is set to something other than VFCOMP_STORE_SRC,
197 * no higher-numbered Component Control fields may be set to
198 * VFCOMP_STORE_SRC"
199 *
200 * This means, that if we have BaseInstance, we need BaseVertex as
201 * well. Just do all or nothing.
202 */
203 uint32_t base_ctrl = (vs_prog_data->uses_firstvertex ||
204 vs_prog_data->uses_baseinstance) ?
205 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
206
207 struct GENX(VERTEX_ELEMENT_STATE) element = {
208 .VertexBufferIndex = ANV_SVGS_VB_INDEX,
209 .Valid = true,
210 .SourceElementFormat = ISL_FORMAT_R32G32_UINT,
211 .Component0Control = base_ctrl,
212 .Component1Control = base_ctrl,
213 #if GEN_GEN >= 8
214 .Component2Control = VFCOMP_STORE_0,
215 .Component3Control = VFCOMP_STORE_0,
216 #else
217 .Component2Control = VFCOMP_STORE_VID,
218 .Component3Control = VFCOMP_STORE_IID,
219 #endif
220 };
221 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
222 }
223
224 #if GEN_GEN >= 8
225 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_SGVS), sgvs) {
226 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
227 sgvs.VertexIDComponentNumber = 2;
228 sgvs.VertexIDElementOffset = id_slot;
229 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
230 sgvs.InstanceIDComponentNumber = 3;
231 sgvs.InstanceIDElementOffset = id_slot;
232 }
233 #endif
234
235 const uint32_t drawid_slot = elem_count + needs_svgs_elem;
236 if (vs_prog_data->uses_drawid) {
237 struct GENX(VERTEX_ELEMENT_STATE) element = {
238 .VertexBufferIndex = ANV_DRAWID_VB_INDEX,
239 .Valid = true,
240 .SourceElementFormat = ISL_FORMAT_R32_UINT,
241 .Component0Control = VFCOMP_STORE_SRC,
242 .Component1Control = VFCOMP_STORE_0,
243 .Component2Control = VFCOMP_STORE_0,
244 .Component3Control = VFCOMP_STORE_0,
245 };
246 GENX(VERTEX_ELEMENT_STATE_pack)(NULL,
247 &p[1 + drawid_slot * 2],
248 &element);
249
250 #if GEN_GEN >= 8
251 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
252 vfi.VertexElementIndex = drawid_slot;
253 }
254 #endif
255 }
256 }
257
258 void
259 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
260 const struct gen_l3_config *l3_config,
261 VkShaderStageFlags active_stages,
262 const unsigned entry_size[4],
263 enum gen_urb_deref_block_size *deref_block_size)
264 {
265 const struct gen_device_info *devinfo = &device->info;
266
267 unsigned entries[4];
268 unsigned start[4];
269 gen_get_urb_config(devinfo, l3_config,
270 active_stages &
271 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
272 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
273 entry_size, entries, start, deref_block_size);
274
275 #if GEN_GEN == 7 && !GEN_IS_HASWELL
276 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
277 *
278 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
279 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
280 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
281 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
282 * needs to be sent before any combination of VS associated 3DSTATE."
283 */
284 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
285 pc.DepthStallEnable = true;
286 pc.PostSyncOperation = WriteImmediateData;
287 pc.Address = (struct anv_address) { device->workaround_bo, 0 };
288 }
289 #endif
290
291 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
292 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
293 urb._3DCommandSubOpcode += i;
294 urb.VSURBStartingAddress = start[i];
295 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
296 urb.VSNumberofURBEntries = entries[i];
297 }
298 }
299 }
300
301 static void
302 emit_urb_setup(struct anv_graphics_pipeline *pipeline,
303 enum gen_urb_deref_block_size *deref_block_size)
304 {
305 unsigned entry_size[4];
306 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
307 const struct brw_vue_prog_data *prog_data =
308 !anv_pipeline_has_stage(pipeline, i) ? NULL :
309 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
310
311 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
312 }
313
314 genX(emit_urb_setup)(pipeline->base.device, &pipeline->base.batch,
315 pipeline->base.l3_config,
316 pipeline->active_stages, entry_size,
317 deref_block_size);
318 }
319
320 static void
321 emit_3dstate_sbe(struct anv_graphics_pipeline *pipeline)
322 {
323 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
324
325 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
326 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_SBE), sbe);
327 #if GEN_GEN >= 8
328 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_SBE_SWIZ), sbe);
329 #endif
330 return;
331 }
332
333 const struct brw_vue_map *fs_input_map =
334 &anv_pipeline_get_last_vue_prog_data(pipeline)->vue_map;
335
336 struct GENX(3DSTATE_SBE) sbe = {
337 GENX(3DSTATE_SBE_header),
338 .AttributeSwizzleEnable = true,
339 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
340 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
341 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
342 };
343
344 #if GEN_GEN >= 9
345 for (unsigned i = 0; i < 32; i++)
346 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
347 #endif
348
349 #if GEN_GEN >= 8
350 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
351 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
352 GENX(3DSTATE_SBE_SWIZ_header),
353 };
354 #else
355 # define swiz sbe
356 #endif
357
358 int first_slot = brw_compute_first_urb_slot_required(wm_prog_data->inputs,
359 fs_input_map);
360 assert(first_slot % 2 == 0);
361 unsigned urb_entry_read_offset = first_slot / 2;
362 int max_source_attr = 0;
363 for (uint8_t idx = 0; idx < wm_prog_data->urb_setup_attribs_count; idx++) {
364 uint8_t attr = wm_prog_data->urb_setup_attribs[idx];
365 int input_index = wm_prog_data->urb_setup[attr];
366
367 assert(0 <= input_index);
368
369 /* gl_Viewport and gl_Layer are stored in the VUE header */
370 if (attr == VARYING_SLOT_VIEWPORT || attr == VARYING_SLOT_LAYER) {
371 continue;
372 }
373
374 if (attr == VARYING_SLOT_PNTC) {
375 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
376 continue;
377 }
378
379 const int slot = fs_input_map->varying_to_slot[attr];
380
381 if (slot == -1) {
382 /* This attribute does not exist in the VUE--that means that the
383 * vertex shader did not write to it. It could be that it's a
384 * regular varying read by the fragment shader but not written by
385 * the vertex shader or it's gl_PrimitiveID. In the first case the
386 * value is undefined, in the second it needs to be
387 * gl_PrimitiveID.
388 */
389 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
390 swiz.Attribute[input_index].ComponentOverrideX = true;
391 swiz.Attribute[input_index].ComponentOverrideY = true;
392 swiz.Attribute[input_index].ComponentOverrideZ = true;
393 swiz.Attribute[input_index].ComponentOverrideW = true;
394 continue;
395 }
396
397 /* We have to subtract two slots to accout for the URB entry output
398 * read offset in the VS and GS stages.
399 */
400 const int source_attr = slot - 2 * urb_entry_read_offset;
401 assert(source_attr >= 0 && source_attr < 32);
402 max_source_attr = MAX2(max_source_attr, source_attr);
403 /* The hardware can only do overrides on 16 overrides at a time, and the
404 * other up to 16 have to be lined up so that the input index = the
405 * output index. We'll need to do some tweaking to make sure that's the
406 * case.
407 */
408 if (input_index < 16)
409 swiz.Attribute[input_index].SourceAttribute = source_attr;
410 else
411 assert(source_attr == input_index);
412 }
413
414 sbe.VertexURBEntryReadOffset = urb_entry_read_offset;
415 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
416 #if GEN_GEN >= 8
417 sbe.ForceVertexURBEntryReadOffset = true;
418 sbe.ForceVertexURBEntryReadLength = true;
419 #endif
420
421 uint32_t *dw = anv_batch_emit_dwords(&pipeline->base.batch,
422 GENX(3DSTATE_SBE_length));
423 if (!dw)
424 return;
425 GENX(3DSTATE_SBE_pack)(&pipeline->base.batch, dw, &sbe);
426
427 #if GEN_GEN >= 8
428 dw = anv_batch_emit_dwords(&pipeline->base.batch, GENX(3DSTATE_SBE_SWIZ_length));
429 if (!dw)
430 return;
431 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->base.batch, dw, &swiz);
432 #endif
433 }
434
435 static const uint32_t vk_to_gen_cullmode[] = {
436 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
437 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
438 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
439 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
440 };
441
442 static const uint32_t vk_to_gen_fillmode[] = {
443 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
444 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
445 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
446 };
447
448 static const uint32_t vk_to_gen_front_face[] = {
449 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
450 [VK_FRONT_FACE_CLOCKWISE] = 0
451 };
452
453 static VkLineRasterizationModeEXT
454 vk_line_rasterization_mode(const VkPipelineRasterizationLineStateCreateInfoEXT *line_info,
455 const VkPipelineMultisampleStateCreateInfo *ms_info)
456 {
457 VkLineRasterizationModeEXT line_mode =
458 line_info ? line_info->lineRasterizationMode :
459 VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT;
460
461 if (line_mode == VK_LINE_RASTERIZATION_MODE_DEFAULT_EXT) {
462 if (ms_info && ms_info->rasterizationSamples > 1) {
463 return VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT;
464 } else {
465 return VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT;
466 }
467 }
468
469 return line_mode;
470 }
471
472 /** Returns the final polygon mode for rasterization
473 *
474 * This function takes into account polygon mode, primitive topology and the
475 * different shader stages which might generate their own type of primitives.
476 */
477 static VkPolygonMode
478 anv_raster_polygon_mode(struct anv_graphics_pipeline *pipeline,
479 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
480 const VkPipelineRasterizationStateCreateInfo *rs_info)
481 {
482 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
483 switch (get_gs_prog_data(pipeline)->output_topology) {
484 case _3DPRIM_POINTLIST:
485 return VK_POLYGON_MODE_POINT;
486
487 case _3DPRIM_LINELIST:
488 case _3DPRIM_LINESTRIP:
489 case _3DPRIM_LINELOOP:
490 return VK_POLYGON_MODE_LINE;
491
492 case _3DPRIM_TRILIST:
493 case _3DPRIM_TRIFAN:
494 case _3DPRIM_TRISTRIP:
495 case _3DPRIM_RECTLIST:
496 case _3DPRIM_QUADLIST:
497 case _3DPRIM_QUADSTRIP:
498 case _3DPRIM_POLYGON:
499 return rs_info->polygonMode;
500 }
501 unreachable("Unsupported GS output topology");
502 } else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
503 switch (get_tes_prog_data(pipeline)->output_topology) {
504 case BRW_TESS_OUTPUT_TOPOLOGY_POINT:
505 return VK_POLYGON_MODE_POINT;
506
507 case BRW_TESS_OUTPUT_TOPOLOGY_LINE:
508 return VK_POLYGON_MODE_LINE;
509
510 case BRW_TESS_OUTPUT_TOPOLOGY_TRI_CW:
511 case BRW_TESS_OUTPUT_TOPOLOGY_TRI_CCW:
512 return rs_info->polygonMode;
513 }
514 unreachable("Unsupported TCS output topology");
515 } else {
516 switch (ia_info->topology) {
517 case VK_PRIMITIVE_TOPOLOGY_POINT_LIST:
518 return VK_POLYGON_MODE_POINT;
519
520 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST:
521 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP:
522 case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY:
523 case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY:
524 return VK_POLYGON_MODE_LINE;
525
526 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST:
527 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP:
528 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN:
529 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY:
530 case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY:
531 return rs_info->polygonMode;
532
533 default:
534 unreachable("Unsupported primitive topology");
535 }
536 }
537 }
538
539 #if GEN_GEN <= 7
540 static uint32_t
541 gen7_ms_rast_mode(struct anv_graphics_pipeline *pipeline,
542 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
543 const VkPipelineRasterizationStateCreateInfo *rs_info,
544 const VkPipelineMultisampleStateCreateInfo *ms_info)
545 {
546 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info =
547 vk_find_struct_const(rs_info->pNext,
548 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
549
550 VkPolygonMode raster_mode =
551 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
552 if (raster_mode == VK_POLYGON_MODE_LINE) {
553 switch (vk_line_rasterization_mode(line_info, ms_info)) {
554 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT:
555 return MSRASTMODE_ON_PATTERN;
556
557 case VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT:
558 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT:
559 return MSRASTMODE_OFF_PIXEL;
560
561 default:
562 unreachable("Unsupported line rasterization mode");
563 }
564 } else {
565 return (ms_info && ms_info->rasterizationSamples > 1) ?
566 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
567 }
568 }
569 #endif
570
571 static void
572 emit_rs_state(struct anv_graphics_pipeline *pipeline,
573 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
574 const VkPipelineRasterizationStateCreateInfo *rs_info,
575 const VkPipelineMultisampleStateCreateInfo *ms_info,
576 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info,
577 const struct anv_render_pass *pass,
578 const struct anv_subpass *subpass,
579 enum gen_urb_deref_block_size urb_deref_block_size)
580 {
581 struct GENX(3DSTATE_SF) sf = {
582 GENX(3DSTATE_SF_header),
583 };
584
585 sf.ViewportTransformEnable = true;
586 sf.StatisticsEnable = true;
587 sf.TriangleStripListProvokingVertexSelect = 0;
588 sf.LineStripListProvokingVertexSelect = 0;
589 sf.TriangleFanProvokingVertexSelect = 1;
590 sf.VertexSubPixelPrecisionSelect = _8Bit;
591 sf.AALineDistanceMode = true;
592
593 #if GEN_IS_HASWELL
594 sf.LineStippleEnable = line_info && line_info->stippledLineEnable;
595 #endif
596
597 #if GEN_GEN >= 12
598 sf.DerefBlockSize = urb_deref_block_size;
599 #endif
600
601 const struct brw_vue_prog_data *last_vue_prog_data =
602 anv_pipeline_get_last_vue_prog_data(pipeline);
603
604 if (last_vue_prog_data->vue_map.slots_valid & VARYING_BIT_PSIZ) {
605 sf.PointWidthSource = Vertex;
606 } else {
607 sf.PointWidthSource = State;
608 sf.PointWidth = 1.0;
609 }
610
611 #if GEN_GEN >= 8
612 struct GENX(3DSTATE_RASTER) raster = {
613 GENX(3DSTATE_RASTER_header),
614 };
615 #else
616 # define raster sf
617 #endif
618
619 VkPolygonMode raster_mode =
620 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
621 VkLineRasterizationModeEXT line_mode =
622 vk_line_rasterization_mode(line_info, ms_info);
623
624 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
625 * "Multisample Modes State".
626 */
627 #if GEN_GEN >= 8
628 if (raster_mode == VK_POLYGON_MODE_LINE) {
629 /* Unfortunately, configuring our line rasterization hardware on gen8
630 * and later is rather painful. Instead of giving us bits to tell the
631 * hardware what line mode to use like we had on gen7, we now have an
632 * arcane combination of API Mode and MSAA enable bits which do things
633 * in a table which are expected to magically put the hardware into the
634 * right mode for your API. Sadly, Vulkan isn't any of the APIs the
635 * hardware people thought of so nothing works the way you want it to.
636 *
637 * Look at the table titled "Multisample Rasterization Modes" in Vol 7
638 * of the Skylake PRM for more details.
639 */
640 switch (line_mode) {
641 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_EXT:
642 raster.APIMode = DX100;
643 raster.DXMultisampleRasterizationEnable = true;
644 break;
645
646 case VK_LINE_RASTERIZATION_MODE_BRESENHAM_EXT:
647 case VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT:
648 raster.APIMode = DX9OGL;
649 raster.DXMultisampleRasterizationEnable = false;
650 break;
651
652 default:
653 unreachable("Unsupported line rasterization mode");
654 }
655 } else {
656 raster.APIMode = DX100;
657 raster.DXMultisampleRasterizationEnable = true;
658 }
659
660 /* NOTE: 3DSTATE_RASTER::ForcedSampleCount affects the BDW and SKL PMA fix
661 * computations. If we ever set this bit to a different value, they will
662 * need to be updated accordingly.
663 */
664 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
665 raster.ForceMultisampling = false;
666 #else
667 raster.MultisampleRasterizationMode =
668 gen7_ms_rast_mode(pipeline, ia_info, rs_info, ms_info);
669 #endif
670
671 if (raster_mode == VK_POLYGON_MODE_LINE &&
672 line_mode == VK_LINE_RASTERIZATION_MODE_RECTANGULAR_SMOOTH_EXT)
673 raster.AntialiasingEnable = true;
674
675 raster.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
676 raster.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
677 raster.FrontFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
678 raster.BackFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
679 raster.ScissorRectangleEnable = true;
680
681 #if GEN_GEN >= 9
682 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
683 raster.ViewportZFarClipTestEnable = pipeline->depth_clip_enable;
684 raster.ViewportZNearClipTestEnable = pipeline->depth_clip_enable;
685 #elif GEN_GEN >= 8
686 raster.ViewportZClipTestEnable = pipeline->depth_clip_enable;
687 #endif
688
689 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
690 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
691 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
692
693 #if GEN_GEN == 7
694 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
695 * can get the depth offsets correct.
696 */
697 if (subpass->depth_stencil_attachment) {
698 VkFormat vk_format =
699 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
700 assert(vk_format_is_depth_or_stencil(vk_format));
701 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
702 enum isl_format isl_format =
703 anv_get_isl_format(&pipeline->base.device->info, vk_format,
704 VK_IMAGE_ASPECT_DEPTH_BIT,
705 VK_IMAGE_TILING_OPTIMAL);
706 sf.DepthBufferSurfaceFormat =
707 isl_format_get_depth_format(isl_format, false);
708 }
709 }
710 #endif
711
712 #if GEN_GEN >= 8
713 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
714 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
715 #else
716 # undef raster
717 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
718 #endif
719 }
720
721 static void
722 emit_ms_state(struct anv_graphics_pipeline *pipeline,
723 const VkPipelineMultisampleStateCreateInfo *info)
724 {
725 uint32_t samples = 1;
726 uint32_t log2_samples = 0;
727
728 /* From the Vulkan 1.0 spec:
729 * If pSampleMask is NULL, it is treated as if the mask has all bits
730 * enabled, i.e. no coverage is removed from fragments.
731 *
732 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
733 */
734 #if GEN_GEN >= 8
735 uint32_t sample_mask = 0xffff;
736 #else
737 uint32_t sample_mask = 0xff;
738 #endif
739
740 if (info) {
741 samples = info->rasterizationSamples;
742 log2_samples = __builtin_ffs(samples) - 1;
743 }
744
745 if (info && info->pSampleMask)
746 sample_mask &= info->pSampleMask[0];
747
748 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_MULTISAMPLE), ms) {
749 ms.NumberofMultisamples = log2_samples;
750
751 ms.PixelLocation = CENTER;
752 #if GEN_GEN >= 8
753 /* The PRM says that this bit is valid only for DX9:
754 *
755 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
756 * should not have any effect by setting or not setting this bit.
757 */
758 ms.PixelPositionOffsetEnable = false;
759 #else
760
761 switch (samples) {
762 case 1:
763 GEN_SAMPLE_POS_1X(ms.Sample);
764 break;
765 case 2:
766 GEN_SAMPLE_POS_2X(ms.Sample);
767 break;
768 case 4:
769 GEN_SAMPLE_POS_4X(ms.Sample);
770 break;
771 case 8:
772 GEN_SAMPLE_POS_8X(ms.Sample);
773 break;
774 default:
775 break;
776 }
777 #endif
778 }
779
780 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
781 sm.SampleMask = sample_mask;
782 }
783 }
784
785 static const uint32_t vk_to_gen_logic_op[] = {
786 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
787 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
788 [VK_LOGIC_OP_AND] = LOGICOP_AND,
789 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
790 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
791 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
792 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
793 [VK_LOGIC_OP_OR] = LOGICOP_OR,
794 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
795 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
796 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
797 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
798 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
799 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
800 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
801 [VK_LOGIC_OP_SET] = LOGICOP_SET,
802 };
803
804 static const uint32_t vk_to_gen_blend[] = {
805 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
806 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
807 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
808 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
809 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
810 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
811 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
812 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
813 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
814 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
815 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
816 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
817 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
818 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
819 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
820 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
821 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
822 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
823 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
824 };
825
826 static const uint32_t vk_to_gen_blend_op[] = {
827 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
828 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
829 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
830 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
831 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
832 };
833
834 static const uint32_t vk_to_gen_compare_op[] = {
835 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
836 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
837 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
838 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
839 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
840 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
841 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
842 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
843 };
844
845 static const uint32_t vk_to_gen_stencil_op[] = {
846 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
847 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
848 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
849 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
850 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
851 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
852 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
853 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
854 };
855
856 /* This function sanitizes the VkStencilOpState by looking at the compare ops
857 * and trying to determine whether or not a given stencil op can ever actually
858 * occur. Stencil ops which can never occur are set to VK_STENCIL_OP_KEEP.
859 * This function returns true if, after sanitation, any of the stencil ops are
860 * set to something other than VK_STENCIL_OP_KEEP.
861 */
862 static bool
863 sanitize_stencil_face(VkStencilOpState *face,
864 VkCompareOp depthCompareOp)
865 {
866 /* If compareOp is ALWAYS then the stencil test will never fail and failOp
867 * will never happen. Set failOp to KEEP in this case.
868 */
869 if (face->compareOp == VK_COMPARE_OP_ALWAYS)
870 face->failOp = VK_STENCIL_OP_KEEP;
871
872 /* If compareOp is NEVER or depthCompareOp is NEVER then one of the depth
873 * or stencil tests will fail and passOp will never happen.
874 */
875 if (face->compareOp == VK_COMPARE_OP_NEVER ||
876 depthCompareOp == VK_COMPARE_OP_NEVER)
877 face->passOp = VK_STENCIL_OP_KEEP;
878
879 /* If compareOp is NEVER or depthCompareOp is ALWAYS then either the
880 * stencil test will fail or the depth test will pass. In either case,
881 * depthFailOp will never happen.
882 */
883 if (face->compareOp == VK_COMPARE_OP_NEVER ||
884 depthCompareOp == VK_COMPARE_OP_ALWAYS)
885 face->depthFailOp = VK_STENCIL_OP_KEEP;
886
887 return face->failOp != VK_STENCIL_OP_KEEP ||
888 face->depthFailOp != VK_STENCIL_OP_KEEP ||
889 face->passOp != VK_STENCIL_OP_KEEP;
890 }
891
892 /* Intel hardware is fairly sensitive to whether or not depth/stencil writes
893 * are enabled. In the presence of discards, it's fairly easy to get into the
894 * non-promoted case which means a fairly big performance hit. From the Iron
895 * Lake PRM, Vol 2, pt. 1, section 8.4.3.2, "Early Depth Test Cases":
896 *
897 * "Non-promoted depth (N) is active whenever the depth test can be done
898 * early but it cannot determine whether or not to write source depth to
899 * the depth buffer, therefore the depth write must be performed post pixel
900 * shader. This includes cases where the pixel shader can kill pixels,
901 * including via sampler chroma key, as well as cases where the alpha test
902 * function is enabled, which kills pixels based on a programmable alpha
903 * test. In this case, even if the depth test fails, the pixel cannot be
904 * killed if a stencil write is indicated. Whether or not the stencil write
905 * happens depends on whether or not the pixel is killed later. In these
906 * cases if stencil test fails and stencil writes are off, the pixels can
907 * also be killed early. If stencil writes are enabled, the pixels must be
908 * treated as Computed depth (described above)."
909 *
910 * The same thing as mentioned in the stencil case can happen in the depth
911 * case as well if it thinks it writes depth but, thanks to the depth test
912 * being GL_EQUAL, the write doesn't actually matter. A little extra work
913 * up-front to try and disable depth and stencil writes can make a big
914 * difference.
915 *
916 * Unfortunately, the way depth and stencil testing is specified, there are
917 * many case where, regardless of depth/stencil writes being enabled, nothing
918 * actually gets written due to some other bit of state being set. This
919 * function attempts to "sanitize" the depth stencil state and disable writes
920 * and sometimes even testing whenever possible.
921 */
922 static void
923 sanitize_ds_state(VkPipelineDepthStencilStateCreateInfo *state,
924 bool *stencilWriteEnable,
925 VkImageAspectFlags ds_aspects)
926 {
927 *stencilWriteEnable = state->stencilTestEnable;
928
929 /* If the depth test is disabled, we won't be writing anything. Make sure we
930 * treat the test as always passing later on as well.
931 *
932 * Also, the Vulkan spec requires that if either depth or stencil is not
933 * present, the pipeline is to act as if the test silently passes. In that
934 * case we won't write either.
935 */
936 if (!state->depthTestEnable || !(ds_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
937 state->depthWriteEnable = false;
938 state->depthCompareOp = VK_COMPARE_OP_ALWAYS;
939 }
940
941 if (!(ds_aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
942 *stencilWriteEnable = false;
943 state->front.compareOp = VK_COMPARE_OP_ALWAYS;
944 state->back.compareOp = VK_COMPARE_OP_ALWAYS;
945 }
946
947 /* If the stencil test is enabled and always fails, then we will never get
948 * to the depth test so we can just disable the depth test entirely.
949 */
950 if (state->stencilTestEnable &&
951 state->front.compareOp == VK_COMPARE_OP_NEVER &&
952 state->back.compareOp == VK_COMPARE_OP_NEVER) {
953 state->depthTestEnable = false;
954 state->depthWriteEnable = false;
955 }
956
957 /* If depthCompareOp is EQUAL then the value we would be writing to the
958 * depth buffer is the same as the value that's already there so there's no
959 * point in writing it.
960 */
961 if (state->depthCompareOp == VK_COMPARE_OP_EQUAL)
962 state->depthWriteEnable = false;
963
964 /* If the stencil ops are such that we don't actually ever modify the
965 * stencil buffer, we should disable writes.
966 */
967 if (!sanitize_stencil_face(&state->front, state->depthCompareOp) &&
968 !sanitize_stencil_face(&state->back, state->depthCompareOp))
969 *stencilWriteEnable = false;
970
971 /* If the depth test always passes and we never write out depth, that's the
972 * same as if the depth test is disabled entirely.
973 */
974 if (state->depthCompareOp == VK_COMPARE_OP_ALWAYS &&
975 !state->depthWriteEnable)
976 state->depthTestEnable = false;
977
978 /* If the stencil test always passes and we never write out stencil, that's
979 * the same as if the stencil test is disabled entirely.
980 */
981 if (state->front.compareOp == VK_COMPARE_OP_ALWAYS &&
982 state->back.compareOp == VK_COMPARE_OP_ALWAYS &&
983 !*stencilWriteEnable)
984 state->stencilTestEnable = false;
985 }
986
987 static void
988 emit_ds_state(struct anv_graphics_pipeline *pipeline,
989 const VkPipelineDepthStencilStateCreateInfo *pCreateInfo,
990 const struct anv_render_pass *pass,
991 const struct anv_subpass *subpass)
992 {
993 #if GEN_GEN == 7
994 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
995 #elif GEN_GEN == 8
996 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
997 #else
998 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
999 #endif
1000
1001 if (pCreateInfo == NULL) {
1002 /* We're going to OR this together with the dynamic state. We need
1003 * to make sure it's initialized to something useful.
1004 */
1005 pipeline->writes_stencil = false;
1006 pipeline->stencil_test_enable = false;
1007 pipeline->writes_depth = false;
1008 pipeline->depth_test_enable = false;
1009 pipeline->depth_bounds_test_enable = false;
1010 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
1011 return;
1012 }
1013
1014 VkImageAspectFlags ds_aspects = 0;
1015 if (subpass->depth_stencil_attachment) {
1016 VkFormat depth_stencil_format =
1017 pass->attachments[subpass->depth_stencil_attachment->attachment].format;
1018 ds_aspects = vk_format_aspects(depth_stencil_format);
1019 }
1020
1021 VkPipelineDepthStencilStateCreateInfo info = *pCreateInfo;
1022 sanitize_ds_state(&info, &pipeline->writes_stencil, ds_aspects);
1023 pipeline->stencil_test_enable = info.stencilTestEnable;
1024 pipeline->writes_depth = info.depthWriteEnable;
1025 pipeline->depth_test_enable = info.depthTestEnable;
1026 pipeline->depth_bounds_test_enable = info.depthBoundsTestEnable;
1027
1028 #if GEN_GEN <= 7
1029 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
1030 #else
1031 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
1032 #endif
1033 .DepthTestEnable = info.depthTestEnable,
1034 .DepthBufferWriteEnable = info.depthWriteEnable,
1035 .DepthTestFunction = vk_to_gen_compare_op[info.depthCompareOp],
1036 .DoubleSidedStencilEnable = true,
1037
1038 .StencilTestEnable = info.stencilTestEnable,
1039 .StencilFailOp = vk_to_gen_stencil_op[info.front.failOp],
1040 .StencilPassDepthPassOp = vk_to_gen_stencil_op[info.front.passOp],
1041 .StencilPassDepthFailOp = vk_to_gen_stencil_op[info.front.depthFailOp],
1042 .StencilTestFunction = vk_to_gen_compare_op[info.front.compareOp],
1043 .BackfaceStencilFailOp = vk_to_gen_stencil_op[info.back.failOp],
1044 .BackfaceStencilPassDepthPassOp = vk_to_gen_stencil_op[info.back.passOp],
1045 .BackfaceStencilPassDepthFailOp =vk_to_gen_stencil_op[info.back.depthFailOp],
1046 .BackfaceStencilTestFunction = vk_to_gen_compare_op[info.back.compareOp],
1047 };
1048
1049 #if GEN_GEN <= 7
1050 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
1051 #else
1052 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
1053 #endif
1054 }
1055
1056 static bool
1057 is_dual_src_blend_factor(VkBlendFactor factor)
1058 {
1059 return factor == VK_BLEND_FACTOR_SRC1_COLOR ||
1060 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR ||
1061 factor == VK_BLEND_FACTOR_SRC1_ALPHA ||
1062 factor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA;
1063 }
1064
1065 static void
1066 emit_cb_state(struct anv_graphics_pipeline *pipeline,
1067 const VkPipelineColorBlendStateCreateInfo *info,
1068 const VkPipelineMultisampleStateCreateInfo *ms_info)
1069 {
1070 struct anv_device *device = pipeline->base.device;
1071 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1072
1073 struct GENX(BLEND_STATE) blend_state = {
1074 #if GEN_GEN >= 8
1075 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
1076 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
1077 #endif
1078 };
1079
1080 uint32_t surface_count = 0;
1081 struct anv_pipeline_bind_map *map;
1082 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1083 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
1084 surface_count = map->surface_count;
1085 }
1086
1087 const uint32_t num_dwords = GENX(BLEND_STATE_length) +
1088 GENX(BLEND_STATE_ENTRY_length) * surface_count;
1089 pipeline->blend_state =
1090 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
1091
1092 bool has_writeable_rt = false;
1093 uint32_t *state_pos = pipeline->blend_state.map;
1094 state_pos += GENX(BLEND_STATE_length);
1095 #if GEN_GEN >= 8
1096 struct GENX(BLEND_STATE_ENTRY) bs0 = { 0 };
1097 #endif
1098 for (unsigned i = 0; i < surface_count; i++) {
1099 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
1100
1101 /* All color attachments are at the beginning of the binding table */
1102 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1103 break;
1104
1105 /* We can have at most 8 attachments */
1106 assert(i < 8);
1107
1108 if (info == NULL || binding->index >= info->attachmentCount) {
1109 /* Default everything to disabled */
1110 struct GENX(BLEND_STATE_ENTRY) entry = {
1111 .WriteDisableAlpha = true,
1112 .WriteDisableRed = true,
1113 .WriteDisableGreen = true,
1114 .WriteDisableBlue = true,
1115 };
1116 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
1117 state_pos += GENX(BLEND_STATE_ENTRY_length);
1118 continue;
1119 }
1120
1121 const VkPipelineColorBlendAttachmentState *a =
1122 &info->pAttachments[binding->index];
1123
1124 struct GENX(BLEND_STATE_ENTRY) entry = {
1125 #if GEN_GEN < 8
1126 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
1127 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
1128 #endif
1129 .LogicOpEnable = info->logicOpEnable,
1130 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
1131 .ColorBufferBlendEnable = a->blendEnable,
1132 .ColorClampRange = COLORCLAMP_RTFORMAT,
1133 .PreBlendColorClampEnable = true,
1134 .PostBlendColorClampEnable = true,
1135 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
1136 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
1137 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
1138 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
1139 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
1140 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
1141 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
1142 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
1143 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
1144 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
1145 };
1146
1147 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
1148 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
1149 a->colorBlendOp != a->alphaBlendOp) {
1150 #if GEN_GEN >= 8
1151 blend_state.IndependentAlphaBlendEnable = true;
1152 #else
1153 entry.IndependentAlphaBlendEnable = true;
1154 #endif
1155 }
1156
1157 /* The Dual Source Blending documentation says:
1158 *
1159 * "If SRC1 is included in a src/dst blend factor and
1160 * a DualSource RT Write message is not used, results
1161 * are UNDEFINED. (This reflects the same restriction in DX APIs,
1162 * where undefined results are produced if “o1” is not written
1163 * by a PS – there are no default values defined)."
1164 *
1165 * There is no way to gracefully fix this undefined situation
1166 * so we just disable the blending to prevent possible issues.
1167 */
1168 if (!wm_prog_data->dual_src_blend &&
1169 (is_dual_src_blend_factor(a->srcColorBlendFactor) ||
1170 is_dual_src_blend_factor(a->dstColorBlendFactor) ||
1171 is_dual_src_blend_factor(a->srcAlphaBlendFactor) ||
1172 is_dual_src_blend_factor(a->dstAlphaBlendFactor))) {
1173 vk_debug_report(&device->physical->instance->debug_report_callbacks,
1174 VK_DEBUG_REPORT_WARNING_BIT_EXT,
1175 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
1176 (uint64_t)(uintptr_t)device,
1177 0, 0, "anv",
1178 "Enabled dual-src blend factors without writing both targets "
1179 "in the shader. Disabling blending to avoid GPU hangs.");
1180 entry.ColorBufferBlendEnable = false;
1181 }
1182
1183 if (a->colorWriteMask != 0)
1184 has_writeable_rt = true;
1185
1186 /* Our hardware applies the blend factor prior to the blend function
1187 * regardless of what function is used. Technically, this means the
1188 * hardware can do MORE than GL or Vulkan specify. However, it also
1189 * means that, for MIN and MAX, we have to stomp the blend factor to
1190 * ONE to make it a no-op.
1191 */
1192 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
1193 a->colorBlendOp == VK_BLEND_OP_MAX) {
1194 entry.SourceBlendFactor = BLENDFACTOR_ONE;
1195 entry.DestinationBlendFactor = BLENDFACTOR_ONE;
1196 }
1197 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
1198 a->alphaBlendOp == VK_BLEND_OP_MAX) {
1199 entry.SourceAlphaBlendFactor = BLENDFACTOR_ONE;
1200 entry.DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
1201 }
1202 GENX(BLEND_STATE_ENTRY_pack)(NULL, state_pos, &entry);
1203 state_pos += GENX(BLEND_STATE_ENTRY_length);
1204 #if GEN_GEN >= 8
1205 if (i == 0)
1206 bs0 = entry;
1207 #endif
1208 }
1209
1210 #if GEN_GEN >= 8
1211 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS_BLEND), blend) {
1212 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
1213 blend.HasWriteableRT = has_writeable_rt;
1214 blend.ColorBufferBlendEnable = bs0.ColorBufferBlendEnable;
1215 blend.SourceAlphaBlendFactor = bs0.SourceAlphaBlendFactor;
1216 blend.DestinationAlphaBlendFactor = bs0.DestinationAlphaBlendFactor;
1217 blend.SourceBlendFactor = bs0.SourceBlendFactor;
1218 blend.DestinationBlendFactor = bs0.DestinationBlendFactor;
1219 blend.AlphaTestEnable = false;
1220 blend.IndependentAlphaBlendEnable =
1221 blend_state.IndependentAlphaBlendEnable;
1222 }
1223 #else
1224 (void)has_writeable_rt;
1225 #endif
1226
1227 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
1228
1229 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
1230 bsp.BlendStatePointer = pipeline->blend_state.offset;
1231 #if GEN_GEN >= 8
1232 bsp.BlendStatePointerValid = true;
1233 #endif
1234 }
1235 }
1236
1237 static void
1238 emit_3dstate_clip(struct anv_graphics_pipeline *pipeline,
1239 const VkPipelineInputAssemblyStateCreateInfo *ia_info,
1240 const VkPipelineViewportStateCreateInfo *vp_info,
1241 const VkPipelineRasterizationStateCreateInfo *rs_info)
1242 {
1243 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1244 (void) wm_prog_data;
1245 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_CLIP), clip) {
1246 clip.ClipEnable = true;
1247 clip.StatisticsEnable = true;
1248 clip.EarlyCullEnable = true;
1249 clip.APIMode = APIMODE_D3D;
1250 clip.GuardbandClipTestEnable = true;
1251
1252 /* Only enable the XY clip test when the final polygon rasterization
1253 * mode is VK_POLYGON_MODE_FILL. We want to leave it disabled for
1254 * points and lines so we get "pop-free" clipping.
1255 */
1256 VkPolygonMode raster_mode =
1257 anv_raster_polygon_mode(pipeline, ia_info, rs_info);
1258 clip.ViewportXYClipTestEnable = (raster_mode == VK_POLYGON_MODE_FILL);
1259
1260 #if GEN_GEN >= 8
1261 clip.VertexSubPixelPrecisionSelect = _8Bit;
1262 #endif
1263
1264 clip.ClipMode = CLIPMODE_NORMAL;
1265
1266 clip.TriangleStripListProvokingVertexSelect = 0;
1267 clip.LineStripListProvokingVertexSelect = 0;
1268 clip.TriangleFanProvokingVertexSelect = 1;
1269
1270 clip.MinimumPointWidth = 0.125;
1271 clip.MaximumPointWidth = 255.875;
1272
1273 const struct brw_vue_prog_data *last =
1274 anv_pipeline_get_last_vue_prog_data(pipeline);
1275
1276 /* From the Vulkan 1.0.45 spec:
1277 *
1278 * "If the last active vertex processing stage shader entry point's
1279 * interface does not include a variable decorated with
1280 * ViewportIndex, then the first viewport is used."
1281 */
1282 if (vp_info && (last->vue_map.slots_valid & VARYING_BIT_VIEWPORT)) {
1283 clip.MaximumVPIndex = vp_info->viewportCount - 1;
1284 } else {
1285 clip.MaximumVPIndex = 0;
1286 }
1287
1288 /* From the Vulkan 1.0.45 spec:
1289 *
1290 * "If the last active vertex processing stage shader entry point's
1291 * interface does not include a variable decorated with Layer, then
1292 * the first layer is used."
1293 */
1294 clip.ForceZeroRTAIndexEnable =
1295 !(last->vue_map.slots_valid & VARYING_BIT_LAYER);
1296
1297 #if GEN_GEN == 7
1298 clip.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
1299 clip.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
1300 clip.ViewportZClipTestEnable = pipeline->depth_clip_enable;
1301 clip.UserClipDistanceClipTestEnableBitmask = last->clip_distance_mask;
1302 clip.UserClipDistanceCullTestEnableBitmask = last->cull_distance_mask;
1303 #else
1304 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
1305 (wm_prog_data->barycentric_interp_modes &
1306 BRW_BARYCENTRIC_NONPERSPECTIVE_BITS) != 0 : 0;
1307 #endif
1308 }
1309 }
1310
1311 static void
1312 emit_3dstate_streamout(struct anv_graphics_pipeline *pipeline,
1313 const VkPipelineRasterizationStateCreateInfo *rs_info)
1314 {
1315 #if GEN_GEN >= 8
1316 const struct brw_vue_prog_data *prog_data =
1317 anv_pipeline_get_last_vue_prog_data(pipeline);
1318 const struct brw_vue_map *vue_map = &prog_data->vue_map;
1319
1320 nir_xfb_info *xfb_info;
1321 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY))
1322 xfb_info = pipeline->shaders[MESA_SHADER_GEOMETRY]->xfb_info;
1323 else if (anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL))
1324 xfb_info = pipeline->shaders[MESA_SHADER_TESS_EVAL]->xfb_info;
1325 else
1326 xfb_info = pipeline->shaders[MESA_SHADER_VERTEX]->xfb_info;
1327 #endif
1328
1329 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_STREAMOUT), so) {
1330 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
1331
1332 #if GEN_GEN >= 8
1333 if (xfb_info) {
1334 so.SOFunctionEnable = true;
1335 so.SOStatisticsEnable = true;
1336
1337 const VkPipelineRasterizationStateStreamCreateInfoEXT *stream_info =
1338 vk_find_struct_const(rs_info, PIPELINE_RASTERIZATION_STATE_STREAM_CREATE_INFO_EXT);
1339 so.RenderStreamSelect = stream_info ?
1340 stream_info->rasterizationStream : 0;
1341
1342 so.Buffer0SurfacePitch = xfb_info->buffers[0].stride;
1343 so.Buffer1SurfacePitch = xfb_info->buffers[1].stride;
1344 so.Buffer2SurfacePitch = xfb_info->buffers[2].stride;
1345 so.Buffer3SurfacePitch = xfb_info->buffers[3].stride;
1346
1347 int urb_entry_read_offset = 0;
1348 int urb_entry_read_length =
1349 (prog_data->vue_map.num_slots + 1) / 2 - urb_entry_read_offset;
1350
1351 /* We always read the whole vertex. This could be reduced at some
1352 * point by reading less and offsetting the register index in the
1353 * SO_DECLs.
1354 */
1355 so.Stream0VertexReadOffset = urb_entry_read_offset;
1356 so.Stream0VertexReadLength = urb_entry_read_length - 1;
1357 so.Stream1VertexReadOffset = urb_entry_read_offset;
1358 so.Stream1VertexReadLength = urb_entry_read_length - 1;
1359 so.Stream2VertexReadOffset = urb_entry_read_offset;
1360 so.Stream2VertexReadLength = urb_entry_read_length - 1;
1361 so.Stream3VertexReadOffset = urb_entry_read_offset;
1362 so.Stream3VertexReadLength = urb_entry_read_length - 1;
1363 }
1364 #endif /* GEN_GEN >= 8 */
1365 }
1366
1367 #if GEN_GEN >= 8
1368 if (xfb_info) {
1369 struct GENX(SO_DECL) so_decl[MAX_XFB_STREAMS][128];
1370 int next_offset[MAX_XFB_BUFFERS] = {0, 0, 0, 0};
1371 int decls[MAX_XFB_STREAMS] = {0, 0, 0, 0};
1372
1373 memset(so_decl, 0, sizeof(so_decl));
1374
1375 for (unsigned i = 0; i < xfb_info->output_count; i++) {
1376 const nir_xfb_output_info *output = &xfb_info->outputs[i];
1377 unsigned buffer = output->buffer;
1378 unsigned stream = xfb_info->buffer_to_stream[buffer];
1379
1380 /* Our hardware is unusual in that it requires us to program SO_DECLs
1381 * for fake "hole" components, rather than simply taking the offset
1382 * for each real varying. Each hole can have size 1, 2, 3, or 4; we
1383 * program as many size = 4 holes as we can, then a final hole to
1384 * accommodate the final 1, 2, or 3 remaining.
1385 */
1386 int hole_dwords = (output->offset - next_offset[buffer]) / 4;
1387 while (hole_dwords > 0) {
1388 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1389 .HoleFlag = 1,
1390 .OutputBufferSlot = buffer,
1391 .ComponentMask = (1 << MIN2(hole_dwords, 4)) - 1,
1392 };
1393 hole_dwords -= 4;
1394 }
1395
1396 int varying = output->location;
1397 uint8_t component_mask = output->component_mask;
1398 /* VARYING_SLOT_PSIZ contains three scalar fields packed together:
1399 * - VARYING_SLOT_LAYER in VARYING_SLOT_PSIZ.y
1400 * - VARYING_SLOT_VIEWPORT in VARYING_SLOT_PSIZ.z
1401 * - VARYING_SLOT_PSIZ in VARYING_SLOT_PSIZ.w
1402 */
1403 if (varying == VARYING_SLOT_LAYER) {
1404 varying = VARYING_SLOT_PSIZ;
1405 component_mask = 1 << 1; // SO_DECL_COMPMASK_Y
1406 } else if (varying == VARYING_SLOT_VIEWPORT) {
1407 varying = VARYING_SLOT_PSIZ;
1408 component_mask = 1 << 2; // SO_DECL_COMPMASK_Z
1409 } else if (varying == VARYING_SLOT_PSIZ) {
1410 component_mask = 1 << 3; // SO_DECL_COMPMASK_W
1411 }
1412
1413 next_offset[buffer] = output->offset +
1414 __builtin_popcount(component_mask) * 4;
1415
1416 const int slot = vue_map->varying_to_slot[varying];
1417 if (slot < 0) {
1418 /* This can happen if the shader never writes to the varying.
1419 * Insert a hole instead of actual varying data.
1420 */
1421 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1422 .HoleFlag = true,
1423 .OutputBufferSlot = buffer,
1424 .ComponentMask = component_mask,
1425 };
1426 } else {
1427 so_decl[stream][decls[stream]++] = (struct GENX(SO_DECL)) {
1428 .OutputBufferSlot = buffer,
1429 .RegisterIndex = slot,
1430 .ComponentMask = component_mask,
1431 };
1432 }
1433 }
1434
1435 int max_decls = 0;
1436 for (unsigned s = 0; s < MAX_XFB_STREAMS; s++)
1437 max_decls = MAX2(max_decls, decls[s]);
1438
1439 uint8_t sbs[MAX_XFB_STREAMS] = { };
1440 for (unsigned b = 0; b < MAX_XFB_BUFFERS; b++) {
1441 if (xfb_info->buffers_written & (1 << b))
1442 sbs[xfb_info->buffer_to_stream[b]] |= 1 << b;
1443 }
1444
1445 uint32_t *dw = anv_batch_emitn(&pipeline->base.batch, 3 + 2 * max_decls,
1446 GENX(3DSTATE_SO_DECL_LIST),
1447 .StreamtoBufferSelects0 = sbs[0],
1448 .StreamtoBufferSelects1 = sbs[1],
1449 .StreamtoBufferSelects2 = sbs[2],
1450 .StreamtoBufferSelects3 = sbs[3],
1451 .NumEntries0 = decls[0],
1452 .NumEntries1 = decls[1],
1453 .NumEntries2 = decls[2],
1454 .NumEntries3 = decls[3]);
1455
1456 for (int i = 0; i < max_decls; i++) {
1457 GENX(SO_DECL_ENTRY_pack)(NULL, dw + 3 + i * 2,
1458 &(struct GENX(SO_DECL_ENTRY)) {
1459 .Stream0Decl = so_decl[0][i],
1460 .Stream1Decl = so_decl[1][i],
1461 .Stream2Decl = so_decl[2][i],
1462 .Stream3Decl = so_decl[3][i],
1463 });
1464 }
1465 }
1466 #endif /* GEN_GEN >= 8 */
1467 }
1468
1469 static uint32_t
1470 get_sampler_count(const struct anv_shader_bin *bin)
1471 {
1472 uint32_t count_by_4 = DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
1473
1474 /* We can potentially have way more than 32 samplers and that's ok.
1475 * However, the 3DSTATE_XS packets only have 3 bits to specify how
1476 * many to pre-fetch and all values above 4 are marked reserved.
1477 */
1478 return MIN2(count_by_4, 4);
1479 }
1480
1481 static uint32_t
1482 get_binding_table_entry_count(const struct anv_shader_bin *bin)
1483 {
1484 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
1485 }
1486
1487 static struct anv_address
1488 get_scratch_address(struct anv_pipeline *pipeline,
1489 gl_shader_stage stage,
1490 const struct anv_shader_bin *bin)
1491 {
1492 return (struct anv_address) {
1493 .bo = anv_scratch_pool_alloc(pipeline->device,
1494 &pipeline->device->scratch_pool,
1495 stage, bin->prog_data->total_scratch),
1496 .offset = 0,
1497 };
1498 }
1499
1500 static uint32_t
1501 get_scratch_space(const struct anv_shader_bin *bin)
1502 {
1503 return ffs(bin->prog_data->total_scratch / 2048);
1504 }
1505
1506 static void
1507 emit_3dstate_vs(struct anv_graphics_pipeline *pipeline)
1508 {
1509 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1510 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
1511 const struct anv_shader_bin *vs_bin =
1512 pipeline->shaders[MESA_SHADER_VERTEX];
1513
1514 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
1515
1516 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VS), vs) {
1517 vs.Enable = true;
1518 vs.StatisticsEnable = true;
1519 vs.KernelStartPointer = vs_bin->kernel.offset;
1520 #if GEN_GEN >= 8
1521 vs.SIMD8DispatchEnable =
1522 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
1523 #endif
1524
1525 assert(!vs_prog_data->base.base.use_alt_mode);
1526 #if GEN_GEN < 11
1527 vs.SingleVertexDispatch = false;
1528 #endif
1529 vs.VectorMaskEnable = false;
1530 /* WA_1606682166:
1531 * Incorrect TDL's SSP address shift in SARB for 16:6 & 18:8 modes.
1532 * Disable the Sampler state prefetch functionality in the SARB by
1533 * programming 0xB000[30] to '1'.
1534 */
1535 vs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(vs_bin);
1536 vs.BindingTableEntryCount = get_binding_table_entry_count(vs_bin);
1537 vs.FloatingPointMode = IEEE754;
1538 vs.IllegalOpcodeExceptionEnable = false;
1539 vs.SoftwareExceptionEnable = false;
1540 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
1541
1542 if (GEN_GEN == 9 && devinfo->gt == 4 &&
1543 anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1544 /* On Sky Lake GT4, we have experienced some hangs related to the VS
1545 * cache and tessellation. It is unknown exactly what is happening
1546 * but the Haswell docs for the "VS Reference Count Full Force Miss
1547 * Enable" field of the "Thread Mode" register refer to a HSW bug in
1548 * which the VUE handle reference count would overflow resulting in
1549 * internal reference counting bugs. My (Jason's) best guess is that
1550 * this bug cropped back up on SKL GT4 when we suddenly had more
1551 * threads in play than any previous gen9 hardware.
1552 *
1553 * What we do know for sure is that setting this bit when
1554 * tessellation shaders are in use fixes a GPU hang in Batman: Arkham
1555 * City when playing with DXVK (https://bugs.freedesktop.org/107280).
1556 * Disabling the vertex cache with tessellation shaders should only
1557 * have a minor performance impact as the tessellation shaders are
1558 * likely generating and processing far more geometry than the vertex
1559 * stage.
1560 */
1561 vs.VertexCacheDisable = true;
1562 }
1563
1564 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
1565 vs.VertexURBEntryReadOffset = 0;
1566 vs.DispatchGRFStartRegisterForURBData =
1567 vs_prog_data->base.base.dispatch_grf_start_reg;
1568
1569 #if GEN_GEN >= 8
1570 vs.UserClipDistanceClipTestEnableBitmask =
1571 vs_prog_data->base.clip_distance_mask;
1572 vs.UserClipDistanceCullTestEnableBitmask =
1573 vs_prog_data->base.cull_distance_mask;
1574 #endif
1575
1576 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
1577 vs.ScratchSpaceBasePointer =
1578 get_scratch_address(&pipeline->base, MESA_SHADER_VERTEX, vs_bin);
1579 }
1580 }
1581
1582 static void
1583 emit_3dstate_hs_te_ds(struct anv_graphics_pipeline *pipeline,
1584 const VkPipelineTessellationStateCreateInfo *tess_info)
1585 {
1586 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_TESS_EVAL)) {
1587 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_HS), hs);
1588 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_TE), te);
1589 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_DS), ds);
1590 return;
1591 }
1592
1593 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1594 const struct anv_shader_bin *tcs_bin =
1595 pipeline->shaders[MESA_SHADER_TESS_CTRL];
1596 const struct anv_shader_bin *tes_bin =
1597 pipeline->shaders[MESA_SHADER_TESS_EVAL];
1598
1599 const struct brw_tcs_prog_data *tcs_prog_data = get_tcs_prog_data(pipeline);
1600 const struct brw_tes_prog_data *tes_prog_data = get_tes_prog_data(pipeline);
1601
1602 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_HS), hs) {
1603 hs.Enable = true;
1604 hs.StatisticsEnable = true;
1605 hs.KernelStartPointer = tcs_bin->kernel.offset;
1606 /* WA_1606682166 */
1607 hs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(tcs_bin);
1608 hs.BindingTableEntryCount = get_binding_table_entry_count(tcs_bin);
1609
1610 #if GEN_GEN >= 12
1611 /* GEN:BUG:1604578095:
1612 *
1613 * Hang occurs when the number of max threads is less than 2 times
1614 * the number of instance count. The number of max threads must be
1615 * more than 2 times the number of instance count.
1616 */
1617 assert((devinfo->max_tcs_threads / 2) > tcs_prog_data->instances);
1618 #endif
1619
1620 hs.MaximumNumberofThreads = devinfo->max_tcs_threads - 1;
1621 hs.IncludeVertexHandles = true;
1622 hs.InstanceCount = tcs_prog_data->instances - 1;
1623
1624 hs.VertexURBEntryReadLength = 0;
1625 hs.VertexURBEntryReadOffset = 0;
1626 hs.DispatchGRFStartRegisterForURBData =
1627 tcs_prog_data->base.base.dispatch_grf_start_reg;
1628
1629 hs.PerThreadScratchSpace = get_scratch_space(tcs_bin);
1630 hs.ScratchSpaceBasePointer =
1631 get_scratch_address(&pipeline->base, MESA_SHADER_TESS_CTRL, tcs_bin);
1632
1633 #if GEN_GEN == 12
1634 /* Patch Count threshold specifies the maximum number of patches that
1635 * will be accumulated before a thread dispatch is forced.
1636 */
1637 hs.PatchCountThreshold = tcs_prog_data->patch_count_threshold;
1638 #endif
1639
1640 #if GEN_GEN >= 9
1641 hs.DispatchMode = tcs_prog_data->base.dispatch_mode;
1642 hs.IncludePrimitiveID = tcs_prog_data->include_primitive_id;
1643 #endif
1644 }
1645
1646 const VkPipelineTessellationDomainOriginStateCreateInfo *domain_origin_state =
1647 tess_info ? vk_find_struct_const(tess_info, PIPELINE_TESSELLATION_DOMAIN_ORIGIN_STATE_CREATE_INFO) : NULL;
1648
1649 VkTessellationDomainOrigin uv_origin =
1650 domain_origin_state ? domain_origin_state->domainOrigin :
1651 VK_TESSELLATION_DOMAIN_ORIGIN_UPPER_LEFT;
1652
1653 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_TE), te) {
1654 te.Partitioning = tes_prog_data->partitioning;
1655
1656 if (uv_origin == VK_TESSELLATION_DOMAIN_ORIGIN_LOWER_LEFT) {
1657 te.OutputTopology = tes_prog_data->output_topology;
1658 } else {
1659 /* When the origin is upper-left, we have to flip the winding order */
1660 if (tes_prog_data->output_topology == OUTPUT_TRI_CCW) {
1661 te.OutputTopology = OUTPUT_TRI_CW;
1662 } else if (tes_prog_data->output_topology == OUTPUT_TRI_CW) {
1663 te.OutputTopology = OUTPUT_TRI_CCW;
1664 } else {
1665 te.OutputTopology = tes_prog_data->output_topology;
1666 }
1667 }
1668
1669 te.TEDomain = tes_prog_data->domain;
1670 te.TEEnable = true;
1671 te.MaximumTessellationFactorOdd = 63.0;
1672 te.MaximumTessellationFactorNotOdd = 64.0;
1673 }
1674
1675 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_DS), ds) {
1676 ds.Enable = true;
1677 ds.StatisticsEnable = true;
1678 ds.KernelStartPointer = tes_bin->kernel.offset;
1679 /* WA_1606682166 */
1680 ds.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(tes_bin);
1681 ds.BindingTableEntryCount = get_binding_table_entry_count(tes_bin);
1682 ds.MaximumNumberofThreads = devinfo->max_tes_threads - 1;
1683
1684 ds.ComputeWCoordinateEnable =
1685 tes_prog_data->domain == BRW_TESS_DOMAIN_TRI;
1686
1687 ds.PatchURBEntryReadLength = tes_prog_data->base.urb_read_length;
1688 ds.PatchURBEntryReadOffset = 0;
1689 ds.DispatchGRFStartRegisterForURBData =
1690 tes_prog_data->base.base.dispatch_grf_start_reg;
1691
1692 #if GEN_GEN >= 8
1693 #if GEN_GEN < 11
1694 ds.DispatchMode =
1695 tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8 ?
1696 DISPATCH_MODE_SIMD8_SINGLE_PATCH :
1697 DISPATCH_MODE_SIMD4X2;
1698 #else
1699 assert(tes_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8);
1700 ds.DispatchMode = DISPATCH_MODE_SIMD8_SINGLE_PATCH;
1701 #endif
1702
1703 ds.UserClipDistanceClipTestEnableBitmask =
1704 tes_prog_data->base.clip_distance_mask;
1705 ds.UserClipDistanceCullTestEnableBitmask =
1706 tes_prog_data->base.cull_distance_mask;
1707 #endif
1708
1709 ds.PerThreadScratchSpace = get_scratch_space(tes_bin);
1710 ds.ScratchSpaceBasePointer =
1711 get_scratch_address(&pipeline->base, MESA_SHADER_TESS_EVAL, tes_bin);
1712 }
1713 }
1714
1715 static void
1716 emit_3dstate_gs(struct anv_graphics_pipeline *pipeline)
1717 {
1718 const struct gen_device_info *devinfo = &pipeline->base.device->info;
1719 const struct anv_shader_bin *gs_bin =
1720 pipeline->shaders[MESA_SHADER_GEOMETRY];
1721
1722 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
1723 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_GS), gs);
1724 return;
1725 }
1726
1727 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
1728
1729 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_GS), gs) {
1730 gs.Enable = true;
1731 gs.StatisticsEnable = true;
1732 gs.KernelStartPointer = gs_bin->kernel.offset;
1733 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
1734
1735 gs.SingleProgramFlow = false;
1736 gs.VectorMaskEnable = false;
1737 /* WA_1606682166 */
1738 gs.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(gs_bin);
1739 gs.BindingTableEntryCount = get_binding_table_entry_count(gs_bin);
1740 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
1741 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
1742
1743 if (GEN_GEN == 8) {
1744 /* Broadwell is weird. It needs us to divide by 2. */
1745 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
1746 } else {
1747 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
1748 }
1749
1750 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
1751 gs.OutputTopology = gs_prog_data->output_topology;
1752 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1753 gs.ControlDataFormat = gs_prog_data->control_data_format;
1754 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
1755 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
1756 gs.ReorderMode = TRAILING;
1757
1758 #if GEN_GEN >= 8
1759 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
1760 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
1761 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
1762 gs_prog_data->static_vertex_count : 0;
1763 #endif
1764
1765 gs.VertexURBEntryReadOffset = 0;
1766 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1767 gs.DispatchGRFStartRegisterForURBData =
1768 gs_prog_data->base.base.dispatch_grf_start_reg;
1769
1770 #if GEN_GEN >= 8
1771 gs.UserClipDistanceClipTestEnableBitmask =
1772 gs_prog_data->base.clip_distance_mask;
1773 gs.UserClipDistanceCullTestEnableBitmask =
1774 gs_prog_data->base.cull_distance_mask;
1775 #endif
1776
1777 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1778 gs.ScratchSpaceBasePointer =
1779 get_scratch_address(&pipeline->base, MESA_SHADER_GEOMETRY, gs_bin);
1780 }
1781 }
1782
1783 static bool
1784 has_color_buffer_write_enabled(const struct anv_graphics_pipeline *pipeline,
1785 const VkPipelineColorBlendStateCreateInfo *blend)
1786 {
1787 const struct anv_shader_bin *shader_bin =
1788 pipeline->shaders[MESA_SHADER_FRAGMENT];
1789 if (!shader_bin)
1790 return false;
1791
1792 const struct anv_pipeline_bind_map *bind_map = &shader_bin->bind_map;
1793 for (int i = 0; i < bind_map->surface_count; i++) {
1794 struct anv_pipeline_binding *binding = &bind_map->surface_to_descriptor[i];
1795
1796 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
1797 continue;
1798
1799 if (binding->index == UINT32_MAX)
1800 continue;
1801
1802 if (blend && blend->pAttachments[binding->index].colorWriteMask != 0)
1803 return true;
1804 }
1805
1806 return false;
1807 }
1808
1809 static void
1810 emit_3dstate_wm(struct anv_graphics_pipeline *pipeline, struct anv_subpass *subpass,
1811 const VkPipelineInputAssemblyStateCreateInfo *ia,
1812 const VkPipelineRasterizationStateCreateInfo *raster,
1813 const VkPipelineColorBlendStateCreateInfo *blend,
1814 const VkPipelineMultisampleStateCreateInfo *multisample,
1815 const VkPipelineRasterizationLineStateCreateInfoEXT *line)
1816 {
1817 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1818
1819 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_WM), wm) {
1820 wm.StatisticsEnable = true;
1821 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1822 wm.LineAntialiasingRegionWidth = _10pixels;
1823 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1824
1825 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1826 if (wm_prog_data->early_fragment_tests) {
1827 wm.EarlyDepthStencilControl = EDSC_PREPS;
1828 } else if (wm_prog_data->has_side_effects) {
1829 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1830 } else {
1831 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1832 }
1833
1834 #if GEN_GEN >= 8
1835 /* Gen8 hardware tries to compute ThreadDispatchEnable for us but
1836 * doesn't take into account KillPixels when no depth or stencil
1837 * writes are enabled. In order for occlusion queries to work
1838 * correctly with no attachments, we need to force-enable PS thread
1839 * dispatch.
1840 *
1841 * The BDW docs are pretty clear that that this bit isn't validated
1842 * and probably shouldn't be used in production:
1843 *
1844 * "This must always be set to Normal. This field should not be
1845 * tested for functional validation."
1846 *
1847 * Unfortunately, however, the other mechanism we have for doing this
1848 * is 3DSTATE_PS_EXTRA::PixelShaderHasUAV which causes hangs on BDW.
1849 * Given two bad options, we choose the one which works.
1850 */
1851 if ((wm_prog_data->has_side_effects || wm_prog_data->uses_kill) &&
1852 !has_color_buffer_write_enabled(pipeline, blend))
1853 wm.ForceThreadDispatchEnable = ForceON;
1854 #endif
1855
1856 wm.BarycentricInterpolationMode =
1857 wm_prog_data->barycentric_interp_modes;
1858
1859 #if GEN_GEN < 8
1860 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1861 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1862 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1863 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1864
1865 /* If the subpass has a depth or stencil self-dependency, then we
1866 * need to force the hardware to do the depth/stencil write *after*
1867 * fragment shader execution. Otherwise, the writes may hit memory
1868 * before we get around to fetching from the input attachment and we
1869 * may get the depth or stencil value from the current draw rather
1870 * than the previous one.
1871 */
1872 wm.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
1873 wm_prog_data->uses_kill;
1874
1875 if (wm.PixelShaderComputedDepthMode != PSCDEPTH_OFF ||
1876 wm_prog_data->has_side_effects ||
1877 wm.PixelShaderKillsPixel ||
1878 has_color_buffer_write_enabled(pipeline, blend))
1879 wm.ThreadDispatchEnable = true;
1880
1881 if (multisample && multisample->rasterizationSamples > 1) {
1882 if (wm_prog_data->persample_dispatch) {
1883 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1884 } else {
1885 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1886 }
1887 } else {
1888 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1889 }
1890 wm.MultisampleRasterizationMode =
1891 gen7_ms_rast_mode(pipeline, ia, raster, multisample);
1892 #endif
1893
1894 wm.LineStippleEnable = line && line->stippledLineEnable;
1895 }
1896 }
1897 }
1898
1899 static void
1900 emit_3dstate_ps(struct anv_graphics_pipeline *pipeline,
1901 const VkPipelineColorBlendStateCreateInfo *blend,
1902 const VkPipelineMultisampleStateCreateInfo *multisample)
1903 {
1904 UNUSED const struct gen_device_info *devinfo = &pipeline->base.device->info;
1905 const struct anv_shader_bin *fs_bin =
1906 pipeline->shaders[MESA_SHADER_FRAGMENT];
1907
1908 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1909 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS), ps) {
1910 #if GEN_GEN == 7
1911 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1912 * we don't at least set the maximum number of threads.
1913 */
1914 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1915 #endif
1916 }
1917 return;
1918 }
1919
1920 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1921
1922 #if GEN_GEN < 8
1923 /* The hardware wedges if you have this bit set but don't turn on any dual
1924 * source blend factors.
1925 */
1926 bool dual_src_blend = false;
1927 if (wm_prog_data->dual_src_blend && blend) {
1928 for (uint32_t i = 0; i < blend->attachmentCount; i++) {
1929 const VkPipelineColorBlendAttachmentState *bstate =
1930 &blend->pAttachments[i];
1931
1932 if (bstate->blendEnable &&
1933 (is_dual_src_blend_factor(bstate->srcColorBlendFactor) ||
1934 is_dual_src_blend_factor(bstate->dstColorBlendFactor) ||
1935 is_dual_src_blend_factor(bstate->srcAlphaBlendFactor) ||
1936 is_dual_src_blend_factor(bstate->dstAlphaBlendFactor))) {
1937 dual_src_blend = true;
1938 break;
1939 }
1940 }
1941 }
1942 #endif
1943
1944 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS), ps) {
1945 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1946 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1947 ps._32PixelDispatchEnable = wm_prog_data->dispatch_32;
1948
1949 /* From the Sky Lake PRM 3DSTATE_PS::32 Pixel Dispatch Enable:
1950 *
1951 * "When NUM_MULTISAMPLES = 16 or FORCE_SAMPLE_COUNT = 16, SIMD32
1952 * Dispatch must not be enabled for PER_PIXEL dispatch mode."
1953 *
1954 * Since 16x MSAA is first introduced on SKL, we don't need to apply
1955 * the workaround on any older hardware.
1956 */
1957 if (GEN_GEN >= 9 && !wm_prog_data->persample_dispatch &&
1958 multisample && multisample->rasterizationSamples == 16) {
1959 assert(ps._8PixelDispatchEnable || ps._16PixelDispatchEnable);
1960 ps._32PixelDispatchEnable = false;
1961 }
1962
1963 ps.KernelStartPointer0 = fs_bin->kernel.offset +
1964 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 0);
1965 ps.KernelStartPointer1 = fs_bin->kernel.offset +
1966 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 1);
1967 ps.KernelStartPointer2 = fs_bin->kernel.offset +
1968 brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
1969
1970 ps.SingleProgramFlow = false;
1971 ps.VectorMaskEnable = GEN_GEN >= 8;
1972 /* WA_1606682166 */
1973 ps.SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(fs_bin);
1974 ps.BindingTableEntryCount = get_binding_table_entry_count(fs_bin);
1975 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0 ||
1976 wm_prog_data->base.ubo_ranges[0].length;
1977 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
1978 POSOFFSET_SAMPLE: POSOFFSET_NONE;
1979 #if GEN_GEN < 8
1980 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1981 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1982 ps.DualSourceBlendEnable = dual_src_blend;
1983 #endif
1984
1985 #if GEN_IS_HASWELL
1986 /* Haswell requires the sample mask to be set in this packet as well
1987 * as in 3DSTATE_SAMPLE_MASK; the values should match.
1988 */
1989 ps.SampleMask = 0xff;
1990 #endif
1991
1992 #if GEN_GEN >= 9
1993 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
1994 #elif GEN_GEN >= 8
1995 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
1996 #else
1997 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1998 #endif
1999
2000 ps.DispatchGRFStartRegisterForConstantSetupData0 =
2001 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 0);
2002 ps.DispatchGRFStartRegisterForConstantSetupData1 =
2003 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 1);
2004 ps.DispatchGRFStartRegisterForConstantSetupData2 =
2005 brw_wm_prog_data_dispatch_grf_start_reg(wm_prog_data, ps, 2);
2006
2007 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
2008 ps.ScratchSpaceBasePointer =
2009 get_scratch_address(&pipeline->base, MESA_SHADER_FRAGMENT, fs_bin);
2010 }
2011 }
2012
2013 #if GEN_GEN >= 8
2014 static void
2015 emit_3dstate_ps_extra(struct anv_graphics_pipeline *pipeline,
2016 struct anv_subpass *subpass)
2017 {
2018 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
2019
2020 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
2021 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS_EXTRA), ps);
2022 return;
2023 }
2024
2025 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PS_EXTRA), ps) {
2026 ps.PixelShaderValid = true;
2027 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
2028 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
2029 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
2030 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
2031 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
2032 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
2033
2034 /* If the subpass has a depth or stencil self-dependency, then we need
2035 * to force the hardware to do the depth/stencil write *after* fragment
2036 * shader execution. Otherwise, the writes may hit memory before we get
2037 * around to fetching from the input attachment and we may get the depth
2038 * or stencil value from the current draw rather than the previous one.
2039 */
2040 ps.PixelShaderKillsPixel = subpass->has_ds_self_dep ||
2041 wm_prog_data->uses_kill;
2042
2043 #if GEN_GEN >= 9
2044 ps.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
2045 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
2046
2047 ps.InputCoverageMaskState = ICMS_NONE;
2048 if (wm_prog_data->uses_sample_mask) {
2049 if (wm_prog_data->post_depth_coverage)
2050 ps.InputCoverageMaskState = ICMS_DEPTH_COVERAGE;
2051 else
2052 ps.InputCoverageMaskState = ICMS_INNER_CONSERVATIVE;
2053 }
2054 #else
2055 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
2056 #endif
2057 }
2058 }
2059
2060 static void
2061 emit_3dstate_vf_topology(struct anv_graphics_pipeline *pipeline)
2062 {
2063 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
2064 vft.PrimitiveTopologyType = pipeline->topology;
2065 }
2066 }
2067 #endif
2068
2069 static void
2070 emit_3dstate_vf_statistics(struct anv_graphics_pipeline *pipeline)
2071 {
2072 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_VF_STATISTICS), vfs) {
2073 vfs.StatisticsEnable = true;
2074 }
2075 }
2076
2077 static void
2078 compute_kill_pixel(struct anv_graphics_pipeline *pipeline,
2079 const VkPipelineMultisampleStateCreateInfo *ms_info,
2080 const struct anv_subpass *subpass)
2081 {
2082 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
2083 pipeline->kill_pixel = false;
2084 return;
2085 }
2086
2087 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
2088
2089 /* This computes the KillPixel portion of the computation for whether or
2090 * not we want to enable the PMA fix on gen8 or gen9. It's given by this
2091 * chunk of the giant formula:
2092 *
2093 * (3DSTATE_PS_EXTRA::PixelShaderKillsPixels ||
2094 * 3DSTATE_PS_EXTRA::oMask Present to RenderTarget ||
2095 * 3DSTATE_PS_BLEND::AlphaToCoverageEnable ||
2096 * 3DSTATE_PS_BLEND::AlphaTestEnable ||
2097 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable)
2098 *
2099 * 3DSTATE_WM_CHROMAKEY::ChromaKeyKillEnable is always false and so is
2100 * 3DSTATE_PS_BLEND::AlphaTestEnable since Vulkan doesn't have a concept
2101 * of an alpha test.
2102 */
2103 pipeline->kill_pixel =
2104 subpass->has_ds_self_dep || wm_prog_data->uses_kill ||
2105 wm_prog_data->uses_omask ||
2106 (ms_info && ms_info->alphaToCoverageEnable);
2107 }
2108
2109 #if GEN_GEN == 12
2110 static void
2111 emit_3dstate_primitive_replication(struct anv_graphics_pipeline *pipeline)
2112 {
2113 if (!pipeline->use_primitive_replication) {
2114 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PRIMITIVE_REPLICATION), pr);
2115 return;
2116 }
2117
2118 uint32_t view_mask = pipeline->subpass->view_mask;
2119 int view_count = util_bitcount(view_mask);
2120 assert(view_count > 1 && view_count <= MAX_VIEWS_FOR_PRIMITIVE_REPLICATION);
2121
2122 anv_batch_emit(&pipeline->base.batch, GENX(3DSTATE_PRIMITIVE_REPLICATION), pr) {
2123 pr.ReplicaMask = (1 << view_count) - 1;
2124 pr.ReplicationCount = view_count - 1;
2125
2126 int i = 0, view_index;
2127 for_each_bit(view_index, view_mask) {
2128 pr.RTAIOffset[i] = view_index;
2129 i++;
2130 }
2131 }
2132 }
2133 #endif
2134
2135 static VkResult
2136 genX(graphics_pipeline_create)(
2137 VkDevice _device,
2138 struct anv_pipeline_cache * cache,
2139 const VkGraphicsPipelineCreateInfo* pCreateInfo,
2140 const VkAllocationCallbacks* pAllocator,
2141 VkPipeline* pPipeline)
2142 {
2143 ANV_FROM_HANDLE(anv_device, device, _device);
2144 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
2145 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
2146 struct anv_graphics_pipeline *pipeline;
2147 VkResult result;
2148
2149 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
2150
2151 /* Use the default pipeline cache if none is specified */
2152 if (cache == NULL && device->physical->instance->pipeline_cache_enabled)
2153 cache = &device->default_pipeline_cache;
2154
2155 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
2156 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2157 if (pipeline == NULL)
2158 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2159
2160 result = anv_pipeline_init(pipeline, device, cache,
2161 pCreateInfo, pAllocator);
2162 if (result != VK_SUCCESS) {
2163 vk_free2(&device->alloc, pAllocator, pipeline);
2164 return result;
2165 }
2166
2167 /* If rasterization is not enabled, various CreateInfo structs must be
2168 * ignored.
2169 */
2170 const bool raster_enabled =
2171 !pCreateInfo->pRasterizationState->rasterizerDiscardEnable;
2172
2173 const VkPipelineViewportStateCreateInfo *vp_info =
2174 raster_enabled ? pCreateInfo->pViewportState : NULL;
2175
2176 const VkPipelineMultisampleStateCreateInfo *ms_info =
2177 raster_enabled ? pCreateInfo->pMultisampleState : NULL;
2178
2179 const VkPipelineDepthStencilStateCreateInfo *ds_info =
2180 raster_enabled ? pCreateInfo->pDepthStencilState : NULL;
2181
2182 const VkPipelineColorBlendStateCreateInfo *cb_info =
2183 raster_enabled ? pCreateInfo->pColorBlendState : NULL;
2184
2185 const VkPipelineRasterizationLineStateCreateInfoEXT *line_info =
2186 vk_find_struct_const(pCreateInfo->pRasterizationState->pNext,
2187 PIPELINE_RASTERIZATION_LINE_STATE_CREATE_INFO_EXT);
2188
2189 enum gen_urb_deref_block_size urb_deref_block_size;
2190 emit_urb_setup(pipeline, &urb_deref_block_size);
2191
2192 assert(pCreateInfo->pVertexInputState);
2193 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
2194 assert(pCreateInfo->pRasterizationState);
2195 emit_rs_state(pipeline, pCreateInfo->pInputAssemblyState,
2196 pCreateInfo->pRasterizationState,
2197 ms_info, line_info, pass, subpass,
2198 urb_deref_block_size);
2199 emit_ms_state(pipeline, ms_info);
2200 emit_ds_state(pipeline, ds_info, pass, subpass);
2201 emit_cb_state(pipeline, cb_info, ms_info);
2202 compute_kill_pixel(pipeline, ms_info, subpass);
2203
2204 emit_3dstate_clip(pipeline,
2205 pCreateInfo->pInputAssemblyState,
2206 vp_info,
2207 pCreateInfo->pRasterizationState);
2208 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
2209
2210 #if GEN_GEN == 12
2211 emit_3dstate_primitive_replication(pipeline);
2212 #endif
2213
2214 #if 0
2215 /* From gen7_vs_state.c */
2216
2217 /**
2218 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
2219 * Geometry > Geometry Shader > State:
2220 *
2221 * "Note: Because of corruption in IVB:GT2, software needs to flush the
2222 * whole fixed function pipeline when the GS enable changes value in
2223 * the 3DSTATE_GS."
2224 *
2225 * The hardware architects have clarified that in this context "flush the
2226 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
2227 * Stall" bit set.
2228 */
2229 if (!device->info.is_haswell && !device->info.is_baytrail)
2230 gen7_emit_vs_workaround_flush(brw);
2231 #endif
2232
2233 emit_3dstate_vs(pipeline);
2234 emit_3dstate_hs_te_ds(pipeline, pCreateInfo->pTessellationState);
2235 emit_3dstate_gs(pipeline);
2236 emit_3dstate_sbe(pipeline);
2237 emit_3dstate_wm(pipeline, subpass,
2238 pCreateInfo->pInputAssemblyState,
2239 pCreateInfo->pRasterizationState,
2240 cb_info, ms_info, line_info);
2241 emit_3dstate_ps(pipeline, cb_info, ms_info);
2242 #if GEN_GEN >= 8
2243 emit_3dstate_ps_extra(pipeline, subpass);
2244 emit_3dstate_vf_topology(pipeline);
2245 #endif
2246 emit_3dstate_vf_statistics(pipeline);
2247
2248 *pPipeline = anv_pipeline_to_handle(&pipeline->base);
2249
2250 return pipeline->base.batch.status;
2251 }
2252
2253 static VkResult
2254 compute_pipeline_create(
2255 VkDevice _device,
2256 struct anv_pipeline_cache * cache,
2257 const VkComputePipelineCreateInfo* pCreateInfo,
2258 const VkAllocationCallbacks* pAllocator,
2259 VkPipeline* pPipeline)
2260 {
2261 ANV_FROM_HANDLE(anv_device, device, _device);
2262 const struct gen_device_info *devinfo = &device->info;
2263 struct anv_compute_pipeline *pipeline;
2264 VkResult result;
2265
2266 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
2267
2268 /* Use the default pipeline cache if none is specified */
2269 if (cache == NULL && device->physical->instance->pipeline_cache_enabled)
2270 cache = &device->default_pipeline_cache;
2271
2272 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
2273 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2274 if (pipeline == NULL)
2275 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2276
2277 pipeline->base.device = device;
2278 pipeline->base.type = ANV_PIPELINE_COMPUTE;
2279
2280 const VkAllocationCallbacks *alloc =
2281 pAllocator ? pAllocator : &device->alloc;
2282
2283 result = anv_reloc_list_init(&pipeline->base.batch_relocs, alloc);
2284 if (result != VK_SUCCESS) {
2285 vk_free2(&device->alloc, pAllocator, pipeline);
2286 return result;
2287 }
2288 pipeline->base.batch.alloc = alloc;
2289 pipeline->base.batch.next = pipeline->base.batch.start = pipeline->batch_data;
2290 pipeline->base.batch.end = pipeline->base.batch.start + sizeof(pipeline->batch_data);
2291 pipeline->base.batch.relocs = &pipeline->base.batch_relocs;
2292 pipeline->base.batch.status = VK_SUCCESS;
2293
2294 pipeline->base.mem_ctx = ralloc_context(NULL);
2295 pipeline->base.flags = pCreateInfo->flags;
2296 pipeline->cs = NULL;
2297
2298 util_dynarray_init(&pipeline->base.executables, pipeline->base.mem_ctx);
2299
2300 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
2301 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
2302 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
2303 pCreateInfo->stage.pName,
2304 pCreateInfo->stage.pSpecializationInfo);
2305 if (result != VK_SUCCESS) {
2306 ralloc_free(pipeline->base.mem_ctx);
2307 vk_free2(&device->alloc, pAllocator, pipeline);
2308 return result;
2309 }
2310
2311 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
2312
2313 anv_pipeline_setup_l3_config(&pipeline->base, cs_prog_data->base.total_shared > 0);
2314
2315 uint32_t group_size = cs_prog_data->local_size[0] *
2316 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
2317 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
2318
2319 if (remainder > 0)
2320 pipeline->cs_right_mask = ~0u >> (32 - remainder);
2321 else
2322 pipeline->cs_right_mask = ~0u >> (32 - cs_prog_data->simd_size);
2323
2324 const uint32_t threads = anv_cs_threads(pipeline);
2325
2326 const uint32_t vfe_curbe_allocation =
2327 ALIGN(cs_prog_data->push.per_thread.regs * threads +
2328 cs_prog_data->push.cross_thread.regs, 2);
2329
2330 const uint32_t subslices = MAX2(device->physical->subslice_total, 1);
2331
2332 const struct anv_shader_bin *cs_bin = pipeline->cs;
2333
2334 anv_batch_emit(&pipeline->base.batch, GENX(MEDIA_VFE_STATE), vfe) {
2335 #if GEN_GEN > 7
2336 vfe.StackSize = 0;
2337 #else
2338 vfe.GPGPUMode = true;
2339 #endif
2340 vfe.MaximumNumberofThreads =
2341 devinfo->max_cs_threads * subslices - 1;
2342 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
2343 #if GEN_GEN < 11
2344 vfe.ResetGatewayTimer = true;
2345 #endif
2346 #if GEN_GEN <= 8
2347 vfe.BypassGatewayControl = true;
2348 #endif
2349 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
2350 vfe.CURBEAllocationSize = vfe_curbe_allocation;
2351
2352 if (cs_bin->prog_data->total_scratch) {
2353 if (GEN_GEN >= 8) {
2354 /* Broadwell's Per Thread Scratch Space is in the range [0, 11]
2355 * where 0 = 1k, 1 = 2k, 2 = 4k, ..., 11 = 2M.
2356 */
2357 vfe.PerThreadScratchSpace =
2358 ffs(cs_bin->prog_data->total_scratch) - 11;
2359 } else if (GEN_IS_HASWELL) {
2360 /* Haswell's Per Thread Scratch Space is in the range [0, 10]
2361 * where 0 = 2k, 1 = 4k, 2 = 8k, ..., 10 = 2M.
2362 */
2363 vfe.PerThreadScratchSpace =
2364 ffs(cs_bin->prog_data->total_scratch) - 12;
2365 } else {
2366 /* IVB and BYT use the range [0, 11] to mean [1kB, 12kB]
2367 * where 0 = 1kB, 1 = 2kB, 2 = 3kB, ..., 11 = 12kB.
2368 */
2369 vfe.PerThreadScratchSpace =
2370 cs_bin->prog_data->total_scratch / 1024 - 1;
2371 }
2372 vfe.ScratchSpaceBasePointer =
2373 get_scratch_address(&pipeline->base, MESA_SHADER_COMPUTE, cs_bin);
2374 }
2375 }
2376
2377 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
2378 .KernelStartPointer = cs_bin->kernel.offset,
2379 /* WA_1606682166 */
2380 .SamplerCount = GEN_GEN == 11 ? 0 : get_sampler_count(cs_bin),
2381 /* We add 1 because the CS indirect parameters buffer isn't accounted
2382 * for in bind_map.surface_count.
2383 */
2384 .BindingTableEntryCount = 1 + MIN2(cs_bin->bind_map.surface_count, 30),
2385 .BarrierEnable = cs_prog_data->uses_barrier,
2386 .SharedLocalMemorySize =
2387 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
2388
2389 #if !GEN_IS_HASWELL
2390 .ConstantURBEntryReadOffset = 0,
2391 #endif
2392 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
2393 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2394 .CrossThreadConstantDataReadLength =
2395 cs_prog_data->push.cross_thread.regs,
2396 #endif
2397 #if GEN_GEN >= 12
2398 /* TODO: Check if we are missing workarounds and enable mid-thread
2399 * preemption.
2400 *
2401 * We still have issues with mid-thread preemption (it was already
2402 * disabled by the kernel on gen11, due to missing workarounds). It's
2403 * possible that we are just missing some workarounds, and could enable
2404 * it later, but for now let's disable it to fix a GPU in compute in Car
2405 * Chase (and possibly more).
2406 */
2407 .ThreadPreemptionDisable = true,
2408 #endif
2409
2410 .NumberofThreadsinGPGPUThreadGroup = threads,
2411 };
2412 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
2413 pipeline->interface_descriptor_data,
2414 &desc);
2415
2416 *pPipeline = anv_pipeline_to_handle(&pipeline->base);
2417
2418 return pipeline->base.batch.status;
2419 }
2420
2421 VkResult genX(CreateGraphicsPipelines)(
2422 VkDevice _device,
2423 VkPipelineCache pipelineCache,
2424 uint32_t count,
2425 const VkGraphicsPipelineCreateInfo* pCreateInfos,
2426 const VkAllocationCallbacks* pAllocator,
2427 VkPipeline* pPipelines)
2428 {
2429 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
2430
2431 VkResult result = VK_SUCCESS;
2432
2433 unsigned i;
2434 for (i = 0; i < count; i++) {
2435 result = genX(graphics_pipeline_create)(_device,
2436 pipeline_cache,
2437 &pCreateInfos[i],
2438 pAllocator, &pPipelines[i]);
2439
2440 /* Bail out on the first error as it is not obvious what error should be
2441 * report upon 2 different failures. */
2442 if (result != VK_SUCCESS)
2443 break;
2444 }
2445
2446 for (; i < count; i++)
2447 pPipelines[i] = VK_NULL_HANDLE;
2448
2449 return result;
2450 }
2451
2452 VkResult genX(CreateComputePipelines)(
2453 VkDevice _device,
2454 VkPipelineCache pipelineCache,
2455 uint32_t count,
2456 const VkComputePipelineCreateInfo* pCreateInfos,
2457 const VkAllocationCallbacks* pAllocator,
2458 VkPipeline* pPipelines)
2459 {
2460 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
2461
2462 VkResult result = VK_SUCCESS;
2463
2464 unsigned i;
2465 for (i = 0; i < count; i++) {
2466 result = compute_pipeline_create(_device, pipeline_cache,
2467 &pCreateInfos[i],
2468 pAllocator, &pPipelines[i]);
2469
2470 /* Bail out on the first error as it is not obvious what error should be
2471 * report upon 2 different failures. */
2472 if (result != VK_SUCCESS)
2473 break;
2474 }
2475
2476 for (; i < count; i++)
2477 pPipelines[i] = VK_NULL_HANDLE;
2478
2479 return result;
2480 }