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