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