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