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