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