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