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