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