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