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