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