intel: Share URB configuration code between GL and Vulkan.
[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 "vk_format_info.h"
32
33 static uint32_t
34 vertex_element_comp_control(enum isl_format format, unsigned comp)
35 {
36 uint8_t bits;
37 switch (comp) {
38 case 0: bits = isl_format_layouts[format].channels.r.bits; break;
39 case 1: bits = isl_format_layouts[format].channels.g.bits; break;
40 case 2: bits = isl_format_layouts[format].channels.b.bits; break;
41 case 3: bits = isl_format_layouts[format].channels.a.bits; break;
42 default: unreachable("Invalid component");
43 }
44
45 if (bits) {
46 return VFCOMP_STORE_SRC;
47 } else if (comp < 3) {
48 return VFCOMP_STORE_0;
49 } else if (isl_format_layouts[format].channels.r.type == ISL_UINT ||
50 isl_format_layouts[format].channels.r.type == ISL_SINT) {
51 assert(comp == 3);
52 return VFCOMP_STORE_1_INT;
53 } else {
54 assert(comp == 3);
55 return VFCOMP_STORE_1_FP;
56 }
57 }
58
59 static void
60 emit_vertex_input(struct anv_pipeline *pipeline,
61 const VkPipelineVertexInputStateCreateInfo *info)
62 {
63 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
64
65 /* Pull inputs_read out of the VS prog data */
66 const uint64_t inputs_read = vs_prog_data->inputs_read;
67 assert((inputs_read & ((1 << VERT_ATTRIB_GENERIC0) - 1)) == 0);
68 const uint32_t elements = inputs_read >> VERT_ATTRIB_GENERIC0;
69
70 #if GEN_GEN >= 8
71 /* On BDW+, we only need to allocate space for base ids. Setting up
72 * the actual vertex and instance id is a separate packet.
73 */
74 const bool needs_svgs_elem = vs_prog_data->uses_basevertex ||
75 vs_prog_data->uses_baseinstance;
76 #else
77 /* On Haswell and prior, vertex and instance id are created by using the
78 * ComponentControl fields, so we need an element for any of them.
79 */
80 const bool needs_svgs_elem = vs_prog_data->uses_vertexid ||
81 vs_prog_data->uses_instanceid ||
82 vs_prog_data->uses_basevertex ||
83 vs_prog_data->uses_baseinstance;
84 #endif
85
86 uint32_t elem_count = __builtin_popcount(elements) + needs_svgs_elem;
87 if (elem_count == 0)
88 return;
89
90 uint32_t *p;
91
92 const uint32_t num_dwords = 1 + elem_count * 2;
93 p = anv_batch_emitn(&pipeline->batch, num_dwords,
94 GENX(3DSTATE_VERTEX_ELEMENTS));
95 memset(p + 1, 0, (num_dwords - 1) * 4);
96
97 for (uint32_t i = 0; i < info->vertexAttributeDescriptionCount; i++) {
98 const VkVertexInputAttributeDescription *desc =
99 &info->pVertexAttributeDescriptions[i];
100 enum isl_format format = anv_get_isl_format(&pipeline->device->info,
101 desc->format,
102 VK_IMAGE_ASPECT_COLOR_BIT,
103 VK_IMAGE_TILING_LINEAR);
104
105 assert(desc->binding < 32);
106
107 if ((elements & (1 << desc->location)) == 0)
108 continue; /* Binding unused */
109
110 uint32_t slot = __builtin_popcount(elements & ((1 << desc->location) - 1));
111
112 struct GENX(VERTEX_ELEMENT_STATE) element = {
113 .VertexBufferIndex = desc->binding,
114 .Valid = true,
115 .SourceElementFormat = format,
116 .EdgeFlagEnable = false,
117 .SourceElementOffset = desc->offset,
118 .Component0Control = vertex_element_comp_control(format, 0),
119 .Component1Control = vertex_element_comp_control(format, 1),
120 .Component2Control = vertex_element_comp_control(format, 2),
121 .Component3Control = vertex_element_comp_control(format, 3),
122 };
123 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + slot * 2], &element);
124
125 #if GEN_GEN >= 8
126 /* On Broadwell and later, we have a separate VF_INSTANCING packet
127 * that controls instancing. On Haswell and prior, that's part of
128 * VERTEX_BUFFER_STATE which we emit later.
129 */
130 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_INSTANCING), vfi) {
131 vfi.InstancingEnable = pipeline->instancing_enable[desc->binding];
132 vfi.VertexElementIndex = slot;
133 /* Vulkan so far doesn't have an instance divisor, so
134 * this is always 1 (ignored if not instancing). */
135 vfi.InstanceDataStepRate = 1;
136 }
137 #endif
138 }
139
140 const uint32_t id_slot = __builtin_popcount(elements);
141 if (needs_svgs_elem) {
142 /* From the Broadwell PRM for the 3D_Vertex_Component_Control enum:
143 * "Within a VERTEX_ELEMENT_STATE structure, if a Component
144 * Control field is set to something other than VFCOMP_STORE_SRC,
145 * no higher-numbered Component Control fields may be set to
146 * VFCOMP_STORE_SRC"
147 *
148 * This means, that if we have BaseInstance, we need BaseVertex as
149 * well. Just do all or nothing.
150 */
151 uint32_t base_ctrl = (vs_prog_data->uses_basevertex ||
152 vs_prog_data->uses_baseinstance) ?
153 VFCOMP_STORE_SRC : VFCOMP_STORE_0;
154
155 struct GENX(VERTEX_ELEMENT_STATE) element = {
156 .VertexBufferIndex = 32, /* Reserved for this */
157 .Valid = true,
158 .SourceElementFormat = ISL_FORMAT_R32G32_UINT,
159 .Component0Control = base_ctrl,
160 .Component1Control = base_ctrl,
161 #if GEN_GEN >= 8
162 .Component2Control = VFCOMP_STORE_0,
163 .Component3Control = VFCOMP_STORE_0,
164 #else
165 .Component2Control = VFCOMP_STORE_VID,
166 .Component3Control = VFCOMP_STORE_IID,
167 #endif
168 };
169 GENX(VERTEX_ELEMENT_STATE_pack)(NULL, &p[1 + id_slot * 2], &element);
170 }
171
172 #if GEN_GEN >= 8
173 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_SGVS), sgvs) {
174 sgvs.VertexIDEnable = vs_prog_data->uses_vertexid;
175 sgvs.VertexIDComponentNumber = 2;
176 sgvs.VertexIDElementOffset = id_slot;
177 sgvs.InstanceIDEnable = vs_prog_data->uses_instanceid;
178 sgvs.InstanceIDComponentNumber = 3;
179 sgvs.InstanceIDElementOffset = id_slot;
180 }
181 #endif
182 }
183
184 void
185 genX(emit_urb_setup)(struct anv_device *device, struct anv_batch *batch,
186 const struct gen_l3_config *l3_config,
187 VkShaderStageFlags active_stages,
188 const unsigned entry_size[4])
189 {
190 const struct gen_device_info *devinfo = &device->info;
191 #if GEN_IS_HASWELL
192 const unsigned push_constant_kb = devinfo->gt == 3 ? 32 : 16;
193 #else
194 const unsigned push_constant_kb = GEN_GEN >= 8 ? 32 : 16;
195 #endif
196
197 const unsigned urb_size_kb = gen_get_l3_config_urb_size(devinfo, l3_config);
198
199 unsigned entries[4];
200 unsigned start[4];
201 gen_get_urb_config(devinfo,
202 1024 * push_constant_kb, 1024 * urb_size_kb,
203 active_stages &
204 VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
205 active_stages & VK_SHADER_STAGE_GEOMETRY_BIT,
206 entry_size, entries, start);
207
208 #if GEN_GEN == 7 && !GEN_IS_HASWELL
209 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
210 *
211 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth stall
212 * needs to be sent just prior to any 3DSTATE_VS, 3DSTATE_URB_VS,
213 * 3DSTATE_CONSTANT_VS, 3DSTATE_BINDING_TABLE_POINTER_VS,
214 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one PIPE_CONTROL
215 * needs to be sent before any combination of VS associated 3DSTATE."
216 */
217 anv_batch_emit(batch, GEN7_PIPE_CONTROL, pc) {
218 pc.DepthStallEnable = true;
219 pc.PostSyncOperation = WriteImmediateData;
220 pc.Address = (struct anv_address) { &device->workaround_bo, 0 };
221 }
222 #endif
223
224 for (int i = 0; i <= MESA_SHADER_GEOMETRY; i++) {
225 anv_batch_emit(batch, GENX(3DSTATE_URB_VS), urb) {
226 urb._3DCommandSubOpcode += i;
227 urb.VSURBStartingAddress = start[i];
228 urb.VSURBEntryAllocationSize = entry_size[i] - 1;
229 urb.VSNumberofURBEntries = entries[i];
230 }
231 }
232 }
233
234 static inline void
235 emit_urb_setup(struct anv_pipeline *pipeline)
236 {
237 unsigned entry_size[4];
238 for (int i = MESA_SHADER_VERTEX; i <= MESA_SHADER_GEOMETRY; i++) {
239 const struct brw_vue_prog_data *prog_data =
240 !anv_pipeline_has_stage(pipeline, i) ? NULL :
241 (const struct brw_vue_prog_data *) pipeline->shaders[i]->prog_data;
242
243 entry_size[i] = prog_data ? prog_data->urb_entry_size : 1;
244 }
245
246 genX(emit_urb_setup)(pipeline->device, &pipeline->batch,
247 pipeline->urb.l3_config,
248 pipeline->active_stages, entry_size);
249 }
250
251 static void
252 emit_3dstate_sbe(struct anv_pipeline *pipeline)
253 {
254 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
255 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
256 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
257 const struct brw_vue_map *fs_input_map;
258
259 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
260 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE), sbe);
261 #if GEN_GEN >= 8
262 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ), sbe);
263 #endif
264 return;
265 }
266
267 if (gs_prog_data)
268 fs_input_map = &gs_prog_data->base.vue_map;
269 else
270 fs_input_map = &vs_prog_data->base.vue_map;
271
272 struct GENX(3DSTATE_SBE) sbe = {
273 GENX(3DSTATE_SBE_header),
274 .AttributeSwizzleEnable = true,
275 .PointSpriteTextureCoordinateOrigin = UPPERLEFT,
276 .NumberofSFOutputAttributes = wm_prog_data->num_varying_inputs,
277 .ConstantInterpolationEnable = wm_prog_data->flat_inputs,
278 };
279
280 #if GEN_GEN >= 9
281 for (unsigned i = 0; i < 32; i++)
282 sbe.AttributeActiveComponentFormat[i] = ACF_XYZW;
283 #endif
284
285 #if GEN_GEN >= 8
286 /* On Broadwell, they broke 3DSTATE_SBE into two packets */
287 struct GENX(3DSTATE_SBE_SWIZ) swiz = {
288 GENX(3DSTATE_SBE_SWIZ_header),
289 };
290 #else
291 # define swiz sbe
292 #endif
293
294 int max_source_attr = 0;
295 for (int attr = 0; attr < VARYING_SLOT_MAX; attr++) {
296 int input_index = wm_prog_data->urb_setup[attr];
297
298 if (input_index < 0)
299 continue;
300
301 if (attr == VARYING_SLOT_PNTC) {
302 sbe.PointSpriteTextureCoordinateEnable = 1 << input_index;
303 continue;
304 }
305
306 const int slot = fs_input_map->varying_to_slot[attr];
307
308 if (input_index >= 16)
309 continue;
310
311 if (slot == -1) {
312 /* This attribute does not exist in the VUE--that means that the
313 * vertex shader did not write to it. It could be that it's a
314 * regular varying read by the fragment shader but not written by
315 * the vertex shader or it's gl_PrimitiveID. In the first case the
316 * value is undefined, in the second it needs to be
317 * gl_PrimitiveID.
318 */
319 swiz.Attribute[input_index].ConstantSource = PRIM_ID;
320 swiz.Attribute[input_index].ComponentOverrideX = true;
321 swiz.Attribute[input_index].ComponentOverrideY = true;
322 swiz.Attribute[input_index].ComponentOverrideZ = true;
323 swiz.Attribute[input_index].ComponentOverrideW = true;
324 } else {
325 assert(slot >= 2);
326 const int source_attr = slot - 2;
327 max_source_attr = MAX2(max_source_attr, source_attr);
328 /* We have to subtract two slots to accout for the URB entry output
329 * read offset in the VS and GS stages.
330 */
331 swiz.Attribute[input_index].SourceAttribute = source_attr;
332 }
333 }
334
335 sbe.VertexURBEntryReadOffset = 1; /* Skip the VUE header and position slots */
336 sbe.VertexURBEntryReadLength = DIV_ROUND_UP(max_source_attr + 1, 2);
337
338 uint32_t *dw = anv_batch_emit_dwords(&pipeline->batch,
339 GENX(3DSTATE_SBE_length));
340 GENX(3DSTATE_SBE_pack)(&pipeline->batch, dw, &sbe);
341
342 #if GEN_GEN >= 8
343 dw = anv_batch_emit_dwords(&pipeline->batch, GENX(3DSTATE_SBE_SWIZ_length));
344 GENX(3DSTATE_SBE_SWIZ_pack)(&pipeline->batch, dw, &swiz);
345 #endif
346 }
347
348 static const uint32_t vk_to_gen_cullmode[] = {
349 [VK_CULL_MODE_NONE] = CULLMODE_NONE,
350 [VK_CULL_MODE_FRONT_BIT] = CULLMODE_FRONT,
351 [VK_CULL_MODE_BACK_BIT] = CULLMODE_BACK,
352 [VK_CULL_MODE_FRONT_AND_BACK] = CULLMODE_BOTH
353 };
354
355 static const uint32_t vk_to_gen_fillmode[] = {
356 [VK_POLYGON_MODE_FILL] = FILL_MODE_SOLID,
357 [VK_POLYGON_MODE_LINE] = FILL_MODE_WIREFRAME,
358 [VK_POLYGON_MODE_POINT] = FILL_MODE_POINT,
359 };
360
361 static const uint32_t vk_to_gen_front_face[] = {
362 [VK_FRONT_FACE_COUNTER_CLOCKWISE] = 1,
363 [VK_FRONT_FACE_CLOCKWISE] = 0
364 };
365
366 static void
367 emit_rs_state(struct anv_pipeline *pipeline,
368 const VkPipelineRasterizationStateCreateInfo *rs_info,
369 const VkPipelineMultisampleStateCreateInfo *ms_info,
370 const struct anv_render_pass *pass,
371 const struct anv_subpass *subpass)
372 {
373 struct GENX(3DSTATE_SF) sf = {
374 GENX(3DSTATE_SF_header),
375 };
376
377 sf.ViewportTransformEnable = true;
378 sf.StatisticsEnable = true;
379 sf.TriangleStripListProvokingVertexSelect = 0;
380 sf.LineStripListProvokingVertexSelect = 0;
381 sf.TriangleFanProvokingVertexSelect = 1;
382 sf.PointWidthSource = Vertex;
383 sf.PointWidth = 1.0;
384
385 #if GEN_GEN >= 8
386 struct GENX(3DSTATE_RASTER) raster = {
387 GENX(3DSTATE_RASTER_header),
388 };
389 #else
390 # define raster sf
391 #endif
392
393 /* For details on 3DSTATE_RASTER multisample state, see the BSpec table
394 * "Multisample Modes State".
395 */
396 #if GEN_GEN >= 8
397 raster.DXMultisampleRasterizationEnable = true;
398 raster.ForcedSampleCount = FSC_NUMRASTSAMPLES_0;
399 raster.ForceMultisampling = false;
400 #else
401 raster.MultisampleRasterizationMode =
402 (ms_info && ms_info->rasterizationSamples > 1) ?
403 MSRASTMODE_ON_PATTERN : MSRASTMODE_OFF_PIXEL;
404 #endif
405
406 raster.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
407 raster.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
408 raster.FrontFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
409 raster.BackFaceFillMode = vk_to_gen_fillmode[rs_info->polygonMode];
410 raster.ScissorRectangleEnable = true;
411
412 #if GEN_GEN >= 9
413 /* GEN9+ splits ViewportZClipTestEnable into near and far enable bits */
414 raster.ViewportZFarClipTestEnable = !pipeline->depth_clamp_enable;
415 raster.ViewportZNearClipTestEnable = !pipeline->depth_clamp_enable;
416 #elif GEN_GEN >= 8
417 raster.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
418 #endif
419
420 raster.GlobalDepthOffsetEnableSolid = rs_info->depthBiasEnable;
421 raster.GlobalDepthOffsetEnableWireframe = rs_info->depthBiasEnable;
422 raster.GlobalDepthOffsetEnablePoint = rs_info->depthBiasEnable;
423
424 #if GEN_GEN == 7
425 /* Gen7 requires that we provide the depth format in 3DSTATE_SF so that it
426 * can get the depth offsets correct.
427 */
428 if (subpass->depth_stencil_attachment < pass->attachment_count) {
429 VkFormat vk_format =
430 pass->attachments[subpass->depth_stencil_attachment].format;
431 assert(vk_format_is_depth_or_stencil(vk_format));
432 if (vk_format_aspects(vk_format) & VK_IMAGE_ASPECT_DEPTH_BIT) {
433 enum isl_format isl_format =
434 anv_get_isl_format(&pipeline->device->info, vk_format,
435 VK_IMAGE_ASPECT_DEPTH_BIT,
436 VK_IMAGE_TILING_OPTIMAL);
437 sf.DepthBufferSurfaceFormat =
438 isl_format_get_depth_format(isl_format, false);
439 }
440 }
441 #endif
442
443 #if GEN_GEN >= 8
444 GENX(3DSTATE_SF_pack)(NULL, pipeline->gen8.sf, &sf);
445 GENX(3DSTATE_RASTER_pack)(NULL, pipeline->gen8.raster, &raster);
446 #else
447 # undef raster
448 GENX(3DSTATE_SF_pack)(NULL, &pipeline->gen7.sf, &sf);
449 #endif
450 }
451
452 static void
453 emit_ms_state(struct anv_pipeline *pipeline,
454 const VkPipelineMultisampleStateCreateInfo *info)
455 {
456 uint32_t samples = 1;
457 uint32_t log2_samples = 0;
458
459 /* From the Vulkan 1.0 spec:
460 * If pSampleMask is NULL, it is treated as if the mask has all bits
461 * enabled, i.e. no coverage is removed from fragments.
462 *
463 * 3DSTATE_SAMPLE_MASK.SampleMask is 16 bits.
464 */
465 #if GEN_GEN >= 8
466 uint32_t sample_mask = 0xffff;
467 #else
468 uint32_t sample_mask = 0xff;
469 #endif
470
471 if (info) {
472 samples = info->rasterizationSamples;
473 log2_samples = __builtin_ffs(samples) - 1;
474 }
475
476 if (info && info->pSampleMask)
477 sample_mask &= info->pSampleMask[0];
478
479 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_MULTISAMPLE), ms) {
480 ms.NumberofMultisamples = log2_samples;
481
482 #if GEN_GEN >= 8
483 /* The PRM says that this bit is valid only for DX9:
484 *
485 * SW can choose to set this bit only for DX9 API. DX10/OGL API's
486 * should not have any effect by setting or not setting this bit.
487 */
488 ms.PixelPositionOffsetEnable = false;
489 ms.PixelLocation = CENTER;
490 #else
491 ms.PixelLocation = PIXLOC_CENTER;
492
493 switch (samples) {
494 case 1:
495 GEN_SAMPLE_POS_1X(ms.Sample);
496 break;
497 case 2:
498 GEN_SAMPLE_POS_2X(ms.Sample);
499 break;
500 case 4:
501 GEN_SAMPLE_POS_4X(ms.Sample);
502 break;
503 case 8:
504 GEN_SAMPLE_POS_8X(ms.Sample);
505 break;
506 default:
507 break;
508 }
509 #endif
510 }
511
512 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_SAMPLE_MASK), sm) {
513 sm.SampleMask = sample_mask;
514 }
515 }
516
517 static const uint32_t vk_to_gen_logic_op[] = {
518 [VK_LOGIC_OP_COPY] = LOGICOP_COPY,
519 [VK_LOGIC_OP_CLEAR] = LOGICOP_CLEAR,
520 [VK_LOGIC_OP_AND] = LOGICOP_AND,
521 [VK_LOGIC_OP_AND_REVERSE] = LOGICOP_AND_REVERSE,
522 [VK_LOGIC_OP_AND_INVERTED] = LOGICOP_AND_INVERTED,
523 [VK_LOGIC_OP_NO_OP] = LOGICOP_NOOP,
524 [VK_LOGIC_OP_XOR] = LOGICOP_XOR,
525 [VK_LOGIC_OP_OR] = LOGICOP_OR,
526 [VK_LOGIC_OP_NOR] = LOGICOP_NOR,
527 [VK_LOGIC_OP_EQUIVALENT] = LOGICOP_EQUIV,
528 [VK_LOGIC_OP_INVERT] = LOGICOP_INVERT,
529 [VK_LOGIC_OP_OR_REVERSE] = LOGICOP_OR_REVERSE,
530 [VK_LOGIC_OP_COPY_INVERTED] = LOGICOP_COPY_INVERTED,
531 [VK_LOGIC_OP_OR_INVERTED] = LOGICOP_OR_INVERTED,
532 [VK_LOGIC_OP_NAND] = LOGICOP_NAND,
533 [VK_LOGIC_OP_SET] = LOGICOP_SET,
534 };
535
536 static const uint32_t vk_to_gen_blend[] = {
537 [VK_BLEND_FACTOR_ZERO] = BLENDFACTOR_ZERO,
538 [VK_BLEND_FACTOR_ONE] = BLENDFACTOR_ONE,
539 [VK_BLEND_FACTOR_SRC_COLOR] = BLENDFACTOR_SRC_COLOR,
540 [VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR] = BLENDFACTOR_INV_SRC_COLOR,
541 [VK_BLEND_FACTOR_DST_COLOR] = BLENDFACTOR_DST_COLOR,
542 [VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR] = BLENDFACTOR_INV_DST_COLOR,
543 [VK_BLEND_FACTOR_SRC_ALPHA] = BLENDFACTOR_SRC_ALPHA,
544 [VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA] = BLENDFACTOR_INV_SRC_ALPHA,
545 [VK_BLEND_FACTOR_DST_ALPHA] = BLENDFACTOR_DST_ALPHA,
546 [VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA] = BLENDFACTOR_INV_DST_ALPHA,
547 [VK_BLEND_FACTOR_CONSTANT_COLOR] = BLENDFACTOR_CONST_COLOR,
548 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR]= BLENDFACTOR_INV_CONST_COLOR,
549 [VK_BLEND_FACTOR_CONSTANT_ALPHA] = BLENDFACTOR_CONST_ALPHA,
550 [VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA]= BLENDFACTOR_INV_CONST_ALPHA,
551 [VK_BLEND_FACTOR_SRC_ALPHA_SATURATE] = BLENDFACTOR_SRC_ALPHA_SATURATE,
552 [VK_BLEND_FACTOR_SRC1_COLOR] = BLENDFACTOR_SRC1_COLOR,
553 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR] = BLENDFACTOR_INV_SRC1_COLOR,
554 [VK_BLEND_FACTOR_SRC1_ALPHA] = BLENDFACTOR_SRC1_ALPHA,
555 [VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA] = BLENDFACTOR_INV_SRC1_ALPHA,
556 };
557
558 static const uint32_t vk_to_gen_blend_op[] = {
559 [VK_BLEND_OP_ADD] = BLENDFUNCTION_ADD,
560 [VK_BLEND_OP_SUBTRACT] = BLENDFUNCTION_SUBTRACT,
561 [VK_BLEND_OP_REVERSE_SUBTRACT] = BLENDFUNCTION_REVERSE_SUBTRACT,
562 [VK_BLEND_OP_MIN] = BLENDFUNCTION_MIN,
563 [VK_BLEND_OP_MAX] = BLENDFUNCTION_MAX,
564 };
565
566 static const uint32_t vk_to_gen_compare_op[] = {
567 [VK_COMPARE_OP_NEVER] = PREFILTEROPNEVER,
568 [VK_COMPARE_OP_LESS] = PREFILTEROPLESS,
569 [VK_COMPARE_OP_EQUAL] = PREFILTEROPEQUAL,
570 [VK_COMPARE_OP_LESS_OR_EQUAL] = PREFILTEROPLEQUAL,
571 [VK_COMPARE_OP_GREATER] = PREFILTEROPGREATER,
572 [VK_COMPARE_OP_NOT_EQUAL] = PREFILTEROPNOTEQUAL,
573 [VK_COMPARE_OP_GREATER_OR_EQUAL] = PREFILTEROPGEQUAL,
574 [VK_COMPARE_OP_ALWAYS] = PREFILTEROPALWAYS,
575 };
576
577 static const uint32_t vk_to_gen_stencil_op[] = {
578 [VK_STENCIL_OP_KEEP] = STENCILOP_KEEP,
579 [VK_STENCIL_OP_ZERO] = STENCILOP_ZERO,
580 [VK_STENCIL_OP_REPLACE] = STENCILOP_REPLACE,
581 [VK_STENCIL_OP_INCREMENT_AND_CLAMP] = STENCILOP_INCRSAT,
582 [VK_STENCIL_OP_DECREMENT_AND_CLAMP] = STENCILOP_DECRSAT,
583 [VK_STENCIL_OP_INVERT] = STENCILOP_INVERT,
584 [VK_STENCIL_OP_INCREMENT_AND_WRAP] = STENCILOP_INCR,
585 [VK_STENCIL_OP_DECREMENT_AND_WRAP] = STENCILOP_DECR,
586 };
587
588 static void
589 emit_ds_state(struct anv_pipeline *pipeline,
590 const VkPipelineDepthStencilStateCreateInfo *info,
591 const struct anv_render_pass *pass,
592 const struct anv_subpass *subpass)
593 {
594 #if GEN_GEN == 7
595 # define depth_stencil_dw pipeline->gen7.depth_stencil_state
596 #elif GEN_GEN == 8
597 # define depth_stencil_dw pipeline->gen8.wm_depth_stencil
598 #else
599 # define depth_stencil_dw pipeline->gen9.wm_depth_stencil
600 #endif
601
602 if (info == NULL) {
603 /* We're going to OR this together with the dynamic state. We need
604 * to make sure it's initialized to something useful.
605 */
606 memset(depth_stencil_dw, 0, sizeof(depth_stencil_dw));
607 return;
608 }
609
610 /* VkBool32 depthBoundsTestEnable; // optional (depth_bounds_test) */
611
612 #if GEN_GEN <= 7
613 struct GENX(DEPTH_STENCIL_STATE) depth_stencil = {
614 #else
615 struct GENX(3DSTATE_WM_DEPTH_STENCIL) depth_stencil = {
616 #endif
617 .DepthTestEnable = info->depthTestEnable,
618 .DepthBufferWriteEnable = info->depthWriteEnable,
619 .DepthTestFunction = vk_to_gen_compare_op[info->depthCompareOp],
620 .DoubleSidedStencilEnable = true,
621
622 .StencilTestEnable = info->stencilTestEnable,
623 .StencilBufferWriteEnable = info->stencilTestEnable,
624 .StencilFailOp = vk_to_gen_stencil_op[info->front.failOp],
625 .StencilPassDepthPassOp = vk_to_gen_stencil_op[info->front.passOp],
626 .StencilPassDepthFailOp = vk_to_gen_stencil_op[info->front.depthFailOp],
627 .StencilTestFunction = vk_to_gen_compare_op[info->front.compareOp],
628 .BackfaceStencilFailOp = vk_to_gen_stencil_op[info->back.failOp],
629 .BackfaceStencilPassDepthPassOp = vk_to_gen_stencil_op[info->back.passOp],
630 .BackfaceStencilPassDepthFailOp =vk_to_gen_stencil_op[info->back.depthFailOp],
631 .BackfaceStencilTestFunction = vk_to_gen_compare_op[info->back.compareOp],
632 };
633
634 VkImageAspectFlags aspects = 0;
635 if (subpass->depth_stencil_attachment != VK_ATTACHMENT_UNUSED) {
636 VkFormat depth_stencil_format =
637 pass->attachments[subpass->depth_stencil_attachment].format;
638 aspects = vk_format_aspects(depth_stencil_format);
639 }
640
641 /* The Vulkan spec requires that if either depth or stencil is not present,
642 * the pipeline is to act as if the test silently passes.
643 */
644 if (!(aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
645 depth_stencil.DepthBufferWriteEnable = false;
646 depth_stencil.DepthTestFunction = PREFILTEROPALWAYS;
647 }
648
649 if (!(aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
650 depth_stencil.StencilBufferWriteEnable = false;
651 depth_stencil.StencilTestFunction = PREFILTEROPALWAYS;
652 depth_stencil.BackfaceStencilTestFunction = PREFILTEROPALWAYS;
653 }
654
655 /* From the Broadwell PRM:
656 *
657 * "If Depth_Test_Enable = 1 AND Depth_Test_func = EQUAL, the
658 * Depth_Write_Enable must be set to 0."
659 */
660 if (info->depthTestEnable && info->depthCompareOp == VK_COMPARE_OP_EQUAL)
661 depth_stencil.DepthBufferWriteEnable = false;
662
663 #if GEN_GEN <= 7
664 GENX(DEPTH_STENCIL_STATE_pack)(NULL, depth_stencil_dw, &depth_stencil);
665 #else
666 GENX(3DSTATE_WM_DEPTH_STENCIL_pack)(NULL, depth_stencil_dw, &depth_stencil);
667 #endif
668 }
669
670 static void
671 emit_cb_state(struct anv_pipeline *pipeline,
672 const VkPipelineColorBlendStateCreateInfo *info,
673 const VkPipelineMultisampleStateCreateInfo *ms_info)
674 {
675 struct anv_device *device = pipeline->device;
676
677 const uint32_t num_dwords = GENX(BLEND_STATE_length);
678 pipeline->blend_state =
679 anv_state_pool_alloc(&device->dynamic_state_pool, num_dwords * 4, 64);
680
681 struct GENX(BLEND_STATE) blend_state = {
682 #if GEN_GEN >= 8
683 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
684 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
685 #else
686 /* Make sure it gets zeroed */
687 .Entry = { { 0, }, },
688 #endif
689 };
690
691 /* Default everything to disabled */
692 for (uint32_t i = 0; i < 8; i++) {
693 blend_state.Entry[i].WriteDisableAlpha = true;
694 blend_state.Entry[i].WriteDisableRed = true;
695 blend_state.Entry[i].WriteDisableGreen = true;
696 blend_state.Entry[i].WriteDisableBlue = true;
697 }
698
699 uint32_t surface_count = 0;
700 struct anv_pipeline_bind_map *map;
701 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
702 map = &pipeline->shaders[MESA_SHADER_FRAGMENT]->bind_map;
703 surface_count = map->surface_count;
704 }
705
706 bool has_writeable_rt = false;
707 for (unsigned i = 0; i < surface_count; i++) {
708 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[i];
709
710 /* All color attachments are at the beginning of the binding table */
711 if (binding->set != ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS)
712 break;
713
714 /* We can have at most 8 attachments */
715 assert(i < 8);
716
717 if (binding->index >= info->attachmentCount)
718 continue;
719
720 assert(binding->binding == 0);
721 const VkPipelineColorBlendAttachmentState *a =
722 &info->pAttachments[binding->index];
723
724 blend_state.Entry[i] = (struct GENX(BLEND_STATE_ENTRY)) {
725 #if GEN_GEN < 8
726 .AlphaToCoverageEnable = ms_info && ms_info->alphaToCoverageEnable,
727 .AlphaToOneEnable = ms_info && ms_info->alphaToOneEnable,
728 #endif
729 .LogicOpEnable = info->logicOpEnable,
730 .LogicOpFunction = vk_to_gen_logic_op[info->logicOp],
731 .ColorBufferBlendEnable = a->blendEnable,
732 .ColorClampRange = COLORCLAMP_RTFORMAT,
733 .PreBlendColorClampEnable = true,
734 .PostBlendColorClampEnable = true,
735 .SourceBlendFactor = vk_to_gen_blend[a->srcColorBlendFactor],
736 .DestinationBlendFactor = vk_to_gen_blend[a->dstColorBlendFactor],
737 .ColorBlendFunction = vk_to_gen_blend_op[a->colorBlendOp],
738 .SourceAlphaBlendFactor = vk_to_gen_blend[a->srcAlphaBlendFactor],
739 .DestinationAlphaBlendFactor = vk_to_gen_blend[a->dstAlphaBlendFactor],
740 .AlphaBlendFunction = vk_to_gen_blend_op[a->alphaBlendOp],
741 .WriteDisableAlpha = !(a->colorWriteMask & VK_COLOR_COMPONENT_A_BIT),
742 .WriteDisableRed = !(a->colorWriteMask & VK_COLOR_COMPONENT_R_BIT),
743 .WriteDisableGreen = !(a->colorWriteMask & VK_COLOR_COMPONENT_G_BIT),
744 .WriteDisableBlue = !(a->colorWriteMask & VK_COLOR_COMPONENT_B_BIT),
745 };
746
747 if (a->srcColorBlendFactor != a->srcAlphaBlendFactor ||
748 a->dstColorBlendFactor != a->dstAlphaBlendFactor ||
749 a->colorBlendOp != a->alphaBlendOp) {
750 #if GEN_GEN >= 8
751 blend_state.IndependentAlphaBlendEnable = true;
752 #else
753 blend_state.Entry[i].IndependentAlphaBlendEnable = true;
754 #endif
755 }
756
757 if (a->colorWriteMask != 0)
758 has_writeable_rt = true;
759
760 /* Our hardware applies the blend factor prior to the blend function
761 * regardless of what function is used. Technically, this means the
762 * hardware can do MORE than GL or Vulkan specify. However, it also
763 * means that, for MIN and MAX, we have to stomp the blend factor to
764 * ONE to make it a no-op.
765 */
766 if (a->colorBlendOp == VK_BLEND_OP_MIN ||
767 a->colorBlendOp == VK_BLEND_OP_MAX) {
768 blend_state.Entry[i].SourceBlendFactor = BLENDFACTOR_ONE;
769 blend_state.Entry[i].DestinationBlendFactor = BLENDFACTOR_ONE;
770 }
771 if (a->alphaBlendOp == VK_BLEND_OP_MIN ||
772 a->alphaBlendOp == VK_BLEND_OP_MAX) {
773 blend_state.Entry[i].SourceAlphaBlendFactor = BLENDFACTOR_ONE;
774 blend_state.Entry[i].DestinationAlphaBlendFactor = BLENDFACTOR_ONE;
775 }
776 }
777
778 #if GEN_GEN >= 8
779 struct GENX(BLEND_STATE_ENTRY) *bs0 = &blend_state.Entry[0];
780 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_BLEND), blend) {
781 blend.AlphaToCoverageEnable = blend_state.AlphaToCoverageEnable;
782 blend.HasWriteableRT = has_writeable_rt;
783 blend.ColorBufferBlendEnable = bs0->ColorBufferBlendEnable;
784 blend.SourceAlphaBlendFactor = bs0->SourceAlphaBlendFactor;
785 blend.DestinationAlphaBlendFactor = bs0->DestinationAlphaBlendFactor;
786 blend.SourceBlendFactor = bs0->SourceBlendFactor;
787 blend.DestinationBlendFactor = bs0->DestinationBlendFactor;
788 blend.AlphaTestEnable = false;
789 blend.IndependentAlphaBlendEnable =
790 blend_state.IndependentAlphaBlendEnable;
791 }
792 #else
793 (void)has_writeable_rt;
794 #endif
795
796 GENX(BLEND_STATE_pack)(NULL, pipeline->blend_state.map, &blend_state);
797 if (!device->info.has_llc)
798 anv_state_clflush(pipeline->blend_state);
799
800 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_BLEND_STATE_POINTERS), bsp) {
801 bsp.BlendStatePointer = pipeline->blend_state.offset;
802 #if GEN_GEN >= 8
803 bsp.BlendStatePointerValid = true;
804 #endif
805 }
806 }
807
808 static void
809 emit_3dstate_clip(struct anv_pipeline *pipeline,
810 const VkPipelineViewportStateCreateInfo *vp_info,
811 const VkPipelineRasterizationStateCreateInfo *rs_info)
812 {
813 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
814 (void) wm_prog_data;
815 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_CLIP), clip) {
816 clip.ClipEnable = true;
817 clip.EarlyCullEnable = true;
818 clip.APIMode = APIMODE_D3D,
819 clip.ViewportXYClipTestEnable = true;
820
821 clip.ClipMode = CLIPMODE_NORMAL;
822
823 clip.TriangleStripListProvokingVertexSelect = 0;
824 clip.LineStripListProvokingVertexSelect = 0;
825 clip.TriangleFanProvokingVertexSelect = 1;
826
827 clip.MinimumPointWidth = 0.125;
828 clip.MaximumPointWidth = 255.875;
829 clip.MaximumVPIndex = (vp_info ? vp_info->viewportCount : 1) - 1;
830
831 #if GEN_GEN == 7
832 clip.FrontWinding = vk_to_gen_front_face[rs_info->frontFace];
833 clip.CullMode = vk_to_gen_cullmode[rs_info->cullMode];
834 clip.ViewportZClipTestEnable = !pipeline->depth_clamp_enable;
835 #else
836 clip.NonPerspectiveBarycentricEnable = wm_prog_data ?
837 (wm_prog_data->barycentric_interp_modes & 0x38) != 0 : 0;
838 #endif
839 }
840 }
841
842 static void
843 emit_3dstate_streamout(struct anv_pipeline *pipeline,
844 const VkPipelineRasterizationStateCreateInfo *rs_info)
845 {
846 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_STREAMOUT), so) {
847 so.RenderingDisable = rs_info->rasterizerDiscardEnable;
848 }
849 }
850
851 static inline uint32_t
852 get_sampler_count(const struct anv_shader_bin *bin)
853 {
854 return DIV_ROUND_UP(bin->bind_map.sampler_count, 4);
855 }
856
857 static inline uint32_t
858 get_binding_table_entry_count(const struct anv_shader_bin *bin)
859 {
860 return DIV_ROUND_UP(bin->bind_map.surface_count, 32);
861 }
862
863 static inline struct anv_address
864 get_scratch_address(struct anv_pipeline *pipeline,
865 gl_shader_stage stage,
866 const struct anv_shader_bin *bin)
867 {
868 return (struct anv_address) {
869 .bo = anv_scratch_pool_alloc(pipeline->device,
870 &pipeline->device->scratch_pool,
871 stage, bin->prog_data->total_scratch),
872 .offset = 0,
873 };
874 }
875
876 static inline uint32_t
877 get_scratch_space(const struct anv_shader_bin *bin)
878 {
879 return ffs(bin->prog_data->total_scratch / 2048);
880 }
881
882 static inline uint32_t
883 get_urb_output_offset()
884 {
885 /* Skip the VUE header and position slots */
886 return 1;
887 }
888
889 static inline uint32_t
890 get_urb_output_length(const struct anv_shader_bin *bin)
891 {
892 const struct brw_vue_prog_data *prog_data =
893 (const struct brw_vue_prog_data *)bin->prog_data;
894
895 return (prog_data->vue_map.num_slots + 1) / 2 - get_urb_output_offset();
896 }
897
898 static void
899 emit_3dstate_vs(struct anv_pipeline *pipeline)
900 {
901 const struct gen_device_info *devinfo = &pipeline->device->info;
902 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
903 const struct anv_shader_bin *vs_bin =
904 pipeline->shaders[MESA_SHADER_VERTEX];
905
906 assert(anv_pipeline_has_stage(pipeline, MESA_SHADER_VERTEX));
907
908 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VS), vs) {
909 vs.FunctionEnable = true;
910 vs.StatisticsEnable = true;
911 vs.KernelStartPointer = vs_bin->kernel.offset;
912 #if GEN_GEN >= 8
913 vs.SIMD8DispatchEnable =
914 vs_prog_data->base.dispatch_mode == DISPATCH_MODE_SIMD8;
915 #endif
916
917 assert(!vs_prog_data->base.base.use_alt_mode);
918 vs.SingleVertexDispatch = false;
919 vs.VectorMaskEnable = false;
920 vs.SamplerCount = get_sampler_count(vs_bin);
921 vs.BindingTableEntryCount = get_binding_table_entry_count(vs_bin);
922 vs.FloatingPointMode = IEEE754;
923 vs.IllegalOpcodeExceptionEnable = false;
924 vs.SoftwareExceptionEnable = false;
925 vs.MaximumNumberofThreads = devinfo->max_vs_threads - 1;
926 vs.VertexCacheDisable = false;
927
928 vs.VertexURBEntryReadLength = vs_prog_data->base.urb_read_length;
929 vs.VertexURBEntryReadOffset = 0;
930 vs.DispatchGRFStartRegisterForURBData =
931 vs_prog_data->base.base.dispatch_grf_start_reg;
932
933 #if GEN_GEN >= 8
934 vs.VertexURBEntryOutputReadOffset = get_urb_output_offset();
935 vs.VertexURBEntryOutputLength = get_urb_output_length(vs_bin);
936
937 /* TODO */
938 vs.UserClipDistanceClipTestEnableBitmask = 0;
939 vs.UserClipDistanceCullTestEnableBitmask = 0;
940 #endif
941
942 vs.PerThreadScratchSpace = get_scratch_space(vs_bin);
943 vs.ScratchSpaceBasePointer =
944 get_scratch_address(pipeline, MESA_SHADER_VERTEX, vs_bin);
945 }
946 }
947
948 static void
949 emit_3dstate_gs(struct anv_pipeline *pipeline)
950 {
951 const struct gen_device_info *devinfo = &pipeline->device->info;
952 const struct anv_shader_bin *gs_bin =
953 pipeline->shaders[MESA_SHADER_GEOMETRY];
954
955 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_GEOMETRY)) {
956 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs);
957 return;
958 }
959
960 const struct brw_gs_prog_data *gs_prog_data = get_gs_prog_data(pipeline);
961
962 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_GS), gs) {
963 gs.FunctionEnable = true;
964 gs.StatisticsEnable = true;
965 gs.KernelStartPointer = gs_bin->kernel.offset;
966 gs.DispatchMode = gs_prog_data->base.dispatch_mode;
967
968 gs.SingleProgramFlow = false;
969 gs.VectorMaskEnable = false;
970 gs.SamplerCount = get_sampler_count(gs_bin);
971 gs.BindingTableEntryCount = get_binding_table_entry_count(gs_bin);
972 gs.IncludeVertexHandles = gs_prog_data->base.include_vue_handles;
973 gs.IncludePrimitiveID = gs_prog_data->include_primitive_id;
974
975 if (GEN_GEN == 8) {
976 /* Broadwell is weird. It needs us to divide by 2. */
977 gs.MaximumNumberofThreads = devinfo->max_gs_threads / 2 - 1;
978 } else {
979 gs.MaximumNumberofThreads = devinfo->max_gs_threads - 1;
980 }
981
982 gs.OutputVertexSize = gs_prog_data->output_vertex_size_hwords * 2 - 1;
983 gs.OutputTopology = gs_prog_data->output_topology;
984 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
985 gs.ControlDataFormat = gs_prog_data->control_data_format;
986 gs.ControlDataHeaderSize = gs_prog_data->control_data_header_size_hwords;
987 gs.InstanceControl = MAX2(gs_prog_data->invocations, 1) - 1;
988 #if GEN_GEN >= 8 || GEN_IS_HASWELL
989 gs.ReorderMode = TRAILING;
990 #else
991 gs.ReorderEnable = true;
992 #endif
993
994 #if GEN_GEN >= 8
995 gs.ExpectedVertexCount = gs_prog_data->vertices_in;
996 gs.StaticOutput = gs_prog_data->static_vertex_count >= 0;
997 gs.StaticOutputVertexCount = gs_prog_data->static_vertex_count >= 0 ?
998 gs_prog_data->static_vertex_count : 0;
999 #endif
1000
1001 gs.VertexURBEntryReadOffset = 0;
1002 gs.VertexURBEntryReadLength = gs_prog_data->base.urb_read_length;
1003 gs.DispatchGRFStartRegisterForURBData =
1004 gs_prog_data->base.base.dispatch_grf_start_reg;
1005
1006 #if GEN_GEN >= 8
1007 gs.VertexURBEntryOutputReadOffset = get_urb_output_offset();
1008 gs.VertexURBEntryOutputLength = get_urb_output_length(gs_bin);
1009
1010 /* TODO */
1011 gs.UserClipDistanceClipTestEnableBitmask = 0;
1012 gs.UserClipDistanceCullTestEnableBitmask = 0;
1013 #endif
1014
1015 gs.PerThreadScratchSpace = get_scratch_space(gs_bin);
1016 gs.ScratchSpaceBasePointer =
1017 get_scratch_address(pipeline, MESA_SHADER_GEOMETRY, gs_bin);
1018 }
1019 }
1020
1021 static void
1022 emit_3dstate_wm(struct anv_pipeline *pipeline,
1023 const VkPipelineMultisampleStateCreateInfo *multisample)
1024 {
1025 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1026
1027 MAYBE_UNUSED uint32_t samples =
1028 multisample ? multisample->rasterizationSamples : 1;
1029
1030 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_WM), wm) {
1031 wm.StatisticsEnable = true;
1032 wm.LineEndCapAntialiasingRegionWidth = _05pixels;
1033 wm.LineAntialiasingRegionWidth = _10pixels;
1034 wm.PointRasterizationRule = RASTRULE_UPPER_RIGHT;
1035
1036 if (anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1037 if (wm_prog_data->early_fragment_tests) {
1038 wm.EarlyDepthStencilControl = EDSC_PREPS;
1039 } else if (wm_prog_data->has_side_effects) {
1040 wm.EarlyDepthStencilControl = EDSC_PSEXEC;
1041 } else {
1042 wm.EarlyDepthStencilControl = EDSC_NORMAL;
1043 }
1044
1045 wm.BarycentricInterpolationMode =
1046 wm_prog_data->barycentric_interp_modes;
1047
1048 #if GEN_GEN < 8
1049 /* FIXME: This needs a lot more work, cf gen7 upload_wm_state(). */
1050 wm.ThreadDispatchEnable = true;
1051
1052 wm.PixelShaderKillsPixel = wm_prog_data->uses_kill;
1053 wm.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1054 wm.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1055 wm.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1056 wm.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1057
1058 if (samples > 1) {
1059 wm.MultisampleRasterizationMode = MSRASTMODE_ON_PATTERN;
1060 if (wm_prog_data->persample_dispatch) {
1061 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1062 } else {
1063 wm.MultisampleDispatchMode = MSDISPMODE_PERPIXEL;
1064 }
1065 } else {
1066 wm.MultisampleRasterizationMode = MSRASTMODE_OFF_PIXEL;
1067 wm.MultisampleDispatchMode = MSDISPMODE_PERSAMPLE;
1068 }
1069 #endif
1070 }
1071 }
1072 }
1073
1074 static void
1075 emit_3dstate_ps(struct anv_pipeline *pipeline)
1076 {
1077 MAYBE_UNUSED const struct gen_device_info *devinfo = &pipeline->device->info;
1078 const struct anv_shader_bin *fs_bin =
1079 pipeline->shaders[MESA_SHADER_FRAGMENT];
1080
1081 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1082 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1083 #if GEN_GEN == 7
1084 /* Even if no fragments are ever dispatched, gen7 hardware hangs if
1085 * we don't at least set the maximum number of threads.
1086 */
1087 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1088 #endif
1089 }
1090 return;
1091 }
1092
1093 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1094
1095 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS), ps) {
1096 ps.KernelStartPointer0 = fs_bin->kernel.offset;
1097 ps.KernelStartPointer1 = 0;
1098 ps.KernelStartPointer2 = fs_bin->kernel.offset +
1099 wm_prog_data->prog_offset_2;
1100 ps._8PixelDispatchEnable = wm_prog_data->dispatch_8;
1101 ps._16PixelDispatchEnable = wm_prog_data->dispatch_16;
1102 ps._32PixelDispatchEnable = false;
1103
1104 ps.SingleProgramFlow = false;
1105 ps.VectorMaskEnable = true;
1106 ps.SamplerCount = get_sampler_count(fs_bin);
1107 ps.BindingTableEntryCount = get_binding_table_entry_count(fs_bin);
1108 ps.PushConstantEnable = wm_prog_data->base.nr_params > 0;
1109 ps.PositionXYOffsetSelect = wm_prog_data->uses_pos_offset ?
1110 POSOFFSET_SAMPLE: POSOFFSET_NONE;
1111 #if GEN_GEN < 8
1112 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1113 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1114 ps.DualSourceBlendEnable = wm_prog_data->dual_src_blend;
1115 #endif
1116
1117 #if GEN_IS_HASWELL
1118 /* Haswell requires the sample mask to be set in this packet as well
1119 * as in 3DSTATE_SAMPLE_MASK; the values should match.
1120 */
1121 ps.SampleMask = 0xff;
1122 #endif
1123
1124 #if GEN_GEN >= 9
1125 ps.MaximumNumberofThreadsPerPSD = 64 - 1;
1126 #elif GEN_GEN >= 8
1127 ps.MaximumNumberofThreadsPerPSD = 64 - 2;
1128 #else
1129 ps.MaximumNumberofThreads = devinfo->max_wm_threads - 1;
1130 #endif
1131
1132 ps.DispatchGRFStartRegisterForConstantSetupData0 =
1133 wm_prog_data->base.dispatch_grf_start_reg;
1134 ps.DispatchGRFStartRegisterForConstantSetupData1 = 0;
1135 ps.DispatchGRFStartRegisterForConstantSetupData2 =
1136 wm_prog_data->dispatch_grf_start_reg_2;
1137
1138 ps.PerThreadScratchSpace = get_scratch_space(fs_bin);
1139 ps.ScratchSpaceBasePointer =
1140 get_scratch_address(pipeline, MESA_SHADER_FRAGMENT, fs_bin);
1141 }
1142 }
1143
1144 #if GEN_GEN >= 8
1145 static void
1146 emit_3dstate_ps_extra(struct anv_pipeline *pipeline)
1147 {
1148 const struct brw_wm_prog_data *wm_prog_data = get_wm_prog_data(pipeline);
1149
1150 if (!anv_pipeline_has_stage(pipeline, MESA_SHADER_FRAGMENT)) {
1151 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps);
1152 return;
1153 }
1154
1155 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_PS_EXTRA), ps) {
1156 ps.PixelShaderValid = true;
1157 ps.AttributeEnable = wm_prog_data->num_varying_inputs > 0;
1158 ps.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
1159 ps.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
1160 ps.PixelShaderKillsPixel = wm_prog_data->uses_kill;
1161 ps.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
1162 ps.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
1163 ps.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
1164
1165 #if GEN_GEN >= 9
1166 ps.PixelShaderPullsBary = wm_prog_data->pulls_bary;
1167 ps.InputCoverageMaskState = wm_prog_data->uses_sample_mask ?
1168 ICMS_INNER_CONSERVATIVE : ICMS_NONE;
1169 #else
1170 ps.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
1171 #endif
1172 }
1173 }
1174
1175 static void
1176 emit_3dstate_vf_topology(struct anv_pipeline *pipeline)
1177 {
1178 anv_batch_emit(&pipeline->batch, GENX(3DSTATE_VF_TOPOLOGY), vft) {
1179 vft.PrimitiveTopologyType = pipeline->topology;
1180 }
1181 }
1182 #endif
1183
1184 static VkResult
1185 genX(graphics_pipeline_create)(
1186 VkDevice _device,
1187 struct anv_pipeline_cache * cache,
1188 const VkGraphicsPipelineCreateInfo* pCreateInfo,
1189 const VkAllocationCallbacks* pAllocator,
1190 VkPipeline* pPipeline)
1191 {
1192 ANV_FROM_HANDLE(anv_device, device, _device);
1193 ANV_FROM_HANDLE(anv_render_pass, pass, pCreateInfo->renderPass);
1194 struct anv_subpass *subpass = &pass->subpasses[pCreateInfo->subpass];
1195 struct anv_pipeline *pipeline;
1196 VkResult result;
1197
1198 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO);
1199
1200 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1201 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1202 if (pipeline == NULL)
1203 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1204
1205 result = anv_pipeline_init(pipeline, device, cache,
1206 pCreateInfo, pAllocator);
1207 if (result != VK_SUCCESS) {
1208 vk_free2(&device->alloc, pAllocator, pipeline);
1209 return result;
1210 }
1211
1212 assert(pCreateInfo->pVertexInputState);
1213 emit_vertex_input(pipeline, pCreateInfo->pVertexInputState);
1214 assert(pCreateInfo->pRasterizationState);
1215 emit_rs_state(pipeline, pCreateInfo->pRasterizationState,
1216 pCreateInfo->pMultisampleState, pass, subpass);
1217 emit_ms_state(pipeline, pCreateInfo->pMultisampleState);
1218 emit_ds_state(pipeline, pCreateInfo->pDepthStencilState, pass, subpass);
1219 emit_cb_state(pipeline, pCreateInfo->pColorBlendState,
1220 pCreateInfo->pMultisampleState);
1221
1222 emit_urb_setup(pipeline);
1223
1224 emit_3dstate_clip(pipeline, pCreateInfo->pViewportState,
1225 pCreateInfo->pRasterizationState);
1226 emit_3dstate_streamout(pipeline, pCreateInfo->pRasterizationState);
1227
1228 #if 0
1229 /* From gen7_vs_state.c */
1230
1231 /**
1232 * From Graphics BSpec: 3D-Media-GPGPU Engine > 3D Pipeline Stages >
1233 * Geometry > Geometry Shader > State:
1234 *
1235 * "Note: Because of corruption in IVB:GT2, software needs to flush the
1236 * whole fixed function pipeline when the GS enable changes value in
1237 * the 3DSTATE_GS."
1238 *
1239 * The hardware architects have clarified that in this context "flush the
1240 * whole fixed function pipeline" means to emit a PIPE_CONTROL with the "CS
1241 * Stall" bit set.
1242 */
1243 if (!brw->is_haswell && !brw->is_baytrail)
1244 gen7_emit_vs_workaround_flush(brw);
1245 #endif
1246
1247 emit_3dstate_vs(pipeline);
1248 emit_3dstate_gs(pipeline);
1249 emit_3dstate_sbe(pipeline);
1250 emit_3dstate_wm(pipeline, pCreateInfo->pMultisampleState);
1251 emit_3dstate_ps(pipeline);
1252 #if GEN_GEN >= 8
1253 emit_3dstate_ps_extra(pipeline);
1254 emit_3dstate_vf_topology(pipeline);
1255 #endif
1256
1257 *pPipeline = anv_pipeline_to_handle(pipeline);
1258
1259 return VK_SUCCESS;
1260 }
1261
1262 static VkResult
1263 compute_pipeline_create(
1264 VkDevice _device,
1265 struct anv_pipeline_cache * cache,
1266 const VkComputePipelineCreateInfo* pCreateInfo,
1267 const VkAllocationCallbacks* pAllocator,
1268 VkPipeline* pPipeline)
1269 {
1270 ANV_FROM_HANDLE(anv_device, device, _device);
1271 const struct anv_physical_device *physical_device =
1272 &device->instance->physicalDevice;
1273 const struct gen_device_info *devinfo = &physical_device->info;
1274 struct anv_pipeline *pipeline;
1275 VkResult result;
1276
1277 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO);
1278
1279 pipeline = vk_alloc2(&device->alloc, pAllocator, sizeof(*pipeline), 8,
1280 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1281 if (pipeline == NULL)
1282 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1283
1284 pipeline->device = device;
1285 pipeline->layout = anv_pipeline_layout_from_handle(pCreateInfo->layout);
1286
1287 pipeline->blend_state.map = NULL;
1288
1289 result = anv_reloc_list_init(&pipeline->batch_relocs,
1290 pAllocator ? pAllocator : &device->alloc);
1291 if (result != VK_SUCCESS) {
1292 vk_free2(&device->alloc, pAllocator, pipeline);
1293 return result;
1294 }
1295 pipeline->batch.next = pipeline->batch.start = pipeline->batch_data;
1296 pipeline->batch.end = pipeline->batch.start + sizeof(pipeline->batch_data);
1297 pipeline->batch.relocs = &pipeline->batch_relocs;
1298
1299 /* When we free the pipeline, we detect stages based on the NULL status
1300 * of various prog_data pointers. Make them NULL by default.
1301 */
1302 memset(pipeline->shaders, 0, sizeof(pipeline->shaders));
1303
1304 pipeline->active_stages = 0;
1305
1306 pipeline->needs_data_cache = false;
1307
1308 assert(pCreateInfo->stage.stage == VK_SHADER_STAGE_COMPUTE_BIT);
1309 ANV_FROM_HANDLE(anv_shader_module, module, pCreateInfo->stage.module);
1310 result = anv_pipeline_compile_cs(pipeline, cache, pCreateInfo, module,
1311 pCreateInfo->stage.pName,
1312 pCreateInfo->stage.pSpecializationInfo);
1313 if (result != VK_SUCCESS) {
1314 vk_free2(&device->alloc, pAllocator, pipeline);
1315 return result;
1316 }
1317
1318 const struct brw_cs_prog_data *cs_prog_data = get_cs_prog_data(pipeline);
1319
1320 anv_pipeline_setup_l3_config(pipeline, cs_prog_data->base.total_shared > 0);
1321
1322 uint32_t group_size = cs_prog_data->local_size[0] *
1323 cs_prog_data->local_size[1] * cs_prog_data->local_size[2];
1324 uint32_t remainder = group_size & (cs_prog_data->simd_size - 1);
1325
1326 if (remainder > 0)
1327 pipeline->cs_right_mask = ~0u >> (32 - remainder);
1328 else
1329 pipeline->cs_right_mask = ~0u >> (32 - cs_prog_data->simd_size);
1330
1331 const uint32_t vfe_curbe_allocation =
1332 ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
1333 cs_prog_data->push.cross_thread.regs, 2);
1334
1335 const uint32_t subslices = MAX2(physical_device->subslice_total, 1);
1336
1337 const struct anv_shader_bin *cs_bin =
1338 pipeline->shaders[MESA_SHADER_COMPUTE];
1339
1340 anv_batch_emit(&pipeline->batch, GENX(MEDIA_VFE_STATE), vfe) {
1341 #if GEN_GEN > 7
1342 vfe.StackSize = 0;
1343 #else
1344 vfe.GPGPUMode = true;
1345 #endif
1346 vfe.MaximumNumberofThreads =
1347 devinfo->max_cs_threads * subslices - 1;
1348 vfe.NumberofURBEntries = GEN_GEN <= 7 ? 0 : 2;
1349 vfe.ResetGatewayTimer = true;
1350 #if GEN_GEN <= 8
1351 vfe.BypassGatewayControl = true;
1352 #endif
1353 vfe.URBEntryAllocationSize = GEN_GEN <= 7 ? 0 : 2;
1354 vfe.CURBEAllocationSize = vfe_curbe_allocation;
1355
1356 vfe.PerThreadScratchSpace = get_scratch_space(cs_bin);
1357 vfe.ScratchSpaceBasePointer =
1358 get_scratch_address(pipeline, MESA_SHADER_COMPUTE, cs_bin);
1359 }
1360
1361 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
1362 .KernelStartPointer = cs_bin->kernel.offset,
1363
1364 .SamplerCount = get_sampler_count(cs_bin),
1365 .BindingTableEntryCount = get_binding_table_entry_count(cs_bin),
1366 .BarrierEnable = cs_prog_data->uses_barrier,
1367 .SharedLocalMemorySize =
1368 encode_slm_size(GEN_GEN, cs_prog_data->base.total_shared),
1369
1370 #if !GEN_IS_HASWELL
1371 .ConstantURBEntryReadOffset = 0,
1372 #endif
1373 .ConstantURBEntryReadLength = cs_prog_data->push.per_thread.regs,
1374 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1375 .CrossThreadConstantDataReadLength =
1376 cs_prog_data->push.cross_thread.regs,
1377 #endif
1378
1379 .NumberofThreadsinGPGPUThreadGroup = cs_prog_data->threads,
1380 };
1381 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL,
1382 pipeline->interface_descriptor_data,
1383 &desc);
1384
1385 *pPipeline = anv_pipeline_to_handle(pipeline);
1386
1387 return VK_SUCCESS;
1388 }
1389
1390 VkResult genX(CreateGraphicsPipelines)(
1391 VkDevice _device,
1392 VkPipelineCache pipelineCache,
1393 uint32_t count,
1394 const VkGraphicsPipelineCreateInfo* pCreateInfos,
1395 const VkAllocationCallbacks* pAllocator,
1396 VkPipeline* pPipelines)
1397 {
1398 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1399
1400 VkResult result = VK_SUCCESS;
1401
1402 unsigned i = 0;
1403 for (; i < count; i++) {
1404 result = genX(graphics_pipeline_create)(_device,
1405 pipeline_cache,
1406 &pCreateInfos[i],
1407 pAllocator, &pPipelines[i]);
1408 if (result != VK_SUCCESS) {
1409 for (unsigned j = 0; j < i; j++) {
1410 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1411 }
1412
1413 return result;
1414 }
1415 }
1416
1417 return VK_SUCCESS;
1418 }
1419
1420 VkResult genX(CreateComputePipelines)(
1421 VkDevice _device,
1422 VkPipelineCache pipelineCache,
1423 uint32_t count,
1424 const VkComputePipelineCreateInfo* pCreateInfos,
1425 const VkAllocationCallbacks* pAllocator,
1426 VkPipeline* pPipelines)
1427 {
1428 ANV_FROM_HANDLE(anv_pipeline_cache, pipeline_cache, pipelineCache);
1429
1430 VkResult result = VK_SUCCESS;
1431
1432 unsigned i = 0;
1433 for (; i < count; i++) {
1434 result = compute_pipeline_create(_device, pipeline_cache,
1435 &pCreateInfos[i],
1436 pAllocator, &pPipelines[i]);
1437 if (result != VK_SUCCESS) {
1438 for (unsigned j = 0; j < i; j++) {
1439 anv_DestroyPipeline(_device, pPipelines[j], pAllocator);
1440 }
1441
1442 return result;
1443 }
1444 }
1445
1446 return VK_SUCCESS;
1447 }