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