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