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