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