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