anv: don't reserve a particular register for draw count
[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 15 for conditional rendering */
38 #define GEN_MI_BUILDER_NUM_ALLOC_GPRS 15
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 static struct gen_mi_value
3859 prepare_for_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3860 struct gen_mi_builder *b,
3861 struct anv_address count_address,
3862 const bool conditional_render_enabled)
3863 {
3864 struct gen_mi_value ret = gen_mi_imm(0);
3865
3866 if (conditional_render_enabled) {
3867 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3868 ret = gen_mi_new_gpr(b);
3869 gen_mi_store(b, gen_mi_value_ref(b, ret), gen_mi_mem32(count_address));
3870 #endif
3871 } else {
3872 /* Upload the current draw count from the draw parameters buffer to
3873 * MI_PREDICATE_SRC0.
3874 */
3875 gen_mi_store(b, gen_mi_reg64(MI_PREDICATE_SRC0),
3876 gen_mi_mem32(count_address));
3877
3878 gen_mi_store(b, gen_mi_reg32(MI_PREDICATE_SRC1 + 4), gen_mi_imm(0));
3879 }
3880
3881 return ret;
3882 }
3883
3884 static void
3885 emit_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3886 struct gen_mi_builder *b,
3887 uint32_t draw_index)
3888 {
3889 /* Upload the index of the current primitive to MI_PREDICATE_SRC1. */
3890 gen_mi_store(b, gen_mi_reg32(MI_PREDICATE_SRC1), gen_mi_imm(draw_index));
3891
3892 if (draw_index == 0) {
3893 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3894 mip.LoadOperation = LOAD_LOADINV;
3895 mip.CombineOperation = COMBINE_SET;
3896 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3897 }
3898 } else {
3899 /* While draw_index < draw_count the predicate's result will be
3900 * (draw_index == draw_count) ^ TRUE = TRUE
3901 * When draw_index == draw_count the result is
3902 * (TRUE) ^ TRUE = FALSE
3903 * After this all results will be:
3904 * (FALSE) ^ FALSE = FALSE
3905 */
3906 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3907 mip.LoadOperation = LOAD_LOAD;
3908 mip.CombineOperation = COMBINE_XOR;
3909 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3910 }
3911 }
3912 }
3913
3914 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3915 static void
3916 emit_draw_count_predicate_with_conditional_render(
3917 struct anv_cmd_buffer *cmd_buffer,
3918 struct gen_mi_builder *b,
3919 uint32_t draw_index,
3920 struct gen_mi_value max)
3921 {
3922 struct gen_mi_value pred = gen_mi_ult(b, gen_mi_imm(draw_index), max);
3923 pred = gen_mi_iand(b, pred, gen_mi_reg64(ANV_PREDICATE_RESULT_REG));
3924
3925 #if GEN_GEN >= 8
3926 gen_mi_store(b, gen_mi_reg64(MI_PREDICATE_RESULT), pred);
3927 #else
3928 /* MI_PREDICATE_RESULT is not whitelisted in i915 command parser
3929 * so we emit MI_PREDICATE to set it.
3930 */
3931
3932 gen_mi_store(b, gen_mi_reg64(MI_PREDICATE_SRC0), pred);
3933 gen_mi_store(b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3934
3935 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3936 mip.LoadOperation = LOAD_LOADINV;
3937 mip.CombineOperation = COMBINE_SET;
3938 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3939 }
3940 #endif
3941 }
3942 #endif
3943
3944 void genX(CmdDrawIndirectCount)(
3945 VkCommandBuffer commandBuffer,
3946 VkBuffer _buffer,
3947 VkDeviceSize offset,
3948 VkBuffer _countBuffer,
3949 VkDeviceSize countBufferOffset,
3950 uint32_t maxDrawCount,
3951 uint32_t stride)
3952 {
3953 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3954 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3955 ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3956 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3957 struct anv_graphics_pipeline *pipeline = cmd_state->gfx.pipeline;
3958 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3959
3960 if (anv_batch_has_error(&cmd_buffer->batch))
3961 return;
3962
3963 genX(cmd_buffer_flush_state)(cmd_buffer);
3964
3965 struct gen_mi_builder b;
3966 gen_mi_builder_init(&b, &cmd_buffer->batch);
3967 struct anv_address count_address =
3968 anv_address_add(count_buffer->address, countBufferOffset);
3969 struct gen_mi_value max =
3970 prepare_for_draw_count_predicate(cmd_buffer, &b, count_address,
3971 cmd_state->conditional_render_enabled);
3972
3973 for (uint32_t i = 0; i < maxDrawCount; i++) {
3974 struct anv_address draw = anv_address_add(buffer->address, offset);
3975
3976 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3977 if (cmd_state->conditional_render_enabled) {
3978 emit_draw_count_predicate_with_conditional_render(
3979 cmd_buffer, &b, i, gen_mi_value_ref(&b, max));
3980 } else {
3981 emit_draw_count_predicate(cmd_buffer, &b, i);
3982 }
3983 #else
3984 emit_draw_count_predicate(cmd_buffer, &b, i);
3985 #endif
3986
3987 if (vs_prog_data->uses_firstvertex ||
3988 vs_prog_data->uses_baseinstance)
3989 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3990 if (vs_prog_data->uses_drawid)
3991 emit_draw_index(cmd_buffer, i);
3992
3993 /* Emitting draw index or vertex index BOs may result in needing
3994 * additional VF cache flushes.
3995 */
3996 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3997
3998 load_indirect_parameters(cmd_buffer, draw, false);
3999
4000 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
4001 prim.IndirectParameterEnable = true;
4002 prim.PredicateEnable = true;
4003 prim.VertexAccessType = SEQUENTIAL;
4004 prim.PrimitiveTopologyType = pipeline->topology;
4005 }
4006
4007 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, SEQUENTIAL);
4008
4009 offset += stride;
4010 }
4011
4012 gen_mi_value_unref(&b, max);
4013 }
4014
4015 void genX(CmdDrawIndexedIndirectCount)(
4016 VkCommandBuffer commandBuffer,
4017 VkBuffer _buffer,
4018 VkDeviceSize offset,
4019 VkBuffer _countBuffer,
4020 VkDeviceSize countBufferOffset,
4021 uint32_t maxDrawCount,
4022 uint32_t stride)
4023 {
4024 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4025 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
4026 ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
4027 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4028 struct anv_graphics_pipeline *pipeline = cmd_state->gfx.pipeline;
4029 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
4030
4031 if (anv_batch_has_error(&cmd_buffer->batch))
4032 return;
4033
4034 genX(cmd_buffer_flush_state)(cmd_buffer);
4035
4036 struct gen_mi_builder b;
4037 gen_mi_builder_init(&b, &cmd_buffer->batch);
4038 struct anv_address count_address =
4039 anv_address_add(count_buffer->address, countBufferOffset);
4040 struct gen_mi_value max =
4041 prepare_for_draw_count_predicate(cmd_buffer, &b, count_address,
4042 cmd_state->conditional_render_enabled);
4043
4044 for (uint32_t i = 0; i < maxDrawCount; i++) {
4045 struct anv_address draw = anv_address_add(buffer->address, offset);
4046
4047 #if GEN_GEN >= 8 || GEN_IS_HASWELL
4048 if (cmd_state->conditional_render_enabled) {
4049 emit_draw_count_predicate_with_conditional_render(
4050 cmd_buffer, &b, i, gen_mi_value_ref(&b, max));
4051 } else {
4052 emit_draw_count_predicate(cmd_buffer, &b, i);
4053 }
4054 #else
4055 emit_draw_count_predicate(cmd_buffer, &b, i);
4056 #endif
4057
4058 /* TODO: We need to stomp base vertex to 0 somehow */
4059 if (vs_prog_data->uses_firstvertex ||
4060 vs_prog_data->uses_baseinstance)
4061 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
4062 if (vs_prog_data->uses_drawid)
4063 emit_draw_index(cmd_buffer, i);
4064
4065 /* Emitting draw index or vertex index BOs may result in needing
4066 * additional VF cache flushes.
4067 */
4068 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4069
4070 load_indirect_parameters(cmd_buffer, draw, true);
4071
4072 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
4073 prim.IndirectParameterEnable = true;
4074 prim.PredicateEnable = true;
4075 prim.VertexAccessType = RANDOM;
4076 prim.PrimitiveTopologyType = pipeline->topology;
4077 }
4078
4079 update_dirty_vbs_for_gen8_vb_flush(cmd_buffer, RANDOM);
4080
4081 offset += stride;
4082 }
4083
4084 gen_mi_value_unref(&b, max);
4085 }
4086
4087 void genX(CmdBeginTransformFeedbackEXT)(
4088 VkCommandBuffer commandBuffer,
4089 uint32_t firstCounterBuffer,
4090 uint32_t counterBufferCount,
4091 const VkBuffer* pCounterBuffers,
4092 const VkDeviceSize* pCounterBufferOffsets)
4093 {
4094 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4095
4096 assert(firstCounterBuffer < MAX_XFB_BUFFERS);
4097 assert(counterBufferCount <= MAX_XFB_BUFFERS);
4098 assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
4099
4100 /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
4101 *
4102 * "Ssoftware must ensure that no HW stream output operations can be in
4103 * process or otherwise pending at the point that the MI_LOAD/STORE
4104 * commands are processed. This will likely require a pipeline flush."
4105 */
4106 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
4107 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4108
4109 for (uint32_t idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
4110 /* If we have a counter buffer, this is a resume so we need to load the
4111 * value into the streamout offset register. Otherwise, this is a begin
4112 * and we need to reset it to zero.
4113 */
4114 if (pCounterBuffers &&
4115 idx >= firstCounterBuffer &&
4116 idx - firstCounterBuffer < counterBufferCount &&
4117 pCounterBuffers[idx - firstCounterBuffer] != VK_NULL_HANDLE) {
4118 uint32_t cb_idx = idx - firstCounterBuffer;
4119 ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
4120 uint64_t offset = pCounterBufferOffsets ?
4121 pCounterBufferOffsets[cb_idx] : 0;
4122
4123 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
4124 lrm.RegisterAddress = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
4125 lrm.MemoryAddress = anv_address_add(counter_buffer->address,
4126 offset);
4127 }
4128 } else {
4129 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
4130 lri.RegisterOffset = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
4131 lri.DataDWord = 0;
4132 }
4133 }
4134 }
4135
4136 cmd_buffer->state.xfb_enabled = true;
4137 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
4138 }
4139
4140 void genX(CmdEndTransformFeedbackEXT)(
4141 VkCommandBuffer commandBuffer,
4142 uint32_t firstCounterBuffer,
4143 uint32_t counterBufferCount,
4144 const VkBuffer* pCounterBuffers,
4145 const VkDeviceSize* pCounterBufferOffsets)
4146 {
4147 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4148
4149 assert(firstCounterBuffer < MAX_XFB_BUFFERS);
4150 assert(counterBufferCount <= MAX_XFB_BUFFERS);
4151 assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
4152
4153 /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
4154 *
4155 * "Ssoftware must ensure that no HW stream output operations can be in
4156 * process or otherwise pending at the point that the MI_LOAD/STORE
4157 * commands are processed. This will likely require a pipeline flush."
4158 */
4159 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
4160 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4161
4162 for (uint32_t cb_idx = 0; cb_idx < counterBufferCount; cb_idx++) {
4163 unsigned idx = firstCounterBuffer + cb_idx;
4164
4165 /* If we have a counter buffer, this is a resume so we need to load the
4166 * value into the streamout offset register. Otherwise, this is a begin
4167 * and we need to reset it to zero.
4168 */
4169 if (pCounterBuffers &&
4170 cb_idx < counterBufferCount &&
4171 pCounterBuffers[cb_idx] != VK_NULL_HANDLE) {
4172 ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
4173 uint64_t offset = pCounterBufferOffsets ?
4174 pCounterBufferOffsets[cb_idx] : 0;
4175
4176 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_REGISTER_MEM), srm) {
4177 srm.MemoryAddress = anv_address_add(counter_buffer->address,
4178 offset);
4179 srm.RegisterAddress = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
4180 }
4181 }
4182 }
4183
4184 cmd_buffer->state.xfb_enabled = false;
4185 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
4186 }
4187
4188 void
4189 genX(cmd_buffer_flush_compute_state)(struct anv_cmd_buffer *cmd_buffer)
4190 {
4191 struct anv_compute_pipeline *pipeline = cmd_buffer->state.compute.pipeline;
4192
4193 assert(pipeline->cs);
4194
4195 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->base.l3_config);
4196
4197 genX(flush_pipeline_select_gpgpu)(cmd_buffer);
4198
4199 /* Apply any pending pipeline flushes we may have. We want to apply them
4200 * now because, if any of those flushes are for things like push constants,
4201 * the GPU will read the state at weird times.
4202 */
4203 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4204
4205 if (cmd_buffer->state.compute.pipeline_dirty) {
4206 /* From the Sky Lake PRM Vol 2a, MEDIA_VFE_STATE:
4207 *
4208 * "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
4209 * the only bits that are changed are scoreboard related: Scoreboard
4210 * Enable, Scoreboard Type, Scoreboard Mask, Scoreboard * Delta. For
4211 * these scoreboard related states, a MEDIA_STATE_FLUSH is
4212 * sufficient."
4213 */
4214 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
4215 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4216
4217 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->base.batch);
4218
4219 /* The workgroup size of the pipeline affects our push constant layout
4220 * so flag push constants as dirty if we change the pipeline.
4221 */
4222 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
4223 }
4224
4225 if ((cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_COMPUTE_BIT) ||
4226 cmd_buffer->state.compute.pipeline_dirty) {
4227 flush_descriptor_sets(cmd_buffer,
4228 &cmd_buffer->state.compute.base,
4229 &pipeline->cs, 1);
4230
4231 uint32_t iface_desc_data_dw[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
4232 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
4233 .BindingTablePointer =
4234 cmd_buffer->state.binding_tables[MESA_SHADER_COMPUTE].offset,
4235 .SamplerStatePointer =
4236 cmd_buffer->state.samplers[MESA_SHADER_COMPUTE].offset,
4237 };
4238 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL, iface_desc_data_dw, &desc);
4239
4240 struct anv_state state =
4241 anv_cmd_buffer_merge_dynamic(cmd_buffer, iface_desc_data_dw,
4242 pipeline->interface_descriptor_data,
4243 GENX(INTERFACE_DESCRIPTOR_DATA_length),
4244 64);
4245
4246 uint32_t size = GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
4247 anv_batch_emit(&cmd_buffer->batch,
4248 GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), mid) {
4249 mid.InterfaceDescriptorTotalLength = size;
4250 mid.InterfaceDescriptorDataStartAddress = state.offset;
4251 }
4252 }
4253
4254 if (cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_COMPUTE_BIT) {
4255 struct anv_state push_state =
4256 anv_cmd_buffer_cs_push_constants(cmd_buffer);
4257
4258 if (push_state.alloc_size) {
4259 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_CURBE_LOAD), curbe) {
4260 curbe.CURBETotalDataLength = push_state.alloc_size;
4261 curbe.CURBEDataStartAddress = push_state.offset;
4262 }
4263 }
4264
4265 cmd_buffer->state.push_constants_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
4266 }
4267
4268 cmd_buffer->state.compute.pipeline_dirty = false;
4269
4270 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4271 }
4272
4273 #if GEN_GEN == 7
4274
4275 static VkResult
4276 verify_cmd_parser(const struct anv_device *device,
4277 int required_version,
4278 const char *function)
4279 {
4280 if (device->physical->cmd_parser_version < required_version) {
4281 return vk_errorf(device, device->physical,
4282 VK_ERROR_FEATURE_NOT_PRESENT,
4283 "cmd parser version %d is required for %s",
4284 required_version, function);
4285 } else {
4286 return VK_SUCCESS;
4287 }
4288 }
4289
4290 #endif
4291
4292 static void
4293 anv_cmd_buffer_push_base_group_id(struct anv_cmd_buffer *cmd_buffer,
4294 uint32_t baseGroupX,
4295 uint32_t baseGroupY,
4296 uint32_t baseGroupZ)
4297 {
4298 if (anv_batch_has_error(&cmd_buffer->batch))
4299 return;
4300
4301 struct anv_push_constants *push =
4302 &cmd_buffer->state.push_constants[MESA_SHADER_COMPUTE];
4303 if (push->cs.base_work_group_id[0] != baseGroupX ||
4304 push->cs.base_work_group_id[1] != baseGroupY ||
4305 push->cs.base_work_group_id[2] != baseGroupZ) {
4306 push->cs.base_work_group_id[0] = baseGroupX;
4307 push->cs.base_work_group_id[1] = baseGroupY;
4308 push->cs.base_work_group_id[2] = baseGroupZ;
4309
4310 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
4311 }
4312 }
4313
4314 void genX(CmdDispatch)(
4315 VkCommandBuffer commandBuffer,
4316 uint32_t x,
4317 uint32_t y,
4318 uint32_t z)
4319 {
4320 genX(CmdDispatchBase)(commandBuffer, 0, 0, 0, x, y, z);
4321 }
4322
4323 void genX(CmdDispatchBase)(
4324 VkCommandBuffer commandBuffer,
4325 uint32_t baseGroupX,
4326 uint32_t baseGroupY,
4327 uint32_t baseGroupZ,
4328 uint32_t groupCountX,
4329 uint32_t groupCountY,
4330 uint32_t groupCountZ)
4331 {
4332 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4333 struct anv_compute_pipeline *pipeline = cmd_buffer->state.compute.pipeline;
4334 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
4335
4336 anv_cmd_buffer_push_base_group_id(cmd_buffer, baseGroupX,
4337 baseGroupY, baseGroupZ);
4338
4339 if (anv_batch_has_error(&cmd_buffer->batch))
4340 return;
4341
4342 if (prog_data->uses_num_work_groups) {
4343 struct anv_state state =
4344 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 12, 4);
4345 uint32_t *sizes = state.map;
4346 sizes[0] = groupCountX;
4347 sizes[1] = groupCountY;
4348 sizes[2] = groupCountZ;
4349 cmd_buffer->state.compute.num_workgroups = (struct anv_address) {
4350 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
4351 .offset = state.offset,
4352 };
4353
4354 /* The num_workgroups buffer goes in the binding table */
4355 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
4356 }
4357
4358 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
4359
4360 if (cmd_buffer->state.conditional_render_enabled)
4361 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
4362
4363 anv_batch_emit(&cmd_buffer->batch, GENX(GPGPU_WALKER), ggw) {
4364 ggw.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
4365 ggw.SIMDSize = prog_data->simd_size / 16;
4366 ggw.ThreadDepthCounterMaximum = 0;
4367 ggw.ThreadHeightCounterMaximum = 0;
4368 ggw.ThreadWidthCounterMaximum = anv_cs_threads(pipeline) - 1;
4369 ggw.ThreadGroupIDXDimension = groupCountX;
4370 ggw.ThreadGroupIDYDimension = groupCountY;
4371 ggw.ThreadGroupIDZDimension = groupCountZ;
4372 ggw.RightExecutionMask = pipeline->cs_right_mask;
4373 ggw.BottomExecutionMask = 0xffffffff;
4374 }
4375
4376 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_STATE_FLUSH), msf);
4377 }
4378
4379 #define GPGPU_DISPATCHDIMX 0x2500
4380 #define GPGPU_DISPATCHDIMY 0x2504
4381 #define GPGPU_DISPATCHDIMZ 0x2508
4382
4383 void genX(CmdDispatchIndirect)(
4384 VkCommandBuffer commandBuffer,
4385 VkBuffer _buffer,
4386 VkDeviceSize offset)
4387 {
4388 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4389 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
4390 struct anv_compute_pipeline *pipeline = cmd_buffer->state.compute.pipeline;
4391 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
4392 struct anv_address addr = anv_address_add(buffer->address, offset);
4393 struct anv_batch *batch = &cmd_buffer->batch;
4394
4395 anv_cmd_buffer_push_base_group_id(cmd_buffer, 0, 0, 0);
4396
4397 #if GEN_GEN == 7
4398 /* Linux 4.4 added command parser version 5 which allows the GPGPU
4399 * indirect dispatch registers to be written.
4400 */
4401 if (verify_cmd_parser(cmd_buffer->device, 5,
4402 "vkCmdDispatchIndirect") != VK_SUCCESS)
4403 return;
4404 #endif
4405
4406 if (prog_data->uses_num_work_groups) {
4407 cmd_buffer->state.compute.num_workgroups = addr;
4408
4409 /* The num_workgroups buffer goes in the binding table */
4410 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
4411 }
4412
4413 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
4414
4415 struct gen_mi_builder b;
4416 gen_mi_builder_init(&b, &cmd_buffer->batch);
4417
4418 struct gen_mi_value size_x = gen_mi_mem32(anv_address_add(addr, 0));
4419 struct gen_mi_value size_y = gen_mi_mem32(anv_address_add(addr, 4));
4420 struct gen_mi_value size_z = gen_mi_mem32(anv_address_add(addr, 8));
4421
4422 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMX), size_x);
4423 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMY), size_y);
4424 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMZ), size_z);
4425
4426 #if GEN_GEN <= 7
4427 /* predicate = (compute_dispatch_indirect_x_size == 0); */
4428 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), size_x);
4429 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
4430 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
4431 mip.LoadOperation = LOAD_LOAD;
4432 mip.CombineOperation = COMBINE_SET;
4433 mip.CompareOperation = COMPARE_SRCS_EQUAL;
4434 }
4435
4436 /* predicate |= (compute_dispatch_indirect_y_size == 0); */
4437 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_y);
4438 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
4439 mip.LoadOperation = LOAD_LOAD;
4440 mip.CombineOperation = COMBINE_OR;
4441 mip.CompareOperation = COMPARE_SRCS_EQUAL;
4442 }
4443
4444 /* predicate |= (compute_dispatch_indirect_z_size == 0); */
4445 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_z);
4446 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
4447 mip.LoadOperation = LOAD_LOAD;
4448 mip.CombineOperation = COMBINE_OR;
4449 mip.CompareOperation = COMPARE_SRCS_EQUAL;
4450 }
4451
4452 /* predicate = !predicate; */
4453 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
4454 mip.LoadOperation = LOAD_LOADINV;
4455 mip.CombineOperation = COMBINE_OR;
4456 mip.CompareOperation = COMPARE_FALSE;
4457 }
4458
4459 #if GEN_IS_HASWELL
4460 if (cmd_buffer->state.conditional_render_enabled) {
4461 /* predicate &= !(conditional_rendering_predicate == 0); */
4462 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0),
4463 gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
4464 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
4465 mip.LoadOperation = LOAD_LOADINV;
4466 mip.CombineOperation = COMBINE_AND;
4467 mip.CompareOperation = COMPARE_SRCS_EQUAL;
4468 }
4469 }
4470 #endif
4471
4472 #else /* GEN_GEN > 7 */
4473 if (cmd_buffer->state.conditional_render_enabled)
4474 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
4475 #endif
4476
4477 anv_batch_emit(batch, GENX(GPGPU_WALKER), ggw) {
4478 ggw.IndirectParameterEnable = true;
4479 ggw.PredicateEnable = GEN_GEN <= 7 ||
4480 cmd_buffer->state.conditional_render_enabled;
4481 ggw.SIMDSize = prog_data->simd_size / 16;
4482 ggw.ThreadDepthCounterMaximum = 0;
4483 ggw.ThreadHeightCounterMaximum = 0;
4484 ggw.ThreadWidthCounterMaximum = anv_cs_threads(pipeline) - 1;
4485 ggw.RightExecutionMask = pipeline->cs_right_mask;
4486 ggw.BottomExecutionMask = 0xffffffff;
4487 }
4488
4489 anv_batch_emit(batch, GENX(MEDIA_STATE_FLUSH), msf);
4490 }
4491
4492 static void
4493 genX(flush_pipeline_select)(struct anv_cmd_buffer *cmd_buffer,
4494 uint32_t pipeline)
4495 {
4496 UNUSED const struct gen_device_info *devinfo = &cmd_buffer->device->info;
4497
4498 if (cmd_buffer->state.current_pipeline == pipeline)
4499 return;
4500
4501 #if GEN_GEN >= 8 && GEN_GEN < 10
4502 /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
4503 *
4504 * Software must clear the COLOR_CALC_STATE Valid field in
4505 * 3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
4506 * with Pipeline Select set to GPGPU.
4507 *
4508 * The internal hardware docs recommend the same workaround for Gen9
4509 * hardware too.
4510 */
4511 if (pipeline == GPGPU)
4512 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
4513 #endif
4514
4515 #if GEN_GEN == 9
4516 if (pipeline == _3D) {
4517 /* There is a mid-object preemption workaround which requires you to
4518 * re-emit MEDIA_VFE_STATE after switching from GPGPU to 3D. However,
4519 * even without preemption, we have issues with geometry flickering when
4520 * GPGPU and 3D are back-to-back and this seems to fix it. We don't
4521 * really know why.
4522 */
4523 const uint32_t subslices =
4524 MAX2(cmd_buffer->device->physical->subslice_total, 1);
4525 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_VFE_STATE), vfe) {
4526 vfe.MaximumNumberofThreads =
4527 devinfo->max_cs_threads * subslices - 1;
4528 vfe.NumberofURBEntries = 2;
4529 vfe.URBEntryAllocationSize = 2;
4530 }
4531
4532 /* We just emitted a dummy MEDIA_VFE_STATE so now that packet is
4533 * invalid. Set the compute pipeline to dirty to force a re-emit of the
4534 * pipeline in case we get back-to-back dispatch calls with the same
4535 * pipeline and a PIPELINE_SELECT in between.
4536 */
4537 cmd_buffer->state.compute.pipeline_dirty = true;
4538 }
4539 #endif
4540
4541 /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
4542 * PIPELINE_SELECT [DevBWR+]":
4543 *
4544 * Project: DEVSNB+
4545 *
4546 * Software must ensure all the write caches are flushed through a
4547 * stalling PIPE_CONTROL command followed by another PIPE_CONTROL
4548 * command to invalidate read only caches prior to programming
4549 * MI_PIPELINE_SELECT command to change the Pipeline Select Mode.
4550 */
4551 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4552 pc.RenderTargetCacheFlushEnable = true;
4553 pc.DepthCacheFlushEnable = true;
4554 pc.DCFlushEnable = true;
4555 pc.PostSyncOperation = NoWrite;
4556 pc.CommandStreamerStallEnable = true;
4557 #if GEN_GEN >= 12
4558 pc.TileCacheFlushEnable = true;
4559
4560 /* GEN:BUG:1409600907: "PIPE_CONTROL with Depth Stall Enable bit must be
4561 * set with any PIPE_CONTROL with Depth Flush Enable bit set.
4562 */
4563 pc.DepthStallEnable = true;
4564 #endif
4565 }
4566
4567 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4568 pc.TextureCacheInvalidationEnable = true;
4569 pc.ConstantCacheInvalidationEnable = true;
4570 pc.StateCacheInvalidationEnable = true;
4571 pc.InstructionCacheInvalidateEnable = true;
4572 pc.PostSyncOperation = NoWrite;
4573 #if GEN_GEN >= 12
4574 pc.TileCacheFlushEnable = true;
4575 #endif
4576 }
4577
4578 anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
4579 #if GEN_GEN >= 9
4580 ps.MaskBits = 3;
4581 #endif
4582 ps.PipelineSelection = pipeline;
4583 }
4584
4585 #if GEN_GEN == 9
4586 if (devinfo->is_geminilake) {
4587 /* Project: DevGLK
4588 *
4589 * "This chicken bit works around a hardware issue with barrier logic
4590 * encountered when switching between GPGPU and 3D pipelines. To
4591 * workaround the issue, this mode bit should be set after a pipeline
4592 * is selected."
4593 */
4594 uint32_t scec;
4595 anv_pack_struct(&scec, GENX(SLICE_COMMON_ECO_CHICKEN1),
4596 .GLKBarrierMode =
4597 pipeline == GPGPU ? GLK_BARRIER_MODE_GPGPU
4598 : GLK_BARRIER_MODE_3D_HULL,
4599 .GLKBarrierModeMask = 1);
4600 emit_lri(&cmd_buffer->batch, GENX(SLICE_COMMON_ECO_CHICKEN1_num), scec);
4601 }
4602 #endif
4603
4604 cmd_buffer->state.current_pipeline = pipeline;
4605 }
4606
4607 void
4608 genX(flush_pipeline_select_3d)(struct anv_cmd_buffer *cmd_buffer)
4609 {
4610 genX(flush_pipeline_select)(cmd_buffer, _3D);
4611 }
4612
4613 void
4614 genX(flush_pipeline_select_gpgpu)(struct anv_cmd_buffer *cmd_buffer)
4615 {
4616 genX(flush_pipeline_select)(cmd_buffer, GPGPU);
4617 }
4618
4619 void
4620 genX(cmd_buffer_emit_gen7_depth_flush)(struct anv_cmd_buffer *cmd_buffer)
4621 {
4622 if (GEN_GEN >= 8)
4623 return;
4624
4625 /* From the Haswell PRM, documentation for 3DSTATE_DEPTH_BUFFER:
4626 *
4627 * "Restriction: Prior to changing Depth/Stencil Buffer state (i.e., any
4628 * combination of 3DSTATE_DEPTH_BUFFER, 3DSTATE_CLEAR_PARAMS,
4629 * 3DSTATE_STENCIL_BUFFER, 3DSTATE_HIER_DEPTH_BUFFER) SW must first
4630 * issue a pipelined depth stall (PIPE_CONTROL with Depth Stall bit
4631 * set), followed by a pipelined depth cache flush (PIPE_CONTROL with
4632 * Depth Flush Bit set, followed by another pipelined depth stall
4633 * (PIPE_CONTROL with Depth Stall Bit set), unless SW can otherwise
4634 * guarantee that the pipeline from WM onwards is already flushed (e.g.,
4635 * via a preceding MI_FLUSH)."
4636 */
4637 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
4638 pipe.DepthStallEnable = true;
4639 }
4640 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
4641 pipe.DepthCacheFlushEnable = true;
4642 #if GEN_GEN >= 12
4643 pipe.TileCacheFlushEnable = true;
4644 #endif
4645 }
4646 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
4647 pipe.DepthStallEnable = true;
4648 }
4649 }
4650
4651 /* From the Skylake PRM, 3DSTATE_VERTEX_BUFFERS:
4652 *
4653 * "The VF cache needs to be invalidated before binding and then using
4654 * Vertex Buffers that overlap with any previously bound Vertex Buffer
4655 * (at a 64B granularity) since the last invalidation. A VF cache
4656 * invalidate is performed by setting the "VF Cache Invalidation Enable"
4657 * bit in PIPE_CONTROL."
4658 *
4659 * This is implemented by carefully tracking all vertex and index buffer
4660 * bindings and flushing if the cache ever ends up with a range in the cache
4661 * that would exceed 4 GiB. This is implemented in three parts:
4662 *
4663 * 1. genX(cmd_buffer_set_binding_for_gen8_vb_flush)() which must be called
4664 * every time a 3DSTATE_VERTEX_BUFFER packet is emitted and informs the
4665 * tracking code of the new binding. If this new binding would cause
4666 * the cache to have a too-large range on the next draw call, a pipeline
4667 * stall and VF cache invalidate are added to pending_pipeline_bits.
4668 *
4669 * 2. genX(cmd_buffer_apply_pipe_flushes)() resets the cache tracking to
4670 * empty whenever we emit a VF invalidate.
4671 *
4672 * 3. genX(cmd_buffer_update_dirty_vbs_for_gen8_vb_flush)() must be called
4673 * after every 3DPRIMITIVE and copies the bound range into the dirty
4674 * range for each used buffer. This has to be a separate step because
4675 * we don't always re-bind all buffers and so 1. can't know which
4676 * buffers are actually bound.
4677 */
4678 void
4679 genX(cmd_buffer_set_binding_for_gen8_vb_flush)(struct anv_cmd_buffer *cmd_buffer,
4680 int vb_index,
4681 struct anv_address vb_address,
4682 uint32_t vb_size)
4683 {
4684 if (GEN_GEN < 8 || GEN_GEN > 9 ||
4685 !cmd_buffer->device->physical->use_softpin)
4686 return;
4687
4688 struct anv_vb_cache_range *bound, *dirty;
4689 if (vb_index == -1) {
4690 bound = &cmd_buffer->state.gfx.ib_bound_range;
4691 dirty = &cmd_buffer->state.gfx.ib_dirty_range;
4692 } else {
4693 assert(vb_index >= 0);
4694 assert(vb_index < ARRAY_SIZE(cmd_buffer->state.gfx.vb_bound_ranges));
4695 assert(vb_index < ARRAY_SIZE(cmd_buffer->state.gfx.vb_dirty_ranges));
4696 bound = &cmd_buffer->state.gfx.vb_bound_ranges[vb_index];
4697 dirty = &cmd_buffer->state.gfx.vb_dirty_ranges[vb_index];
4698 }
4699
4700 if (vb_size == 0) {
4701 bound->start = 0;
4702 bound->end = 0;
4703 return;
4704 }
4705
4706 assert(vb_address.bo && (vb_address.bo->flags & EXEC_OBJECT_PINNED));
4707 bound->start = gen_48b_address(anv_address_physical(vb_address));
4708 bound->end = bound->start + vb_size;
4709 assert(bound->end > bound->start); /* No overflow */
4710
4711 /* Align everything to a cache line */
4712 bound->start &= ~(64ull - 1ull);
4713 bound->end = align_u64(bound->end, 64);
4714
4715 /* Compute the dirty range */
4716 dirty->start = MIN2(dirty->start, bound->start);
4717 dirty->end = MAX2(dirty->end, bound->end);
4718
4719 /* If our range is larger than 32 bits, we have to flush */
4720 assert(bound->end - bound->start <= (1ull << 32));
4721 if (dirty->end - dirty->start > (1ull << 32)) {
4722 cmd_buffer->state.pending_pipe_bits |=
4723 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
4724 }
4725 }
4726
4727 void
4728 genX(cmd_buffer_update_dirty_vbs_for_gen8_vb_flush)(struct anv_cmd_buffer *cmd_buffer,
4729 uint32_t access_type,
4730 uint64_t vb_used)
4731 {
4732 if (GEN_GEN < 8 || GEN_GEN > 9 ||
4733 !cmd_buffer->device->physical->use_softpin)
4734 return;
4735
4736 if (access_type == RANDOM) {
4737 /* We have an index buffer */
4738 struct anv_vb_cache_range *bound = &cmd_buffer->state.gfx.ib_bound_range;
4739 struct anv_vb_cache_range *dirty = &cmd_buffer->state.gfx.ib_dirty_range;
4740
4741 if (bound->end > bound->start) {
4742 dirty->start = MIN2(dirty->start, bound->start);
4743 dirty->end = MAX2(dirty->end, bound->end);
4744 }
4745 }
4746
4747 uint64_t mask = vb_used;
4748 while (mask) {
4749 int i = u_bit_scan64(&mask);
4750 assert(i >= 0);
4751 assert(i < ARRAY_SIZE(cmd_buffer->state.gfx.vb_bound_ranges));
4752 assert(i < ARRAY_SIZE(cmd_buffer->state.gfx.vb_dirty_ranges));
4753
4754 struct anv_vb_cache_range *bound, *dirty;
4755 bound = &cmd_buffer->state.gfx.vb_bound_ranges[i];
4756 dirty = &cmd_buffer->state.gfx.vb_dirty_ranges[i];
4757
4758 if (bound->end > bound->start) {
4759 dirty->start = MIN2(dirty->start, bound->start);
4760 dirty->end = MAX2(dirty->end, bound->end);
4761 }
4762 }
4763 }
4764
4765 /**
4766 * Update the pixel hashing modes that determine the balancing of PS threads
4767 * across subslices and slices.
4768 *
4769 * \param width Width bound of the rendering area (already scaled down if \p
4770 * scale is greater than 1).
4771 * \param height Height bound of the rendering area (already scaled down if \p
4772 * scale is greater than 1).
4773 * \param scale The number of framebuffer samples that could potentially be
4774 * affected by an individual channel of the PS thread. This is
4775 * typically one for single-sampled rendering, but for operations
4776 * like CCS resolves and fast clears a single PS invocation may
4777 * update a huge number of pixels, in which case a finer
4778 * balancing is desirable in order to maximally utilize the
4779 * bandwidth available. UINT_MAX can be used as shorthand for
4780 * "finest hashing mode available".
4781 */
4782 void
4783 genX(cmd_buffer_emit_hashing_mode)(struct anv_cmd_buffer *cmd_buffer,
4784 unsigned width, unsigned height,
4785 unsigned scale)
4786 {
4787 #if GEN_GEN == 9
4788 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
4789 const unsigned slice_hashing[] = {
4790 /* Because all Gen9 platforms with more than one slice require
4791 * three-way subslice hashing, a single "normal" 16x16 slice hashing
4792 * block is guaranteed to suffer from substantial imbalance, with one
4793 * subslice receiving twice as much work as the other two in the
4794 * slice.
4795 *
4796 * The performance impact of that would be particularly severe when
4797 * three-way hashing is also in use for slice balancing (which is the
4798 * case for all Gen9 GT4 platforms), because one of the slices
4799 * receives one every three 16x16 blocks in either direction, which
4800 * is roughly the periodicity of the underlying subslice imbalance
4801 * pattern ("roughly" because in reality the hardware's
4802 * implementation of three-way hashing doesn't do exact modulo 3
4803 * arithmetic, which somewhat decreases the magnitude of this effect
4804 * in practice). This leads to a systematic subslice imbalance
4805 * within that slice regardless of the size of the primitive. The
4806 * 32x32 hashing mode guarantees that the subslice imbalance within a
4807 * single slice hashing block is minimal, largely eliminating this
4808 * effect.
4809 */
4810 _32x32,
4811 /* Finest slice hashing mode available. */
4812 NORMAL
4813 };
4814 const unsigned subslice_hashing[] = {
4815 /* 16x16 would provide a slight cache locality benefit especially
4816 * visible in the sampler L1 cache efficiency of low-bandwidth
4817 * non-LLC platforms, but it comes at the cost of greater subslice
4818 * imbalance for primitives of dimensions approximately intermediate
4819 * between 16x4 and 16x16.
4820 */
4821 _16x4,
4822 /* Finest subslice hashing mode available. */
4823 _8x4
4824 };
4825 /* Dimensions of the smallest hashing block of a given hashing mode. If
4826 * the rendering area is smaller than this there can't possibly be any
4827 * benefit from switching to this mode, so we optimize out the
4828 * transition.
4829 */
4830 const unsigned min_size[][2] = {
4831 { 16, 4 },
4832 { 8, 4 }
4833 };
4834 const unsigned idx = scale > 1;
4835
4836 if (cmd_buffer->state.current_hash_scale != scale &&
4837 (width > min_size[idx][0] || height > min_size[idx][1])) {
4838 uint32_t gt_mode;
4839
4840 anv_pack_struct(&gt_mode, GENX(GT_MODE),
4841 .SliceHashing = (devinfo->num_slices > 1 ? slice_hashing[idx] : 0),
4842 .SliceHashingMask = (devinfo->num_slices > 1 ? -1 : 0),
4843 .SubsliceHashing = subslice_hashing[idx],
4844 .SubsliceHashingMask = -1);
4845
4846 cmd_buffer->state.pending_pipe_bits |=
4847 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
4848 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4849
4850 emit_lri(&cmd_buffer->batch, GENX(GT_MODE_num), gt_mode);
4851
4852 cmd_buffer->state.current_hash_scale = scale;
4853 }
4854 #endif
4855 }
4856
4857 static void
4858 cmd_buffer_emit_depth_stencil(struct anv_cmd_buffer *cmd_buffer)
4859 {
4860 struct anv_device *device = cmd_buffer->device;
4861 const struct anv_image_view *iview =
4862 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
4863 const struct anv_image *image = iview ? iview->image : NULL;
4864
4865 /* FIXME: Width and Height are wrong */
4866
4867 genX(cmd_buffer_emit_gen7_depth_flush)(cmd_buffer);
4868
4869 uint32_t *dw = anv_batch_emit_dwords(&cmd_buffer->batch,
4870 device->isl_dev.ds.size / 4);
4871 if (dw == NULL)
4872 return;
4873
4874 struct isl_depth_stencil_hiz_emit_info info = { };
4875
4876 if (iview)
4877 info.view = &iview->planes[0].isl;
4878
4879 if (image && (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
4880 uint32_t depth_plane =
4881 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_DEPTH_BIT);
4882 const struct anv_surface *surface = &image->planes[depth_plane].surface;
4883
4884 info.depth_surf = &surface->isl;
4885
4886 info.depth_address =
4887 anv_batch_emit_reloc(&cmd_buffer->batch,
4888 dw + device->isl_dev.ds.depth_offset / 4,
4889 image->planes[depth_plane].address.bo,
4890 image->planes[depth_plane].address.offset +
4891 surface->offset);
4892 info.mocs =
4893 anv_mocs_for_bo(device, image->planes[depth_plane].address.bo);
4894
4895 const uint32_t ds =
4896 cmd_buffer->state.subpass->depth_stencil_attachment->attachment;
4897 info.hiz_usage = cmd_buffer->state.attachments[ds].aux_usage;
4898 if (info.hiz_usage != ISL_AUX_USAGE_NONE) {
4899 assert(isl_aux_usage_has_hiz(info.hiz_usage));
4900 info.hiz_surf = &image->planes[depth_plane].aux_surface.isl;
4901
4902 info.hiz_address =
4903 anv_batch_emit_reloc(&cmd_buffer->batch,
4904 dw + device->isl_dev.ds.hiz_offset / 4,
4905 image->planes[depth_plane].address.bo,
4906 image->planes[depth_plane].address.offset +
4907 image->planes[depth_plane].aux_surface.offset);
4908
4909 info.depth_clear_value = ANV_HZ_FC_VAL;
4910 }
4911 }
4912
4913 if (image && (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
4914 uint32_t stencil_plane =
4915 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_STENCIL_BIT);
4916 const struct anv_surface *surface = &image->planes[stencil_plane].surface;
4917
4918 info.stencil_surf = &surface->isl;
4919
4920 info.stencil_address =
4921 anv_batch_emit_reloc(&cmd_buffer->batch,
4922 dw + device->isl_dev.ds.stencil_offset / 4,
4923 image->planes[stencil_plane].address.bo,
4924 image->planes[stencil_plane].address.offset +
4925 surface->offset);
4926 info.mocs =
4927 anv_mocs_for_bo(device, image->planes[stencil_plane].address.bo);
4928 }
4929
4930 isl_emit_depth_stencil_hiz_s(&device->isl_dev, dw, &info);
4931
4932 if (GEN_GEN >= 12) {
4933 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_POST_SYNC_BIT;
4934 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4935
4936 /* GEN:BUG:1408224581
4937 *
4938 * Workaround: Gen12LP Astep only An additional pipe control with
4939 * post-sync = store dword operation would be required.( w/a is to
4940 * have an additional pipe control after the stencil state whenever
4941 * the surface state bits of this state is changing).
4942 */
4943 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4944 pc.PostSyncOperation = WriteImmediateData;
4945 pc.Address =
4946 (struct anv_address) { cmd_buffer->device->workaround_bo, 0 };
4947 }
4948 }
4949 cmd_buffer->state.hiz_enabled = isl_aux_usage_has_hiz(info.hiz_usage);
4950 }
4951
4952 /**
4953 * This ANDs the view mask of the current subpass with the pending clear
4954 * views in the attachment to get the mask of views active in the subpass
4955 * that still need to be cleared.
4956 */
4957 static inline uint32_t
4958 get_multiview_subpass_clear_mask(const struct anv_cmd_state *cmd_state,
4959 const struct anv_attachment_state *att_state)
4960 {
4961 return cmd_state->subpass->view_mask & att_state->pending_clear_views;
4962 }
4963
4964 static inline bool
4965 do_first_layer_clear(const struct anv_cmd_state *cmd_state,
4966 const struct anv_attachment_state *att_state)
4967 {
4968 if (!cmd_state->subpass->view_mask)
4969 return true;
4970
4971 uint32_t pending_clear_mask =
4972 get_multiview_subpass_clear_mask(cmd_state, att_state);
4973
4974 return pending_clear_mask & 1;
4975 }
4976
4977 static inline bool
4978 current_subpass_is_last_for_attachment(const struct anv_cmd_state *cmd_state,
4979 uint32_t att_idx)
4980 {
4981 const uint32_t last_subpass_idx =
4982 cmd_state->pass->attachments[att_idx].last_subpass_idx;
4983 const struct anv_subpass *last_subpass =
4984 &cmd_state->pass->subpasses[last_subpass_idx];
4985 return last_subpass == cmd_state->subpass;
4986 }
4987
4988 static void
4989 cmd_buffer_begin_subpass(struct anv_cmd_buffer *cmd_buffer,
4990 uint32_t subpass_id)
4991 {
4992 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4993 struct anv_render_pass *pass = cmd_state->pass;
4994 struct anv_subpass *subpass = &pass->subpasses[subpass_id];
4995 cmd_state->subpass = subpass;
4996
4997 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
4998
4999 /* Our implementation of VK_KHR_multiview uses instancing to draw the
5000 * different views. If the client asks for instancing, we need to use the
5001 * Instance Data Step Rate to ensure that we repeat the client's
5002 * per-instance data once for each view. Since this bit is in
5003 * VERTEX_BUFFER_STATE on gen7, we need to dirty vertex buffers at the top
5004 * of each subpass.
5005 */
5006 if (GEN_GEN == 7)
5007 cmd_buffer->state.gfx.vb_dirty |= ~0;
5008
5009 /* It is possible to start a render pass with an old pipeline. Because the
5010 * render pass and subpass index are both baked into the pipeline, this is
5011 * highly unlikely. In order to do so, it requires that you have a render
5012 * pass with a single subpass and that you use that render pass twice
5013 * back-to-back and use the same pipeline at the start of the second render
5014 * pass as at the end of the first. In order to avoid unpredictable issues
5015 * with this edge case, we just dirty the pipeline at the start of every
5016 * subpass.
5017 */
5018 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_PIPELINE;
5019
5020 /* Accumulate any subpass flushes that need to happen before the subpass */
5021 cmd_buffer->state.pending_pipe_bits |=
5022 cmd_buffer->state.pass->subpass_flushes[subpass_id];
5023
5024 VkRect2D render_area = cmd_buffer->state.render_area;
5025 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
5026
5027 bool is_multiview = subpass->view_mask != 0;
5028
5029 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
5030 const uint32_t a = subpass->attachments[i].attachment;
5031 if (a == VK_ATTACHMENT_UNUSED)
5032 continue;
5033
5034 assert(a < cmd_state->pass->attachment_count);
5035 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
5036
5037 struct anv_image_view *iview = cmd_state->attachments[a].image_view;
5038 const struct anv_image *image = iview->image;
5039
5040 VkImageLayout target_layout = subpass->attachments[i].layout;
5041 VkImageLayout target_stencil_layout =
5042 subpass->attachments[i].stencil_layout;
5043
5044 uint32_t base_layer, layer_count;
5045 if (image->type == VK_IMAGE_TYPE_3D) {
5046 base_layer = 0;
5047 layer_count = anv_minify(iview->image->extent.depth,
5048 iview->planes[0].isl.base_level);
5049 } else {
5050 base_layer = iview->planes[0].isl.base_array_layer;
5051 layer_count = fb->layers;
5052 }
5053
5054 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
5055 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
5056 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
5057 iview->planes[0].isl.base_level, 1,
5058 base_layer, layer_count,
5059 att_state->current_layout, target_layout);
5060 att_state->aux_usage =
5061 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
5062 VK_IMAGE_ASPECT_COLOR_BIT,
5063 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
5064 target_layout);
5065 }
5066
5067 if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
5068 transition_depth_buffer(cmd_buffer, image,
5069 base_layer, layer_count,
5070 att_state->current_layout, target_layout);
5071 att_state->aux_usage =
5072 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
5073 VK_IMAGE_ASPECT_DEPTH_BIT,
5074 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
5075 target_layout);
5076 }
5077
5078 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
5079 transition_stencil_buffer(cmd_buffer, image,
5080 iview->planes[0].isl.base_level, 1,
5081 base_layer, layer_count,
5082 att_state->current_stencil_layout,
5083 target_stencil_layout);
5084 }
5085 att_state->current_layout = target_layout;
5086 att_state->current_stencil_layout = target_stencil_layout;
5087
5088 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
5089 assert(att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
5090
5091 /* Multi-planar images are not supported as attachments */
5092 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
5093 assert(image->n_planes == 1);
5094
5095 uint32_t base_clear_layer = iview->planes[0].isl.base_array_layer;
5096 uint32_t clear_layer_count = fb->layers;
5097
5098 if (att_state->fast_clear &&
5099 do_first_layer_clear(cmd_state, att_state)) {
5100 /* We only support fast-clears on the first layer */
5101 assert(iview->planes[0].isl.base_level == 0);
5102 assert(iview->planes[0].isl.base_array_layer == 0);
5103
5104 union isl_color_value clear_color = {};
5105 anv_clear_color_from_att_state(&clear_color, att_state, iview);
5106 if (iview->image->samples == 1) {
5107 anv_image_ccs_op(cmd_buffer, image,
5108 iview->planes[0].isl.format,
5109 iview->planes[0].isl.swizzle,
5110 VK_IMAGE_ASPECT_COLOR_BIT,
5111 0, 0, 1, ISL_AUX_OP_FAST_CLEAR,
5112 &clear_color,
5113 false);
5114 } else {
5115 anv_image_mcs_op(cmd_buffer, image,
5116 iview->planes[0].isl.format,
5117 iview->planes[0].isl.swizzle,
5118 VK_IMAGE_ASPECT_COLOR_BIT,
5119 0, 1, ISL_AUX_OP_FAST_CLEAR,
5120 &clear_color,
5121 false);
5122 }
5123 base_clear_layer++;
5124 clear_layer_count--;
5125 if (is_multiview)
5126 att_state->pending_clear_views &= ~1;
5127
5128 if (isl_color_value_is_zero(clear_color,
5129 iview->planes[0].isl.format)) {
5130 /* This image has the auxiliary buffer enabled. We can mark the
5131 * subresource as not needing a resolve because the clear color
5132 * will match what's in every RENDER_SURFACE_STATE object when
5133 * it's being used for sampling.
5134 */
5135 set_image_fast_clear_state(cmd_buffer, iview->image,
5136 VK_IMAGE_ASPECT_COLOR_BIT,
5137 ANV_FAST_CLEAR_DEFAULT_VALUE);
5138 } else {
5139 set_image_fast_clear_state(cmd_buffer, iview->image,
5140 VK_IMAGE_ASPECT_COLOR_BIT,
5141 ANV_FAST_CLEAR_ANY);
5142 }
5143 }
5144
5145 /* From the VkFramebufferCreateInfo spec:
5146 *
5147 * "If the render pass uses multiview, then layers must be one and each
5148 * attachment requires a number of layers that is greater than the
5149 * maximum bit index set in the view mask in the subpasses in which it
5150 * is used."
5151 *
5152 * So if multiview is active we ignore the number of layers in the
5153 * framebuffer and instead we honor the view mask from the subpass.
5154 */
5155 if (is_multiview) {
5156 assert(image->n_planes == 1);
5157 uint32_t pending_clear_mask =
5158 get_multiview_subpass_clear_mask(cmd_state, att_state);
5159
5160 uint32_t layer_idx;
5161 for_each_bit(layer_idx, pending_clear_mask) {
5162 uint32_t layer =
5163 iview->planes[0].isl.base_array_layer + layer_idx;
5164
5165 anv_image_clear_color(cmd_buffer, image,
5166 VK_IMAGE_ASPECT_COLOR_BIT,
5167 att_state->aux_usage,
5168 iview->planes[0].isl.format,
5169 iview->planes[0].isl.swizzle,
5170 iview->planes[0].isl.base_level,
5171 layer, 1,
5172 render_area,
5173 vk_to_isl_color(att_state->clear_value.color));
5174 }
5175
5176 att_state->pending_clear_views &= ~pending_clear_mask;
5177 } else if (clear_layer_count > 0) {
5178 assert(image->n_planes == 1);
5179 anv_image_clear_color(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
5180 att_state->aux_usage,
5181 iview->planes[0].isl.format,
5182 iview->planes[0].isl.swizzle,
5183 iview->planes[0].isl.base_level,
5184 base_clear_layer, clear_layer_count,
5185 render_area,
5186 vk_to_isl_color(att_state->clear_value.color));
5187 }
5188 } else if (att_state->pending_clear_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT |
5189 VK_IMAGE_ASPECT_STENCIL_BIT)) {
5190 if (att_state->fast_clear && !is_multiview) {
5191 /* We currently only support HiZ for single-LOD images */
5192 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
5193 assert(isl_aux_usage_has_hiz(iview->image->planes[0].aux_usage));
5194 assert(iview->planes[0].isl.base_level == 0);
5195 }
5196
5197 anv_image_hiz_clear(cmd_buffer, image,
5198 att_state->pending_clear_aspects,
5199 iview->planes[0].isl.base_level,
5200 iview->planes[0].isl.base_array_layer,
5201 fb->layers, render_area,
5202 att_state->clear_value.depthStencil.stencil);
5203 } else if (is_multiview) {
5204 uint32_t pending_clear_mask =
5205 get_multiview_subpass_clear_mask(cmd_state, att_state);
5206
5207 uint32_t layer_idx;
5208 for_each_bit(layer_idx, pending_clear_mask) {
5209 uint32_t layer =
5210 iview->planes[0].isl.base_array_layer + layer_idx;
5211
5212 anv_image_clear_depth_stencil(cmd_buffer, image,
5213 att_state->pending_clear_aspects,
5214 att_state->aux_usage,
5215 iview->planes[0].isl.base_level,
5216 layer, 1,
5217 render_area,
5218 att_state->clear_value.depthStencil.depth,
5219 att_state->clear_value.depthStencil.stencil);
5220 }
5221
5222 att_state->pending_clear_views &= ~pending_clear_mask;
5223 } else {
5224 anv_image_clear_depth_stencil(cmd_buffer, image,
5225 att_state->pending_clear_aspects,
5226 att_state->aux_usage,
5227 iview->planes[0].isl.base_level,
5228 iview->planes[0].isl.base_array_layer,
5229 fb->layers, render_area,
5230 att_state->clear_value.depthStencil.depth,
5231 att_state->clear_value.depthStencil.stencil);
5232 }
5233 } else {
5234 assert(att_state->pending_clear_aspects == 0);
5235 }
5236
5237 /* If multiview is enabled, then we are only done clearing when we no
5238 * longer have pending layers to clear, or when we have processed the
5239 * last subpass that uses this attachment.
5240 */
5241 if (!is_multiview ||
5242 att_state->pending_clear_views == 0 ||
5243 current_subpass_is_last_for_attachment(cmd_state, a)) {
5244 att_state->pending_clear_aspects = 0;
5245 }
5246
5247 att_state->pending_load_aspects = 0;
5248 }
5249
5250 /* We've transitioned all our images possibly fast clearing them. Now we
5251 * can fill out the surface states that we will use as render targets
5252 * during actual subpass rendering.
5253 */
5254 VkResult result = genX(cmd_buffer_alloc_att_surf_states)(cmd_buffer,
5255 pass, subpass);
5256 if (result != VK_SUCCESS)
5257 return;
5258
5259 isl_null_fill_state(&cmd_buffer->device->isl_dev,
5260 cmd_state->null_surface_state.map,
5261 isl_extent3d(fb->width, fb->height, fb->layers));
5262
5263 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
5264 const uint32_t att = subpass->attachments[i].attachment;
5265 if (att == VK_ATTACHMENT_UNUSED)
5266 continue;
5267
5268 assert(att < cmd_state->pass->attachment_count);
5269 struct anv_render_pass_attachment *pass_att = &pass->attachments[att];
5270 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
5271 struct anv_image_view *iview = att_state->image_view;
5272
5273 if (!vk_format_is_color(pass_att->format))
5274 continue;
5275
5276 const VkImageUsageFlagBits att_usage = subpass->attachments[i].usage;
5277 assert(util_bitcount(att_usage) == 1);
5278
5279 struct anv_surface_state *surface_state;
5280 isl_surf_usage_flags_t isl_surf_usage;
5281 enum isl_aux_usage isl_aux_usage;
5282 if (att_usage == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
5283 surface_state = &att_state->color;
5284 isl_surf_usage = ISL_SURF_USAGE_RENDER_TARGET_BIT;
5285 isl_aux_usage = att_state->aux_usage;
5286 } else if (att_usage == VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) {
5287 surface_state = &att_state->input;
5288 isl_surf_usage = ISL_SURF_USAGE_TEXTURE_BIT;
5289 isl_aux_usage =
5290 anv_layout_to_aux_usage(&cmd_buffer->device->info, iview->image,
5291 VK_IMAGE_ASPECT_COLOR_BIT,
5292 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT,
5293 att_state->current_layout);
5294 } else {
5295 continue;
5296 }
5297
5298 /* We had better have a surface state when we get here */
5299 assert(surface_state->state.map);
5300
5301 union isl_color_value clear_color = { .u32 = { 0, } };
5302 if (pass_att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR &&
5303 att_state->fast_clear)
5304 anv_clear_color_from_att_state(&clear_color, att_state, iview);
5305
5306 anv_image_fill_surface_state(cmd_buffer->device,
5307 iview->image,
5308 VK_IMAGE_ASPECT_COLOR_BIT,
5309 &iview->planes[0].isl,
5310 isl_surf_usage,
5311 isl_aux_usage,
5312 &clear_color,
5313 0,
5314 surface_state,
5315 NULL);
5316
5317 add_surface_state_relocs(cmd_buffer, *surface_state);
5318
5319 if (GEN_GEN < 10 &&
5320 pass_att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD &&
5321 iview->image->planes[0].aux_usage != ISL_AUX_USAGE_NONE &&
5322 iview->planes[0].isl.base_level == 0 &&
5323 iview->planes[0].isl.base_array_layer == 0) {
5324 genX(copy_fast_clear_dwords)(cmd_buffer, surface_state->state,
5325 iview->image,
5326 VK_IMAGE_ASPECT_COLOR_BIT,
5327 false /* copy to ss */);
5328 }
5329 }
5330
5331 #if GEN_GEN >= 11
5332 /* The PIPE_CONTROL command description says:
5333 *
5334 * "Whenever a Binding Table Index (BTI) used by a Render Taget Message
5335 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
5336 * Target Cache Flush by enabling this bit. When render target flush
5337 * is set due to new association of BTI, PS Scoreboard Stall bit must
5338 * be set in this packet."
5339 */
5340 cmd_buffer->state.pending_pipe_bits |=
5341 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT |
5342 ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
5343 #endif
5344
5345 #if GEN_GEN == 12
5346 /* GEN:BUG:14010455700
5347 *
5348 * ISL will change some CHICKEN registers depending on the depth surface
5349 * format, along with emitting the depth and stencil packets. In that case,
5350 * we want to do a depth flush and stall, so the pipeline is not using these
5351 * settings while we change the registers.
5352 */
5353 cmd_buffer->state.pending_pipe_bits |=
5354 ANV_PIPE_DEPTH_CACHE_FLUSH_BIT |
5355 ANV_PIPE_DEPTH_STALL_BIT |
5356 ANV_PIPE_END_OF_PIPE_SYNC_BIT;
5357 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
5358 #endif
5359
5360 cmd_buffer_emit_depth_stencil(cmd_buffer);
5361 }
5362
5363 static enum blorp_filter
5364 vk_to_blorp_resolve_mode(VkResolveModeFlagBitsKHR vk_mode)
5365 {
5366 switch (vk_mode) {
5367 case VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR:
5368 return BLORP_FILTER_SAMPLE_0;
5369 case VK_RESOLVE_MODE_AVERAGE_BIT_KHR:
5370 return BLORP_FILTER_AVERAGE;
5371 case VK_RESOLVE_MODE_MIN_BIT_KHR:
5372 return BLORP_FILTER_MIN_SAMPLE;
5373 case VK_RESOLVE_MODE_MAX_BIT_KHR:
5374 return BLORP_FILTER_MAX_SAMPLE;
5375 default:
5376 return BLORP_FILTER_NONE;
5377 }
5378 }
5379
5380 static void
5381 cmd_buffer_end_subpass(struct anv_cmd_buffer *cmd_buffer)
5382 {
5383 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
5384 struct anv_subpass *subpass = cmd_state->subpass;
5385 uint32_t subpass_id = anv_get_subpass_id(&cmd_buffer->state);
5386 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
5387
5388 /* We are done with the previous subpass and all rendering directly to that
5389 * subpass is now complete. Zero out all the surface states so we don't
5390 * accidentally use them between now and the next subpass.
5391 */
5392 for (uint32_t i = 0; i < cmd_state->pass->attachment_count; ++i) {
5393 memset(&cmd_state->attachments[i].color, 0,
5394 sizeof(cmd_state->attachments[i].color));
5395 memset(&cmd_state->attachments[i].input, 0,
5396 sizeof(cmd_state->attachments[i].input));
5397 }
5398 cmd_state->null_surface_state = ANV_STATE_NULL;
5399 cmd_state->attachment_states = ANV_STATE_NULL;
5400
5401 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
5402 const uint32_t a = subpass->attachments[i].attachment;
5403 if (a == VK_ATTACHMENT_UNUSED)
5404 continue;
5405
5406 assert(a < cmd_state->pass->attachment_count);
5407 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
5408 struct anv_image_view *iview = att_state->image_view;
5409
5410 assert(util_bitcount(subpass->attachments[i].usage) == 1);
5411 if (subpass->attachments[i].usage ==
5412 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
5413 /* We assume that if we're ending a subpass, we did do some rendering
5414 * so we may end up with compressed data.
5415 */
5416 genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
5417 VK_IMAGE_ASPECT_COLOR_BIT,
5418 att_state->aux_usage,
5419 iview->planes[0].isl.base_level,
5420 iview->planes[0].isl.base_array_layer,
5421 fb->layers);
5422 } else if (subpass->attachments[i].usage ==
5423 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
5424 /* We may be writing depth or stencil so we need to mark the surface.
5425 * Unfortunately, there's no way to know at this point whether the
5426 * depth or stencil tests used will actually write to the surface.
5427 *
5428 * Even though stencil may be plane 1, it always shares a base_level
5429 * with depth.
5430 */
5431 const struct isl_view *ds_view = &iview->planes[0].isl;
5432 if (iview->aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
5433 genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
5434 VK_IMAGE_ASPECT_DEPTH_BIT,
5435 att_state->aux_usage,
5436 ds_view->base_level,
5437 ds_view->base_array_layer,
5438 fb->layers);
5439 }
5440 if (iview->aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
5441 /* Even though stencil may be plane 1, it always shares a
5442 * base_level with depth.
5443 */
5444 genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
5445 VK_IMAGE_ASPECT_STENCIL_BIT,
5446 ISL_AUX_USAGE_NONE,
5447 ds_view->base_level,
5448 ds_view->base_array_layer,
5449 fb->layers);
5450 }
5451 }
5452 }
5453
5454 if (subpass->has_color_resolve) {
5455 /* We are about to do some MSAA resolves. We need to flush so that the
5456 * result of writes to the MSAA color attachments show up in the sampler
5457 * when we blit to the single-sampled resolve target.
5458 */
5459 cmd_buffer->state.pending_pipe_bits |=
5460 ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
5461 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
5462
5463 for (uint32_t i = 0; i < subpass->color_count; ++i) {
5464 uint32_t src_att = subpass->color_attachments[i].attachment;
5465 uint32_t dst_att = subpass->resolve_attachments[i].attachment;
5466
5467 if (dst_att == VK_ATTACHMENT_UNUSED)
5468 continue;
5469
5470 assert(src_att < cmd_buffer->state.pass->attachment_count);
5471 assert(dst_att < cmd_buffer->state.pass->attachment_count);
5472
5473 if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
5474 /* From the Vulkan 1.0 spec:
5475 *
5476 * If the first use of an attachment in a render pass is as a
5477 * resolve attachment, then the loadOp is effectively ignored
5478 * as the resolve is guaranteed to overwrite all pixels in the
5479 * render area.
5480 */
5481 cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
5482 }
5483
5484 struct anv_image_view *src_iview = cmd_state->attachments[src_att].image_view;
5485 struct anv_image_view *dst_iview = cmd_state->attachments[dst_att].image_view;
5486
5487 const VkRect2D render_area = cmd_buffer->state.render_area;
5488
5489 enum isl_aux_usage src_aux_usage =
5490 cmd_buffer->state.attachments[src_att].aux_usage;
5491 enum isl_aux_usage dst_aux_usage =
5492 cmd_buffer->state.attachments[dst_att].aux_usage;
5493
5494 assert(src_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT &&
5495 dst_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT);
5496
5497 anv_image_msaa_resolve(cmd_buffer,
5498 src_iview->image, src_aux_usage,
5499 src_iview->planes[0].isl.base_level,
5500 src_iview->planes[0].isl.base_array_layer,
5501 dst_iview->image, dst_aux_usage,
5502 dst_iview->planes[0].isl.base_level,
5503 dst_iview->planes[0].isl.base_array_layer,
5504 VK_IMAGE_ASPECT_COLOR_BIT,
5505 render_area.offset.x, render_area.offset.y,
5506 render_area.offset.x, render_area.offset.y,
5507 render_area.extent.width,
5508 render_area.extent.height,
5509 fb->layers, BLORP_FILTER_NONE);
5510 }
5511 }
5512
5513 if (subpass->ds_resolve_attachment) {
5514 /* We are about to do some MSAA resolves. We need to flush so that the
5515 * result of writes to the MSAA depth attachments show up in the sampler
5516 * when we blit to the single-sampled resolve target.
5517 */
5518 cmd_buffer->state.pending_pipe_bits |=
5519 ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
5520 ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
5521
5522 uint32_t src_att = subpass->depth_stencil_attachment->attachment;
5523 uint32_t dst_att = subpass->ds_resolve_attachment->attachment;
5524
5525 assert(src_att < cmd_buffer->state.pass->attachment_count);
5526 assert(dst_att < cmd_buffer->state.pass->attachment_count);
5527
5528 if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
5529 /* From the Vulkan 1.0 spec:
5530 *
5531 * If the first use of an attachment in a render pass is as a
5532 * resolve attachment, then the loadOp is effectively ignored
5533 * as the resolve is guaranteed to overwrite all pixels in the
5534 * render area.
5535 */
5536 cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
5537 }
5538
5539 struct anv_image_view *src_iview = cmd_state->attachments[src_att].image_view;
5540 struct anv_image_view *dst_iview = cmd_state->attachments[dst_att].image_view;
5541
5542 const VkRect2D render_area = cmd_buffer->state.render_area;
5543
5544 struct anv_attachment_state *src_state =
5545 &cmd_state->attachments[src_att];
5546 struct anv_attachment_state *dst_state =
5547 &cmd_state->attachments[dst_att];
5548
5549 if ((src_iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
5550 subpass->depth_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
5551
5552 /* MSAA resolves sample from the source attachment. Transition the
5553 * depth attachment first to get rid of any HiZ that we may not be
5554 * able to handle.
5555 */
5556 transition_depth_buffer(cmd_buffer, src_iview->image,
5557 src_iview->planes[0].isl.base_array_layer,
5558 fb->layers,
5559 src_state->current_layout,
5560 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
5561 src_state->aux_usage =
5562 anv_layout_to_aux_usage(&cmd_buffer->device->info, src_iview->image,
5563 VK_IMAGE_ASPECT_DEPTH_BIT,
5564 VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
5565 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
5566 src_state->current_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
5567
5568 /* MSAA resolves write to the resolve attachment as if it were any
5569 * other transfer op. Transition the resolve attachment accordingly.
5570 */
5571 VkImageLayout dst_initial_layout = dst_state->current_layout;
5572
5573 /* If our render area is the entire size of the image, we're going to
5574 * blow it all away so we can claim the initial layout is UNDEFINED
5575 * and we'll get a HiZ ambiguate instead of a resolve.
5576 */
5577 if (dst_iview->image->type != VK_IMAGE_TYPE_3D &&
5578 render_area.offset.x == 0 && render_area.offset.y == 0 &&
5579 render_area.extent.width == dst_iview->extent.width &&
5580 render_area.extent.height == dst_iview->extent.height)
5581 dst_initial_layout = VK_IMAGE_LAYOUT_UNDEFINED;
5582
5583 transition_depth_buffer(cmd_buffer, dst_iview->image,
5584 dst_iview->planes[0].isl.base_array_layer,
5585 fb->layers,
5586 dst_initial_layout,
5587 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
5588 dst_state->aux_usage =
5589 anv_layout_to_aux_usage(&cmd_buffer->device->info, dst_iview->image,
5590 VK_IMAGE_ASPECT_DEPTH_BIT,
5591 VK_IMAGE_USAGE_TRANSFER_DST_BIT,
5592 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
5593 dst_state->current_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
5594
5595 enum blorp_filter filter =
5596 vk_to_blorp_resolve_mode(subpass->depth_resolve_mode);
5597
5598 anv_image_msaa_resolve(cmd_buffer,
5599 src_iview->image, src_state->aux_usage,
5600 src_iview->planes[0].isl.base_level,
5601 src_iview->planes[0].isl.base_array_layer,
5602 dst_iview->image, dst_state->aux_usage,
5603 dst_iview->planes[0].isl.base_level,
5604 dst_iview->planes[0].isl.base_array_layer,
5605 VK_IMAGE_ASPECT_DEPTH_BIT,
5606 render_area.offset.x, render_area.offset.y,
5607 render_area.offset.x, render_area.offset.y,
5608 render_area.extent.width,
5609 render_area.extent.height,
5610 fb->layers, filter);
5611 }
5612
5613 if ((src_iview->image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
5614 subpass->stencil_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
5615
5616 src_state->current_stencil_layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
5617 dst_state->current_stencil_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
5618
5619 enum isl_aux_usage src_aux_usage = ISL_AUX_USAGE_NONE;
5620 enum isl_aux_usage dst_aux_usage = ISL_AUX_USAGE_NONE;
5621
5622 enum blorp_filter filter =
5623 vk_to_blorp_resolve_mode(subpass->stencil_resolve_mode);
5624
5625 anv_image_msaa_resolve(cmd_buffer,
5626 src_iview->image, src_aux_usage,
5627 src_iview->planes[0].isl.base_level,
5628 src_iview->planes[0].isl.base_array_layer,
5629 dst_iview->image, dst_aux_usage,
5630 dst_iview->planes[0].isl.base_level,
5631 dst_iview->planes[0].isl.base_array_layer,
5632 VK_IMAGE_ASPECT_STENCIL_BIT,
5633 render_area.offset.x, render_area.offset.y,
5634 render_area.offset.x, render_area.offset.y,
5635 render_area.extent.width,
5636 render_area.extent.height,
5637 fb->layers, filter);
5638 }
5639 }
5640
5641 #if GEN_GEN == 7
5642 /* On gen7, we have to store a texturable version of the stencil buffer in
5643 * a shadow whenever VK_IMAGE_USAGE_SAMPLED_BIT is set and copy back and
5644 * forth at strategic points. Stencil writes are only allowed in following
5645 * layouts:
5646 *
5647 * - VK_IMAGE_LAYOUT_GENERAL
5648 * - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
5649 * - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
5650 * - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL
5651 * - VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR
5652 *
5653 * For general, we have no nice opportunity to transition so we do the copy
5654 * to the shadow unconditionally at the end of the subpass. For transfer
5655 * destinations, we can update it as part of the transfer op. For the other
5656 * layouts, we delay the copy until a transition into some other layout.
5657 */
5658 if (subpass->depth_stencil_attachment) {
5659 uint32_t a = subpass->depth_stencil_attachment->attachment;
5660 assert(a != VK_ATTACHMENT_UNUSED);
5661
5662 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
5663 struct anv_image_view *iview = cmd_state->attachments[a].image_view;;
5664 const struct anv_image *image = iview->image;
5665
5666 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
5667 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
5668 VK_IMAGE_ASPECT_STENCIL_BIT);
5669
5670 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
5671 att_state->current_stencil_layout == VK_IMAGE_LAYOUT_GENERAL) {
5672 assert(image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT);
5673 anv_image_copy_to_shadow(cmd_buffer, image,
5674 VK_IMAGE_ASPECT_STENCIL_BIT,
5675 iview->planes[plane].isl.base_level, 1,
5676 iview->planes[plane].isl.base_array_layer,
5677 fb->layers);
5678 }
5679 }
5680 }
5681 #endif /* GEN_GEN == 7 */
5682
5683 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
5684 const uint32_t a = subpass->attachments[i].attachment;
5685 if (a == VK_ATTACHMENT_UNUSED)
5686 continue;
5687
5688 if (cmd_state->pass->attachments[a].last_subpass_idx != subpass_id)
5689 continue;
5690
5691 assert(a < cmd_state->pass->attachment_count);
5692 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
5693 struct anv_image_view *iview = cmd_state->attachments[a].image_view;
5694 const struct anv_image *image = iview->image;
5695
5696 /* Transition the image into the final layout for this render pass */
5697 VkImageLayout target_layout =
5698 cmd_state->pass->attachments[a].final_layout;
5699 VkImageLayout target_stencil_layout =
5700 cmd_state->pass->attachments[a].stencil_final_layout;
5701
5702 uint32_t base_layer, layer_count;
5703 if (image->type == VK_IMAGE_TYPE_3D) {
5704 base_layer = 0;
5705 layer_count = anv_minify(iview->image->extent.depth,
5706 iview->planes[0].isl.base_level);
5707 } else {
5708 base_layer = iview->planes[0].isl.base_array_layer;
5709 layer_count = fb->layers;
5710 }
5711
5712 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
5713 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
5714 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
5715 iview->planes[0].isl.base_level, 1,
5716 base_layer, layer_count,
5717 att_state->current_layout, target_layout);
5718 }
5719
5720 if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
5721 transition_depth_buffer(cmd_buffer, image,
5722 base_layer, layer_count,
5723 att_state->current_layout, target_layout);
5724 }
5725
5726 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
5727 transition_stencil_buffer(cmd_buffer, image,
5728 iview->planes[0].isl.base_level, 1,
5729 base_layer, layer_count,
5730 att_state->current_stencil_layout,
5731 target_stencil_layout);
5732 }
5733 }
5734
5735 /* Accumulate any subpass flushes that need to happen after the subpass.
5736 * Yes, they do get accumulated twice in the NextSubpass case but since
5737 * genX_CmdNextSubpass just calls end/begin back-to-back, we just end up
5738 * ORing the bits in twice so it's harmless.
5739 */
5740 cmd_buffer->state.pending_pipe_bits |=
5741 cmd_buffer->state.pass->subpass_flushes[subpass_id + 1];
5742 }
5743
5744 void genX(CmdBeginRenderPass)(
5745 VkCommandBuffer commandBuffer,
5746 const VkRenderPassBeginInfo* pRenderPassBegin,
5747 VkSubpassContents contents)
5748 {
5749 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5750 ANV_FROM_HANDLE(anv_render_pass, pass, pRenderPassBegin->renderPass);
5751 ANV_FROM_HANDLE(anv_framebuffer, framebuffer, pRenderPassBegin->framebuffer);
5752 VkResult result;
5753
5754 cmd_buffer->state.framebuffer = framebuffer;
5755 cmd_buffer->state.pass = pass;
5756 cmd_buffer->state.render_area = pRenderPassBegin->renderArea;
5757
5758 result = genX(cmd_buffer_setup_attachments)(cmd_buffer, pass,
5759 framebuffer,
5760 pRenderPassBegin);
5761 if (result != VK_SUCCESS) {
5762 assert(anv_batch_has_error(&cmd_buffer->batch));
5763 return;
5764 }
5765
5766 genX(flush_pipeline_select_3d)(cmd_buffer);
5767
5768 cmd_buffer_begin_subpass(cmd_buffer, 0);
5769 }
5770
5771 void genX(CmdBeginRenderPass2)(
5772 VkCommandBuffer commandBuffer,
5773 const VkRenderPassBeginInfo* pRenderPassBeginInfo,
5774 const VkSubpassBeginInfoKHR* pSubpassBeginInfo)
5775 {
5776 genX(CmdBeginRenderPass)(commandBuffer, pRenderPassBeginInfo,
5777 pSubpassBeginInfo->contents);
5778 }
5779
5780 void genX(CmdNextSubpass)(
5781 VkCommandBuffer commandBuffer,
5782 VkSubpassContents contents)
5783 {
5784 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5785
5786 if (anv_batch_has_error(&cmd_buffer->batch))
5787 return;
5788
5789 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
5790
5791 uint32_t prev_subpass = anv_get_subpass_id(&cmd_buffer->state);
5792 cmd_buffer_end_subpass(cmd_buffer);
5793 cmd_buffer_begin_subpass(cmd_buffer, prev_subpass + 1);
5794 }
5795
5796 void genX(CmdNextSubpass2)(
5797 VkCommandBuffer commandBuffer,
5798 const VkSubpassBeginInfoKHR* pSubpassBeginInfo,
5799 const VkSubpassEndInfoKHR* pSubpassEndInfo)
5800 {
5801 genX(CmdNextSubpass)(commandBuffer, pSubpassBeginInfo->contents);
5802 }
5803
5804 void genX(CmdEndRenderPass)(
5805 VkCommandBuffer commandBuffer)
5806 {
5807 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5808
5809 if (anv_batch_has_error(&cmd_buffer->batch))
5810 return;
5811
5812 cmd_buffer_end_subpass(cmd_buffer);
5813
5814 cmd_buffer->state.hiz_enabled = false;
5815
5816 #ifndef NDEBUG
5817 anv_dump_add_attachments(cmd_buffer);
5818 #endif
5819
5820 /* Remove references to render pass specific state. This enables us to
5821 * detect whether or not we're in a renderpass.
5822 */
5823 cmd_buffer->state.framebuffer = NULL;
5824 cmd_buffer->state.pass = NULL;
5825 cmd_buffer->state.subpass = NULL;
5826 }
5827
5828 void genX(CmdEndRenderPass2)(
5829 VkCommandBuffer commandBuffer,
5830 const VkSubpassEndInfoKHR* pSubpassEndInfo)
5831 {
5832 genX(CmdEndRenderPass)(commandBuffer);
5833 }
5834
5835 void
5836 genX(cmd_emit_conditional_render_predicate)(struct anv_cmd_buffer *cmd_buffer)
5837 {
5838 #if GEN_GEN >= 8 || GEN_IS_HASWELL
5839 struct gen_mi_builder b;
5840 gen_mi_builder_init(&b, &cmd_buffer->batch);
5841
5842 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
5843 gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
5844 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
5845
5846 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
5847 mip.LoadOperation = LOAD_LOADINV;
5848 mip.CombineOperation = COMBINE_SET;
5849 mip.CompareOperation = COMPARE_SRCS_EQUAL;
5850 }
5851 #endif
5852 }
5853
5854 #if GEN_GEN >= 8 || GEN_IS_HASWELL
5855 void genX(CmdBeginConditionalRenderingEXT)(
5856 VkCommandBuffer commandBuffer,
5857 const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin)
5858 {
5859 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5860 ANV_FROM_HANDLE(anv_buffer, buffer, pConditionalRenderingBegin->buffer);
5861 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
5862 struct anv_address value_address =
5863 anv_address_add(buffer->address, pConditionalRenderingBegin->offset);
5864
5865 const bool isInverted = pConditionalRenderingBegin->flags &
5866 VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT;
5867
5868 cmd_state->conditional_render_enabled = true;
5869
5870 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
5871
5872 struct gen_mi_builder b;
5873 gen_mi_builder_init(&b, &cmd_buffer->batch);
5874
5875 /* Section 19.4 of the Vulkan 1.1.85 spec says:
5876 *
5877 * If the value of the predicate in buffer memory changes
5878 * while conditional rendering is active, the rendering commands
5879 * may be discarded in an implementation-dependent way.
5880 * Some implementations may latch the value of the predicate
5881 * upon beginning conditional rendering while others
5882 * may read it before every rendering command.
5883 *
5884 * So it's perfectly fine to read a value from the buffer once.
5885 */
5886 struct gen_mi_value value = gen_mi_mem32(value_address);
5887
5888 /* Precompute predicate result, it is necessary to support secondary
5889 * command buffers since it is unknown if conditional rendering is
5890 * inverted when populating them.
5891 */
5892 gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
5893 isInverted ? gen_mi_uge(&b, gen_mi_imm(0), value) :
5894 gen_mi_ult(&b, gen_mi_imm(0), value));
5895 }
5896
5897 void genX(CmdEndConditionalRenderingEXT)(
5898 VkCommandBuffer commandBuffer)
5899 {
5900 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5901 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
5902
5903 cmd_state->conditional_render_enabled = false;
5904 }
5905 #endif
5906
5907 /* Set of stage bits for which are pipelined, i.e. they get queued by the
5908 * command streamer for later execution.
5909 */
5910 #define ANV_PIPELINE_STAGE_PIPELINED_BITS \
5911 (VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | \
5912 VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | \
5913 VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | \
5914 VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | \
5915 VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | \
5916 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | \
5917 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | \
5918 VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | \
5919 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | \
5920 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | \
5921 VK_PIPELINE_STAGE_TRANSFER_BIT | \
5922 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | \
5923 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | \
5924 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)
5925
5926 void genX(CmdSetEvent)(
5927 VkCommandBuffer commandBuffer,
5928 VkEvent _event,
5929 VkPipelineStageFlags stageMask)
5930 {
5931 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5932 ANV_FROM_HANDLE(anv_event, event, _event);
5933
5934 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_POST_SYNC_BIT;
5935 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
5936
5937 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
5938 if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
5939 pc.StallAtPixelScoreboard = true;
5940 pc.CommandStreamerStallEnable = true;
5941 }
5942
5943 pc.DestinationAddressType = DAT_PPGTT,
5944 pc.PostSyncOperation = WriteImmediateData,
5945 pc.Address = (struct anv_address) {
5946 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5947 event->state.offset
5948 };
5949 pc.ImmediateData = VK_EVENT_SET;
5950 }
5951 }
5952
5953 void genX(CmdResetEvent)(
5954 VkCommandBuffer commandBuffer,
5955 VkEvent _event,
5956 VkPipelineStageFlags stageMask)
5957 {
5958 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5959 ANV_FROM_HANDLE(anv_event, event, _event);
5960
5961 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_POST_SYNC_BIT;
5962 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
5963
5964 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
5965 if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
5966 pc.StallAtPixelScoreboard = true;
5967 pc.CommandStreamerStallEnable = true;
5968 }
5969
5970 pc.DestinationAddressType = DAT_PPGTT;
5971 pc.PostSyncOperation = WriteImmediateData;
5972 pc.Address = (struct anv_address) {
5973 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5974 event->state.offset
5975 };
5976 pc.ImmediateData = VK_EVENT_RESET;
5977 }
5978 }
5979
5980 void genX(CmdWaitEvents)(
5981 VkCommandBuffer commandBuffer,
5982 uint32_t eventCount,
5983 const VkEvent* pEvents,
5984 VkPipelineStageFlags srcStageMask,
5985 VkPipelineStageFlags destStageMask,
5986 uint32_t memoryBarrierCount,
5987 const VkMemoryBarrier* pMemoryBarriers,
5988 uint32_t bufferMemoryBarrierCount,
5989 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
5990 uint32_t imageMemoryBarrierCount,
5991 const VkImageMemoryBarrier* pImageMemoryBarriers)
5992 {
5993 #if GEN_GEN >= 8
5994 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5995
5996 for (uint32_t i = 0; i < eventCount; i++) {
5997 ANV_FROM_HANDLE(anv_event, event, pEvents[i]);
5998
5999 anv_batch_emit(&cmd_buffer->batch, GENX(MI_SEMAPHORE_WAIT), sem) {
6000 sem.WaitMode = PollingMode,
6001 sem.CompareOperation = COMPARE_SAD_EQUAL_SDD,
6002 sem.SemaphoreDataDword = VK_EVENT_SET,
6003 sem.SemaphoreAddress = (struct anv_address) {
6004 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
6005 event->state.offset
6006 };
6007 }
6008 }
6009 #else
6010 anv_finishme("Implement events on gen7");
6011 #endif
6012
6013 genX(CmdPipelineBarrier)(commandBuffer, srcStageMask, destStageMask,
6014 false, /* byRegion */
6015 memoryBarrierCount, pMemoryBarriers,
6016 bufferMemoryBarrierCount, pBufferMemoryBarriers,
6017 imageMemoryBarrierCount, pImageMemoryBarriers);
6018 }
6019
6020 VkResult genX(CmdSetPerformanceOverrideINTEL)(
6021 VkCommandBuffer commandBuffer,
6022 const VkPerformanceOverrideInfoINTEL* pOverrideInfo)
6023 {
6024 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
6025
6026 switch (pOverrideInfo->type) {
6027 case VK_PERFORMANCE_OVERRIDE_TYPE_NULL_HARDWARE_INTEL: {
6028 uint32_t dw;
6029
6030 #if GEN_GEN >= 9
6031 anv_pack_struct(&dw, GENX(CS_DEBUG_MODE2),
6032 ._3DRenderingInstructionDisable = pOverrideInfo->enable,
6033 .MediaInstructionDisable = pOverrideInfo->enable,
6034 ._3DRenderingInstructionDisableMask = true,
6035 .MediaInstructionDisableMask = true);
6036 emit_lri(&cmd_buffer->batch, GENX(CS_DEBUG_MODE2_num), dw);
6037 #else
6038 anv_pack_struct(&dw, GENX(INSTPM),
6039 ._3DRenderingInstructionDisable = pOverrideInfo->enable,
6040 .MediaInstructionDisable = pOverrideInfo->enable,
6041 ._3DRenderingInstructionDisableMask = true,
6042 .MediaInstructionDisableMask = true);
6043 emit_lri(&cmd_buffer->batch, GENX(INSTPM_num), dw);
6044 #endif
6045 break;
6046 }
6047
6048 case VK_PERFORMANCE_OVERRIDE_TYPE_FLUSH_GPU_CACHES_INTEL:
6049 if (pOverrideInfo->enable) {
6050 /* FLUSH ALL THE THINGS! As requested by the MDAPI team. */
6051 cmd_buffer->state.pending_pipe_bits |=
6052 ANV_PIPE_FLUSH_BITS |
6053 ANV_PIPE_INVALIDATE_BITS;
6054 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
6055 }
6056 break;
6057
6058 default:
6059 unreachable("Invalid override");
6060 }
6061
6062 return VK_SUCCESS;
6063 }
6064
6065 VkResult genX(CmdSetPerformanceStreamMarkerINTEL)(
6066 VkCommandBuffer commandBuffer,
6067 const VkPerformanceStreamMarkerInfoINTEL* pMarkerInfo)
6068 {
6069 /* TODO: Waiting on the register to write, might depend on generation. */
6070
6071 return VK_SUCCESS;
6072 }