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