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