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