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