anv: fix alignments for uniform buffers
[mesa.git] / src / intel / vulkan / genX_cmd_buffer.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26
27 #include "anv_private.h"
28 #include "vk_format_info.h"
29 #include "vk_util.h"
30 #include "util/fast_idiv_by_const.h"
31
32 #include "common/gen_aux_map.h"
33 #include "common/gen_l3_config.h"
34 #include "genxml/gen_macros.h"
35 #include "genxml/genX_pack.h"
36
37 /* We reserve GPR 14 and 15 for conditional rendering */
38 #define GEN_MI_BUILDER_NUM_ALLOC_GPRS 14
39 #define __gen_get_batch_dwords anv_batch_emit_dwords
40 #define __gen_address_offset anv_address_add
41 #include "common/gen_mi_builder.h"
42
43 static void genX(flush_pipeline_select)(struct anv_cmd_buffer *cmd_buffer,
44 uint32_t pipeline);
45
46 static void
47 emit_lri(struct anv_batch *batch, uint32_t reg, uint32_t imm)
48 {
49 anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
50 lri.RegisterOffset = reg;
51 lri.DataDWord = imm;
52 }
53 }
54
55 void
56 genX(cmd_buffer_emit_state_base_address)(struct anv_cmd_buffer *cmd_buffer)
57 {
58 struct anv_device *device = cmd_buffer->device;
59 UNUSED const struct gen_device_info *devinfo = &device->info;
60 uint32_t mocs = device->isl_dev.mocs.internal;
61
62 /* If we are emitting a new state base address we probably need to re-emit
63 * binding tables.
64 */
65 cmd_buffer->state.descriptors_dirty |= ~0;
66
67 /* Emit a render target cache flush.
68 *
69 * This isn't documented anywhere in the PRM. However, it seems to be
70 * necessary prior to changing the surface state base adress. Without
71 * this, we get GPU hangs when using multi-level command buffers which
72 * clear depth, reset state base address, and then go render stuff.
73 */
74 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
75 pc.DCFlushEnable = true;
76 pc.RenderTargetCacheFlushEnable = true;
77 pc.CommandStreamerStallEnable = true;
78 #if GEN_GEN >= 12
79 pc.TileCacheFlushEnable = true;
80 #endif
81 #if GEN_GEN == 12
82 /* GEN:BUG:1606662791:
83 *
84 * Software must program PIPE_CONTROL command with "HDC Pipeline
85 * Flush" prior to programming of the below two non-pipeline state :
86 * * STATE_BASE_ADDRESS
87 * * 3DSTATE_BINDING_TABLE_POOL_ALLOC
88 */
89 if (devinfo->revision == 0 /* A0 */)
90 pc.HDCPipelineFlushEnable = true;
91 #endif
92 }
93
94 #if GEN_GEN == 12
95 /* GEN:BUG:1607854226:
96 *
97 * Workaround the non pipelined state not applying in MEDIA/GPGPU pipeline
98 * mode by putting the pipeline temporarily in 3D mode.
99 */
100 uint32_t gen12_wa_pipeline = cmd_buffer->state.current_pipeline;
101 genX(flush_pipeline_select_3d)(cmd_buffer);
102 #endif
103
104 anv_batch_emit(&cmd_buffer->batch, GENX(STATE_BASE_ADDRESS), sba) {
105 sba.GeneralStateBaseAddress = (struct anv_address) { NULL, 0 };
106 sba.GeneralStateMOCS = mocs;
107 sba.GeneralStateBaseAddressModifyEnable = true;
108
109 sba.StatelessDataPortAccessMOCS = mocs;
110
111 sba.SurfaceStateBaseAddress =
112 anv_cmd_buffer_surface_base_address(cmd_buffer);
113 sba.SurfaceStateMOCS = mocs;
114 sba.SurfaceStateBaseAddressModifyEnable = true;
115
116 sba.DynamicStateBaseAddress =
117 (struct anv_address) { device->dynamic_state_pool.block_pool.bo, 0 };
118 sba.DynamicStateMOCS = mocs;
119 sba.DynamicStateBaseAddressModifyEnable = true;
120
121 sba.IndirectObjectBaseAddress = (struct anv_address) { NULL, 0 };
122 sba.IndirectObjectMOCS = mocs;
123 sba.IndirectObjectBaseAddressModifyEnable = true;
124
125 sba.InstructionBaseAddress =
126 (struct anv_address) { device->instruction_state_pool.block_pool.bo, 0 };
127 sba.InstructionMOCS = mocs;
128 sba.InstructionBaseAddressModifyEnable = true;
129
130 # if (GEN_GEN >= 8)
131 /* Broadwell requires that we specify a buffer size for a bunch of
132 * these fields. However, since we will be growing the BO's live, we
133 * just set them all to the maximum.
134 */
135 sba.GeneralStateBufferSize = 0xfffff;
136 sba.IndirectObjectBufferSize = 0xfffff;
137 if (device->physical->use_softpin) {
138 /* With softpin, we use fixed addresses so we actually know how big
139 * our base addresses are.
140 */
141 sba.DynamicStateBufferSize = DYNAMIC_STATE_POOL_SIZE / 4096;
142 sba.InstructionBufferSize = INSTRUCTION_STATE_POOL_SIZE / 4096;
143 } else {
144 sba.DynamicStateBufferSize = 0xfffff;
145 sba.InstructionBufferSize = 0xfffff;
146 }
147 sba.GeneralStateBufferSizeModifyEnable = true;
148 sba.IndirectObjectBufferSizeModifyEnable = true;
149 sba.DynamicStateBufferSizeModifyEnable = true;
150 sba.InstructionBuffersizeModifyEnable = true;
151 # else
152 /* On gen7, we have upper bounds instead. According to the docs,
153 * setting an upper bound of zero means that no bounds checking is
154 * performed so, in theory, we should be able to leave them zero.
155 * However, border color is broken and the GPU bounds-checks anyway.
156 * To avoid this and other potential problems, we may as well set it
157 * for everything.
158 */
159 sba.GeneralStateAccessUpperBound =
160 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
161 sba.GeneralStateAccessUpperBoundModifyEnable = true;
162 sba.DynamicStateAccessUpperBound =
163 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
164 sba.DynamicStateAccessUpperBoundModifyEnable = true;
165 sba.InstructionAccessUpperBound =
166 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
167 sba.InstructionAccessUpperBoundModifyEnable = true;
168 # endif
169 # if (GEN_GEN >= 9)
170 if (cmd_buffer->device->physical->use_softpin) {
171 sba.BindlessSurfaceStateBaseAddress = (struct anv_address) {
172 .bo = device->surface_state_pool.block_pool.bo,
173 .offset = 0,
174 };
175 sba.BindlessSurfaceStateSize = (1 << 20) - 1;
176 } else {
177 sba.BindlessSurfaceStateBaseAddress = ANV_NULL_ADDRESS;
178 sba.BindlessSurfaceStateSize = 0;
179 }
180 sba.BindlessSurfaceStateMOCS = mocs;
181 sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
182 # endif
183 # if (GEN_GEN >= 10)
184 sba.BindlessSamplerStateBaseAddress = (struct anv_address) { NULL, 0 };
185 sba.BindlessSamplerStateMOCS = mocs;
186 sba.BindlessSamplerStateBaseAddressModifyEnable = true;
187 sba.BindlessSamplerStateBufferSize = 0;
188 # endif
189 }
190
191 #if GEN_GEN == 12
192 /* GEN:BUG:1607854226:
193 *
194 * Put the pipeline back into its current mode.
195 */
196 if (gen12_wa_pipeline != UINT32_MAX)
197 genX(flush_pipeline_select)(cmd_buffer, gen12_wa_pipeline);
198 #endif
199
200 /* After re-setting the surface state base address, we have to do some
201 * cache flusing so that the sampler engine will pick up the new
202 * SURFACE_STATE objects and binding tables. From the Broadwell PRM,
203 * Shared Function > 3D Sampler > State > State Caching (page 96):
204 *
205 * Coherency with system memory in the state cache, like the texture
206 * cache is handled partially by software. It is expected that the
207 * command stream or shader will issue Cache Flush operation or
208 * Cache_Flush sampler message to ensure that the L1 cache remains
209 * coherent with system memory.
210 *
211 * [...]
212 *
213 * Whenever the value of the Dynamic_State_Base_Addr,
214 * Surface_State_Base_Addr are altered, the L1 state cache must be
215 * invalidated to ensure the new surface or sampler state is fetched
216 * from system memory.
217 *
218 * The PIPE_CONTROL command has a "State Cache Invalidation Enable" bit
219 * which, according the PIPE_CONTROL instruction documentation in the
220 * Broadwell PRM:
221 *
222 * Setting this bit is independent of any other bit in this packet.
223 * This bit controls the invalidation of the L1 and L2 state caches
224 * at the top of the pipe i.e. at the parsing time.
225 *
226 * Unfortunately, experimentation seems to indicate that state cache
227 * invalidation through a PIPE_CONTROL does nothing whatsoever in
228 * regards to surface state and binding tables. In stead, it seems that
229 * invalidating the texture cache is what is actually needed.
230 *
231 * XXX: As far as we have been able to determine through
232 * experimentation, shows that flush the texture cache appears to be
233 * sufficient. The theory here is that all of the sampling/rendering
234 * units cache the binding table in the texture cache. However, we have
235 * yet to be able to actually confirm this.
236 */
237 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
238 pc.TextureCacheInvalidationEnable = true;
239 pc.ConstantCacheInvalidationEnable = true;
240 pc.StateCacheInvalidationEnable = true;
241 }
242 }
243
244 static void
245 add_surface_reloc(struct anv_cmd_buffer *cmd_buffer,
246 struct anv_state state, struct anv_address addr)
247 {
248 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
249
250 VkResult result =
251 anv_reloc_list_add(&cmd_buffer->surface_relocs, &cmd_buffer->pool->alloc,
252 state.offset + isl_dev->ss.addr_offset,
253 addr.bo, addr.offset, NULL);
254 if (result != VK_SUCCESS)
255 anv_batch_set_error(&cmd_buffer->batch, result);
256 }
257
258 static void
259 add_surface_state_relocs(struct anv_cmd_buffer *cmd_buffer,
260 struct anv_surface_state state)
261 {
262 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
263
264 assert(!anv_address_is_null(state.address));
265 add_surface_reloc(cmd_buffer, state.state, state.address);
266
267 if (!anv_address_is_null(state.aux_address)) {
268 VkResult result =
269 anv_reloc_list_add(&cmd_buffer->surface_relocs,
270 &cmd_buffer->pool->alloc,
271 state.state.offset + isl_dev->ss.aux_addr_offset,
272 state.aux_address.bo,
273 state.aux_address.offset,
274 NULL);
275 if (result != VK_SUCCESS)
276 anv_batch_set_error(&cmd_buffer->batch, result);
277 }
278
279 if (!anv_address_is_null(state.clear_address)) {
280 VkResult result =
281 anv_reloc_list_add(&cmd_buffer->surface_relocs,
282 &cmd_buffer->pool->alloc,
283 state.state.offset +
284 isl_dev->ss.clear_color_state_offset,
285 state.clear_address.bo,
286 state.clear_address.offset,
287 NULL);
288 if (result != VK_SUCCESS)
289 anv_batch_set_error(&cmd_buffer->batch, result);
290 }
291 }
292
293 static bool
294 isl_color_value_requires_conversion(union isl_color_value color,
295 const struct isl_surf *surf,
296 const struct isl_view *view)
297 {
298 if (surf->format == view->format && isl_swizzle_is_identity(view->swizzle))
299 return false;
300
301 uint32_t surf_pack[4] = { 0, 0, 0, 0 };
302 isl_color_value_pack(&color, surf->format, surf_pack);
303
304 uint32_t view_pack[4] = { 0, 0, 0, 0 };
305 union isl_color_value swiz_color =
306 isl_color_value_swizzle_inv(color, view->swizzle);
307 isl_color_value_pack(&swiz_color, view->format, view_pack);
308
309 return memcmp(surf_pack, view_pack, sizeof(surf_pack)) != 0;
310 }
311
312 static bool
313 anv_can_fast_clear_color_view(struct anv_device * device,
314 struct anv_image_view *iview,
315 VkImageLayout layout,
316 union isl_color_value clear_color,
317 uint32_t num_layers,
318 VkRect2D render_area)
319 {
320 if (iview->planes[0].isl.base_array_layer >=
321 anv_image_aux_layers(iview->image, VK_IMAGE_ASPECT_COLOR_BIT,
322 iview->planes[0].isl.base_level))
323 return false;
324
325 /* Start by getting the fast clear type. We use the first subpass
326 * layout here because we don't want to fast-clear if the first subpass
327 * to use the attachment can't handle fast-clears.
328 */
329 enum anv_fast_clear_type fast_clear_type =
330 anv_layout_to_fast_clear_type(&device->info, iview->image,
331 VK_IMAGE_ASPECT_COLOR_BIT,
332 layout);
333 switch (fast_clear_type) {
334 case ANV_FAST_CLEAR_NONE:
335 return false;
336 case ANV_FAST_CLEAR_DEFAULT_VALUE:
337 if (!isl_color_value_is_zero(clear_color, iview->planes[0].isl.format))
338 return false;
339 break;
340 case ANV_FAST_CLEAR_ANY:
341 break;
342 }
343
344 /* Potentially, we could do partial fast-clears but doing so has crazy
345 * alignment restrictions. It's easier to just restrict to full size
346 * fast clears for now.
347 */
348 if (render_area.offset.x != 0 ||
349 render_area.offset.y != 0 ||
350 render_area.extent.width != iview->extent.width ||
351 render_area.extent.height != iview->extent.height)
352 return false;
353
354 /* On Broadwell and earlier, we can only handle 0/1 clear colors */
355 if (GEN_GEN <= 8 &&
356 !isl_color_value_is_zero_one(clear_color, iview->planes[0].isl.format))
357 return false;
358
359 /* If the clear color is one that would require non-trivial format
360 * conversion on resolve, we don't bother with the fast clear. This
361 * shouldn't be common as most clear colors are 0/1 and the most common
362 * format re-interpretation is for sRGB.
363 */
364 if (isl_color_value_requires_conversion(clear_color,
365 &iview->image->planes[0].surface.isl,
366 &iview->planes[0].isl)) {
367 anv_perf_warn(device, iview,
368 "Cannot fast-clear to colors which would require "
369 "format conversion on resolve");
370 return false;
371 }
372
373 /* We only allow fast clears to the first slice of an image (level 0,
374 * layer 0) and only for the entire slice. This guarantees us that, at
375 * any given time, there is only one clear color on any given image at
376 * any given time. At the time of our testing (Jan 17, 2018), there
377 * were no known applications which would benefit from fast-clearing
378 * more than just the first slice.
379 */
380 if (iview->planes[0].isl.base_level > 0 ||
381 iview->planes[0].isl.base_array_layer > 0) {
382 anv_perf_warn(device, iview->image,
383 "Rendering with multi-lod or multi-layer framebuffer "
384 "with LOAD_OP_LOAD and baseMipLevel > 0 or "
385 "baseArrayLayer > 0. Not fast clearing.");
386 return false;
387 }
388
389 if (num_layers > 1) {
390 anv_perf_warn(device, iview->image,
391 "Rendering to a multi-layer framebuffer with "
392 "LOAD_OP_CLEAR. Only fast-clearing the first slice");
393 }
394
395 return true;
396 }
397
398 static bool
399 anv_can_hiz_clear_ds_view(struct anv_device *device,
400 struct anv_image_view *iview,
401 VkImageLayout layout,
402 VkImageAspectFlags clear_aspects,
403 float depth_clear_value,
404 VkRect2D render_area)
405 {
406 /* We don't do any HiZ or depth fast-clears on gen7 yet */
407 if (GEN_GEN == 7)
408 return false;
409
410 /* If we're just clearing stencil, we can always HiZ clear */
411 if (!(clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
412 return true;
413
414 /* We must have depth in order to have HiZ */
415 if (!(iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
416 return false;
417
418 const enum isl_aux_usage clear_aux_usage =
419 anv_layout_to_aux_usage(&device->info, iview->image,
420 VK_IMAGE_ASPECT_DEPTH_BIT,
421 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
422 layout);
423 if (!blorp_can_hiz_clear_depth(&device->info,
424 &iview->image->planes[0].surface.isl,
425 clear_aux_usage,
426 iview->planes[0].isl.base_level,
427 iview->planes[0].isl.base_array_layer,
428 render_area.offset.x,
429 render_area.offset.y,
430 render_area.offset.x +
431 render_area.extent.width,
432 render_area.offset.y +
433 render_area.extent.height))
434 return false;
435
436 if (depth_clear_value != ANV_HZ_FC_VAL)
437 return false;
438
439 /* Only gen9+ supports returning ANV_HZ_FC_VAL when sampling a fast-cleared
440 * portion of a HiZ buffer. Testing has revealed that Gen8 only supports
441 * returning 0.0f. Gens prior to gen8 do not support this feature at all.
442 */
443 if (GEN_GEN == 8 && anv_can_sample_with_hiz(&device->info, iview->image))
444 return false;
445
446 /* If we got here, then we can fast clear */
447 return true;
448 }
449
450 #define READ_ONCE(x) (*(volatile __typeof__(x) *)&(x))
451
452 #if GEN_GEN == 12
453 static void
454 anv_image_init_aux_tt(struct anv_cmd_buffer *cmd_buffer,
455 const struct anv_image *image,
456 VkImageAspectFlagBits aspect,
457 uint32_t base_level, uint32_t level_count,
458 uint32_t base_layer, uint32_t layer_count)
459 {
460 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
461
462 uint64_t base_address =
463 anv_address_physical(image->planes[plane].address);
464
465 const struct isl_surf *isl_surf = &image->planes[plane].surface.isl;
466 uint64_t format_bits = gen_aux_map_format_bits_for_isl_surf(isl_surf);
467
468 /* We're about to live-update the AUX-TT. We really don't want anyone else
469 * trying to read it while we're doing this. We could probably get away
470 * with not having this stall in some cases if we were really careful but
471 * it's better to play it safe. Full stall the GPU.
472 */
473 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_END_OF_PIPE_SYNC_BIT;
474 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
475
476 struct gen_mi_builder b;
477 gen_mi_builder_init(&b, &cmd_buffer->batch);
478
479 for (uint32_t a = 0; a < layer_count; a++) {
480 const uint32_t layer = base_layer + a;
481
482 uint64_t start_offset_B = UINT64_MAX, end_offset_B = 0;
483 for (uint32_t l = 0; l < level_count; l++) {
484 const uint32_t level = base_level + l;
485
486 uint32_t logical_array_layer, logical_z_offset_px;
487 if (image->type == VK_IMAGE_TYPE_3D) {
488 logical_array_layer = 0;
489
490 /* If the given miplevel does not have this layer, then any higher
491 * miplevels won't either because miplevels only get smaller the
492 * higher the LOD.
493 */
494 assert(layer < image->extent.depth);
495 if (layer >= anv_minify(image->extent.depth, level))
496 break;
497 logical_z_offset_px = layer;
498 } else {
499 assert(layer < image->array_size);
500 logical_array_layer = layer;
501 logical_z_offset_px = 0;
502 }
503
504 uint32_t slice_start_offset_B, slice_end_offset_B;
505 isl_surf_get_image_range_B_tile(isl_surf, level,
506 logical_array_layer,
507 logical_z_offset_px,
508 &slice_start_offset_B,
509 &slice_end_offset_B);
510
511 start_offset_B = MIN2(start_offset_B, slice_start_offset_B);
512 end_offset_B = MAX2(end_offset_B, slice_end_offset_B);
513 }
514
515 /* Aux operates 64K at a time */
516 start_offset_B = align_down_u64(start_offset_B, 64 * 1024);
517 end_offset_B = align_u64(end_offset_B, 64 * 1024);
518
519 for (uint64_t offset = start_offset_B;
520 offset < end_offset_B; offset += 64 * 1024) {
521 uint64_t address = base_address + offset;
522
523 uint64_t aux_entry_addr64, *aux_entry_map;
524 aux_entry_map = gen_aux_map_get_entry(cmd_buffer->device->aux_map_ctx,
525 address, &aux_entry_addr64);
526
527 assert(cmd_buffer->device->physical->use_softpin);
528 struct anv_address aux_entry_address = {
529 .bo = NULL,
530 .offset = aux_entry_addr64,
531 };
532
533 const uint64_t old_aux_entry = READ_ONCE(*aux_entry_map);
534 uint64_t new_aux_entry =
535 (old_aux_entry & GEN_AUX_MAP_ADDRESS_MASK) | format_bits;
536
537 if (isl_aux_usage_has_ccs(image->planes[plane].aux_usage))
538 new_aux_entry |= GEN_AUX_MAP_ENTRY_VALID_BIT;
539
540 gen_mi_store(&b, gen_mi_mem64(aux_entry_address),
541 gen_mi_imm(new_aux_entry));
542 }
543 }
544
545 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_AUX_TABLE_INVALIDATE_BIT;
546 }
547 #endif /* GEN_GEN == 12 */
548
549 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
550 * the initial layout is undefined, the HiZ buffer and depth buffer will
551 * represent the same data at the end of this operation.
552 */
553 static void
554 transition_depth_buffer(struct anv_cmd_buffer *cmd_buffer,
555 const struct anv_image *image,
556 uint32_t base_layer, uint32_t layer_count,
557 VkImageLayout initial_layout,
558 VkImageLayout final_layout)
559 {
560 uint32_t depth_plane =
561 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_DEPTH_BIT);
562 if (image->planes[depth_plane].aux_usage == ISL_AUX_USAGE_NONE)
563 return;
564
565 #if GEN_GEN == 12
566 if ((initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ||
567 initial_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) &&
568 cmd_buffer->device->physical->has_implicit_ccs &&
569 cmd_buffer->device->info.has_aux_map) {
570 anv_image_init_aux_tt(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
571 0, 1, 0, 1);
572 }
573 #endif
574
575 const enum isl_aux_state initial_state =
576 anv_layout_to_aux_state(&cmd_buffer->device->info, image,
577 VK_IMAGE_ASPECT_DEPTH_BIT,
578 initial_layout);
579 const enum isl_aux_state final_state =
580 anv_layout_to_aux_state(&cmd_buffer->device->info, image,
581 VK_IMAGE_ASPECT_DEPTH_BIT,
582 final_layout);
583
584 const bool initial_depth_valid =
585 isl_aux_state_has_valid_primary(initial_state);
586 const bool initial_hiz_valid =
587 isl_aux_state_has_valid_aux(initial_state);
588 const bool final_needs_depth =
589 isl_aux_state_has_valid_primary(final_state);
590 const bool final_needs_hiz =
591 isl_aux_state_has_valid_aux(final_state);
592
593 /* Getting into the pass-through state for Depth is tricky and involves
594 * both a resolve and an ambiguate. We don't handle that state right now
595 * as anv_layout_to_aux_state never returns it.
596 */
597 assert(final_state != ISL_AUX_STATE_PASS_THROUGH);
598
599 if (final_needs_depth && !initial_depth_valid) {
600 assert(initial_hiz_valid);
601 anv_image_hiz_op(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
602 0, base_layer, layer_count, ISL_AUX_OP_FULL_RESOLVE);
603 } else if (final_needs_hiz && !initial_hiz_valid) {
604 assert(initial_depth_valid);
605 anv_image_hiz_op(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
606 0, base_layer, layer_count, ISL_AUX_OP_AMBIGUATE);
607 }
608 }
609
610 static inline bool
611 vk_image_layout_stencil_write_optimal(VkImageLayout layout)
612 {
613 return layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
614 layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
615 layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR;
616 }
617
618 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
619 * the initial layout is undefined, the HiZ buffer and depth buffer will
620 * represent the same data at the end of this operation.
621 */
622 static void
623 transition_stencil_buffer(struct anv_cmd_buffer *cmd_buffer,
624 const struct anv_image *image,
625 uint32_t base_level, uint32_t level_count,
626 uint32_t base_layer, uint32_t layer_count,
627 VkImageLayout initial_layout,
628 VkImageLayout final_layout)
629 {
630 #if GEN_GEN == 7
631 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
632 VK_IMAGE_ASPECT_STENCIL_BIT);
633
634 /* On gen7, we have to store a texturable version of the stencil buffer in
635 * a shadow whenever VK_IMAGE_USAGE_SAMPLED_BIT is set and copy back and
636 * forth at strategic points. Stencil writes are only allowed in following
637 * layouts:
638 *
639 * - VK_IMAGE_LAYOUT_GENERAL
640 * - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
641 * - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
642 * - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL
643 * - VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL_KHR
644 *
645 * For general, we have no nice opportunity to transition so we do the copy
646 * to the shadow unconditionally at the end of the subpass. For transfer
647 * destinations, we can update it as part of the transfer op. For the other
648 * layouts, we delay the copy until a transition into some other layout.
649 */
650 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
651 vk_image_layout_stencil_write_optimal(initial_layout) &&
652 !vk_image_layout_stencil_write_optimal(final_layout)) {
653 anv_image_copy_to_shadow(cmd_buffer, image,
654 VK_IMAGE_ASPECT_STENCIL_BIT,
655 base_level, level_count,
656 base_layer, layer_count);
657 }
658 #endif /* GEN_GEN == 7 */
659 }
660
661 #define MI_PREDICATE_SRC0 0x2400
662 #define MI_PREDICATE_SRC1 0x2408
663 #define MI_PREDICATE_RESULT 0x2418
664
665 static void
666 set_image_compressed_bit(struct anv_cmd_buffer *cmd_buffer,
667 const struct anv_image *image,
668 VkImageAspectFlagBits aspect,
669 uint32_t level,
670 uint32_t base_layer, uint32_t layer_count,
671 bool compressed)
672 {
673 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
674
675 /* We only have compression tracking for CCS_E */
676 if (image->planes[plane].aux_usage != ISL_AUX_USAGE_CCS_E)
677 return;
678
679 for (uint32_t a = 0; a < layer_count; a++) {
680 uint32_t layer = base_layer + a;
681 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
682 sdi.Address = anv_image_get_compression_state_addr(cmd_buffer->device,
683 image, aspect,
684 level, layer);
685 sdi.ImmediateData = compressed ? UINT32_MAX : 0;
686 }
687 }
688 }
689
690 static void
691 set_image_fast_clear_state(struct anv_cmd_buffer *cmd_buffer,
692 const struct anv_image *image,
693 VkImageAspectFlagBits aspect,
694 enum anv_fast_clear_type fast_clear)
695 {
696 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
697 sdi.Address = anv_image_get_fast_clear_type_addr(cmd_buffer->device,
698 image, aspect);
699 sdi.ImmediateData = fast_clear;
700 }
701
702 /* Whenever we have fast-clear, we consider that slice to be compressed.
703 * This makes building predicates much easier.
704 */
705 if (fast_clear != ANV_FAST_CLEAR_NONE)
706 set_image_compressed_bit(cmd_buffer, image, aspect, 0, 0, 1, true);
707 }
708
709 /* This is only really practical on haswell and above because it requires
710 * MI math in order to get it correct.
711 */
712 #if GEN_GEN >= 8 || GEN_IS_HASWELL
713 static void
714 anv_cmd_compute_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
715 const struct anv_image *image,
716 VkImageAspectFlagBits aspect,
717 uint32_t level, uint32_t array_layer,
718 enum isl_aux_op resolve_op,
719 enum anv_fast_clear_type fast_clear_supported)
720 {
721 struct gen_mi_builder b;
722 gen_mi_builder_init(&b, &cmd_buffer->batch);
723
724 const struct gen_mi_value fast_clear_type =
725 gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
726 image, aspect));
727
728 if (resolve_op == ISL_AUX_OP_FULL_RESOLVE) {
729 /* In this case, we're doing a full resolve which means we want the
730 * resolve to happen if any compression (including fast-clears) is
731 * present.
732 *
733 * In order to simplify the logic a bit, we make the assumption that,
734 * if the first slice has been fast-cleared, it is also marked as
735 * compressed. See also set_image_fast_clear_state.
736 */
737 const struct gen_mi_value compression_state =
738 gen_mi_mem32(anv_image_get_compression_state_addr(cmd_buffer->device,
739 image, aspect,
740 level, array_layer));
741 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
742 compression_state);
743 gen_mi_store(&b, compression_state, gen_mi_imm(0));
744
745 if (level == 0 && array_layer == 0) {
746 /* If the predicate is true, we want to write 0 to the fast clear type
747 * and, if it's false, leave it alone. We can do this by writing
748 *
749 * clear_type = clear_type & ~predicate;
750 */
751 struct gen_mi_value new_fast_clear_type =
752 gen_mi_iand(&b, fast_clear_type,
753 gen_mi_inot(&b, gen_mi_reg64(MI_PREDICATE_SRC0)));
754 gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
755 }
756 } else if (level == 0 && array_layer == 0) {
757 /* In this case, we are doing a partial resolve to get rid of fast-clear
758 * colors. We don't care about the compression state but we do care
759 * about how much fast clear is allowed by the final layout.
760 */
761 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
762 assert(fast_clear_supported < ANV_FAST_CLEAR_ANY);
763
764 /* We need to compute (fast_clear_supported < image->fast_clear) */
765 struct gen_mi_value pred =
766 gen_mi_ult(&b, gen_mi_imm(fast_clear_supported), fast_clear_type);
767 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
768 gen_mi_value_ref(&b, pred));
769
770 /* If the predicate is true, we want to write 0 to the fast clear type
771 * and, if it's false, leave it alone. We can do this by writing
772 *
773 * clear_type = clear_type & ~predicate;
774 */
775 struct gen_mi_value new_fast_clear_type =
776 gen_mi_iand(&b, fast_clear_type, gen_mi_inot(&b, pred));
777 gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
778 } else {
779 /* In this case, we're trying to do a partial resolve on a slice that
780 * doesn't have clear color. There's nothing to do.
781 */
782 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
783 return;
784 }
785
786 /* Set src1 to 0 and use a != condition */
787 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
788
789 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
790 mip.LoadOperation = LOAD_LOADINV;
791 mip.CombineOperation = COMBINE_SET;
792 mip.CompareOperation = COMPARE_SRCS_EQUAL;
793 }
794 }
795 #endif /* GEN_GEN >= 8 || GEN_IS_HASWELL */
796
797 #if GEN_GEN <= 8
798 static void
799 anv_cmd_simple_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
800 const struct anv_image *image,
801 VkImageAspectFlagBits aspect,
802 uint32_t level, uint32_t array_layer,
803 enum isl_aux_op resolve_op,
804 enum anv_fast_clear_type fast_clear_supported)
805 {
806 struct gen_mi_builder b;
807 gen_mi_builder_init(&b, &cmd_buffer->batch);
808
809 struct gen_mi_value fast_clear_type_mem =
810 gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
811 image, aspect));
812
813 /* This only works for partial resolves and only when the clear color is
814 * all or nothing. On the upside, this emits less command streamer code
815 * and works on Ivybridge and Bay Trail.
816 */
817 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
818 assert(fast_clear_supported != ANV_FAST_CLEAR_ANY);
819
820 /* We don't support fast clears on anything other than the first slice. */
821 if (level > 0 || array_layer > 0)
822 return;
823
824 /* On gen8, we don't have a concept of default clear colors because we
825 * can't sample from CCS surfaces. It's enough to just load the fast clear
826 * state into the predicate register.
827 */
828 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), fast_clear_type_mem);
829 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
830 gen_mi_store(&b, fast_clear_type_mem, gen_mi_imm(0));
831
832 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
833 mip.LoadOperation = LOAD_LOADINV;
834 mip.CombineOperation = COMBINE_SET;
835 mip.CompareOperation = COMPARE_SRCS_EQUAL;
836 }
837 }
838 #endif /* GEN_GEN <= 8 */
839
840 static void
841 anv_cmd_predicated_ccs_resolve(struct anv_cmd_buffer *cmd_buffer,
842 const struct anv_image *image,
843 enum isl_format format,
844 struct isl_swizzle swizzle,
845 VkImageAspectFlagBits aspect,
846 uint32_t level, uint32_t array_layer,
847 enum isl_aux_op resolve_op,
848 enum anv_fast_clear_type fast_clear_supported)
849 {
850 const uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
851
852 #if GEN_GEN >= 9
853 anv_cmd_compute_resolve_predicate(cmd_buffer, image,
854 aspect, level, array_layer,
855 resolve_op, fast_clear_supported);
856 #else /* GEN_GEN <= 8 */
857 anv_cmd_simple_resolve_predicate(cmd_buffer, image,
858 aspect, level, array_layer,
859 resolve_op, fast_clear_supported);
860 #endif
861
862 /* CCS_D only supports full resolves and BLORP will assert on us if we try
863 * to do a partial resolve on a CCS_D surface.
864 */
865 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
866 image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_D)
867 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
868
869 anv_image_ccs_op(cmd_buffer, image, format, swizzle, aspect,
870 level, array_layer, 1, resolve_op, NULL, true);
871 }
872
873 static void
874 anv_cmd_predicated_mcs_resolve(struct anv_cmd_buffer *cmd_buffer,
875 const struct anv_image *image,
876 enum isl_format format,
877 struct isl_swizzle swizzle,
878 VkImageAspectFlagBits aspect,
879 uint32_t array_layer,
880 enum isl_aux_op resolve_op,
881 enum anv_fast_clear_type fast_clear_supported)
882 {
883 assert(aspect == VK_IMAGE_ASPECT_COLOR_BIT);
884 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
885
886 #if GEN_GEN >= 8 || GEN_IS_HASWELL
887 anv_cmd_compute_resolve_predicate(cmd_buffer, image,
888 aspect, 0, array_layer,
889 resolve_op, fast_clear_supported);
890
891 anv_image_mcs_op(cmd_buffer, image, format, swizzle, aspect,
892 array_layer, 1, resolve_op, NULL, true);
893 #else
894 unreachable("MCS resolves are unsupported on Ivybridge and Bay Trail");
895 #endif
896 }
897
898 void
899 genX(cmd_buffer_mark_image_written)(struct anv_cmd_buffer *cmd_buffer,
900 const struct anv_image *image,
901 VkImageAspectFlagBits aspect,
902 enum isl_aux_usage aux_usage,
903 uint32_t level,
904 uint32_t base_layer,
905 uint32_t layer_count)
906 {
907 /* The aspect must be exactly one of the image aspects. */
908 assert(util_bitcount(aspect) == 1 && (aspect & image->aspects));
909
910 /* The only compression types with more than just fast-clears are MCS,
911 * CCS_E, and HiZ. With HiZ we just trust the layout and don't actually
912 * track the current fast-clear and compression state. This leaves us
913 * with just MCS and CCS_E.
914 */
915 if (aux_usage != ISL_AUX_USAGE_CCS_E &&
916 aux_usage != ISL_AUX_USAGE_MCS)
917 return;
918
919 set_image_compressed_bit(cmd_buffer, image, aspect,
920 level, base_layer, layer_count, true);
921 }
922
923 static void
924 init_fast_clear_color(struct anv_cmd_buffer *cmd_buffer,
925 const struct anv_image *image,
926 VkImageAspectFlagBits aspect)
927 {
928 assert(cmd_buffer && image);
929 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
930
931 set_image_fast_clear_state(cmd_buffer, image, aspect,
932 ANV_FAST_CLEAR_NONE);
933
934 /* Initialize the struct fields that are accessed for fast-clears so that
935 * the HW restrictions on the field values are satisfied.
936 */
937 struct anv_address addr =
938 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
939
940 if (GEN_GEN >= 9) {
941 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
942 const unsigned num_dwords = GEN_GEN >= 10 ?
943 isl_dev->ss.clear_color_state_size / 4 :
944 isl_dev->ss.clear_value_size / 4;
945 for (unsigned i = 0; i < num_dwords; i++) {
946 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
947 sdi.Address = addr;
948 sdi.Address.offset += i * 4;
949 sdi.ImmediateData = 0;
950 }
951 }
952 } else {
953 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
954 sdi.Address = addr;
955 if (GEN_GEN >= 8 || GEN_IS_HASWELL) {
956 /* Pre-SKL, the dword containing the clear values also contains
957 * other fields, so we need to initialize those fields to match the
958 * values that would be in a color attachment.
959 */
960 sdi.ImmediateData = ISL_CHANNEL_SELECT_RED << 25 |
961 ISL_CHANNEL_SELECT_GREEN << 22 |
962 ISL_CHANNEL_SELECT_BLUE << 19 |
963 ISL_CHANNEL_SELECT_ALPHA << 16;
964 } else if (GEN_GEN == 7) {
965 /* On IVB, the dword containing the clear values also contains
966 * other fields that must be zero or can be zero.
967 */
968 sdi.ImmediateData = 0;
969 }
970 }
971 }
972 }
973
974 /* Copy the fast-clear value dword(s) between a surface state object and an
975 * image's fast clear state buffer.
976 */
977 static void
978 genX(copy_fast_clear_dwords)(struct anv_cmd_buffer *cmd_buffer,
979 struct anv_state surface_state,
980 const struct anv_image *image,
981 VkImageAspectFlagBits aspect,
982 bool copy_from_surface_state)
983 {
984 assert(cmd_buffer && image);
985 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
986
987 struct anv_address ss_clear_addr = {
988 .bo = cmd_buffer->device->surface_state_pool.block_pool.bo,
989 .offset = surface_state.offset +
990 cmd_buffer->device->isl_dev.ss.clear_value_offset,
991 };
992 const struct anv_address entry_addr =
993 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
994 unsigned copy_size = cmd_buffer->device->isl_dev.ss.clear_value_size;
995
996 #if GEN_GEN == 7
997 /* On gen7, the combination of commands used here(MI_LOAD_REGISTER_MEM
998 * and MI_STORE_REGISTER_MEM) can cause GPU hangs if any rendering is
999 * in-flight when they are issued even if the memory touched is not
1000 * currently active for rendering. The weird bit is that it is not the
1001 * MI_LOAD/STORE_REGISTER_MEM commands which hang but rather the in-flight
1002 * rendering hangs such that the next stalling command after the
1003 * MI_LOAD/STORE_REGISTER_MEM commands will catch the hang.
1004 *
1005 * It is unclear exactly why this hang occurs. Both MI commands come with
1006 * warnings about the 3D pipeline but that doesn't seem to fully explain
1007 * it. My (Jason's) best theory is that it has something to do with the
1008 * fact that we're using a GPU state register as our temporary and that
1009 * something with reading/writing it is causing problems.
1010 *
1011 * In order to work around this issue, we emit a PIPE_CONTROL with the
1012 * command streamer stall bit set.
1013 */
1014 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
1015 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
1016 #endif
1017
1018 struct gen_mi_builder b;
1019 gen_mi_builder_init(&b, &cmd_buffer->batch);
1020
1021 if (copy_from_surface_state) {
1022 gen_mi_memcpy(&b, entry_addr, ss_clear_addr, copy_size);
1023 } else {
1024 gen_mi_memcpy(&b, ss_clear_addr, entry_addr, copy_size);
1025
1026 /* Updating a surface state object may require that the state cache be
1027 * invalidated. From the SKL PRM, Shared Functions -> State -> State
1028 * Caching:
1029 *
1030 * Whenever the RENDER_SURFACE_STATE object in memory pointed to by
1031 * the Binding Table Pointer (BTP) and Binding Table Index (BTI) is
1032 * modified [...], the L1 state cache must be invalidated to ensure
1033 * the new surface or sampler state is fetched from system memory.
1034 *
1035 * In testing, SKL doesn't actually seem to need this, but HSW does.
1036 */
1037 cmd_buffer->state.pending_pipe_bits |=
1038 ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
1039 }
1040 }
1041
1042 /**
1043 * @brief Transitions a color buffer from one layout to another.
1044 *
1045 * See section 6.1.1. Image Layout Transitions of the Vulkan 1.0.50 spec for
1046 * more information.
1047 *
1048 * @param level_count VK_REMAINING_MIP_LEVELS isn't supported.
1049 * @param layer_count VK_REMAINING_ARRAY_LAYERS isn't supported. For 3D images,
1050 * this represents the maximum layers to transition at each
1051 * specified miplevel.
1052 */
1053 static void
1054 transition_color_buffer(struct anv_cmd_buffer *cmd_buffer,
1055 const struct anv_image *image,
1056 VkImageAspectFlagBits aspect,
1057 const uint32_t base_level, uint32_t level_count,
1058 uint32_t base_layer, uint32_t layer_count,
1059 VkImageLayout initial_layout,
1060 VkImageLayout final_layout)
1061 {
1062 struct anv_device *device = cmd_buffer->device;
1063 const struct gen_device_info *devinfo = &device->info;
1064 /* Validate the inputs. */
1065 assert(cmd_buffer);
1066 assert(image && image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
1067 /* These values aren't supported for simplicity's sake. */
1068 assert(level_count != VK_REMAINING_MIP_LEVELS &&
1069 layer_count != VK_REMAINING_ARRAY_LAYERS);
1070 /* Ensure the subresource range is valid. */
1071 UNUSED uint64_t last_level_num = base_level + level_count;
1072 const uint32_t max_depth = anv_minify(image->extent.depth, base_level);
1073 UNUSED const uint32_t image_layers = MAX2(image->array_size, max_depth);
1074 assert((uint64_t)base_layer + layer_count <= image_layers);
1075 assert(last_level_num <= image->levels);
1076 /* The spec disallows these final layouts. */
1077 assert(final_layout != VK_IMAGE_LAYOUT_UNDEFINED &&
1078 final_layout != VK_IMAGE_LAYOUT_PREINITIALIZED);
1079
1080 /* No work is necessary if the layout stays the same or if this subresource
1081 * range lacks auxiliary data.
1082 */
1083 if (initial_layout == final_layout)
1084 return;
1085
1086 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
1087
1088 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
1089 final_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
1090 /* This surface is a linear compressed image with a tiled shadow surface
1091 * for texturing. The client is about to use it in READ_ONLY_OPTIMAL so
1092 * we need to ensure the shadow copy is up-to-date.
1093 */
1094 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1095 assert(image->planes[plane].surface.isl.tiling == ISL_TILING_LINEAR);
1096 assert(image->planes[plane].shadow_surface.isl.tiling != ISL_TILING_LINEAR);
1097 assert(isl_format_is_compressed(image->planes[plane].surface.isl.format));
1098 assert(plane == 0);
1099 anv_image_copy_to_shadow(cmd_buffer, image,
1100 VK_IMAGE_ASPECT_COLOR_BIT,
1101 base_level, level_count,
1102 base_layer, layer_count);
1103 }
1104
1105 if (base_layer >= anv_image_aux_layers(image, aspect, base_level))
1106 return;
1107
1108 assert(image->planes[plane].surface.isl.tiling != ISL_TILING_LINEAR);
1109
1110 if (initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ||
1111 initial_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
1112 #if GEN_GEN == 12
1113 if (device->physical->has_implicit_ccs && devinfo->has_aux_map) {
1114 anv_image_init_aux_tt(cmd_buffer, image, aspect,
1115 base_level, level_count,
1116 base_layer, layer_count);
1117 }
1118 #else
1119 assert(!(device->physical->has_implicit_ccs && devinfo->has_aux_map));
1120 #endif
1121
1122 /* A subresource in the undefined layout may have been aliased and
1123 * populated with any arrangement of bits. Therefore, we must initialize
1124 * the related aux buffer and clear buffer entry with desirable values.
1125 * An initial layout of PREINITIALIZED is the same as UNDEFINED for
1126 * images with VK_IMAGE_TILING_OPTIMAL.
1127 *
1128 * Initialize the relevant clear buffer entries.
1129 */
1130 if (base_level == 0 && base_layer == 0)
1131 init_fast_clear_color(cmd_buffer, image, aspect);
1132
1133 /* Initialize the aux buffers to enable correct rendering. In order to
1134 * ensure that things such as storage images work correctly, aux buffers
1135 * need to be initialized to valid data.
1136 *
1137 * Having an aux buffer with invalid data is a problem for two reasons:
1138 *
1139 * 1) Having an invalid value in the buffer can confuse the hardware.
1140 * For instance, with CCS_E on SKL, a two-bit CCS value of 2 is
1141 * invalid and leads to the hardware doing strange things. It
1142 * doesn't hang as far as we can tell but rendering corruption can
1143 * occur.
1144 *
1145 * 2) If this transition is into the GENERAL layout and we then use the
1146 * image as a storage image, then we must have the aux buffer in the
1147 * pass-through state so that, if we then go to texture from the
1148 * image, we get the results of our storage image writes and not the
1149 * fast clear color or other random data.
1150 *
1151 * For CCS both of the problems above are real demonstrable issues. In
1152 * that case, the only thing we can do is to perform an ambiguate to
1153 * transition the aux surface into the pass-through state.
1154 *
1155 * For MCS, (2) is never an issue because we don't support multisampled
1156 * storage images. In theory, issue (1) is a problem with MCS but we've
1157 * never seen it in the wild. For 4x and 16x, all bit patters could, in
1158 * theory, be interpreted as something but we don't know that all bit
1159 * patterns are actually valid. For 2x and 8x, you could easily end up
1160 * with the MCS referring to an invalid plane because not all bits of
1161 * the MCS value are actually used. Even though we've never seen issues
1162 * in the wild, it's best to play it safe and initialize the MCS. We
1163 * can use a fast-clear for MCS because we only ever touch from render
1164 * and texture (no image load store).
1165 */
1166 if (image->samples == 1) {
1167 for (uint32_t l = 0; l < level_count; l++) {
1168 const uint32_t level = base_level + l;
1169
1170 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1171 if (base_layer >= aux_layers)
1172 break; /* We will only get fewer layers as level increases */
1173 uint32_t level_layer_count =
1174 MIN2(layer_count, aux_layers - base_layer);
1175
1176 anv_image_ccs_op(cmd_buffer, image,
1177 image->planes[plane].surface.isl.format,
1178 ISL_SWIZZLE_IDENTITY,
1179 aspect, level, base_layer, level_layer_count,
1180 ISL_AUX_OP_AMBIGUATE, NULL, false);
1181
1182 if (image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_E) {
1183 set_image_compressed_bit(cmd_buffer, image, aspect,
1184 level, base_layer, level_layer_count,
1185 false);
1186 }
1187 }
1188 } else {
1189 if (image->samples == 4 || image->samples == 16) {
1190 anv_perf_warn(cmd_buffer->device, image,
1191 "Doing a potentially unnecessary fast-clear to "
1192 "define an MCS buffer.");
1193 }
1194
1195 assert(base_level == 0 && level_count == 1);
1196 anv_image_mcs_op(cmd_buffer, image,
1197 image->planes[plane].surface.isl.format,
1198 ISL_SWIZZLE_IDENTITY,
1199 aspect, base_layer, layer_count,
1200 ISL_AUX_OP_FAST_CLEAR, NULL, false);
1201 }
1202 return;
1203 }
1204
1205 const enum isl_aux_usage initial_aux_usage =
1206 anv_layout_to_aux_usage(devinfo, image, aspect, 0, initial_layout);
1207 const enum isl_aux_usage final_aux_usage =
1208 anv_layout_to_aux_usage(devinfo, image, aspect, 0, final_layout);
1209
1210 /* The current code assumes that there is no mixing of CCS_E and CCS_D.
1211 * We can handle transitions between CCS_D/E to and from NONE. What we
1212 * don't yet handle is switching between CCS_E and CCS_D within a given
1213 * image. Doing so in a performant way requires more detailed aux state
1214 * tracking such as what is done in i965. For now, just assume that we
1215 * only have one type of compression.
1216 */
1217 assert(initial_aux_usage == ISL_AUX_USAGE_NONE ||
1218 final_aux_usage == ISL_AUX_USAGE_NONE ||
1219 initial_aux_usage == final_aux_usage);
1220
1221 /* If initial aux usage is NONE, there is nothing to resolve */
1222 if (initial_aux_usage == ISL_AUX_USAGE_NONE)
1223 return;
1224
1225 enum isl_aux_op resolve_op = ISL_AUX_OP_NONE;
1226
1227 /* If the initial layout supports more fast clear than the final layout
1228 * then we need at least a partial resolve.
1229 */
1230 const enum anv_fast_clear_type initial_fast_clear =
1231 anv_layout_to_fast_clear_type(devinfo, image, aspect, initial_layout);
1232 const enum anv_fast_clear_type final_fast_clear =
1233 anv_layout_to_fast_clear_type(devinfo, image, aspect, final_layout);
1234 if (final_fast_clear < initial_fast_clear)
1235 resolve_op = ISL_AUX_OP_PARTIAL_RESOLVE;
1236
1237 if (initial_aux_usage == ISL_AUX_USAGE_CCS_E &&
1238 final_aux_usage != ISL_AUX_USAGE_CCS_E)
1239 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
1240
1241 if (resolve_op == ISL_AUX_OP_NONE)
1242 return;
1243
1244 /* Perform a resolve to synchronize data between the main and aux buffer.
1245 * Before we begin, we must satisfy the cache flushing requirement specified
1246 * in the Sky Lake PRM Vol. 7, "MCS Buffer for Render Target(s)":
1247 *
1248 * Any transition from any value in {Clear, Render, Resolve} to a
1249 * different value in {Clear, Render, Resolve} requires end of pipe
1250 * synchronization.
1251 *
1252 * We perform a flush of the write cache before and after the clear and
1253 * resolve operations to meet this requirement.
1254 *
1255 * Unlike other drawing, fast clear operations are not properly
1256 * synchronized. The first PIPE_CONTROL here likely ensures that the
1257 * contents of the previous render or clear hit the render target before we
1258 * resolve and the second likely ensures that the resolve is complete before
1259 * we do any more rendering or clearing.
1260 */
1261 cmd_buffer->state.pending_pipe_bits |=
1262 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_END_OF_PIPE_SYNC_BIT;
1263
1264 for (uint32_t l = 0; l < level_count; l++) {
1265 uint32_t level = base_level + l;
1266
1267 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1268 if (base_layer >= aux_layers)
1269 break; /* We will only get fewer layers as level increases */
1270 uint32_t level_layer_count =
1271 MIN2(layer_count, aux_layers - base_layer);
1272
1273 for (uint32_t a = 0; a < level_layer_count; a++) {
1274 uint32_t array_layer = base_layer + a;
1275 if (image->samples == 1) {
1276 anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
1277 image->planes[plane].surface.isl.format,
1278 ISL_SWIZZLE_IDENTITY,
1279 aspect, level, array_layer, resolve_op,
1280 final_fast_clear);
1281 } else {
1282 /* We only support fast-clear on the first layer so partial
1283 * resolves should not be used on other layers as they will use
1284 * the clear color stored in memory that is only valid for layer0.
1285 */
1286 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
1287 array_layer != 0)
1288 continue;
1289
1290 anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
1291 image->planes[plane].surface.isl.format,
1292 ISL_SWIZZLE_IDENTITY,
1293 aspect, array_layer, resolve_op,
1294 final_fast_clear);
1295 }
1296 }
1297 }
1298
1299 cmd_buffer->state.pending_pipe_bits |=
1300 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_END_OF_PIPE_SYNC_BIT;
1301 }
1302
1303 static VkResult
1304 genX(cmd_buffer_setup_attachments)(struct anv_cmd_buffer *cmd_buffer,
1305 const struct anv_render_pass *pass,
1306 const struct anv_framebuffer *framebuffer,
1307 const VkRenderPassBeginInfo *begin)
1308 {
1309 struct anv_cmd_state *state = &cmd_buffer->state;
1310
1311 vk_free(&cmd_buffer->pool->alloc, state->attachments);
1312
1313 if (pass->attachment_count > 0) {
1314 state->attachments = vk_zalloc(&cmd_buffer->pool->alloc,
1315 pass->attachment_count *
1316 sizeof(state->attachments[0]),
1317 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1318 if (state->attachments == NULL) {
1319 /* Propagate VK_ERROR_OUT_OF_HOST_MEMORY to vkEndCommandBuffer */
1320 return anv_batch_set_error(&cmd_buffer->batch,
1321 VK_ERROR_OUT_OF_HOST_MEMORY);
1322 }
1323 } else {
1324 state->attachments = NULL;
1325 }
1326
1327 const VkRenderPassAttachmentBeginInfoKHR *attach_begin =
1328 vk_find_struct_const(begin, RENDER_PASS_ATTACHMENT_BEGIN_INFO_KHR);
1329 if (begin && !attach_begin)
1330 assert(pass->attachment_count == framebuffer->attachment_count);
1331
1332 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1333 if (attach_begin && attach_begin->attachmentCount != 0) {
1334 assert(attach_begin->attachmentCount == pass->attachment_count);
1335 ANV_FROM_HANDLE(anv_image_view, iview, attach_begin->pAttachments[i]);
1336 state->attachments[i].image_view = iview;
1337 } else if (framebuffer && i < framebuffer->attachment_count) {
1338 state->attachments[i].image_view = framebuffer->attachments[i];
1339 } else {
1340 state->attachments[i].image_view = NULL;
1341 }
1342 }
1343
1344 if (begin) {
1345 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1346 const struct anv_render_pass_attachment *pass_att = &pass->attachments[i];
1347 struct anv_attachment_state *att_state = &state->attachments[i];
1348 VkImageAspectFlags att_aspects = vk_format_aspects(pass_att->format);
1349 VkImageAspectFlags clear_aspects = 0;
1350 VkImageAspectFlags load_aspects = 0;
1351
1352 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1353 /* color attachment */
1354 if (pass_att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1355 clear_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1356 } else if (pass_att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1357 load_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1358 }
1359 } else {
1360 /* depthstencil attachment */
1361 if (att_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
1362 if (pass_att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1363 clear_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1364 } else if (pass_att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1365 load_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1366 }
1367 }
1368 if (att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
1369 if (pass_att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1370 clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1371 } else if (pass_att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1372 load_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1373 }
1374 }
1375 }
1376
1377 att_state->current_layout = pass_att->initial_layout;
1378 att_state->current_stencil_layout = pass_att->stencil_initial_layout;
1379 att_state->pending_clear_aspects = clear_aspects;
1380 att_state->pending_load_aspects = load_aspects;
1381 if (clear_aspects)
1382 att_state->clear_value = begin->pClearValues[i];
1383
1384 struct anv_image_view *iview = state->attachments[i].image_view;
1385 anv_assert(iview->vk_format == pass_att->format);
1386
1387 const uint32_t num_layers = iview->planes[0].isl.array_len;
1388 att_state->pending_clear_views = (1 << num_layers) - 1;
1389
1390 /* This will be initialized after the first subpass transition. */
1391 att_state->aux_usage = ISL_AUX_USAGE_NONE;
1392
1393 att_state->fast_clear = false;
1394 if (clear_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1395 assert(clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1396 att_state->fast_clear =
1397 anv_can_fast_clear_color_view(cmd_buffer->device, iview,
1398 pass_att->first_subpass_layout,
1399 vk_to_isl_color(att_state->clear_value.color),
1400 framebuffer->layers,
1401 begin->renderArea);
1402 } else if (clear_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT |
1403 VK_IMAGE_ASPECT_STENCIL_BIT)) {
1404 att_state->fast_clear =
1405 anv_can_hiz_clear_ds_view(cmd_buffer->device, iview,
1406 pass_att->first_subpass_layout,
1407 clear_aspects,
1408 att_state->clear_value.depthStencil.depth,
1409 begin->renderArea);
1410 }
1411 }
1412 }
1413
1414 return VK_SUCCESS;
1415 }
1416
1417 /**
1418 * Setup anv_cmd_state::attachments for vkCmdBeginRenderPass.
1419 */
1420 static VkResult
1421 genX(cmd_buffer_alloc_att_surf_states)(struct anv_cmd_buffer *cmd_buffer,
1422 const struct anv_render_pass *pass,
1423 const struct anv_subpass *subpass)
1424 {
1425 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
1426 struct anv_cmd_state *state = &cmd_buffer->state;
1427
1428 /* Reserve one for the NULL state. */
1429 unsigned num_states = 1;
1430 for (uint32_t i = 0; i < subpass->attachment_count; i++) {
1431 uint32_t att = subpass->attachments[i].attachment;
1432 if (att == VK_ATTACHMENT_UNUSED)
1433 continue;
1434
1435 assert(att < pass->attachment_count);
1436 if (!vk_format_is_color(pass->attachments[att].format))
1437 continue;
1438
1439 const VkImageUsageFlagBits att_usage = subpass->attachments[i].usage;
1440 assert(util_bitcount(att_usage) == 1);
1441
1442 if (att_usage == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ||
1443 att_usage == VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)
1444 num_states++;
1445 }
1446
1447 const uint32_t ss_stride = align_u32(isl_dev->ss.size, isl_dev->ss.align);
1448 state->attachment_states =
1449 anv_state_stream_alloc(&cmd_buffer->surface_state_stream,
1450 num_states * ss_stride, isl_dev->ss.align);
1451 if (state->attachment_states.map == NULL) {
1452 return anv_batch_set_error(&cmd_buffer->batch,
1453 VK_ERROR_OUT_OF_DEVICE_MEMORY);
1454 }
1455
1456 struct anv_state next_state = state->attachment_states;
1457 next_state.alloc_size = isl_dev->ss.size;
1458
1459 state->null_surface_state = next_state;
1460 next_state.offset += ss_stride;
1461 next_state.map += ss_stride;
1462
1463 for (uint32_t i = 0; i < subpass->attachment_count; i++) {
1464 uint32_t att = subpass->attachments[i].attachment;
1465 if (att == VK_ATTACHMENT_UNUSED)
1466 continue;
1467
1468 assert(att < pass->attachment_count);
1469 if (!vk_format_is_color(pass->attachments[att].format))
1470 continue;
1471
1472 const VkImageUsageFlagBits att_usage = subpass->attachments[i].usage;
1473 assert(util_bitcount(att_usage) == 1);
1474
1475 if (att_usage == VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)
1476 state->attachments[att].color.state = next_state;
1477 else if (att_usage == VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)
1478 state->attachments[att].input.state = next_state;
1479 else
1480 continue;
1481
1482 state->attachments[att].color.state = next_state;
1483 next_state.offset += ss_stride;
1484 next_state.map += ss_stride;
1485 }
1486
1487 assert(next_state.offset == state->attachment_states.offset +
1488 state->attachment_states.alloc_size);
1489
1490 return VK_SUCCESS;
1491 }
1492
1493 VkResult
1494 genX(BeginCommandBuffer)(
1495 VkCommandBuffer commandBuffer,
1496 const VkCommandBufferBeginInfo* pBeginInfo)
1497 {
1498 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1499
1500 /* If this is the first vkBeginCommandBuffer, we must *initialize* the
1501 * command buffer's state. Otherwise, we must *reset* its state. In both
1502 * cases we reset it.
1503 *
1504 * From the Vulkan 1.0 spec:
1505 *
1506 * If a command buffer is in the executable state and the command buffer
1507 * was allocated from a command pool with the
1508 * VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, then
1509 * vkBeginCommandBuffer implicitly resets the command buffer, behaving
1510 * as if vkResetCommandBuffer had been called with
1511 * VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT not set. It then puts
1512 * the command buffer in the recording state.
1513 */
1514 anv_cmd_buffer_reset(cmd_buffer);
1515
1516 cmd_buffer->usage_flags = pBeginInfo->flags;
1517
1518 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY ||
1519 !(cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT));
1520
1521 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
1522
1523 /* We sometimes store vertex data in the dynamic state buffer for blorp
1524 * operations and our dynamic state stream may re-use data from previous
1525 * command buffers. In order to prevent stale cache data, we flush the VF
1526 * cache. We could do this on every blorp call but that's not really
1527 * needed as all of the data will get written by the CPU prior to the GPU
1528 * executing anything. The chances are fairly high that they will use
1529 * blorp at least once per primary command buffer so it shouldn't be
1530 * wasted.
1531 *
1532 * There is also a workaround on gen8 which requires us to invalidate the
1533 * VF cache occasionally. It's easier if we can assume we start with a
1534 * fresh cache (See also genX(cmd_buffer_set_binding_for_gen8_vb_flush).)
1535 */
1536 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1537
1538 /* Re-emit the aux table register in every command buffer. This way we're
1539 * ensured that we have the table even if this command buffer doesn't
1540 * initialize any images.
1541 */
1542 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_AUX_TABLE_INVALIDATE_BIT;
1543
1544 /* We send an "Indirect State Pointers Disable" packet at
1545 * EndCommandBuffer, so all push contant packets are ignored during a
1546 * context restore. Documentation says after that command, we need to
1547 * emit push constants again before any rendering operation. So we
1548 * flag them dirty here to make sure they get emitted.
1549 */
1550 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1551
1552 VkResult result = VK_SUCCESS;
1553 if (cmd_buffer->usage_flags &
1554 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1555 assert(pBeginInfo->pInheritanceInfo);
1556 ANV_FROM_HANDLE(anv_render_pass, pass,
1557 pBeginInfo->pInheritanceInfo->renderPass);
1558 struct anv_subpass *subpass =
1559 &pass->subpasses[pBeginInfo->pInheritanceInfo->subpass];
1560 ANV_FROM_HANDLE(anv_framebuffer, framebuffer,
1561 pBeginInfo->pInheritanceInfo->framebuffer);
1562
1563 cmd_buffer->state.pass = pass;
1564 cmd_buffer->state.subpass = subpass;
1565
1566 /* This is optional in the inheritance info. */
1567 cmd_buffer->state.framebuffer = framebuffer;
1568
1569 result = genX(cmd_buffer_setup_attachments)(cmd_buffer, pass,
1570 framebuffer, NULL);
1571 if (result != VK_SUCCESS)
1572 return result;
1573
1574 result = genX(cmd_buffer_alloc_att_surf_states)(cmd_buffer, pass,
1575 subpass);
1576 if (result != VK_SUCCESS)
1577 return result;
1578
1579 /* Record that HiZ is enabled if we can. */
1580 if (cmd_buffer->state.framebuffer) {
1581 const struct anv_image_view * const iview =
1582 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
1583
1584 if (iview) {
1585 VkImageLayout layout =
1586 cmd_buffer->state.subpass->depth_stencil_attachment->layout;
1587
1588 enum isl_aux_usage aux_usage =
1589 anv_layout_to_aux_usage(&cmd_buffer->device->info, iview->image,
1590 VK_IMAGE_ASPECT_DEPTH_BIT,
1591 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
1592 layout);
1593
1594 cmd_buffer->state.hiz_enabled = isl_aux_usage_has_hiz(aux_usage);
1595 }
1596 }
1597
1598 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
1599 }
1600
1601 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1602 if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
1603 const VkCommandBufferInheritanceConditionalRenderingInfoEXT *conditional_rendering_info =
1604 vk_find_struct_const(pBeginInfo->pInheritanceInfo->pNext, COMMAND_BUFFER_INHERITANCE_CONDITIONAL_RENDERING_INFO_EXT);
1605
1606 /* If secondary buffer supports conditional rendering
1607 * we should emit commands as if conditional rendering is enabled.
1608 */
1609 cmd_buffer->state.conditional_render_enabled =
1610 conditional_rendering_info && conditional_rendering_info->conditionalRenderingEnable;
1611 }
1612 #endif
1613
1614 return result;
1615 }
1616
1617 /* From the PRM, Volume 2a:
1618 *
1619 * "Indirect State Pointers Disable
1620 *
1621 * At the completion of the post-sync operation associated with this pipe
1622 * control packet, the indirect state pointers in the hardware are
1623 * considered invalid; the indirect pointers are not saved in the context.
1624 * If any new indirect state commands are executed in the command stream
1625 * while the pipe control is pending, the new indirect state commands are
1626 * preserved.
1627 *
1628 * [DevIVB+]: Using Invalidate State Pointer (ISP) only inhibits context
1629 * restoring of Push Constant (3DSTATE_CONSTANT_*) commands. Push Constant
1630 * commands are only considered as Indirect State Pointers. Once ISP is
1631 * issued in a context, SW must initialize by programming push constant
1632 * commands for all the shaders (at least to zero length) before attempting
1633 * any rendering operation for the same context."
1634 *
1635 * 3DSTATE_CONSTANT_* packets are restored during a context restore,
1636 * even though they point to a BO that has been already unreferenced at
1637 * the end of the previous batch buffer. This has been fine so far since
1638 * we are protected by these scratch page (every address not covered by
1639 * a BO should be pointing to the scratch page). But on CNL, it is
1640 * causing a GPU hang during context restore at the 3DSTATE_CONSTANT_*
1641 * instruction.
1642 *
1643 * The flag "Indirect State Pointers Disable" in PIPE_CONTROL tells the
1644 * hardware to ignore previous 3DSTATE_CONSTANT_* packets during a
1645 * context restore, so the mentioned hang doesn't happen. However,
1646 * software must program push constant commands for all stages prior to
1647 * rendering anything. So we flag them dirty in BeginCommandBuffer.
1648 *
1649 * Finally, we also make sure to stall at pixel scoreboard to make sure the
1650 * constants have been loaded into the EUs prior to disable the push constants
1651 * so that it doesn't hang a previous 3DPRIMITIVE.
1652 */
1653 static void
1654 emit_isp_disable(struct anv_cmd_buffer *cmd_buffer)
1655 {
1656 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1657 pc.StallAtPixelScoreboard = true;
1658 pc.CommandStreamerStallEnable = true;
1659 }
1660 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1661 pc.IndirectStatePointersDisable = true;
1662 pc.CommandStreamerStallEnable = true;
1663 }
1664 }
1665
1666 VkResult
1667 genX(EndCommandBuffer)(
1668 VkCommandBuffer commandBuffer)
1669 {
1670 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1671
1672 if (anv_batch_has_error(&cmd_buffer->batch))
1673 return cmd_buffer->batch.status;
1674
1675 /* We want every command buffer to start with the PMA fix in a known state,
1676 * so we disable it at the end of the command buffer.
1677 */
1678 genX(cmd_buffer_enable_pma_fix)(cmd_buffer, false);
1679
1680 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
1681
1682 emit_isp_disable(cmd_buffer);
1683
1684 anv_cmd_buffer_end_batch_buffer(cmd_buffer);
1685
1686 return VK_SUCCESS;
1687 }
1688
1689 void
1690 genX(CmdExecuteCommands)(
1691 VkCommandBuffer commandBuffer,
1692 uint32_t commandBufferCount,
1693 const VkCommandBuffer* pCmdBuffers)
1694 {
1695 ANV_FROM_HANDLE(anv_cmd_buffer, primary, commandBuffer);
1696
1697 assert(primary->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1698
1699 if (anv_batch_has_error(&primary->batch))
1700 return;
1701
1702 /* The secondary command buffers will assume that the PMA fix is disabled
1703 * when they begin executing. Make sure this is true.
1704 */
1705 genX(cmd_buffer_enable_pma_fix)(primary, false);
1706
1707 /* The secondary command buffer doesn't know which textures etc. have been
1708 * flushed prior to their execution. Apply those flushes now.
1709 */
1710 genX(cmd_buffer_apply_pipe_flushes)(primary);
1711
1712 for (uint32_t i = 0; i < commandBufferCount; i++) {
1713 ANV_FROM_HANDLE(anv_cmd_buffer, secondary, pCmdBuffers[i]);
1714
1715 assert(secondary->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY);
1716 assert(!anv_batch_has_error(&secondary->batch));
1717
1718 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1719 if (secondary->state.conditional_render_enabled) {
1720 if (!primary->state.conditional_render_enabled) {
1721 /* Secondary buffer is constructed as if it will be executed
1722 * with conditional rendering, we should satisfy this dependency
1723 * regardless of conditional rendering being enabled in primary.
1724 */
1725 struct gen_mi_builder b;
1726 gen_mi_builder_init(&b, &primary->batch);
1727 gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
1728 gen_mi_imm(UINT64_MAX));
1729 }
1730 }
1731 #endif
1732
1733 if (secondary->usage_flags &
1734 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1735 /* If we're continuing a render pass from the primary, we need to
1736 * copy the surface states for the current subpass into the storage
1737 * we allocated for them in BeginCommandBuffer.
1738 */
1739 struct anv_bo *ss_bo =
1740 primary->device->surface_state_pool.block_pool.bo;
1741 struct anv_state src_state = primary->state.attachment_states;
1742 struct anv_state dst_state = secondary->state.attachment_states;
1743 assert(src_state.alloc_size == dst_state.alloc_size);
1744
1745 genX(cmd_buffer_so_memcpy)(primary,
1746 (struct anv_address) {
1747 .bo = ss_bo,
1748 .offset = dst_state.offset,
1749 },
1750 (struct anv_address) {
1751 .bo = ss_bo,
1752 .offset = src_state.offset,
1753 },
1754 src_state.alloc_size);
1755 }
1756
1757 anv_cmd_buffer_add_secondary(primary, secondary);
1758 }
1759
1760 /* The secondary isn't counted in our VF cache tracking so we need to
1761 * invalidate the whole thing.
1762 */
1763 if (GEN_GEN >= 8 && GEN_GEN <= 9) {
1764 primary->state.pending_pipe_bits |=
1765 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1766 }
1767
1768 /* The secondary may have selected a different pipeline (3D or compute) and
1769 * may have changed the current L3$ configuration. Reset our tracking
1770 * variables to invalid values to ensure that we re-emit these in the case
1771 * where we do any draws or compute dispatches from the primary after the
1772 * secondary has returned.
1773 */
1774 primary->state.current_pipeline = UINT32_MAX;
1775 primary->state.current_l3_config = NULL;
1776 primary->state.current_hash_scale = 0;
1777
1778 /* Each of the secondary command buffers will use its own state base
1779 * address. We need to re-emit state base address for the primary after
1780 * all of the secondaries are done.
1781 *
1782 * TODO: Maybe we want to make this a dirty bit to avoid extra state base
1783 * address calls?
1784 */
1785 genX(cmd_buffer_emit_state_base_address)(primary);
1786 }
1787
1788 #define IVB_L3SQCREG1_SQGHPCI_DEFAULT 0x00730000
1789 #define VLV_L3SQCREG1_SQGHPCI_DEFAULT 0x00d30000
1790 #define HSW_L3SQCREG1_SQGHPCI_DEFAULT 0x00610000
1791
1792 /**
1793 * Program the hardware to use the specified L3 configuration.
1794 */
1795 void
1796 genX(cmd_buffer_config_l3)(struct anv_cmd_buffer *cmd_buffer,
1797 const struct gen_l3_config *cfg)
1798 {
1799 assert(cfg);
1800 if (cfg == cmd_buffer->state.current_l3_config)
1801 return;
1802
1803 if (unlikely(INTEL_DEBUG & DEBUG_L3)) {
1804 intel_logd("L3 config transition: ");
1805 gen_dump_l3_config(cfg, stderr);
1806 }
1807
1808 UNUSED const bool has_slm = cfg->n[GEN_L3P_SLM];
1809
1810 /* According to the hardware docs, the L3 partitioning can only be changed
1811 * while the pipeline is completely drained and the caches are flushed,
1812 * which involves a first PIPE_CONTROL flush which stalls the pipeline...
1813 */
1814 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1815 pc.DCFlushEnable = true;
1816 pc.PostSyncOperation = NoWrite;
1817 pc.CommandStreamerStallEnable = true;
1818 }
1819
1820 /* ...followed by a second pipelined PIPE_CONTROL that initiates
1821 * invalidation of the relevant caches. Note that because RO invalidation
1822 * happens at the top of the pipeline (i.e. right away as the PIPE_CONTROL
1823 * command is processed by the CS) we cannot combine it with the previous
1824 * stalling flush as the hardware documentation suggests, because that
1825 * would cause the CS to stall on previous rendering *after* RO
1826 * invalidation and wouldn't prevent the RO caches from being polluted by
1827 * concurrent rendering before the stall completes. This intentionally
1828 * doesn't implement the SKL+ hardware workaround suggesting to enable CS
1829 * stall on PIPE_CONTROLs with the texture cache invalidation bit set for
1830 * GPGPU workloads because the previous and subsequent PIPE_CONTROLs
1831 * already guarantee that there is no concurrent GPGPU kernel execution
1832 * (see SKL HSD 2132585).
1833 */
1834 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1835 pc.TextureCacheInvalidationEnable = true;
1836 pc.ConstantCacheInvalidationEnable = true;
1837 pc.InstructionCacheInvalidateEnable = true;
1838 pc.StateCacheInvalidationEnable = true;
1839 pc.PostSyncOperation = NoWrite;
1840 }
1841
1842 /* Now send a third stalling flush to make sure that invalidation is
1843 * complete when the L3 configuration registers are modified.
1844 */
1845 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1846 pc.DCFlushEnable = true;
1847 pc.PostSyncOperation = NoWrite;
1848 pc.CommandStreamerStallEnable = true;
1849 }
1850
1851 #if GEN_GEN >= 8
1852
1853 assert(!cfg->n[GEN_L3P_IS] && !cfg->n[GEN_L3P_C] && !cfg->n[GEN_L3P_T]);
1854
1855 #if GEN_GEN >= 12
1856 #define L3_ALLOCATION_REG GENX(L3ALLOC)
1857 #define L3_ALLOCATION_REG_num GENX(L3ALLOC_num)
1858 #else
1859 #define L3_ALLOCATION_REG GENX(L3CNTLREG)
1860 #define L3_ALLOCATION_REG_num GENX(L3CNTLREG_num)
1861 #endif
1862
1863 uint32_t l3cr;
1864 anv_pack_struct(&l3cr, L3_ALLOCATION_REG,
1865 #if GEN_GEN < 11
1866 .SLMEnable = has_slm,
1867 #endif
1868 #if GEN_GEN == 11
1869 /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
1870 * in L3CNTLREG register. The default setting of the bit is not the
1871 * desirable behavior.
1872 */
1873 .ErrorDetectionBehaviorControl = true,
1874 .UseFullWays = true,
1875 #endif
1876 .URBAllocation = cfg->n[GEN_L3P_URB],
1877 .ROAllocation = cfg->n[GEN_L3P_RO],
1878 .DCAllocation = cfg->n[GEN_L3P_DC],
1879 .AllAllocation = cfg->n[GEN_L3P_ALL]);
1880
1881 /* Set up the L3 partitioning. */
1882 emit_lri(&cmd_buffer->batch, L3_ALLOCATION_REG_num, l3cr);
1883
1884 #else
1885
1886 const bool has_dc = cfg->n[GEN_L3P_DC] || cfg->n[GEN_L3P_ALL];
1887 const bool has_is = cfg->n[GEN_L3P_IS] || cfg->n[GEN_L3P_RO] ||
1888 cfg->n[GEN_L3P_ALL];
1889 const bool has_c = cfg->n[GEN_L3P_C] || cfg->n[GEN_L3P_RO] ||
1890 cfg->n[GEN_L3P_ALL];
1891 const bool has_t = cfg->n[GEN_L3P_T] || cfg->n[GEN_L3P_RO] ||
1892 cfg->n[GEN_L3P_ALL];
1893
1894 assert(!cfg->n[GEN_L3P_ALL]);
1895
1896 /* When enabled SLM only uses a portion of the L3 on half of the banks,
1897 * the matching space on the remaining banks has to be allocated to a
1898 * client (URB for all validated configurations) set to the
1899 * lower-bandwidth 2-bank address hashing mode.
1900 */
1901 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1902 const bool urb_low_bw = has_slm && !devinfo->is_baytrail;
1903 assert(!urb_low_bw || cfg->n[GEN_L3P_URB] == cfg->n[GEN_L3P_SLM]);
1904
1905 /* Minimum number of ways that can be allocated to the URB. */
1906 const unsigned n0_urb = devinfo->is_baytrail ? 32 : 0;
1907 assert(cfg->n[GEN_L3P_URB] >= n0_urb);
1908
1909 uint32_t l3sqcr1, l3cr2, l3cr3;
1910 anv_pack_struct(&l3sqcr1, GENX(L3SQCREG1),
1911 .ConvertDC_UC = !has_dc,
1912 .ConvertIS_UC = !has_is,
1913 .ConvertC_UC = !has_c,
1914 .ConvertT_UC = !has_t);
1915 l3sqcr1 |=
1916 GEN_IS_HASWELL ? HSW_L3SQCREG1_SQGHPCI_DEFAULT :
1917 devinfo->is_baytrail ? VLV_L3SQCREG1_SQGHPCI_DEFAULT :
1918 IVB_L3SQCREG1_SQGHPCI_DEFAULT;
1919
1920 anv_pack_struct(&l3cr2, GENX(L3CNTLREG2),
1921 .SLMEnable = has_slm,
1922 .URBLowBandwidth = urb_low_bw,
1923 .URBAllocation = cfg->n[GEN_L3P_URB] - n0_urb,
1924 #if !GEN_IS_HASWELL
1925 .ALLAllocation = cfg->n[GEN_L3P_ALL],
1926 #endif
1927 .ROAllocation = cfg->n[GEN_L3P_RO],
1928 .DCAllocation = cfg->n[GEN_L3P_DC]);
1929
1930 anv_pack_struct(&l3cr3, GENX(L3CNTLREG3),
1931 .ISAllocation = cfg->n[GEN_L3P_IS],
1932 .ISLowBandwidth = 0,
1933 .CAllocation = cfg->n[GEN_L3P_C],
1934 .CLowBandwidth = 0,
1935 .TAllocation = cfg->n[GEN_L3P_T],
1936 .TLowBandwidth = 0);
1937
1938 /* Set up the L3 partitioning. */
1939 emit_lri(&cmd_buffer->batch, GENX(L3SQCREG1_num), l3sqcr1);
1940 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG2_num), l3cr2);
1941 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG3_num), l3cr3);
1942
1943 #if GEN_IS_HASWELL
1944 if (cmd_buffer->device->physical->cmd_parser_version >= 4) {
1945 /* Enable L3 atomics on HSW if we have a DC partition, otherwise keep
1946 * them disabled to avoid crashing the system hard.
1947 */
1948 uint32_t scratch1, chicken3;
1949 anv_pack_struct(&scratch1, GENX(SCRATCH1),
1950 .L3AtomicDisable = !has_dc);
1951 anv_pack_struct(&chicken3, GENX(CHICKEN3),
1952 .L3AtomicDisableMask = true,
1953 .L3AtomicDisable = !has_dc);
1954 emit_lri(&cmd_buffer->batch, GENX(SCRATCH1_num), scratch1);
1955 emit_lri(&cmd_buffer->batch, GENX(CHICKEN3_num), chicken3);
1956 }
1957 #endif
1958
1959 #endif
1960
1961 cmd_buffer->state.current_l3_config = cfg;
1962 }
1963
1964 void
1965 genX(cmd_buffer_apply_pipe_flushes)(struct anv_cmd_buffer *cmd_buffer)
1966 {
1967 UNUSED const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1968 enum anv_pipe_bits bits = cmd_buffer->state.pending_pipe_bits;
1969
1970 if (cmd_buffer->device->physical->always_flush_cache)
1971 bits |= ANV_PIPE_FLUSH_BITS | ANV_PIPE_INVALIDATE_BITS;
1972
1973 /*
1974 * From Sandybridge PRM, volume 2, "1.7.2 End-of-Pipe Synchronization":
1975 *
1976 * Write synchronization is a special case of end-of-pipe
1977 * synchronization that requires that the render cache and/or depth
1978 * related caches are flushed to memory, where the data will become
1979 * globally visible. This type of synchronization is required prior to
1980 * SW (CPU) actually reading the result data from memory, or initiating
1981 * an operation that will use as a read surface (such as a texture
1982 * surface) a previous render target and/or depth/stencil buffer
1983 *
1984 *
1985 * From Haswell PRM, volume 2, part 1, "End-of-Pipe Synchronization":
1986 *
1987 * Exercising the write cache flush bits (Render Target Cache Flush
1988 * Enable, Depth Cache Flush Enable, DC Flush) in PIPE_CONTROL only
1989 * ensures the write caches are flushed and doesn't guarantee the data
1990 * is globally visible.
1991 *
1992 * SW can track the completion of the end-of-pipe-synchronization by
1993 * using "Notify Enable" and "PostSync Operation - Write Immediate
1994 * Data" in the PIPE_CONTROL command.
1995 *
1996 * In other words, flushes are pipelined while invalidations are handled
1997 * immediately. Therefore, if we're flushing anything then we need to
1998 * schedule an end-of-pipe sync before any invalidations can happen.
1999 */
2000 if (bits & ANV_PIPE_FLUSH_BITS)
2001 bits |= ANV_PIPE_NEEDS_END_OF_PIPE_SYNC_BIT;
2002
2003
2004 /* HSD 1209978178: docs say that before programming the aux table:
2005 *
2006 * "Driver must ensure that the engine is IDLE but ensure it doesn't
2007 * add extra flushes in the case it knows that the engine is already
2008 * IDLE."
2009 */
2010 if (GEN_GEN == 12 && (bits & ANV_PIPE_AUX_TABLE_INVALIDATE_BIT))
2011 bits |= ANV_PIPE_NEEDS_END_OF_PIPE_SYNC_BIT;
2012
2013 /* If we're going to do an invalidate and we have a pending end-of-pipe
2014 * sync that has yet to be resolved, we do the end-of-pipe sync now.
2015 */
2016 if ((bits & ANV_PIPE_INVALIDATE_BITS) &&
2017 (bits & ANV_PIPE_NEEDS_END_OF_PIPE_SYNC_BIT)) {
2018 bits |= ANV_PIPE_END_OF_PIPE_SYNC_BIT;
2019 bits &= ~ANV_PIPE_NEEDS_END_OF_PIPE_SYNC_BIT;
2020 }
2021
2022 if (GEN_GEN >= 12 &&
2023 ((bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT) ||
2024 (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT))) {
2025 /* From the PIPE_CONTROL instruction table, bit 28 (Tile Cache Flush
2026 * Enable):
2027 *
2028 * Unified Cache (Tile Cache Disabled):
2029 *
2030 * When the Color and Depth (Z) streams are enabled to be cached in
2031 * the DC space of L2, Software must use "Render Target Cache Flush
2032 * Enable" and "Depth Cache Flush Enable" along with "Tile Cache
2033 * Flush" for getting the color and depth (Z) write data to be
2034 * globally observable. In this mode of operation it is not required
2035 * to set "CS Stall" upon setting "Tile Cache Flush" bit.
2036 */
2037 bits |= ANV_PIPE_TILE_CACHE_FLUSH_BIT;
2038 }
2039
2040 /* GEN:BUG:1409226450, Wait for EU to be idle before pipe control which
2041 * invalidates the instruction cache
2042 */
2043 if (GEN_GEN == 12 && (bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT))
2044 bits |= ANV_PIPE_CS_STALL_BIT | ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
2045
2046 if ((GEN_GEN >= 8 && GEN_GEN <= 9) &&
2047 (bits & ANV_PIPE_CS_STALL_BIT) &&
2048 (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT)) {
2049 /* If we are doing a VF cache invalidate AND a CS stall (it must be
2050 * both) then we can reset our vertex cache tracking.
2051 */
2052 memset(cmd_buffer->state.gfx.vb_dirty_ranges, 0,
2053 sizeof(cmd_buffer->state.gfx.vb_dirty_ranges));
2054 memset(&cmd_buffer->state.gfx.ib_dirty_range, 0,
2055 sizeof(cmd_buffer->state.gfx.ib_dirty_range));
2056 }
2057
2058 /* Project: SKL / Argument: LRI Post Sync Operation [23]
2059 *
2060 * "PIPECONTROL command with “Command Streamer Stall Enable” must be
2061 * programmed prior to programming a PIPECONTROL command with "LRI
2062 * Post Sync Operation" in GPGPU mode of operation (i.e when
2063 * PIPELINE_SELECT command is set to GPGPU mode of operation)."
2064 *
2065 * The same text exists a few rows below for Post Sync Op.
2066 *
2067 * On Gen12 this is GEN:BUG:1607156449.
2068 */
2069 if (bits & ANV_PIPE_POST_SYNC_BIT) {
2070 if ((GEN_GEN == 9 || (GEN_GEN == 12 && devinfo->revision == 0 /* A0 */)) &&
2071 cmd_buffer->state.current_pipeline == GPGPU)
2072 bits |= ANV_PIPE_CS_STALL_BIT;
2073 bits &= ~ANV_PIPE_POST_SYNC_BIT;
2074 }
2075
2076 if (bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT |
2077 ANV_PIPE_END_OF_PIPE_SYNC_BIT)) {
2078 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
2079 #if GEN_GEN >= 12
2080 pipe.TileCacheFlushEnable = bits & ANV_PIPE_TILE_CACHE_FLUSH_BIT;
2081 #endif
2082 pipe.DepthCacheFlushEnable = bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
2083 pipe.DCFlushEnable = bits & ANV_PIPE_DATA_CACHE_FLUSH_BIT;
2084 pipe.RenderTargetCacheFlushEnable =
2085 bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
2086
2087 /* GEN:BUG:1409600907: "PIPE_CONTROL with Depth Stall Enable bit must
2088 * be set with any PIPE_CONTROL with Depth Flush Enable bit set.
2089 */
2090 #if GEN_GEN >= 12
2091 pipe.DepthStallEnable =
2092 pipe.DepthCacheFlushEnable || (bits & ANV_PIPE_DEPTH_STALL_BIT);
2093 #else
2094 pipe.DepthStallEnable = bits & ANV_PIPE_DEPTH_STALL_BIT;
2095 #endif
2096
2097 pipe.CommandStreamerStallEnable = bits & ANV_PIPE_CS_STALL_BIT;
2098 pipe.StallAtPixelScoreboard = bits & ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
2099
2100 /* From Sandybridge PRM, volume 2, "1.7.3.1 Writing a Value to Memory":
2101 *
2102 * "The most common action to perform upon reaching a
2103 * synchronization point is to write a value out to memory. An
2104 * immediate value (included with the synchronization command) may
2105 * be written."
2106 *
2107 *
2108 * From Broadwell PRM, volume 7, "End-of-Pipe Synchronization":
2109 *
2110 * "In case the data flushed out by the render engine is to be
2111 * read back in to the render engine in coherent manner, then the
2112 * render engine has to wait for the fence completion before
2113 * accessing the flushed data. This can be achieved by following
2114 * means on various products: PIPE_CONTROL command with CS Stall
2115 * and the required write caches flushed with Post-Sync-Operation
2116 * as Write Immediate Data.
2117 *
2118 * Example:
2119 * - Workload-1 (3D/GPGPU/MEDIA)
2120 * - PIPE_CONTROL (CS Stall, Post-Sync-Operation Write
2121 * Immediate Data, Required Write Cache Flush bits set)
2122 * - Workload-2 (Can use the data produce or output by
2123 * Workload-1)
2124 */
2125 if (bits & ANV_PIPE_END_OF_PIPE_SYNC_BIT) {
2126 pipe.CommandStreamerStallEnable = true;
2127 pipe.PostSyncOperation = WriteImmediateData;
2128 pipe.Address = (struct anv_address) {
2129 .bo = cmd_buffer->device->workaround_bo,
2130 .offset = 0
2131 };
2132 }
2133
2134 /*
2135 * According to the Broadwell documentation, any PIPE_CONTROL with the
2136 * "Command Streamer Stall" bit set must also have another bit set,
2137 * with five different options:
2138 *
2139 * - Render Target Cache Flush
2140 * - Depth Cache Flush
2141 * - Stall at Pixel Scoreboard
2142 * - Post-Sync Operation
2143 * - Depth Stall
2144 * - DC Flush Enable
2145 *
2146 * I chose "Stall at Pixel Scoreboard" since that's what we use in
2147 * mesa and it seems to work fine. The choice is fairly arbitrary.
2148 */
2149 if (pipe.CommandStreamerStallEnable &&
2150 !pipe.RenderTargetCacheFlushEnable &&
2151 !pipe.DepthCacheFlushEnable &&
2152 !pipe.StallAtPixelScoreboard &&
2153 !pipe.PostSyncOperation &&
2154 !pipe.DepthStallEnable &&
2155 !pipe.DCFlushEnable)
2156 pipe.StallAtPixelScoreboard = true;
2157 }
2158
2159 /* If a render target flush was emitted, then we can toggle off the bit
2160 * saying that render target writes are ongoing.
2161 */
2162 if (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
2163 bits &= ~(ANV_PIPE_RENDER_TARGET_BUFFER_WRITES);
2164
2165 if (GEN_IS_HASWELL) {
2166 /* Haswell needs addition work-arounds:
2167 *
2168 * From Haswell PRM, volume 2, part 1, "End-of-Pipe Synchronization":
2169 *
2170 * Option 1:
2171 * PIPE_CONTROL command with the CS Stall and the required write
2172 * caches flushed with Post-SyncOperation as Write Immediate Data
2173 * followed by eight dummy MI_STORE_DATA_IMM (write to scratch
2174 * spce) commands.
2175 *
2176 * Example:
2177 * - Workload-1
2178 * - PIPE_CONTROL (CS Stall, Post-Sync-Operation Write
2179 * Immediate Data, Required Write Cache Flush bits set)
2180 * - MI_STORE_DATA_IMM (8 times) (Dummy data, Scratch Address)
2181 * - Workload-2 (Can use the data produce or output by
2182 * Workload-1)
2183 *
2184 * Unfortunately, both the PRMs and the internal docs are a bit
2185 * out-of-date in this regard. What the windows driver does (and
2186 * this appears to actually work) is to emit a register read from the
2187 * memory address written by the pipe control above.
2188 *
2189 * What register we load into doesn't matter. We choose an indirect
2190 * rendering register because we know it always exists and it's one
2191 * of the first registers the command parser allows us to write. If
2192 * you don't have command parser support in your kernel (pre-4.2),
2193 * this will get turned into MI_NOOP and you won't get the
2194 * workaround. Unfortunately, there's just not much we can do in
2195 * that case. This register is perfectly safe to write since we
2196 * always re-load all of the indirect draw registers right before
2197 * 3DPRIMITIVE when needed anyway.
2198 */
2199 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
2200 lrm.RegisterAddress = 0x243C; /* GEN7_3DPRIM_START_INSTANCE */
2201 lrm.MemoryAddress = (struct anv_address) {
2202 .bo = cmd_buffer->device->workaround_bo,
2203 .offset = 0
2204 };
2205 }
2206 }
2207
2208 bits &= ~(ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT |
2209 ANV_PIPE_END_OF_PIPE_SYNC_BIT);
2210 }
2211
2212 if (bits & ANV_PIPE_INVALIDATE_BITS) {
2213 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
2214 *
2215 * "If the VF Cache Invalidation Enable is set to a 1 in a
2216 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields sets to
2217 * 0, with the VF Cache Invalidation Enable set to 0 needs to be sent
2218 * prior to the PIPE_CONTROL with VF Cache Invalidation Enable set to
2219 * a 1."
2220 *
2221 * This appears to hang Broadwell, so we restrict it to just gen9.
2222 */
2223 if (GEN_GEN == 9 && (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT))
2224 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe);
2225
2226 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
2227 pipe.StateCacheInvalidationEnable =
2228 bits & ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
2229 pipe.ConstantCacheInvalidationEnable =
2230 bits & ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
2231 pipe.VFCacheInvalidationEnable =
2232 bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
2233 pipe.TextureCacheInvalidationEnable =
2234 bits & ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
2235 pipe.InstructionCacheInvalidateEnable =
2236 bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT;
2237
2238 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
2239 *
2240 * "When VF Cache Invalidate is set “Post Sync Operation” must be
2241 * enabled to “Write Immediate Data” or “Write PS Depth Count” or
2242 * “Write Timestamp”.
2243 */
2244 if (GEN_GEN == 9 && pipe.VFCacheInvalidationEnable) {
2245 pipe.PostSyncOperation = WriteImmediateData;
2246 pipe.Address =
2247 (struct anv_address) { cmd_buffer->device->workaround_bo, 0 };
2248 }
2249 }
2250
2251 #if GEN_GEN == 12
2252 if ((bits & ANV_PIPE_AUX_TABLE_INVALIDATE_BIT) &&
2253 cmd_buffer->device->info.has_aux_map) {
2254 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
2255 lri.RegisterOffset = GENX(GFX_CCS_AUX_INV_num);
2256 lri.DataDWord = 1;
2257 }
2258 }
2259 #endif
2260
2261 bits &= ~ANV_PIPE_INVALIDATE_BITS;
2262 }
2263
2264 cmd_buffer->state.pending_pipe_bits = bits;
2265 }
2266
2267 void genX(CmdPipelineBarrier)(
2268 VkCommandBuffer commandBuffer,
2269 VkPipelineStageFlags srcStageMask,
2270 VkPipelineStageFlags destStageMask,
2271 VkBool32 byRegion,
2272 uint32_t memoryBarrierCount,
2273 const VkMemoryBarrier* pMemoryBarriers,
2274 uint32_t bufferMemoryBarrierCount,
2275 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
2276 uint32_t imageMemoryBarrierCount,
2277 const VkImageMemoryBarrier* pImageMemoryBarriers)
2278 {
2279 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2280
2281 /* XXX: Right now, we're really dumb and just flush whatever categories
2282 * the app asks for. One of these days we may make this a bit better
2283 * but right now that's all the hardware allows for in most areas.
2284 */
2285 VkAccessFlags src_flags = 0;
2286 VkAccessFlags dst_flags = 0;
2287
2288 for (uint32_t i = 0; i < memoryBarrierCount; i++) {
2289 src_flags |= pMemoryBarriers[i].srcAccessMask;
2290 dst_flags |= pMemoryBarriers[i].dstAccessMask;
2291 }
2292
2293 for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
2294 src_flags |= pBufferMemoryBarriers[i].srcAccessMask;
2295 dst_flags |= pBufferMemoryBarriers[i].dstAccessMask;
2296 }
2297
2298 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
2299 src_flags |= pImageMemoryBarriers[i].srcAccessMask;
2300 dst_flags |= pImageMemoryBarriers[i].dstAccessMask;
2301 ANV_FROM_HANDLE(anv_image, image, pImageMemoryBarriers[i].image);
2302 const VkImageSubresourceRange *range =
2303 &pImageMemoryBarriers[i].subresourceRange;
2304
2305 uint32_t base_layer, layer_count;
2306 if (image->type == VK_IMAGE_TYPE_3D) {
2307 base_layer = 0;
2308 layer_count = anv_minify(image->extent.depth, range->baseMipLevel);
2309 } else {
2310 base_layer = range->baseArrayLayer;
2311 layer_count = anv_get_layerCount(image, range);
2312 }
2313
2314 if (range->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
2315 transition_depth_buffer(cmd_buffer, image,
2316 base_layer, layer_count,
2317 pImageMemoryBarriers[i].oldLayout,
2318 pImageMemoryBarriers[i].newLayout);
2319 }
2320
2321 if (range->aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
2322 transition_stencil_buffer(cmd_buffer, image,
2323 range->baseMipLevel,
2324 anv_get_levelCount(image, range),
2325 base_layer, layer_count,
2326 pImageMemoryBarriers[i].oldLayout,
2327 pImageMemoryBarriers[i].newLayout);
2328 }
2329
2330 if (range->aspectMask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
2331 VkImageAspectFlags color_aspects =
2332 anv_image_expand_aspects(image, range->aspectMask);
2333 uint32_t aspect_bit;
2334 anv_foreach_image_aspect_bit(aspect_bit, image, color_aspects) {
2335 transition_color_buffer(cmd_buffer, image, 1UL << aspect_bit,
2336 range->baseMipLevel,
2337 anv_get_levelCount(image, range),
2338 base_layer, layer_count,
2339 pImageMemoryBarriers[i].oldLayout,
2340 pImageMemoryBarriers[i].newLayout);
2341 }
2342 }
2343 }
2344
2345 cmd_buffer->state.pending_pipe_bits |=
2346 anv_pipe_flush_bits_for_access_flags(src_flags) |
2347 anv_pipe_invalidate_bits_for_access_flags(dst_flags);
2348 }
2349
2350 static void
2351 cmd_buffer_alloc_push_constants(struct anv_cmd_buffer *cmd_buffer)
2352 {
2353 VkShaderStageFlags stages =
2354 cmd_buffer->state.gfx.pipeline->active_stages;
2355
2356 /* In order to avoid thrash, we assume that vertex and fragment stages
2357 * always exist. In the rare case where one is missing *and* the other
2358 * uses push concstants, this may be suboptimal. However, avoiding stalls
2359 * seems more important.
2360 */
2361 stages |= VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT;
2362
2363 if (stages == cmd_buffer->state.push_constant_stages)
2364 return;
2365
2366 #if GEN_GEN >= 8
2367 const unsigned push_constant_kb = 32;
2368 #elif GEN_IS_HASWELL
2369 const unsigned push_constant_kb = cmd_buffer->device->info.gt == 3 ? 32 : 16;
2370 #else
2371 const unsigned push_constant_kb = 16;
2372 #endif
2373
2374 const unsigned num_stages =
2375 util_bitcount(stages & VK_SHADER_STAGE_ALL_GRAPHICS);
2376 unsigned size_per_stage = push_constant_kb / num_stages;
2377
2378 /* Broadwell+ and Haswell gt3 require that the push constant sizes be in
2379 * units of 2KB. Incidentally, these are the same platforms that have
2380 * 32KB worth of push constant space.
2381 */
2382 if (push_constant_kb == 32)
2383 size_per_stage &= ~1u;
2384
2385 uint32_t kb_used = 0;
2386 for (int i = MESA_SHADER_VERTEX; i < MESA_SHADER_FRAGMENT; i++) {
2387 unsigned push_size = (stages & (1 << i)) ? size_per_stage : 0;
2388 anv_batch_emit(&cmd_buffer->batch,
2389 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
2390 alloc._3DCommandSubOpcode = 18 + i;
2391 alloc.ConstantBufferOffset = (push_size > 0) ? kb_used : 0;
2392 alloc.ConstantBufferSize = push_size;
2393 }
2394 kb_used += push_size;
2395 }
2396
2397 anv_batch_emit(&cmd_buffer->batch,
2398 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_PS), alloc) {
2399 alloc.ConstantBufferOffset = kb_used;
2400 alloc.ConstantBufferSize = push_constant_kb - kb_used;
2401 }
2402
2403 cmd_buffer->state.push_constant_stages = stages;
2404
2405 /* From the BDW PRM for 3DSTATE_PUSH_CONSTANT_ALLOC_VS:
2406 *
2407 * "The 3DSTATE_CONSTANT_VS must be reprogrammed prior to
2408 * the next 3DPRIMITIVE command after programming the
2409 * 3DSTATE_PUSH_CONSTANT_ALLOC_VS"
2410 *
2411 * Since 3DSTATE_PUSH_CONSTANT_ALLOC_VS is programmed as part of
2412 * pipeline setup, we need to dirty push constants.
2413 */
2414 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
2415 }
2416
2417 static struct anv_address
2418 anv_descriptor_set_address(struct anv_cmd_buffer *cmd_buffer,
2419 struct anv_descriptor_set *set)
2420 {
2421 if (set->pool) {
2422 /* This is a normal descriptor set */
2423 return (struct anv_address) {
2424 .bo = set->pool->bo,
2425 .offset = set->desc_mem.offset,
2426 };
2427 } else {
2428 /* This is a push descriptor set. We have to flag it as used on the GPU
2429 * so that the next time we push descriptors, we grab a new memory.
2430 */
2431 struct anv_push_descriptor_set *push_set =
2432 (struct anv_push_descriptor_set *)set;
2433 push_set->set_used_on_gpu = true;
2434
2435 return (struct anv_address) {
2436 .bo = cmd_buffer->dynamic_state_stream.state_pool->block_pool.bo,
2437 .offset = set->desc_mem.offset,
2438 };
2439 }
2440 }
2441
2442 static VkResult
2443 emit_binding_table(struct anv_cmd_buffer *cmd_buffer,
2444 struct anv_cmd_pipeline_state *pipe_state,
2445 struct anv_shader_bin *shader,
2446 struct anv_state *bt_state)
2447 {
2448 struct anv_subpass *subpass = cmd_buffer->state.subpass;
2449 uint32_t state_offset;
2450
2451 struct anv_pipeline_bind_map *map = &shader->bind_map;
2452 if (map->surface_count == 0) {
2453 *bt_state = (struct anv_state) { 0, };
2454 return VK_SUCCESS;
2455 }
2456
2457 *bt_state = anv_cmd_buffer_alloc_binding_table(cmd_buffer,
2458 map->surface_count,
2459 &state_offset);
2460 uint32_t *bt_map = bt_state->map;
2461
2462 if (bt_state->map == NULL)
2463 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2464
2465 /* We only need to emit relocs if we're not using softpin. If we are using
2466 * softpin then we always keep all user-allocated memory objects resident.
2467 */
2468 const bool need_client_mem_relocs =
2469 !cmd_buffer->device->physical->use_softpin;
2470
2471 for (uint32_t s = 0; s < map->surface_count; s++) {
2472 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[s];
2473
2474 struct anv_state surface_state;
2475
2476 switch (binding->set) {
2477 case ANV_DESCRIPTOR_SET_NULL:
2478 bt_map[s] = 0;
2479 break;
2480
2481 case ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS:
2482 /* Color attachment binding */
2483 assert(shader->stage == MESA_SHADER_FRAGMENT);
2484 if (binding->index < subpass->color_count) {
2485 const unsigned att =
2486 subpass->color_attachments[binding->index].attachment;
2487
2488 /* From the Vulkan 1.0.46 spec:
2489 *
2490 * "If any color or depth/stencil attachments are
2491 * VK_ATTACHMENT_UNUSED, then no writes occur for those
2492 * attachments."
2493 */
2494 if (att == VK_ATTACHMENT_UNUSED) {
2495 surface_state = cmd_buffer->state.null_surface_state;
2496 } else {
2497 surface_state = cmd_buffer->state.attachments[att].color.state;
2498 }
2499 } else {
2500 surface_state = cmd_buffer->state.null_surface_state;
2501 }
2502
2503 assert(surface_state.map);
2504 bt_map[s] = surface_state.offset + state_offset;
2505 break;
2506
2507 case ANV_DESCRIPTOR_SET_SHADER_CONSTANTS: {
2508 struct anv_state surface_state =
2509 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2510
2511 struct anv_address constant_data = {
2512 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2513 .offset = shader->constant_data.offset,
2514 };
2515 unsigned constant_data_size = shader->constant_data_size;
2516
2517 const enum isl_format format =
2518 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2519 anv_fill_buffer_surface_state(cmd_buffer->device,
2520 surface_state, format,
2521 constant_data, constant_data_size, 1);
2522
2523 assert(surface_state.map);
2524 bt_map[s] = surface_state.offset + state_offset;
2525 add_surface_reloc(cmd_buffer, surface_state, constant_data);
2526 break;
2527 }
2528
2529 case ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS: {
2530 /* This is always the first binding for compute shaders */
2531 assert(shader->stage == MESA_SHADER_COMPUTE && s == 0);
2532
2533 struct anv_state surface_state =
2534 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2535
2536 const enum isl_format format =
2537 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2538 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2539 format,
2540 cmd_buffer->state.compute.num_workgroups,
2541 12, 1);
2542
2543 assert(surface_state.map);
2544 bt_map[s] = surface_state.offset + state_offset;
2545 if (need_client_mem_relocs) {
2546 add_surface_reloc(cmd_buffer, surface_state,
2547 cmd_buffer->state.compute.num_workgroups);
2548 }
2549 break;
2550 }
2551
2552 case ANV_DESCRIPTOR_SET_DESCRIPTORS: {
2553 /* This is a descriptor set buffer so the set index is actually
2554 * given by binding->binding. (Yes, that's confusing.)
2555 */
2556 struct anv_descriptor_set *set =
2557 pipe_state->descriptors[binding->index];
2558 assert(set->desc_mem.alloc_size);
2559 assert(set->desc_surface_state.alloc_size);
2560 bt_map[s] = set->desc_surface_state.offset + state_offset;
2561 add_surface_reloc(cmd_buffer, set->desc_surface_state,
2562 anv_descriptor_set_address(cmd_buffer, set));
2563 break;
2564 }
2565
2566 default: {
2567 assert(binding->set < MAX_SETS);
2568 const struct anv_descriptor *desc =
2569 &pipe_state->descriptors[binding->set]->descriptors[binding->index];
2570
2571 switch (desc->type) {
2572 case VK_DESCRIPTOR_TYPE_SAMPLER:
2573 /* Nothing for us to do here */
2574 continue;
2575
2576 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2577 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
2578 if (desc->image_view) {
2579 struct anv_surface_state sstate =
2580 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2581 desc->image_view->planes[binding->plane].general_sampler_surface_state :
2582 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2583 surface_state = sstate.state;
2584 assert(surface_state.alloc_size);
2585 if (need_client_mem_relocs)
2586 add_surface_state_relocs(cmd_buffer, sstate);
2587 } else {
2588 surface_state = cmd_buffer->device->null_surface_state;
2589 }
2590 break;
2591 }
2592 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2593 assert(shader->stage == MESA_SHADER_FRAGMENT);
2594 assert(desc->image_view != NULL);
2595 if ((desc->image_view->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) == 0) {
2596 /* For depth and stencil input attachments, we treat it like any
2597 * old texture that a user may have bound.
2598 */
2599 assert(desc->image_view->n_planes == 1);
2600 struct anv_surface_state sstate =
2601 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2602 desc->image_view->planes[0].general_sampler_surface_state :
2603 desc->image_view->planes[0].optimal_sampler_surface_state;
2604 surface_state = sstate.state;
2605 assert(surface_state.alloc_size);
2606 if (need_client_mem_relocs)
2607 add_surface_state_relocs(cmd_buffer, sstate);
2608 } else {
2609 /* For color input attachments, we create the surface state at
2610 * vkBeginRenderPass time so that we can include aux and clear
2611 * color information.
2612 */
2613 assert(binding->input_attachment_index < subpass->input_count);
2614 const unsigned subpass_att = binding->input_attachment_index;
2615 const unsigned att = subpass->input_attachments[subpass_att].attachment;
2616 surface_state = cmd_buffer->state.attachments[att].input.state;
2617 }
2618 break;
2619
2620 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
2621 if (desc->image_view) {
2622 struct anv_surface_state sstate = (binding->write_only)
2623 ? desc->image_view->planes[binding->plane].writeonly_storage_surface_state
2624 : desc->image_view->planes[binding->plane].storage_surface_state;
2625 surface_state = sstate.state;
2626 assert(surface_state.alloc_size);
2627 if (need_client_mem_relocs)
2628 add_surface_state_relocs(cmd_buffer, sstate);
2629 } else {
2630 surface_state = cmd_buffer->device->null_surface_state;
2631 }
2632 break;
2633 }
2634
2635 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2636 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2637 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2638 if (desc->buffer_view) {
2639 surface_state = desc->buffer_view->surface_state;
2640 assert(surface_state.alloc_size);
2641 if (need_client_mem_relocs) {
2642 add_surface_reloc(cmd_buffer, surface_state,
2643 desc->buffer_view->address);
2644 }
2645 } else {
2646 surface_state = cmd_buffer->device->null_surface_state;
2647 }
2648 break;
2649
2650 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2651 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
2652 if (desc->buffer) {
2653 /* Compute the offset within the buffer */
2654 struct anv_push_constants *push =
2655 &cmd_buffer->state.push_constants[shader->stage];
2656
2657 uint32_t dynamic_offset =
2658 push->dynamic_offsets[binding->dynamic_offset_index];
2659 uint64_t offset = desc->offset + dynamic_offset;
2660 /* Clamp to the buffer size */
2661 offset = MIN2(offset, desc->buffer->size);
2662 /* Clamp the range to the buffer size */
2663 uint32_t range = MIN2(desc->range, desc->buffer->size - offset);
2664
2665 /* Align the range for consistency */
2666 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC)
2667 range = align_u32(range, ANV_UBO_ALIGNMENT);
2668
2669 struct anv_address address =
2670 anv_address_add(desc->buffer->address, offset);
2671
2672 surface_state =
2673 anv_state_stream_alloc(&cmd_buffer->surface_state_stream, 64, 64);
2674 enum isl_format format =
2675 anv_isl_format_for_descriptor_type(desc->type);
2676
2677 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2678 format, address, range, 1);
2679 if (need_client_mem_relocs)
2680 add_surface_reloc(cmd_buffer, surface_state, address);
2681 } else {
2682 surface_state = cmd_buffer->device->null_surface_state;
2683 }
2684 break;
2685 }
2686
2687 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2688 if (desc->buffer_view) {
2689 surface_state = (binding->write_only)
2690 ? desc->buffer_view->writeonly_storage_surface_state
2691 : desc->buffer_view->storage_surface_state;
2692 assert(surface_state.alloc_size);
2693 if (need_client_mem_relocs) {
2694 add_surface_reloc(cmd_buffer, surface_state,
2695 desc->buffer_view->address);
2696 }
2697 } else {
2698 surface_state = cmd_buffer->device->null_surface_state;
2699 }
2700 break;
2701
2702 default:
2703 assert(!"Invalid descriptor type");
2704 continue;
2705 }
2706 assert(surface_state.map);
2707 bt_map[s] = surface_state.offset + state_offset;
2708 break;
2709 }
2710 }
2711 }
2712
2713 return VK_SUCCESS;
2714 }
2715
2716 static VkResult
2717 emit_samplers(struct anv_cmd_buffer *cmd_buffer,
2718 struct anv_cmd_pipeline_state *pipe_state,
2719 struct anv_shader_bin *shader,
2720 struct anv_state *state)
2721 {
2722 struct anv_pipeline_bind_map *map = &shader->bind_map;
2723 if (map->sampler_count == 0) {
2724 *state = (struct anv_state) { 0, };
2725 return VK_SUCCESS;
2726 }
2727
2728 uint32_t size = map->sampler_count * 16;
2729 *state = anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, size, 32);
2730
2731 if (state->map == NULL)
2732 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2733
2734 for (uint32_t s = 0; s < map->sampler_count; s++) {
2735 struct anv_pipeline_binding *binding = &map->sampler_to_descriptor[s];
2736 const struct anv_descriptor *desc =
2737 &pipe_state->descriptors[binding->set]->descriptors[binding->index];
2738
2739 if (desc->type != VK_DESCRIPTOR_TYPE_SAMPLER &&
2740 desc->type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
2741 continue;
2742
2743 struct anv_sampler *sampler = desc->sampler;
2744
2745 /* This can happen if we have an unfilled slot since TYPE_SAMPLER
2746 * happens to be zero.
2747 */
2748 if (sampler == NULL)
2749 continue;
2750
2751 memcpy(state->map + (s * 16),
2752 sampler->state[binding->plane], sizeof(sampler->state[0]));
2753 }
2754
2755 return VK_SUCCESS;
2756 }
2757
2758 static uint32_t
2759 flush_descriptor_sets(struct anv_cmd_buffer *cmd_buffer,
2760 struct anv_cmd_pipeline_state *pipe_state,
2761 struct anv_shader_bin **shaders,
2762 uint32_t num_shaders)
2763 {
2764 const VkShaderStageFlags dirty = cmd_buffer->state.descriptors_dirty;
2765 VkShaderStageFlags flushed = 0;
2766
2767 VkResult result = VK_SUCCESS;
2768 for (uint32_t i = 0; i < num_shaders; i++) {
2769 if (!shaders[i])
2770 continue;
2771
2772 gl_shader_stage stage = shaders[i]->stage;
2773 VkShaderStageFlags vk_stage = mesa_to_vk_shader_stage(stage);
2774 if ((vk_stage & dirty) == 0)
2775 continue;
2776
2777 result = emit_samplers(cmd_buffer, pipe_state, shaders[i],
2778 &cmd_buffer->state.samplers[stage]);
2779 if (result != VK_SUCCESS)
2780 break;
2781 result = emit_binding_table(cmd_buffer, pipe_state, shaders[i],
2782 &cmd_buffer->state.binding_tables[stage]);
2783 if (result != VK_SUCCESS)
2784 break;
2785
2786 flushed |= vk_stage;
2787 }
2788
2789 if (result != VK_SUCCESS) {
2790 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2791
2792 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2793 if (result != VK_SUCCESS)
2794 return 0;
2795
2796 /* Re-emit state base addresses so we get the new surface state base
2797 * address before we start emitting binding tables etc.
2798 */
2799 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2800
2801 /* Re-emit all active binding tables */
2802 flushed = 0;
2803
2804 for (uint32_t i = 0; i < num_shaders; i++) {
2805 if (!shaders[i])
2806 continue;
2807
2808 gl_shader_stage stage = shaders[i]->stage;
2809
2810 result = emit_samplers(cmd_buffer, pipe_state, shaders[i],
2811 &cmd_buffer->state.samplers[stage]);
2812 if (result != VK_SUCCESS) {
2813 anv_batch_set_error(&cmd_buffer->batch, result);
2814 return 0;
2815 }
2816 result = emit_binding_table(cmd_buffer, pipe_state, shaders[i],
2817 &cmd_buffer->state.binding_tables[stage]);
2818 if (result != VK_SUCCESS) {
2819 anv_batch_set_error(&cmd_buffer->batch, result);
2820 return 0;
2821 }
2822
2823 flushed |= mesa_to_vk_shader_stage(stage);
2824 }
2825 }
2826
2827 cmd_buffer->state.descriptors_dirty &= ~flushed;
2828
2829 return flushed;
2830 }
2831
2832 static void
2833 cmd_buffer_emit_descriptor_pointers(struct anv_cmd_buffer *cmd_buffer,
2834 uint32_t stages)
2835 {
2836 static const uint32_t sampler_state_opcodes[] = {
2837 [MESA_SHADER_VERTEX] = 43,
2838 [MESA_SHADER_TESS_CTRL] = 44, /* HS */
2839 [MESA_SHADER_TESS_EVAL] = 45, /* DS */
2840 [MESA_SHADER_GEOMETRY] = 46,
2841 [MESA_SHADER_FRAGMENT] = 47,
2842 [MESA_SHADER_COMPUTE] = 0,
2843 };
2844
2845 static const uint32_t binding_table_opcodes[] = {
2846 [MESA_SHADER_VERTEX] = 38,
2847 [MESA_SHADER_TESS_CTRL] = 39,
2848 [MESA_SHADER_TESS_EVAL] = 40,
2849 [MESA_SHADER_GEOMETRY] = 41,
2850 [MESA_SHADER_FRAGMENT] = 42,
2851 [MESA_SHADER_COMPUTE] = 0,
2852 };
2853
2854 anv_foreach_stage(s, stages) {
2855 assert(s < ARRAY_SIZE(binding_table_opcodes));
2856 assert(binding_table_opcodes[s] > 0);
2857
2858 if (cmd_buffer->state.samplers[s].alloc_size > 0) {
2859 anv_batch_emit(&cmd_buffer->batch,
2860 GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ssp) {
2861 ssp._3DCommandSubOpcode = sampler_state_opcodes[s];
2862 ssp.PointertoVSSamplerState = cmd_buffer->state.samplers[s].offset;
2863 }
2864 }
2865
2866 /* Always emit binding table pointers if we're asked to, since on SKL
2867 * this is what flushes push constants. */
2868 anv_batch_emit(&cmd_buffer->batch,
2869 GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), btp) {
2870 btp._3DCommandSubOpcode = binding_table_opcodes[s];
2871 btp.PointertoVSBindingTable = cmd_buffer->state.binding_tables[s].offset;
2872 }
2873 }
2874 }
2875
2876 static struct anv_address
2877 get_push_range_address(struct anv_cmd_buffer *cmd_buffer,
2878 gl_shader_stage stage,
2879 const struct anv_push_range *range)
2880 {
2881 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2882 switch (range->set) {
2883 case ANV_DESCRIPTOR_SET_DESCRIPTORS: {
2884 /* This is a descriptor set buffer so the set index is
2885 * actually given by binding->binding. (Yes, that's
2886 * confusing.)
2887 */
2888 struct anv_descriptor_set *set =
2889 gfx_state->base.descriptors[range->index];
2890 return anv_descriptor_set_address(cmd_buffer, set);
2891 }
2892
2893 case ANV_DESCRIPTOR_SET_PUSH_CONSTANTS: {
2894 struct anv_state state =
2895 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2896 return (struct anv_address) {
2897 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2898 .offset = state.offset,
2899 };
2900 }
2901
2902 default: {
2903 assert(range->set < MAX_SETS);
2904 struct anv_descriptor_set *set =
2905 gfx_state->base.descriptors[range->set];
2906 const struct anv_descriptor *desc =
2907 &set->descriptors[range->index];
2908
2909 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2910 if (desc->buffer_view)
2911 return desc->buffer_view->address;
2912 } else {
2913 assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2914 if (desc->buffer) {
2915 struct anv_push_constants *push =
2916 &cmd_buffer->state.push_constants[stage];
2917 uint32_t dynamic_offset =
2918 push->dynamic_offsets[range->dynamic_offset_index];
2919 return anv_address_add(desc->buffer->address,
2920 desc->offset + dynamic_offset);
2921 }
2922 }
2923
2924 /* For NULL UBOs, we just return an address in the workaround BO. We do
2925 * writes to it for workarounds but always at the bottom. The higher
2926 * bytes should be all zeros.
2927 */
2928 assert(range->length * 32 <= 2048);
2929 return (struct anv_address) {
2930 .bo = cmd_buffer->device->workaround_bo,
2931 .offset = 1024,
2932 };
2933 }
2934 }
2935 }
2936
2937
2938 /** Returns the size in bytes of the bound buffer
2939 *
2940 * The range is relative to the start of the buffer, not the start of the
2941 * range. The returned range may be smaller than
2942 *
2943 * (range->start + range->length) * 32;
2944 */
2945 static uint32_t
2946 get_push_range_bound_size(struct anv_cmd_buffer *cmd_buffer,
2947 gl_shader_stage stage,
2948 const struct anv_push_range *range)
2949 {
2950 assert(stage != MESA_SHADER_COMPUTE);
2951 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2952 switch (range->set) {
2953 case ANV_DESCRIPTOR_SET_DESCRIPTORS: {
2954 struct anv_descriptor_set *set =
2955 gfx_state->base.descriptors[range->index];
2956 assert(range->start * 32 < set->desc_mem.alloc_size);
2957 assert((range->start + range->length) * 32 <= set->desc_mem.alloc_size);
2958 return set->desc_mem.alloc_size;
2959 }
2960
2961 case ANV_DESCRIPTOR_SET_PUSH_CONSTANTS:
2962 return (range->start + range->length) * 32;
2963
2964 default: {
2965 assert(range->set < MAX_SETS);
2966 struct anv_descriptor_set *set =
2967 gfx_state->base.descriptors[range->set];
2968 const struct anv_descriptor *desc =
2969 &set->descriptors[range->index];
2970
2971 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2972 if (!desc->buffer_view)
2973 return 0;
2974
2975 if (range->start * 32 > desc->buffer_view->range)
2976 return 0;
2977
2978 return desc->buffer_view->range;
2979 } else {
2980 if (!desc->buffer)
2981 return 0;
2982
2983 assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2984 /* Compute the offset within the buffer */
2985 struct anv_push_constants *push =
2986 &cmd_buffer->state.push_constants[stage];
2987 uint32_t dynamic_offset =
2988 push->dynamic_offsets[range->dynamic_offset_index];
2989 uint64_t offset = desc->offset + dynamic_offset;
2990 /* Clamp to the buffer size */
2991 offset = MIN2(offset, desc->buffer->size);
2992 /* Clamp the range to the buffer size */
2993 uint32_t bound_range = MIN2(desc->range, desc->buffer->size - offset);
2994
2995 /* Align the range for consistency */
2996 bound_range = align_u32(bound_range, ANV_UBO_ALIGNMENT);
2997
2998 return bound_range;
2999 }
3000 }
3001 }
3002 }
3003
3004 static void
3005 cmd_buffer_emit_push_constant(struct anv_cmd_buffer *cmd_buffer,
3006 gl_shader_stage stage,
3007 struct anv_address *buffers,
3008 unsigned buffer_count)
3009 {
3010 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
3011 const struct anv_graphics_pipeline *pipeline = gfx_state->pipeline;
3012
3013 static const uint32_t push_constant_opcodes[] = {
3014 [MESA_SHADER_VERTEX] = 21,
3015 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
3016 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
3017 [MESA_SHADER_GEOMETRY] = 22,
3018 [MESA_SHADER_FRAGMENT] = 23,
3019 [MESA_SHADER_COMPUTE] = 0,
3020 };
3021
3022 assert(stage < ARRAY_SIZE(push_constant_opcodes));
3023 assert(push_constant_opcodes[stage] > 0);
3024
3025 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_VS), c) {
3026 c._3DCommandSubOpcode = push_constant_opcodes[stage];
3027
3028 if (anv_pipeline_has_stage(pipeline, stage)) {
3029 const struct anv_pipeline_bind_map *bind_map =
3030 &pipeline->shaders[stage]->bind_map;
3031
3032 #if GEN_GEN >= 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</