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