anv: Implement Gen12 workaround for non pipelined state
[mesa.git] / src / intel / vulkan / genX_cmd_buffer.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 <assert.h>
25 #include <stdbool.h>
26
27 #include "anv_private.h"
28 #include "vk_format_info.h"
29 #include "vk_util.h"
30 #include "util/fast_idiv_by_const.h"
31
32 #include "common/gen_aux_map.h"
33 #include "common/gen_l3_config.h"
34 #include "genxml/gen_macros.h"
35 #include "genxml/genX_pack.h"
36
37 /* We reserve GPR 14 and 15 for conditional rendering */
38 #define GEN_MI_BUILDER_NUM_ALLOC_GPRS 14
39 #define __gen_get_batch_dwords anv_batch_emit_dwords
40 #define __gen_address_offset anv_address_add
41 #include "common/gen_mi_builder.h"
42
43 static void
44 emit_lri(struct anv_batch *batch, uint32_t reg, uint32_t imm)
45 {
46 anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
47 lri.RegisterOffset = reg;
48 lri.DataDWord = imm;
49 }
50 }
51
52 void
53 genX(cmd_buffer_emit_state_base_address)(struct anv_cmd_buffer *cmd_buffer)
54 {
55 struct anv_device *device = cmd_buffer->device;
56 uint32_t mocs = device->isl_dev.mocs.internal;
57
58 /* If we are emitting a new state base address we probably need to re-emit
59 * binding tables.
60 */
61 cmd_buffer->state.descriptors_dirty |= ~0;
62
63 /* Emit a render target cache flush.
64 *
65 * This isn't documented anywhere in the PRM. However, it seems to be
66 * necessary prior to changing the surface state base adress. Without
67 * this, we get GPU hangs when using multi-level command buffers which
68 * clear depth, reset state base address, and then go render stuff.
69 */
70 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
71 pc.DCFlushEnable = true;
72 pc.RenderTargetCacheFlushEnable = true;
73 pc.CommandStreamerStallEnable = true;
74 #if GEN_GEN >= 12
75 pc.TileCacheFlushEnable = true;
76 #endif
77 }
78
79 #if GEN_GEN == 12
80 /* GEN:BUG:1607854226:
81 *
82 * Workaround the non pipelined state not applying in MEDIA/GPGPU pipeline
83 * mode by putting the pipeline temporarily in 3D mode.
84 */
85 if (cmd_buffer->state.current_pipeline != _3D) {
86 anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
87 ps.MaskBits = 3;
88 ps.PipelineSelection = _3D;
89 }
90 }
91 #endif
92
93 anv_batch_emit(&cmd_buffer->batch, GENX(STATE_BASE_ADDRESS), sba) {
94 sba.GeneralStateBaseAddress = (struct anv_address) { NULL, 0 };
95 sba.GeneralStateMOCS = mocs;
96 sba.GeneralStateBaseAddressModifyEnable = true;
97
98 sba.StatelessDataPortAccessMOCS = mocs;
99
100 sba.SurfaceStateBaseAddress =
101 anv_cmd_buffer_surface_base_address(cmd_buffer);
102 sba.SurfaceStateMOCS = mocs;
103 sba.SurfaceStateBaseAddressModifyEnable = true;
104
105 sba.DynamicStateBaseAddress =
106 (struct anv_address) { device->dynamic_state_pool.block_pool.bo, 0 };
107 sba.DynamicStateMOCS = mocs;
108 sba.DynamicStateBaseAddressModifyEnable = true;
109
110 sba.IndirectObjectBaseAddress = (struct anv_address) { NULL, 0 };
111 sba.IndirectObjectMOCS = mocs;
112 sba.IndirectObjectBaseAddressModifyEnable = true;
113
114 sba.InstructionBaseAddress =
115 (struct anv_address) { device->instruction_state_pool.block_pool.bo, 0 };
116 sba.InstructionMOCS = mocs;
117 sba.InstructionBaseAddressModifyEnable = true;
118
119 # if (GEN_GEN >= 8)
120 /* Broadwell requires that we specify a buffer size for a bunch of
121 * these fields. However, since we will be growing the BO's live, we
122 * just set them all to the maximum.
123 */
124 sba.GeneralStateBufferSize = 0xfffff;
125 sba.GeneralStateBufferSizeModifyEnable = true;
126 sba.DynamicStateBufferSize = 0xfffff;
127 sba.DynamicStateBufferSizeModifyEnable = true;
128 sba.IndirectObjectBufferSize = 0xfffff;
129 sba.IndirectObjectBufferSizeModifyEnable = true;
130 sba.InstructionBufferSize = 0xfffff;
131 sba.InstructionBuffersizeModifyEnable = true;
132 # else
133 /* On gen7, we have upper bounds instead. According to the docs,
134 * setting an upper bound of zero means that no bounds checking is
135 * performed so, in theory, we should be able to leave them zero.
136 * However, border color is broken and the GPU bounds-checks anyway.
137 * To avoid this and other potential problems, we may as well set it
138 * for everything.
139 */
140 sba.GeneralStateAccessUpperBound =
141 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
142 sba.GeneralStateAccessUpperBoundModifyEnable = true;
143 sba.DynamicStateAccessUpperBound =
144 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
145 sba.DynamicStateAccessUpperBoundModifyEnable = true;
146 sba.InstructionAccessUpperBound =
147 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
148 sba.InstructionAccessUpperBoundModifyEnable = true;
149 # endif
150 # if (GEN_GEN >= 9)
151 if (cmd_buffer->device->instance->physicalDevice.use_softpin) {
152 sba.BindlessSurfaceStateBaseAddress = (struct anv_address) {
153 .bo = device->surface_state_pool.block_pool.bo,
154 .offset = 0,
155 };
156 sba.BindlessSurfaceStateSize = (1 << 20) - 1;
157 } else {
158 sba.BindlessSurfaceStateBaseAddress = ANV_NULL_ADDRESS;
159 sba.BindlessSurfaceStateSize = 0;
160 }
161 sba.BindlessSurfaceStateMOCS = mocs;
162 sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
163 # endif
164 # if (GEN_GEN >= 10)
165 sba.BindlessSamplerStateBaseAddress = (struct anv_address) { NULL, 0 };
166 sba.BindlessSamplerStateMOCS = mocs;
167 sba.BindlessSamplerStateBaseAddressModifyEnable = true;
168 sba.BindlessSamplerStateBufferSize = 0;
169 # endif
170 }
171
172 #if GEN_GEN == 12
173 /* GEN:BUG:1607854226:
174 *
175 * Put the pipeline back into compute mode.
176 */
177 if (cmd_buffer->state.current_pipeline != _3D) {
178 anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
179 ps.MaskBits = 3;
180 ps.PipelineSelection = cmd_buffer->state.current_pipeline;
181 }
182 }
183 #endif
184
185 /* After re-setting the surface state base address, we have to do some
186 * cache flusing so that the sampler engine will pick up the new
187 * SURFACE_STATE objects and binding tables. From the Broadwell PRM,
188 * Shared Function > 3D Sampler > State > State Caching (page 96):
189 *
190 * Coherency with system memory in the state cache, like the texture
191 * cache is handled partially by software. It is expected that the
192 * command stream or shader will issue Cache Flush operation or
193 * Cache_Flush sampler message to ensure that the L1 cache remains
194 * coherent with system memory.
195 *
196 * [...]
197 *
198 * Whenever the value of the Dynamic_State_Base_Addr,
199 * Surface_State_Base_Addr are altered, the L1 state cache must be
200 * invalidated to ensure the new surface or sampler state is fetched
201 * from system memory.
202 *
203 * The PIPE_CONTROL command has a "State Cache Invalidation Enable" bit
204 * which, according the PIPE_CONTROL instruction documentation in the
205 * Broadwell PRM:
206 *
207 * Setting this bit is independent of any other bit in this packet.
208 * This bit controls the invalidation of the L1 and L2 state caches
209 * at the top of the pipe i.e. at the parsing time.
210 *
211 * Unfortunately, experimentation seems to indicate that state cache
212 * invalidation through a PIPE_CONTROL does nothing whatsoever in
213 * regards to surface state and binding tables. In stead, it seems that
214 * invalidating the texture cache is what is actually needed.
215 *
216 * XXX: As far as we have been able to determine through
217 * experimentation, shows that flush the texture cache appears to be
218 * sufficient. The theory here is that all of the sampling/rendering
219 * units cache the binding table in the texture cache. However, we have
220 * yet to be able to actually confirm this.
221 */
222 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
223 pc.TextureCacheInvalidationEnable = true;
224 pc.ConstantCacheInvalidationEnable = true;
225 pc.StateCacheInvalidationEnable = true;
226 }
227 }
228
229 static void
230 add_surface_reloc(struct anv_cmd_buffer *cmd_buffer,
231 struct anv_state state, struct anv_address addr)
232 {
233 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
234
235 VkResult result =
236 anv_reloc_list_add(&cmd_buffer->surface_relocs, &cmd_buffer->pool->alloc,
237 state.offset + isl_dev->ss.addr_offset,
238 addr.bo, addr.offset, NULL);
239 if (result != VK_SUCCESS)
240 anv_batch_set_error(&cmd_buffer->batch, result);
241 }
242
243 static void
244 add_surface_state_relocs(struct anv_cmd_buffer *cmd_buffer,
245 struct anv_surface_state state)
246 {
247 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
248
249 assert(!anv_address_is_null(state.address));
250 add_surface_reloc(cmd_buffer, state.state, state.address);
251
252 if (!anv_address_is_null(state.aux_address)) {
253 VkResult result =
254 anv_reloc_list_add(&cmd_buffer->surface_relocs,
255 &cmd_buffer->pool->alloc,
256 state.state.offset + isl_dev->ss.aux_addr_offset,
257 state.aux_address.bo,
258 state.aux_address.offset,
259 NULL);
260 if (result != VK_SUCCESS)
261 anv_batch_set_error(&cmd_buffer->batch, result);
262 }
263
264 if (!anv_address_is_null(state.clear_address)) {
265 VkResult result =
266 anv_reloc_list_add(&cmd_buffer->surface_relocs,
267 &cmd_buffer->pool->alloc,
268 state.state.offset +
269 isl_dev->ss.clear_color_state_offset,
270 state.clear_address.bo,
271 state.clear_address.offset,
272 NULL);
273 if (result != VK_SUCCESS)
274 anv_batch_set_error(&cmd_buffer->batch, result);
275 }
276 }
277
278 static void
279 color_attachment_compute_aux_usage(struct anv_device * device,
280 struct anv_cmd_state * cmd_state,
281 uint32_t att, VkRect2D render_area,
282 union isl_color_value *fast_clear_color)
283 {
284 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
285 struct anv_image_view *iview = cmd_state->attachments[att].image_view;
286
287 assert(iview->n_planes == 1);
288
289 if (iview->planes[0].isl.base_array_layer >=
290 anv_image_aux_layers(iview->image, VK_IMAGE_ASPECT_COLOR_BIT,
291 iview->planes[0].isl.base_level)) {
292 /* There is no aux buffer which corresponds to the level and layer(s)
293 * being accessed.
294 */
295 att_state->aux_usage = ISL_AUX_USAGE_NONE;
296 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
297 att_state->fast_clear = false;
298 return;
299 }
300
301 att_state->aux_usage =
302 anv_layout_to_aux_usage(&device->info, iview->image,
303 VK_IMAGE_ASPECT_COLOR_BIT,
304 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
305
306 /* If we don't have aux, then we should have returned early in the layer
307 * check above. If we got here, we must have something.
308 */
309 assert(att_state->aux_usage != ISL_AUX_USAGE_NONE);
310
311 if (att_state->aux_usage == ISL_AUX_USAGE_CCS_E ||
312 att_state->aux_usage == ISL_AUX_USAGE_MCS) {
313 att_state->input_aux_usage = att_state->aux_usage;
314 } else {
315 /* From the Sky Lake PRM, RENDER_SURFACE_STATE::AuxiliarySurfaceMode:
316 *
317 * "If Number of Multisamples is MULTISAMPLECOUNT_1, AUX_CCS_D
318 * setting is only allowed if Surface Format supported for Fast
319 * Clear. In addition, if the surface is bound to the sampling
320 * engine, Surface Format must be supported for Render Target
321 * Compression for surfaces bound to the sampling engine."
322 *
323 * In other words, we can only sample from a fast-cleared image if it
324 * also supports color compression.
325 */
326 if (isl_format_supports_ccs_e(&device->info, iview->planes[0].isl.format) &&
327 isl_format_supports_ccs_d(&device->info, iview->planes[0].isl.format)) {
328 att_state->input_aux_usage = ISL_AUX_USAGE_CCS_D;
329
330 /* While fast-clear resolves and partial resolves are fairly cheap in the
331 * case where you render to most of the pixels, full resolves are not
332 * because they potentially involve reading and writing the entire
333 * framebuffer. If we can't texture with CCS_E, we should leave it off and
334 * limit ourselves to fast clears.
335 */
336 if (cmd_state->pass->attachments[att].first_subpass_layout ==
337 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
338 anv_perf_warn(device->instance, iview->image,
339 "Not temporarily enabling CCS_E.");
340 }
341 } else {
342 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
343 }
344 }
345
346 assert(iview->image->planes[0].aux_surface.isl.usage &
347 (ISL_SURF_USAGE_CCS_BIT | ISL_SURF_USAGE_MCS_BIT));
348
349 union isl_color_value clear_color = {};
350 anv_clear_color_from_att_state(&clear_color, att_state, iview);
351
352 att_state->clear_color_is_zero_one =
353 isl_color_value_is_zero_one(clear_color, iview->planes[0].isl.format);
354 att_state->clear_color_is_zero =
355 isl_color_value_is_zero(clear_color, iview->planes[0].isl.format);
356
357 if (att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
358 /* Start by getting the fast clear type. We use the first subpass
359 * layout here because we don't want to fast-clear if the first subpass
360 * to use the attachment can't handle fast-clears.
361 */
362 enum anv_fast_clear_type fast_clear_type =
363 anv_layout_to_fast_clear_type(&device->info, iview->image,
364 VK_IMAGE_ASPECT_COLOR_BIT,
365 cmd_state->pass->attachments[att].first_subpass_layout);
366 switch (fast_clear_type) {
367 case ANV_FAST_CLEAR_NONE:
368 att_state->fast_clear = false;
369 break;
370 case ANV_FAST_CLEAR_DEFAULT_VALUE:
371 att_state->fast_clear = att_state->clear_color_is_zero;
372 break;
373 case ANV_FAST_CLEAR_ANY:
374 att_state->fast_clear = true;
375 break;
376 }
377
378 /* Potentially, we could do partial fast-clears but doing so has crazy
379 * alignment restrictions. It's easier to just restrict to full size
380 * fast clears for now.
381 */
382 if (render_area.offset.x != 0 ||
383 render_area.offset.y != 0 ||
384 render_area.extent.width != iview->extent.width ||
385 render_area.extent.height != iview->extent.height)
386 att_state->fast_clear = false;
387
388 /* On Broadwell and earlier, we can only handle 0/1 clear colors */
389 if (GEN_GEN <= 8 && !att_state->clear_color_is_zero_one)
390 att_state->fast_clear = false;
391
392 /* We only allow fast clears to the first slice of an image (level 0,
393 * layer 0) and only for the entire slice. This guarantees us that, at
394 * any given time, there is only one clear color on any given image at
395 * any given time. At the time of our testing (Jan 17, 2018), there
396 * were no known applications which would benefit from fast-clearing
397 * more than just the first slice.
398 */
399 if (att_state->fast_clear &&
400 (iview->planes[0].isl.base_level > 0 ||
401 iview->planes[0].isl.base_array_layer > 0)) {
402 anv_perf_warn(device->instance, iview->image,
403 "Rendering with multi-lod or multi-layer framebuffer "
404 "with LOAD_OP_LOAD and baseMipLevel > 0 or "
405 "baseArrayLayer > 0. Not fast clearing.");
406 att_state->fast_clear = false;
407 } else if (att_state->fast_clear && cmd_state->framebuffer->layers > 1) {
408 anv_perf_warn(device->instance, iview->image,
409 "Rendering to a multi-layer framebuffer with "
410 "LOAD_OP_CLEAR. Only fast-clearing the first slice");
411 }
412
413 if (att_state->fast_clear)
414 *fast_clear_color = clear_color;
415 } else {
416 att_state->fast_clear = false;
417 }
418 }
419
420 static void
421 depth_stencil_attachment_compute_aux_usage(struct anv_device *device,
422 struct anv_cmd_state *cmd_state,
423 uint32_t att, VkRect2D render_area)
424 {
425 struct anv_render_pass_attachment *pass_att =
426 &cmd_state->pass->attachments[att];
427 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
428 struct anv_image_view *iview = cmd_state->attachments[att].image_view;
429
430 /* These will be initialized after the first subpass transition. */
431 att_state->aux_usage = ISL_AUX_USAGE_NONE;
432 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
433
434 if (GEN_GEN == 7) {
435 /* We don't do any HiZ or depth fast-clears on gen7 yet */
436 att_state->fast_clear = false;
437 return;
438 }
439
440 if (!(att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
441 /* If we're just clearing stencil, we can always HiZ clear */
442 att_state->fast_clear = true;
443 return;
444 }
445
446 /* Default to false for now */
447 att_state->fast_clear = false;
448
449 /* We must have depth in order to have HiZ */
450 if (!(iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
451 return;
452
453 const enum isl_aux_usage first_subpass_aux_usage =
454 anv_layout_to_aux_usage(&device->info, iview->image,
455 VK_IMAGE_ASPECT_DEPTH_BIT,
456 pass_att->first_subpass_layout);
457 if (!blorp_can_hiz_clear_depth(&device->info,
458 &iview->image->planes[0].surface.isl,
459 first_subpass_aux_usage,
460 iview->planes[0].isl.base_level,
461 iview->planes[0].isl.base_array_layer,
462 render_area.offset.x,
463 render_area.offset.y,
464 render_area.offset.x +
465 render_area.extent.width,
466 render_area.offset.y +
467 render_area.extent.height))
468 return;
469
470 if (att_state->clear_value.depthStencil.depth != ANV_HZ_FC_VAL)
471 return;
472
473 if (GEN_GEN == 8 && anv_can_sample_with_hiz(&device->info, iview->image)) {
474 /* Only gen9+ supports returning ANV_HZ_FC_VAL when sampling a
475 * fast-cleared portion of a HiZ buffer. Testing has revealed that Gen8
476 * only supports returning 0.0f. Gens prior to gen8 do not support this
477 * feature at all.
478 */
479 return;
480 }
481
482 /* If we got here, then we can fast clear */
483 att_state->fast_clear = true;
484 }
485
486 static bool
487 need_input_attachment_state(const struct anv_render_pass_attachment *att)
488 {
489 if (!(att->usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT))
490 return false;
491
492 /* We only allocate input attachment states for color surfaces. Compression
493 * is not yet enabled for depth textures and stencil doesn't allow
494 * compression so we can just use the texture surface state from the view.
495 */
496 return vk_format_is_color(att->format);
497 }
498
499 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
500 * the initial layout is undefined, the HiZ buffer and depth buffer will
501 * represent the same data at the end of this operation.
502 */
503 static void
504 transition_depth_buffer(struct anv_cmd_buffer *cmd_buffer,
505 const struct anv_image *image,
506 VkImageLayout initial_layout,
507 VkImageLayout final_layout)
508 {
509 const bool hiz_enabled = ISL_AUX_USAGE_HIZ ==
510 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
511 VK_IMAGE_ASPECT_DEPTH_BIT, initial_layout);
512 const bool enable_hiz = ISL_AUX_USAGE_HIZ ==
513 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
514 VK_IMAGE_ASPECT_DEPTH_BIT, final_layout);
515
516 enum isl_aux_op hiz_op;
517 if (hiz_enabled && !enable_hiz) {
518 hiz_op = ISL_AUX_OP_FULL_RESOLVE;
519 } else if (!hiz_enabled && enable_hiz) {
520 hiz_op = ISL_AUX_OP_AMBIGUATE;
521 } else {
522 assert(hiz_enabled == enable_hiz);
523 /* If the same buffer will be used, no resolves are necessary. */
524 hiz_op = ISL_AUX_OP_NONE;
525 }
526
527 if (hiz_op != ISL_AUX_OP_NONE)
528 anv_image_hiz_op(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
529 0, 0, 1, hiz_op);
530 }
531
532 static inline bool
533 vk_image_layout_stencil_write_optimal(VkImageLayout layout)
534 {
535 return layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
536 layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
537 layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR;
538 }
539
540 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
541 * the initial layout is undefined, the HiZ buffer and depth buffer will
542 * represent the same data at the end of this operation.
543 */
544 static void
545 transition_stencil_buffer(struct anv_cmd_buffer *cmd_buffer,
546 const struct anv_image *image,
547 uint32_t base_level, uint32_t level_count,
548 uint32_t base_layer, uint32_t layer_count,
549 VkImageLayout initial_layout,
550 VkImageLayout final_layout)
551 {
552 #if GEN_GEN == 7
553 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
554 VK_IMAGE_ASPECT_STENCIL_BIT);
555
556 /* On gen7, we have to store a texturable version of the stencil buffer in
557 * a shadow whenever VK_IMAGE_USAGE_SAMPLED_BIT is set and copy back and
558 * forth at strategic points. Stencil writes are only allowed in following
559 * layouts:
560 *
561 * - VK_IMAGE_LAYOUT_GENERAL
562 * - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
563 * - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
564 * - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL
565 * - VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR
566 *
567 * For general, we have no nice opportunity to transition so we do the copy
568 * to the shadow unconditionally at the end of the subpass. For transfer
569 * destinations, we can update it as part of the transfer op. For the other
570 * layouts, we delay the copy until a transition into some other layout.
571 */
572 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
573 vk_image_layout_stencil_write_optimal(initial_layout) &&
574 !vk_image_layout_stencil_write_optimal(final_layout)) {
575 anv_image_copy_to_shadow(cmd_buffer, image,
576 VK_IMAGE_ASPECT_STENCIL_BIT,
577 base_level, level_count,
578 base_layer, layer_count);
579 }
580 #endif /* GEN_GEN == 7 */
581 }
582
583 #define MI_PREDICATE_SRC0 0x2400
584 #define MI_PREDICATE_SRC1 0x2408
585 #define MI_PREDICATE_RESULT 0x2418
586
587 static void
588 set_image_compressed_bit(struct anv_cmd_buffer *cmd_buffer,
589 const struct anv_image *image,
590 VkImageAspectFlagBits aspect,
591 uint32_t level,
592 uint32_t base_layer, uint32_t layer_count,
593 bool compressed)
594 {
595 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
596
597 /* We only have compression tracking for CCS_E */
598 if (image->planes[plane].aux_usage != ISL_AUX_USAGE_CCS_E)
599 return;
600
601 for (uint32_t a = 0; a < layer_count; a++) {
602 uint32_t layer = base_layer + a;
603 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
604 sdi.Address = anv_image_get_compression_state_addr(cmd_buffer->device,
605 image, aspect,
606 level, layer);
607 sdi.ImmediateData = compressed ? UINT32_MAX : 0;
608 }
609 }
610 }
611
612 static void
613 set_image_fast_clear_state(struct anv_cmd_buffer *cmd_buffer,
614 const struct anv_image *image,
615 VkImageAspectFlagBits aspect,
616 enum anv_fast_clear_type fast_clear)
617 {
618 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
619 sdi.Address = anv_image_get_fast_clear_type_addr(cmd_buffer->device,
620 image, aspect);
621 sdi.ImmediateData = fast_clear;
622 }
623
624 /* Whenever we have fast-clear, we consider that slice to be compressed.
625 * This makes building predicates much easier.
626 */
627 if (fast_clear != ANV_FAST_CLEAR_NONE)
628 set_image_compressed_bit(cmd_buffer, image, aspect, 0, 0, 1, true);
629 }
630
631 /* This is only really practical on haswell and above because it requires
632 * MI math in order to get it correct.
633 */
634 #if GEN_GEN >= 8 || GEN_IS_HASWELL
635 static void
636 anv_cmd_compute_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
637 const struct anv_image *image,
638 VkImageAspectFlagBits aspect,
639 uint32_t level, uint32_t array_layer,
640 enum isl_aux_op resolve_op,
641 enum anv_fast_clear_type fast_clear_supported)
642 {
643 struct gen_mi_builder b;
644 gen_mi_builder_init(&b, &cmd_buffer->batch);
645
646 const struct gen_mi_value fast_clear_type =
647 gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
648 image, aspect));
649
650 if (resolve_op == ISL_AUX_OP_FULL_RESOLVE) {
651 /* In this case, we're doing a full resolve which means we want the
652 * resolve to happen if any compression (including fast-clears) is
653 * present.
654 *
655 * In order to simplify the logic a bit, we make the assumption that,
656 * if the first slice has been fast-cleared, it is also marked as
657 * compressed. See also set_image_fast_clear_state.
658 */
659 const struct gen_mi_value compression_state =
660 gen_mi_mem32(anv_image_get_compression_state_addr(cmd_buffer->device,
661 image, aspect,
662 level, array_layer));
663 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
664 compression_state);
665 gen_mi_store(&b, compression_state, gen_mi_imm(0));
666
667 if (level == 0 && array_layer == 0) {
668 /* If the predicate is true, we want to write 0 to the fast clear type
669 * and, if it's false, leave it alone. We can do this by writing
670 *
671 * clear_type = clear_type & ~predicate;
672 */
673 struct gen_mi_value new_fast_clear_type =
674 gen_mi_iand(&b, fast_clear_type,
675 gen_mi_inot(&b, gen_mi_reg64(MI_PREDICATE_SRC0)));
676 gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
677 }
678 } else if (level == 0 && array_layer == 0) {
679 /* In this case, we are doing a partial resolve to get rid of fast-clear
680 * colors. We don't care about the compression state but we do care
681 * about how much fast clear is allowed by the final layout.
682 */
683 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
684 assert(fast_clear_supported < ANV_FAST_CLEAR_ANY);
685
686 /* We need to compute (fast_clear_supported < image->fast_clear) */
687 struct gen_mi_value pred =
688 gen_mi_ult(&b, gen_mi_imm(fast_clear_supported), fast_clear_type);
689 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
690 gen_mi_value_ref(&b, pred));
691
692 /* If the predicate is true, we want to write 0 to the fast clear type
693 * and, if it's false, leave it alone. We can do this by writing
694 *
695 * clear_type = clear_type & ~predicate;
696 */
697 struct gen_mi_value new_fast_clear_type =
698 gen_mi_iand(&b, fast_clear_type, gen_mi_inot(&b, pred));
699 gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
700 } else {
701 /* In this case, we're trying to do a partial resolve on a slice that
702 * doesn't have clear color. There's nothing to do.
703 */
704 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
705 return;
706 }
707
708 /* Set src1 to 0 and use a != condition */
709 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
710
711 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
712 mip.LoadOperation = LOAD_LOADINV;
713 mip.CombineOperation = COMBINE_SET;
714 mip.CompareOperation = COMPARE_SRCS_EQUAL;
715 }
716 }
717 #endif /* GEN_GEN >= 8 || GEN_IS_HASWELL */
718
719 #if GEN_GEN <= 8
720 static void
721 anv_cmd_simple_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
722 const struct anv_image *image,
723 VkImageAspectFlagBits aspect,
724 uint32_t level, uint32_t array_layer,
725 enum isl_aux_op resolve_op,
726 enum anv_fast_clear_type fast_clear_supported)
727 {
728 struct gen_mi_builder b;
729 gen_mi_builder_init(&b, &cmd_buffer->batch);
730
731 struct gen_mi_value fast_clear_type_mem =
732 gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
733 image, aspect));
734
735 /* This only works for partial resolves and only when the clear color is
736 * all or nothing. On the upside, this emits less command streamer code
737 * and works on Ivybridge and Bay Trail.
738 */
739 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
740 assert(fast_clear_supported != ANV_FAST_CLEAR_ANY);
741
742 /* We don't support fast clears on anything other than the first slice. */
743 if (level > 0 || array_layer > 0)
744 return;
745
746 /* On gen8, we don't have a concept of default clear colors because we
747 * can't sample from CCS surfaces. It's enough to just load the fast clear
748 * state into the predicate register.
749 */
750 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), fast_clear_type_mem);
751 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
752 gen_mi_store(&b, fast_clear_type_mem, gen_mi_imm(0));
753
754 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
755 mip.LoadOperation = LOAD_LOADINV;
756 mip.CombineOperation = COMBINE_SET;
757 mip.CompareOperation = COMPARE_SRCS_EQUAL;
758 }
759 }
760 #endif /* GEN_GEN <= 8 */
761
762 static void
763 anv_cmd_predicated_ccs_resolve(struct anv_cmd_buffer *cmd_buffer,
764 const struct anv_image *image,
765 enum isl_format format,
766 VkImageAspectFlagBits aspect,
767 uint32_t level, uint32_t array_layer,
768 enum isl_aux_op resolve_op,
769 enum anv_fast_clear_type fast_clear_supported)
770 {
771 const uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
772
773 #if GEN_GEN >= 9
774 anv_cmd_compute_resolve_predicate(cmd_buffer, image,
775 aspect, level, array_layer,
776 resolve_op, fast_clear_supported);
777 #else /* GEN_GEN <= 8 */
778 anv_cmd_simple_resolve_predicate(cmd_buffer, image,
779 aspect, level, array_layer,
780 resolve_op, fast_clear_supported);
781 #endif
782
783 /* CCS_D only supports full resolves and BLORP will assert on us if we try
784 * to do a partial resolve on a CCS_D surface.
785 */
786 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
787 image->planes[plane].aux_usage == ISL_AUX_USAGE_NONE)
788 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
789
790 anv_image_ccs_op(cmd_buffer, image, format, aspect, level,
791 array_layer, 1, resolve_op, NULL, true);
792 }
793
794 static void
795 anv_cmd_predicated_mcs_resolve(struct anv_cmd_buffer *cmd_buffer,
796 const struct anv_image *image,
797 enum isl_format format,
798 VkImageAspectFlagBits aspect,
799 uint32_t array_layer,
800 enum isl_aux_op resolve_op,
801 enum anv_fast_clear_type fast_clear_supported)
802 {
803 assert(aspect == VK_IMAGE_ASPECT_COLOR_BIT);
804 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
805
806 #if GEN_GEN >= 8 || GEN_IS_HASWELL
807 anv_cmd_compute_resolve_predicate(cmd_buffer, image,
808 aspect, 0, array_layer,
809 resolve_op, fast_clear_supported);
810
811 anv_image_mcs_op(cmd_buffer, image, format, aspect,
812 array_layer, 1, resolve_op, NULL, true);
813 #else
814 unreachable("MCS resolves are unsupported on Ivybridge and Bay Trail");
815 #endif
816 }
817
818 void
819 genX(cmd_buffer_mark_image_written)(struct anv_cmd_buffer *cmd_buffer,
820 const struct anv_image *image,
821 VkImageAspectFlagBits aspect,
822 enum isl_aux_usage aux_usage,
823 uint32_t level,
824 uint32_t base_layer,
825 uint32_t layer_count)
826 {
827 /* The aspect must be exactly one of the image aspects. */
828 assert(util_bitcount(aspect) == 1 && (aspect & image->aspects));
829
830 /* The only compression types with more than just fast-clears are MCS,
831 * CCS_E, and HiZ. With HiZ we just trust the layout and don't actually
832 * track the current fast-clear and compression state. This leaves us
833 * with just MCS and CCS_E.
834 */
835 if (aux_usage != ISL_AUX_USAGE_CCS_E &&
836 aux_usage != ISL_AUX_USAGE_MCS)
837 return;
838
839 set_image_compressed_bit(cmd_buffer, image, aspect,
840 level, base_layer, layer_count, true);
841 }
842
843 static void
844 init_fast_clear_color(struct anv_cmd_buffer *cmd_buffer,
845 const struct anv_image *image,
846 VkImageAspectFlagBits aspect)
847 {
848 assert(cmd_buffer && image);
849 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
850
851 set_image_fast_clear_state(cmd_buffer, image, aspect,
852 ANV_FAST_CLEAR_NONE);
853
854 /* Initialize the struct fields that are accessed for fast-clears so that
855 * the HW restrictions on the field values are satisfied.
856 */
857 struct anv_address addr =
858 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
859
860 if (GEN_GEN >= 9) {
861 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
862 const unsigned num_dwords = GEN_GEN >= 10 ?
863 isl_dev->ss.clear_color_state_size / 4 :
864 isl_dev->ss.clear_value_size / 4;
865 for (unsigned i = 0; i < num_dwords; i++) {
866 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
867 sdi.Address = addr;
868 sdi.Address.offset += i * 4;
869 sdi.ImmediateData = 0;
870 }
871 }
872 } else {
873 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
874 sdi.Address = addr;
875 if (GEN_GEN >= 8 || GEN_IS_HASWELL) {
876 /* Pre-SKL, the dword containing the clear values also contains
877 * other fields, so we need to initialize those fields to match the
878 * values that would be in a color attachment.
879 */
880 sdi.ImmediateData = ISL_CHANNEL_SELECT_RED << 25 |
881 ISL_CHANNEL_SELECT_GREEN << 22 |
882 ISL_CHANNEL_SELECT_BLUE << 19 |
883 ISL_CHANNEL_SELECT_ALPHA << 16;
884 } else if (GEN_GEN == 7) {
885 /* On IVB, the dword containing the clear values also contains
886 * other fields that must be zero or can be zero.
887 */
888 sdi.ImmediateData = 0;
889 }
890 }
891 }
892 }
893
894 /* Copy the fast-clear value dword(s) between a surface state object and an
895 * image's fast clear state buffer.
896 */
897 static void
898 genX(copy_fast_clear_dwords)(struct anv_cmd_buffer *cmd_buffer,
899 struct anv_state surface_state,
900 const struct anv_image *image,
901 VkImageAspectFlagBits aspect,
902 bool copy_from_surface_state)
903 {
904 assert(cmd_buffer && image);
905 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
906
907 struct anv_address ss_clear_addr = {
908 .bo = cmd_buffer->device->surface_state_pool.block_pool.bo,
909 .offset = surface_state.offset +
910 cmd_buffer->device->isl_dev.ss.clear_value_offset,
911 };
912 const struct anv_address entry_addr =
913 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
914 unsigned copy_size = cmd_buffer->device->isl_dev.ss.clear_value_size;
915
916 #if GEN_GEN == 7
917 /* On gen7, the combination of commands used here(MI_LOAD_REGISTER_MEM
918 * and MI_STORE_REGISTER_MEM) can cause GPU hangs if any rendering is
919 * in-flight when they are issued even if the memory touched is not
920 * currently active for rendering. The weird bit is that it is not the
921 * MI_LOAD/STORE_REGISTER_MEM commands which hang but rather the in-flight
922 * rendering hangs such that the next stalling command after the
923 * MI_LOAD/STORE_REGISTER_MEM commands will catch the hang.
924 *
925 * It is unclear exactly why this hang occurs. Both MI commands come with
926 * warnings about the 3D pipeline but that doesn't seem to fully explain
927 * it. My (Jason's) best theory is that it has something to do with the
928 * fact that we're using a GPU state register as our temporary and that
929 * something with reading/writing it is causing problems.
930 *
931 * In order to work around this issue, we emit a PIPE_CONTROL with the
932 * command streamer stall bit set.
933 */
934 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
935 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
936 #endif
937
938 struct gen_mi_builder b;
939 gen_mi_builder_init(&b, &cmd_buffer->batch);
940
941 if (copy_from_surface_state) {
942 gen_mi_memcpy(&b, entry_addr, ss_clear_addr, copy_size);
943 } else {
944 gen_mi_memcpy(&b, ss_clear_addr, entry_addr, copy_size);
945
946 /* Updating a surface state object may require that the state cache be
947 * invalidated. From the SKL PRM, Shared Functions -> State -> State
948 * Caching:
949 *
950 * Whenever the RENDER_SURFACE_STATE object in memory pointed to by
951 * the Binding Table Pointer (BTP) and Binding Table Index (BTI) is
952 * modified [...], the L1 state cache must be invalidated to ensure
953 * the new surface or sampler state is fetched from system memory.
954 *
955 * In testing, SKL doesn't actually seem to need this, but HSW does.
956 */
957 cmd_buffer->state.pending_pipe_bits |=
958 ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
959 }
960 }
961
962 /**
963 * @brief Transitions a color buffer from one layout to another.
964 *
965 * See section 6.1.1. Image Layout Transitions of the Vulkan 1.0.50 spec for
966 * more information.
967 *
968 * @param level_count VK_REMAINING_MIP_LEVELS isn't supported.
969 * @param layer_count VK_REMAINING_ARRAY_LAYERS isn't supported. For 3D images,
970 * this represents the maximum layers to transition at each
971 * specified miplevel.
972 */
973 static void
974 transition_color_buffer(struct anv_cmd_buffer *cmd_buffer,
975 const struct anv_image *image,
976 VkImageAspectFlagBits aspect,
977 const uint32_t base_level, uint32_t level_count,
978 uint32_t base_layer, uint32_t layer_count,
979 VkImageLayout initial_layout,
980 VkImageLayout final_layout)
981 {
982 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
983 /* Validate the inputs. */
984 assert(cmd_buffer);
985 assert(image && image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
986 /* These values aren't supported for simplicity's sake. */
987 assert(level_count != VK_REMAINING_MIP_LEVELS &&
988 layer_count != VK_REMAINING_ARRAY_LAYERS);
989 /* Ensure the subresource range is valid. */
990 UNUSED uint64_t last_level_num = base_level + level_count;
991 const uint32_t max_depth = anv_minify(image->extent.depth, base_level);
992 UNUSED const uint32_t image_layers = MAX2(image->array_size, max_depth);
993 assert((uint64_t)base_layer + layer_count <= image_layers);
994 assert(last_level_num <= image->levels);
995 /* The spec disallows these final layouts. */
996 assert(final_layout != VK_IMAGE_LAYOUT_UNDEFINED &&
997 final_layout != VK_IMAGE_LAYOUT_PREINITIALIZED);
998
999 /* No work is necessary if the layout stays the same or if this subresource
1000 * range lacks auxiliary data.
1001 */
1002 if (initial_layout == final_layout)
1003 return;
1004
1005 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
1006
1007 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
1008 final_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
1009 /* This surface is a linear compressed image with a tiled shadow surface
1010 * for texturing. The client is about to use it in READ_ONLY_OPTIMAL so
1011 * we need to ensure the shadow copy is up-to-date.
1012 */
1013 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1014 assert(image->planes[plane].surface.isl.tiling == ISL_TILING_LINEAR);
1015 assert(image->planes[plane].shadow_surface.isl.tiling != ISL_TILING_LINEAR);
1016 assert(isl_format_is_compressed(image->planes[plane].surface.isl.format));
1017 assert(plane == 0);
1018 anv_image_copy_to_shadow(cmd_buffer, image,
1019 VK_IMAGE_ASPECT_COLOR_BIT,
1020 base_level, level_count,
1021 base_layer, layer_count);
1022 }
1023
1024 if (base_layer >= anv_image_aux_layers(image, aspect, base_level))
1025 return;
1026
1027 assert(image->tiling == VK_IMAGE_TILING_OPTIMAL);
1028
1029 if (initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ||
1030 initial_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
1031 /* A subresource in the undefined layout may have been aliased and
1032 * populated with any arrangement of bits. Therefore, we must initialize
1033 * the related aux buffer and clear buffer entry with desirable values.
1034 * An initial layout of PREINITIALIZED is the same as UNDEFINED for
1035 * images with VK_IMAGE_TILING_OPTIMAL.
1036 *
1037 * Initialize the relevant clear buffer entries.
1038 */
1039 if (base_level == 0 && base_layer == 0)
1040 init_fast_clear_color(cmd_buffer, image, aspect);
1041
1042 /* Initialize the aux buffers to enable correct rendering. In order to
1043 * ensure that things such as storage images work correctly, aux buffers
1044 * need to be initialized to valid data.
1045 *
1046 * Having an aux buffer with invalid data is a problem for two reasons:
1047 *
1048 * 1) Having an invalid value in the buffer can confuse the hardware.
1049 * For instance, with CCS_E on SKL, a two-bit CCS value of 2 is
1050 * invalid and leads to the hardware doing strange things. It
1051 * doesn't hang as far as we can tell but rendering corruption can
1052 * occur.
1053 *
1054 * 2) If this transition is into the GENERAL layout and we then use the
1055 * image as a storage image, then we must have the aux buffer in the
1056 * pass-through state so that, if we then go to texture from the
1057 * image, we get the results of our storage image writes and not the
1058 * fast clear color or other random data.
1059 *
1060 * For CCS both of the problems above are real demonstrable issues. In
1061 * that case, the only thing we can do is to perform an ambiguate to
1062 * transition the aux surface into the pass-through state.
1063 *
1064 * For MCS, (2) is never an issue because we don't support multisampled
1065 * storage images. In theory, issue (1) is a problem with MCS but we've
1066 * never seen it in the wild. For 4x and 16x, all bit patters could, in
1067 * theory, be interpreted as something but we don't know that all bit
1068 * patterns are actually valid. For 2x and 8x, you could easily end up
1069 * with the MCS referring to an invalid plane because not all bits of
1070 * the MCS value are actually used. Even though we've never seen issues
1071 * in the wild, it's best to play it safe and initialize the MCS. We
1072 * can use a fast-clear for MCS because we only ever touch from render
1073 * and texture (no image load store).
1074 */
1075 if (image->samples == 1) {
1076 for (uint32_t l = 0; l < level_count; l++) {
1077 const uint32_t level = base_level + l;
1078
1079 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1080 if (base_layer >= aux_layers)
1081 break; /* We will only get fewer layers as level increases */
1082 uint32_t level_layer_count =
1083 MIN2(layer_count, aux_layers - base_layer);
1084
1085 anv_image_ccs_op(cmd_buffer, image,
1086 image->planes[plane].surface.isl.format,
1087 aspect, level, base_layer, level_layer_count,
1088 ISL_AUX_OP_AMBIGUATE, NULL, false);
1089
1090 if (image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_E) {
1091 set_image_compressed_bit(cmd_buffer, image, aspect,
1092 level, base_layer, level_layer_count,
1093 false);
1094 }
1095 }
1096 } else {
1097 if (image->samples == 4 || image->samples == 16) {
1098 anv_perf_warn(cmd_buffer->device->instance, image,
1099 "Doing a potentially unnecessary fast-clear to "
1100 "define an MCS buffer.");
1101 }
1102
1103 assert(base_level == 0 && level_count == 1);
1104 anv_image_mcs_op(cmd_buffer, image,
1105 image->planes[plane].surface.isl.format,
1106 aspect, base_layer, layer_count,
1107 ISL_AUX_OP_FAST_CLEAR, NULL, false);
1108 }
1109 return;
1110 }
1111
1112 const enum isl_aux_usage initial_aux_usage =
1113 anv_layout_to_aux_usage(devinfo, image, aspect, initial_layout);
1114 const enum isl_aux_usage final_aux_usage =
1115 anv_layout_to_aux_usage(devinfo, image, aspect, final_layout);
1116
1117 /* The current code assumes that there is no mixing of CCS_E and CCS_D.
1118 * We can handle transitions between CCS_D/E to and from NONE. What we
1119 * don't yet handle is switching between CCS_E and CCS_D within a given
1120 * image. Doing so in a performant way requires more detailed aux state
1121 * tracking such as what is done in i965. For now, just assume that we
1122 * only have one type of compression.
1123 */
1124 assert(initial_aux_usage == ISL_AUX_USAGE_NONE ||
1125 final_aux_usage == ISL_AUX_USAGE_NONE ||
1126 initial_aux_usage == final_aux_usage);
1127
1128 /* If initial aux usage is NONE, there is nothing to resolve */
1129 if (initial_aux_usage == ISL_AUX_USAGE_NONE)
1130 return;
1131
1132 enum isl_aux_op resolve_op = ISL_AUX_OP_NONE;
1133
1134 /* If the initial layout supports more fast clear than the final layout
1135 * then we need at least a partial resolve.
1136 */
1137 const enum anv_fast_clear_type initial_fast_clear =
1138 anv_layout_to_fast_clear_type(devinfo, image, aspect, initial_layout);
1139 const enum anv_fast_clear_type final_fast_clear =
1140 anv_layout_to_fast_clear_type(devinfo, image, aspect, final_layout);
1141 if (final_fast_clear < initial_fast_clear)
1142 resolve_op = ISL_AUX_OP_PARTIAL_RESOLVE;
1143
1144 if (initial_aux_usage == ISL_AUX_USAGE_CCS_E &&
1145 final_aux_usage != ISL_AUX_USAGE_CCS_E)
1146 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
1147
1148 if (resolve_op == ISL_AUX_OP_NONE)
1149 return;
1150
1151 /* Perform a resolve to synchronize data between the main and aux buffer.
1152 * Before we begin, we must satisfy the cache flushing requirement specified
1153 * in the Sky Lake PRM Vol. 7, "MCS Buffer for Render Target(s)":
1154 *
1155 * Any transition from any value in {Clear, Render, Resolve} to a
1156 * different value in {Clear, Render, Resolve} requires end of pipe
1157 * synchronization.
1158 *
1159 * We perform a flush of the write cache before and after the clear and
1160 * resolve operations to meet this requirement.
1161 *
1162 * Unlike other drawing, fast clear operations are not properly
1163 * synchronized. The first PIPE_CONTROL here likely ensures that the
1164 * contents of the previous render or clear hit the render target before we
1165 * resolve and the second likely ensures that the resolve is complete before
1166 * we do any more rendering or clearing.
1167 */
1168 cmd_buffer->state.pending_pipe_bits |=
1169 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1170
1171 for (uint32_t l = 0; l < level_count; l++) {
1172 uint32_t level = base_level + l;
1173
1174 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1175 if (base_layer >= aux_layers)
1176 break; /* We will only get fewer layers as level increases */
1177 uint32_t level_layer_count =
1178 MIN2(layer_count, aux_layers - base_layer);
1179
1180 for (uint32_t a = 0; a < level_layer_count; a++) {
1181 uint32_t array_layer = base_layer + a;
1182 if (image->samples == 1) {
1183 anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
1184 image->planes[plane].surface.isl.format,
1185 aspect, level, array_layer, resolve_op,
1186 final_fast_clear);
1187 } else {
1188 /* We only support fast-clear on the first layer so partial
1189 * resolves should not be used on other layers as they will use
1190 * the clear color stored in memory that is only valid for layer0.
1191 */
1192 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
1193 array_layer != 0)
1194 continue;
1195
1196 anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
1197 image->planes[plane].surface.isl.format,
1198 aspect, array_layer, resolve_op,
1199 final_fast_clear);
1200 }
1201 }
1202 }
1203
1204 cmd_buffer->state.pending_pipe_bits |=
1205 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1206 }
1207
1208 /**
1209 * Setup anv_cmd_state::attachments for vkCmdBeginRenderPass.
1210 */
1211 static VkResult
1212 genX(cmd_buffer_setup_attachments)(struct anv_cmd_buffer *cmd_buffer,
1213 struct anv_render_pass *pass,
1214 const VkRenderPassBeginInfo *begin)
1215 {
1216 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
1217 struct anv_cmd_state *state = &cmd_buffer->state;
1218 struct anv_framebuffer *framebuffer = cmd_buffer->state.framebuffer;
1219
1220 vk_free(&cmd_buffer->pool->alloc, state->attachments);
1221
1222 if (pass->attachment_count > 0) {
1223 state->attachments = vk_alloc(&cmd_buffer->pool->alloc,
1224 pass->attachment_count *
1225 sizeof(state->attachments[0]),
1226 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1227 if (state->attachments == NULL) {
1228 /* Propagate VK_ERROR_OUT_OF_HOST_MEMORY to vkEndCommandBuffer */
1229 return anv_batch_set_error(&cmd_buffer->batch,
1230 VK_ERROR_OUT_OF_HOST_MEMORY);
1231 }
1232 } else {
1233 state->attachments = NULL;
1234 }
1235
1236 /* Reserve one for the NULL state. */
1237 unsigned num_states = 1;
1238 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1239 if (vk_format_is_color(pass->attachments[i].format))
1240 num_states++;
1241
1242 if (need_input_attachment_state(&pass->attachments[i]))
1243 num_states++;
1244 }
1245
1246 const uint32_t ss_stride = align_u32(isl_dev->ss.size, isl_dev->ss.align);
1247 state->render_pass_states =
1248 anv_state_stream_alloc(&cmd_buffer->surface_state_stream,
1249 num_states * ss_stride, isl_dev->ss.align);
1250
1251 struct anv_state next_state = state->render_pass_states;
1252 next_state.alloc_size = isl_dev->ss.size;
1253
1254 state->null_surface_state = next_state;
1255 next_state.offset += ss_stride;
1256 next_state.map += ss_stride;
1257
1258 const VkRenderPassAttachmentBeginInfoKHR *begin_attachment =
1259 vk_find_struct_const(begin, RENDER_PASS_ATTACHMENT_BEGIN_INFO_KHR);
1260
1261 if (begin && !begin_attachment)
1262 assert(pass->attachment_count == framebuffer->attachment_count);
1263
1264 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1265 if (vk_format_is_color(pass->attachments[i].format)) {
1266 state->attachments[i].color.state = next_state;
1267 next_state.offset += ss_stride;
1268 next_state.map += ss_stride;
1269 }
1270
1271 if (need_input_attachment_state(&pass->attachments[i])) {
1272 state->attachments[i].input.state = next_state;
1273 next_state.offset += ss_stride;
1274 next_state.map += ss_stride;
1275 }
1276
1277 if (begin_attachment && begin_attachment->attachmentCount != 0) {
1278 assert(begin_attachment->attachmentCount == pass->attachment_count);
1279 ANV_FROM_HANDLE(anv_image_view, iview, begin_attachment->pAttachments[i]);
1280 cmd_buffer->state.attachments[i].image_view = iview;
1281 } else if (framebuffer && i < framebuffer->attachment_count) {
1282 cmd_buffer->state.attachments[i].image_view = framebuffer->attachments[i];
1283 }
1284 }
1285 assert(next_state.offset == state->render_pass_states.offset +
1286 state->render_pass_states.alloc_size);
1287
1288 if (begin) {
1289 isl_null_fill_state(isl_dev, state->null_surface_state.map,
1290 isl_extent3d(framebuffer->width,
1291 framebuffer->height,
1292 framebuffer->layers));
1293
1294 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1295 struct anv_render_pass_attachment *att = &pass->attachments[i];
1296 VkImageAspectFlags att_aspects = vk_format_aspects(att->format);
1297 VkImageAspectFlags clear_aspects = 0;
1298 VkImageAspectFlags load_aspects = 0;
1299
1300 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1301 /* color attachment */
1302 if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1303 clear_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1304 } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1305 load_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1306 }
1307 } else {
1308 /* depthstencil attachment */
1309 if (att_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
1310 if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1311 clear_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1312 } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1313 load_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1314 }
1315 }
1316 if (att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
1317 if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1318 clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1319 } else if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1320 load_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1321 }
1322 }
1323 }
1324
1325 state->attachments[i].current_layout = att->initial_layout;
1326 state->attachments[i].current_stencil_layout = att->stencil_initial_layout;
1327 state->attachments[i].pending_clear_aspects = clear_aspects;
1328 state->attachments[i].pending_load_aspects = load_aspects;
1329 if (clear_aspects)
1330 state->attachments[i].clear_value = begin->pClearValues[i];
1331
1332 struct anv_image_view *iview = cmd_buffer->state.attachments[i].image_view;
1333 anv_assert(iview->vk_format == att->format);
1334
1335 const uint32_t num_layers = iview->planes[0].isl.array_len;
1336 state->attachments[i].pending_clear_views = (1 << num_layers) - 1;
1337
1338 union isl_color_value clear_color = { .u32 = { 0, } };
1339 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1340 anv_assert(iview->n_planes == 1);
1341 assert(att_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1342 color_attachment_compute_aux_usage(cmd_buffer->device,
1343 state, i, begin->renderArea,
1344 &clear_color);
1345
1346 anv_image_fill_surface_state(cmd_buffer->device,
1347 iview->image,
1348 VK_IMAGE_ASPECT_COLOR_BIT,
1349 &iview->planes[0].isl,
1350 ISL_SURF_USAGE_RENDER_TARGET_BIT,
1351 state->attachments[i].aux_usage,
1352 &clear_color,
1353 0,
1354 &state->attachments[i].color,
1355 NULL);
1356
1357 add_surface_state_relocs(cmd_buffer, state->attachments[i].color);
1358 } else {
1359 depth_stencil_attachment_compute_aux_usage(cmd_buffer->device,
1360 state, i,
1361 begin->renderArea);
1362 }
1363
1364 if (need_input_attachment_state(&pass->attachments[i])) {
1365 anv_image_fill_surface_state(cmd_buffer->device,
1366 iview->image,
1367 VK_IMAGE_ASPECT_COLOR_BIT,
1368 &iview->planes[0].isl,
1369 ISL_SURF_USAGE_TEXTURE_BIT,
1370 state->attachments[i].input_aux_usage,
1371 &clear_color,
1372 0,
1373 &state->attachments[i].input,
1374 NULL);
1375
1376 add_surface_state_relocs(cmd_buffer, state->attachments[i].input);
1377 }
1378 }
1379 }
1380
1381 return VK_SUCCESS;
1382 }
1383
1384 VkResult
1385 genX(BeginCommandBuffer)(
1386 VkCommandBuffer commandBuffer,
1387 const VkCommandBufferBeginInfo* pBeginInfo)
1388 {
1389 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1390
1391 /* If this is the first vkBeginCommandBuffer, we must *initialize* the
1392 * command buffer's state. Otherwise, we must *reset* its state. In both
1393 * cases we reset it.
1394 *
1395 * From the Vulkan 1.0 spec:
1396 *
1397 * If a command buffer is in the executable state and the command buffer
1398 * was allocated from a command pool with the
1399 * VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, then
1400 * vkBeginCommandBuffer implicitly resets the command buffer, behaving
1401 * as if vkResetCommandBuffer had been called with
1402 * VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT not set. It then puts
1403 * the command buffer in the recording state.
1404 */
1405 anv_cmd_buffer_reset(cmd_buffer);
1406
1407 cmd_buffer->usage_flags = pBeginInfo->flags;
1408
1409 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY ||
1410 !(cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT));
1411
1412 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
1413
1414 /* We sometimes store vertex data in the dynamic state buffer for blorp
1415 * operations and our dynamic state stream may re-use data from previous
1416 * command buffers. In order to prevent stale cache data, we flush the VF
1417 * cache. We could do this on every blorp call but that's not really
1418 * needed as all of the data will get written by the CPU prior to the GPU
1419 * executing anything. The chances are fairly high that they will use
1420 * blorp at least once per primary command buffer so it shouldn't be
1421 * wasted.
1422 *
1423 * There is also a workaround on gen8 which requires us to invalidate the
1424 * VF cache occasionally. It's easier if we can assume we start with a
1425 * fresh cache (See also genX(cmd_buffer_set_binding_for_gen8_vb_flush).)
1426 */
1427 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1428
1429 /* We send an "Indirect State Pointers Disable" packet at
1430 * EndCommandBuffer, so all push contant packets are ignored during a
1431 * context restore. Documentation says after that command, we need to
1432 * emit push constants again before any rendering operation. So we
1433 * flag them dirty here to make sure they get emitted.
1434 */
1435 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1436
1437 VkResult result = VK_SUCCESS;
1438 if (cmd_buffer->usage_flags &
1439 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1440 assert(pBeginInfo->pInheritanceInfo);
1441 cmd_buffer->state.pass =
1442 anv_render_pass_from_handle(pBeginInfo->pInheritanceInfo->renderPass);
1443 cmd_buffer->state.subpass =
1444 &cmd_buffer->state.pass->subpasses[pBeginInfo->pInheritanceInfo->subpass];
1445
1446 /* This is optional in the inheritance info. */
1447 cmd_buffer->state.framebuffer =
1448 anv_framebuffer_from_handle(pBeginInfo->pInheritanceInfo->framebuffer);
1449
1450 result = genX(cmd_buffer_setup_attachments)(cmd_buffer,
1451 cmd_buffer->state.pass, NULL);
1452
1453 /* Record that HiZ is enabled if we can. */
1454 if (cmd_buffer->state.framebuffer) {
1455 const struct anv_image_view * const iview =
1456 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
1457
1458 if (iview) {
1459 VkImageLayout layout =
1460 cmd_buffer->state.subpass->depth_stencil_attachment->layout;
1461
1462 enum isl_aux_usage aux_usage =
1463 anv_layout_to_aux_usage(&cmd_buffer->device->info, iview->image,
1464 VK_IMAGE_ASPECT_DEPTH_BIT, layout);
1465
1466 cmd_buffer->state.hiz_enabled = aux_usage == ISL_AUX_USAGE_HIZ;
1467 }
1468 }
1469
1470 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
1471 }
1472
1473 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1474 if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
1475 const VkCommandBufferInheritanceConditionalRenderingInfoEXT *conditional_rendering_info =
1476 vk_find_struct_const(pBeginInfo->pInheritanceInfo->pNext, COMMAND_BUFFER_INHERITANCE_CONDITIONAL_RENDERING_INFO_EXT);
1477
1478 /* If secondary buffer supports conditional rendering
1479 * we should emit commands as if conditional rendering is enabled.
1480 */
1481 cmd_buffer->state.conditional_render_enabled =
1482 conditional_rendering_info && conditional_rendering_info->conditionalRenderingEnable;
1483 }
1484 #endif
1485
1486 return result;
1487 }
1488
1489 /* From the PRM, Volume 2a:
1490 *
1491 * "Indirect State Pointers Disable
1492 *
1493 * At the completion of the post-sync operation associated with this pipe
1494 * control packet, the indirect state pointers in the hardware are
1495 * considered invalid; the indirect pointers are not saved in the context.
1496 * If any new indirect state commands are executed in the command stream
1497 * while the pipe control is pending, the new indirect state commands are
1498 * preserved.
1499 *
1500 * [DevIVB+]: Using Invalidate State Pointer (ISP) only inhibits context
1501 * restoring of Push Constant (3DSTATE_CONSTANT_*) commands. Push Constant
1502 * commands are only considered as Indirect State Pointers. Once ISP is
1503 * issued in a context, SW must initialize by programming push constant
1504 * commands for all the shaders (at least to zero length) before attempting
1505 * any rendering operation for the same context."
1506 *
1507 * 3DSTATE_CONSTANT_* packets are restored during a context restore,
1508 * even though they point to a BO that has been already unreferenced at
1509 * the end of the previous batch buffer. This has been fine so far since
1510 * we are protected by these scratch page (every address not covered by
1511 * a BO should be pointing to the scratch page). But on CNL, it is
1512 * causing a GPU hang during context restore at the 3DSTATE_CONSTANT_*
1513 * instruction.
1514 *
1515 * The flag "Indirect State Pointers Disable" in PIPE_CONTROL tells the
1516 * hardware to ignore previous 3DSTATE_CONSTANT_* packets during a
1517 * context restore, so the mentioned hang doesn't happen. However,
1518 * software must program push constant commands for all stages prior to
1519 * rendering anything. So we flag them dirty in BeginCommandBuffer.
1520 *
1521 * Finally, we also make sure to stall at pixel scoreboard to make sure the
1522 * constants have been loaded into the EUs prior to disable the push constants
1523 * so that it doesn't hang a previous 3DPRIMITIVE.
1524 */
1525 static void
1526 emit_isp_disable(struct anv_cmd_buffer *cmd_buffer)
1527 {
1528 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1529 pc.StallAtPixelScoreboard = true;
1530 pc.CommandStreamerStallEnable = true;
1531 }
1532 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1533 pc.IndirectStatePointersDisable = true;
1534 pc.CommandStreamerStallEnable = true;
1535 }
1536 }
1537
1538 VkResult
1539 genX(EndCommandBuffer)(
1540 VkCommandBuffer commandBuffer)
1541 {
1542 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1543
1544 if (anv_batch_has_error(&cmd_buffer->batch))
1545 return cmd_buffer->batch.status;
1546
1547 /* We want every command buffer to start with the PMA fix in a known state,
1548 * so we disable it at the end of the command buffer.
1549 */
1550 genX(cmd_buffer_enable_pma_fix)(cmd_buffer, false);
1551
1552 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
1553
1554 emit_isp_disable(cmd_buffer);
1555
1556 anv_cmd_buffer_end_batch_buffer(cmd_buffer);
1557
1558 return VK_SUCCESS;
1559 }
1560
1561 void
1562 genX(CmdExecuteCommands)(
1563 VkCommandBuffer commandBuffer,
1564 uint32_t commandBufferCount,
1565 const VkCommandBuffer* pCmdBuffers)
1566 {
1567 ANV_FROM_HANDLE(anv_cmd_buffer, primary, commandBuffer);
1568
1569 assert(primary->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1570
1571 if (anv_batch_has_error(&primary->batch))
1572 return;
1573
1574 /* The secondary command buffers will assume that the PMA fix is disabled
1575 * when they begin executing. Make sure this is true.
1576 */
1577 genX(cmd_buffer_enable_pma_fix)(primary, false);
1578
1579 /* The secondary command buffer doesn't know which textures etc. have been
1580 * flushed prior to their execution. Apply those flushes now.
1581 */
1582 genX(cmd_buffer_apply_pipe_flushes)(primary);
1583
1584 for (uint32_t i = 0; i < commandBufferCount; i++) {
1585 ANV_FROM_HANDLE(anv_cmd_buffer, secondary, pCmdBuffers[i]);
1586
1587 assert(secondary->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY);
1588 assert(!anv_batch_has_error(&secondary->batch));
1589
1590 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1591 if (secondary->state.conditional_render_enabled) {
1592 if (!primary->state.conditional_render_enabled) {
1593 /* Secondary buffer is constructed as if it will be executed
1594 * with conditional rendering, we should satisfy this dependency
1595 * regardless of conditional rendering being enabled in primary.
1596 */
1597 struct gen_mi_builder b;
1598 gen_mi_builder_init(&b, &primary->batch);
1599 gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
1600 gen_mi_imm(UINT64_MAX));
1601 }
1602 }
1603 #endif
1604
1605 if (secondary->usage_flags &
1606 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1607 /* If we're continuing a render pass from the primary, we need to
1608 * copy the surface states for the current subpass into the storage
1609 * we allocated for them in BeginCommandBuffer.
1610 */
1611 struct anv_bo *ss_bo =
1612 primary->device->surface_state_pool.block_pool.bo;
1613 struct anv_state src_state = primary->state.render_pass_states;
1614 struct anv_state dst_state = secondary->state.render_pass_states;
1615 assert(src_state.alloc_size == dst_state.alloc_size);
1616
1617 genX(cmd_buffer_so_memcpy)(primary,
1618 (struct anv_address) {
1619 .bo = ss_bo,
1620 .offset = dst_state.offset,
1621 },
1622 (struct anv_address) {
1623 .bo = ss_bo,
1624 .offset = src_state.offset,
1625 },
1626 src_state.alloc_size);
1627 }
1628
1629 anv_cmd_buffer_add_secondary(primary, secondary);
1630 }
1631
1632 /* The secondary isn't counted in our VF cache tracking so we need to
1633 * invalidate the whole thing.
1634 */
1635 if (GEN_GEN >= 8 && GEN_GEN <= 9) {
1636 primary->state.pending_pipe_bits |=
1637 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1638 }
1639
1640 /* The secondary may have selected a different pipeline (3D or compute) and
1641 * may have changed the current L3$ configuration. Reset our tracking
1642 * variables to invalid values to ensure that we re-emit these in the case
1643 * where we do any draws or compute dispatches from the primary after the
1644 * secondary has returned.
1645 */
1646 primary->state.current_pipeline = UINT32_MAX;
1647 primary->state.current_l3_config = NULL;
1648 primary->state.current_hash_scale = 0;
1649
1650 /* Each of the secondary command buffers will use its own state base
1651 * address. We need to re-emit state base address for the primary after
1652 * all of the secondaries are done.
1653 *
1654 * TODO: Maybe we want to make this a dirty bit to avoid extra state base
1655 * address calls?
1656 */
1657 genX(cmd_buffer_emit_state_base_address)(primary);
1658 }
1659
1660 #define IVB_L3SQCREG1_SQGHPCI_DEFAULT 0x00730000
1661 #define VLV_L3SQCREG1_SQGHPCI_DEFAULT 0x00d30000
1662 #define HSW_L3SQCREG1_SQGHPCI_DEFAULT 0x00610000
1663
1664 /**
1665 * Program the hardware to use the specified L3 configuration.
1666 */
1667 void
1668 genX(cmd_buffer_config_l3)(struct anv_cmd_buffer *cmd_buffer,
1669 const struct gen_l3_config *cfg)
1670 {
1671 assert(cfg);
1672 if (cfg == cmd_buffer->state.current_l3_config)
1673 return;
1674
1675 if (unlikely(INTEL_DEBUG & DEBUG_L3)) {
1676 intel_logd("L3 config transition: ");
1677 gen_dump_l3_config(cfg, stderr);
1678 }
1679
1680 UNUSED const bool has_slm = cfg->n[GEN_L3P_SLM];
1681
1682 /* According to the hardware docs, the L3 partitioning can only be changed
1683 * while the pipeline is completely drained and the caches are flushed,
1684 * which involves a first PIPE_CONTROL flush which stalls the pipeline...
1685 */
1686 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1687 pc.DCFlushEnable = true;
1688 pc.PostSyncOperation = NoWrite;
1689 pc.CommandStreamerStallEnable = true;
1690 }
1691
1692 /* ...followed by a second pipelined PIPE_CONTROL that initiates
1693 * invalidation of the relevant caches. Note that because RO invalidation
1694 * happens at the top of the pipeline (i.e. right away as the PIPE_CONTROL
1695 * command is processed by the CS) we cannot combine it with the previous
1696 * stalling flush as the hardware documentation suggests, because that
1697 * would cause the CS to stall on previous rendering *after* RO
1698 * invalidation and wouldn't prevent the RO caches from being polluted by
1699 * concurrent rendering before the stall completes. This intentionally
1700 * doesn't implement the SKL+ hardware workaround suggesting to enable CS
1701 * stall on PIPE_CONTROLs with the texture cache invalidation bit set for
1702 * GPGPU workloads because the previous and subsequent PIPE_CONTROLs
1703 * already guarantee that there is no concurrent GPGPU kernel execution
1704 * (see SKL HSD 2132585).
1705 */
1706 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1707 pc.TextureCacheInvalidationEnable = true;
1708 pc.ConstantCacheInvalidationEnable = true;
1709 pc.InstructionCacheInvalidateEnable = true;
1710 pc.StateCacheInvalidationEnable = true;
1711 pc.PostSyncOperation = NoWrite;
1712 }
1713
1714 /* Now send a third stalling flush to make sure that invalidation is
1715 * complete when the L3 configuration registers are modified.
1716 */
1717 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1718 pc.DCFlushEnable = true;
1719 pc.PostSyncOperation = NoWrite;
1720 pc.CommandStreamerStallEnable = true;
1721 }
1722
1723 #if GEN_GEN >= 8
1724
1725 assert(!cfg->n[GEN_L3P_IS] && !cfg->n[GEN_L3P_C] && !cfg->n[GEN_L3P_T]);
1726
1727 #if GEN_GEN >= 12
1728 #define L3_ALLOCATION_REG GENX(L3ALLOC)
1729 #define L3_ALLOCATION_REG_num GENX(L3ALLOC_num)
1730 #else
1731 #define L3_ALLOCATION_REG GENX(L3CNTLREG)
1732 #define L3_ALLOCATION_REG_num GENX(L3CNTLREG_num)
1733 #endif
1734
1735 uint32_t l3cr;
1736 anv_pack_struct(&l3cr, L3_ALLOCATION_REG,
1737 #if GEN_GEN < 12
1738 .SLMEnable = has_slm,
1739 #endif
1740 #if GEN_GEN == 11
1741 /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
1742 * in L3CNTLREG register. The default setting of the bit is not the
1743 * desirable behavior.
1744 */
1745 .ErrorDetectionBehaviorControl = true,
1746 .UseFullWays = true,
1747 #endif
1748 .URBAllocation = cfg->n[GEN_L3P_URB],
1749 .ROAllocation = cfg->n[GEN_L3P_RO],
1750 .DCAllocation = cfg->n[GEN_L3P_DC],
1751 .AllAllocation = cfg->n[GEN_L3P_ALL]);
1752
1753 /* Set up the L3 partitioning. */
1754 emit_lri(&cmd_buffer->batch, L3_ALLOCATION_REG_num, l3cr);
1755
1756 #else
1757
1758 const bool has_dc = cfg->n[GEN_L3P_DC] || cfg->n[GEN_L3P_ALL];
1759 const bool has_is = cfg->n[GEN_L3P_IS] || cfg->n[GEN_L3P_RO] ||
1760 cfg->n[GEN_L3P_ALL];
1761 const bool has_c = cfg->n[GEN_L3P_C] || cfg->n[GEN_L3P_RO] ||
1762 cfg->n[GEN_L3P_ALL];
1763 const bool has_t = cfg->n[GEN_L3P_T] || cfg->n[GEN_L3P_RO] ||
1764 cfg->n[GEN_L3P_ALL];
1765
1766 assert(!cfg->n[GEN_L3P_ALL]);
1767
1768 /* When enabled SLM only uses a portion of the L3 on half of the banks,
1769 * the matching space on the remaining banks has to be allocated to a
1770 * client (URB for all validated configurations) set to the
1771 * lower-bandwidth 2-bank address hashing mode.
1772 */
1773 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1774 const bool urb_low_bw = has_slm && !devinfo->is_baytrail;
1775 assert(!urb_low_bw || cfg->n[GEN_L3P_URB] == cfg->n[GEN_L3P_SLM]);
1776
1777 /* Minimum number of ways that can be allocated to the URB. */
1778 const unsigned n0_urb = devinfo->is_baytrail ? 32 : 0;
1779 assert(cfg->n[GEN_L3P_URB] >= n0_urb);
1780
1781 uint32_t l3sqcr1, l3cr2, l3cr3;
1782 anv_pack_struct(&l3sqcr1, GENX(L3SQCREG1),
1783 .ConvertDC_UC = !has_dc,
1784 .ConvertIS_UC = !has_is,
1785 .ConvertC_UC = !has_c,
1786 .ConvertT_UC = !has_t);
1787 l3sqcr1 |=
1788 GEN_IS_HASWELL ? HSW_L3SQCREG1_SQGHPCI_DEFAULT :
1789 devinfo->is_baytrail ? VLV_L3SQCREG1_SQGHPCI_DEFAULT :
1790 IVB_L3SQCREG1_SQGHPCI_DEFAULT;
1791
1792 anv_pack_struct(&l3cr2, GENX(L3CNTLREG2),
1793 .SLMEnable = has_slm,
1794 .URBLowBandwidth = urb_low_bw,
1795 .URBAllocation = cfg->n[GEN_L3P_URB] - n0_urb,
1796 #if !GEN_IS_HASWELL
1797 .ALLAllocation = cfg->n[GEN_L3P_ALL],
1798 #endif
1799 .ROAllocation = cfg->n[GEN_L3P_RO],
1800 .DCAllocation = cfg->n[GEN_L3P_DC]);
1801
1802 anv_pack_struct(&l3cr3, GENX(L3CNTLREG3),
1803 .ISAllocation = cfg->n[GEN_L3P_IS],
1804 .ISLowBandwidth = 0,
1805 .CAllocation = cfg->n[GEN_L3P_C],
1806 .CLowBandwidth = 0,
1807 .TAllocation = cfg->n[GEN_L3P_T],
1808 .TLowBandwidth = 0);
1809
1810 /* Set up the L3 partitioning. */
1811 emit_lri(&cmd_buffer->batch, GENX(L3SQCREG1_num), l3sqcr1);
1812 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG2_num), l3cr2);
1813 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG3_num), l3cr3);
1814
1815 #if GEN_IS_HASWELL
1816 if (cmd_buffer->device->instance->physicalDevice.cmd_parser_version >= 4) {
1817 /* Enable L3 atomics on HSW if we have a DC partition, otherwise keep
1818 * them disabled to avoid crashing the system hard.
1819 */
1820 uint32_t scratch1, chicken3;
1821 anv_pack_struct(&scratch1, GENX(SCRATCH1),
1822 .L3AtomicDisable = !has_dc);
1823 anv_pack_struct(&chicken3, GENX(CHICKEN3),
1824 .L3AtomicDisableMask = true,
1825 .L3AtomicDisable = !has_dc);
1826 emit_lri(&cmd_buffer->batch, GENX(SCRATCH1_num), scratch1);
1827 emit_lri(&cmd_buffer->batch, GENX(CHICKEN3_num), chicken3);
1828 }
1829 #endif
1830
1831 #endif
1832
1833 cmd_buffer->state.current_l3_config = cfg;
1834 }
1835
1836 void
1837 genX(cmd_buffer_apply_pipe_flushes)(struct anv_cmd_buffer *cmd_buffer)
1838 {
1839 enum anv_pipe_bits bits = cmd_buffer->state.pending_pipe_bits;
1840
1841 if (cmd_buffer->device->instance->physicalDevice.always_flush_cache)
1842 bits |= ANV_PIPE_FLUSH_BITS | ANV_PIPE_INVALIDATE_BITS;
1843
1844 /* Flushes are pipelined while invalidations are handled immediately.
1845 * Therefore, if we're flushing anything then we need to schedule a stall
1846 * before any invalidations can happen.
1847 */
1848 if (bits & ANV_PIPE_FLUSH_BITS)
1849 bits |= ANV_PIPE_NEEDS_CS_STALL_BIT;
1850
1851 /* If we're going to do an invalidate and we have a pending CS stall that
1852 * has yet to be resolved, we do the CS stall now.
1853 */
1854 if ((bits & ANV_PIPE_INVALIDATE_BITS) &&
1855 (bits & ANV_PIPE_NEEDS_CS_STALL_BIT)) {
1856 bits |= ANV_PIPE_CS_STALL_BIT;
1857 bits &= ~ANV_PIPE_NEEDS_CS_STALL_BIT;
1858 }
1859
1860 if (GEN_GEN >= 12 &&
1861 ((bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT) ||
1862 (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT))) {
1863 /* From the PIPE_CONTROL instruction table, bit 28 (Tile Cache Flush
1864 * Enable):
1865 *
1866 * Unified Cache (Tile Cache Disabled):
1867 *
1868 * When the Color and Depth (Z) streams are enabled to be cached in
1869 * the DC space of L2, Software must use "Render Target Cache Flush
1870 * Enable" and "Depth Cache Flush Enable" along with "Tile Cache
1871 * Flush" for getting the color and depth (Z) write data to be
1872 * globally observable. In this mode of operation it is not required
1873 * to set "CS Stall" upon setting "Tile Cache Flush" bit.
1874 */
1875 bits |= ANV_PIPE_TILE_CACHE_FLUSH_BIT;
1876 }
1877
1878 if ((GEN_GEN >= 8 && GEN_GEN <= 9) &&
1879 (bits & ANV_PIPE_CS_STALL_BIT) &&
1880 (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT)) {
1881 /* If we are doing a VF cache invalidate AND a CS stall (it must be
1882 * both) then we can reset our vertex cache tracking.
1883 */
1884 memset(cmd_buffer->state.gfx.vb_dirty_ranges, 0,
1885 sizeof(cmd_buffer->state.gfx.vb_dirty_ranges));
1886 memset(&cmd_buffer->state.gfx.ib_dirty_range, 0,
1887 sizeof(cmd_buffer->state.gfx.ib_dirty_range));
1888 }
1889
1890 if (bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT)) {
1891 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1892 #if GEN_GEN >= 12
1893 pipe.TileCacheFlushEnable = bits & ANV_PIPE_TILE_CACHE_FLUSH_BIT;
1894 #endif
1895 pipe.DepthCacheFlushEnable = bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1896 pipe.DCFlushEnable = bits & ANV_PIPE_DATA_CACHE_FLUSH_BIT;
1897 pipe.RenderTargetCacheFlushEnable =
1898 bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1899
1900 pipe.DepthStallEnable = bits & ANV_PIPE_DEPTH_STALL_BIT;
1901 pipe.CommandStreamerStallEnable = bits & ANV_PIPE_CS_STALL_BIT;
1902 pipe.StallAtPixelScoreboard = bits & ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
1903
1904 /*
1905 * According to the Broadwell documentation, any PIPE_CONTROL with the
1906 * "Command Streamer Stall" bit set must also have another bit set,
1907 * with five different options:
1908 *
1909 * - Render Target Cache Flush
1910 * - Depth Cache Flush
1911 * - Stall at Pixel Scoreboard
1912 * - Post-Sync Operation
1913 * - Depth Stall
1914 * - DC Flush Enable
1915 *
1916 * I chose "Stall at Pixel Scoreboard" since that's what we use in
1917 * mesa and it seems to work fine. The choice is fairly arbitrary.
1918 */
1919 if ((bits & ANV_PIPE_CS_STALL_BIT) &&
1920 !(bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_DEPTH_STALL_BIT |
1921 ANV_PIPE_STALL_AT_SCOREBOARD_BIT)))
1922 pipe.StallAtPixelScoreboard = true;
1923 }
1924
1925 /* If a render target flush was emitted, then we can toggle off the bit
1926 * saying that render target writes are ongoing.
1927 */
1928 if (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
1929 bits &= ~(ANV_PIPE_RENDER_TARGET_BUFFER_WRITES);
1930
1931 bits &= ~(ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT);
1932 }
1933
1934 if (bits & ANV_PIPE_INVALIDATE_BITS) {
1935 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1936 *
1937 * "If the VF Cache Invalidation Enable is set to a 1 in a
1938 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields sets to
1939 * 0, with the VF Cache Invalidation Enable set to 0 needs to be sent
1940 * prior to the PIPE_CONTROL with VF Cache Invalidation Enable set to
1941 * a 1."
1942 *
1943 * This appears to hang Broadwell, so we restrict it to just gen9.
1944 */
1945 if (GEN_GEN == 9 && (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT))
1946 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe);
1947
1948 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1949 pipe.StateCacheInvalidationEnable =
1950 bits & ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
1951 pipe.ConstantCacheInvalidationEnable =
1952 bits & ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
1953 pipe.VFCacheInvalidationEnable =
1954 bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1955 pipe.TextureCacheInvalidationEnable =
1956 bits & ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1957 pipe.InstructionCacheInvalidateEnable =
1958 bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT;
1959
1960 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1961 *
1962 * "When VF Cache Invalidate is set “Post Sync Operation” must be
1963 * enabled to “Write Immediate Data” or “Write PS Depth Count” or
1964 * “Write Timestamp”.
1965 */
1966 if (GEN_GEN == 9 && pipe.VFCacheInvalidationEnable) {
1967 pipe.PostSyncOperation = WriteImmediateData;
1968 pipe.Address =
1969 (struct anv_address) { cmd_buffer->device->workaround_bo, 0 };
1970 }
1971 }
1972
1973 bits &= ~ANV_PIPE_INVALIDATE_BITS;
1974 }
1975
1976 cmd_buffer->state.pending_pipe_bits = bits;
1977 }
1978
1979 void genX(CmdPipelineBarrier)(
1980 VkCommandBuffer commandBuffer,
1981 VkPipelineStageFlags srcStageMask,
1982 VkPipelineStageFlags destStageMask,
1983 VkBool32 byRegion,
1984 uint32_t memoryBarrierCount,
1985 const VkMemoryBarrier* pMemoryBarriers,
1986 uint32_t bufferMemoryBarrierCount,
1987 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1988 uint32_t imageMemoryBarrierCount,
1989 const VkImageMemoryBarrier* pImageMemoryBarriers)
1990 {
1991 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1992
1993 /* XXX: Right now, we're really dumb and just flush whatever categories
1994 * the app asks for. One of these days we may make this a bit better
1995 * but right now that's all the hardware allows for in most areas.
1996 */
1997 VkAccessFlags src_flags = 0;
1998 VkAccessFlags dst_flags = 0;
1999
2000 for (uint32_t i = 0; i < memoryBarrierCount; i++) {
2001 src_flags |= pMemoryBarriers[i].srcAccessMask;
2002 dst_flags |= pMemoryBarriers[i].dstAccessMask;
2003 }
2004
2005 for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
2006 src_flags |= pBufferMemoryBarriers[i].srcAccessMask;
2007 dst_flags |= pBufferMemoryBarriers[i].dstAccessMask;
2008 }
2009
2010 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
2011 src_flags |= pImageMemoryBarriers[i].srcAccessMask;
2012 dst_flags |= pImageMemoryBarriers[i].dstAccessMask;
2013 ANV_FROM_HANDLE(anv_image, image, pImageMemoryBarriers[i].image);
2014 const VkImageSubresourceRange *range =
2015 &pImageMemoryBarriers[i].subresourceRange;
2016
2017 uint32_t base_layer, layer_count;
2018 if (image->type == VK_IMAGE_TYPE_3D) {
2019 base_layer = 0;
2020 layer_count = anv_minify(image->extent.depth, range->baseMipLevel);
2021 } else {
2022 base_layer = range->baseArrayLayer;
2023 layer_count = anv_get_layerCount(image, range);
2024 }
2025
2026 if (range->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2027 transition_depth_buffer(cmd_buffer, image,
2028 pImageMemoryBarriers[i].oldLayout,
2029 pImageMemoryBarriers[i].newLayout);
2030 }
2031
2032 if (range->aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2033 transition_stencil_buffer(cmd_buffer, image,
2034 range->baseMipLevel,
2035 anv_get_levelCount(image, range),
2036 base_layer, layer_count,
2037 pImageMemoryBarriers[i].oldLayout,
2038 pImageMemoryBarriers[i].newLayout);
2039 }
2040
2041 if (range->aspectMask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
2042 VkImageAspectFlags color_aspects =
2043 anv_image_expand_aspects(image, range->aspectMask);
2044 uint32_t aspect_bit;
2045 anv_foreach_image_aspect_bit(aspect_bit, image, color_aspects) {
2046 transition_color_buffer(cmd_buffer, image, 1UL << aspect_bit,
2047 range->baseMipLevel,
2048 anv_get_levelCount(image, range),
2049 base_layer, layer_count,
2050 pImageMemoryBarriers[i].oldLayout,
2051 pImageMemoryBarriers[i].newLayout);
2052 }
2053 }
2054 }
2055
2056 cmd_buffer->state.pending_pipe_bits |=
2057 anv_pipe_flush_bits_for_access_flags(src_flags) |
2058 anv_pipe_invalidate_bits_for_access_flags(dst_flags);
2059 }
2060
2061 static void
2062 cmd_buffer_alloc_push_constants(struct anv_cmd_buffer *cmd_buffer)
2063 {
2064 VkShaderStageFlags stages =
2065 cmd_buffer->state.gfx.base.pipeline->active_stages;
2066
2067 /* In order to avoid thrash, we assume that vertex and fragment stages
2068 * always exist. In the rare case where one is missing *and* the other
2069 * uses push concstants, this may be suboptimal. However, avoiding stalls
2070 * seems more important.
2071 */
2072 stages |= VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT;
2073
2074 if (stages == cmd_buffer->state.push_constant_stages)
2075 return;
2076
2077 #if GEN_GEN >= 8
2078 const unsigned push_constant_kb = 32;
2079 #elif GEN_IS_HASWELL
2080 const unsigned push_constant_kb = cmd_buffer->device->info.gt == 3 ? 32 : 16;
2081 #else
2082 const unsigned push_constant_kb = 16;
2083 #endif
2084
2085 const unsigned num_stages =
2086 util_bitcount(stages & VK_SHADER_STAGE_ALL_GRAPHICS);
2087 unsigned size_per_stage = push_constant_kb / num_stages;
2088
2089 /* Broadwell+ and Haswell gt3 require that the push constant sizes be in
2090 * units of 2KB. Incidentally, these are the same platforms that have
2091 * 32KB worth of push constant space.
2092 */
2093 if (push_constant_kb == 32)
2094 size_per_stage &= ~1u;
2095
2096 uint32_t kb_used = 0;
2097 for (int i = MESA_SHADER_VERTEX; i < MESA_SHADER_FRAGMENT; i++) {
2098 unsigned push_size = (stages & (1 << i)) ? size_per_stage : 0;
2099 anv_batch_emit(&cmd_buffer->batch,
2100 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
2101 alloc._3DCommandSubOpcode = 18 + i;
2102 alloc.ConstantBufferOffset = (push_size > 0) ? kb_used : 0;
2103 alloc.ConstantBufferSize = push_size;
2104 }
2105 kb_used += push_size;
2106 }
2107
2108 anv_batch_emit(&cmd_buffer->batch,
2109 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_PS), alloc) {
2110 alloc.ConstantBufferOffset = kb_used;
2111 alloc.ConstantBufferSize = push_constant_kb - kb_used;
2112 }
2113
2114 cmd_buffer->state.push_constant_stages = stages;
2115
2116 /* From the BDW PRM for 3DSTATE_PUSH_CONSTANT_ALLOC_VS:
2117 *
2118 * "The 3DSTATE_CONSTANT_VS must be reprogrammed prior to
2119 * the next 3DPRIMITIVE command after programming the
2120 * 3DSTATE_PUSH_CONSTANT_ALLOC_VS"
2121 *
2122 * Since 3DSTATE_PUSH_CONSTANT_ALLOC_VS is programmed as part of
2123 * pipeline setup, we need to dirty push constants.
2124 */
2125 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
2126 }
2127
2128 static struct anv_address
2129 anv_descriptor_set_address(struct anv_cmd_buffer *cmd_buffer,
2130 struct anv_descriptor_set *set)
2131 {
2132 if (set->pool) {
2133 /* This is a normal descriptor set */
2134 return (struct anv_address) {
2135 .bo = set->pool->bo,
2136 .offset = set->desc_mem.offset,
2137 };
2138 } else {
2139 /* This is a push descriptor set. We have to flag it as used on the GPU
2140 * so that the next time we push descriptors, we grab a new memory.
2141 */
2142 struct anv_push_descriptor_set *push_set =
2143 (struct anv_push_descriptor_set *)set;
2144 push_set->set_used_on_gpu = true;
2145
2146 return (struct anv_address) {
2147 .bo = cmd_buffer->dynamic_state_stream.state_pool->block_pool.bo,
2148 .offset = set->desc_mem.offset,
2149 };
2150 }
2151 }
2152
2153 static VkResult
2154 emit_binding_table(struct anv_cmd_buffer *cmd_buffer,
2155 gl_shader_stage stage,
2156 struct anv_state *bt_state)
2157 {
2158 struct anv_subpass *subpass = cmd_buffer->state.subpass;
2159 struct anv_cmd_pipeline_state *pipe_state;
2160 struct anv_pipeline *pipeline;
2161 uint32_t state_offset;
2162
2163 switch (stage) {
2164 case MESA_SHADER_COMPUTE:
2165 pipe_state = &cmd_buffer->state.compute.base;
2166 break;
2167 default:
2168 pipe_state = &cmd_buffer->state.gfx.base;
2169 break;
2170 }
2171 pipeline = pipe_state->pipeline;
2172
2173 if (!anv_pipeline_has_stage(pipeline, stage)) {
2174 *bt_state = (struct anv_state) { 0, };
2175 return VK_SUCCESS;
2176 }
2177
2178 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2179 if (map->surface_count == 0) {
2180 *bt_state = (struct anv_state) { 0, };
2181 return VK_SUCCESS;
2182 }
2183
2184 *bt_state = anv_cmd_buffer_alloc_binding_table(cmd_buffer,
2185 map->surface_count,
2186 &state_offset);
2187 uint32_t *bt_map = bt_state->map;
2188
2189 if (bt_state->map == NULL)
2190 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2191
2192 /* We only need to emit relocs if we're not using softpin. If we are using
2193 * softpin then we always keep all user-allocated memory objects resident.
2194 */
2195 const bool need_client_mem_relocs =
2196 !cmd_buffer->device->instance->physicalDevice.use_softpin;
2197
2198 for (uint32_t s = 0; s < map->surface_count; s++) {
2199 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[s];
2200
2201 struct anv_state surface_state;
2202
2203 switch (binding->set) {
2204 case ANV_DESCRIPTOR_SET_NULL:
2205 bt_map[s] = 0;
2206 break;
2207
2208 case ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS:
2209 /* Color attachment binding */
2210 assert(stage == MESA_SHADER_FRAGMENT);
2211 if (binding->index < subpass->color_count) {
2212 const unsigned att =
2213 subpass->color_attachments[binding->index].attachment;
2214
2215 /* From the Vulkan 1.0.46 spec:
2216 *
2217 * "If any color or depth/stencil attachments are
2218 * VK_ATTACHMENT_UNUSED, then no writes occur for those
2219 * attachments."
2220 */
2221 if (att == VK_ATTACHMENT_UNUSED) {
2222 surface_state = cmd_buffer->state.null_surface_state;
2223 } else {
2224 surface_state = cmd_buffer->state.attachments[att].color.state;
2225 }
2226 } else {
2227 surface_state = cmd_buffer->state.null_surface_state;
2228 }
2229
2230 bt_map[s] = surface_state.offset + state_offset;
2231 break;
2232
2233 case ANV_DESCRIPTOR_SET_SHADER_CONSTANTS: {
2234 struct anv_state surface_state =
2235 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2236
2237 struct anv_address constant_data = {
2238 .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2239 .offset = pipeline->shaders[stage]->constant_data.offset,
2240 };
2241 unsigned constant_data_size =
2242 pipeline->shaders[stage]->constant_data_size;
2243
2244 const enum isl_format format =
2245 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2246 anv_fill_buffer_surface_state(cmd_buffer->device,
2247 surface_state, format,
2248 constant_data, constant_data_size, 1);
2249
2250 bt_map[s] = surface_state.offset + state_offset;
2251 add_surface_reloc(cmd_buffer, surface_state, constant_data);
2252 break;
2253 }
2254
2255 case ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS: {
2256 /* This is always the first binding for compute shaders */
2257 assert(stage == MESA_SHADER_COMPUTE && s == 0);
2258
2259 struct anv_state surface_state =
2260 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2261
2262 const enum isl_format format =
2263 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2264 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2265 format,
2266 cmd_buffer->state.compute.num_workgroups,
2267 12, 1);
2268 bt_map[s] = surface_state.offset + state_offset;
2269 if (need_client_mem_relocs) {
2270 add_surface_reloc(cmd_buffer, surface_state,
2271 cmd_buffer->state.compute.num_workgroups);
2272 }
2273 break;
2274 }
2275
2276 case ANV_DESCRIPTOR_SET_DESCRIPTORS: {
2277 /* This is a descriptor set buffer so the set index is actually
2278 * given by binding->binding. (Yes, that's confusing.)
2279 */
2280 struct anv_descriptor_set *set =
2281 pipe_state->descriptors[binding->index];
2282 assert(set->desc_mem.alloc_size);
2283 assert(set->desc_surface_state.alloc_size);
2284 bt_map[s] = set->desc_surface_state.offset + state_offset;
2285 add_surface_reloc(cmd_buffer, set->desc_surface_state,
2286 anv_descriptor_set_address(cmd_buffer, set));
2287 break;
2288 }
2289
2290 default: {
2291 assert(binding->set < MAX_SETS);
2292 const struct anv_descriptor *desc =
2293 &pipe_state->descriptors[binding->set]->descriptors[binding->index];
2294
2295 switch (desc->type) {
2296 case VK_DESCRIPTOR_TYPE_SAMPLER:
2297 /* Nothing for us to do here */
2298 continue;
2299
2300 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2301 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
2302 struct anv_surface_state sstate =
2303 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2304 desc->image_view->planes[binding->plane].general_sampler_surface_state :
2305 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2306 surface_state = sstate.state;
2307 assert(surface_state.alloc_size);
2308 if (need_client_mem_relocs)
2309 add_surface_state_relocs(cmd_buffer, sstate);
2310 break;
2311 }
2312 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2313 assert(stage == MESA_SHADER_FRAGMENT);
2314 if ((desc->image_view->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) == 0) {
2315 /* For depth and stencil input attachments, we treat it like any
2316 * old texture that a user may have bound.
2317 */
2318 assert(desc->image_view->n_planes == 1);
2319 struct anv_surface_state sstate =
2320 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2321 desc->image_view->planes[0].general_sampler_surface_state :
2322 desc->image_view->planes[0].optimal_sampler_surface_state;
2323 surface_state = sstate.state;
2324 assert(surface_state.alloc_size);
2325 if (need_client_mem_relocs)
2326 add_surface_state_relocs(cmd_buffer, sstate);
2327 } else {
2328 /* For color input attachments, we create the surface state at
2329 * vkBeginRenderPass time so that we can include aux and clear
2330 * color information.
2331 */
2332 assert(binding->input_attachment_index < subpass->input_count);
2333 const unsigned subpass_att = binding->input_attachment_index;
2334 const unsigned att = subpass->input_attachments[subpass_att].attachment;
2335 surface_state = cmd_buffer->state.attachments[att].input.state;
2336 }
2337 break;
2338
2339 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
2340 struct anv_surface_state sstate = (binding->write_only)
2341 ? desc->image_view->planes[binding->plane].writeonly_storage_surface_state
2342 : desc->image_view->planes[binding->plane].storage_surface_state;
2343 surface_state = sstate.state;
2344 assert(surface_state.alloc_size);
2345 if (need_client_mem_relocs)
2346 add_surface_state_relocs(cmd_buffer, sstate);
2347 break;
2348 }
2349
2350 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2351 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2352 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2353 surface_state = desc->buffer_view->surface_state;
2354 assert(surface_state.alloc_size);
2355 if (need_client_mem_relocs) {
2356 add_surface_reloc(cmd_buffer, surface_state,
2357 desc->buffer_view->address);
2358 }
2359 break;
2360
2361 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2362 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
2363 /* Compute the offset within the buffer */
2364 struct anv_push_constants *push =
2365 &cmd_buffer->state.push_constants[stage];
2366
2367 uint32_t dynamic_offset =
2368 push->dynamic_offsets[binding->dynamic_offset_index];
2369 uint64_t offset = desc->offset + dynamic_offset;
2370 /* Clamp to the buffer size */
2371 offset = MIN2(offset, desc->buffer->size);
2372 /* Clamp the range to the buffer size */
2373 uint32_t range = MIN2(desc->range, desc->buffer->size - offset);
2374
2375 struct anv_address address =
2376 anv_address_add(desc->buffer->address, offset);
2377
2378 surface_state =
2379 anv_state_stream_alloc(&cmd_buffer->surface_state_stream, 64, 64);
2380 enum isl_format format =
2381 anv_isl_format_for_descriptor_type(desc->type);
2382
2383 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2384 format, address, range, 1);
2385 if (need_client_mem_relocs)
2386 add_surface_reloc(cmd_buffer, surface_state, address);
2387 break;
2388 }
2389
2390 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2391 surface_state = (binding->write_only)
2392 ? desc->buffer_view->writeonly_storage_surface_state
2393 : desc->buffer_view->storage_surface_state;
2394 assert(surface_state.alloc_size);
2395 if (need_client_mem_relocs) {
2396 add_surface_reloc(cmd_buffer, surface_state,
2397 desc->buffer_view->address);
2398 }
2399 break;
2400
2401 default:
2402 assert(!"Invalid descriptor type");
2403 continue;
2404 }
2405 bt_map[s] = surface_state.offset + state_offset;
2406 break;
2407 }
2408 }
2409 }
2410
2411 return VK_SUCCESS;
2412 }
2413
2414 static VkResult
2415 emit_samplers(struct anv_cmd_buffer *cmd_buffer,
2416 gl_shader_stage stage,
2417 struct anv_state *state)
2418 {
2419 struct anv_cmd_pipeline_state *pipe_state =
2420 stage == MESA_SHADER_COMPUTE ? &cmd_buffer->state.compute.base :
2421 &cmd_buffer->state.gfx.base;
2422 struct anv_pipeline *pipeline = pipe_state->pipeline;
2423
2424 if (!anv_pipeline_has_stage(pipeline, stage)) {
2425 *state = (struct anv_state) { 0, };
2426 return VK_SUCCESS;
2427 }
2428
2429 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2430 if (map->sampler_count == 0) {
2431 *state = (struct anv_state) { 0, };
2432 return VK_SUCCESS;
2433 }
2434
2435 uint32_t size = map->sampler_count * 16;
2436 *state = anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, size, 32);
2437
2438 if (state->map == NULL)
2439 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2440
2441 for (uint32_t s = 0; s < map->sampler_count; s++) {
2442 struct anv_pipeline_binding *binding = &map->sampler_to_descriptor[s];
2443 const struct anv_descriptor *desc =
2444 &pipe_state->descriptors[binding->set]->descriptors[binding->index];
2445
2446 if (desc->type != VK_DESCRIPTOR_TYPE_SAMPLER &&
2447 desc->type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
2448 continue;
2449
2450 struct anv_sampler *sampler = desc->sampler;
2451
2452 /* This can happen if we have an unfilled slot since TYPE_SAMPLER
2453 * happens to be zero.
2454 */
2455 if (sampler == NULL)
2456 continue;
2457
2458 memcpy(state->map + (s * 16),
2459 sampler->state[binding->plane], sizeof(sampler->state[0]));
2460 }
2461
2462 return VK_SUCCESS;
2463 }
2464
2465 static uint32_t
2466 flush_descriptor_sets(struct anv_cmd_buffer *cmd_buffer,
2467 struct anv_pipeline *pipeline)
2468 {
2469 VkShaderStageFlags dirty = cmd_buffer->state.descriptors_dirty &
2470 pipeline->active_stages;
2471
2472 VkResult result = VK_SUCCESS;
2473 anv_foreach_stage(s, dirty) {
2474 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2475 if (result != VK_SUCCESS)
2476 break;
2477 result = emit_binding_table(cmd_buffer, s,
2478 &cmd_buffer->state.binding_tables[s]);
2479 if (result != VK_SUCCESS)
2480 break;
2481 }
2482
2483 if (result != VK_SUCCESS) {
2484 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2485
2486 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2487 if (result != VK_SUCCESS)
2488 return 0;
2489
2490 /* Re-emit state base addresses so we get the new surface state base
2491 * address before we start emitting binding tables etc.
2492 */
2493 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2494
2495 /* Re-emit all active binding tables */
2496 dirty |= pipeline->active_stages;
2497 anv_foreach_stage(s, dirty) {
2498 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2499 if (result != VK_SUCCESS) {
2500 anv_batch_set_error(&cmd_buffer->batch, result);
2501 return 0;
2502 }
2503 result = emit_binding_table(cmd_buffer, s,
2504 &cmd_buffer->state.binding_tables[s]);
2505 if (result != VK_SUCCESS) {
2506 anv_batch_set_error(&cmd_buffer->batch, result);
2507 return 0;
2508 }
2509 }
2510 }
2511
2512 cmd_buffer->state.descriptors_dirty &= ~dirty;
2513
2514 return dirty;
2515 }
2516
2517 static void
2518 cmd_buffer_emit_descriptor_pointers(struct anv_cmd_buffer *cmd_buffer,
2519 uint32_t stages)
2520 {
2521 static const uint32_t sampler_state_opcodes[] = {
2522 [MESA_SHADER_VERTEX] = 43,
2523 [MESA_SHADER_TESS_CTRL] = 44, /* HS */
2524 [MESA_SHADER_TESS_EVAL] = 45, /* DS */
2525 [MESA_SHADER_GEOMETRY] = 46,
2526 [MESA_SHADER_FRAGMENT] = 47,
2527 [MESA_SHADER_COMPUTE] = 0,
2528 };
2529
2530 static const uint32_t binding_table_opcodes[] = {
2531 [MESA_SHADER_VERTEX] = 38,
2532 [MESA_SHADER_TESS_CTRL] = 39,
2533 [MESA_SHADER_TESS_EVAL] = 40,
2534 [MESA_SHADER_GEOMETRY] = 41,
2535 [MESA_SHADER_FRAGMENT] = 42,
2536 [MESA_SHADER_COMPUTE] = 0,
2537 };
2538
2539 anv_foreach_stage(s, stages) {
2540 assert(s < ARRAY_SIZE(binding_table_opcodes));
2541 assert(binding_table_opcodes[s] > 0);
2542
2543 if (cmd_buffer->state.samplers[s].alloc_size > 0) {
2544 anv_batch_emit(&cmd_buffer->batch,
2545 GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ssp) {
2546 ssp._3DCommandSubOpcode = sampler_state_opcodes[s];
2547 ssp.PointertoVSSamplerState = cmd_buffer->state.samplers[s].offset;
2548 }
2549 }
2550
2551 /* Always emit binding table pointers if we're asked to, since on SKL
2552 * this is what flushes push constants. */
2553 anv_batch_emit(&cmd_buffer->batch,
2554 GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), btp) {
2555 btp._3DCommandSubOpcode = binding_table_opcodes[s];
2556 btp.PointertoVSBindingTable = cmd_buffer->state.binding_tables[s].offset;
2557 }
2558 }
2559 }
2560
2561 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2562 static struct anv_address
2563 get_push_range_address(struct anv_cmd_buffer *cmd_buffer,
2564 gl_shader_stage stage,
2565 const struct anv_push_range *range)
2566 {
2567 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2568 switch (range->set) {
2569 case ANV_DESCRIPTOR_SET_DESCRIPTORS: {
2570 /* This is a descriptor set buffer so the set index is
2571 * actually given by binding->binding. (Yes, that's
2572 * confusing.)
2573 */
2574 struct anv_descriptor_set *set =
2575 gfx_state->base.descriptors[range->index];
2576 return anv_descriptor_set_address(cmd_buffer, set);
2577 break;
2578 }
2579
2580 case ANV_DESCRIPTOR_SET_PUSH_CONSTANTS: {
2581 struct anv_state state =
2582 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2583 return (struct anv_address) {
2584 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2585 .offset = state.offset,
2586 };
2587 break;
2588 }
2589
2590 default: {
2591 assert(range->set < MAX_SETS);
2592 struct anv_descriptor_set *set =
2593 gfx_state->base.descriptors[range->set];
2594 const struct anv_descriptor *desc =
2595 &set->descriptors[range->index];
2596
2597 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2598 return desc->buffer_view->address;
2599 } else {
2600 assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2601 struct anv_push_constants *push =
2602 &cmd_buffer->state.push_constants[stage];
2603 uint32_t dynamic_offset =
2604 push->dynamic_offsets[range->dynamic_offset_index];
2605 return anv_address_add(desc->buffer->address,
2606 desc->offset + dynamic_offset);
2607 }
2608 }
2609 }
2610 }
2611 #endif
2612
2613 static void
2614 cmd_buffer_emit_push_constant(struct anv_cmd_buffer *cmd_buffer,
2615 gl_shader_stage stage, unsigned buffer_count)
2616 {
2617 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2618 const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2619
2620 static const uint32_t push_constant_opcodes[] = {
2621 [MESA_SHADER_VERTEX] = 21,
2622 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2623 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2624 [MESA_SHADER_GEOMETRY] = 22,
2625 [MESA_SHADER_FRAGMENT] = 23,
2626 [MESA_SHADER_COMPUTE] = 0,
2627 };
2628
2629 assert(stage < ARRAY_SIZE(push_constant_opcodes));
2630 assert(push_constant_opcodes[stage] > 0);
2631
2632 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_VS), c) {
2633 c._3DCommandSubOpcode = push_constant_opcodes[stage];
2634
2635 if (anv_pipeline_has_stage(pipeline, stage)) {
2636 const struct anv_pipeline_bind_map *bind_map =
2637 &pipeline->shaders[stage]->bind_map;
2638
2639 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2640 /* The Skylake PRM contains the following restriction:
2641 *
2642 * "The driver must ensure The following case does not occur
2643 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
2644 * buffer 3 read length equal to zero committed followed by a
2645 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
2646 * zero committed."
2647 *
2648 * To avoid this, we program the buffers in the highest slots.
2649 * This way, slot 0 is only used if slot 3 is also used.
2650 */
2651 assert(buffer_count <= 4);
2652 const unsigned shift = 4 - buffer_count;
2653 for (unsigned i = 0; i < buffer_count; i++) {
2654 const struct anv_push_range *range = &bind_map->push_ranges[i];
2655
2656 /* At this point we only have non-empty ranges */
2657 assert(range->length > 0);
2658
2659 /* For Ivy Bridge, make sure we only set the first range (actual
2660 * push constants)
2661 */
2662 assert((GEN_GEN >= 8 || GEN_IS_HASWELL) || i == 0);
2663
2664 const struct anv_address addr =
2665 get_push_range_address(cmd_buffer, stage, range);
2666 c.ConstantBody.ReadLength[i + shift] = range->length;
2667 c.ConstantBody.Buffer[i + shift] =
2668 anv_address_add(addr, range->start * 32);
2669 }
2670 #else
2671 /* For Ivy Bridge, push constants are relative to dynamic state
2672 * base address and we only ever push actual push constants.
2673 */
2674 if (bind_map->push_ranges[0].length > 0) {
2675 assert(bind_map->push_ranges[0].set ==
2676 ANV_DESCRIPTOR_SET_PUSH_CONSTANTS);
2677 struct anv_state state =
2678 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2679 c.ConstantBody.ReadLength[0] = bind_map->push_ranges[0].length;
2680 c.ConstantBody.Buffer[0].bo = NULL;
2681 c.ConstantBody.Buffer[0].offset = state.offset;
2682 }
2683 assert(bind_map->push_ranges[1].length == 0);
2684 assert(bind_map->push_ranges[2].length == 0);
2685 assert(bind_map->push_ranges[3].length == 0);
2686 #endif
2687 }
2688 }
2689 }
2690
2691 #if GEN_GEN >= 12
2692 static void
2693 cmd_buffer_emit_push_constant_all(struct anv_cmd_buffer *cmd_buffer,
2694 uint32_t shader_mask, uint32_t count)
2695 {
2696 if (count == 0) {
2697 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_ALL), c) {
2698 c.ShaderUpdateEnable = shader_mask;
2699 }
2700 return;
2701 }
2702
2703 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2704 const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2705
2706 static const uint32_t push_constant_opcodes[] = {
2707 [MESA_SHADER_VERTEX] = 21,
2708 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2709 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2710 [MESA_SHADER_GEOMETRY] = 22,
2711 [MESA_SHADER_FRAGMENT] = 23,
2712 [MESA_SHADER_COMPUTE] = 0,
2713 };
2714
2715 gl_shader_stage stage = vk_to_mesa_shader_stage(shader_mask);
2716 assert(stage < ARRAY_SIZE(push_constant_opcodes));
2717 assert(push_constant_opcodes[stage] > 0);
2718
2719 const struct anv_pipeline_bind_map *bind_map =
2720 &pipeline->shaders[stage]->bind_map;
2721
2722 uint32_t *dw;
2723 const uint32_t buffers = (1 << count) - 1;
2724 const uint32_t num_dwords = 2 + 2 * count;
2725
2726 dw = anv_batch_emitn(&cmd_buffer->batch, num_dwords,
2727 GENX(3DSTATE_CONSTANT_ALL),
2728 .ShaderUpdateEnable = shader_mask,
2729 .PointerBufferMask = buffers);
2730
2731 for (int i = 0; i < count; i++) {
2732 const struct anv_push_range *range = &bind_map->push_ranges[i];
2733 const struct anv_address addr =
2734 get_push_range_address(cmd_buffer, stage, range);
2735
2736 GENX(3DSTATE_CONSTANT_ALL_DATA_pack)(
2737 &cmd_buffer->batch, dw + 2 + i * 2,
2738 &(struct GENX(3DSTATE_CONSTANT_ALL_DATA)) {
2739 .PointerToConstantBuffer = anv_address_add(addr, range->start * 32),
2740 .ConstantBufferReadLength = range->length,
2741 });
2742 }
2743 }
2744 #endif
2745
2746 static void
2747 cmd_buffer_flush_push_constants(struct anv_cmd_buffer *cmd_buffer,
2748 VkShaderStageFlags dirty_stages)
2749 {
2750 VkShaderStageFlags flushed = 0;
2751 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2752 const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2753
2754 #if GEN_GEN >= 12
2755 uint32_t nobuffer_stages = 0;
2756 #endif
2757
2758 anv_foreach_stage(stage, dirty_stages) {
2759 unsigned buffer_count = 0;
2760 flushed |= mesa_to_vk_shader_stage(stage);
2761 uint32_t max_push_range = 0;
2762
2763 if (anv_pipeline_has_stage(pipeline, stage)) {
2764 const struct anv_pipeline_bind_map *bind_map =
2765 &pipeline->shaders[stage]->bind_map;
2766
2767 for (unsigned i = 0; i < 4; i++) {
2768 const struct anv_push_range *range = &bind_map->push_ranges[i];
2769 if (range->length > 0) {
2770 buffer_count++;
2771 if (GEN_GEN >= 12 && range->length > max_push_range)
2772 max_push_range = range->length;
2773 }
2774 }
2775 }
2776
2777 #if GEN_GEN >= 12
2778 /* If this stage doesn't have any push constants, emit it later in a
2779 * single CONSTANT_ALL packet.
2780 */
2781 if (buffer_count == 0) {
2782 nobuffer_stages |= 1 << stage;
2783 continue;
2784 }
2785
2786 /* The Constant Buffer Read Length field from 3DSTATE_CONSTANT_ALL
2787 * contains only 5 bits, so we can only use it for buffers smaller than
2788 * 32.
2789 */
2790 if (max_push_range < 32) {
2791 cmd_buffer_emit_push_constant_all(cmd_buffer, 1 << stage,
2792 buffer_count);
2793 continue;
2794 }
2795 #endif
2796
2797 cmd_buffer_emit_push_constant(cmd_buffer, stage, buffer_count);
2798 }
2799
2800 #if GEN_GEN >= 12
2801 if (nobuffer_stages)
2802 cmd_buffer_emit_push_constant_all(cmd_buffer, nobuffer_stages, 0);
2803 #endif
2804
2805 cmd_buffer->state.push_constants_dirty &= ~flushed;
2806 }
2807
2808 #if GEN_GEN >= 12
2809 void
2810 genX(cmd_buffer_aux_map_state)(struct anv_cmd_buffer *cmd_buffer)
2811 {
2812 void *aux_map_ctx = cmd_buffer->device->aux_map_ctx;
2813 if (!aux_map_ctx)
2814 return;
2815 uint32_t aux_map_state_num = gen_aux_map_get_state_num(aux_map_ctx);
2816 if (cmd_buffer->state.last_aux_map_state != aux_map_state_num) {
2817 /* If the aux-map state number increased, then we need to rewrite the
2818 * register. Rewriting the register is used to both set the aux-map
2819 * translation table address, and also to invalidate any previously
2820 * cached translations.
2821 */
2822 uint64_t base_addr = gen_aux_map_get_base(aux_map_ctx);
2823 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
2824 lri.RegisterOffset = GENX(GFX_AUX_TABLE_BASE_ADDR_num);
2825 lri.DataDWord = base_addr & 0xffffffff;
2826 }
2827 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
2828 lri.RegisterOffset = GENX(GFX_AUX_TABLE_BASE_ADDR_num) + 4;
2829 lri.DataDWord = base_addr >> 32;
2830 }
2831 cmd_buffer->state.last_aux_map_state = aux_map_state_num;
2832 }
2833 }
2834 #endif
2835
2836 void
2837 genX(cmd_buffer_flush_state)(struct anv_cmd_buffer *cmd_buffer)
2838 {
2839 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2840 uint32_t *p;
2841
2842 uint32_t vb_emit = cmd_buffer->state.gfx.vb_dirty & pipeline->vb_used;
2843 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE)
2844 vb_emit |= pipeline->vb_used;
2845
2846 assert((pipeline->active_stages & VK_SHADER_STAGE_COMPUTE_BIT) == 0);
2847
2848 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
2849
2850 genX(cmd_buffer_emit_hashing_mode)(cmd_buffer, UINT_MAX, UINT_MAX, 1);
2851
2852 genX(flush_pipeline_select_3d)(cmd_buffer);
2853
2854 #if GEN_GEN >= 12
2855 genX(cmd_buffer_aux_map_state)(cmd_buffer);
2856 #endif
2857
2858 if (vb_emit) {
2859 const uint32_t num_buffers = __builtin_popcount(vb_emit);
2860 const uint32_t num_dwords = 1 + num_buffers * 4;
2861
2862 p = anv_batch_emitn(&cmd_buffer->batch, num_dwords,
2863 GENX(3DSTATE_VERTEX_BUFFERS));
2864 uint32_t vb, i = 0;
2865 for_each_bit(vb, vb_emit) {
2866 struct anv_buffer *buffer = cmd_buffer->state.vertex_bindings[vb].buffer;
2867 uint32_t offset = cmd_buffer->state.vertex_bindings[vb].offset;
2868
2869 struct GENX(VERTEX_BUFFER_STATE) state = {
2870 .VertexBufferIndex = vb,
2871
2872 .MOCS = anv_mocs_for_bo(cmd_buffer->device, buffer->address.bo),
2873 #if GEN_GEN <= 7
2874 .BufferAccessType = pipeline->vb[vb].instanced ? INSTANCEDATA : VERTEXDATA,
2875 .InstanceDataStepRate = pipeline->vb[vb].instance_divisor,
2876 #endif
2877
2878 .AddressModifyEnable = true,
2879 .BufferPitch = pipeline->vb[vb].stride,
2880 .BufferStartingAddress = anv_address_add(buffer->address, offset),
2881
2882 #if GEN_GEN >= 8
2883 .BufferSize = buffer->size - offset
2884 #else
2885 .EndAddress = anv_address_add(buffer->address, buffer->size - 1),
2886 #endif
2887 };
2888
2889 #if GEN_GEN >= 8 && GEN_GEN <= 9
2890 genX(cmd_buffer_set_binding_for_gen8_vb_flush)(cmd_buffer, vb,
2891 state.BufferStartingAddress,
2892 state.BufferSize);
2893 #endif
2894
2895 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, &p[1 + i * 4], &state);
2896 i++;
2897 }
2898 }
2899
2900 cmd_buffer->state.gfx.vb_dirty &= ~vb_emit;
2901
2902 #if GEN_GEN >= 8
2903 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_XFB_ENABLE) {
2904 /* We don't need any per-buffer dirty tracking because you're not
2905 * allowed to bind different XFB buffers while XFB is enabled.
2906 */
2907 for (unsigned idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
2908 struct anv_xfb_binding *xfb = &cmd_buffer->state.xfb_bindings[idx];
2909 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_SO_BUFFER), sob) {
2910 #if GEN_GEN < 12
2911 sob.SOBufferIndex = idx;
2912 #else
2913 sob._3DCommandOpcode = 0;
2914 sob._3DCommandSubOpcode = SO_BUFFER_INDEX_0_CMD + idx;
2915 #endif
2916
2917 if (cmd_buffer->state.xfb_enabled && xfb->buffer && xfb->size != 0) {
2918 sob.SOBufferEnable = true;
2919 sob.MOCS = cmd_buffer->device->isl_dev.mocs.internal,
2920 sob.StreamOffsetWriteEnable = false;
2921 sob.SurfaceBaseAddress = anv_address_add(xfb->buffer->address,
2922 xfb->offset);
2923 /* Size is in DWords - 1 */
2924 sob.SurfaceSize = xfb->size / 4 - 1;
2925 }
2926 }
2927 }
2928
2929 /* CNL and later require a CS stall after 3DSTATE_SO_BUFFER */
2930 if (GEN_GEN >= 10)
2931 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2932 }
2933 #endif
2934
2935 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE) {
2936 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
2937
2938 /* If the pipeline changed, we may need to re-allocate push constant
2939 * space in the URB.
2940 */
2941 cmd_buffer_alloc_push_constants(cmd_buffer);
2942 }
2943
2944 #if GEN_GEN <= 7
2945 if (cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_VERTEX_BIT ||
2946 cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_VERTEX_BIT) {
2947 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
2948 *
2949 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth
2950 * stall needs to be sent just prior to any 3DSTATE_VS,
2951 * 3DSTATE_URB_VS, 3DSTATE_CONSTANT_VS,
2952 * 3DSTATE_BINDING_TABLE_POINTER_VS,
2953 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one
2954 * PIPE_CONTROL needs to be sent before any combination of VS
2955 * associated 3DSTATE."
2956 */
2957 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2958 pc.DepthStallEnable = true;
2959 pc.PostSyncOperation = WriteImmediateData;
2960 pc.Address =
2961 (struct anv_address) { cmd_buffer->device->workaround_bo, 0 };
2962 }
2963 }
2964 #endif
2965
2966 /* Render targets live in the same binding table as fragment descriptors */
2967 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_RENDER_TARGETS)
2968 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_FRAGMENT_BIT;
2969
2970 /* We emit the binding tables and sampler tables first, then emit push
2971 * constants and then finally emit binding table and sampler table
2972 * pointers. It has to happen in this order, since emitting the binding
2973 * tables may change the push constants (in case of storage images). After
2974 * emitting push constants, on SKL+ we have to emit the corresponding
2975 * 3DSTATE_BINDING_TABLE_POINTER_* for the push constants to take effect.
2976 */
2977 uint32_t dirty = 0;
2978 if (cmd_buffer->state.descriptors_dirty)
2979 dirty = flush_descriptor_sets(cmd_buffer, pipeline);
2980
2981 if (dirty || cmd_buffer->state.push_constants_dirty) {
2982 /* Because we're pushing UBOs, we have to push whenever either
2983 * descriptors or push constants is dirty.
2984 */
2985 dirty |= cmd_buffer->state.push_constants_dirty;
2986 dirty &= ANV_STAGE_MASK & VK_SHADER_STAGE_ALL_GRAPHICS;
2987 cmd_buffer_flush_push_constants(cmd_buffer, dirty);
2988 }
2989
2990 if (dirty)
2991 cmd_buffer_emit_descriptor_pointers(cmd_buffer, dirty);
2992
2993 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT)
2994 gen8_cmd_buffer_emit_viewport(cmd_buffer);
2995
2996 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_VIEWPORT |
2997 ANV_CMD_DIRTY_PIPELINE)) {
2998 gen8_cmd_buffer_emit_depth_viewport(cmd_buffer,
2999 pipeline->depth_clamp_enable);
3000 }
3001
3002 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_SCISSOR |
3003 ANV_CMD_DIRTY_RENDER_TARGETS))
3004 gen7_cmd_buffer_emit_scissor(cmd_buffer);
3005
3006 genX(cmd_buffer_flush_dynamic_state)(cmd_buffer);
3007 }
3008
3009 static void
3010 emit_vertex_bo(struct anv_cmd_buffer *cmd_buffer,
3011 struct anv_address addr,
3012 uint32_t size, uint32_t index)
3013 {
3014 uint32_t *p = anv_batch_emitn(&cmd_buffer->batch, 5,
3015 GENX(3DSTATE_VERTEX_BUFFERS));
3016
3017 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, p + 1,
3018 &(struct GENX(VERTEX_BUFFER_STATE)) {
3019 .VertexBufferIndex = index,
3020 .AddressModifyEnable = true,
3021 .BufferPitch = 0,
3022 .MOCS = addr.bo ? anv_mocs_for_bo(cmd_buffer->device, addr.bo) : 0,
3023 .NullVertexBuffer = size == 0,
3024 #if (GEN_GEN >= 8)
3025 .BufferStartingAddress = addr,
3026 .BufferSize = size
3027 #else
3028 .BufferStartingAddress = addr,
3029 .EndAddress = anv_address_add(addr, size),
3030 #endif
3031 });
3032
3033 genX(cmd_buffer_set_binding_for_gen8_vb_flush)(cmd_buffer,
3034 index, addr, size);
3035 }
3036
3037 static void
3038 emit_base_vertex_instance_bo(struct anv_cmd_buffer *cmd_buffer,
3039 struct anv_address addr)
3040 {
3041 emit_vertex_bo(cmd_buffer, addr, addr.bo ? 8 : 0, ANV_SVGS_VB_INDEX);
3042 }
3043
3044 static void
3045 emit_base_vertex_instance(struct anv_cmd_buffer *cmd_buffer,
3046 uint32_t base_vertex, uint32_t base_instance)
3047 {
3048 if (base_vertex == 0 && base_instance == 0) {
3049 emit_base_vertex_instance_bo(cmd_buffer, ANV_NULL_ADDRESS);
3050 } else {
3051 struct anv_state id_state =
3052 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 8, 4);
3053
3054 ((uint32_t *)id_state.map)[0] = base_vertex;
3055 ((uint32_t *)id_state.map)[1] = base_instance;
3056
3057 struct anv_address addr = {
3058 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
3059 .offset = id_state.offset,
3060 };
3061
3062 emit_base_vertex_instance_bo(cmd_buffer, addr);
3063 }
3064 }
3065
3066 static void
3067 emit_draw_index(struct anv_cmd_buffer *cmd_buffer, uint32_t draw_index)
3068 {
3069 struct anv_state state =
3070 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 4, 4);
3071
3072 ((uint32_t *)state.map)[0] = draw_index;
3073
3074 struct anv_address addr = {
3075 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
3076 .offset = state.offset,
3077 };
3078
3079 emit_vertex_bo(cmd_buffer, addr, 4, ANV_DRAWID_VB_INDEX);
3080 }
3081
3082 static void
3083 update_dirty_vbs_for_gen8_vb_flush(struct anv_cmd_buffer *cmd_buffer,
3084 uint32_t access_type)
3085 {
3086 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3087 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3088
3089 uint64_t vb_used = pipeline->vb_used;
3090 if (vs_prog_data->uses_firstvertex ||
3091 vs_prog_data->uses_baseinstance)
3092 vb_used |= 1ull << ANV_SVGS_VB_INDEX;
3093 if (vs_prog_data->uses_drawid)
3094 vb_used |= 1ull << ANV_DRAWID_VB_INDEX;
3095
3096 genX(cmd_buffer_update_dirty_vbs_for_gen8_vb_flush)(cmd_buffer,
3097 access_type == RANDOM,
3098 vb_used);
3099 }
3100
3101 void genX(CmdDraw)(
3102 VkCommandBuffer commandBuffer,
3103 uint32_t vertexCount,
3104 uint32_t instanceCount,
3105 uint32_t firstVertex,
3106 uint32_t firstInstance)
3107 {
3108 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3109 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3110 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3111
3112 if (anv_batch_has_error(&cmd_buffer->batch))
3113 return;
3114
3115 genX(cmd_buffer_flush_state)(cmd_buffer);
3116
3117 if (cmd_buffer->state.conditional_render_enabled)
3118 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3119
3120 if (vs_prog_data->uses_firstvertex ||
3121 vs_prog_data->uses_baseinstance)
3122 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
3123 if (vs_prog_data->uses_drawid)
3124 emit_draw_index(cmd_buffer, 0);
3125
3126 /* Emitting draw index or vertex index BOs may result in needing
3127 * additional VF cache flushes.
3128 */
3129 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3130
3131 /* Our implementation of VK_KHR_multiview uses instancing to draw the
3132 * different views. We need to multiply instanceCount by the view count.
3133 */
3134 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
3135
3136 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3137 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3138 prim.VertexAccessType = SEQUENTIAL;
3139 prim.PrimitiveTopologyType = pipeline->topology;
3140 prim.VertexCountPerInstance = vertexCount;
3141 prim.StartVertexLocation = firstVertex;
3142 prim.InstanceCount = instanceCount;
3143 prim.StartInstanceLocation = firstInstance;
3144 prim.BaseVertexLocation = 0;
3145 }
3146
3147 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, SEQUENTIAL);
3148 }
3149
3150 void genX(CmdDrawIndexed)(
3151 VkCommandBuffer commandBuffer,
3152 uint32_t indexCount,
3153 uint32_t instanceCount,
3154 uint32_t firstIndex,
3155 int32_t vertexOffset,
3156 uint32_t firstInstance)
3157 {
3158 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3159 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3160 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3161
3162 if (anv_batch_has_error(&cmd_buffer->batch))
3163 return;
3164
3165 genX(cmd_buffer_flush_state)(cmd_buffer);
3166
3167 if (cmd_buffer->state.conditional_render_enabled)
3168 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3169
3170 if (vs_prog_data->uses_firstvertex ||
3171 vs_prog_data->uses_baseinstance)
3172 emit_base_vertex_instance(cmd_buffer, vertexOffset, firstInstance);
3173 if (vs_prog_data->uses_drawid)
3174 emit_draw_index(cmd_buffer, 0);
3175
3176 /* Emitting draw index or vertex index BOs may result in needing
3177 * additional VF cache flushes.
3178 */
3179 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3180
3181 /* Our implementation of VK_KHR_multiview uses instancing to draw the
3182 * different views. We need to multiply instanceCount by the view count.
3183 */
3184 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
3185
3186 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3187 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3188 prim.VertexAccessType = RANDOM;
3189 prim.PrimitiveTopologyType = pipeline->topology;
3190 prim.VertexCountPerInstance = indexCount;
3191 prim.StartVertexLocation = firstIndex;
3192 prim.InstanceCount = instanceCount;
3193 prim.StartInstanceLocation = firstInstance;
3194 prim.BaseVertexLocation = vertexOffset;
3195 }
3196
3197 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, RANDOM);
3198 }
3199
3200 /* Auto-Draw / Indirect Registers */
3201 #define GEN7_3DPRIM_END_OFFSET 0x2420
3202 #define GEN7_3DPRIM_START_VERTEX 0x2430
3203 #define GEN7_3DPRIM_VERTEX_COUNT 0x2434
3204 #define GEN7_3DPRIM_INSTANCE_COUNT 0x2438
3205 #define GEN7_3DPRIM_START_INSTANCE 0x243C
3206 #define GEN7_3DPRIM_BASE_VERTEX 0x2440
3207
3208 void genX(CmdDrawIndirectByteCountEXT)(
3209 VkCommandBuffer commandBuffer,
3210 uint32_t instanceCount,
3211 uint32_t firstInstance,
3212 VkBuffer counterBuffer,
3213 VkDeviceSize counterBufferOffset,
3214 uint32_t counterOffset,
3215 uint32_t vertexStride)
3216 {
3217 #if GEN_IS_HASWELL || GEN_GEN >= 8
3218 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3219 ANV_FROM_HANDLE(anv_buffer, counter_buffer, counterBuffer);
3220 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3221 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3222
3223 /* firstVertex is always zero for this draw function */
3224 const uint32_t firstVertex = 0;
3225
3226 if (anv_batch_has_error(&cmd_buffer->batch))
3227 return;
3228
3229 genX(cmd_buffer_flush_state)(cmd_buffer);
3230
3231 if (vs_prog_data->uses_firstvertex ||
3232 vs_prog_data->uses_baseinstance)
3233 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
3234 if (vs_prog_data->uses_drawid)
3235 emit_draw_index(cmd_buffer, 0);
3236
3237 /* Emitting draw index or vertex index BOs may result in needing
3238 * additional VF cache flushes.
3239 */
3240 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3241
3242 /* Our implementation of VK_KHR_multiview uses instancing to draw the
3243 * different views. We need to multiply instanceCount by the view count.
3244 */
3245 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
3246
3247 struct gen_mi_builder b;
3248 gen_mi_builder_init(&b, &cmd_buffer->batch);
3249 struct gen_mi_value count =
3250 gen_mi_mem32(anv_address_add(counter_buffer->address,
3251 counterBufferOffset));
3252 if (counterOffset)
3253 count = gen_mi_isub(&b, count, gen_mi_imm(counterOffset));
3254 count = gen_mi_udiv32_imm(&b, count, vertexStride);
3255 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT), count);
3256
3257 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3258 gen_mi_imm(firstVertex));
3259 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT),
3260 gen_mi_imm(instanceCount));
3261 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3262 gen_mi_imm(firstInstance));
3263 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3264
3265 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3266 prim.IndirectParameterEnable = true;
3267 prim.VertexAccessType = SEQUENTIAL;
3268 prim.PrimitiveTopologyType = pipeline->topology;
3269 }
3270
3271 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, SEQUENTIAL);
3272 #endif /* GEN_IS_HASWELL || GEN_GEN >= 8 */
3273 }
3274
3275 static void
3276 load_indirect_parameters(struct anv_cmd_buffer *cmd_buffer,
3277 struct anv_address addr,
3278 bool indexed)
3279 {
3280 struct gen_mi_builder b;
3281 gen_mi_builder_init(&b, &cmd_buffer->batch);
3282
3283 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT),
3284 gen_mi_mem32(anv_address_add(addr, 0)));
3285
3286 struct gen_mi_value instance_count = gen_mi_mem32(anv_address_add(addr, 4));
3287 unsigned view_count = anv_subpass_view_count(cmd_buffer->state.subpass);
3288 if (view_count > 1) {
3289 #if GEN_IS_HASWELL || GEN_GEN >= 8
3290 instance_count = gen_mi_imul_imm(&b, instance_count, view_count);
3291 #else
3292 anv_finishme("Multiview + indirect draw requires MI_MATH; "
3293 "MI_MATH is not supported on Ivy Bridge");
3294 #endif
3295 }
3296 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT), instance_count);
3297
3298 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3299 gen_mi_mem32(anv_address_add(addr, 8)));
3300
3301 if (indexed) {
3302 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX),
3303 gen_mi_mem32(anv_address_add(addr, 12)));
3304 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3305 gen_mi_mem32(anv_address_add(addr, 16)));
3306 } else {
3307 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3308 gen_mi_mem32(anv_address_add(addr, 12)));
3309 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3310 }
3311 }
3312
3313 void genX(CmdDrawIndirect)(
3314 VkCommandBuffer commandBuffer,
3315 VkBuffer _buffer,
3316 VkDeviceSize offset,
3317 uint32_t drawCount,
3318 uint32_t stride)
3319 {
3320 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3321 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3322 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3323 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3324
3325 if (anv_batch_has_error(&cmd_buffer->batch))
3326 return;
3327
3328 genX(cmd_buffer_flush_state)(cmd_buffer);
3329
3330 if (cmd_buffer->state.conditional_render_enabled)
3331 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3332
3333 for (uint32_t i = 0; i < drawCount; i++) {
3334 struct anv_address draw = anv_address_add(buffer->address, offset);
3335
3336 if (vs_prog_data->uses_firstvertex ||
3337 vs_prog_data->uses_baseinstance)
3338 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3339 if (vs_prog_data->uses_drawid)
3340 emit_draw_index(cmd_buffer, i);
3341
3342 /* Emitting draw index or vertex index BOs may result in needing
3343 * additional VF cache flushes.
3344 */
3345 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3346
3347 load_indirect_parameters(cmd_buffer, draw, false);
3348
3349 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3350 prim.IndirectParameterEnable = true;
3351 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3352 prim.VertexAccessType = SEQUENTIAL;
3353 prim.PrimitiveTopologyType = pipeline->topology;
3354 }
3355
3356 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, SEQUENTIAL);
3357
3358 offset += stride;
3359 }
3360 }
3361
3362 void genX(CmdDrawIndexedIndirect)(
3363 VkCommandBuffer commandBuffer,
3364 VkBuffer _buffer,
3365 VkDeviceSize offset,
3366 uint32_t drawCount,
3367 uint32_t stride)
3368 {
3369 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3370 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3371 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3372 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3373
3374 if (anv_batch_has_error(&cmd_buffer->batch))
3375 return;
3376
3377 genX(cmd_buffer_flush_state)(cmd_buffer);
3378
3379 if (cmd_buffer->state.conditional_render_enabled)
3380 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3381
3382 for (uint32_t i = 0; i < drawCount; i++) {
3383 struct anv_address draw = anv_address_add(buffer->address, offset);
3384
3385 /* TODO: We need to stomp base vertex to 0 somehow */
3386 if (vs_prog_data->uses_firstvertex ||
3387 vs_prog_data->uses_baseinstance)
3388 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
3389 if (vs_prog_data->uses_drawid)
3390 emit_draw_index(cmd_buffer, i);
3391
3392 /* Emitting draw index or vertex index BOs may result in needing
3393 * additional VF cache flushes.
3394 */
3395 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3396
3397 load_indirect_parameters(cmd_buffer, draw, true);
3398
3399 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3400 prim.IndirectParameterEnable = true;
3401 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3402 prim.VertexAccessType = RANDOM;
3403 prim.PrimitiveTopologyType = pipeline->topology;
3404 }
3405
3406 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, RANDOM);
3407
3408 offset += stride;
3409 }
3410 }
3411
3412 #define TMP_DRAW_COUNT_REG 0x2670 /* MI_ALU_REG14 */
3413
3414 static void
3415 prepare_for_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3416 struct anv_address count_address,
3417 const bool conditional_render_enabled)
3418 {
3419 struct gen_mi_builder b;
3420 gen_mi_builder_init(&b, &cmd_buffer->batch);
3421
3422 if (conditional_render_enabled) {
3423 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3424 gen_mi_store(&b, gen_mi_reg64(TMP_DRAW_COUNT_REG),
3425 gen_mi_mem32(count_address));
3426 #endif
3427 } else {
3428 /* Upload the current draw count from the draw parameters buffer to
3429 * MI_PREDICATE_SRC0.
3430 */
3431 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
3432 gen_mi_mem32(count_address));
3433
3434 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC1 + 4), gen_mi_imm(0));
3435 }
3436 }
3437
3438 static void
3439 emit_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3440 uint32_t draw_index)
3441 {
3442 struct gen_mi_builder b;
3443 gen_mi_builder_init(&b, &cmd_buffer->batch);
3444
3445 /* Upload the index of the current primitive to MI_PREDICATE_SRC1. */
3446 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC1), gen_mi_imm(draw_index));
3447
3448 if (draw_index == 0) {
3449 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3450 mip.LoadOperation = LOAD_LOADINV;
3451 mip.CombineOperation = COMBINE_SET;
3452 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3453 }
3454 } else {
3455 /* While draw_index < draw_count the predicate's result will be
3456 * (draw_index == draw_count) ^ TRUE = TRUE
3457 * When draw_index == draw_count the result is
3458 * (TRUE) ^ TRUE = FALSE
3459 * After this all results will be:
3460 * (FALSE) ^ FALSE = FALSE
3461 */
3462 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3463 mip.LoadOperation = LOAD_LOAD;
3464 mip.CombineOperation = COMBINE_XOR;
3465 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3466 }
3467 }
3468 }
3469
3470 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3471 static void
3472 emit_draw_count_predicate_with_conditional_render(
3473 struct anv_cmd_buffer *cmd_buffer,
3474 uint32_t draw_index)
3475 {
3476 struct gen_mi_builder b;
3477 gen_mi_builder_init(&b, &cmd_buffer->batch);
3478
3479 struct gen_mi_value pred = gen_mi_ult(&b, gen_mi_imm(draw_index),
3480 gen_mi_reg64(TMP_DRAW_COUNT_REG));
3481 pred = gen_mi_iand(&b, pred, gen_mi_reg64(ANV_PREDICATE_RESULT_REG));
3482
3483 #if GEN_GEN >= 8
3484 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_RESULT), pred);
3485 #else
3486 /* MI_PREDICATE_RESULT is not whitelisted in i915 command parser
3487 * so we emit MI_PREDICATE to set it.
3488 */
3489
3490 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), pred);
3491 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3492
3493 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3494 mip.LoadOperation = LOAD_LOADINV;
3495 mip.CombineOperation = COMBINE_SET;
3496 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3497 }
3498 #endif
3499 }
3500 #endif
3501
3502 void genX(CmdDrawIndirectCountKHR)(
3503 VkCommandBuffer commandBuffer,
3504 VkBuffer _buffer,
3505 VkDeviceSize offset,
3506 VkBuffer _countBuffer,
3507 VkDeviceSize countBufferOffset,
3508 uint32_t maxDrawCount,
3509 uint32_t stride)
3510 {
3511 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3512 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3513 ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3514 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3515 struct anv_pipeline *pipeline = cmd_state->gfx.base.pipeline;
3516 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3517
3518 if (anv_batch_has_error(&cmd_buffer->batch))
3519 return;
3520
3521 genX(cmd_buffer_flush_state)(cmd_buffer);
3522
3523 struct anv_address count_address =
3524 anv_address_add(count_buffer->address, countBufferOffset);
3525
3526 prepare_for_draw_count_predicate(cmd_buffer, count_address,
3527 cmd_state->conditional_render_enabled);
3528
3529 for (uint32_t i = 0; i < maxDrawCount; i++) {
3530 struct anv_address draw = anv_address_add(buffer->address, offset);
3531
3532 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3533 if (cmd_state->conditional_render_enabled) {
3534 emit_draw_count_predicate_with_conditional_render(cmd_buffer, i);
3535 } else {
3536 emit_draw_count_predicate(cmd_buffer, i);
3537 }
3538 #else
3539 emit_draw_count_predicate(cmd_buffer, i);
3540 #endif
3541
3542 if (vs_prog_data->uses_firstvertex ||
3543 vs_prog_data->uses_baseinstance)
3544 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3545 if (vs_prog_data->uses_drawid)
3546 emit_draw_index(cmd_buffer, i);
3547
3548 /* Emitting draw index or vertex index BOs may result in needing
3549 * additional VF cache flushes.
3550 */
3551 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3552
3553 load_indirect_parameters(cmd_buffer, draw, false);
3554
3555 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3556 prim.IndirectParameterEnable = true;
3557 prim.PredicateEnable = true;
3558 prim.VertexAccessType = SEQUENTIAL;
3559 prim.PrimitiveTopologyType = pipeline->topology;
3560 }
3561
3562 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, SEQUENTIAL);
3563
3564 offset += stride;
3565 }
3566 }
3567
3568 void genX(CmdDrawIndexedIndirectCountKHR)(
3569 VkCommandBuffer commandBuffer,
3570 VkBuffer _buffer,
3571 VkDeviceSize offset,
3572 VkBuffer _countBuffer,
3573 VkDeviceSize countBufferOffset,
3574 uint32_t maxDrawCount,
3575 uint32_t stride)
3576 {
3577 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3578 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3579 ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3580 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3581 struct anv_pipeline *pipeline = cmd_state->gfx.base.pipeline;
3582 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3583
3584 if (anv_batch_has_error(&cmd_buffer->batch))
3585 return;
3586
3587 genX(cmd_buffer_flush_state)(cmd_buffer);
3588
3589 struct anv_address count_address =
3590 anv_address_add(count_buffer->address, countBufferOffset);
3591
3592 prepare_for_draw_count_predicate(cmd_buffer, count_address,
3593 cmd_state->conditional_render_enabled);
3594
3595 for (uint32_t i = 0; i < maxDrawCount; i++) {
3596 struct anv_address draw = anv_address_add(buffer->address, offset);
3597
3598 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3599 if (cmd_state->conditional_render_enabled) {
3600 emit_draw_count_predicate_with_conditional_render(cmd_buffer, i);
3601 } else {
3602 emit_draw_count_predicate(cmd_buffer, i);
3603 }
3604 #else
3605 emit_draw_count_predicate(cmd_buffer, i);
3606 #endif
3607
3608 /* TODO: We need to stomp base vertex to 0 somehow */
3609 if (vs_prog_data->uses_firstvertex ||
3610 vs_prog_data->uses_baseinstance)
3611 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
3612 if (vs_prog_data->uses_drawid)
3613 emit_draw_index(cmd_buffer, i);
3614
3615 /* Emitting draw index or vertex index BOs may result in needing
3616 * additional VF cache flushes.
3617 */
3618 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3619
3620 load_indirect_parameters(cmd_buffer, draw, true);
3621
3622 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3623 prim.IndirectParameterEnable = true;
3624 prim.PredicateEnable = true;
3625 prim.VertexAccessType = RANDOM;
3626 prim.PrimitiveTopologyType = pipeline->topology;
3627 }
3628
3629 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, RANDOM);
3630
3631 offset += stride;
3632 }
3633 }
3634
3635 void genX(CmdBeginTransformFeedbackEXT)(
3636 VkCommandBuffer commandBuffer,
3637 uint32_t firstCounterBuffer,
3638 uint32_t counterBufferCount,
3639 const VkBuffer* pCounterBuffers,
3640 const VkDeviceSize* pCounterBufferOffsets)
3641 {
3642 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3643
3644 assert(firstCounterBuffer < MAX_XFB_BUFFERS);
3645 assert(counterBufferCount <= MAX_XFB_BUFFERS);
3646 assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
3647
3648 /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
3649 *
3650 * "Ssoftware must ensure that no HW stream output operations can be in
3651 * process or otherwise pending at the point that the MI_LOAD/STORE
3652 * commands are processed. This will likely require a pipeline flush."
3653 */
3654 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3655 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3656
3657 for (uint32_t idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
3658 /* If we have a counter buffer, this is a resume so we need to load the
3659 * value into the streamout offset register. Otherwise, this is a begin
3660 * and we need to reset it to zero.
3661 */
3662 if (pCounterBuffers &&
3663 idx >= firstCounterBuffer &&
3664 idx - firstCounterBuffer < counterBufferCount &&
3665 pCounterBuffers[idx - firstCounterBuffer] != VK_NULL_HANDLE) {
3666 uint32_t cb_idx = idx - firstCounterBuffer;
3667 ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
3668 uint64_t offset = pCounterBufferOffsets ?
3669 pCounterBufferOffsets[cb_idx] : 0;
3670
3671 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3672 lrm.RegisterAddress = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3673 lrm.MemoryAddress = anv_address_add(counter_buffer->address,
3674 offset);
3675 }
3676 } else {
3677 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
3678 lri.RegisterOffset = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3679 lri.DataDWord = 0;
3680 }
3681 }
3682 }
3683
3684 cmd_buffer->state.xfb_enabled = true;
3685 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
3686 }
3687
3688 void genX(CmdEndTransformFeedbackEXT)(
3689 VkCommandBuffer commandBuffer,
3690 uint32_t firstCounterBuffer,
3691 uint32_t counterBufferCount,
3692 const VkBuffer* pCounterBuffers,
3693 const VkDeviceSize* pCounterBufferOffsets)
3694 {
3695 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3696
3697 assert(firstCounterBuffer < MAX_XFB_BUFFERS);
3698 assert(counterBufferCount <= MAX_XFB_BUFFERS);
3699 assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
3700
3701 /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
3702 *
3703 * "Ssoftware must ensure that no HW stream output operations can be in
3704 * process or otherwise pending at the point that the MI_LOAD/STORE
3705 * commands are processed. This will likely require a pipeline flush."
3706 */
3707 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3708 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3709
3710 for (uint32_t cb_idx = 0; cb_idx < counterBufferCount; cb_idx++) {
3711 unsigned idx = firstCounterBuffer + cb_idx;
3712
3713 /* If we have a counter buffer, this is a resume so we need to load the
3714 * value into the streamout offset register. Otherwise, this is a begin
3715 * and we need to reset it to zero.
3716 */
3717 if (pCounterBuffers &&
3718 cb_idx < counterBufferCount &&
3719 pCounterBuffers[cb_idx] != VK_NULL_HANDLE) {
3720 ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
3721 uint64_t offset = pCounterBufferOffsets ?
3722 pCounterBufferOffsets[cb_idx] : 0;
3723
3724 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_REGISTER_MEM), srm) {
3725 srm.MemoryAddress = anv_address_add(counter_buffer->address,
3726 offset);
3727 srm.RegisterAddress = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3728 }
3729 }
3730 }
3731
3732 cmd_buffer->state.xfb_enabled = false;
3733 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
3734 }
3735
3736 void
3737 genX(cmd_buffer_flush_compute_state)(struct anv_cmd_buffer *cmd_buffer)
3738 {
3739 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3740
3741 assert(pipeline->active_stages == VK_SHADER_STAGE_COMPUTE_BIT);
3742
3743 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
3744
3745 genX(flush_pipeline_select_gpgpu)(cmd_buffer);
3746
3747 #if GEN_GEN >= 12
3748 genX(cmd_buffer_aux_map_state)(cmd_buffer);
3749 #endif
3750
3751 if (cmd_buffer->state.compute.pipeline_dirty) {
3752 /* From the Sky Lake PRM Vol 2a, MEDIA_VFE_STATE:
3753 *
3754 * "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
3755 * the only bits that are changed are scoreboard related: Scoreboard
3756 * Enable, Scoreboard Type, Scoreboard Mask, Scoreboard * Delta. For
3757 * these scoreboard related states, a MEDIA_STATE_FLUSH is
3758 * sufficient."
3759 */
3760 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3761 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3762
3763 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
3764
3765 /* The workgroup size of the pipeline affects our push constant layout
3766 * so flag push constants as dirty if we change the pipeline.
3767 */
3768 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
3769 }
3770
3771 if ((cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_COMPUTE_BIT) ||
3772 cmd_buffer->state.compute.pipeline_dirty) {
3773 flush_descriptor_sets(cmd_buffer, pipeline);
3774
3775 uint32_t iface_desc_data_dw[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
3776 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
3777 .BindingTablePointer =
3778 cmd_buffer->state.binding_tables[MESA_SHADER_COMPUTE].offset,
3779 .SamplerStatePointer =
3780 cmd_buffer->state.samplers[MESA_SHADER_COMPUTE].offset,
3781 };
3782 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL, iface_desc_data_dw, &desc);
3783
3784 struct anv_state state =
3785 anv_cmd_buffer_merge_dynamic(cmd_buffer, iface_desc_data_dw,
3786 pipeline->interface_descriptor_data,
3787 GENX(INTERFACE_DESCRIPTOR_DATA_length),
3788 64);
3789
3790 uint32_t size = GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
3791 anv_batch_emit(&cmd_buffer->batch,
3792 GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), mid) {
3793 mid.InterfaceDescriptorTotalLength = size;
3794 mid.InterfaceDescriptorDataStartAddress = state.offset;
3795 }
3796 }
3797
3798 if (cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_COMPUTE_BIT) {
3799 struct anv_state push_state =
3800 anv_cmd_buffer_cs_push_constants(cmd_buffer);
3801
3802 if (push_state.alloc_size) {
3803 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_CURBE_LOAD), curbe) {
3804 curbe.CURBETotalDataLength = push_state.alloc_size;
3805 curbe.CURBEDataStartAddress = push_state.offset;
3806 }
3807 }
3808
3809 cmd_buffer->state.push_constants_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
3810 }
3811
3812 cmd_buffer->state.compute.pipeline_dirty = false;
3813
3814 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3815 }
3816
3817 #if GEN_GEN == 7
3818
3819 static VkResult
3820 verify_cmd_parser(const struct anv_device *device,
3821 int required_version,
3822 const char *function)
3823 {
3824 if (device->instance->physicalDevice.cmd_parser_version < required_version) {
3825 return vk_errorf(device->instance, device->instance,
3826 VK_ERROR_FEATURE_NOT_PRESENT,
3827 "cmd parser version %d is required for %s",
3828 required_version, function);
3829 } else {
3830 return VK_SUCCESS;
3831 }
3832 }
3833
3834 #endif
3835
3836 static void
3837 anv_cmd_buffer_push_base_group_id(struct anv_cmd_buffer *cmd_buffer,
3838 uint32_t baseGroupX,
3839 uint32_t baseGroupY,
3840 uint32_t baseGroupZ)
3841 {
3842 if (anv_batch_has_error(&cmd_buffer->batch))
3843 return;
3844
3845 struct anv_push_constants *push =
3846 &cmd_buffer->state.push_constants[MESA_SHADER_COMPUTE];
3847 if (push->cs.base_work_group_id[0] != baseGroupX ||
3848 push->cs.base_work_group_id[1] != baseGroupY ||
3849 push->cs.base_work_group_id[2] != baseGroupZ) {
3850 push->cs.base_work_group_id[0] = baseGroupX;
3851 push->cs.base_work_group_id[1] = baseGroupY;
3852 push->cs.base_work_group_id[2] = baseGroupZ;
3853
3854 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
3855 }
3856 }
3857
3858 void genX(CmdDispatch)(
3859 VkCommandBuffer commandBuffer,
3860 uint32_t x,
3861 uint32_t y,
3862 uint32_t z)
3863 {
3864 genX(CmdDispatchBase)(commandBuffer, 0, 0, 0, x, y, z);
3865 }
3866
3867 void genX(CmdDispatchBase)(
3868 VkCommandBuffer commandBuffer,
3869 uint32_t baseGroupX,
3870 uint32_t baseGroupY,
3871 uint32_t baseGroupZ,
3872 uint32_t groupCountX,
3873 uint32_t groupCountY,
3874 uint32_t groupCountZ)
3875 {
3876 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3877 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3878 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3879
3880 anv_cmd_buffer_push_base_group_id(cmd_buffer, baseGroupX,
3881 baseGroupY, baseGroupZ);
3882
3883 if (anv_batch_has_error(&cmd_buffer->batch))
3884 return;
3885
3886 if (prog_data->uses_num_work_groups) {
3887 struct anv_state state =
3888 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 12, 4);
3889 uint32_t *sizes = state.map;
3890 sizes[0] = groupCountX;
3891 sizes[1] = groupCountY;
3892 sizes[2] = groupCountZ;
3893 cmd_buffer->state.compute.num_workgroups = (struct anv_address) {
3894 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
3895 .offset = state.offset,
3896 };
3897
3898 /* The num_workgroups buffer goes in the binding table */
3899 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
3900 }
3901
3902 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3903
3904 if (cmd_buffer->state.conditional_render_enabled)
3905 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3906
3907 anv_batch_emit(&cmd_buffer->batch, GENX(GPGPU_WALKER), ggw) {
3908 ggw.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3909 ggw.SIMDSize = prog_data->simd_size / 16;
3910 ggw.ThreadDepthCounterMaximum = 0;
3911 ggw.ThreadHeightCounterMaximum = 0;
3912 ggw.ThreadWidthCounterMaximum = prog_data->threads - 1;
3913 ggw.ThreadGroupIDXDimension = groupCountX;
3914 ggw.ThreadGroupIDYDimension = groupCountY;
3915 ggw.ThreadGroupIDZDimension = groupCountZ;
3916 ggw.RightExecutionMask = pipeline->cs_right_mask;
3917 ggw.BottomExecutionMask = 0xffffffff;
3918 }
3919
3920 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_STATE_FLUSH), msf);
3921 }
3922
3923 #define GPGPU_DISPATCHDIMX 0x2500
3924 #define GPGPU_DISPATCHDIMY 0x2504
3925 #define GPGPU_DISPATCHDIMZ 0x2508
3926
3927 void genX(CmdDispatchIndirect)(
3928 VkCommandBuffer commandBuffer,
3929 VkBuffer _buffer,
3930 VkDeviceSize offset)
3931 {
3932 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3933 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3934 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3935 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3936 struct anv_address addr = anv_address_add(buffer->address, offset);
3937 struct anv_batch *batch = &cmd_buffer->batch;
3938
3939 anv_cmd_buffer_push_base_group_id(cmd_buffer, 0, 0, 0);
3940
3941 #if GEN_GEN == 7
3942 /* Linux 4.4 added command parser version 5 which allows the GPGPU
3943 * indirect dispatch registers to be written.
3944 */
3945 if (verify_cmd_parser(cmd_buffer->device, 5,
3946 "vkCmdDispatchIndirect") != VK_SUCCESS)
3947 return;
3948 #endif
3949
3950 if (prog_data->uses_num_work_groups) {
3951 cmd_buffer->state.compute.num_workgroups = addr;
3952
3953 /* The num_workgroups buffer goes in the binding table */
3954 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
3955 }
3956
3957 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3958
3959 struct gen_mi_builder b;
3960 gen_mi_builder_init(&b, &cmd_buffer->batch);
3961
3962 struct gen_mi_value size_x = gen_mi_mem32(anv_address_add(addr, 0));
3963 struct gen_mi_value size_y = gen_mi_mem32(anv_address_add(addr, 4));
3964 struct gen_mi_value size_z = gen_mi_mem32(anv_address_add(addr, 8));
3965
3966 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMX), size_x);
3967 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMY), size_y);
3968 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMZ), size_z);
3969
3970 #if GEN_GEN <= 7
3971 /* predicate = (compute_dispatch_indirect_x_size == 0); */
3972 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), size_x);
3973 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3974 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3975 mip.LoadOperation = LOAD_LOAD;
3976 mip.CombineOperation = COMBINE_SET;
3977 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3978 }
3979
3980 /* predicate |= (compute_dispatch_indirect_y_size == 0); */
3981 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_y);
3982 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3983 mip.LoadOperation = LOAD_LOAD;
3984 mip.CombineOperation = COMBINE_OR;
3985 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3986 }
3987
3988 /* predicate |= (compute_dispatch_indirect_z_size == 0); */
3989 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_z);
3990 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3991 mip.LoadOperation = LOAD_LOAD;
3992 mip.CombineOperation = COMBINE_OR;
3993 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3994 }
3995
3996 /* predicate = !predicate; */
3997 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3998 mip.LoadOperation = LOAD_LOADINV;
3999 mip.CombineOperation = COMBINE_OR;
4000 mip.CompareOperation = COMPARE_FALSE;
4001 }
4002
4003 #if GEN_IS_HASWELL
4004 if (cmd_buffer->state.conditional_render_enabled) {
4005 /* predicate &= !(conditional_rendering_predicate == 0); */
4006 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0),
4007 gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
4008 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
4009 mip.LoadOperation = LOAD_LOADINV;
4010 mip.CombineOperation = COMBINE_AND;
4011 mip.CompareOperation = COMPARE_SRCS_EQUAL;
4012 }
4013 }
4014 #endif
4015
4016 #else /* GEN_GEN > 7 */
4017 if (cmd_buffer->state.conditional_render_enabled)
4018 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
4019 #endif
4020
4021 anv_batch_emit(batch, GENX(GPGPU_WALKER), ggw) {
4022 ggw.IndirectParameterEnable = true;
4023 ggw.PredicateEnable = GEN_GEN <= 7 ||
4024 cmd_buffer->state.conditional_render_enabled;
4025 ggw.SIMDSize = prog_data->simd_size / 16;
4026 ggw.ThreadDepthCounterMaximum = 0;
4027 ggw.ThreadHeightCounterMaximum = 0;
4028 ggw.ThreadWidthCounterMaximum = prog_data->threads - 1;
4029 ggw.RightExecutionMask = pipeline->cs_right_mask;
4030 ggw.BottomExecutionMask = 0xffffffff;
4031 }
4032
4033 anv_batch_emit(batch, GENX(MEDIA_STATE_FLUSH), msf);
4034 }
4035
4036 static void
4037 genX(flush_pipeline_select)(struct anv_cmd_buffer *cmd_buffer,
4038 uint32_t pipeline)
4039 {
4040 UNUSED const struct gen_device_info *devinfo = &cmd_buffer->device->info;
4041
4042 if (cmd_buffer->state.current_pipeline == pipeline)
4043 return;
4044
4045 #if GEN_GEN >= 8 && GEN_GEN < 10
4046 /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
4047 *
4048 * Software must clear the COLOR_CALC_STATE Valid field in
4049 * 3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
4050 * with Pipeline Select set to GPGPU.
4051 *
4052 * The internal hardware docs recommend the same workaround for Gen9
4053 * hardware too.
4054 */
4055 if (pipeline == GPGPU)
4056 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
4057 #endif
4058
4059 #if GEN_GEN == 9
4060 if (pipeline == _3D) {
4061 /* There is a mid-object preemption workaround which requires you to
4062 * re-emit MEDIA_VFE_STATE after switching from GPGPU to 3D. However,
4063 * even without preemption, we have issues with geometry flickering when
4064 * GPGPU and 3D are back-to-back and this seems to fix it. We don't
4065 * really know why.
4066 */
4067 const uint32_t subslices =
4068 MAX2(cmd_buffer->device->instance->physicalDevice.subslice_total, 1);
4069 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_VFE_STATE), vfe) {
4070 vfe.MaximumNumberofThreads =
4071 devinfo->max_cs_threads * subslices - 1;
4072 vfe.NumberofURBEntries = 2;
4073 vfe.URBEntryAllocationSize = 2;
4074 }
4075
4076 /* We just emitted a dummy MEDIA_VFE_STATE so now that packet is
4077 * invalid. Set the compute pipeline to dirty to force a re-emit of the
4078 * pipeline in case we get back-to-back dispatch calls with the same
4079 * pipeline and a PIPELINE_SELECT in between.
4080 */
4081 cmd_buffer->state.compute.pipeline_dirty = true;
4082 }
4083 #endif
4084
4085 /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
4086 * PIPELINE_SELECT [DevBWR+]":
4087 *
4088 * Project: DEVSNB+
4089 *
4090 * Software must ensure all the write caches are flushed through a
4091 * stalling PIPE_CONTROL command followed by another PIPE_CONTROL
4092 * command to invalidate read only caches prior to programming
4093 * MI_PIPELINE_SELECT command to change the Pipeline Select Mode.
4094 */
4095 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4096 pc.RenderTargetCacheFlushEnable = true;
4097 pc.DepthCacheFlushEnable = true;
4098 pc.DCFlushEnable = true;
4099 pc.PostSyncOperation = NoWrite;
4100 pc.CommandStreamerStallEnable = true;
4101 #if GEN_GEN >= 12
4102 pc.TileCacheFlushEnable = true;
4103 #endif
4104 }
4105
4106 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4107 pc.TextureCacheInvalidationEnable = true;
4108 pc.ConstantCacheInvalidationEnable = true;
4109 pc.StateCacheInvalidationEnable = true;
4110 pc.InstructionCacheInvalidateEnable = true;
4111 pc.PostSyncOperation = NoWrite;
4112 #if GEN_GEN >= 12
4113 pc.TileCacheFlushEnable = true;
4114 #endif
4115 }
4116
4117 anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
4118 #if GEN_GEN >= 9
4119 ps.MaskBits = 3;
4120 #endif
4121 ps.PipelineSelection = pipeline;
4122 }
4123
4124 #if GEN_GEN == 9
4125 if (devinfo->is_geminilake) {
4126 /* Project: DevGLK
4127 *
4128 * "This chicken bit works around a hardware issue with barrier logic
4129 * encountered when switching between GPGPU and 3D pipelines. To
4130 * workaround the issue, this mode bit should be set after a pipeline
4131 * is selected."
4132 */
4133 uint32_t scec;
4134 anv_pack_struct(&scec, GENX(SLICE_COMMON_ECO_CHICKEN1),
4135 .GLKBarrierMode =
4136 pipeline == GPGPU ? GLK_BARRIER_MODE_GPGPU
4137 : GLK_BARRIER_MODE_3D_HULL,
4138 .GLKBarrierModeMask = 1);
4139 emit_lri(&cmd_buffer->batch, GENX(SLICE_COMMON_ECO_CHICKEN1_num), scec);
4140 }
4141 #endif
4142
4143 cmd_buffer->state.current_pipeline = pipeline;
4144 }
4145
4146 void
4147 genX(flush_pipeline_select_3d)(struct anv_cmd_buffer *cmd_buffer)
4148 {
4149 genX(flush_pipeline_select)(cmd_buffer, _3D);
4150 }
4151
4152 void
4153 genX(flush_pipeline_select_gpgpu)(struct anv_cmd_buffer *cmd_buffer)
4154 {
4155 genX(flush_pipeline_select)(cmd_buffer, GPGPU);
4156 }
4157
4158 void
4159 genX(cmd_buffer_emit_gen7_depth_flush)(struct anv_cmd_buffer *cmd_buffer)
4160 {
4161 if (GEN_GEN >= 8)
4162 return;
4163
4164 /* From the Haswell PRM, documentation for 3DSTATE_DEPTH_BUFFER:
4165 *
4166 * "Restriction: Prior to changing Depth/Stencil Buffer state (i.e., any
4167 * combination of 3DSTATE_DEPTH_BUFFER, 3DSTATE_CLEAR_PARAMS,
4168 * 3DSTATE_STENCIL_BUFFER, 3DSTATE_HIER_DEPTH_BUFFER) SW must first
4169 * issue a pipelined depth stall (PIPE_CONTROL with Depth Stall bit
4170 * set), followed by a pipelined depth cache flush (PIPE_CONTROL with
4171 * Depth Flush Bit set, followed by another pipelined depth stall
4172 * (PIPE_CONTROL with Depth Stall Bit set), unless SW can otherwise
4173 * guarantee that the pipeline from WM onwards is already flushed (e.g.,
4174 * via a preceding MI_FLUSH)."
4175 */
4176 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
4177 pipe.DepthStallEnable = true;
4178 }
4179 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
4180 pipe.DepthCacheFlushEnable = true;
4181 #if GEN_GEN >= 12
4182 pipe.TileCacheFlushEnable = true;
4183 #endif
4184 }
4185 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
4186 pipe.DepthStallEnable = true;
4187 }
4188 }
4189
4190 /* From the Skylake PRM, 3DSTATE_VERTEX_BUFFERS:
4191 *
4192 * "The VF cache needs to be invalidated before binding and then using
4193 * Vertex Buffers that overlap with any previously bound Vertex Buffer
4194 * (at a 64B granularity) since the last invalidation. A VF cache
4195 * invalidate is performed by setting the "VF Cache Invalidation Enable"
4196 * bit in PIPE_CONTROL."
4197 *
4198 * This is implemented by carefully tracking all vertex and index buffer
4199 * bindings and flushing if the cache ever ends up with a range in the cache
4200 * that would exceed 4 GiB. This is implemented in three parts:
4201 *
4202 * 1. genX(cmd_buffer_set_binding_for_gen8_vb_flush)() which must be called
4203 * every time a 3DSTATE_VERTEX_BUFFER packet is emitted and informs the
4204 * tracking code of the new binding. If this new binding would cause
4205 * the cache to have a too-large range on the next draw call, a pipeline
4206 * stall and VF cache invalidate are added to pending_pipeline_bits.
4207 *
4208 * 2. genX(cmd_buffer_apply_pipe_flushes)() resets the cache tracking to
4209 * empty whenever we emit a VF invalidate.
4210 *
4211 * 3. genX(cmd_buffer_update_dirty_vbs_for_gen8_vb_flush)() must be called
4212 * after every 3DPRIMITIVE and copies the bound range into the dirty
4213 * range for each used buffer. This has to be a separate step because
4214 * we don't always re-bind all buffers and so 1. can't know which
4215 * buffers are actually bound.
4216 */
4217 void
4218 genX(cmd_buffer_set_binding_for_gen8_vb_flush)(struct anv_cmd_buffer *cmd_buffer,
4219 int vb_index,
4220 struct anv_address vb_address,
4221 uint32_t vb_size)
4222 {
4223 if (GEN_GEN < 8 || GEN_GEN > 9 ||
4224 !cmd_buffer->device->instance->physicalDevice.use_softpin)
4225 return;
4226
4227 struct anv_vb_cache_range *bound, *dirty;
4228 if (vb_index == -1) {
4229 bound = &cmd_buffer->state.gfx.ib_bound_range;
4230 dirty = &cmd_buffer->state.gfx.ib_dirty_range;
4231 } else {
4232 assert(vb_index >= 0);
4233 assert(vb_index < ARRAY_SIZE(cmd_buffer->state.gfx.vb_bound_ranges));
4234 assert(vb_index < ARRAY_SIZE(cmd_buffer->state.gfx.vb_dirty_ranges));
4235 bound = &cmd_buffer->state.gfx.vb_bound_ranges[vb_index];
4236 dirty = &cmd_buffer->state.gfx.vb_dirty_ranges[vb_index];
4237 }
4238
4239 if (vb_size == 0) {
4240 bound->start = 0;
4241 bound->end = 0;
4242 return;
4243 }
4244
4245 assert(vb_address.bo && (vb_address.bo->flags & EXEC_OBJECT_PINNED));
4246 bound->start = gen_48b_address(anv_address_physical(vb_address));
4247 bound->end = bound->start + vb_size;
4248 assert(bound->end > bound->start); /* No overflow */
4249
4250 /* Align everything to a cache line */
4251 bound->start &= ~(64ull - 1ull);
4252 bound->end = align_u64(bound->end, 64);
4253
4254 /* Compute the dirty range */
4255 dirty->start = MIN2(dirty->start, bound->start);
4256 dirty->end = MAX2(dirty->end, bound->end);
4257
4258 /* If our range is larger than 32 bits, we have to flush */
4259 assert(bound->end - bound->start <= (1ull << 32));
4260 if (dirty->end - dirty->start > (1ull << 32)) {
4261 cmd_buffer->state.pending_pipe_bits |=
4262 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
4263 }
4264 }
4265
4266 void
4267 genX(cmd_buffer_update_dirty_vbs_for_gen8_vb_flush)(struct anv_cmd_buffer *cmd_buffer,
4268 uint32_t access_type,
4269 uint64_t vb_used)
4270 {
4271 if (GEN_GEN < 8 || GEN_GEN > 9 ||
4272 !cmd_buffer->device->instance->physicalDevice.use_softpin)
4273 return;
4274
4275 if (access_type == RANDOM) {
4276 /* We have an index buffer */
4277 struct anv_vb_cache_range *bound = &cmd_buffer->state.gfx.ib_bound_range;
4278 struct anv_vb_cache_range *dirty = &cmd_buffer->state.gfx.ib_dirty_range;
4279
4280 if (bound->end > bound->start) {
4281 dirty->start = MIN2(dirty->start, bound->start);
4282 dirty->end = MAX2(dirty->end, bound->end);
4283 }
4284 }
4285
4286 uint64_t mask = vb_used;
4287 while (mask) {
4288 int i = u_bit_scan64(&mask);
4289 assert(i >= 0);
4290 assert(i < ARRAY_SIZE(cmd_buffer->state.gfx.vb_bound_ranges));
4291 assert(i < ARRAY_SIZE(cmd_buffer->state.gfx.vb_dirty_ranges));
4292
4293 struct anv_vb_cache_range *bound, *dirty;
4294 bound = &cmd_buffer->state.gfx.vb_bound_ranges[i];
4295 dirty = &cmd_buffer->state.gfx.vb_dirty_ranges[i];
4296
4297 if (bound->end > bound->start) {
4298 dirty->start = MIN2(dirty->start, bound->start);
4299 dirty->end = MAX2(dirty->end, bound->end);
4300 }
4301 }
4302 }
4303
4304 /**
4305 * Update the pixel hashing modes that determine the balancing of PS threads
4306 * across subslices and slices.
4307 *
4308 * \param width Width bound of the rendering area (already scaled down if \p
4309 * scale is greater than 1).
4310 * \param height Height bound of the rendering area (already scaled down if \p
4311 * scale is greater than 1).
4312 * \param scale The number of framebuffer samples that could potentially be
4313 * affected by an individual channel of the PS thread. This is
4314 * typically one for single-sampled rendering, but for operations
4315 * like CCS resolves and fast clears a single PS invocation may
4316 * update a huge number of pixels, in which case a finer
4317 * balancing is desirable in order to maximally utilize the
4318 * bandwidth available. UINT_MAX can be used as shorthand for
4319 * "finest hashing mode available".
4320 */
4321 void
4322 genX(cmd_buffer_emit_hashing_mode)(struct anv_cmd_buffer *cmd_buffer,
4323 unsigned width, unsigned height,
4324 unsigned scale)
4325 {
4326 #if GEN_GEN == 9
4327 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
4328 const unsigned slice_hashing[] = {
4329 /* Because all Gen9 platforms with more than one slice require
4330 * three-way subslice hashing, a single "normal" 16x16 slice hashing
4331 * block is guaranteed to suffer from substantial imbalance, with one
4332 * subslice receiving twice as much work as the other two in the
4333 * slice.
4334 *
4335 * The performance impact of that would be particularly severe when
4336 * three-way hashing is also in use for slice balancing (which is the
4337 * case for all Gen9 GT4 platforms), because one of the slices
4338 * receives one every three 16x16 blocks in either direction, which
4339 * is roughly the periodicity of the underlying subslice imbalance
4340 * pattern ("roughly" because in reality the hardware's
4341 * implementation of three-way hashing doesn't do exact modulo 3
4342 * arithmetic, which somewhat decreases the magnitude of this effect
4343 * in practice). This leads to a systematic subslice imbalance
4344 * within that slice regardless of the size of the primitive. The
4345 * 32x32 hashing mode guarantees that the subslice imbalance within a
4346 * single slice hashing block is minimal, largely eliminating this
4347 * effect.
4348 */
4349 _32x32,
4350 /* Finest slice hashing mode available. */
4351 NORMAL
4352 };
4353 const unsigned subslice_hashing[] = {
4354 /* 16x16 would provide a slight cache locality benefit especially
4355 * visible in the sampler L1 cache efficiency of low-bandwidth
4356 * non-LLC platforms, but it comes at the cost of greater subslice
4357 * imbalance for primitives of dimensions approximately intermediate
4358 * between 16x4 and 16x16.
4359 */
4360 _16x4,
4361 /* Finest subslice hashing mode available. */
4362 _8x4
4363 };
4364 /* Dimensions of the smallest hashing block of a given hashing mode. If
4365 * the rendering area is smaller than this there can't possibly be any
4366 * benefit from switching to this mode, so we optimize out the
4367 * transition.
4368 */
4369 const unsigned min_size[][2] = {
4370 { 16, 4 },
4371 { 8, 4 }
4372 };
4373 const unsigned idx = scale > 1;
4374
4375 if (cmd_buffer->state.current_hash_scale != scale &&
4376 (width > min_size[idx][0] || height > min_size[idx][1])) {
4377 uint32_t gt_mode;
4378
4379 anv_pack_struct(&gt_mode, GENX(GT_MODE),
4380 .SliceHashing = (devinfo->num_slices > 1 ? slice_hashing[idx] : 0),
4381 .SliceHashingMask = (devinfo->num_slices > 1 ? -1 : 0),
4382 .SubsliceHashing = subslice_hashing[idx],
4383 .SubsliceHashingMask = -1);
4384
4385 cmd_buffer->state.pending_pipe_bits |=
4386 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
4387 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4388
4389 emit_lri(&cmd_buffer->batch, GENX(GT_MODE_num), gt_mode);
4390
4391 cmd_buffer->state.current_hash_scale = scale;
4392 }
4393 #endif
4394 }
4395
4396 static void
4397 cmd_buffer_emit_depth_stencil(struct anv_cmd_buffer *cmd_buffer)
4398 {
4399 struct anv_device *device = cmd_buffer->device;
4400 const struct anv_image_view *iview =
4401 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
4402 const struct anv_image *image = iview ? iview->image : NULL;
4403
4404 /* FIXME: Width and Height are wrong */
4405
4406 genX(cmd_buffer_emit_gen7_depth_flush)(cmd_buffer);
4407
4408 uint32_t *dw = anv_batch_emit_dwords(&cmd_buffer->batch,
4409 device->isl_dev.ds.size / 4);
4410 if (dw == NULL)
4411 return;
4412
4413 struct isl_depth_stencil_hiz_emit_info info = { };
4414
4415 if (iview)
4416 info.view = &iview->planes[0].isl;
4417
4418 if (image && (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
4419 uint32_t depth_plane =
4420 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_DEPTH_BIT);
4421 const struct anv_surface *surface = &image->planes[depth_plane].surface;
4422
4423 info.depth_surf = &surface->isl;
4424
4425 info.depth_address =
4426 anv_batch_emit_reloc(&cmd_buffer->batch,
4427 dw + device->isl_dev.ds.depth_offset / 4,
4428 image->planes[depth_plane].address.bo,
4429 image->planes[depth_plane].address.offset +
4430 surface->offset);
4431 info.mocs =
4432 anv_mocs_for_bo(device, image->planes[depth_plane].address.bo);
4433
4434 const uint32_t ds =
4435 cmd_buffer->state.subpass->depth_stencil_attachment->attachment;
4436 info.hiz_usage = cmd_buffer->state.attachments[ds].aux_usage;
4437 if (info.hiz_usage == ISL_AUX_USAGE_HIZ) {
4438 info.hiz_surf = &image->planes[depth_plane].aux_surface.isl;
4439
4440 info.hiz_address =
4441 anv_batch_emit_reloc(&cmd_buffer->batch,
4442 dw + device->isl_dev.ds.hiz_offset / 4,
4443 image->planes[depth_plane].address.bo,
4444 image->planes[depth_plane].address.offset +
4445 image->planes[depth_plane].aux_surface.offset);
4446
4447 info.depth_clear_value = ANV_HZ_FC_VAL;
4448 }
4449 }
4450
4451 if (image && (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
4452 uint32_t stencil_plane =
4453 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_STENCIL_BIT);
4454 const struct anv_surface *surface = &image->planes[stencil_plane].surface;
4455
4456 info.stencil_surf = &surface->isl;
4457
4458 info.stencil_address =
4459 anv_batch_emit_reloc(&cmd_buffer->batch,
4460 dw + device->isl_dev.ds.stencil_offset / 4,
4461 image->planes[stencil_plane].address.bo,
4462 image->planes[stencil_plane].address.offset +
4463 surface->offset);
4464 info.mocs =
4465 anv_mocs_for_bo(device, image->planes[stencil_plane].address.bo);
4466 }
4467
4468 isl_emit_depth_stencil_hiz_s(&device->isl_dev, dw, &info);
4469
4470 if (GEN_GEN >= 12) {
4471 /* GEN:BUG:1408224581
4472 *
4473 * Workaround: Gen12LP Astep only An additional pipe control with
4474 * post-sync = store dword operation would be required.( w/a is to
4475 * have an additional pipe control after the stencil state whenever
4476 * the surface state bits of this state is changing).
4477 */
4478 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4479 pc.PostSyncOperation = WriteImmediateData;
4480 pc.Address =
4481 (struct anv_address) { cmd_buffer->device->workaround_bo, 0 };
4482 }
4483 }
4484 cmd_buffer->state.hiz_enabled = info.hiz_usage == ISL_AUX_USAGE_HIZ;
4485 }
4486
4487 /**
4488 * This ANDs the view mask of the current subpass with the pending clear
4489 * views in the attachment to get the mask of views active in the subpass
4490 * that still need to be cleared.
4491 */
4492 static inline uint32_t
4493 get_multiview_subpass_clear_mask(const struct anv_cmd_state *cmd_state,
4494 const struct anv_attachment_state *att_state)
4495 {
4496 return cmd_state->subpass->view_mask & att_state->pending_clear_views;
4497 }
4498
4499 static inline bool
4500 do_first_layer_clear(const struct anv_cmd_state *cmd_state,
4501 const struct anv_attachment_state *att_state)
4502 {
4503 if (!cmd_state->subpass->view_mask)
4504 return true;
4505
4506 uint32_t pending_clear_mask =
4507 get_multiview_subpass_clear_mask(cmd_state, att_state);
4508
4509 return pending_clear_mask & 1;
4510 }
4511
4512 static inline bool
4513 current_subpass_is_last_for_attachment(const struct anv_cmd_state *cmd_state,
4514 uint32_t att_idx)
4515 {
4516 const uint32_t last_subpass_idx =
4517 cmd_state->pass->attachments[att_idx].last_subpass_idx;
4518 const struct anv_subpass *last_subpass =
4519 &cmd_state->pass->subpasses[last_subpass_idx];
4520 return last_subpass == cmd_state->subpass;
4521 }
4522
4523 static void
4524 cmd_buffer_begin_subpass(struct anv_cmd_buffer *cmd_buffer,
4525 uint32_t subpass_id)
4526 {
4527 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4528 struct anv_subpass *subpass = &cmd_state->pass->subpasses[subpass_id];
4529 cmd_state->subpass = subpass;
4530
4531 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
4532
4533 /* Our implementation of VK_KHR_multiview uses instancing to draw the
4534 * different views. If the client asks for instancing, we need to use the
4535 * Instance Data Step Rate to ensure that we repeat the client's
4536 * per-instance data once for each view. Since this bit is in
4537 * VERTEX_BUFFER_STATE on gen7, we need to dirty vertex buffers at the top
4538 * of each subpass.
4539 */
4540 if (GEN_GEN == 7)
4541 cmd_buffer->state.gfx.vb_dirty |= ~0;
4542
4543 /* It is possible to start a render pass with an old pipeline. Because the
4544 * render pass and subpass index are both baked into the pipeline, this is
4545 * highly unlikely. In order to do so, it requires that you have a render
4546 * pass with a single subpass and that you use that render pass twice
4547 * back-to-back and use the same pipeline at the start of the second render
4548 * pass as at the end of the first. In order to avoid unpredictable issues
4549 * with this edge case, we just dirty the pipeline at the start of every
4550 * subpass.
4551 */
4552 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_PIPELINE;
4553
4554 /* Accumulate any subpass flushes that need to happen before the subpass */
4555 cmd_buffer->state.pending_pipe_bits |=
4556 cmd_buffer->state.pass->subpass_flushes[subpass_id];
4557
4558 VkRect2D render_area = cmd_buffer->state.render_area;
4559 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
4560
4561 bool is_multiview = subpass->view_mask != 0;
4562
4563 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
4564 const uint32_t a = subpass->attachments[i].attachment;
4565 if (a == VK_ATTACHMENT_UNUSED)
4566 continue;
4567
4568 assert(a < cmd_state->pass->attachment_count);
4569 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
4570
4571 struct anv_image_view *iview = cmd_state->attachments[a].image_view;
4572 const struct anv_image *image = iview->image;
4573
4574 /* A resolve is necessary before use as an input attachment if the clear
4575 * color or auxiliary buffer usage isn't supported by the sampler.
4576 */
4577 const bool input_needs_resolve =
4578 (att_state->fast_clear && !att_state->clear_color_is_zero_one) ||
4579 att_state->input_aux_usage != att_state->aux_usage;
4580
4581 VkImageLayout target_layout, target_stencil_layout;
4582 if (iview->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV &&
4583 !input_needs_resolve) {
4584 /* Layout transitions before the final only help to enable sampling
4585 * as an input attachment. If the input attachment supports sampling
4586 * using the auxiliary surface, we can skip such transitions by
4587 * making the target layout one that is CCS-aware.
4588 */
4589 target_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
4590 } else {
4591 target_layout = subpass->attachments[i].layout;
4592 target_stencil_layout = subpass->attachments[i].stencil_layout;
4593 }
4594
4595 uint32_t base_layer, layer_count;
4596 if (image->type == VK_IMAGE_TYPE_3D) {
4597 base_layer = 0;
4598 layer_count = anv_minify(iview->image->extent.depth,
4599 iview->planes[0].isl.base_level);
4600 } else {
4601 base_layer = iview->planes[0].isl.base_array_layer;
4602 layer_count = fb->layers;
4603 }
4604
4605 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
4606 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4607 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4608 iview->planes[0].isl.base_level, 1,
4609 base_layer, layer_count,
4610 att_state->current_layout, target_layout);
4611 }
4612
4613 if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4614 transition_depth_buffer(cmd_buffer, image,
4615 att_state->current_layout, target_layout);
4616 att_state->aux_usage =
4617 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
4618 VK_IMAGE_ASPECT_DEPTH_BIT, target_layout);
4619 }
4620
4621 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
4622 transition_stencil_buffer(cmd_buffer, image,
4623 iview->planes[0].isl.base_level, 1,
4624 base_layer, layer_count,
4625 att_state->current_stencil_layout,
4626 target_stencil_layout);
4627 }
4628 att_state->current_layout = target_layout;
4629 att_state->current_stencil_layout = target_stencil_layout;
4630
4631 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
4632 assert(att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4633
4634 /* Multi-planar images are not supported as attachments */
4635 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4636 assert(image->n_planes == 1);
4637
4638 uint32_t base_clear_layer = iview->planes[0].isl.base_array_layer;
4639 uint32_t clear_layer_count = fb->layers;
4640
4641 if (att_state->fast_clear &&
4642 do_first_layer_clear(cmd_state, att_state)) {
4643 /* We only support fast-clears on the first layer */
4644 assert(iview->planes[0].isl.base_level == 0);
4645 assert(iview->planes[0].isl.base_array_layer == 0);
4646
4647 union isl_color_value clear_color = {};
4648 anv_clear_color_from_att_state(&clear_color, att_state, iview);
4649 if (iview->image->samples == 1) {
4650 anv_image_ccs_op(cmd_buffer, image,
4651 iview->planes[0].isl.format,
4652 VK_IMAGE_ASPECT_COLOR_BIT,
4653 0, 0, 1, ISL_AUX_OP_FAST_CLEAR,
4654 &clear_color,
4655 false);
4656 } else {
4657 anv_image_mcs_op(cmd_buffer, image,
4658 iview->planes[0].isl.format,
4659 VK_IMAGE_ASPECT_COLOR_BIT,
4660 0, 1, ISL_AUX_OP_FAST_CLEAR,
4661 &clear_color,
4662 false);
4663 }
4664 base_clear_layer++;
4665 clear_layer_count--;
4666 if (is_multiview)
4667 att_state->pending_clear_views &= ~1;
4668
4669 if (att_state->clear_color_is_zero) {
4670 /* This image has the auxiliary buffer enabled. We can mark the
4671 * subresource as not needing a resolve because the clear color
4672 * will match what's in every RENDER_SURFACE_STATE object when
4673 * it's being used for sampling.
4674 */
4675 set_image_fast_clear_state(cmd_buffer, iview->image,
4676 VK_IMAGE_ASPECT_COLOR_BIT,
4677 ANV_FAST_CLEAR_DEFAULT_VALUE);
4678 } else {
4679 set_image_fast_clear_state(cmd_buffer, iview->image,
4680 VK_IMAGE_ASPECT_COLOR_BIT,
4681 ANV_FAST_CLEAR_ANY);
4682 }
4683 }
4684
4685 /* From the VkFramebufferCreateInfo spec:
4686 *
4687 * "If the render pass uses multiview, then layers must be one and each
4688 * attachment requires a number of layers that is greater than the
4689 * maximum bit index set in the view mask in the subpasses in which it
4690 * is used."
4691 *
4692 * So if multiview is active we ignore the number of layers in the
4693 * framebuffer and instead we honor the view mask from the subpass.
4694 */
4695 if (is_multiview) {
4696 assert(image->n_planes == 1);
4697 uint32_t pending_clear_mask =
4698 get_multiview_subpass_clear_mask(cmd_state, att_state);
4699
4700 uint32_t layer_idx;
4701 for_each_bit(layer_idx, pending_clear_mask) {
4702 uint32_t layer =
4703 iview->planes[0].isl.base_array_layer + layer_idx;
4704
4705 anv_image_clear_color(cmd_buffer, image,
4706 VK_IMAGE_ASPECT_COLOR_BIT,
4707 att_state->aux_usage,
4708 iview->planes[0].isl.format,
4709 iview->planes[0].isl.swizzle,
4710 iview->planes[0].isl.base_level,
4711 layer, 1,
4712 render_area,
4713 vk_to_isl_color(att_state->clear_value.color));
4714 }
4715
4716 att_state->pending_clear_views &= ~pending_clear_mask;
4717 } else if (clear_layer_count > 0) {
4718 assert(image->n_planes == 1);
4719 anv_image_clear_color(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4720 att_state->aux_usage,
4721 iview->planes[0].isl.format,
4722 iview->planes[0].isl.swizzle,
4723 iview->planes[0].isl.base_level,
4724 base_clear_layer, clear_layer_count,
4725 render_area,
4726 vk_to_isl_color(att_state->clear_value.color));
4727 }
4728 } else if (att_state->pending_clear_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT |
4729 VK_IMAGE_ASPECT_STENCIL_BIT)) {
4730 if (att_state->fast_clear && !is_multiview) {
4731 /* We currently only support HiZ for single-layer images */
4732 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4733 assert(iview->image->planes[0].aux_usage == ISL_AUX_USAGE_HIZ);
4734 assert(iview->planes[0].isl.base_level == 0);
4735 assert(iview->planes[0].isl.base_array_layer == 0);
4736 assert(fb->layers == 1);
4737 }
4738
4739 anv_image_hiz_clear(cmd_buffer, image,
4740 att_state->pending_clear_aspects,
4741 iview->planes[0].isl.base_level,
4742 iview->planes[0].isl.base_array_layer,
4743 fb->layers, render_area,
4744 att_state->clear_value.depthStencil.stencil);
4745 } else if (is_multiview) {
4746 uint32_t pending_clear_mask =
4747 get_multiview_subpass_clear_mask(cmd_state, att_state);
4748
4749 uint32_t layer_idx;
4750 for_each_bit(layer_idx, pending_clear_mask) {
4751 uint32_t layer =
4752 iview->planes[0].isl.base_array_layer + layer_idx;
4753
4754 anv_image_clear_depth_stencil(cmd_buffer, image,
4755 att_state->pending_clear_aspects,
4756 att_state->aux_usage,
4757 iview->planes[0].isl.base_level,
4758 layer, 1,
4759 render_area,
4760 att_state->clear_value.depthStencil.depth,
4761 att_state->clear_value.depthStencil.stencil);
4762 }
4763
4764 att_state->pending_clear_views &= ~pending_clear_mask;
4765 } else {
4766 anv_image_clear_depth_stencil(cmd_buffer, image,
4767 att_state->pending_clear_aspects,
4768 att_state->aux_usage,
4769 iview->planes[0].isl.base_level,
4770 iview->planes[0].isl.base_array_layer,
4771 fb->layers, render_area,
4772 att_state->clear_value.depthStencil.depth,
4773 att_state->clear_value.depthStencil.stencil);
4774 }
4775 } else {
4776 assert(att_state->pending_clear_aspects == 0);
4777 }
4778
4779 if (GEN_GEN < 10 &&
4780 (att_state->pending_load_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
4781 image->planes[0].aux_surface.isl.size_B > 0 &&
4782 iview->planes[0].isl.base_level == 0 &&
4783 iview->planes[0].isl.base_array_layer == 0) {
4784 if (att_state->aux_usage != ISL_AUX_USAGE_NONE) {
4785 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->color.state,
4786 image, VK_IMAGE_ASPECT_COLOR_BIT,
4787 false /* copy to ss */);
4788 }
4789
4790 if (need_input_attachment_state(&cmd_state->pass->attachments[a]) &&
4791 att_state->input_aux_usage != ISL_AUX_USAGE_NONE) {
4792 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->input.state,
4793 image, VK_IMAGE_ASPECT_COLOR_BIT,
4794 false /* copy to ss */);
4795 }
4796 }
4797
4798 if (subpass->attachments[i].usage ==
4799 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
4800 /* We assume that if we're starting a subpass, we're going to do some
4801 * rendering so we may end up with compressed data.
4802 */
4803 genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
4804 VK_IMAGE_ASPECT_COLOR_BIT,
4805 att_state->aux_usage,
4806 iview->planes[0].isl.base_level,
4807 iview->planes[0].isl.base_array_layer,
4808 fb->layers);
4809 } else if (subpass->attachments[i].usage ==
4810 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
4811 /* We may be writing depth or stencil so we need to mark the surface.
4812 * Unfortunately, there's no way to know at this point whether the
4813 * depth or stencil tests used will actually write to the surface.
4814 *
4815 * Even though stencil may be plane 1, it always shares a base_level
4816 * with depth.
4817 */
4818 const struct isl_view *ds_view = &iview->planes[0].isl;
4819 if (iview->aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
4820 genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
4821 VK_IMAGE_ASPECT_DEPTH_BIT,
4822 att_state->aux_usage,
4823 ds_view->base_level,
4824 ds_view->base_array_layer,
4825 fb->layers);
4826 }
4827 if (iview->aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
4828 /* Even though stencil may be plane 1, it always shares a
4829 * base_level with depth.
4830 */
4831 genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
4832 VK_IMAGE_ASPECT_STENCIL_BIT,
4833 ISL_AUX_USAGE_NONE,
4834 ds_view->base_level,
4835 ds_view->base_array_layer,
4836 fb->layers);
4837 }
4838 }
4839
4840 /* If multiview is enabled, then we are only done clearing when we no
4841 * longer have pending layers to clear, or when we have processed the
4842 * last subpass that uses this attachment.
4843 */
4844 if (!is_multiview ||
4845 att_state->pending_clear_views == 0 ||
4846 current_subpass_is_last_for_attachment(cmd_state, a)) {
4847 att_state->pending_clear_aspects = 0;
4848 }
4849
4850 att_state->pending_load_aspects = 0;
4851 }
4852
4853 cmd_buffer_emit_depth_stencil(cmd_buffer);
4854
4855 #if GEN_GEN >= 11
4856 /* The PIPE_CONTROL command description says:
4857 *
4858 * "Whenever a Binding Table Index (BTI) used by a Render Taget Message
4859 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
4860 * Target Cache Flush by enabling this bit. When render target flush
4861 * is set due to new association of BTI, PS Scoreboard Stall bit must
4862 * be set in this packet."
4863 */
4864 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4865 pc.RenderTargetCacheFlushEnable = true;
4866 pc.StallAtPixelScoreboard = true;
4867 #if GEN_GEN >= 12
4868 pc.TileCacheFlushEnable = true;
4869 #endif
4870 }
4871 #endif
4872 }
4873
4874 static enum blorp_filter
4875 vk_to_blorp_resolve_mode(VkResolveModeFlagBitsKHR vk_mode)
4876 {
4877 switch (vk_mode) {
4878 case VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR:
4879 return BLORP_FILTER_SAMPLE_0;
4880 case VK_RESOLVE_MODE_AVERAGE_BIT_KHR:
4881 return BLORP_FILTER_AVERAGE;
4882 case VK_RESOLVE_MODE_MIN_BIT_KHR:
4883 return BLORP_FILTER_MIN_SAMPLE;
4884 case VK_RESOLVE_MODE_MAX_BIT_KHR:
4885 return BLORP_FILTER_MAX_SAMPLE;
4886 default:
4887 return BLORP_FILTER_NONE;
4888 }
4889 }
4890
4891 static void
4892 cmd_buffer_end_subpass(struct anv_cmd_buffer *cmd_buffer)
4893 {
4894 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4895 struct anv_subpass *subpass = cmd_state->subpass;
4896 uint32_t subpass_id = anv_get_subpass_id(&cmd_buffer->state);
4897 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
4898
4899 if (subpass->has_color_resolve) {
4900 /* We are about to do some MSAA resolves. We need to flush so that the
4901 * result of writes to the MSAA color attachments show up in the sampler
4902 * when we blit to the single-sampled resolve target.
4903 */
4904 cmd_buffer->state.pending_pipe_bits |=
4905 ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
4906 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
4907
4908 for (uint32_t i = 0; i < subpass->color_count; ++i) {
4909 uint32_t src_att = subpass->color_attachments[i].attachment;
4910 uint32_t dst_att = subpass->resolve_attachments[i].attachment;
4911
4912 if (dst_att == VK_ATTACHMENT_UNUSED)
4913 continue;
4914
4915 assert(src_att < cmd_buffer->state.pass->attachment_count);
4916 assert(dst_att < cmd_buffer->state.pass->attachment_count);
4917
4918 if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
4919 /* From the Vulkan 1.0 spec:
4920 *
4921 * If the first use of an attachment in a render pass is as a
4922 * resolve attachment, then the loadOp is effectively ignored
4923 * as the resolve is guaranteed to overwrite all pixels in the
4924 * render area.
4925 */
4926 cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
4927 }
4928
4929 struct anv_image_view *src_iview = cmd_state->attachments[src_att].image_view;
4930 struct anv_image_view *dst_iview = cmd_state->attachments[dst_att].image_view;
4931
4932 const VkRect2D render_area = cmd_buffer->state.render_area;
4933
4934 enum isl_aux_usage src_aux_usage =
4935 cmd_buffer->state.attachments[src_att].aux_usage;
4936 enum isl_aux_usage dst_aux_usage =
4937 cmd_buffer->state.attachments[dst_att].aux_usage;
4938
4939 assert(src_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT &&
4940 dst_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT);
4941
4942 anv_image_msaa_resolve(cmd_buffer,
4943 src_iview->image, src_aux_usage,
4944 src_iview->planes[0].isl.base_level,
4945 src_iview->planes[0].isl.base_array_layer,
4946 dst_iview->image, dst_aux_usage,
4947 dst_iview->planes[0].isl.base_level,
4948 dst_iview->planes[0].isl.base_array_layer,
4949 VK_IMAGE_ASPECT_COLOR_BIT,
4950 render_area.offset.x, render_area.offset.y,
4951 render_area.offset.x, render_area.offset.y,
4952 render_area.extent.width,
4953 render_area.extent.height,
4954 fb->layers, BLORP_FILTER_NONE);
4955 }
4956 }
4957
4958 if (subpass->ds_resolve_attachment) {
4959 /* We are about to do some MSAA resolves. We need to flush so that the
4960 * result of writes to the MSAA depth attachments show up in the sampler
4961 * when we blit to the single-sampled resolve target.
4962 */
4963 cmd_buffer->state.pending_pipe_bits |=
4964 ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
4965 ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
4966
4967 uint32_t src_att = subpass->depth_stencil_attachment->attachment;
4968 uint32_t dst_att = subpass->ds_resolve_attachment->attachment;
4969
4970 assert(src_att < cmd_buffer->state.pass->attachment_count);
4971 assert(dst_att < cmd_buffer->state.pass->attachment_count);
4972
4973 if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
4974 /* From the Vulkan 1.0 spec:
4975 *
4976 * If the first use of an attachment in a render pass is as a
4977 * resolve attachment, then the loadOp is effectively ignored
4978 * as the resolve is guaranteed to overwrite all pixels in the
4979 * render area.
4980 */
4981 cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
4982 }
4983
4984 struct anv_image_view *src_iview = cmd_state->attachments[src_att].image_view;
4985 struct anv_image_view *dst_iview = cmd_state->attachments[dst_att].image_view;
4986
4987 const VkRect2D render_area = cmd_buffer->state.render_area;
4988
4989 struct anv_attachment_state *src_state =
4990 &cmd_state->attachments[src_att];
4991 struct anv_attachment_state *dst_state =
4992 &cmd_state->attachments[dst_att];
4993
4994 if ((src_iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4995 subpass->depth_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
4996
4997 /* MSAA resolves sample from the source attachment. Transition the
4998 * depth attachment first to get rid of any HiZ that we may not be
4999 * able to handle.
5000 */
5001 transition_depth_buffer(cmd_buffer, src_iview->image,
5002 src_state->current_layout,
5003 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
5004 src_state->aux_usage =
5005 anv_layout_to_aux_usage(&cmd_buffer->device->info, src_iview->image,
5006 VK_IMAGE_ASPECT_DEPTH_BIT,
5007 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
5008 src_state->current_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
5009
5010 /* MSAA resolves write to the resolve attachment as if it were any
5011 * other transfer op. Transition the resolve attachment accordingly.
5012 */
5013 VkImageLayout dst_initial_layout = dst_state->current_layout;
5014
5015 /* If our render area is the entire size of the image, we're going to
5016 * blow it all away so we can claim the initial layout is UNDEFINED
5017 * and we'll get a HiZ ambiguate instead of a resolve.
5018 */
5019 if (dst_iview->image->type != VK_IMAGE_TYPE_3D &&
5020 render_area.offset.x == 0 && render_area.offset.y == 0 &&
5021 render_area.extent.width == dst_iview->extent.width &&
5022 render_area.extent.height == dst_iview->extent.height)
5023 dst_initial_layout = VK_IMAGE_LAYOUT_UNDEFINED;
5024
5025 transition_depth_buffer(cmd_buffer, dst_iview->image,
5026 dst_initial_layout,
5027 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
5028 dst_state->aux_usage =
5029 anv_layout_to_aux_usage(&cmd_buffer->device->info, dst_iview->image,
5030 VK_IMAGE_ASPECT_DEPTH_BIT,
5031 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
5032 dst_state->current_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
5033
5034 enum blorp_filter filter =
5035 vk_to_blorp_resolve_mode(subpass->depth_resolve_mode);
5036
5037 anv_image_msaa_resolve(cmd_buffer,
5038 src_iview->image, src_state->aux_usage,
5039 src_iview->planes[0].isl.base_level,
5040 src_iview->planes[0].isl.base_array_layer,
5041 dst_iview->image, dst_state->aux_usage,
5042 dst_iview->planes[0].isl.base_level,
5043 dst_iview->planes[0].isl.base_array_layer,
5044 VK_IMAGE_ASPECT_DEPTH_BIT,
5045 render_area.offset.x, render_area.offset.y,
5046 render_area.offset.x, render_area.offset.y,
5047 render_area.extent.width,
5048 render_area.extent.height,
5049 fb->layers, filter);
5050 }
5051
5052 if ((src_iview->image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
5053 subpass->stencil_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
5054
5055 src_state->current_stencil_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
5056 dst_state->current_stencil_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
5057
5058 enum isl_aux_usage src_aux_usage = ISL_AUX_USAGE_NONE;
5059 enum isl_aux_usage dst_aux_usage = ISL_AUX_USAGE_NONE;
5060
5061 enum blorp_filter filter =
5062 vk_to_blorp_resolve_mode(subpass->stencil_resolve_mode);
5063
5064 anv_image_msaa_resolve(cmd_buffer,
5065 src_iview->image, src_aux_usage,
5066 src_iview->planes[0].isl.base_level,
5067 src_iview->planes[0].isl.base_array_layer,
5068 dst_iview->image, dst_aux_usage,
5069 dst_iview->planes[0].isl.base_level,
5070 dst_iview->planes[0].isl.base_array_layer,
5071 VK_IMAGE_ASPECT_STENCIL_BIT,
5072 render_area.offset.x, render_area.offset.y,
5073 render_area.offset.x, render_area.offset.y,
5074 render_area.extent.width,
5075 render_area.extent.height,
5076 fb->layers, filter);
5077 }
5078 }
5079
5080 #if GEN_GEN == 7
5081 /* On gen7, we have to store a texturable version of the stencil buffer in
5082 * a shadow whenever VK_IMAGE_USAGE_SAMPLED_BIT is set and copy back and
5083 * forth at strategic points. Stencil writes are only allowed in following
5084 * layouts:
5085 *
5086 * - VK_IMAGE_LAYOUT_GENERAL
5087 * - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
5088 * - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
5089 * - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL
5090 * - VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR
5091 *
5092 * For general, we have no nice opportunity to transition so we do the copy
5093 * to the shadow unconditionally at the end of the subpass. For transfer
5094 * destinations, we can update it as part of the transfer op. For the other
5095 * layouts, we delay the copy until a transition into some other layout.
5096 */
5097 if (subpass->depth_stencil_attachment) {
5098 uint32_t a = subpass->depth_stencil_attachment->attachment;
5099 assert(a != VK_ATTACHMENT_UNUSED);
5100
5101 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
5102 struct anv_image_view *iview = cmd_state->attachments[a].image_view;;
5103 const struct anv_image *image = iview->image;
5104
5105 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
5106 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
5107 VK_IMAGE_ASPECT_STENCIL_BIT);
5108
5109 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
5110 att_state->current_stencil_layout == VK_IMAGE_LAYOUT_GENERAL) {
5111 assert(image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT);
5112 anv_image_copy_to_shadow(cmd_buffer, image,
5113 VK_IMAGE_ASPECT_STENCIL_BIT,
5114 iview->planes[plane].isl.base_level, 1,
5115 iview->planes[plane].isl.base_array_layer,
5116 fb->layers);
5117 }
5118 }
5119 }
5120 #endif /* GEN_GEN == 7 */
5121
5122 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
5123 const uint32_t a = subpass->attachments[i].attachment;
5124 if (a == VK_ATTACHMENT_UNUSED)
5125 continue;
5126
5127 if (cmd_state->pass->attachments[a].last_subpass_idx != subpass_id)
5128 continue;
5129
5130 assert(a < cmd_state->pass->attachment_count);
5131 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
5132 struct anv_image_view *iview = cmd_state->attachments[a].image_view;
5133 const struct anv_image *image = iview->image;
5134
5135 if ((image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
5136 image->vk_format != iview->vk_format) {
5137 enum anv_fast_clear_type fast_clear_type =
5138 anv_layout_to_fast_clear_type(&cmd_buffer->device->info,
5139 image, VK_IMAGE_ASPECT_COLOR_BIT,
5140 att_state->current_layout);
5141
5142 /* If any clear color was used, flush it down the aux surfaces. If we
5143 * don't do it now using the view's format we might use the clear
5144 * color incorrectly in the following resolves (for example with an
5145 * SRGB view & a UNORM image).
5146 */
5147 if (fast_clear_type != ANV_FAST_CLEAR_NONE) {
5148 anv_perf_warn(cmd_buffer->device->instance, iview,
5149 "Doing a partial resolve to get rid of clear color at the "
5150 "end of a renderpass due to an image/view format mismatch");
5151
5152 uint32_t base_layer, layer_count;
5153 if (image->type == VK_IMAGE_TYPE_3D) {
5154 base_layer = 0;
5155 layer_count = anv_minify(iview->image->extent.depth,
5156 iview->planes[0].isl.base_level);
5157 } else {
5158 base_layer = iview->planes[0].isl.base_array_layer;
5159 layer_count = fb->layers;
5160 }
5161
5162 for (uint32_t a = 0; a < layer_count; a++) {
5163 uint32_t array_layer = base_layer + a;
5164 if (image->samples == 1) {
5165 anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
5166 iview->planes[0].isl.format,
5167 VK_IMAGE_ASPECT_COLOR_BIT,
5168 iview->planes[0].isl.base_level,
5169 array_layer,
5170 ISL_AUX_OP_PARTIAL_RESOLVE,
5171 ANV_FAST_CLEAR_NONE);
5172 } else {
5173 anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
5174 iview->planes[0].isl.format,
5175 VK_IMAGE_ASPECT_COLOR_BIT,
5176 base_layer,
5177 ISL_AUX_OP_PARTIAL_RESOLVE,
5178 ANV_FAST_CLEAR_NONE);
5179 }
5180 }
5181 }
5182 }
5183
5184 /* Transition the image into the final layout for this render pass */
5185 VkImageLayout target_layout =
5186 cmd_state->pass->attachments[a].final_layout;
5187 VkImageLayout target_stencil_layout =
5188 cmd_state->pass->attachments[a].stencil_final_layout;
5189
5190 uint32_t base_layer, layer_count;
5191 if (image->type == VK_IMAGE_TYPE_3D) {
5192 base_layer = 0;
5193 layer_count = anv_minify(iview->image->extent.depth,
5194 iview->planes[0].isl.base_level);
5195 } else {
5196 base_layer = iview->planes[0].isl.base_array_layer;
5197 layer_count = fb->layers;
5198 }
5199
5200 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
5201 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
5202 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
5203 iview->planes[0].isl.base_level, 1,
5204 base_layer, layer_count,
5205 att_state->current_layout, target_layout);
5206 }
5207
5208 if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
5209 transition_depth_buffer(cmd_buffer, image,
5210 att_state->current_layout, target_layout);
5211 }
5212
5213 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
5214 transition_stencil_buffer(cmd_buffer, image,
5215 iview->planes[0].isl.base_level, 1,
5216 base_layer, layer_count,
5217 att_state->current_stencil_layout,
5218 target_stencil_layout);
5219 }
5220 }
5221
5222 /* Accumulate any subpass flushes that need to happen after the subpass.
5223 * Yes, they do get accumulated twice in the NextSubpass case but since
5224 * genX_CmdNextSubpass just calls end/begin back-to-back, we just end up
5225 * ORing the bits in twice so it's harmless.
5226 */
5227 cmd_buffer->state.pending_pipe_bits |=
5228 cmd_buffer->state.pass->subpass_flushes[subpass_id + 1];
5229 }
5230
5231 void genX(CmdBeginRenderPass)(
5232 VkCommandBuffer commandBuffer,
5233 const VkRenderPassBeginInfo* pRenderPassBegin,
5234 VkSubpassContents contents)
5235 {
5236 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5237 ANV_FROM_HANDLE(anv_render_pass, pass, pRenderPassBegin->renderPass);
5238 ANV_FROM_HANDLE(anv_framebuffer, framebuffer, pRenderPassBegin->framebuffer);
5239
5240 cmd_buffer->state.framebuffer = framebuffer;
5241 cmd_buffer->state.pass = pass;
5242 cmd_buffer->state.render_area = pRenderPassBegin->renderArea;
5243 VkResult result =
5244 genX(cmd_buffer_setup_attachments)(cmd_buffer, pass, pRenderPassBegin);
5245
5246 /* If we failed to setup the attachments we should not try to go further */
5247 if (result != VK_SUCCESS) {
5248 assert(anv_batch_has_error(&cmd_buffer->batch));
5249 return;
5250 }
5251
5252 genX(flush_pipeline_select_3d)(cmd_buffer);
5253
5254 cmd_buffer_begin_subpass(cmd_buffer, 0);
5255 }
5256
5257 void genX(CmdBeginRenderPass2KHR)(
5258 VkCommandBuffer commandBuffer,
5259 const VkRenderPassBeginInfo* pRenderPassBeginInfo,
5260 const VkSubpassBeginInfoKHR* pSubpassBeginInfo)
5261 {
5262 genX(CmdBeginRenderPass)(commandBuffer, pRenderPassBeginInfo,
5263 pSubpassBeginInfo->contents);
5264 }
5265
5266 void genX(CmdNextSubpass)(
5267 VkCommandBuffer commandBuffer,
5268 VkSubpassContents contents)
5269 {
5270 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5271
5272 if (anv_batch_has_error(&cmd_buffer->batch))
5273 return;
5274
5275 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
5276
5277 uint32_t prev_subpass = anv_get_subpass_id(&cmd_buffer->state);
5278 cmd_buffer_end_subpass(cmd_buffer);
5279 cmd_buffer_begin_subpass(cmd_buffer, prev_subpass + 1);
5280 }
5281
5282 void genX(CmdNextSubpass2KHR)(
5283 VkCommandBuffer commandBuffer,
5284 const VkSubpassBeginInfoKHR* pSubpassBeginInfo,
5285 const VkSubpassEndInfoKHR* pSubpassEndInfo)
5286 {
5287 genX(CmdNextSubpass)(commandBuffer, pSubpassBeginInfo->contents);
5288 }
5289
5290 void genX(CmdEndRenderPass)(
5291 VkCommandBuffer commandBuffer)
5292 {
5293 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5294
5295 if (anv_batch_has_error(&cmd_buffer->batch))
5296 return;
5297
5298 cmd_buffer_end_subpass(cmd_buffer);
5299
5300 cmd_buffer->state.hiz_enabled = false;
5301
5302 #ifndef NDEBUG
5303 anv_dump_add_attachments(cmd_buffer);
5304 #endif
5305
5306 /* Remove references to render pass specific state. This enables us to
5307 * detect whether or not we're in a renderpass.
5308 */
5309 cmd_buffer->state.framebuffer = NULL;
5310 cmd_buffer->state.pass = NULL;
5311 cmd_buffer->state.subpass = NULL;
5312 }
5313
5314 void genX(CmdEndRenderPass2KHR)(
5315 VkCommandBuffer commandBuffer,
5316 const VkSubpassEndInfoKHR* pSubpassEndInfo)
5317 {
5318 genX(CmdEndRenderPass)(commandBuffer);
5319 }
5320
5321 void
5322 genX(cmd_emit_conditional_render_predicate)(struct anv_cmd_buffer *cmd_buffer)
5323 {
5324 #if GEN_GEN >= 8 || GEN_IS_HASWELL
5325 struct gen_mi_builder b;
5326 gen_mi_builder_init(&b, &cmd_buffer->batch);
5327
5328 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
5329 gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
5330 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
5331
5332 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
5333 mip.LoadOperation = LOAD_LOADINV;
5334 mip.CombineOperation = COMBINE_SET;
5335 mip.CompareOperation = COMPARE_SRCS_EQUAL;
5336 }
5337 #endif
5338 }
5339
5340 #if GEN_GEN >= 8 || GEN_IS_HASWELL
5341 void genX(CmdBeginConditionalRenderingEXT)(
5342 VkCommandBuffer commandBuffer,
5343 const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin)
5344 {
5345 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5346 ANV_FROM_HANDLE(anv_buffer, buffer, pConditionalRenderingBegin->buffer);
5347 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
5348 struct anv_address value_address =
5349 anv_address_add(buffer->address, pConditionalRenderingBegin->offset);
5350
5351 const bool isInverted = pConditionalRenderingBegin->flags &
5352 VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT;
5353
5354 cmd_state->conditional_render_enabled = true;
5355
5356 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
5357
5358 struct gen_mi_builder b;
5359 gen_mi_builder_init(&b, &cmd_buffer->batch);
5360
5361 /* Section 19.4 of the Vulkan 1.1.85 spec says:
5362 *
5363 * If the value of the predicate in buffer memory changes
5364 * while conditional rendering is active, the rendering commands
5365 * may be discarded in an implementation-dependent way.
5366 * Some implementations may latch the value of the predicate
5367 * upon beginning conditional rendering while others
5368 * may read it before every rendering command.
5369 *
5370 * So it's perfectly fine to read a value from the buffer once.
5371 */
5372 struct gen_mi_value value = gen_mi_mem32(value_address);
5373
5374 /* Precompute predicate result, it is necessary to support secondary
5375 * command buffers since it is unknown if conditional rendering is
5376 * inverted when populating them.
5377 */
5378 gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
5379 isInverted ? gen_mi_uge(&b, gen_mi_imm(0), value) :
5380 gen_mi_ult(&b, gen_mi_imm(0), value));
5381 }
5382
5383 void genX(CmdEndConditionalRenderingEXT)(
5384 VkCommandBuffer commandBuffer)
5385 {
5386 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5387 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
5388
5389 cmd_state->conditional_render_enabled = false;
5390 }
5391 #endif
5392
5393 /* Set of stage bits for which are pipelined, i.e. they get queued by the
5394 * command streamer for later execution.
5395 */
5396 #define ANV_PIPELINE_STAGE_PIPELINED_BITS \
5397 (VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | \
5398 VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | \
5399 VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | \
5400 VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | \
5401 VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | \
5402 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | \
5403 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | \
5404 VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | \
5405 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | \
5406 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | \
5407 VK_PIPELINE_STAGE_TRANSFER_BIT | \
5408 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | \
5409 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | \
5410 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)
5411
5412 void genX(CmdSetEvent)(
5413 VkCommandBuffer commandBuffer,
5414 VkEvent _event,
5415 VkPipelineStageFlags stageMask)
5416 {
5417 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5418 ANV_FROM_HANDLE(anv_event, event, _event);
5419
5420 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
5421 if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
5422 pc.StallAtPixelScoreboard = true;
5423 pc.CommandStreamerStallEnable = true;
5424 }
5425
5426 pc.DestinationAddressType = DAT_PPGTT,
5427 pc.PostSyncOperation = WriteImmediateData,
5428 pc.Address = (struct anv_address) {
5429 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5430 event->state.offset
5431 };
5432 pc.ImmediateData = VK_EVENT_SET;
5433 }
5434 }
5435
5436 void genX(CmdResetEvent)(
5437 VkCommandBuffer commandBuffer,
5438 VkEvent _event,
5439 VkPipelineStageFlags stageMask)
5440 {
5441 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5442 ANV_FROM_HANDLE(anv_event, event, _event);
5443
5444 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
5445 if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
5446 pc.StallAtPixelScoreboard = true;
5447 pc.CommandStreamerStallEnable = true;
5448 }
5449
5450 pc.DestinationAddressType = DAT_PPGTT;
5451 pc.PostSyncOperation = WriteImmediateData;
5452 pc.Address = (struct anv_address) {
5453 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5454 event->state.offset
5455 };
5456 pc.ImmediateData = VK_EVENT_RESET;
5457 }
5458 }
5459
5460 void genX(CmdWaitEvents)(
5461 VkCommandBuffer commandBuffer,
5462 uint32_t eventCount,
5463 const VkEvent* pEvents,
5464 VkPipelineStageFlags srcStageMask,
5465 VkPipelineStageFlags destStageMask,
5466 uint32_t memoryBarrierCount,
5467 const VkMemoryBarrier* pMemoryBarriers,
5468 uint32_t bufferMemoryBarrierCount,
5469 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
5470 uint32_t imageMemoryBarrierCount,
5471 const VkImageMemoryBarrier* pImageMemoryBarriers)
5472 {
5473 #if GEN_GEN >= 8
5474 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5475
5476 for (uint32_t i = 0; i < eventCount; i++) {
5477 ANV_FROM_HANDLE(anv_event, event, pEvents[i]);
5478
5479 anv_batch_emit(&cmd_buffer->batch, GENX(MI_SEMAPHORE_WAIT), sem) {
5480 sem.WaitMode = PollingMode,
5481 sem.CompareOperation = COMPARE_SAD_EQUAL_SDD,
5482 sem.SemaphoreDataDword = VK_EVENT_SET,
5483 sem.SemaphoreAddress = (struct anv_address) {
5484 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5485 event->state.offset
5486 };
5487 }
5488 }
5489 #else
5490 anv_finishme("Implement events on gen7");
5491 #endif
5492
5493 genX(CmdPipelineBarrier)(commandBuffer, srcStageMask, destStageMask,
5494 false, /* byRegion */
5495 memoryBarrierCount, pMemoryBarriers,
5496 bufferMemoryBarrierCount, pBufferMemoryBarriers,
5497 imageMemoryBarrierCount, pImageMemoryBarriers);
5498 }
5499
5500 VkResult genX(CmdSetPerformanceOverrideINTEL)(
5501 VkCommandBuffer commandBuffer,
5502 const VkPerformanceOverrideInfoINTEL* pOverrideInfo)
5503 {
5504 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5505
5506 switch (pOverrideInfo->type) {
5507 case VK_PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL: {
5508 uint32_t dw;
5509
5510 #if GEN_GEN >= 9
5511 anv_pack_struct(&dw, GENX(CS_DEBUG_MODE2),
5512 ._3DRenderingInstructionDisable = pOverrideInfo->enable,
5513 .MediaInstructionDisable = pOverrideInfo->enable,
5514 ._3DRenderingInstructionDisableMask = true,
5515 .MediaInstructionDisableMask = true);
5516 emit_lri(&cmd_buffer->batch, GENX(CS_DEBUG_MODE2_num), dw);
5517 #else
5518 anv_pack_struct(&dw, GENX(INSTPM),
5519 ._3DRenderingInstructionDisable = pOverrideInfo->enable,
5520 .MediaInstructionDisable = pOverrideInfo->enable,
5521 ._3DRenderingInstructionDisableMask = true,
5522 .MediaInstructionDisableMask = true);
5523 emit_lri(&cmd_buffer->batch, GENX(INSTPM_num), dw);
5524 #endif
5525 break;
5526 }
5527
5528 case VK_PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL:
5529 if (pOverrideInfo->enable) {
5530 /* FLUSH ALL THE THINGS! As requested by the MDAPI team. */
5531 cmd_buffer->state.pending_pipe_bits |=
5532 ANV_PIPE_FLUSH_BITS |
5533 ANV_PIPE_INVALIDATE_BITS;
5534 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
5535 }
5536 break;
5537
5538 default:
5539 unreachable("Invalid override");
5540 }
5541
5542 return VK_SUCCESS;
5543 }
5544
5545 VkResult genX(CmdSetPerformanceStreamMarkerINTEL)(
5546 VkCommandBuffer commandBuffer,
5547 const VkPerformanceStreamMarkerInfoINTEL* pMarkerInfo)
5548 {
5549 /* TODO: Waiting on the register to write, might depend on generation. */
5550
5551 return VK_SUCCESS;
5552 }