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