anv,iris: L3ALLOC register replaces L3CNTLREG for gen12
[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 UNUSED 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 #if GEN_GEN >= 12
1678 #define L3_ALLOCATION_REG GENX(L3ALLOC)
1679 #define L3_ALLOCATION_REG_num GENX(L3ALLOC_num)
1680 #else
1681 #define L3_ALLOCATION_REG GENX(L3CNTLREG)
1682 #define L3_ALLOCATION_REG_num GENX(L3CNTLREG_num)
1683 #endif
1684
1685 uint32_t l3cr;
1686 anv_pack_struct(&l3cr, L3_ALLOCATION_REG,
1687 #if GEN_GEN < 12
1688 .SLMEnable = has_slm,
1689 #endif
1690 #if GEN_GEN == 11
1691 /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
1692 * in L3CNTLREG register. The default setting of the bit is not the
1693 * desirable behavior.
1694 */
1695 .ErrorDetectionBehaviorControl = true,
1696 .UseFullWays = true,
1697 #endif
1698 .URBAllocation = cfg->n[GEN_L3P_URB],
1699 .ROAllocation = cfg->n[GEN_L3P_RO],
1700 .DCAllocation = cfg->n[GEN_L3P_DC],
1701 .AllAllocation = cfg->n[GEN_L3P_ALL]);
1702
1703 /* Set up the L3 partitioning. */
1704 emit_lri(&cmd_buffer->batch, L3_ALLOCATION_REG_num, l3cr);
1705
1706 #else
1707
1708 const bool has_dc = cfg->n[GEN_L3P_DC] || cfg->n[GEN_L3P_ALL];
1709 const bool has_is = cfg->n[GEN_L3P_IS] || cfg->n[GEN_L3P_RO] ||
1710 cfg->n[GEN_L3P_ALL];
1711 const bool has_c = cfg->n[GEN_L3P_C] || cfg->n[GEN_L3P_RO] ||
1712 cfg->n[GEN_L3P_ALL];
1713 const bool has_t = cfg->n[GEN_L3P_T] || cfg->n[GEN_L3P_RO] ||
1714 cfg->n[GEN_L3P_ALL];
1715
1716 assert(!cfg->n[GEN_L3P_ALL]);
1717
1718 /* When enabled SLM only uses a portion of the L3 on half of the banks,
1719 * the matching space on the remaining banks has to be allocated to a
1720 * client (URB for all validated configurations) set to the
1721 * lower-bandwidth 2-bank address hashing mode.
1722 */
1723 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1724 const bool urb_low_bw = has_slm && !devinfo->is_baytrail;
1725 assert(!urb_low_bw || cfg->n[GEN_L3P_URB] == cfg->n[GEN_L3P_SLM]);
1726
1727 /* Minimum number of ways that can be allocated to the URB. */
1728 const unsigned n0_urb = devinfo->is_baytrail ? 32 : 0;
1729 assert(cfg->n[GEN_L3P_URB] >= n0_urb);
1730
1731 uint32_t l3sqcr1, l3cr2, l3cr3;
1732 anv_pack_struct(&l3sqcr1, GENX(L3SQCREG1),
1733 .ConvertDC_UC = !has_dc,
1734 .ConvertIS_UC = !has_is,
1735 .ConvertC_UC = !has_c,
1736 .ConvertT_UC = !has_t);
1737 l3sqcr1 |=
1738 GEN_IS_HASWELL ? HSW_L3SQCREG1_SQGHPCI_DEFAULT :
1739 devinfo->is_baytrail ? VLV_L3SQCREG1_SQGHPCI_DEFAULT :
1740 IVB_L3SQCREG1_SQGHPCI_DEFAULT;
1741
1742 anv_pack_struct(&l3cr2, GENX(L3CNTLREG2),
1743 .SLMEnable = has_slm,
1744 .URBLowBandwidth = urb_low_bw,
1745 .URBAllocation = cfg->n[GEN_L3P_URB] - n0_urb,
1746 #if !GEN_IS_HASWELL
1747 .ALLAllocation = cfg->n[GEN_L3P_ALL],
1748 #endif
1749 .ROAllocation = cfg->n[GEN_L3P_RO],
1750 .DCAllocation = cfg->n[GEN_L3P_DC]);
1751
1752 anv_pack_struct(&l3cr3, GENX(L3CNTLREG3),
1753 .ISAllocation = cfg->n[GEN_L3P_IS],
1754 .ISLowBandwidth = 0,
1755 .CAllocation = cfg->n[GEN_L3P_C],
1756 .CLowBandwidth = 0,
1757 .TAllocation = cfg->n[GEN_L3P_T],
1758 .TLowBandwidth = 0);
1759
1760 /* Set up the L3 partitioning. */
1761 emit_lri(&cmd_buffer->batch, GENX(L3SQCREG1_num), l3sqcr1);
1762 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG2_num), l3cr2);
1763 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG3_num), l3cr3);
1764
1765 #if GEN_IS_HASWELL
1766 if (cmd_buffer->device->instance->physicalDevice.cmd_parser_version >= 4) {
1767 /* Enable L3 atomics on HSW if we have a DC partition, otherwise keep
1768 * them disabled to avoid crashing the system hard.
1769 */
1770 uint32_t scratch1, chicken3;
1771 anv_pack_struct(&scratch1, GENX(SCRATCH1),
1772 .L3AtomicDisable = !has_dc);
1773 anv_pack_struct(&chicken3, GENX(CHICKEN3),
1774 .L3AtomicDisableMask = true,
1775 .L3AtomicDisable = !has_dc);
1776 emit_lri(&cmd_buffer->batch, GENX(SCRATCH1_num), scratch1);
1777 emit_lri(&cmd_buffer->batch, GENX(CHICKEN3_num), chicken3);
1778 }
1779 #endif
1780
1781 #endif
1782
1783 cmd_buffer->state.current_l3_config = cfg;
1784 }
1785
1786 void
1787 genX(cmd_buffer_apply_pipe_flushes)(struct anv_cmd_buffer *cmd_buffer)
1788 {
1789 enum anv_pipe_bits bits = cmd_buffer->state.pending_pipe_bits;
1790
1791 /* Flushes are pipelined while invalidations are handled immediately.
1792 * Therefore, if we're flushing anything then we need to schedule a stall
1793 * before any invalidations can happen.
1794 */
1795 if (bits & ANV_PIPE_FLUSH_BITS)
1796 bits |= ANV_PIPE_NEEDS_CS_STALL_BIT;
1797
1798 /* If we're going to do an invalidate and we have a pending CS stall that
1799 * has yet to be resolved, we do the CS stall now.
1800 */
1801 if ((bits & ANV_PIPE_INVALIDATE_BITS) &&
1802 (bits & ANV_PIPE_NEEDS_CS_STALL_BIT)) {
1803 bits |= ANV_PIPE_CS_STALL_BIT;
1804 bits &= ~ANV_PIPE_NEEDS_CS_STALL_BIT;
1805 }
1806
1807 if (bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT)) {
1808 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1809 pipe.DepthCacheFlushEnable = bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1810 pipe.DCFlushEnable = bits & ANV_PIPE_DATA_CACHE_FLUSH_BIT;
1811 pipe.RenderTargetCacheFlushEnable =
1812 bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1813
1814 pipe.DepthStallEnable = bits & ANV_PIPE_DEPTH_STALL_BIT;
1815 pipe.CommandStreamerStallEnable = bits & ANV_PIPE_CS_STALL_BIT;
1816 pipe.StallAtPixelScoreboard = bits & ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
1817
1818 /*
1819 * According to the Broadwell documentation, any PIPE_CONTROL with the
1820 * "Command Streamer Stall" bit set must also have another bit set,
1821 * with five different options:
1822 *
1823 * - Render Target Cache Flush
1824 * - Depth Cache Flush
1825 * - Stall at Pixel Scoreboard
1826 * - Post-Sync Operation
1827 * - Depth Stall
1828 * - DC Flush Enable
1829 *
1830 * I chose "Stall at Pixel Scoreboard" since that's what we use in
1831 * mesa and it seems to work fine. The choice is fairly arbitrary.
1832 */
1833 if ((bits & ANV_PIPE_CS_STALL_BIT) &&
1834 !(bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_DEPTH_STALL_BIT |
1835 ANV_PIPE_STALL_AT_SCOREBOARD_BIT)))
1836 pipe.StallAtPixelScoreboard = true;
1837 }
1838
1839 /* If a render target flush was emitted, then we can toggle off the bit
1840 * saying that render target writes are ongoing.
1841 */
1842 if (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
1843 bits &= ~(ANV_PIPE_RENDER_TARGET_BUFFER_WRITES);
1844
1845 bits &= ~(ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT);
1846 }
1847
1848 if (bits & ANV_PIPE_INVALIDATE_BITS) {
1849 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1850 *
1851 * "If the VF Cache Invalidation Enable is set to a 1 in a
1852 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields sets to
1853 * 0, with the VF Cache Invalidation Enable set to 0 needs to be sent
1854 * prior to the PIPE_CONTROL with VF Cache Invalidation Enable set to
1855 * a 1."
1856 *
1857 * This appears to hang Broadwell, so we restrict it to just gen9.
1858 */
1859 if (GEN_GEN == 9 && (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT))
1860 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe);
1861
1862 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1863 pipe.StateCacheInvalidationEnable =
1864 bits & ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
1865 pipe.ConstantCacheInvalidationEnable =
1866 bits & ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
1867 pipe.VFCacheInvalidationEnable =
1868 bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1869 pipe.TextureCacheInvalidationEnable =
1870 bits & ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1871 pipe.InstructionCacheInvalidateEnable =
1872 bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT;
1873
1874 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1875 *
1876 * "When VF Cache Invalidate is set “Post Sync Operation” must be
1877 * enabled to “Write Immediate Data” or “Write PS Depth Count” or
1878 * “Write Timestamp”.
1879 */
1880 if (GEN_GEN == 9 && pipe.VFCacheInvalidationEnable) {
1881 pipe.PostSyncOperation = WriteImmediateData;
1882 pipe.Address =
1883 (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
1884 }
1885 }
1886
1887 bits &= ~ANV_PIPE_INVALIDATE_BITS;
1888 }
1889
1890 cmd_buffer->state.pending_pipe_bits = bits;
1891 }
1892
1893 void genX(CmdPipelineBarrier)(
1894 VkCommandBuffer commandBuffer,
1895 VkPipelineStageFlags srcStageMask,
1896 VkPipelineStageFlags destStageMask,
1897 VkBool32 byRegion,
1898 uint32_t memoryBarrierCount,
1899 const VkMemoryBarrier* pMemoryBarriers,
1900 uint32_t bufferMemoryBarrierCount,
1901 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1902 uint32_t imageMemoryBarrierCount,
1903 const VkImageMemoryBarrier* pImageMemoryBarriers)
1904 {
1905 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1906
1907 /* XXX: Right now, we're really dumb and just flush whatever categories
1908 * the app asks for. One of these days we may make this a bit better
1909 * but right now that's all the hardware allows for in most areas.
1910 */
1911 VkAccessFlags src_flags = 0;
1912 VkAccessFlags dst_flags = 0;
1913
1914 for (uint32_t i = 0; i < memoryBarrierCount; i++) {
1915 src_flags |= pMemoryBarriers[i].srcAccessMask;
1916 dst_flags |= pMemoryBarriers[i].dstAccessMask;
1917 }
1918
1919 for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
1920 src_flags |= pBufferMemoryBarriers[i].srcAccessMask;
1921 dst_flags |= pBufferMemoryBarriers[i].dstAccessMask;
1922 }
1923
1924 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1925 src_flags |= pImageMemoryBarriers[i].srcAccessMask;
1926 dst_flags |= pImageMemoryBarriers[i].dstAccessMask;
1927 ANV_FROM_HANDLE(anv_image, image, pImageMemoryBarriers[i].image);
1928 const VkImageSubresourceRange *range =
1929 &pImageMemoryBarriers[i].subresourceRange;
1930
1931 uint32_t base_layer, layer_count;
1932 if (image->type == VK_IMAGE_TYPE_3D) {
1933 base_layer = 0;
1934 layer_count = anv_minify(image->extent.depth, range->baseMipLevel);
1935 } else {
1936 base_layer = range->baseArrayLayer;
1937 layer_count = anv_get_layerCount(image, range);
1938 }
1939
1940 if (range->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1941 transition_depth_buffer(cmd_buffer, image,
1942 pImageMemoryBarriers[i].oldLayout,
1943 pImageMemoryBarriers[i].newLayout);
1944 }
1945
1946 if (range->aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1947 transition_stencil_buffer(cmd_buffer, image,
1948 range->baseMipLevel,
1949 anv_get_levelCount(image, range),
1950 base_layer, layer_count,
1951 pImageMemoryBarriers[i].oldLayout,
1952 pImageMemoryBarriers[i].newLayout);
1953 }
1954
1955 if (range->aspectMask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1956 VkImageAspectFlags color_aspects =
1957 anv_image_expand_aspects(image, range->aspectMask);
1958 uint32_t aspect_bit;
1959 anv_foreach_image_aspect_bit(aspect_bit, image, color_aspects) {
1960 transition_color_buffer(cmd_buffer, image, 1UL << aspect_bit,
1961 range->baseMipLevel,
1962 anv_get_levelCount(image, range),
1963 base_layer, layer_count,
1964 pImageMemoryBarriers[i].oldLayout,
1965 pImageMemoryBarriers[i].newLayout);
1966 }
1967 }
1968 }
1969
1970 cmd_buffer->state.pending_pipe_bits |=
1971 anv_pipe_flush_bits_for_access_flags(src_flags) |
1972 anv_pipe_invalidate_bits_for_access_flags(dst_flags);
1973 }
1974
1975 static void
1976 cmd_buffer_alloc_push_constants(struct anv_cmd_buffer *cmd_buffer)
1977 {
1978 VkShaderStageFlags stages =
1979 cmd_buffer->state.gfx.base.pipeline->active_stages;
1980
1981 /* In order to avoid thrash, we assume that vertex and fragment stages
1982 * always exist. In the rare case where one is missing *and* the other
1983 * uses push concstants, this may be suboptimal. However, avoiding stalls
1984 * seems more important.
1985 */
1986 stages |= VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT;
1987
1988 if (stages == cmd_buffer->state.push_constant_stages)
1989 return;
1990
1991 #if GEN_GEN >= 8
1992 const unsigned push_constant_kb = 32;
1993 #elif GEN_IS_HASWELL
1994 const unsigned push_constant_kb = cmd_buffer->device->info.gt == 3 ? 32 : 16;
1995 #else
1996 const unsigned push_constant_kb = 16;
1997 #endif
1998
1999 const unsigned num_stages =
2000 util_bitcount(stages & VK_SHADER_STAGE_ALL_GRAPHICS);
2001 unsigned size_per_stage = push_constant_kb / num_stages;
2002
2003 /* Broadwell+ and Haswell gt3 require that the push constant sizes be in
2004 * units of 2KB. Incidentally, these are the same platforms that have
2005 * 32KB worth of push constant space.
2006 */
2007 if (push_constant_kb == 32)
2008 size_per_stage &= ~1u;
2009
2010 uint32_t kb_used = 0;
2011 for (int i = MESA_SHADER_VERTEX; i < MESA_SHADER_FRAGMENT; i++) {
2012 unsigned push_size = (stages & (1 << i)) ? size_per_stage : 0;
2013 anv_batch_emit(&cmd_buffer->batch,
2014 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
2015 alloc._3DCommandSubOpcode = 18 + i;
2016 alloc.ConstantBufferOffset = (push_size > 0) ? kb_used : 0;
2017 alloc.ConstantBufferSize = push_size;
2018 }
2019 kb_used += push_size;
2020 }
2021
2022 anv_batch_emit(&cmd_buffer->batch,
2023 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_PS), alloc) {
2024 alloc.ConstantBufferOffset = kb_used;
2025 alloc.ConstantBufferSize = push_constant_kb - kb_used;
2026 }
2027
2028 cmd_buffer->state.push_constant_stages = stages;
2029
2030 /* From the BDW PRM for 3DSTATE_PUSH_CONSTANT_ALLOC_VS:
2031 *
2032 * "The 3DSTATE_CONSTANT_VS must be reprogrammed prior to
2033 * the next 3DPRIMITIVE command after programming the
2034 * 3DSTATE_PUSH_CONSTANT_ALLOC_VS"
2035 *
2036 * Since 3DSTATE_PUSH_CONSTANT_ALLOC_VS is programmed as part of
2037 * pipeline setup, we need to dirty push constants.
2038 */
2039 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
2040 }
2041
2042 static const struct anv_descriptor *
2043 anv_descriptor_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
2044 const struct anv_pipeline_binding *binding)
2045 {
2046 assert(binding->set < MAX_SETS);
2047 const struct anv_descriptor_set *set =
2048 pipe_state->descriptors[binding->set];
2049 const uint32_t offset =
2050 set->layout->binding[binding->binding].descriptor_index;
2051 return &set->descriptors[offset + binding->index];
2052 }
2053
2054 static uint32_t
2055 dynamic_offset_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
2056 const struct anv_pipeline_binding *binding)
2057 {
2058 assert(binding->set < MAX_SETS);
2059 const struct anv_descriptor_set *set =
2060 pipe_state->descriptors[binding->set];
2061
2062 uint32_t dynamic_offset_idx =
2063 pipe_state->layout->set[binding->set].dynamic_offset_start +
2064 set->layout->binding[binding->binding].dynamic_offset_index +
2065 binding->index;
2066
2067 return pipe_state->dynamic_offsets[dynamic_offset_idx];
2068 }
2069
2070 static struct anv_address
2071 anv_descriptor_set_address(struct anv_cmd_buffer *cmd_buffer,
2072 struct anv_descriptor_set *set)
2073 {
2074 if (set->pool) {
2075 /* This is a normal descriptor set */
2076 return (struct anv_address) {
2077 .bo = &set->pool->bo,
2078 .offset = set->desc_mem.offset,
2079 };
2080 } else {
2081 /* This is a push descriptor set. We have to flag it as used on the GPU
2082 * so that the next time we push descriptors, we grab a new memory.
2083 */
2084 struct anv_push_descriptor_set *push_set =
2085 (struct anv_push_descriptor_set *)set;
2086 push_set->set_used_on_gpu = true;
2087
2088 return (struct anv_address) {
2089 .bo = cmd_buffer->dynamic_state_stream.state_pool->block_pool.bo,
2090 .offset = set->desc_mem.offset,
2091 };
2092 }
2093 }
2094
2095 static VkResult
2096 emit_binding_table(struct anv_cmd_buffer *cmd_buffer,
2097 gl_shader_stage stage,
2098 struct anv_state *bt_state)
2099 {
2100 struct anv_subpass *subpass = cmd_buffer->state.subpass;
2101 struct anv_cmd_pipeline_state *pipe_state;
2102 struct anv_pipeline *pipeline;
2103 uint32_t state_offset;
2104
2105 switch (stage) {
2106 case MESA_SHADER_COMPUTE:
2107 pipe_state = &cmd_buffer->state.compute.base;
2108 break;
2109 default:
2110 pipe_state = &cmd_buffer->state.gfx.base;
2111 break;
2112 }
2113 pipeline = pipe_state->pipeline;
2114
2115 if (!anv_pipeline_has_stage(pipeline, stage)) {
2116 *bt_state = (struct anv_state) { 0, };
2117 return VK_SUCCESS;
2118 }
2119
2120 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2121 if (map->surface_count == 0) {
2122 *bt_state = (struct anv_state) { 0, };
2123 return VK_SUCCESS;
2124 }
2125
2126 *bt_state = anv_cmd_buffer_alloc_binding_table(cmd_buffer,
2127 map->surface_count,
2128 &state_offset);
2129 uint32_t *bt_map = bt_state->map;
2130
2131 if (bt_state->map == NULL)
2132 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2133
2134 /* We only need to emit relocs if we're not using softpin. If we are using
2135 * softpin then we always keep all user-allocated memory objects resident.
2136 */
2137 const bool need_client_mem_relocs =
2138 !cmd_buffer->device->instance->physicalDevice.use_softpin;
2139
2140 for (uint32_t s = 0; s < map->surface_count; s++) {
2141 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[s];
2142
2143 struct anv_state surface_state;
2144
2145 if (binding->set == ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS) {
2146 /* Color attachment binding */
2147 assert(stage == MESA_SHADER_FRAGMENT);
2148 assert(binding->binding == 0);
2149 if (binding->index < subpass->color_count) {
2150 const unsigned att =
2151 subpass->color_attachments[binding->index].attachment;
2152
2153 /* From the Vulkan 1.0.46 spec:
2154 *
2155 * "If any color or depth/stencil attachments are
2156 * VK_ATTACHMENT_UNUSED, then no writes occur for those
2157 * attachments."
2158 */
2159 if (att == VK_ATTACHMENT_UNUSED) {
2160 surface_state = cmd_buffer->state.null_surface_state;
2161 } else {
2162 surface_state = cmd_buffer->state.attachments[att].color.state;
2163 }
2164 } else {
2165 surface_state = cmd_buffer->state.null_surface_state;
2166 }
2167
2168 bt_map[s] = surface_state.offset + state_offset;
2169 continue;
2170 } else if (binding->set == ANV_DESCRIPTOR_SET_SHADER_CONSTANTS) {
2171 struct anv_state surface_state =
2172 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2173
2174 struct anv_address constant_data = {
2175 .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2176 .offset = pipeline->shaders[stage]->constant_data.offset,
2177 };
2178 unsigned constant_data_size =
2179 pipeline->shaders[stage]->constant_data_size;
2180
2181 const enum isl_format format =
2182 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2183 anv_fill_buffer_surface_state(cmd_buffer->device,
2184 surface_state, format,
2185 constant_data, constant_data_size, 1);
2186
2187 bt_map[s] = surface_state.offset + state_offset;
2188 add_surface_reloc(cmd_buffer, surface_state, constant_data);
2189 continue;
2190 } else if (binding->set == ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS) {
2191 /* This is always the first binding for compute shaders */
2192 assert(stage == MESA_SHADER_COMPUTE && s == 0);
2193 if (!get_cs_prog_data(pipeline)->uses_num_work_groups)
2194 continue;
2195
2196 struct anv_state surface_state =
2197 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2198
2199 const enum isl_format format =
2200 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2201 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2202 format,
2203 cmd_buffer->state.compute.num_workgroups,
2204 12, 1);
2205 bt_map[s] = surface_state.offset + state_offset;
2206 if (need_client_mem_relocs) {
2207 add_surface_reloc(cmd_buffer, surface_state,
2208 cmd_buffer->state.compute.num_workgroups);
2209 }
2210 continue;
2211 } else if (binding->set == ANV_DESCRIPTOR_SET_DESCRIPTORS) {
2212 /* This is a descriptor set buffer so the set index is actually
2213 * given by binding->binding. (Yes, that's confusing.)
2214 */
2215 struct anv_descriptor_set *set =
2216 pipe_state->descriptors[binding->binding];
2217 assert(set->desc_mem.alloc_size);
2218 assert(set->desc_surface_state.alloc_size);
2219 bt_map[s] = set->desc_surface_state.offset + state_offset;
2220 add_surface_reloc(cmd_buffer, set->desc_surface_state,
2221 anv_descriptor_set_address(cmd_buffer, set));
2222 continue;
2223 }
2224
2225 const struct anv_descriptor *desc =
2226 anv_descriptor_for_binding(pipe_state, binding);
2227
2228 switch (desc->type) {
2229 case VK_DESCRIPTOR_TYPE_SAMPLER:
2230 /* Nothing for us to do here */
2231 continue;
2232
2233 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2234 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
2235 struct anv_surface_state sstate =
2236 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2237 desc->image_view->planes[binding->plane].general_sampler_surface_state :
2238 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2239 surface_state = sstate.state;
2240 assert(surface_state.alloc_size);
2241 if (need_client_mem_relocs)
2242 add_surface_state_relocs(cmd_buffer, sstate);
2243 break;
2244 }
2245 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2246 assert(stage == MESA_SHADER_FRAGMENT);
2247 if ((desc->image_view->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) == 0) {
2248 /* For depth and stencil input attachments, we treat it like any
2249 * old texture that a user may have bound.
2250 */
2251 struct anv_surface_state sstate =
2252 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2253 desc->image_view->planes[binding->plane].general_sampler_surface_state :
2254 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2255 surface_state = sstate.state;
2256 assert(surface_state.alloc_size);
2257 if (need_client_mem_relocs)
2258 add_surface_state_relocs(cmd_buffer, sstate);
2259 } else {
2260 /* For color input attachments, we create the surface state at
2261 * vkBeginRenderPass time so that we can include aux and clear
2262 * color information.
2263 */
2264 assert(binding->input_attachment_index < subpass->input_count);
2265 const unsigned subpass_att = binding->input_attachment_index;
2266 const unsigned att = subpass->input_attachments[subpass_att].attachment;
2267 surface_state = cmd_buffer->state.attachments[att].input.state;
2268 }
2269 break;
2270
2271 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
2272 struct anv_surface_state sstate = (binding->write_only)
2273 ? desc->image_view->planes[binding->plane].writeonly_storage_surface_state
2274 : desc->image_view->planes[binding->plane].storage_surface_state;
2275 surface_state = sstate.state;
2276 assert(surface_state.alloc_size);
2277 if (need_client_mem_relocs)
2278 add_surface_state_relocs(cmd_buffer, sstate);
2279 break;
2280 }
2281
2282 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2283 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2284 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2285 surface_state = desc->buffer_view->surface_state;
2286 assert(surface_state.alloc_size);
2287 if (need_client_mem_relocs) {
2288 add_surface_reloc(cmd_buffer, surface_state,
2289 desc->buffer_view->address);
2290 }
2291 break;
2292
2293 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2294 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
2295 /* Compute the offset within the buffer */
2296 uint32_t dynamic_offset =
2297 dynamic_offset_for_binding(pipe_state, binding);
2298 uint64_t offset = desc->offset + dynamic_offset;
2299 /* Clamp to the buffer size */
2300 offset = MIN2(offset, desc->buffer->size);
2301 /* Clamp the range to the buffer size */
2302 uint32_t range = MIN2(desc->range, desc->buffer->size - offset);
2303
2304 struct anv_address address =
2305 anv_address_add(desc->buffer->address, offset);
2306
2307 surface_state =
2308 anv_state_stream_alloc(&cmd_buffer->surface_state_stream, 64, 64);
2309 enum isl_format format =
2310 anv_isl_format_for_descriptor_type(desc->type);
2311
2312 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2313 format, address, range, 1);
2314 if (need_client_mem_relocs)
2315 add_surface_reloc(cmd_buffer, surface_state, address);
2316 break;
2317 }
2318
2319 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2320 surface_state = (binding->write_only)
2321 ? desc->buffer_view->writeonly_storage_surface_state
2322 : desc->buffer_view->storage_surface_state;
2323 assert(surface_state.alloc_size);
2324 if (need_client_mem_relocs) {
2325 add_surface_reloc(cmd_buffer, surface_state,
2326 desc->buffer_view->address);
2327 }
2328 break;
2329
2330 default:
2331 assert(!"Invalid descriptor type");
2332 continue;
2333 }
2334
2335 bt_map[s] = surface_state.offset + state_offset;
2336 }
2337
2338 #if GEN_GEN >= 11
2339 /* The PIPE_CONTROL command description says:
2340 *
2341 * "Whenever a Binding Table Index (BTI) used by a Render Taget Message
2342 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
2343 * Target Cache Flush by enabling this bit. When render target flush
2344 * is set due to new association of BTI, PS Scoreboard Stall bit must
2345 * be set in this packet."
2346 *
2347 * FINISHME: Currently we shuffle around the surface states in the binding
2348 * table based on if they are getting used or not. So, we've to do below
2349 * pipe control flush for every binding table upload. Make changes so
2350 * that we do it only when we modify render target surface states.
2351 */
2352 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2353 pc.RenderTargetCacheFlushEnable = true;
2354 pc.StallAtPixelScoreboard = true;
2355 }
2356 #endif
2357
2358 return VK_SUCCESS;
2359 }
2360
2361 static VkResult
2362 emit_samplers(struct anv_cmd_buffer *cmd_buffer,
2363 gl_shader_stage stage,
2364 struct anv_state *state)
2365 {
2366 struct anv_cmd_pipeline_state *pipe_state =
2367 stage == MESA_SHADER_COMPUTE ? &cmd_buffer->state.compute.base :
2368 &cmd_buffer->state.gfx.base;
2369 struct anv_pipeline *pipeline = pipe_state->pipeline;
2370
2371 if (!anv_pipeline_has_stage(pipeline, stage)) {
2372 *state = (struct anv_state) { 0, };
2373 return VK_SUCCESS;
2374 }
2375
2376 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2377 if (map->sampler_count == 0) {
2378 *state = (struct anv_state) { 0, };
2379 return VK_SUCCESS;
2380 }
2381
2382 uint32_t size = map->sampler_count * 16;
2383 *state = anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, size, 32);
2384
2385 if (state->map == NULL)
2386 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2387
2388 for (uint32_t s = 0; s < map->sampler_count; s++) {
2389 struct anv_pipeline_binding *binding = &map->sampler_to_descriptor[s];
2390 const struct anv_descriptor *desc =
2391 anv_descriptor_for_binding(pipe_state, binding);
2392
2393 if (desc->type != VK_DESCRIPTOR_TYPE_SAMPLER &&
2394 desc->type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
2395 continue;
2396
2397 struct anv_sampler *sampler = desc->sampler;
2398
2399 /* This can happen if we have an unfilled slot since TYPE_SAMPLER
2400 * happens to be zero.
2401 */
2402 if (sampler == NULL)
2403 continue;
2404
2405 memcpy(state->map + (s * 16),
2406 sampler->state[binding->plane], sizeof(sampler->state[0]));
2407 }
2408
2409 return VK_SUCCESS;
2410 }
2411
2412 static uint32_t
2413 flush_descriptor_sets(struct anv_cmd_buffer *cmd_buffer)
2414 {
2415 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2416
2417 VkShaderStageFlags dirty = cmd_buffer->state.descriptors_dirty &
2418 pipeline->active_stages;
2419
2420 VkResult result = VK_SUCCESS;
2421 anv_foreach_stage(s, dirty) {
2422 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2423 if (result != VK_SUCCESS)
2424 break;
2425 result = emit_binding_table(cmd_buffer, s,
2426 &cmd_buffer->state.binding_tables[s]);
2427 if (result != VK_SUCCESS)
2428 break;
2429 }
2430
2431 if (result != VK_SUCCESS) {
2432 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2433
2434 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2435 if (result != VK_SUCCESS)
2436 return 0;
2437
2438 /* Re-emit state base addresses so we get the new surface state base
2439 * address before we start emitting binding tables etc.
2440 */
2441 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2442
2443 /* Re-emit all active binding tables */
2444 dirty |= pipeline->active_stages;
2445 anv_foreach_stage(s, dirty) {
2446 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2447 if (result != VK_SUCCESS) {
2448 anv_batch_set_error(&cmd_buffer->batch, result);
2449 return 0;
2450 }
2451 result = emit_binding_table(cmd_buffer, s,
2452 &cmd_buffer->state.binding_tables[s]);
2453 if (result != VK_SUCCESS) {
2454 anv_batch_set_error(&cmd_buffer->batch, result);
2455 return 0;
2456 }
2457 }
2458 }
2459
2460 cmd_buffer->state.descriptors_dirty &= ~dirty;
2461
2462 return dirty;
2463 }
2464
2465 static void
2466 cmd_buffer_emit_descriptor_pointers(struct anv_cmd_buffer *cmd_buffer,
2467 uint32_t stages)
2468 {
2469 static const uint32_t sampler_state_opcodes[] = {
2470 [MESA_SHADER_VERTEX] = 43,
2471 [MESA_SHADER_TESS_CTRL] = 44, /* HS */
2472 [MESA_SHADER_TESS_EVAL] = 45, /* DS */
2473 [MESA_SHADER_GEOMETRY] = 46,
2474 [MESA_SHADER_FRAGMENT] = 47,
2475 [MESA_SHADER_COMPUTE] = 0,
2476 };
2477
2478 static const uint32_t binding_table_opcodes[] = {
2479 [MESA_SHADER_VERTEX] = 38,
2480 [MESA_SHADER_TESS_CTRL] = 39,
2481 [MESA_SHADER_TESS_EVAL] = 40,
2482 [MESA_SHADER_GEOMETRY] = 41,
2483 [MESA_SHADER_FRAGMENT] = 42,
2484 [MESA_SHADER_COMPUTE] = 0,
2485 };
2486
2487 anv_foreach_stage(s, stages) {
2488 assert(s < ARRAY_SIZE(binding_table_opcodes));
2489 assert(binding_table_opcodes[s] > 0);
2490
2491 if (cmd_buffer->state.samplers[s].alloc_size > 0) {
2492 anv_batch_emit(&cmd_buffer->batch,
2493 GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ssp) {
2494 ssp._3DCommandSubOpcode = sampler_state_opcodes[s];
2495 ssp.PointertoVSSamplerState = cmd_buffer->state.samplers[s].offset;
2496 }
2497 }
2498
2499 /* Always emit binding table pointers if we're asked to, since on SKL
2500 * this is what flushes push constants. */
2501 anv_batch_emit(&cmd_buffer->batch,
2502 GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), btp) {
2503 btp._3DCommandSubOpcode = binding_table_opcodes[s];
2504 btp.PointertoVSBindingTable = cmd_buffer->state.binding_tables[s].offset;
2505 }
2506 }
2507 }
2508
2509 static void
2510 cmd_buffer_flush_push_constants(struct anv_cmd_buffer *cmd_buffer,
2511 VkShaderStageFlags dirty_stages)
2512 {
2513 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2514 const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2515
2516 static const uint32_t push_constant_opcodes[] = {
2517 [MESA_SHADER_VERTEX] = 21,
2518 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2519 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2520 [MESA_SHADER_GEOMETRY] = 22,
2521 [MESA_SHADER_FRAGMENT] = 23,
2522 [MESA_SHADER_COMPUTE] = 0,
2523 };
2524
2525 VkShaderStageFlags flushed = 0;
2526
2527 anv_foreach_stage(stage, dirty_stages) {
2528 assert(stage < ARRAY_SIZE(push_constant_opcodes));
2529 assert(push_constant_opcodes[stage] > 0);
2530
2531 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_VS), c) {
2532 c._3DCommandSubOpcode = push_constant_opcodes[stage];
2533
2534 if (anv_pipeline_has_stage(pipeline, stage)) {
2535 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2536 const struct brw_stage_prog_data *prog_data =
2537 pipeline->shaders[stage]->prog_data;
2538 const struct anv_pipeline_bind_map *bind_map =
2539 &pipeline->shaders[stage]->bind_map;
2540
2541 /* The Skylake PRM contains the following restriction:
2542 *
2543 * "The driver must ensure The following case does not occur
2544 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
2545 * buffer 3 read length equal to zero committed followed by a
2546 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
2547 * zero committed."
2548 *
2549 * To avoid this, we program the buffers in the highest slots.
2550 * This way, slot 0 is only used if slot 3 is also used.
2551 */
2552 int n = 3;
2553
2554 for (int i = 3; i >= 0; i--) {
2555 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2556 if (range->length == 0)
2557 continue;
2558
2559 const unsigned surface =
2560 prog_data->binding_table.ubo_start + range->block;
2561
2562 assert(surface <= bind_map->surface_count);
2563 const struct anv_pipeline_binding *binding =
2564 &bind_map->surface_to_descriptor[surface];
2565
2566 struct anv_address read_addr;
2567 uint32_t read_len;
2568 if (binding->set == ANV_DESCRIPTOR_SET_SHADER_CONSTANTS) {
2569 struct anv_address constant_data = {
2570 .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2571 .offset = pipeline->shaders[stage]->constant_data.offset,
2572 };
2573 unsigned constant_data_size =
2574 pipeline->shaders[stage]->constant_data_size;
2575
2576 read_len = MIN2(range->length,
2577 DIV_ROUND_UP(constant_data_size, 32) - range->start);
2578 read_addr = anv_address_add(constant_data,
2579 range->start * 32);
2580 } else if (binding->set == ANV_DESCRIPTOR_SET_DESCRIPTORS) {
2581 /* This is a descriptor set buffer so the set index is
2582 * actually given by binding->binding. (Yes, that's
2583 * confusing.)
2584 */
2585 struct anv_descriptor_set *set =
2586 gfx_state->base.descriptors[binding->binding];
2587 struct anv_address desc_buffer_addr =
2588 anv_descriptor_set_address(cmd_buffer, set);
2589 const unsigned desc_buffer_size = set->desc_mem.alloc_size;
2590
2591 read_len = MIN2(range->length,
2592 DIV_ROUND_UP(desc_buffer_size, 32) - range->start);
2593 read_addr = anv_address_add(desc_buffer_addr,
2594 range->start * 32);
2595 } else {
2596 const struct anv_descriptor *desc =
2597 anv_descriptor_for_binding(&gfx_state->base, binding);
2598
2599 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2600 read_len = MIN2(range->length,
2601 DIV_ROUND_UP(desc->buffer_view->range, 32) - range->start);
2602 read_addr = anv_address_add(desc->buffer_view->address,
2603 range->start * 32);
2604 } else {
2605 assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2606
2607 uint32_t dynamic_offset =
2608 dynamic_offset_for_binding(&gfx_state->base, binding);
2609 uint32_t buf_offset =
2610 MIN2(desc->offset + dynamic_offset, desc->buffer->size);
2611 uint32_t buf_range =
2612 MIN2(desc->range, desc->buffer->size - buf_offset);
2613
2614 read_len = MIN2(range->length,
2615 DIV_ROUND_UP(buf_range, 32) - range->start);
2616 read_addr = anv_address_add(desc->buffer->address,
2617 buf_offset + range->start * 32);
2618 }
2619 }
2620
2621 if (read_len > 0) {
2622 c.ConstantBody.Buffer[n] = read_addr;
2623 c.ConstantBody.ReadLength[n] = read_len;
2624 n--;
2625 }
2626 }
2627
2628 struct anv_state state =
2629 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2630
2631 if (state.alloc_size > 0) {
2632 c.ConstantBody.Buffer[n] = (struct anv_address) {
2633 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2634 .offset = state.offset,
2635 };
2636 c.ConstantBody.ReadLength[n] =
2637 DIV_ROUND_UP(state.alloc_size, 32);
2638 }
2639 #else
2640 /* For Ivy Bridge, the push constants packets have a different
2641 * rule that would require us to iterate in the other direction
2642 * and possibly mess around with dynamic state base address.
2643 * Don't bother; just emit regular push constants at n = 0.
2644 */
2645 struct anv_state state =
2646 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2647
2648 if (state.alloc_size > 0) {
2649 c.ConstantBody.Buffer[0].offset = state.offset,
2650 c.ConstantBody.ReadLength[0] =
2651 DIV_ROUND_UP(state.alloc_size, 32);
2652 }
2653 #endif
2654 }
2655 }
2656
2657 flushed |= mesa_to_vk_shader_stage(stage);
2658 }
2659
2660 cmd_buffer->state.push_constants_dirty &= ~flushed;
2661 }
2662
2663 void
2664 genX(cmd_buffer_flush_state)(struct anv_cmd_buffer *cmd_buffer)
2665 {
2666 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2667 uint32_t *p;
2668
2669 uint32_t vb_emit = cmd_buffer->state.gfx.vb_dirty & pipeline->vb_used;
2670 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE)
2671 vb_emit |= pipeline->vb_used;
2672
2673 assert((pipeline->active_stages & VK_SHADER_STAGE_COMPUTE_BIT) == 0);
2674
2675 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
2676
2677 genX(cmd_buffer_emit_hashing_mode)(cmd_buffer, UINT_MAX, UINT_MAX, 1);
2678
2679 genX(flush_pipeline_select_3d)(cmd_buffer);
2680
2681 if (vb_emit) {
2682 const uint32_t num_buffers = __builtin_popcount(vb_emit);
2683 const uint32_t num_dwords = 1 + num_buffers * 4;
2684
2685 p = anv_batch_emitn(&cmd_buffer->batch, num_dwords,
2686 GENX(3DSTATE_VERTEX_BUFFERS));
2687 uint32_t vb, i = 0;
2688 for_each_bit(vb, vb_emit) {
2689 struct anv_buffer *buffer = cmd_buffer->state.vertex_bindings[vb].buffer;
2690 uint32_t offset = cmd_buffer->state.vertex_bindings[vb].offset;
2691
2692 struct GENX(VERTEX_BUFFER_STATE) state = {
2693 .VertexBufferIndex = vb,
2694
2695 .MOCS = anv_mocs_for_bo(cmd_buffer->device, buffer->address.bo),
2696 #if GEN_GEN <= 7
2697 .BufferAccessType = pipeline->vb[vb].instanced ? INSTANCEDATA : VERTEXDATA,
2698 .InstanceDataStepRate = pipeline->vb[vb].instance_divisor,
2699 #endif
2700
2701 .AddressModifyEnable = true,
2702 .BufferPitch = pipeline->vb[vb].stride,
2703 .BufferStartingAddress = anv_address_add(buffer->address, offset),
2704
2705 #if GEN_GEN >= 8
2706 .BufferSize = buffer->size - offset
2707 #else
2708 .EndAddress = anv_address_add(buffer->address, buffer->size - 1),
2709 #endif
2710 };
2711
2712 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, &p[1 + i * 4], &state);
2713 i++;
2714 }
2715 }
2716
2717 cmd_buffer->state.gfx.vb_dirty &= ~vb_emit;
2718
2719 #if GEN_GEN >= 8
2720 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_XFB_ENABLE) {
2721 /* We don't need any per-buffer dirty tracking because you're not
2722 * allowed to bind different XFB buffers while XFB is enabled.
2723 */
2724 for (unsigned idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
2725 struct anv_xfb_binding *xfb = &cmd_buffer->state.xfb_bindings[idx];
2726 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_SO_BUFFER), sob) {
2727 sob.SOBufferIndex = idx;
2728
2729 if (cmd_buffer->state.xfb_enabled && xfb->buffer && xfb->size != 0) {
2730 sob.SOBufferEnable = true;
2731 sob.MOCS = cmd_buffer->device->default_mocs,
2732 sob.StreamOffsetWriteEnable = false;
2733 sob.SurfaceBaseAddress = anv_address_add(xfb->buffer->address,
2734 xfb->offset);
2735 /* Size is in DWords - 1 */
2736 sob.SurfaceSize = xfb->size / 4 - 1;
2737 }
2738 }
2739 }
2740
2741 /* CNL and later require a CS stall after 3DSTATE_SO_BUFFER */
2742 if (GEN_GEN >= 10)
2743 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2744 }
2745 #endif
2746
2747 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE) {
2748 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
2749
2750 /* The exact descriptor layout is pulled from the pipeline, so we need
2751 * to re-emit binding tables on every pipeline change.
2752 */
2753 cmd_buffer->state.descriptors_dirty |= pipeline->active_stages;
2754
2755 /* If the pipeline changed, we may need to re-allocate push constant
2756 * space in the URB.
2757 */
2758 cmd_buffer_alloc_push_constants(cmd_buffer);
2759 }
2760
2761 #if GEN_GEN <= 7
2762 if (cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_VERTEX_BIT ||
2763 cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_VERTEX_BIT) {
2764 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
2765 *
2766 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth
2767 * stall needs to be sent just prior to any 3DSTATE_VS,
2768 * 3DSTATE_URB_VS, 3DSTATE_CONSTANT_VS,
2769 * 3DSTATE_BINDING_TABLE_POINTER_VS,
2770 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one
2771 * PIPE_CONTROL needs to be sent before any combination of VS
2772 * associated 3DSTATE."
2773 */
2774 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2775 pc.DepthStallEnable = true;
2776 pc.PostSyncOperation = WriteImmediateData;
2777 pc.Address =
2778 (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
2779 }
2780 }
2781 #endif
2782
2783 /* Render targets live in the same binding table as fragment descriptors */
2784 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_RENDER_TARGETS)
2785 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_FRAGMENT_BIT;
2786
2787 /* We emit the binding tables and sampler tables first, then emit push
2788 * constants and then finally emit binding table and sampler table
2789 * pointers. It has to happen in this order, since emitting the binding
2790 * tables may change the push constants (in case of storage images). After
2791 * emitting push constants, on SKL+ we have to emit the corresponding
2792 * 3DSTATE_BINDING_TABLE_POINTER_* for the push constants to take effect.
2793 */
2794 uint32_t dirty = 0;
2795 if (cmd_buffer->state.descriptors_dirty)
2796 dirty = flush_descriptor_sets(cmd_buffer);
2797
2798 if (dirty || cmd_buffer->state.push_constants_dirty) {
2799 /* Because we're pushing UBOs, we have to push whenever either
2800 * descriptors or push constants is dirty.
2801 */
2802 dirty |= cmd_buffer->state.push_constants_dirty;
2803 dirty &= ANV_STAGE_MASK & VK_SHADER_STAGE_ALL_GRAPHICS;
2804 cmd_buffer_flush_push_constants(cmd_buffer, dirty);
2805 }
2806
2807 if (dirty)
2808 cmd_buffer_emit_descriptor_pointers(cmd_buffer, dirty);
2809
2810 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT)
2811 gen8_cmd_buffer_emit_viewport(cmd_buffer);
2812
2813 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_VIEWPORT |
2814 ANV_CMD_DIRTY_PIPELINE)) {
2815 gen8_cmd_buffer_emit_depth_viewport(cmd_buffer,
2816 pipeline->depth_clamp_enable);
2817 }
2818
2819 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_SCISSOR |
2820 ANV_CMD_DIRTY_RENDER_TARGETS))
2821 gen7_cmd_buffer_emit_scissor(cmd_buffer);
2822
2823 genX(cmd_buffer_flush_dynamic_state)(cmd_buffer);
2824
2825 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
2826 }
2827
2828 static void
2829 emit_vertex_bo(struct anv_cmd_buffer *cmd_buffer,
2830 struct anv_address addr,
2831 uint32_t size, uint32_t index)
2832 {
2833 uint32_t *p = anv_batch_emitn(&cmd_buffer->batch, 5,
2834 GENX(3DSTATE_VERTEX_BUFFERS));
2835
2836 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, p + 1,
2837 &(struct GENX(VERTEX_BUFFER_STATE)) {
2838 .VertexBufferIndex = index,
2839 .AddressModifyEnable = true,
2840 .BufferPitch = 0,
2841 .MOCS = anv_mocs_for_bo(cmd_buffer->device, addr.bo),
2842 #if (GEN_GEN >= 8)
2843 .BufferStartingAddress = addr,
2844 .BufferSize = size
2845 #else
2846 .BufferStartingAddress = addr,
2847 .EndAddress = anv_address_add(addr, size),
2848 #endif
2849 });
2850 }
2851
2852 static void
2853 emit_base_vertex_instance_bo(struct anv_cmd_buffer *cmd_buffer,
2854 struct anv_address addr)
2855 {
2856 emit_vertex_bo(cmd_buffer, addr, 8, ANV_SVGS_VB_INDEX);
2857 }
2858
2859 static void
2860 emit_base_vertex_instance(struct anv_cmd_buffer *cmd_buffer,
2861 uint32_t base_vertex, uint32_t base_instance)
2862 {
2863 struct anv_state id_state =
2864 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 8, 4);
2865
2866 ((uint32_t *)id_state.map)[0] = base_vertex;
2867 ((uint32_t *)id_state.map)[1] = base_instance;
2868
2869 struct anv_address addr = {
2870 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2871 .offset = id_state.offset,
2872 };
2873
2874 emit_base_vertex_instance_bo(cmd_buffer, addr);
2875 }
2876
2877 static void
2878 emit_draw_index(struct anv_cmd_buffer *cmd_buffer, uint32_t draw_index)
2879 {
2880 struct anv_state state =
2881 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 4, 4);
2882
2883 ((uint32_t *)state.map)[0] = draw_index;
2884
2885 struct anv_address addr = {
2886 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2887 .offset = state.offset,
2888 };
2889
2890 emit_vertex_bo(cmd_buffer, addr, 4, ANV_DRAWID_VB_INDEX);
2891 }
2892
2893 void genX(CmdDraw)(
2894 VkCommandBuffer commandBuffer,
2895 uint32_t vertexCount,
2896 uint32_t instanceCount,
2897 uint32_t firstVertex,
2898 uint32_t firstInstance)
2899 {
2900 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2901 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2902 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2903
2904 if (anv_batch_has_error(&cmd_buffer->batch))
2905 return;
2906
2907 genX(cmd_buffer_flush_state)(cmd_buffer);
2908
2909 if (cmd_buffer->state.conditional_render_enabled)
2910 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
2911
2912 if (vs_prog_data->uses_firstvertex ||
2913 vs_prog_data->uses_baseinstance)
2914 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
2915 if (vs_prog_data->uses_drawid)
2916 emit_draw_index(cmd_buffer, 0);
2917
2918 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2919 * different views. We need to multiply instanceCount by the view count.
2920 */
2921 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2922
2923 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2924 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
2925 prim.VertexAccessType = SEQUENTIAL;
2926 prim.PrimitiveTopologyType = pipeline->topology;
2927 prim.VertexCountPerInstance = vertexCount;
2928 prim.StartVertexLocation = firstVertex;
2929 prim.InstanceCount = instanceCount;
2930 prim.StartInstanceLocation = firstInstance;
2931 prim.BaseVertexLocation = 0;
2932 }
2933 }
2934
2935 void genX(CmdDrawIndexed)(
2936 VkCommandBuffer commandBuffer,
2937 uint32_t indexCount,
2938 uint32_t instanceCount,
2939 uint32_t firstIndex,
2940 int32_t vertexOffset,
2941 uint32_t firstInstance)
2942 {
2943 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2944 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2945 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2946
2947 if (anv_batch_has_error(&cmd_buffer->batch))
2948 return;
2949
2950 genX(cmd_buffer_flush_state)(cmd_buffer);
2951
2952 if (cmd_buffer->state.conditional_render_enabled)
2953 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
2954
2955 if (vs_prog_data->uses_firstvertex ||
2956 vs_prog_data->uses_baseinstance)
2957 emit_base_vertex_instance(cmd_buffer, vertexOffset, firstInstance);
2958 if (vs_prog_data->uses_drawid)
2959 emit_draw_index(cmd_buffer, 0);
2960
2961 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2962 * different views. We need to multiply instanceCount by the view count.
2963 */
2964 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2965
2966 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2967 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
2968 prim.VertexAccessType = RANDOM;
2969 prim.PrimitiveTopologyType = pipeline->topology;
2970 prim.VertexCountPerInstance = indexCount;
2971 prim.StartVertexLocation = firstIndex;
2972 prim.InstanceCount = instanceCount;
2973 prim.StartInstanceLocation = firstInstance;
2974 prim.BaseVertexLocation = vertexOffset;
2975 }
2976 }
2977
2978 /* Auto-Draw / Indirect Registers */
2979 #define GEN7_3DPRIM_END_OFFSET 0x2420
2980 #define GEN7_3DPRIM_START_VERTEX 0x2430
2981 #define GEN7_3DPRIM_VERTEX_COUNT 0x2434
2982 #define GEN7_3DPRIM_INSTANCE_COUNT 0x2438
2983 #define GEN7_3DPRIM_START_INSTANCE 0x243C
2984 #define GEN7_3DPRIM_BASE_VERTEX 0x2440
2985
2986 void genX(CmdDrawIndirectByteCountEXT)(
2987 VkCommandBuffer commandBuffer,
2988 uint32_t instanceCount,
2989 uint32_t firstInstance,
2990 VkBuffer counterBuffer,
2991 VkDeviceSize counterBufferOffset,
2992 uint32_t counterOffset,
2993 uint32_t vertexStride)
2994 {
2995 #if GEN_IS_HASWELL || GEN_GEN >= 8
2996 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2997 ANV_FROM_HANDLE(anv_buffer, counter_buffer, counterBuffer);
2998 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2999 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3000
3001 /* firstVertex is always zero for this draw function */
3002 const uint32_t firstVertex = 0;
3003
3004 if (anv_batch_has_error(&cmd_buffer->batch))
3005 return;
3006
3007 genX(cmd_buffer_flush_state)(cmd_buffer);
3008
3009 if (vs_prog_data->uses_firstvertex ||
3010 vs_prog_data->uses_baseinstance)
3011 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
3012 if (vs_prog_data->uses_drawid)
3013 emit_draw_index(cmd_buffer, 0);
3014
3015 /* Our implementation of VK_KHR_multiview uses instancing to draw the
3016 * different views. We need to multiply instanceCount by the view count.
3017 */
3018 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
3019
3020 struct gen_mi_builder b;
3021 gen_mi_builder_init(&b, &cmd_buffer->batch);
3022 struct gen_mi_value count =
3023 gen_mi_mem32(anv_address_add(counter_buffer->address,
3024 counterBufferOffset));
3025 if (counterOffset)
3026 count = gen_mi_isub(&b, count, gen_mi_imm(counterOffset));
3027 count = gen_mi_udiv32_imm(&b, count, vertexStride);
3028 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT), count);
3029
3030 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3031 gen_mi_imm(firstVertex));
3032 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT),
3033 gen_mi_imm(instanceCount));
3034 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3035 gen_mi_imm(firstInstance));
3036 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3037
3038 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3039 prim.IndirectParameterEnable = true;
3040 prim.VertexAccessType = SEQUENTIAL;
3041 prim.PrimitiveTopologyType = pipeline->topology;
3042 }
3043 #endif /* GEN_IS_HASWELL || GEN_GEN >= 8 */
3044 }
3045
3046 static void
3047 load_indirect_parameters(struct anv_cmd_buffer *cmd_buffer,
3048 struct anv_address addr,
3049 bool indexed)
3050 {
3051 struct gen_mi_builder b;
3052 gen_mi_builder_init(&b, &cmd_buffer->batch);
3053
3054 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT),
3055 gen_mi_mem32(anv_address_add(addr, 0)));
3056
3057 struct gen_mi_value instance_count = gen_mi_mem32(anv_address_add(addr, 4));
3058 unsigned view_count = anv_subpass_view_count(cmd_buffer->state.subpass);
3059 if (view_count > 1) {
3060 #if GEN_IS_HASWELL || GEN_GEN >= 8
3061 instance_count = gen_mi_imul_imm(&b, instance_count, view_count);
3062 #else
3063 anv_finishme("Multiview + indirect draw requires MI_MATH; "
3064 "MI_MATH is not supported on Ivy Bridge");
3065 #endif
3066 }
3067 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT), instance_count);
3068
3069 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3070 gen_mi_mem32(anv_address_add(addr, 8)));
3071
3072 if (indexed) {
3073 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX),
3074 gen_mi_mem32(anv_address_add(addr, 12)));
3075 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3076 gen_mi_mem32(anv_address_add(addr, 16)));
3077 } else {
3078 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3079 gen_mi_mem32(anv_address_add(addr, 12)));
3080 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3081 }
3082 }
3083
3084 void genX(CmdDrawIndirect)(
3085 VkCommandBuffer commandBuffer,
3086 VkBuffer _buffer,
3087 VkDeviceSize offset,
3088 uint32_t drawCount,
3089 uint32_t stride)
3090 {
3091 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3092 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3093 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3094 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3095
3096 if (anv_batch_has_error(&cmd_buffer->batch))
3097 return;
3098
3099 genX(cmd_buffer_flush_state)(cmd_buffer);
3100
3101 if (cmd_buffer->state.conditional_render_enabled)
3102 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3103
3104 for (uint32_t i = 0; i < drawCount; i++) {
3105 struct anv_address draw = anv_address_add(buffer->address, offset);
3106
3107 if (vs_prog_data->uses_firstvertex ||
3108 vs_prog_data->uses_baseinstance)
3109 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3110 if (vs_prog_data->uses_drawid)
3111 emit_draw_index(cmd_buffer, i);
3112
3113 load_indirect_parameters(cmd_buffer, draw, false);
3114
3115 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3116 prim.IndirectParameterEnable = true;
3117 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3118 prim.VertexAccessType = SEQUENTIAL;
3119 prim.PrimitiveTopologyType = pipeline->topology;
3120 }
3121
3122 offset += stride;
3123 }
3124 }
3125
3126 void genX(CmdDrawIndexedIndirect)(
3127 VkCommandBuffer commandBuffer,
3128 VkBuffer _buffer,
3129 VkDeviceSize offset,
3130 uint32_t drawCount,
3131 uint32_t stride)
3132 {
3133 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3134 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3135 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3136 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3137
3138 if (anv_batch_has_error(&cmd_buffer->batch))
3139 return;
3140
3141 genX(cmd_buffer_flush_state)(cmd_buffer);
3142
3143 if (cmd_buffer->state.conditional_render_enabled)
3144 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3145
3146 for (uint32_t i = 0; i < drawCount; i++) {
3147 struct anv_address draw = anv_address_add(buffer->address, offset);
3148
3149 /* TODO: We need to stomp base vertex to 0 somehow */
3150 if (vs_prog_data->uses_firstvertex ||
3151 vs_prog_data->uses_baseinstance)
3152 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
3153 if (vs_prog_data->uses_drawid)
3154 emit_draw_index(cmd_buffer, i);
3155
3156 load_indirect_parameters(cmd_buffer, draw, true);
3157
3158 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3159 prim.IndirectParameterEnable = true;
3160 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3161 prim.VertexAccessType = RANDOM;
3162 prim.PrimitiveTopologyType = pipeline->topology;
3163 }
3164
3165 offset += stride;
3166 }
3167 }
3168
3169 #define TMP_DRAW_COUNT_REG 0x2670 /* MI_ALU_REG14 */
3170
3171 static void
3172 prepare_for_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3173 struct anv_address count_address,
3174 const bool conditional_render_enabled)
3175 {
3176 struct gen_mi_builder b;
3177 gen_mi_builder_init(&b, &cmd_buffer->batch);
3178
3179 if (conditional_render_enabled) {
3180 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3181 gen_mi_store(&b, gen_mi_reg64(TMP_DRAW_COUNT_REG),
3182 gen_mi_mem32(count_address));
3183 #endif
3184 } else {
3185 /* Upload the current draw count from the draw parameters buffer to
3186 * MI_PREDICATE_SRC0.
3187 */
3188 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
3189 gen_mi_mem32(count_address));
3190
3191 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC1 + 4), gen_mi_imm(0));
3192 }
3193 }
3194
3195 static void
3196 emit_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3197 uint32_t draw_index)
3198 {
3199 struct gen_mi_builder b;
3200 gen_mi_builder_init(&b, &cmd_buffer->batch);
3201
3202 /* Upload the index of the current primitive to MI_PREDICATE_SRC1. */
3203 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC1), gen_mi_imm(draw_index));
3204
3205 if (draw_index == 0) {
3206 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3207 mip.LoadOperation = LOAD_LOADINV;
3208 mip.CombineOperation = COMBINE_SET;
3209 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3210 }
3211 } else {
3212 /* While draw_index < draw_count the predicate's result will be
3213 * (draw_index == draw_count) ^ TRUE = TRUE
3214 * When draw_index == draw_count the result is
3215 * (TRUE) ^ TRUE = FALSE
3216 * After this all results will be:
3217 * (FALSE) ^ FALSE = FALSE
3218 */
3219 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3220 mip.LoadOperation = LOAD_LOAD;
3221 mip.CombineOperation = COMBINE_XOR;
3222 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3223 }
3224 }
3225 }
3226
3227 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3228 static void
3229 emit_draw_count_predicate_with_conditional_render(
3230 struct anv_cmd_buffer *cmd_buffer,
3231 uint32_t draw_index)
3232 {
3233 struct gen_mi_builder b;
3234 gen_mi_builder_init(&b, &cmd_buffer->batch);
3235
3236 struct gen_mi_value pred = gen_mi_ult(&b, gen_mi_imm(draw_index),
3237 gen_mi_reg64(TMP_DRAW_COUNT_REG));
3238 pred = gen_mi_iand(&b, pred, gen_mi_reg64(ANV_PREDICATE_RESULT_REG));
3239
3240 #if GEN_GEN >= 8
3241 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_RESULT), pred);
3242 #else
3243 /* MI_PREDICATE_RESULT is not whitelisted in i915 command parser
3244 * so we emit MI_PREDICATE to set it.
3245 */
3246
3247 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), pred);
3248 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3249
3250 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3251 mip.LoadOperation = LOAD_LOADINV;
3252 mip.CombineOperation = COMBINE_SET;
3253 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3254 }
3255 #endif
3256 }
3257 #endif
3258
3259 void genX(CmdDrawIndirectCountKHR)(
3260 VkCommandBuffer commandBuffer,
3261 VkBuffer _buffer,
3262 VkDeviceSize offset,
3263 VkBuffer _countBuffer,
3264 VkDeviceSize countBufferOffset,
3265 uint32_t maxDrawCount,
3266 uint32_t stride)
3267 {
3268 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3269 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3270 ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3271 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3272 struct anv_pipeline *pipeline = cmd_state->gfx.base.pipeline;
3273 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3274
3275 if (anv_batch_has_error(&cmd_buffer->batch))
3276 return;
3277
3278 genX(cmd_buffer_flush_state)(cmd_buffer);
3279
3280 struct anv_address count_address =
3281 anv_address_add(count_buffer->address, countBufferOffset);
3282
3283 prepare_for_draw_count_predicate(cmd_buffer, count_address,
3284 cmd_state->conditional_render_enabled);
3285
3286 for (uint32_t i = 0; i < maxDrawCount; i++) {
3287 struct anv_address draw = anv_address_add(buffer->address, offset);
3288
3289 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3290 if (cmd_state->conditional_render_enabled) {
3291 emit_draw_count_predicate_with_conditional_render(cmd_buffer, i);
3292 } else {
3293 emit_draw_count_predicate(cmd_buffer, i);
3294 }
3295 #else
3296 emit_draw_count_predicate(cmd_buffer, i);
3297 #endif
3298
3299 if (vs_prog_data->uses_firstvertex ||
3300 vs_prog_data->uses_baseinstance)
3301 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3302 if (vs_prog_data->uses_drawid)
3303 emit_draw_index(cmd_buffer, i);
3304
3305 load_indirect_parameters(cmd_buffer, draw, false);
3306
3307 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3308 prim.IndirectParameterEnable = true;
3309 prim.PredicateEnable = true;
3310 prim.VertexAccessType = SEQUENTIAL;
3311 prim.PrimitiveTopologyType = pipeline->topology;
3312 }
3313
3314 offset += stride;
3315 }
3316 }
3317
3318 void genX(CmdDrawIndexedIndirectCountKHR)(
3319 VkCommandBuffer commandBuffer,
3320 VkBuffer _buffer,
3321 VkDeviceSize offset,
3322 VkBuffer _countBuffer,
3323 VkDeviceSize countBufferOffset,
3324 uint32_t maxDrawCount,
3325 uint32_t stride)
3326 {
3327 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3328 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3329 ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3330 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3331 struct anv_pipeline *pipeline = cmd_state->gfx.base.pipeline;
3332 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3333
3334 if (anv_batch_has_error(&cmd_buffer->batch))
3335 return;
3336
3337 genX(cmd_buffer_flush_state)(cmd_buffer);
3338
3339 struct anv_address count_address =
3340 anv_address_add(count_buffer->address, countBufferOffset);
3341
3342 prepare_for_draw_count_predicate(cmd_buffer, count_address,
3343 cmd_state->conditional_render_enabled);
3344
3345 for (uint32_t i = 0; i < maxDrawCount; i++) {
3346 struct anv_address draw = anv_address_add(buffer->address, offset);
3347
3348 #if GEN_GEN >= 8 || GEN_IS_HASWELL
3349 if (cmd_state->conditional_render_enabled) {
3350 emit_draw_count_predicate_with_conditional_render(cmd_buffer, i);
3351 } else {
3352 emit_draw_count_predicate(cmd_buffer, i);
3353 }
3354 #else
3355 emit_draw_count_predicate(cmd_buffer, i);
3356 #endif
3357
3358 /* TODO: We need to stomp base vertex to 0 somehow */
3359 if (vs_prog_data->uses_firstvertex ||
3360 vs_prog_data->uses_baseinstance)
3361 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
3362 if (vs_prog_data->uses_drawid)
3363 emit_draw_index(cmd_buffer, i);
3364
3365 load_indirect_parameters(cmd_buffer, draw, true);
3366
3367 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3368 prim.IndirectParameterEnable = true;
3369 prim.PredicateEnable = true;
3370 prim.VertexAccessType = RANDOM;
3371 prim.PrimitiveTopologyType = pipeline->topology;
3372 }
3373
3374 offset += stride;
3375 }
3376 }
3377
3378 void genX(CmdBeginTransformFeedbackEXT)(
3379 VkCommandBuffer commandBuffer,
3380 uint32_t firstCounterBuffer,
3381 uint32_t counterBufferCount,
3382 const VkBuffer* pCounterBuffers,
3383 const VkDeviceSize* pCounterBufferOffsets)
3384 {
3385 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3386
3387 assert(firstCounterBuffer < MAX_XFB_BUFFERS);
3388 assert(counterBufferCount <= MAX_XFB_BUFFERS);
3389 assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
3390
3391 /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
3392 *
3393 * "Ssoftware must ensure that no HW stream output operations can be in
3394 * process or otherwise pending at the point that the MI_LOAD/STORE
3395 * commands are processed. This will likely require a pipeline flush."
3396 */
3397 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3398 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3399
3400 for (uint32_t idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
3401 /* If we have a counter buffer, this is a resume so we need to load the
3402 * value into the streamout offset register. Otherwise, this is a begin
3403 * and we need to reset it to zero.
3404 */
3405 if (pCounterBuffers &&
3406 idx >= firstCounterBuffer &&
3407 idx - firstCounterBuffer < counterBufferCount &&
3408 pCounterBuffers[idx - firstCounterBuffer] != VK_NULL_HANDLE) {
3409 uint32_t cb_idx = idx - firstCounterBuffer;
3410 ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
3411 uint64_t offset = pCounterBufferOffsets ?
3412 pCounterBufferOffsets[cb_idx] : 0;
3413
3414 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3415 lrm.RegisterAddress = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3416 lrm.MemoryAddress = anv_address_add(counter_buffer->address,
3417 offset);
3418 }
3419 } else {
3420 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
3421 lri.RegisterOffset = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3422 lri.DataDWord = 0;
3423 }
3424 }
3425 }
3426
3427 cmd_buffer->state.xfb_enabled = true;
3428 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
3429 }
3430
3431 void genX(CmdEndTransformFeedbackEXT)(
3432 VkCommandBuffer commandBuffer,
3433 uint32_t firstCounterBuffer,
3434 uint32_t counterBufferCount,
3435 const VkBuffer* pCounterBuffers,
3436 const VkDeviceSize* pCounterBufferOffsets)
3437 {
3438 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3439
3440 assert(firstCounterBuffer < MAX_XFB_BUFFERS);
3441 assert(counterBufferCount <= MAX_XFB_BUFFERS);
3442 assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
3443
3444 /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
3445 *
3446 * "Ssoftware must ensure that no HW stream output operations can be in
3447 * process or otherwise pending at the point that the MI_LOAD/STORE
3448 * commands are processed. This will likely require a pipeline flush."
3449 */
3450 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3451 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3452
3453 for (uint32_t cb_idx = 0; cb_idx < counterBufferCount; cb_idx++) {
3454 unsigned idx = firstCounterBuffer + cb_idx;
3455
3456 /* If we have a counter buffer, this is a resume so we need to load the
3457 * value into the streamout offset register. Otherwise, this is a begin
3458 * and we need to reset it to zero.
3459 */
3460 if (pCounterBuffers &&
3461 cb_idx < counterBufferCount &&
3462 pCounterBuffers[cb_idx] != VK_NULL_HANDLE) {
3463 ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
3464 uint64_t offset = pCounterBufferOffsets ?
3465 pCounterBufferOffsets[cb_idx] : 0;
3466
3467 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_REGISTER_MEM), srm) {
3468 srm.MemoryAddress = anv_address_add(counter_buffer->address,
3469 offset);
3470 srm.RegisterAddress = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3471 }
3472 }
3473 }
3474
3475 cmd_buffer->state.xfb_enabled = false;
3476 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
3477 }
3478
3479 static VkResult
3480 flush_compute_descriptor_set(struct anv_cmd_buffer *cmd_buffer)
3481 {
3482 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3483 struct anv_state surfaces = { 0, }, samplers = { 0, };
3484 VkResult result;
3485
3486 result = emit_binding_table(cmd_buffer, MESA_SHADER_COMPUTE, &surfaces);
3487 if (result != VK_SUCCESS) {
3488 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
3489
3490 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
3491 if (result != VK_SUCCESS)
3492 return result;
3493
3494 /* Re-emit state base addresses so we get the new surface state base
3495 * address before we start emitting binding tables etc.
3496 */
3497 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
3498
3499 result = emit_binding_table(cmd_buffer, MESA_SHADER_COMPUTE, &surfaces);
3500 if (result != VK_SUCCESS) {
3501 anv_batch_set_error(&cmd_buffer->batch, result);
3502 return result;
3503 }
3504 }
3505
3506 result = emit_samplers(cmd_buffer, MESA_SHADER_COMPUTE, &samplers);
3507 if (result != VK_SUCCESS) {
3508 anv_batch_set_error(&cmd_buffer->batch, result);
3509 return result;
3510 }
3511
3512 uint32_t iface_desc_data_dw[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
3513 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
3514 .BindingTablePointer = surfaces.offset,
3515 .SamplerStatePointer = samplers.offset,
3516 };
3517 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL, iface_desc_data_dw, &desc);
3518
3519 struct anv_state state =
3520 anv_cmd_buffer_merge_dynamic(cmd_buffer, iface_desc_data_dw,
3521 pipeline->interface_descriptor_data,
3522 GENX(INTERFACE_DESCRIPTOR_DATA_length),
3523 64);
3524
3525 uint32_t size = GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
3526 anv_batch_emit(&cmd_buffer->batch,
3527 GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), mid) {
3528 mid.InterfaceDescriptorTotalLength = size;
3529 mid.InterfaceDescriptorDataStartAddress = state.offset;
3530 }
3531
3532 return VK_SUCCESS;
3533 }
3534
3535 void
3536 genX(cmd_buffer_flush_compute_state)(struct anv_cmd_buffer *cmd_buffer)
3537 {
3538 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3539 VkResult result;
3540
3541 assert(pipeline->active_stages == VK_SHADER_STAGE_COMPUTE_BIT);
3542
3543 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
3544
3545 genX(flush_pipeline_select_gpgpu)(cmd_buffer);
3546
3547 if (cmd_buffer->state.compute.pipeline_dirty) {
3548 /* From the Sky Lake PRM Vol 2a, MEDIA_VFE_STATE:
3549 *
3550 * "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
3551 * the only bits that are changed are scoreboard related: Scoreboard
3552 * Enable, Scoreboard Type, Scoreboard Mask, Scoreboard * Delta. For
3553 * these scoreboard related states, a MEDIA_STATE_FLUSH is
3554 * sufficient."
3555 */
3556 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3557 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3558
3559 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
3560 }
3561
3562 if ((cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_COMPUTE_BIT) ||
3563 cmd_buffer->state.compute.pipeline_dirty) {
3564 /* FIXME: figure out descriptors for gen7 */
3565 result = flush_compute_descriptor_set(cmd_buffer);
3566 if (result != VK_SUCCESS)
3567 return;
3568
3569 cmd_buffer->state.descriptors_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
3570 }
3571
3572 if (cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_COMPUTE_BIT) {
3573 struct anv_state push_state =
3574 anv_cmd_buffer_cs_push_constants(cmd_buffer);
3575
3576 if (push_state.alloc_size) {
3577 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_CURBE_LOAD), curbe) {
3578 curbe.CURBETotalDataLength = push_state.alloc_size;
3579 curbe.CURBEDataStartAddress = push_state.offset;
3580 }
3581 }
3582
3583 cmd_buffer->state.push_constants_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
3584 }
3585
3586 cmd_buffer->state.compute.pipeline_dirty = false;
3587
3588 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3589 }
3590
3591 #if GEN_GEN == 7
3592
3593 static VkResult
3594 verify_cmd_parser(const struct anv_device *device,
3595 int required_version,
3596 const char *function)
3597 {
3598 if (device->instance->physicalDevice.cmd_parser_version < required_version) {
3599 return vk_errorf(device->instance, device->instance,
3600 VK_ERROR_FEATURE_NOT_PRESENT,
3601 "cmd parser version %d is required for %s",
3602 required_version, function);
3603 } else {
3604 return VK_SUCCESS;
3605 }
3606 }
3607
3608 #endif
3609
3610 static void
3611 anv_cmd_buffer_push_base_group_id(struct anv_cmd_buffer *cmd_buffer,
3612 uint32_t baseGroupX,
3613 uint32_t baseGroupY,
3614 uint32_t baseGroupZ)
3615 {
3616 if (anv_batch_has_error(&cmd_buffer->batch))
3617 return;
3618
3619 struct anv_push_constants *push =
3620 &cmd_buffer->state.push_constants[MESA_SHADER_COMPUTE];
3621 if (push->base_work_group_id[0] != baseGroupX ||
3622 push->base_work_group_id[1] != baseGroupY ||
3623 push->base_work_group_id[2] != baseGroupZ) {
3624 push->base_work_group_id[0] = baseGroupX;
3625 push->base_work_group_id[1] = baseGroupY;
3626 push->base_work_group_id[2] = baseGroupZ;
3627
3628 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
3629 }
3630 }
3631
3632 void genX(CmdDispatch)(
3633 VkCommandBuffer commandBuffer,
3634 uint32_t x,
3635 uint32_t y,
3636 uint32_t z)
3637 {
3638 genX(CmdDispatchBase)(commandBuffer, 0, 0, 0, x, y, z);
3639 }
3640
3641 void genX(CmdDispatchBase)(
3642 VkCommandBuffer commandBuffer,
3643 uint32_t baseGroupX,
3644 uint32_t baseGroupY,
3645 uint32_t baseGroupZ,
3646 uint32_t groupCountX,
3647 uint32_t groupCountY,
3648 uint32_t groupCountZ)
3649 {
3650 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3651 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3652 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3653
3654 anv_cmd_buffer_push_base_group_id(cmd_buffer, baseGroupX,
3655 baseGroupY, baseGroupZ);
3656
3657 if (anv_batch_has_error(&cmd_buffer->batch))
3658 return;
3659
3660 if (prog_data->uses_num_work_groups) {
3661 struct anv_state state =
3662 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 12, 4);
3663 uint32_t *sizes = state.map;
3664 sizes[0] = groupCountX;
3665 sizes[1] = groupCountY;
3666 sizes[2] = groupCountZ;
3667 cmd_buffer->state.compute.num_workgroups = (struct anv_address) {
3668 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
3669 .offset = state.offset,
3670 };
3671 }
3672
3673 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3674
3675 if (cmd_buffer->state.conditional_render_enabled)
3676 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3677
3678 anv_batch_emit(&cmd_buffer->batch, GENX(GPGPU_WALKER), ggw) {
3679 ggw.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3680 ggw.SIMDSize = prog_data->simd_size / 16;
3681 ggw.ThreadDepthCounterMaximum = 0;
3682 ggw.ThreadHeightCounterMaximum = 0;
3683 ggw.ThreadWidthCounterMaximum = prog_data->threads - 1;
3684 ggw.ThreadGroupIDXDimension = groupCountX;
3685 ggw.ThreadGroupIDYDimension = groupCountY;
3686 ggw.ThreadGroupIDZDimension = groupCountZ;
3687 ggw.RightExecutionMask = pipeline->cs_right_mask;
3688 ggw.BottomExecutionMask = 0xffffffff;
3689 }
3690
3691 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_STATE_FLUSH), msf);
3692 }
3693
3694 #define GPGPU_DISPATCHDIMX 0x2500
3695 #define GPGPU_DISPATCHDIMY 0x2504
3696 #define GPGPU_DISPATCHDIMZ 0x2508
3697
3698 void genX(CmdDispatchIndirect)(
3699 VkCommandBuffer commandBuffer,
3700 VkBuffer _buffer,
3701 VkDeviceSize offset)
3702 {
3703 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3704 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3705 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3706 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3707 struct anv_address addr = anv_address_add(buffer->address, offset);
3708 struct anv_batch *batch = &cmd_buffer->batch;
3709
3710 anv_cmd_buffer_push_base_group_id(cmd_buffer, 0, 0, 0);
3711
3712 #if GEN_GEN == 7
3713 /* Linux 4.4 added command parser version 5 which allows the GPGPU
3714 * indirect dispatch registers to be written.
3715 */
3716 if (verify_cmd_parser(cmd_buffer->device, 5,
3717 "vkCmdDispatchIndirect") != VK_SUCCESS)
3718 return;
3719 #endif
3720
3721 if (prog_data->uses_num_work_groups)
3722 cmd_buffer->state.compute.num_workgroups = addr;
3723
3724 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3725
3726 struct gen_mi_builder b;
3727 gen_mi_builder_init(&b, &cmd_buffer->batch);
3728
3729 struct gen_mi_value size_x = gen_mi_mem32(anv_address_add(addr, 0));
3730 struct gen_mi_value size_y = gen_mi_mem32(anv_address_add(addr, 4));
3731 struct gen_mi_value size_z = gen_mi_mem32(anv_address_add(addr, 8));
3732
3733 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMX), size_x);
3734 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMY), size_y);
3735 gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMZ), size_z);
3736
3737 #if GEN_GEN <= 7
3738 /* predicate = (compute_dispatch_indirect_x_size == 0); */
3739 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), size_x);
3740 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3741 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3742 mip.LoadOperation = LOAD_LOAD;
3743 mip.CombineOperation = COMBINE_SET;
3744 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3745 }
3746
3747 /* predicate |= (compute_dispatch_indirect_y_size == 0); */
3748 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_y);
3749 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3750 mip.LoadOperation = LOAD_LOAD;
3751 mip.CombineOperation = COMBINE_OR;
3752 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3753 }
3754
3755 /* predicate |= (compute_dispatch_indirect_z_size == 0); */
3756 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_z);
3757 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3758 mip.LoadOperation = LOAD_LOAD;
3759 mip.CombineOperation = COMBINE_OR;
3760 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3761 }
3762
3763 /* predicate = !predicate; */
3764 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3765 mip.LoadOperation = LOAD_LOADINV;
3766 mip.CombineOperation = COMBINE_OR;
3767 mip.CompareOperation = COMPARE_FALSE;
3768 }
3769
3770 #if GEN_IS_HASWELL
3771 if (cmd_buffer->state.conditional_render_enabled) {
3772 /* predicate &= !(conditional_rendering_predicate == 0); */
3773 gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0),
3774 gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
3775 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3776 mip.LoadOperation = LOAD_LOADINV;
3777 mip.CombineOperation = COMBINE_AND;
3778 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3779 }
3780 }
3781 #endif
3782
3783 #else /* GEN_GEN > 7 */
3784 if (cmd_buffer->state.conditional_render_enabled)
3785 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3786 #endif
3787
3788 anv_batch_emit(batch, GENX(GPGPU_WALKER), ggw) {
3789 ggw.IndirectParameterEnable = true;
3790 ggw.PredicateEnable = GEN_GEN <= 7 ||
3791 cmd_buffer->state.conditional_render_enabled;
3792 ggw.SIMDSize = prog_data->simd_size / 16;
3793 ggw.ThreadDepthCounterMaximum = 0;
3794 ggw.ThreadHeightCounterMaximum = 0;
3795 ggw.ThreadWidthCounterMaximum = prog_data->threads - 1;
3796 ggw.RightExecutionMask = pipeline->cs_right_mask;
3797 ggw.BottomExecutionMask = 0xffffffff;
3798 }
3799
3800 anv_batch_emit(batch, GENX(MEDIA_STATE_FLUSH), msf);
3801 }
3802
3803 static void
3804 genX(flush_pipeline_select)(struct anv_cmd_buffer *cmd_buffer,
3805 uint32_t pipeline)
3806 {
3807 UNUSED const struct gen_device_info *devinfo = &cmd_buffer->device->info;
3808
3809 if (cmd_buffer->state.current_pipeline == pipeline)
3810 return;
3811
3812 #if GEN_GEN >= 8 && GEN_GEN < 10
3813 /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
3814 *
3815 * Software must clear the COLOR_CALC_STATE Valid field in
3816 * 3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
3817 * with Pipeline Select set to GPGPU.
3818 *
3819 * The internal hardware docs recommend the same workaround for Gen9
3820 * hardware too.
3821 */
3822 if (pipeline == GPGPU)
3823 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
3824 #endif
3825
3826 #if GEN_GEN == 9
3827 if (pipeline == _3D) {
3828 /* There is a mid-object preemption workaround which requires you to
3829 * re-emit MEDIA_VFE_STATE after switching from GPGPU to 3D. However,
3830 * even without preemption, we have issues with geometry flickering when
3831 * GPGPU and 3D are back-to-back and this seems to fix it. We don't
3832 * really know why.
3833 */
3834 const uint32_t subslices =
3835 MAX2(cmd_buffer->device->instance->physicalDevice.subslice_total, 1);
3836 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_VFE_STATE), vfe) {
3837 vfe.MaximumNumberofThreads =
3838 devinfo->max_cs_threads * subslices - 1;
3839 vfe.NumberofURBEntries = 2;
3840 vfe.URBEntryAllocationSize = 2;
3841 }
3842 }
3843 #endif
3844
3845 /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
3846 * PIPELINE_SELECT [DevBWR+]":
3847 *
3848 * Project: DEVSNB+
3849 *
3850 * Software must ensure all the write caches are flushed through a
3851 * stalling PIPE_CONTROL command followed by another PIPE_CONTROL
3852 * command to invalidate read only caches prior to programming
3853 * MI_PIPELINE_SELECT command to change the Pipeline Select Mode.
3854 */
3855 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
3856 pc.RenderTargetCacheFlushEnable = true;
3857 pc.DepthCacheFlushEnable = true;
3858 pc.DCFlushEnable = true;
3859 pc.PostSyncOperation = NoWrite;
3860 pc.CommandStreamerStallEnable = true;
3861 }
3862
3863 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
3864 pc.TextureCacheInvalidationEnable = true;
3865 pc.ConstantCacheInvalidationEnable = true;
3866 pc.StateCacheInvalidationEnable = true;
3867 pc.InstructionCacheInvalidateEnable = true;
3868 pc.PostSyncOperation = NoWrite;
3869 }
3870
3871 anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
3872 #if GEN_GEN >= 9
3873 ps.MaskBits = 3;
3874 #endif
3875 ps.PipelineSelection = pipeline;
3876 }
3877
3878 #if GEN_GEN == 9
3879 if (devinfo->is_geminilake) {
3880 /* Project: DevGLK
3881 *
3882 * "This chicken bit works around a hardware issue with barrier logic
3883 * encountered when switching between GPGPU and 3D pipelines. To
3884 * workaround the issue, this mode bit should be set after a pipeline
3885 * is selected."
3886 */
3887 uint32_t scec;
3888 anv_pack_struct(&scec, GENX(SLICE_COMMON_ECO_CHICKEN1),
3889 .GLKBarrierMode =
3890 pipeline == GPGPU ? GLK_BARRIER_MODE_GPGPU
3891 : GLK_BARRIER_MODE_3D_HULL,
3892 .GLKBarrierModeMask = 1);
3893 emit_lri(&cmd_buffer->batch, GENX(SLICE_COMMON_ECO_CHICKEN1_num), scec);
3894 }
3895 #endif
3896
3897 cmd_buffer->state.current_pipeline = pipeline;
3898 }
3899
3900 void
3901 genX(flush_pipeline_select_3d)(struct anv_cmd_buffer *cmd_buffer)
3902 {
3903 genX(flush_pipeline_select)(cmd_buffer, _3D);
3904 }
3905
3906 void
3907 genX(flush_pipeline_select_gpgpu)(struct anv_cmd_buffer *cmd_buffer)
3908 {
3909 genX(flush_pipeline_select)(cmd_buffer, GPGPU);
3910 }
3911
3912 void
3913 genX(cmd_buffer_emit_gen7_depth_flush)(struct anv_cmd_buffer *cmd_buffer)
3914 {
3915 if (GEN_GEN >= 8)
3916 return;
3917
3918 /* From the Haswell PRM, documentation for 3DSTATE_DEPTH_BUFFER:
3919 *
3920 * "Restriction: Prior to changing Depth/Stencil Buffer state (i.e., any
3921 * combination of 3DSTATE_DEPTH_BUFFER, 3DSTATE_CLEAR_PARAMS,
3922 * 3DSTATE_STENCIL_BUFFER, 3DSTATE_HIER_DEPTH_BUFFER) SW must first
3923 * issue a pipelined depth stall (PIPE_CONTROL with Depth Stall bit
3924 * set), followed by a pipelined depth cache flush (PIPE_CONTROL with
3925 * Depth Flush Bit set, followed by another pipelined depth stall
3926 * (PIPE_CONTROL with Depth Stall Bit set), unless SW can otherwise
3927 * guarantee that the pipeline from WM onwards is already flushed (e.g.,
3928 * via a preceding MI_FLUSH)."
3929 */
3930 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3931 pipe.DepthStallEnable = true;
3932 }
3933 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3934 pipe.DepthCacheFlushEnable = true;
3935 }
3936 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3937 pipe.DepthStallEnable = true;
3938 }
3939 }
3940
3941 /**
3942 * Update the pixel hashing modes that determine the balancing of PS threads
3943 * across subslices and slices.
3944 *
3945 * \param width Width bound of the rendering area (already scaled down if \p
3946 * scale is greater than 1).
3947 * \param height Height bound of the rendering area (already scaled down if \p
3948 * scale is greater than 1).
3949 * \param scale The number of framebuffer samples that could potentially be
3950 * affected by an individual channel of the PS thread. This is
3951 * typically one for single-sampled rendering, but for operations
3952 * like CCS resolves and fast clears a single PS invocation may
3953 * update a huge number of pixels, in which case a finer
3954 * balancing is desirable in order to maximally utilize the
3955 * bandwidth available. UINT_MAX can be used as shorthand for
3956 * "finest hashing mode available".
3957 */
3958 void
3959 genX(cmd_buffer_emit_hashing_mode)(struct anv_cmd_buffer *cmd_buffer,
3960 unsigned width, unsigned height,
3961 unsigned scale)
3962 {
3963 #if GEN_GEN == 9
3964 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
3965 const unsigned slice_hashing[] = {
3966 /* Because all Gen9 platforms with more than one slice require
3967 * three-way subslice hashing, a single "normal" 16x16 slice hashing
3968 * block is guaranteed to suffer from substantial imbalance, with one
3969 * subslice receiving twice as much work as the other two in the
3970 * slice.
3971 *
3972 * The performance impact of that would be particularly severe when
3973 * three-way hashing is also in use for slice balancing (which is the
3974 * case for all Gen9 GT4 platforms), because one of the slices
3975 * receives one every three 16x16 blocks in either direction, which
3976 * is roughly the periodicity of the underlying subslice imbalance
3977 * pattern ("roughly" because in reality the hardware's
3978 * implementation of three-way hashing doesn't do exact modulo 3
3979 * arithmetic, which somewhat decreases the magnitude of this effect
3980 * in practice). This leads to a systematic subslice imbalance
3981 * within that slice regardless of the size of the primitive. The
3982 * 32x32 hashing mode guarantees that the subslice imbalance within a
3983 * single slice hashing block is minimal, largely eliminating this
3984 * effect.
3985 */
3986 _32x32,
3987 /* Finest slice hashing mode available. */
3988 NORMAL
3989 };
3990 const unsigned subslice_hashing[] = {
3991 /* 16x16 would provide a slight cache locality benefit especially
3992 * visible in the sampler L1 cache efficiency of low-bandwidth
3993 * non-LLC platforms, but it comes at the cost of greater subslice
3994 * imbalance for primitives of dimensions approximately intermediate
3995 * between 16x4 and 16x16.
3996 */
3997 _16x4,
3998 /* Finest subslice hashing mode available. */
3999 _8x4
4000 };
4001 /* Dimensions of the smallest hashing block of a given hashing mode. If
4002 * the rendering area is smaller than this there can't possibly be any
4003 * benefit from switching to this mode, so we optimize out the
4004 * transition.
4005 */
4006 const unsigned min_size[][2] = {
4007 { 16, 4 },
4008 { 8, 4 }
4009 };
4010 const unsigned idx = scale > 1;
4011
4012 if (cmd_buffer->state.current_hash_scale != scale &&
4013 (width > min_size[idx][0] || height > min_size[idx][1])) {
4014 uint32_t gt_mode;
4015
4016 anv_pack_struct(&gt_mode, GENX(GT_MODE),
4017 .SliceHashing = (devinfo->num_slices > 1 ? slice_hashing[idx] : 0),
4018 .SliceHashingMask = (devinfo->num_slices > 1 ? -1 : 0),
4019 .SubsliceHashing = subslice_hashing[idx],
4020 .SubsliceHashingMask = -1);
4021
4022 cmd_buffer->state.pending_pipe_bits |=
4023 ANV_PIPE_CS_STALL_BIT | ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
4024 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4025
4026 emit_lri(&cmd_buffer->batch, GENX(GT_MODE_num), gt_mode);
4027
4028 cmd_buffer->state.current_hash_scale = scale;
4029 }
4030 #endif
4031 }
4032
4033 static void
4034 cmd_buffer_emit_depth_stencil(struct anv_cmd_buffer *cmd_buffer)
4035 {
4036 struct anv_device *device = cmd_buffer->device;
4037 const struct anv_image_view *iview =
4038 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
4039 const struct anv_image *image = iview ? iview->image : NULL;
4040
4041 /* FIXME: Width and Height are wrong */
4042
4043 genX(cmd_buffer_emit_gen7_depth_flush)(cmd_buffer);
4044
4045 uint32_t *dw = anv_batch_emit_dwords(&cmd_buffer->batch,
4046 device->isl_dev.ds.size / 4);
4047 if (dw == NULL)
4048 return;
4049
4050 struct isl_depth_stencil_hiz_emit_info info = { };
4051
4052 if (iview)
4053 info.view = &iview->planes[0].isl;
4054
4055 if (image && (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
4056 uint32_t depth_plane =
4057 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_DEPTH_BIT);
4058 const struct anv_surface *surface = &image->planes[depth_plane].surface;
4059
4060 info.depth_surf = &surface->isl;
4061
4062 info.depth_address =
4063 anv_batch_emit_reloc(&cmd_buffer->batch,
4064 dw + device->isl_dev.ds.depth_offset / 4,
4065 image->planes[depth_plane].address.bo,
4066 image->planes[depth_plane].address.offset +
4067 surface->offset);
4068 info.mocs =
4069 anv_mocs_for_bo(device, image->planes[depth_plane].address.bo);
4070
4071 const uint32_t ds =
4072 cmd_buffer->state.subpass->depth_stencil_attachment->attachment;
4073 info.hiz_usage = cmd_buffer->state.attachments[ds].aux_usage;
4074 if (info.hiz_usage == ISL_AUX_USAGE_HIZ) {
4075 info.hiz_surf = &image->planes[depth_plane].aux_surface.isl;
4076
4077 info.hiz_address =
4078 anv_batch_emit_reloc(&cmd_buffer->batch,
4079 dw + device->isl_dev.ds.hiz_offset / 4,
4080 image->planes[depth_plane].address.bo,
4081 image->planes[depth_plane].address.offset +
4082 image->planes[depth_plane].aux_surface.offset);
4083
4084 info.depth_clear_value = ANV_HZ_FC_VAL;
4085 }
4086 }
4087
4088 if (image && (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
4089 uint32_t stencil_plane =
4090 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_STENCIL_BIT);
4091 const struct anv_surface *surface = &image->planes[stencil_plane].surface;
4092
4093 info.stencil_surf = &surface->isl;
4094
4095 info.stencil_address =
4096 anv_batch_emit_reloc(&cmd_buffer->batch,
4097 dw + device->isl_dev.ds.stencil_offset / 4,
4098 image->planes[stencil_plane].address.bo,
4099 image->planes[stencil_plane].address.offset +
4100 surface->offset);
4101 info.mocs =
4102 anv_mocs_for_bo(device, image->planes[stencil_plane].address.bo);
4103 }
4104
4105 isl_emit_depth_stencil_hiz_s(&device->isl_dev, dw, &info);
4106
4107 cmd_buffer->state.hiz_enabled = info.hiz_usage == ISL_AUX_USAGE_HIZ;
4108 }
4109
4110 /**
4111 * This ANDs the view mask of the current subpass with the pending clear
4112 * views in the attachment to get the mask of views active in the subpass
4113 * that still need to be cleared.
4114 */
4115 static inline uint32_t
4116 get_multiview_subpass_clear_mask(const struct anv_cmd_state *cmd_state,
4117 const struct anv_attachment_state *att_state)
4118 {
4119 return cmd_state->subpass->view_mask & att_state->pending_clear_views;
4120 }
4121
4122 static inline bool
4123 do_first_layer_clear(const struct anv_cmd_state *cmd_state,
4124 const struct anv_attachment_state *att_state)
4125 {
4126 if (!cmd_state->subpass->view_mask)
4127 return true;
4128
4129 uint32_t pending_clear_mask =
4130 get_multiview_subpass_clear_mask(cmd_state, att_state);
4131
4132 return pending_clear_mask & 1;
4133 }
4134
4135 static inline bool
4136 current_subpass_is_last_for_attachment(const struct anv_cmd_state *cmd_state,
4137 uint32_t att_idx)
4138 {
4139 const uint32_t last_subpass_idx =
4140 cmd_state->pass->attachments[att_idx].last_subpass_idx;
4141 const struct anv_subpass *last_subpass =
4142 &cmd_state->pass->subpasses[last_subpass_idx];
4143 return last_subpass == cmd_state->subpass;
4144 }
4145
4146 static void
4147 cmd_buffer_begin_subpass(struct anv_cmd_buffer *cmd_buffer,
4148 uint32_t subpass_id)
4149 {
4150 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4151 struct anv_subpass *subpass = &cmd_state->pass->subpasses[subpass_id];
4152 cmd_state->subpass = subpass;
4153
4154 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
4155
4156 /* Our implementation of VK_KHR_multiview uses instancing to draw the
4157 * different views. If the client asks for instancing, we need to use the
4158 * Instance Data Step Rate to ensure that we repeat the client's
4159 * per-instance data once for each view. Since this bit is in
4160 * VERTEX_BUFFER_STATE on gen7, we need to dirty vertex buffers at the top
4161 * of each subpass.
4162 */
4163 if (GEN_GEN == 7)
4164 cmd_buffer->state.gfx.vb_dirty |= ~0;
4165
4166 /* It is possible to start a render pass with an old pipeline. Because the
4167 * render pass and subpass index are both baked into the pipeline, this is
4168 * highly unlikely. In order to do so, it requires that you have a render
4169 * pass with a single subpass and that you use that render pass twice
4170 * back-to-back and use the same pipeline at the start of the second render
4171 * pass as at the end of the first. In order to avoid unpredictable issues
4172 * with this edge case, we just dirty the pipeline at the start of every
4173 * subpass.
4174 */
4175 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_PIPELINE;
4176
4177 /* Accumulate any subpass flushes that need to happen before the subpass */
4178 cmd_buffer->state.pending_pipe_bits |=
4179 cmd_buffer->state.pass->subpass_flushes[subpass_id];
4180
4181 VkRect2D render_area = cmd_buffer->state.render_area;
4182 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
4183
4184 bool is_multiview = subpass->view_mask != 0;
4185
4186 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
4187 const uint32_t a = subpass->attachments[i].attachment;
4188 if (a == VK_ATTACHMENT_UNUSED)
4189 continue;
4190
4191 assert(a < cmd_state->pass->attachment_count);
4192 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
4193
4194 struct anv_image_view *iview = cmd_state->attachments[a].image_view;
4195 const struct anv_image *image = iview->image;
4196
4197 /* A resolve is necessary before use as an input attachment if the clear
4198 * color or auxiliary buffer usage isn't supported by the sampler.
4199 */
4200 const bool input_needs_resolve =
4201 (att_state->fast_clear && !att_state->clear_color_is_zero_one) ||
4202 att_state->input_aux_usage != att_state->aux_usage;
4203
4204 VkImageLayout target_layout;
4205 if (iview->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV &&
4206 !input_needs_resolve) {
4207 /* Layout transitions before the final only help to enable sampling
4208 * as an input attachment. If the input attachment supports sampling
4209 * using the auxiliary surface, we can skip such transitions by
4210 * making the target layout one that is CCS-aware.
4211 */
4212 target_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
4213 } else {
4214 target_layout = subpass->attachments[i].layout;
4215 }
4216
4217 uint32_t base_layer, layer_count;
4218 if (image->type == VK_IMAGE_TYPE_3D) {
4219 base_layer = 0;
4220 layer_count = anv_minify(iview->image->extent.depth,
4221 iview->planes[0].isl.base_level);
4222 } else {
4223 base_layer = iview->planes[0].isl.base_array_layer;
4224 layer_count = fb->layers;
4225 }
4226
4227 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
4228 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4229 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4230 iview->planes[0].isl.base_level, 1,
4231 base_layer, layer_count,
4232 att_state->current_layout, target_layout);
4233 }
4234
4235 if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4236 transition_depth_buffer(cmd_buffer, image,
4237 att_state->current_layout, target_layout);
4238 att_state->aux_usage =
4239 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
4240 VK_IMAGE_ASPECT_DEPTH_BIT, target_layout);
4241 }
4242
4243 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
4244 transition_stencil_buffer(cmd_buffer, image,
4245 iview->planes[0].isl.base_level, 1,
4246 base_layer, layer_count,
4247 att_state->current_layout, target_layout);
4248 }
4249 att_state->current_layout = target_layout;
4250
4251 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
4252 assert(att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4253
4254 /* Multi-planar images are not supported as attachments */
4255 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4256 assert(image->n_planes == 1);
4257
4258 uint32_t base_clear_layer = iview->planes[0].isl.base_array_layer;
4259 uint32_t clear_layer_count = fb->layers;
4260
4261 if (att_state->fast_clear &&
4262 do_first_layer_clear(cmd_state, att_state)) {
4263 /* We only support fast-clears on the first layer */
4264 assert(iview->planes[0].isl.base_level == 0);
4265 assert(iview->planes[0].isl.base_array_layer == 0);
4266
4267 union isl_color_value clear_color = {};
4268 anv_clear_color_from_att_state(&clear_color, att_state, iview);
4269 if (iview->image->samples == 1) {
4270 anv_image_ccs_op(cmd_buffer, image,
4271 iview->planes[0].isl.format,
4272 VK_IMAGE_ASPECT_COLOR_BIT,
4273 0, 0, 1, ISL_AUX_OP_FAST_CLEAR,
4274 &clear_color,
4275 false);
4276 } else {
4277 anv_image_mcs_op(cmd_buffer, image,
4278 iview->planes[0].isl.format,
4279 VK_IMAGE_ASPECT_COLOR_BIT,
4280 0, 1, ISL_AUX_OP_FAST_CLEAR,
4281 &clear_color,
4282 false);
4283 }
4284 base_clear_layer++;
4285 clear_layer_count--;
4286 if (is_multiview)
4287 att_state->pending_clear_views &= ~1;
4288
4289 if (att_state->clear_color_is_zero) {
4290 /* This image has the auxiliary buffer enabled. We can mark the
4291 * subresource as not needing a resolve because the clear color
4292 * will match what's in every RENDER_SURFACE_STATE object when
4293 * it's being used for sampling.
4294 */
4295 set_image_fast_clear_state(cmd_buffer, iview->image,
4296 VK_IMAGE_ASPECT_COLOR_BIT,
4297 ANV_FAST_CLEAR_DEFAULT_VALUE);
4298 } else {
4299 set_image_fast_clear_state(cmd_buffer, iview->image,
4300 VK_IMAGE_ASPECT_COLOR_BIT,
4301 ANV_FAST_CLEAR_ANY);
4302 }
4303 }
4304
4305 /* From the VkFramebufferCreateInfo spec:
4306 *
4307 * "If the render pass uses multiview, then layers must be one and each
4308 * attachment requires a number of layers that is greater than the
4309 * maximum bit index set in the view mask in the subpasses in which it
4310 * is used."
4311 *
4312 * So if multiview is active we ignore the number of layers in the
4313 * framebuffer and instead we honor the view mask from the subpass.
4314 */
4315 if (is_multiview) {
4316 assert(image->n_planes == 1);
4317 uint32_t pending_clear_mask =
4318 get_multiview_subpass_clear_mask(cmd_state, att_state);
4319
4320 uint32_t layer_idx;
4321 for_each_bit(layer_idx, pending_clear_mask) {
4322 uint32_t layer =
4323 iview->planes[0].isl.base_array_layer + layer_idx;
4324
4325 anv_image_clear_color(cmd_buffer, image,
4326 VK_IMAGE_ASPECT_COLOR_BIT,
4327 att_state->aux_usage,
4328 iview->planes[0].isl.format,
4329 iview->planes[0].isl.swizzle,
4330 iview->planes[0].isl.base_level,
4331 layer, 1,
4332 render_area,
4333 vk_to_isl_color(att_state->clear_value.color));
4334 }
4335
4336 att_state->pending_clear_views &= ~pending_clear_mask;
4337 } else if (clear_layer_count > 0) {
4338 assert(image->n_planes == 1);
4339 anv_image_clear_color(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4340 att_state->aux_usage,
4341 iview->planes[0].isl.format,
4342 iview->planes[0].isl.swizzle,
4343 iview->planes[0].isl.base_level,
4344 base_clear_layer, clear_layer_count,
4345 render_area,
4346 vk_to_isl_color(att_state->clear_value.color));
4347 }
4348 } else if (att_state->pending_clear_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT |
4349 VK_IMAGE_ASPECT_STENCIL_BIT)) {
4350 if (att_state->fast_clear && !is_multiview) {
4351 /* We currently only support HiZ for single-layer images */
4352 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4353 assert(iview->image->planes[0].aux_usage == ISL_AUX_USAGE_HIZ);
4354 assert(iview->planes[0].isl.base_level == 0);
4355 assert(iview->planes[0].isl.base_array_layer == 0);
4356 assert(fb->layers == 1);
4357 }
4358
4359 anv_image_hiz_clear(cmd_buffer, image,
4360 att_state->pending_clear_aspects,
4361 iview->planes[0].isl.base_level,
4362 iview->planes[0].isl.base_array_layer,
4363 fb->layers, render_area,
4364 att_state->clear_value.depthStencil.stencil);
4365 } else if (is_multiview) {
4366 uint32_t pending_clear_mask =
4367 get_multiview_subpass_clear_mask(cmd_state, att_state);
4368
4369 uint32_t layer_idx;
4370 for_each_bit(layer_idx, pending_clear_mask) {
4371 uint32_t layer =
4372 iview->planes[0].isl.base_array_layer + layer_idx;
4373
4374 anv_image_clear_depth_stencil(cmd_buffer, image,
4375 att_state->pending_clear_aspects,
4376 att_state->aux_usage,
4377 iview->planes[0].isl.base_level,
4378 layer, 1,
4379 render_area,
4380 att_state->clear_value.depthStencil.depth,
4381 att_state->clear_value.depthStencil.stencil);
4382 }
4383
4384 att_state->pending_clear_views &= ~pending_clear_mask;
4385 } else {
4386 anv_image_clear_depth_stencil(cmd_buffer, image,
4387 att_state->pending_clear_aspects,
4388 att_state->aux_usage,
4389 iview->planes[0].isl.base_level,
4390 iview->planes[0].isl.base_array_layer,
4391 fb->layers, render_area,
4392 att_state->clear_value.depthStencil.depth,
4393 att_state->clear_value.depthStencil.stencil);
4394 }
4395 } else {
4396 assert(att_state->pending_clear_aspects == 0);
4397 }
4398
4399 if (GEN_GEN < 10 &&
4400 (att_state->pending_load_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
4401 image->planes[0].aux_surface.isl.size_B > 0 &&
4402 iview->planes[0].isl.base_level == 0 &&
4403 iview->planes[0].isl.base_array_layer == 0) {
4404 if (att_state->aux_usage != ISL_AUX_USAGE_NONE) {
4405 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->color.state,
4406 image, VK_IMAGE_ASPECT_COLOR_BIT,
4407 false /* copy to ss */);
4408 }
4409
4410 if (need_input_attachment_state(&cmd_state->pass->attachments[a]) &&
4411 att_state->input_aux_usage != ISL_AUX_USAGE_NONE) {
4412 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->input.state,
4413 image, VK_IMAGE_ASPECT_COLOR_BIT,
4414 false /* copy to ss */);
4415 }
4416 }
4417
4418 if (subpass->attachments[i].usage ==
4419 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
4420 /* We assume that if we're starting a subpass, we're going to do some
4421 * rendering so we may end up with compressed data.
4422 */
4423 genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
4424 VK_IMAGE_ASPECT_COLOR_BIT,
4425 att_state->aux_usage,
4426 iview->planes[0].isl.base_level,
4427 iview->planes[0].isl.base_array_layer,
4428 fb->layers);
4429 } else if (subpass->attachments[i].usage ==
4430 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
4431 /* We may be writing depth or stencil so we need to mark the surface.
4432 * Unfortunately, there's no way to know at this point whether the
4433 * depth or stencil tests used will actually write to the surface.
4434 *
4435 * Even though stencil may be plane 1, it always shares a base_level
4436 * with depth.
4437 */
4438 const struct isl_view *ds_view = &iview->planes[0].isl;
4439 if (iview->aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
4440 genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
4441 VK_IMAGE_ASPECT_DEPTH_BIT,
4442 att_state->aux_usage,
4443 ds_view->base_level,
4444 ds_view->base_array_layer,
4445 fb->layers);
4446 }
4447 if (iview->aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
4448 /* Even though stencil may be plane 1, it always shares a
4449 * base_level with depth.
4450 */
4451 genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
4452 VK_IMAGE_ASPECT_STENCIL_BIT,
4453 ISL_AUX_USAGE_NONE,
4454 ds_view->base_level,
4455 ds_view->base_array_layer,
4456 fb->layers);
4457 }
4458 }
4459
4460 /* If multiview is enabled, then we are only done clearing when we no
4461 * longer have pending layers to clear, or when we have processed the
4462 * last subpass that uses this attachment.
4463 */
4464 if (!is_multiview ||
4465 att_state->pending_clear_views == 0 ||
4466 current_subpass_is_last_for_attachment(cmd_state, a)) {
4467 att_state->pending_clear_aspects = 0;
4468 }
4469
4470 att_state->pending_load_aspects = 0;
4471 }
4472
4473 cmd_buffer_emit_depth_stencil(cmd_buffer);
4474 }
4475
4476 static enum blorp_filter
4477 vk_to_blorp_resolve_mode(VkResolveModeFlagBitsKHR vk_mode)
4478 {
4479 switch (vk_mode) {
4480 case VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR:
4481 return BLORP_FILTER_SAMPLE_0;
4482 case VK_RESOLVE_MODE_AVERAGE_BIT_KHR:
4483 return BLORP_FILTER_AVERAGE;
4484 case VK_RESOLVE_MODE_MIN_BIT_KHR:
4485 return BLORP_FILTER_MIN_SAMPLE;
4486 case VK_RESOLVE_MODE_MAX_BIT_KHR:
4487 return BLORP_FILTER_MAX_SAMPLE;
4488 default:
4489 return BLORP_FILTER_NONE;
4490 }
4491 }
4492
4493 static void
4494 cmd_buffer_end_subpass(struct anv_cmd_buffer *cmd_buffer)
4495 {
4496 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4497 struct anv_subpass *subpass = cmd_state->subpass;
4498 uint32_t subpass_id = anv_get_subpass_id(&cmd_buffer->state);
4499 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
4500
4501 if (subpass->has_color_resolve) {
4502 /* We are about to do some MSAA resolves. We need to flush so that the
4503 * result of writes to the MSAA color attachments show up in the sampler
4504 * when we blit to the single-sampled resolve target.
4505 */
4506 cmd_buffer->state.pending_pipe_bits |=
4507 ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
4508 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
4509
4510 for (uint32_t i = 0; i < subpass->color_count; ++i) {
4511 uint32_t src_att = subpass->color_attachments[i].attachment;
4512 uint32_t dst_att = subpass->resolve_attachments[i].attachment;
4513
4514 if (dst_att == VK_ATTACHMENT_UNUSED)
4515 continue;
4516
4517 assert(src_att < cmd_buffer->state.pass->attachment_count);
4518 assert(dst_att < cmd_buffer->state.pass->attachment_count);
4519
4520 if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
4521 /* From the Vulkan 1.0 spec:
4522 *
4523 * If the first use of an attachment in a render pass is as a
4524 * resolve attachment, then the loadOp is effectively ignored
4525 * as the resolve is guaranteed to overwrite all pixels in the
4526 * render area.
4527 */
4528 cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
4529 }
4530
4531 struct anv_image_view *src_iview = cmd_state->attachments[src_att].image_view;
4532 struct anv_image_view *dst_iview = cmd_state->attachments[dst_att].image_view;
4533
4534 const VkRect2D render_area = cmd_buffer->state.render_area;
4535
4536 enum isl_aux_usage src_aux_usage =
4537 cmd_buffer->state.attachments[src_att].aux_usage;
4538 enum isl_aux_usage dst_aux_usage =
4539 cmd_buffer->state.attachments[dst_att].aux_usage;
4540
4541 assert(src_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT &&
4542 dst_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT);
4543
4544 anv_image_msaa_resolve(cmd_buffer,
4545 src_iview->image, src_aux_usage,
4546 src_iview->planes[0].isl.base_level,
4547 src_iview->planes[0].isl.base_array_layer,
4548 dst_iview->image, dst_aux_usage,
4549 dst_iview->planes[0].isl.base_level,
4550 dst_iview->planes[0].isl.base_array_layer,
4551 VK_IMAGE_ASPECT_COLOR_BIT,
4552 render_area.offset.x, render_area.offset.y,
4553 render_area.offset.x, render_area.offset.y,
4554 render_area.extent.width,
4555 render_area.extent.height,
4556 fb->layers, BLORP_FILTER_NONE);
4557 }
4558 }
4559
4560 if (subpass->ds_resolve_attachment) {
4561 /* We are about to do some MSAA resolves. We need to flush so that the
4562 * result of writes to the MSAA depth attachments show up in the sampler
4563 * when we blit to the single-sampled resolve target.
4564 */
4565 cmd_buffer->state.pending_pipe_bits |=
4566 ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
4567 ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
4568
4569 uint32_t src_att = subpass->depth_stencil_attachment->attachment;
4570 uint32_t dst_att = subpass->ds_resolve_attachment->attachment;
4571
4572 assert(src_att < cmd_buffer->state.pass->attachment_count);
4573 assert(dst_att < cmd_buffer->state.pass->attachment_count);
4574
4575 if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
4576 /* From the Vulkan 1.0 spec:
4577 *
4578 * If the first use of an attachment in a render pass is as a
4579 * resolve attachment, then the loadOp is effectively ignored
4580 * as the resolve is guaranteed to overwrite all pixels in the
4581 * render area.
4582 */
4583 cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
4584 }
4585
4586 struct anv_image_view *src_iview = cmd_state->attachments[src_att].image_view;
4587 struct anv_image_view *dst_iview = cmd_state->attachments[dst_att].image_view;
4588
4589 const VkRect2D render_area = cmd_buffer->state.render_area;
4590
4591 if ((src_iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4592 subpass->depth_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
4593
4594 struct anv_attachment_state *src_state =
4595 &cmd_state->attachments[src_att];
4596 struct anv_attachment_state *dst_state =
4597 &cmd_state->attachments[dst_att];
4598
4599 /* MSAA resolves sample from the source attachment. Transition the
4600 * depth attachment first to get rid of any HiZ that we may not be
4601 * able to handle.
4602 */
4603 transition_depth_buffer(cmd_buffer, src_iview->image,
4604 src_state->current_layout,
4605 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
4606 src_state->aux_usage =
4607 anv_layout_to_aux_usage(&cmd_buffer->device->info, src_iview->image,
4608 VK_IMAGE_ASPECT_DEPTH_BIT,
4609 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
4610 src_state->current_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
4611
4612 /* MSAA resolves write to the resolve attachment as if it were any
4613 * other transfer op. Transition the resolve attachment accordingly.
4614 */
4615 VkImageLayout dst_initial_layout = dst_state->current_layout;
4616
4617 /* If our render area is the entire size of the image, we're going to
4618 * blow it all away so we can claim the initial layout is UNDEFINED
4619 * and we'll get a HiZ ambiguate instead of a resolve.
4620 */
4621 if (dst_iview->image->type != VK_IMAGE_TYPE_3D &&
4622 render_area.offset.x == 0 && render_area.offset.y == 0 &&
4623 render_area.extent.width == dst_iview->extent.width &&
4624 render_area.extent.height == dst_iview->extent.height)
4625 dst_initial_layout = VK_IMAGE_LAYOUT_UNDEFINED;
4626
4627 transition_depth_buffer(cmd_buffer, dst_iview->image,
4628 dst_initial_layout,
4629 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
4630 dst_state->aux_usage =
4631 anv_layout_to_aux_usage(&cmd_buffer->device->info, dst_iview->image,
4632 VK_IMAGE_ASPECT_DEPTH_BIT,
4633 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
4634 dst_state->current_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
4635
4636 enum blorp_filter filter =
4637 vk_to_blorp_resolve_mode(subpass->depth_resolve_mode);
4638
4639 anv_image_msaa_resolve(cmd_buffer,
4640 src_iview->image, src_state->aux_usage,
4641 src_iview->planes[0].isl.base_level,
4642 src_iview->planes[0].isl.base_array_layer,
4643 dst_iview->image, dst_state->aux_usage,
4644 dst_iview->planes[0].isl.base_level,
4645 dst_iview->planes[0].isl.base_array_layer,
4646 VK_IMAGE_ASPECT_DEPTH_BIT,
4647 render_area.offset.x, render_area.offset.y,
4648 render_area.offset.x, render_area.offset.y,
4649 render_area.extent.width,
4650 render_area.extent.height,
4651 fb->layers, filter);
4652 }
4653
4654 if ((src_iview->image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
4655 subpass->stencil_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
4656
4657 enum isl_aux_usage src_aux_usage = ISL_AUX_USAGE_NONE;
4658 enum isl_aux_usage dst_aux_usage = ISL_AUX_USAGE_NONE;
4659
4660 enum blorp_filter filter =
4661 vk_to_blorp_resolve_mode(subpass->stencil_resolve_mode);
4662
4663 anv_image_msaa_resolve(cmd_buffer,
4664 src_iview->image, src_aux_usage,
4665 src_iview->planes[0].isl.base_level,
4666 src_iview->planes[0].isl.base_array_layer,
4667 dst_iview->image, dst_aux_usage,
4668 dst_iview->planes[0].isl.base_level,
4669 dst_iview->planes[0].isl.base_array_layer,
4670 VK_IMAGE_ASPECT_STENCIL_BIT,
4671 render_area.offset.x, render_area.offset.y,
4672 render_area.offset.x, render_area.offset.y,
4673 render_area.extent.width,
4674 render_area.extent.height,
4675 fb->layers, filter);
4676 }
4677 }
4678
4679 #if GEN_GEN == 7
4680 /* On gen7, we have to store a texturable version of the stencil buffer in
4681 * a shadow whenever VK_IMAGE_USAGE_SAMPLED_BIT is set and copy back and
4682 * forth at strategic points. Stencil writes are only allowed in three
4683 * layouts:
4684 *
4685 * - VK_IMAGE_LAYOUT_GENERAL
4686 * - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
4687 * - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
4688 * - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL
4689 *
4690 * For general, we have no nice opportunity to transition so we do the copy
4691 * to the shadow unconditionally at the end of the subpass. For transfer
4692 * destinations, we can update it as part of the transfer op. For the
4693 * other two, we delay the copy until a transition into some other layout.
4694 */
4695 if (subpass->depth_stencil_attachment) {
4696 uint32_t a = subpass->depth_stencil_attachment->attachment;
4697 assert(a != VK_ATTACHMENT_UNUSED);
4698
4699 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
4700 struct anv_image_view *iview = cmd_state->attachments[a].image_view;;
4701 const struct anv_image *image = iview->image;
4702
4703 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
4704 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
4705 VK_IMAGE_ASPECT_STENCIL_BIT);
4706
4707 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
4708 att_state->current_layout == VK_IMAGE_LAYOUT_GENERAL) {
4709 assert(image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT);
4710 anv_image_copy_to_shadow(cmd_buffer, image,
4711 VK_IMAGE_ASPECT_STENCIL_BIT,
4712 iview->planes[plane].isl.base_level, 1,
4713 iview->planes[plane].isl.base_array_layer,
4714 fb->layers);
4715 }
4716 }
4717 }
4718 #endif /* GEN_GEN == 7 */
4719
4720 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
4721 const uint32_t a = subpass->attachments[i].attachment;
4722 if (a == VK_ATTACHMENT_UNUSED)
4723 continue;
4724
4725 if (cmd_state->pass->attachments[a].last_subpass_idx != subpass_id)
4726 continue;
4727
4728 assert(a < cmd_state->pass->attachment_count);
4729 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
4730 struct anv_image_view *iview = cmd_state->attachments[a].image_view;
4731 const struct anv_image *image = iview->image;
4732
4733 if ((image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
4734 image->vk_format != iview->vk_format) {
4735 enum anv_fast_clear_type fast_clear_type =
4736 anv_layout_to_fast_clear_type(&cmd_buffer->device->info,
4737 image, VK_IMAGE_ASPECT_COLOR_BIT,
4738 att_state->current_layout);
4739
4740 /* If any clear color was used, flush it down the aux surfaces. If we
4741 * don't do it now using the view's format we might use the clear
4742 * color incorrectly in the following resolves (for example with an
4743 * SRGB view & a UNORM image).
4744 */
4745 if (fast_clear_type != ANV_FAST_CLEAR_NONE) {
4746 anv_perf_warn(cmd_buffer->device->instance, iview,
4747 "Doing a partial resolve to get rid of clear color at the "
4748 "end of a renderpass due to an image/view format mismatch");
4749
4750 uint32_t base_layer, layer_count;
4751 if (image->type == VK_IMAGE_TYPE_3D) {
4752 base_layer = 0;
4753 layer_count = anv_minify(iview->image->extent.depth,
4754 iview->planes[0].isl.base_level);
4755 } else {
4756 base_layer = iview->planes[0].isl.base_array_layer;
4757 layer_count = fb->layers;
4758 }
4759
4760 for (uint32_t a = 0; a < layer_count; a++) {
4761 uint32_t array_layer = base_layer + a;
4762 if (image->samples == 1) {
4763 anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
4764 iview->planes[0].isl.format,
4765 VK_IMAGE_ASPECT_COLOR_BIT,
4766 iview->planes[0].isl.base_level,
4767 array_layer,
4768 ISL_AUX_OP_PARTIAL_RESOLVE,
4769 ANV_FAST_CLEAR_NONE);
4770 } else {
4771 anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
4772 iview->planes[0].isl.format,
4773 VK_IMAGE_ASPECT_COLOR_BIT,
4774 base_layer,
4775 ISL_AUX_OP_PARTIAL_RESOLVE,
4776 ANV_FAST_CLEAR_NONE);
4777 }
4778 }
4779 }
4780 }
4781
4782 /* Transition the image into the final layout for this render pass */
4783 VkImageLayout target_layout =
4784 cmd_state->pass->attachments[a].final_layout;
4785
4786 uint32_t base_layer, layer_count;
4787 if (image->type == VK_IMAGE_TYPE_3D) {
4788 base_layer = 0;
4789 layer_count = anv_minify(iview->image->extent.depth,
4790 iview->planes[0].isl.base_level);
4791 } else {
4792 base_layer = iview->planes[0].isl.base_array_layer;
4793 layer_count = fb->layers;
4794 }
4795
4796 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
4797 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4798 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4799 iview->planes[0].isl.base_level, 1,
4800 base_layer, layer_count,
4801 att_state->current_layout, target_layout);
4802 }
4803
4804 if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4805 transition_depth_buffer(cmd_buffer, image,
4806 att_state->current_layout, target_layout);
4807 }
4808
4809 if (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
4810 transition_stencil_buffer(cmd_buffer, image,
4811 iview->planes[0].isl.base_level, 1,
4812 base_layer, layer_count,
4813 att_state->current_layout, target_layout);
4814 }
4815 }
4816
4817 /* Accumulate any subpass flushes that need to happen after the subpass.
4818 * Yes, they do get accumulated twice in the NextSubpass case but since
4819 * genX_CmdNextSubpass just calls end/begin back-to-back, we just end up
4820 * ORing the bits in twice so it's harmless.
4821 */
4822 cmd_buffer->state.pending_pipe_bits |=
4823 cmd_buffer->state.pass->subpass_flushes[subpass_id + 1];
4824 }
4825
4826 void genX(CmdBeginRenderPass)(
4827 VkCommandBuffer commandBuffer,
4828 const VkRenderPassBeginInfo* pRenderPassBegin,
4829 VkSubpassContents contents)
4830 {
4831 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4832 ANV_FROM_HANDLE(anv_render_pass, pass, pRenderPassBegin->renderPass);
4833 ANV_FROM_HANDLE(anv_framebuffer, framebuffer, pRenderPassBegin->framebuffer);
4834
4835 cmd_buffer->state.framebuffer = framebuffer;
4836 cmd_buffer->state.pass = pass;
4837 cmd_buffer->state.render_area = pRenderPassBegin->renderArea;
4838 VkResult result =
4839 genX(cmd_buffer_setup_attachments)(cmd_buffer, pass, pRenderPassBegin);
4840
4841 /* If we failed to setup the attachments we should not try to go further */
4842 if (result != VK_SUCCESS) {
4843 assert(anv_batch_has_error(&cmd_buffer->batch));
4844 return;
4845 }
4846
4847 genX(flush_pipeline_select_3d)(cmd_buffer);
4848
4849 cmd_buffer_begin_subpass(cmd_buffer, 0);
4850 }
4851
4852 void genX(CmdBeginRenderPass2KHR)(
4853 VkCommandBuffer commandBuffer,
4854 const VkRenderPassBeginInfo* pRenderPassBeginInfo,
4855 const VkSubpassBeginInfoKHR* pSubpassBeginInfo)
4856 {
4857 genX(CmdBeginRenderPass)(commandBuffer, pRenderPassBeginInfo,
4858 pSubpassBeginInfo->contents);
4859 }
4860
4861 void genX(CmdNextSubpass)(
4862 VkCommandBuffer commandBuffer,
4863 VkSubpassContents contents)
4864 {
4865 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4866
4867 if (anv_batch_has_error(&cmd_buffer->batch))
4868 return;
4869
4870 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4871
4872 uint32_t prev_subpass = anv_get_subpass_id(&cmd_buffer->state);
4873 cmd_buffer_end_subpass(cmd_buffer);
4874 cmd_buffer_begin_subpass(cmd_buffer, prev_subpass + 1);
4875 }
4876
4877 void genX(CmdNextSubpass2KHR)(
4878 VkCommandBuffer commandBuffer,
4879 const VkSubpassBeginInfoKHR* pSubpassBeginInfo,
4880 const VkSubpassEndInfoKHR* pSubpassEndInfo)
4881 {
4882 genX(CmdNextSubpass)(commandBuffer, pSubpassBeginInfo->contents);
4883 }
4884
4885 void genX(CmdEndRenderPass)(
4886 VkCommandBuffer commandBuffer)
4887 {
4888 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4889
4890 if (anv_batch_has_error(&cmd_buffer->batch))
4891 return;
4892
4893 cmd_buffer_end_subpass(cmd_buffer);
4894
4895 cmd_buffer->state.hiz_enabled = false;
4896
4897 #ifndef NDEBUG
4898 anv_dump_add_attachments(cmd_buffer);
4899 #endif
4900
4901 /* Remove references to render pass specific state. This enables us to
4902 * detect whether or not we're in a renderpass.
4903 */
4904 cmd_buffer->state.framebuffer = NULL;
4905 cmd_buffer->state.pass = NULL;
4906 cmd_buffer->state.subpass = NULL;
4907 }
4908
4909 void genX(CmdEndRenderPass2KHR)(
4910 VkCommandBuffer commandBuffer,
4911 const VkSubpassEndInfoKHR* pSubpassEndInfo)
4912 {
4913 genX(CmdEndRenderPass)(commandBuffer);
4914 }
4915
4916 void
4917 genX(cmd_emit_conditional_render_predicate)(struct anv_cmd_buffer *cmd_buffer)
4918 {
4919 #if GEN_GEN >= 8 || GEN_IS_HASWELL
4920 struct gen_mi_builder b;
4921 gen_mi_builder_init(&b, &cmd_buffer->batch);
4922
4923 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
4924 gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
4925 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
4926
4927 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
4928 mip.LoadOperation = LOAD_LOADINV;
4929 mip.CombineOperation = COMBINE_SET;
4930 mip.CompareOperation = COMPARE_SRCS_EQUAL;
4931 }
4932 #endif
4933 }
4934
4935 #if GEN_GEN >= 8 || GEN_IS_HASWELL
4936 void genX(CmdBeginConditionalRenderingEXT)(
4937 VkCommandBuffer commandBuffer,
4938 const VkConditionalRenderingBeginInfoEXT* pConditionalRenderingBegin)
4939 {
4940 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4941 ANV_FROM_HANDLE(anv_buffer, buffer, pConditionalRenderingBegin->buffer);
4942 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4943 struct anv_address value_address =
4944 anv_address_add(buffer->address, pConditionalRenderingBegin->offset);
4945
4946 const bool isInverted = pConditionalRenderingBegin->flags &
4947 VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT;
4948
4949 cmd_state->conditional_render_enabled = true;
4950
4951 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4952
4953 struct gen_mi_builder b;
4954 gen_mi_builder_init(&b, &cmd_buffer->batch);
4955
4956 /* Section 19.4 of the Vulkan 1.1.85 spec says:
4957 *
4958 * If the value of the predicate in buffer memory changes
4959 * while conditional rendering is active, the rendering commands
4960 * may be discarded in an implementation-dependent way.
4961 * Some implementations may latch the value of the predicate
4962 * upon beginning conditional rendering while others
4963 * may read it before every rendering command.
4964 *
4965 * So it's perfectly fine to read a value from the buffer once.
4966 */
4967 struct gen_mi_value value = gen_mi_mem32(value_address);
4968
4969 /* Precompute predicate result, it is necessary to support secondary
4970 * command buffers since it is unknown if conditional rendering is
4971 * inverted when populating them.
4972 */
4973 gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
4974 isInverted ? gen_mi_uge(&b, gen_mi_imm(0), value) :
4975 gen_mi_ult(&b, gen_mi_imm(0), value));
4976 }
4977
4978 void genX(CmdEndConditionalRenderingEXT)(
4979 VkCommandBuffer commandBuffer)
4980 {
4981 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4982 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4983
4984 cmd_state->conditional_render_enabled = false;
4985 }
4986 #endif
4987
4988 /* Set of stage bits for which are pipelined, i.e. they get queued by the
4989 * command streamer for later execution.
4990 */
4991 #define ANV_PIPELINE_STAGE_PIPELINED_BITS \
4992 (VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | \
4993 VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | \
4994 VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | \
4995 VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | \
4996 VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | \
4997 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | \
4998 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | \
4999 VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | \
5000 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | \
5001 VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | \
5002 VK_PIPELINE_STAGE_TRANSFER_BIT | \
5003 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | \
5004 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | \
5005 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)
5006
5007 void genX(CmdSetEvent)(
5008 VkCommandBuffer commandBuffer,
5009 VkEvent _event,
5010 VkPipelineStageFlags stageMask)
5011 {
5012 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5013 ANV_FROM_HANDLE(anv_event, event, _event);
5014
5015 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
5016 if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
5017 pc.StallAtPixelScoreboard = true;
5018 pc.CommandStreamerStallEnable = true;
5019 }
5020
5021 pc.DestinationAddressType = DAT_PPGTT,
5022 pc.PostSyncOperation = WriteImmediateData,
5023 pc.Address = (struct anv_address) {
5024 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5025 event->state.offset
5026 };
5027 pc.ImmediateData = VK_EVENT_SET;
5028 }
5029 }
5030
5031 void genX(CmdResetEvent)(
5032 VkCommandBuffer commandBuffer,
5033 VkEvent _event,
5034 VkPipelineStageFlags stageMask)
5035 {
5036 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5037 ANV_FROM_HANDLE(anv_event, event, _event);
5038
5039 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
5040 if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
5041 pc.StallAtPixelScoreboard = true;
5042 pc.CommandStreamerStallEnable = true;
5043 }
5044
5045 pc.DestinationAddressType = DAT_PPGTT;
5046 pc.PostSyncOperation = WriteImmediateData;
5047 pc.Address = (struct anv_address) {
5048 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5049 event->state.offset
5050 };
5051 pc.ImmediateData = VK_EVENT_RESET;
5052 }
5053 }
5054
5055 void genX(CmdWaitEvents)(
5056 VkCommandBuffer commandBuffer,
5057 uint32_t eventCount,
5058 const VkEvent* pEvents,
5059 VkPipelineStageFlags srcStageMask,
5060 VkPipelineStageFlags destStageMask,
5061 uint32_t memoryBarrierCount,
5062 const VkMemoryBarrier* pMemoryBarriers,
5063 uint32_t bufferMemoryBarrierCount,
5064 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
5065 uint32_t imageMemoryBarrierCount,
5066 const VkImageMemoryBarrier* pImageMemoryBarriers)
5067 {
5068 #if GEN_GEN >= 8
5069 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
5070
5071 for (uint32_t i = 0; i < eventCount; i++) {
5072 ANV_FROM_HANDLE(anv_event, event, pEvents[i]);
5073
5074 anv_batch_emit(&cmd_buffer->batch, GENX(MI_SEMAPHORE_WAIT), sem) {
5075 sem.WaitMode = PollingMode,
5076 sem.CompareOperation = COMPARE_SAD_EQUAL_SDD,
5077 sem.SemaphoreDataDword = VK_EVENT_SET,
5078 sem.SemaphoreAddress = (struct anv_address) {
5079 cmd_buffer->device->dynamic_state_pool.block_pool.bo,
5080 event->state.offset
5081 };
5082 }
5083 }
5084 #else
5085 anv_finishme("Implement events on gen7");
5086 #endif
5087
5088 genX(CmdPipelineBarrier)(commandBuffer, srcStageMask, destStageMask,
5089 false, /* byRegion */
5090 memoryBarrierCount, pMemoryBarriers,
5091 bufferMemoryBarrierCount, pBufferMemoryBarriers,
5092 imageMemoryBarrierCount, pImageMemoryBarriers);
5093 }