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