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