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