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