anv: drop unused code
[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_l3_config.h"
33 #include "genxml/gen_macros.h"
34 #include "genxml/genX_pack.h"
35
36 /* We reserve GPR 14 and 15 for conditional rendering */
37 #define GEN_MI_BUILDER_NUM_ALLOC_GPRS 14
38 #define __gen_get_batch_dwords anv_batch_emit_dwords
39 #define __gen_address_offset anv_address_add
40 #include "common/gen_mi_builder.h"
41
42 static void
43 emit_lri(struct anv_batch *batch, uint32_t reg, uint32_t imm)
44 {
45 anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
46 lri.RegisterOffset = reg;
47 lri.DataDWord = imm;
48 }
49 }
50
51 void
52 genX(cmd_buffer_emit_state_base_address)(struct anv_cmd_buffer *cmd_buffer)
53 {
54 struct anv_device *device = cmd_buffer->device;
55
56 /* If we are emitting a new state base address we probably need to re-emit
57 * binding tables.
58 */
59 cmd_buffer->state.descriptors_dirty |= ~0;
60
61 /* Emit a render target cache flush.
62 *
63 * This isn't documented anywhere in the PRM. However, it seems to be
64 * necessary prior to changing the surface state base adress. Without
65 * this, we get GPU hangs when using multi-level command buffers which
66 * clear depth, reset state base address, and then go render stuff.
67 */
68 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
69 pc.DCFlushEnable = true;
70 pc.RenderTargetCacheFlushEnable = true;
71 pc.CommandStreamerStallEnable = true;
72 }
73
74 anv_batch_emit(&cmd_buffer->batch, GENX(STATE_BASE_ADDRESS), sba) {
75 sba.GeneralStateBaseAddress = (struct anv_address) { NULL, 0 };
76 sba.GeneralStateMOCS = GENX(MOCS);
77 sba.GeneralStateBaseAddressModifyEnable = true;
78
79 sba.StatelessDataPortAccessMOCS = GENX(MOCS);
80
81 sba.SurfaceStateBaseAddress =
82 anv_cmd_buffer_surface_base_address(cmd_buffer);
83 sba.SurfaceStateMOCS = GENX(MOCS);
84 sba.SurfaceStateBaseAddressModifyEnable = true;
85
86 sba.DynamicStateBaseAddress =
87 (struct anv_address) { device->dynamic_state_pool.block_pool.bo, 0 };
88 sba.DynamicStateMOCS = GENX(MOCS);
89 sba.DynamicStateBaseAddressModifyEnable = true;
90
91 sba.IndirectObjectBaseAddress = (struct anv_address) { NULL, 0 };
92 sba.IndirectObjectMOCS = GENX(MOCS);
93 sba.IndirectObjectBaseAddressModifyEnable = true;
94
95 sba.InstructionBaseAddress =
96 (struct anv_address) { device->instruction_state_pool.block_pool.bo, 0 };
97 sba.InstructionMOCS = GENX(MOCS);
98 sba.InstructionBaseAddressModifyEnable = true;
99
100 # if (GEN_GEN >= 8)
101 /* Broadwell requires that we specify a buffer size for a bunch of
102 * these fields. However, since we will be growing the BO's live, we
103 * just set them all to the maximum.
104 */
105 sba.GeneralStateBufferSize = 0xfffff;
106 sba.GeneralStateBufferSizeModifyEnable = true;
107 sba.DynamicStateBufferSize = 0xfffff;
108 sba.DynamicStateBufferSizeModifyEnable = true;
109 sba.IndirectObjectBufferSize = 0xfffff;
110 sba.IndirectObjectBufferSizeModifyEnable = true;
111 sba.InstructionBufferSize = 0xfffff;
112 sba.InstructionBuffersizeModifyEnable = true;
113 # else
114 /* On gen7, we have upper bounds instead. According to the docs,
115 * setting an upper bound of zero means that no bounds checking is
116 * performed so, in theory, we should be able to leave them zero.
117 * However, border color is broken and the GPU bounds-checks anyway.
118 * To avoid this and other potential problems, we may as well set it
119 * for everything.
120 */
121 sba.GeneralStateAccessUpperBound =
122 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
123 sba.GeneralStateAccessUpperBoundModifyEnable = true;
124 sba.DynamicStateAccessUpperBound =
125 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
126 sba.DynamicStateAccessUpperBoundModifyEnable = true;
127 sba.InstructionAccessUpperBound =
128 (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
129 sba.InstructionAccessUpperBoundModifyEnable = true;
130 # endif
131 # if (GEN_GEN >= 9)
132 if (cmd_buffer->device->instance->physicalDevice.use_softpin) {
133 sba.BindlessSurfaceStateBaseAddress = (struct anv_address) {
134 .bo = device->surface_state_pool.block_pool.bo,
135 .offset = 0,
136 };
137 sba.BindlessSurfaceStateSize = (1 << 20) - 1;
138 } else {
139 sba.BindlessSurfaceStateBaseAddress = ANV_NULL_ADDRESS;
140 sba.BindlessSurfaceStateSize = 0;
141 }
142 sba.BindlessSurfaceStateMOCS = GENX(MOCS);
143 sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
144 # endif
145 # if (GEN_GEN >= 10)
146 sba.BindlessSamplerStateBaseAddress = (struct anv_address) { NULL, 0 };
147 sba.BindlessSamplerStateMOCS = GENX(MOCS);
148 sba.BindlessSamplerStateBaseAddressModifyEnable = true;
149 sba.BindlessSamplerStateBufferSize = 0;
150 # endif
151 }
152
153 /* After re-setting the surface state base address, we have to do some
154 * cache flusing so that the sampler engine will pick up the new
155 * SURFACE_STATE objects and binding tables. From the Broadwell PRM,
156 * Shared Function > 3D Sampler > State > State Caching (page 96):
157 *
158 * Coherency with system memory in the state cache, like the texture
159 * cache is handled partially by software. It is expected that the
160 * command stream or shader will issue Cache Flush operation or
161 * Cache_Flush sampler message to ensure that the L1 cache remains
162 * coherent with system memory.
163 *
164 * [...]
165 *
166 * Whenever the value of the Dynamic_State_Base_Addr,
167 * Surface_State_Base_Addr are altered, the L1 state cache must be
168 * invalidated to ensure the new surface or sampler state is fetched
169 * from system memory.
170 *
171 * The PIPE_CONTROL command has a "State Cache Invalidation Enable" bit
172 * which, according the PIPE_CONTROL instruction documentation in the
173 * Broadwell PRM:
174 *
175 * Setting this bit is independent of any other bit in this packet.
176 * This bit controls the invalidation of the L1 and L2 state caches
177 * at the top of the pipe i.e. at the parsing time.
178 *
179 * Unfortunately, experimentation seems to indicate that state cache
180 * invalidation through a PIPE_CONTROL does nothing whatsoever in
181 * regards to surface state and binding tables. In stead, it seems that
182 * invalidating the texture cache is what is actually needed.
183 *
184 * XXX: As far as we have been able to determine through
185 * experimentation, shows that flush the texture cache appears to be
186 * sufficient. The theory here is that all of the sampling/rendering
187 * units cache the binding table in the texture cache. However, we have
188 * yet to be able to actually confirm this.
189 */
190 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
191 pc.TextureCacheInvalidationEnable = true;
192 pc.ConstantCacheInvalidationEnable = true;
193 pc.StateCacheInvalidationEnable = true;
194 }
195 }
196
197 static void
198 add_surface_reloc(struct anv_cmd_buffer *cmd_buffer,
199 struct anv_state state, struct anv_address addr)
200 {
201 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
202
203 VkResult result =
204 anv_reloc_list_add(&cmd_buffer->surface_relocs, &cmd_buffer->pool->alloc,
205 state.offset + isl_dev->ss.addr_offset,
206 addr.bo, addr.offset);
207 if (result != VK_SUCCESS)
208 anv_batch_set_error(&cmd_buffer->batch, result);
209 }
210
211 static void
212 add_surface_state_relocs(struct anv_cmd_buffer *cmd_buffer,
213 struct anv_surface_state state)
214 {
215 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
216
217 assert(!anv_address_is_null(state.address));
218 add_surface_reloc(cmd_buffer, state.state, state.address);
219
220 if (!anv_address_is_null(state.aux_address)) {
221 VkResult result =
222 anv_reloc_list_add(&cmd_buffer->surface_relocs,
223 &cmd_buffer->pool->alloc,
224 state.state.offset + isl_dev->ss.aux_addr_offset,
225 state.aux_address.bo, state.aux_address.offset);
226 if (result != VK_SUCCESS)
227 anv_batch_set_error(&cmd_buffer->batch, result);
228 }
229
230 if (!anv_address_is_null(state.clear_address)) {
231 VkResult result =
232 anv_reloc_list_add(&cmd_buffer->surface_relocs,
233 &cmd_buffer->pool->alloc,
234 state.state.offset +
235 isl_dev->ss.clear_color_state_offset,
236 state.clear_address.bo, state.clear_address.offset);
237 if (result != VK_SUCCESS)
238 anv_batch_set_error(&cmd_buffer->batch, result);
239 }
240 }
241
242 static void
243 color_attachment_compute_aux_usage(struct anv_device * device,
244 struct anv_cmd_state * cmd_state,
245 uint32_t att, VkRect2D render_area,
246 union isl_color_value *fast_clear_color)
247 {
248 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
249 struct anv_image_view *iview = cmd_state->attachments[att].image_view;
250
251 assert(iview->n_planes == 1);
252
253 if (iview->planes[0].isl.base_array_layer >=
254 anv_image_aux_layers(iview->image, VK_IMAGE_ASPECT_COLOR_BIT,
255 iview->planes[0].isl.base_level)) {
256 /* There is no aux buffer which corresponds to the level and layer(s)
257 * being accessed.
258 */
259 att_state->aux_usage = ISL_AUX_USAGE_NONE;
260 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
261 att_state->fast_clear = false;
262 return;
263 }
264
265 att_state->aux_usage =
266 anv_layout_to_aux_usage(&device->info, iview->image,
267 VK_IMAGE_ASPECT_COLOR_BIT,
268 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
269
270 /* If we don't have aux, then we should have returned early in the layer
271 * check above. If we got here, we must have something.
272 */
273 assert(att_state->aux_usage != ISL_AUX_USAGE_NONE);
274
275 if (att_state->aux_usage == ISL_AUX_USAGE_CCS_E ||
276 att_state->aux_usage == ISL_AUX_USAGE_MCS) {
277 att_state->input_aux_usage = att_state->aux_usage;
278 } else {
279 /* From the Sky Lake PRM, RENDER_SURFACE_STATE::AuxiliarySurfaceMode:
280 *
281 * "If Number of Multisamples is MULTISAMPLECOUNT_1, AUX_CCS_D
282 * setting is only allowed if Surface Format supported for Fast
283 * Clear. In addition, if the surface is bound to the sampling
284 * engine, Surface Format must be supported for Render Target
285 * Compression for surfaces bound to the sampling engine."
286 *
287 * In other words, we can only sample from a fast-cleared image if it
288 * also supports color compression.
289 */
290 if (isl_format_supports_ccs_e(&device->info, iview->planes[0].isl.format)) {
291 att_state->input_aux_usage = ISL_AUX_USAGE_CCS_D;
292
293 /* While fast-clear resolves and partial resolves are fairly cheap in the
294 * case where you render to most of the pixels, full resolves are not
295 * because they potentially involve reading and writing the entire
296 * framebuffer. If we can't texture with CCS_E, we should leave it off and
297 * limit ourselves to fast clears.
298 */
299 if (cmd_state->pass->attachments[att].first_subpass_layout ==
300 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
301 anv_perf_warn(device->instance, iview->image,
302 "Not temporarily enabling CCS_E.");
303 }
304 } else {
305 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
306 }
307 }
308
309 assert(iview->image->planes[0].aux_surface.isl.usage &
310 (ISL_SURF_USAGE_CCS_BIT | ISL_SURF_USAGE_MCS_BIT));
311
312 union isl_color_value clear_color = {};
313 anv_clear_color_from_att_state(&clear_color, att_state, iview);
314
315 att_state->clear_color_is_zero_one =
316 isl_color_value_is_zero_one(clear_color, iview->planes[0].isl.format);
317 att_state->clear_color_is_zero =
318 isl_color_value_is_zero(clear_color, iview->planes[0].isl.format);
319
320 if (att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
321 /* Start by getting the fast clear type. We use the first subpass
322 * layout here because we don't want to fast-clear if the first subpass
323 * to use the attachment can't handle fast-clears.
324 */
325 enum anv_fast_clear_type fast_clear_type =
326 anv_layout_to_fast_clear_type(&device->info, iview->image,
327 VK_IMAGE_ASPECT_COLOR_BIT,
328 cmd_state->pass->attachments[att].first_subpass_layout);
329 switch (fast_clear_type) {
330 case ANV_FAST_CLEAR_NONE:
331 att_state->fast_clear = false;
332 break;
333 case ANV_FAST_CLEAR_DEFAULT_VALUE:
334 att_state->fast_clear = att_state->clear_color_is_zero;
335 break;
336 case ANV_FAST_CLEAR_ANY:
337 att_state->fast_clear = true;
338 break;
339 }
340
341 /* Potentially, we could do partial fast-clears but doing so has crazy
342 * alignment restrictions. It's easier to just restrict to full size
343 * fast clears for now.
344 */
345 if (render_area.offset.x != 0 ||
346 render_area.offset.y != 0 ||
347 render_area.extent.width != iview->extent.width ||
348 render_area.extent.height != iview->extent.height)
349 att_state->fast_clear = false;
350
351 /* On Broadwell and earlier, we can only handle 0/1 clear colors */
352 if (GEN_GEN <= 8 && !att_state->clear_color_is_zero_one)
353 att_state->fast_clear = false;
354
355 /* We only allow fast clears to the first slice of an image (level 0,
356 * layer 0) and only for the entire slice. This guarantees us that, at
357 * any given time, there is only one clear color on any given image at
358 * any given time. At the time of our testing (Jan 17, 2018), there
359 * were no known applications which would benefit from fast-clearing
360 * more than just the first slice.
361 */
362 if (att_state->fast_clear &&
363 (iview->planes[0].isl.base_level > 0 ||
364 iview->planes[0].isl.base_array_layer > 0)) {
365 anv_perf_warn(device->instance, iview->image,
366 "Rendering with multi-lod or multi-layer framebuffer "
367 "with LOAD_OP_LOAD and baseMipLevel > 0 or "
368 "baseArrayLayer > 0. Not fast clearing.");
369 att_state->fast_clear = false;
370 } else if (att_state->fast_clear && cmd_state->framebuffer->layers > 1) {
371 anv_perf_warn(device->instance, iview->image,
372 "Rendering to a multi-layer framebuffer with "
373 "LOAD_OP_CLEAR. Only fast-clearing the first slice");
374 }
375
376 if (att_state->fast_clear)
377 *fast_clear_color = clear_color;
378 } else {
379 att_state->fast_clear = false;
380 }
381 }
382
383 static void
384 depth_stencil_attachment_compute_aux_usage(struct anv_device *device,
385 struct anv_cmd_state *cmd_state,
386 uint32_t att, VkRect2D render_area)
387 {
388 struct anv_render_pass_attachment *pass_att =
389 &cmd_state->pass->attachments[att];
390 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
391 struct anv_image_view *iview = cmd_state->attachments[att].image_view;
392
393 /* These will be initialized after the first subpass transition. */
394 att_state->aux_usage = ISL_AUX_USAGE_NONE;
395 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
396
397 if (GEN_GEN == 7) {
398 /* We don't do any HiZ or depth fast-clears on gen7 yet */
399 att_state->fast_clear = false;
400 return;
401 }
402
403 if (!(att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
404 /* If we're just clearing stencil, we can always HiZ clear */
405 att_state->fast_clear = true;
406 return;
407 }
408
409 /* Default to false for now */
410 att_state->fast_clear = false;
411
412 /* We must have depth in order to have HiZ */
413 if (!(iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
414 return;
415
416 const enum isl_aux_usage first_subpass_aux_usage =
417 anv_layout_to_aux_usage(&device->info, iview->image,
418 VK_IMAGE_ASPECT_DEPTH_BIT,
419 pass_att->first_subpass_layout);
420 if (first_subpass_aux_usage != ISL_AUX_USAGE_HIZ)
421 return;
422
423 if (!blorp_can_hiz_clear_depth(GEN_GEN,
424 iview->planes[0].isl.format,
425 iview->image->samples,
426 render_area.offset.x,
427 render_area.offset.y,
428 render_area.offset.x +
429 render_area.extent.width,
430 render_area.offset.y +
431 render_area.extent.height))
432 return;
433
434 if (att_state->clear_value.depthStencil.depth != ANV_HZ_FC_VAL)
435 return;
436
437 if (GEN_GEN == 8 && anv_can_sample_with_hiz(&device->info, iview->image)) {
438 /* Only gen9+ supports returning ANV_HZ_FC_VAL when sampling a
439 * fast-cleared portion of a HiZ buffer. Testing has revealed that Gen8
440 * only supports returning 0.0f. Gens prior to gen8 do not support this
441 * feature at all.
442 */
443 return;
444 }
445
446 /* If we got here, then we can fast clear */
447 att_state->fast_clear = true;
448 }
449
450 static bool
451 need_input_attachment_state(const struct anv_render_pass_attachment *att)
452 {
453 if (!(att->usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT))
454 return false;
455
456 /* We only allocate input attachment states for color surfaces. Compression
457 * is not yet enabled for depth textures and stencil doesn't allow
458 * compression so we can just use the texture surface state from the view.
459 */
460 return vk_format_is_color(att->format);
461 }
462
463 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
464 * the initial layout is undefined, the HiZ buffer and depth buffer will
465 * represent the same data at the end of this operation.
466 */
467 static void
468 transition_depth_buffer(struct anv_cmd_buffer *cmd_buffer,
469 const struct anv_image *image,
470 VkImageLayout initial_layout,
471 VkImageLayout final_layout)
472 {
473 const bool hiz_enabled = ISL_AUX_USAGE_HIZ ==
474 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
475 VK_IMAGE_ASPECT_DEPTH_BIT, initial_layout);
476 const bool enable_hiz = ISL_AUX_USAGE_HIZ ==
477 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
478 VK_IMAGE_ASPECT_DEPTH_BIT, final_layout);
479
480 enum isl_aux_op hiz_op;
481 if (hiz_enabled && !enable_hiz) {
482 hiz_op = ISL_AUX_OP_FULL_RESOLVE;
483 } else if (!hiz_enabled && enable_hiz) {
484 hiz_op = ISL_AUX_OP_AMBIGUATE;
485 } else {
486 assert(hiz_enabled == enable_hiz);
487 /* If the same buffer will be used, no resolves are necessary. */
488 hiz_op = ISL_AUX_OP_NONE;
489 }
490
491 if (hiz_op != ISL_AUX_OP_NONE)
492 anv_image_hiz_op(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
493 0, 0, 1, hiz_op);
494 }
495
496 static inline bool
497 vk_image_layout_stencil_write_optimal(VkImageLayout layout)
498 {
499 return layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
500 layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL;
501 }
502
503 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
504 * the initial layout is undefined, the HiZ buffer and depth buffer will
505 * represent the same data at the end of this operation.
506 */
507 static void
508 transition_stencil_buffer(struct anv_cmd_buffer *cmd_buffer,
509 const struct anv_image *image,
510 uint32_t base_level, uint32_t level_count,
511 uint32_t base_layer, uint32_t layer_count,
512 VkImageLayout initial_layout,
513 VkImageLayout final_layout)
514 {
515 #if GEN_GEN == 7
516 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
517 VK_IMAGE_ASPECT_STENCIL_BIT);
518
519 /* On gen7, we have to store a texturable version of the stencil buffer in
520 * a shadow whenever VK_IMAGE_USAGE_SAMPLED_BIT is set and copy back and
521 * forth at strategic points. Stencil writes are only allowed in three
522 * layouts:
523 *
524 * - VK_IMAGE_LAYOUT_GENERAL
525 * - VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL
526 * - VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL
527 * - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL
528 *
529 * For general, we have no nice opportunity to transition so we do the copy
530 * to the shadow unconditionally at the end of the subpass. For transfer
531 * destinations, we can update it as part of the transfer op. For the
532 * other two, we delay the copy until a transition into some other layout.
533 */
534 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
535 vk_image_layout_stencil_write_optimal(initial_layout) &&
536 !vk_image_layout_stencil_write_optimal(final_layout)) {
537 anv_image_copy_to_shadow(cmd_buffer, image,
538 VK_IMAGE_ASPECT_STENCIL_BIT,
539 base_level, level_count,
540 base_layer, layer_count);
541 }
542 #endif /* GEN_GEN == 7 */
543 }
544
545 #define MI_PREDICATE_SRC0 0x2400
546 #define MI_PREDICATE_SRC1 0x2408
547 #define MI_PREDICATE_RESULT 0x2418
548
549 static void
550 set_image_compressed_bit(struct anv_cmd_buffer *cmd_buffer,
551 const struct anv_image *image,
552 VkImageAspectFlagBits aspect,
553 uint32_t level,
554 uint32_t base_layer, uint32_t layer_count,
555 bool compressed)
556 {
557 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
558
559 /* We only have compression tracking for CCS_E */
560 if (image->planes[plane].aux_usage != ISL_AUX_USAGE_CCS_E)
561 return;
562
563 for (uint32_t a = 0; a < layer_count; a++) {
564 uint32_t layer = base_layer + a;
565 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
566 sdi.Address = anv_image_get_compression_state_addr(cmd_buffer->device,
567 image, aspect,
568 level, layer);
569 sdi.ImmediateData = compressed ? UINT32_MAX : 0;
570 }
571 }
572 }
573
574 static void
575 set_image_fast_clear_state(struct anv_cmd_buffer *cmd_buffer,
576 const struct anv_image *image,
577 VkImageAspectFlagBits aspect,
578 enum anv_fast_clear_type fast_clear)
579 {
580 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
581 sdi.Address = anv_image_get_fast_clear_type_addr(cmd_buffer->device,
582 image, aspect);
583 sdi.ImmediateData = fast_clear;
584 }
585
586 /* Whenever we have fast-clear, we consider that slice to be compressed.
587 * This makes building predicates much easier.
588 */
589 if (fast_clear != ANV_FAST_CLEAR_NONE)
590 set_image_compressed_bit(cmd_buffer, image, aspect, 0, 0, 1, true);
591 }
592
593 /* This is only really practical on haswell and above because it requires
594 * MI math in order to get it correct.
595 */
596 #if GEN_GEN >= 8 || GEN_IS_HASWELL
597 static void
598 anv_cmd_compute_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
599 const struct anv_image *image,
600 VkImageAspectFlagBits aspect,
601 uint32_t level, uint32_t array_layer,
602 enum isl_aux_op resolve_op,
603 enum anv_fast_clear_type fast_clear_supported)
604 {
605 struct gen_mi_builder b;
606 gen_mi_builder_init(&b, &cmd_buffer->batch);
607
608 const struct gen_mi_value fast_clear_type =
609 gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
610 image, aspect));
611
612 if (resolve_op == ISL_AUX_OP_FULL_RESOLVE) {
613 /* In this case, we're doing a full resolve which means we want the
614 * resolve to happen if any compression (including fast-clears) is
615 * present.
616 *
617 * In order to simplify the logic a bit, we make the assumption that,
618 * if the first slice has been fast-cleared, it is also marked as
619 * compressed. See also set_image_fast_clear_state.
620 */
621 const struct gen_mi_value compression_state =
622 gen_mi_mem32(anv_image_get_compression_state_addr(cmd_buffer->device,
623 image, aspect,
624 level, array_layer));
625 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
626 compression_state);
627 gen_mi_store(&b, compression_state, gen_mi_imm(0));
628
629 if (level == 0 && array_layer == 0) {
630 /* If the predicate is true, we want to write 0 to the fast clear type
631 * and, if it's false, leave it alone. We can do this by writing
632 *
633 * clear_type = clear_type & ~predicate;
634 */
635 struct gen_mi_value new_fast_clear_type =
636 gen_mi_iand(&b, fast_clear_type,
637 gen_mi_inot(&b, gen_mi_reg64(MI_PREDICATE_SRC0)));
638 gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
639 }
640 } else if (level == 0 && array_layer == 0) {
641 /* In this case, we are doing a partial resolve to get rid of fast-clear
642 * colors. We don't care about the compression state but we do care
643 * about how much fast clear is allowed by the final layout.
644 */
645 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
646 assert(fast_clear_supported < ANV_FAST_CLEAR_ANY);
647
648 /* We need to compute (fast_clear_supported < image->fast_clear) */
649 struct gen_mi_value pred =
650 gen_mi_ult(&b, gen_mi_imm(fast_clear_supported), fast_clear_type);
651 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
652 gen_mi_value_ref(&b, pred));
653
654 /* If the predicate is true, we want to write 0 to the fast clear type
655 * and, if it's false, leave it alone. We can do this by writing
656 *
657 * clear_type = clear_type & ~predicate;
658 */
659 struct gen_mi_value new_fast_clear_type =
660 gen_mi_iand(&b, fast_clear_type, gen_mi_inot(&b, pred));
661 gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
662 } else {
663 /* In this case, we're trying to do a partial resolve on a slice that
664 * doesn't have clear color. There's nothing to do.
665 */
666 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
667 return;
668 }
669
670 /* Set src1 to 0 and use a != condition */
671 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
672
673 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
674 mip.LoadOperation = LOAD_LOADINV;
675 mip.CombineOperation = COMBINE_SET;
676 mip.CompareOperation = COMPARE_SRCS_EQUAL;
677 }
678 }
679 #endif /* GEN_GEN >= 8 || GEN_IS_HASWELL */
680
681 #if GEN_GEN <= 8
682 static void
683 anv_cmd_simple_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
684 const struct anv_image *image,
685 VkImageAspectFlagBits aspect,
686 uint32_t level, uint32_t array_layer,
687 enum isl_aux_op resolve_op,
688 enum anv_fast_clear_type fast_clear_supported)
689 {
690 struct gen_mi_builder b;
691 gen_mi_builder_init(&b, &cmd_buffer->batch);
692
693 struct gen_mi_value fast_clear_type_mem =
694 gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
695 image, aspect));
696
697 /* This only works for partial resolves and only when the clear color is
698 * all or nothing. On the upside, this emits less command streamer code
699 * and works on Ivybridge and Bay Trail.
700 */
701 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
702 assert(fast_clear_supported != ANV_FAST_CLEAR_ANY);
703
704 /* We don't support fast clears on anything other than the first slice. */
705 if (level > 0 || array_layer > 0)
706 return;
707
708 /* On gen8, we don't have a concept of default clear colors because we
709 * can't sample from CCS surfaces. It's enough to just load the fast clear
710 * state into the predicate register.
711 */
712 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), fast_clear_type_mem);
713 gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
714 gen_mi_store(&b, fast_clear_type_mem, gen_mi_imm(0));
715
716 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
717 mip.LoadOperation = LOAD_LOADINV;
718 mip.CombineOperation = COMBINE_SET;
719 mip.CompareOperation = COMPARE_SRCS_EQUAL;
720 }
721 }
722 #endif /* GEN_GEN <= 8 */
723
724 static void
725 anv_cmd_predicated_ccs_resolve(struct anv_cmd_buffer *cmd_buffer,
726 const struct anv_image *image,
727 enum isl_format format,
728 VkImageAspectFlagBits aspect,
729 uint32_t level, uint32_t array_layer,
730 enum isl_aux_op resolve_op,
731 enum anv_fast_clear_type fast_clear_supported)
732 {
733 const uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
734
735 #if GEN_GEN >= 9
736 anv_cmd_compute_resolve_predicate(cmd_buffer, image,
737 aspect, level, array_layer,
738 resolve_op, fast_clear_supported);
739 #else /* GEN_GEN <= 8 */
740 anv_cmd_simple_resolve_predicate(cmd_buffer, image,
741 aspect, level, array_layer,
742 resolve_op, fast_clear_supported);
743 #endif
744
745 /* CCS_D only supports full resolves and BLORP will assert on us if we try
746 * to do a partial resolve on a CCS_D surface.
747 */
748 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
749 image->planes[plane].aux_usage == ISL_AUX_USAGE_NONE)
750 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
751
752 anv_image_ccs_op(cmd_buffer, image, format, aspect, level,
753 array_layer, 1, resolve_op, NULL, true);
754 }
755
756 static void
757 anv_cmd_predicated_mcs_resolve(struct anv_cmd_buffer *cmd_buffer,
758 const struct anv_image *image,
759 enum isl_format format,
760 VkImageAspectFlagBits aspect,
761 uint32_t array_layer,
762 enum isl_aux_op resolve_op,
763 enum anv_fast_clear_type fast_clear_supported)
764 {
765 assert(aspect == VK_IMAGE_ASPECT_COLOR_BIT);
766 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
767
768 #if GEN_GEN >= 8 || GEN_IS_HASWELL
769 anv_cmd_compute_resolve_predicate(cmd_buffer, image,
770 aspect, 0, array_layer,
771 resolve_op, fast_clear_supported);
772
773 anv_image_mcs_op(cmd_buffer, image, format, aspect,
774 array_layer, 1, resolve_op, NULL, true);
775 #else
776 unreachable("MCS resolves are unsupported on Ivybridge and Bay Trail");
777 #endif
778 }
779
780 void
781 genX(cmd_buffer_mark_image_written)(struct anv_cmd_buffer *cmd_buffer,
782 const struct anv_image *image,
783 VkImageAspectFlagBits aspect,
784 enum isl_aux_usage aux_usage,
785 uint32_t level,
786 uint32_t base_layer,
787 uint32_t layer_count)
788 {
789 /* The aspect must be exactly one of the image aspects. */
790 assert(util_bitcount(aspect) == 1 && (aspect & image->aspects));
791
792 /* The only compression types with more than just fast-clears are MCS,
793 * CCS_E, and HiZ. With HiZ we just trust the layout and don't actually
794 * track the current fast-clear and compression state. This leaves us
795 * with just MCS and CCS_E.
796 */
797 if (aux_usage != ISL_AUX_USAGE_CCS_E &&
798 aux_usage != ISL_AUX_USAGE_MCS)
799 return;
800
801 set_image_compressed_bit(cmd_buffer, image, aspect,
802 level, base_layer, layer_count, true);
803 }
804
805 static void
806 init_fast_clear_color(struct anv_cmd_buffer *cmd_buffer,
807 const struct anv_image *image,
808 VkImageAspectFlagBits aspect)
809 {
810 assert(cmd_buffer && image);
811 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
812
813 set_image_fast_clear_state(cmd_buffer, image, aspect,
814 ANV_FAST_CLEAR_NONE);
815
816 /* Initialize the struct fields that are accessed for fast-clears so that
817 * the HW restrictions on the field values are satisfied.
818 */
819 struct anv_address addr =
820 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
821
822 if (GEN_GEN >= 9) {
823 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
824 const unsigned num_dwords = GEN_GEN >= 10 ?
825 isl_dev->ss.clear_color_state_size / 4 :
826 isl_dev->ss.clear_value_size / 4;
827 for (unsigned i = 0; i < num_dwords; i++) {
828 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
829 sdi.Address = addr;
830 sdi.Address.offset += i * 4;
831 sdi.ImmediateData = 0;
832 }
833 }
834 } else {
835 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
836 sdi.Address = addr;
837 if (GEN_GEN >= 8 || GEN_IS_HASWELL) {
838 /* Pre-SKL, the dword containing the clear values also contains
839 * other fields, so we need to initialize those fields to match the
840 * values that would be in a color attachment.
841 */
842 sdi.ImmediateData = ISL_CHANNEL_SELECT_RED << 25 |
843 ISL_CHANNEL_SELECT_GREEN << 22 |
844 ISL_CHANNEL_SELECT_BLUE << 19 |
845 ISL_CHANNEL_SELECT_ALPHA << 16;
846 } else if (GEN_GEN == 7) {
847 /* On IVB, the dword containing the clear values also contains
848 * other fields that must be zero or can be zero.
849 */
850 sdi.ImmediateData = 0;
851 }
852 }
853 }
854 }
855
856 /* Copy the fast-clear value dword(s) between a surface state object and an
857 * image's fast clear state buffer.
858 */
859 static void
860 genX(copy_fast_clear_dwords)(struct anv_cmd_buffer *cmd_buffer,
861 struct anv_state surface_state,
862 const struct anv_image *image,
863 VkImageAspectFlagBits aspect,
864 bool copy_from_surface_state)
865 {
866 assert(cmd_buffer && image);
867 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
868
869 struct anv_address ss_clear_addr = {
870 .bo = cmd_buffer->device->surface_state_pool.block_pool.bo,
871 .offset = surface_state.offset +
872 cmd_buffer->device->isl_dev.ss.clear_value_offset,
873 };
874 const struct anv_address entry_addr =
875 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
876 unsigned copy_size = cmd_buffer->device->isl_dev.ss.clear_value_size;
877
878 #if GEN_GEN == 7
879 /* On gen7, the combination of commands used here(MI_LOAD_REGISTER_MEM
880 * and MI_STORE_REGISTER_MEM) can cause GPU hangs if any rendering is
881 * in-flight when they are issued even if the memory touched is not
882 * currently active for rendering. The weird bit is that it is not the
883 * MI_LOAD/STORE_REGISTER_MEM commands which hang but rather the in-flight
884 * rendering hangs such that the next stalling command after the
885 * MI_LOAD/STORE_REGISTER_MEM commands will catch the hang.
886 *
887 * It is unclear exactly why this hang occurs. Both MI commands come with
888 * warnings about the 3D pipeline but that doesn't seem to fully explain
889 * it. My (Jason's) best theory is that it has something to do with the
890 * fact that we're using a GPU state register as our temporary and that
891 * something with reading/writing it is causing problems.
892 *
893 * In order to work around this issue, we emit a PIPE_CONTROL with the
894 * command streamer stall bit set.
895 */
896 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
897 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
898 #endif
899
900 struct gen_mi_builder b;
901 gen_mi_builder_init(&b, &cmd_buffer->batch);
902
903 if (copy_from_surface_state) {
904 gen_mi_memcpy(&b, entry_addr, ss_clear_addr, copy_size);
905 } else {
906 gen_mi_memcpy(&b, ss_clear_addr, entry_addr, copy_size);
907
908 /* Updating a surface state object may require that the state cache be
909 * invalidated. From the SKL PRM, Shared Functions -> State -> State
910 * Caching:
911 *
912 * Whenever the RENDER_SURFACE_STATE object in memory pointed to by
913 * the Binding Table Pointer (BTP) and Binding Table Index (BTI) is
914 * modified [...], the L1 state cache must be invalidated to ensure
915 * the new surface or sampler state is fetched from system memory.
916 *
917 * In testing, SKL doesn't actually seem to need this, but HSW does.
918 */
919 cmd_buffer->state.pending_pipe_bits |=
920 ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
921 }
922 }
923
924 /**
925 * @brief Transitions a color buffer from one layout to another.
926 *
927 * See section 6.1.1. Image Layout Transitions of the Vulkan 1.0.50 spec for
928 * more information.
929 *
930 * @param level_count VK_REMAINING_MIP_LEVELS isn't supported.
931 * @param layer_count VK_REMAINING_ARRAY_LAYERS isn't supported. For 3D images,
932 * this represents the maximum layers to transition at each
933 * specified miplevel.
934 */
935 static void
936 transition_color_buffer(struct anv_cmd_buffer *cmd_buffer,
937 const struct anv_image *image,
938 VkImageAspectFlagBits aspect,
939 const uint32_t base_level, uint32_t level_count,
940 uint32_t base_layer, uint32_t layer_count,
941 VkImageLayout initial_layout,
942 VkImageLayout final_layout)
943 {
944 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
945 /* Validate the inputs. */
946 assert(cmd_buffer);
947 assert(image && image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
948 /* These values aren't supported for simplicity's sake. */
949 assert(level_count != VK_REMAINING_MIP_LEVELS &&
950 layer_count != VK_REMAINING_ARRAY_LAYERS);
951 /* Ensure the subresource range is valid. */
952 UNUSED uint64_t last_level_num = base_level + level_count;
953 const uint32_t max_depth = anv_minify(image->extent.depth, base_level);
954 UNUSED const uint32_t image_layers = MAX2(image->array_size, max_depth);
955 assert((uint64_t)base_layer + layer_count <= image_layers);
956 assert(last_level_num <= image->levels);
957 /* The spec disallows these final layouts. */
958 assert(final_layout != VK_IMAGE_LAYOUT_UNDEFINED &&
959 final_layout != VK_IMAGE_LAYOUT_PREINITIALIZED);
960
961 /* No work is necessary if the layout stays the same or if this subresource
962 * range lacks auxiliary data.
963 */
964 if (initial_layout == final_layout)
965 return;
966
967 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
968
969 if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
970 final_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
971 /* This surface is a linear compressed image with a tiled shadow surface
972 * for texturing. The client is about to use it in READ_ONLY_OPTIMAL so
973 * we need to ensure the shadow copy is up-to-date.
974 */
975 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
976 assert(image->planes[plane].surface.isl.tiling == ISL_TILING_LINEAR);
977 assert(image->planes[plane].shadow_surface.isl.tiling != ISL_TILING_LINEAR);
978 assert(isl_format_is_compressed(image->planes[plane].surface.isl.format));
979 assert(plane == 0);
980 anv_image_copy_to_shadow(cmd_buffer, image,
981 VK_IMAGE_ASPECT_COLOR_BIT,
982 base_level, level_count,
983 base_layer, layer_count);
984 }
985
986 if (base_layer >= anv_image_aux_layers(image, aspect, base_level))
987 return;
988
989 assert(image->tiling == VK_IMAGE_TILING_OPTIMAL);
990
991 if (initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ||
992 initial_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
993 /* A subresource in the undefined layout may have been aliased and
994 * populated with any arrangement of bits. Therefore, we must initialize
995 * the related aux buffer and clear buffer entry with desirable values.
996 * An initial layout of PREINITIALIZED is the same as UNDEFINED for
997 * images with VK_IMAGE_TILING_OPTIMAL.
998 *
999 * Initialize the relevant clear buffer entries.
1000 */
1001 if (base_level == 0 && base_layer == 0)
1002 init_fast_clear_color(cmd_buffer, image, aspect);
1003
1004 /* Initialize the aux buffers to enable correct rendering. In order to
1005 * ensure that things such as storage images work correctly, aux buffers
1006 * need to be initialized to valid data.
1007 *
1008 * Having an aux buffer with invalid data is a problem for two reasons:
1009 *
1010 * 1) Having an invalid value in the buffer can confuse the hardware.
1011 * For instance, with CCS_E on SKL, a two-bit CCS value of 2 is
1012 * invalid and leads to the hardware doing strange things. It
1013 * doesn't hang as far as we can tell but rendering corruption can
1014 * occur.
1015 *
1016 * 2) If this transition is into the GENERAL layout and we then use the
1017 * image as a storage image, then we must have the aux buffer in the
1018 * pass-through state so that, if we then go to texture from the
1019 * image, we get the results of our storage image writes and not the
1020 * fast clear color or other random data.
1021 *
1022 * For CCS both of the problems above are real demonstrable issues. In
1023 * that case, the only thing we can do is to perform an ambiguate to
1024 * transition the aux surface into the pass-through state.
1025 *
1026 * For MCS, (2) is never an issue because we don't support multisampled
1027 * storage images. In theory, issue (1) is a problem with MCS but we've
1028 * never seen it in the wild. For 4x and 16x, all bit patters could, in
1029 * theory, be interpreted as something but we don't know that all bit
1030 * patterns are actually valid. For 2x and 8x, you could easily end up
1031 * with the MCS referring to an invalid plane because not all bits of
1032 * the MCS value are actually used. Even though we've never seen issues
1033 * in the wild, it's best to play it safe and initialize the MCS. We
1034 * can use a fast-clear for MCS because we only ever touch from render
1035 * and texture (no image load store).
1036 */
1037 if (image->samples == 1) {
1038 for (uint32_t l = 0; l < level_count; l++) {
1039 const uint32_t level = base_level + l;
1040
1041 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1042 if (base_layer >= aux_layers)
1043 break; /* We will only get fewer layers as level increases */
1044 uint32_t level_layer_count =
1045 MIN2(layer_count, aux_layers - base_layer);
1046
1047 anv_image_ccs_op(cmd_buffer, image,
1048 image->planes[plane].surface.isl.format,
1049 aspect, level, base_layer, level_layer_count,
1050 ISL_AUX_OP_AMBIGUATE, NULL, false);
1051
1052 if (image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_E) {
1053 set_image_compressed_bit(cmd_buffer, image, aspect,
1054 level, base_layer, level_layer_count,
1055 false);
1056 }
1057 }
1058 } else {
1059 if (image->samples == 4 || image->samples == 16) {
1060 anv_perf_warn(cmd_buffer->device->instance, image,
1061 "Doing a potentially unnecessary fast-clear to "
1062 "define an MCS buffer.");
1063 }
1064
1065 assert(base_level == 0 && level_count == 1);
1066 anv_image_mcs_op(cmd_buffer, image,
1067 image->planes[plane].surface.isl.format,
1068 aspect, base_layer, layer_count,
1069 ISL_AUX_OP_FAST_CLEAR, NULL, false);
1070 }
1071 return;
1072 }
1073
1074 const enum isl_aux_usage initial_aux_usage =
1075 anv_layout_to_aux_usage(devinfo, image, aspect, initial_layout);
1076 const enum isl_aux_usage final_aux_usage =
1077 anv_layout_to_aux_usage(devinfo, image, aspect, final_layout);
1078
1079 /* The current code assumes that there is no mixing of CCS_E and CCS_D.
1080 * We can handle transitions between CCS_D/E to and from NONE. What we
1081 * don't yet handle is switching between CCS_E and CCS_D within a given
1082 * image. Doing so in a performant way requires more detailed aux state
1083 * tracking such as what is done in i965. For now, just assume that we
1084 * only have one type of compression.
1085 */
1086 assert(initial_aux_usage == ISL_AUX_USAGE_NONE ||
1087 final_aux_usage == ISL_AUX_USAGE_NONE ||
1088 initial_aux_usage == final_aux_usage);
1089
1090 /* If initial aux usage is NONE, there is nothing to resolve */
1091 if (initial_aux_usage == ISL_AUX_USAGE_NONE)
1092 return;
1093
1094 enum isl_aux_op resolve_op = ISL_AUX_OP_NONE;
1095
1096 /* If the initial layout supports more fast clear than the final layout
1097 * then we need at least a partial resolve.
1098 */
1099 const enum anv_fast_clear_type initial_fast_clear =
1100 anv_layout_to_fast_clear_type(devinfo, image, aspect, initial_layout);
1101 const enum anv_fast_clear_type final_fast_clear =
1102 anv_layout_to_fast_clear_type(devinfo, image, aspect, final_layout);
1103 if (final_fast_clear < initial_fast_clear)
1104 resolve_op = ISL_AUX_OP_PARTIAL_RESOLVE;
1105
1106 if (initial_aux_usage == ISL_AUX_USAGE_CCS_E &&
1107 final_aux_usage != ISL_AUX_USAGE_CCS_E)
1108 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
1109
1110 if (resolve_op == ISL_AUX_OP_NONE)
1111 return;
1112
1113 /* Perform a resolve to synchronize data between the main and aux buffer.
1114 * Before we begin, we must satisfy the cache flushing requirement specified
1115 * in the Sky Lake PRM Vol. 7, "MCS Buffer for Render Target(s)":
1116 *
1117 * Any transition from any value in {Clear, Render, Resolve} to a
1118 * different value in {Clear, Render, Resolve} requires end of pipe
1119 * synchronization.
1120 *
1121 * We perform a flush of the write cache before and after the clear and
1122 * resolve operations to meet this requirement.
1123 *
1124 * Unlike other drawing, fast clear operations are not properly
1125 * synchronized. The first PIPE_CONTROL here likely ensures that the
1126 * contents of the previous render or clear hit the render target before we
1127 * resolve and the second likely ensures that the resolve is complete before
1128 * we do any more rendering or clearing.
1129 */
1130 cmd_buffer->state.pending_pipe_bits |=
1131 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1132
1133 for (uint32_t l = 0; l < level_count; l++) {
1134 uint32_t level = base_level + l;
1135
1136 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1137 if (base_layer >= aux_layers)
1138 break; /* We will only get fewer layers as level increases */
1139 uint32_t level_layer_count =
1140 MIN2(layer_count, aux_layers - base_layer);
1141
1142 for (uint32_t a = 0; a < level_layer_count; a++) {
1143 uint32_t array_layer = base_layer + a;
1144 if (image->samples == 1) {
1145 anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
1146 image->planes[plane].surface.isl.format,
1147 aspect, level, array_layer, resolve_op,
1148 final_fast_clear);
1149 } else {
1150 /* We only support fast-clear on the first layer so partial
1151 * resolves should not be used on other layers as they will use
1152 * the clear color stored in memory that is only valid for layer0.
1153 */
1154 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
1155 array_layer != 0)
1156 continue;
1157
1158 anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
1159 image->planes[plane].surface.isl.format,
1160 aspect, array_layer, resolve_op,
1161 final_fast_clear);
1162 }
1163 }
1164 }
1165
1166 cmd_buffer->state.pending_pipe_bits |=
1167 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1168 }
1169
1170 /**
1171 * Setup anv_cmd_state::attachments for vkCmdBeginRenderPass.
1172 */
1173 static VkResult
1174 genX(cmd_buffer_setup_attachments)(struct anv_cmd_buffer *cmd_buffer,
1175 struct anv_render_pass *pass,
1176 const VkRenderPassBeginInfo *begin)
1177 {
1178 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
1179 struct anv_cmd_state *state = &cmd_buffer->state;
1180 struct anv_framebuffer *framebuffer = cmd_buffer->state.framebuffer;
1181
1182 vk_free(&cmd_buffer->pool->alloc, state->attachments);
1183
1184 if (pass->attachment_count > 0) {
1185 state->attachments = vk_alloc(&cmd_buffer->pool->alloc,
1186 pass->attachment_count *
1187 sizeof(state->attachments[0]),
1188 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1189 if (state->attachments == NULL) {
1190 /* Propagate VK_ERROR_OUT_OF_HOST_MEMORY to vkEndCommandBuffer */
1191 return anv_batch_set_error(&cmd_buffer->batch,
1192 VK_ERROR_OUT_OF_HOST_MEMORY);
1193 }
1194 } else {
1195 state->attachments = NULL;
1196 }
1197
1198 /* Reserve one for the NULL state. */
1199 unsigned num_states = 1;
1200 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1201 if (vk_format_is_color(pass->attachments[i].format))
1202 num_states++;
1203
1204 if (need_input_attachment_state(&pass->attachments[i]))
1205 num_states++;
1206 }
1207
1208 const uint32_t ss_stride = align_u32(isl_dev->ss.size, isl_dev->ss.align);
1209 state->render_pass_states =
1210 anv_state_stream_alloc(&cmd_buffer->surface_state_stream,
1211 num_states * ss_stride, isl_dev->ss.align);
1212
1213 struct anv_state next_state = state->render_pass_states;
1214 next_state.alloc_size = isl_dev->ss.size;
1215
1216 state->null_surface_state = next_state;
1217 next_state.offset += ss_stride;
1218 next_state.map += ss_stride;
1219
1220 const VkRenderPassAttachmentBeginInfoKHR *begin_attachment =
1221 vk_find_struct_const(begin, RENDER_PASS_ATTACHMENT_BEGIN_INFO_KHR);
1222
1223 if (begin && !begin_attachment)
1224 assert(pass->attachment_count == framebuffer->attachment_count);
1225
1226 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1227 if (vk_format_is_color(pass->attachments[i].format)) {
1228 state->attachments[i].color.state = next_state;
1229 next_state.offset += ss_stride;
1230 next_state.map += ss_stride;
1231 }
1232
1233 if (need_input_attachment_state(&pass->attachments[i])) {
1234 state->attachments[i].input.state = next_state;
1235 next_state.offset += ss_stride;
1236 next_state.map += ss_stride;
1237 }
1238
1239 if (begin_attachment && begin_attachment->attachmentCount != 0) {
1240 assert(begin_attachment->attachmentCount == pass->attachment_count);
1241 ANV_FROM_HANDLE(anv_image_view, iview, begin_attachment->pAttachments[i]);
1242 cmd_buffer->state.attachments[i].image_view = iview;
1243 } else if (framebuffer && i < framebuffer->attachment_count) {
1244 cmd_buffer->state.attachments[i].image_view = framebuffer->attachments[i];
1245 }
1246 }
1247 assert(next_state.offset == state->render_pass_states.offset +
1248 state->render_pass_states.alloc_size);
1249
1250 if (begin) {
1251 isl_null_fill_state(isl_dev, state->null_surface_state.map,
1252 isl_extent3d(framebuffer->width,
1253 framebuffer->height,
1254 framebuffer->layers));
1255
1256 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1257 struct anv_render_pass_attachment *att = &pass->attachments[i];
1258 VkImageAspectFlags att_aspects = vk_format_aspects(att->format);
1259 VkImageAspectFlags clear_aspects = 0;
1260 VkImageAspectFlags load_aspects = 0;
1261
1262 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1263 /* color attachment */
1264 if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1265 clear_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1266 } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1267 load_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1268 }
1269 } else {
1270 /* depthstencil attachment */
1271 if (att_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
1272 if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1273 clear_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1274 } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1275 load_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1276 }
1277 }
1278 if (att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
1279 if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1280 clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1281 } else if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1282 load_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1283 }
1284 }
1285 }
1286
1287 state->attachments[i].current_layout = att->initial_layout;
1288 state->attachments[i].pending_clear_aspects = clear_aspects;
1289 state->attachments[i].pending_load_aspects = load_aspects;
1290 if (clear_aspects)
1291 state->attachments[i].clear_value = begin->pClearValues[i];
1292
1293 struct anv_image_view *iview = cmd_buffer->state.attachments[i].image_view;
1294 anv_assert(iview->vk_format == att->format);
1295
1296 const uint32_t num_layers = iview->planes[0].isl.array_len;
1297 state->attachments[i].pending_clear_views = (1 << num_layers) - 1;
1298
1299 union isl_color_value clear_color = { .u32 = { 0, } };
1300 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1301 anv_assert(iview->n_planes == 1);
1302 assert(att_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1303 color_attachment_compute_aux_usage(cmd_buffer->device,
1304 state, i, begin->renderArea,
1305 &clear_color);
1306
1307 anv_image_fill_surface_state(cmd_buffer->device,
1308 iview->image,
1309 VK_IMAGE_ASPECT_COLOR_BIT,
1310 &iview->planes[0].isl,
1311 ISL_SURF_USAGE_RENDER_TARGET_BIT,
1312 state->attachments[i].aux_usage,
1313 &clear_color,
1314 0,
1315 &state->attachments[i].color,
1316 NULL);
1317
1318 add_surface_state_relocs(cmd_buffer, state->attachments[i].color);
1319 } else {
1320 depth_stencil_attachment_compute_aux_usage(cmd_buffer->device,
1321 state, i,
1322 begin->renderArea);
1323 }
1324
1325 if (need_input_attachment_state(&pass->attachments[i])) {
1326 anv_image_fill_surface_state(cmd_buffer->device,
1327 iview->image,
1328 VK_IMAGE_ASPECT_COLOR_BIT,
1329 &iview->planes[0].isl,
1330 ISL_SURF_USAGE_TEXTURE_BIT,
1331 state->attachments[i].input_aux_usage,
1332 &clear_color,
1333 0,
1334 &state->attachments[i].input,
1335 NULL);
1336
1337 add_surface_state_relocs(cmd_buffer, state->attachments[i].input);
1338 }
1339 }
1340 }
1341
1342 return VK_SUCCESS;
1343 }
1344
1345 VkResult
1346 genX(BeginCommandBuffer)(
1347 VkCommandBuffer commandBuffer,
1348 const VkCommandBufferBeginInfo* pBeginInfo)
1349 {
1350 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1351
1352 /* If this is the first vkBeginCommandBuffer, we must *initialize* the
1353 * command buffer's state. Otherwise, we must *reset* its state. In both
1354 * cases we reset it.
1355 *
1356 * From the Vulkan 1.0 spec:
1357 *
1358 * If a command buffer is in the executable state and the command buffer
1359 * was allocated from a command pool with the
1360 * VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, then
1361 * vkBeginCommandBuffer implicitly resets the command buffer, behaving
1362 * as if vkResetCommandBuffer had been called with
1363 * VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT not set. It then puts
1364 * the command buffer in the recording state.
1365 */
1366 anv_cmd_buffer_reset(cmd_buffer);
1367
1368 cmd_buffer->usage_flags = pBeginInfo->flags;
1369
1370 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY ||
1371 !(cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT));
1372
1373 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
1374
1375 /* We sometimes store vertex data in the dynamic state buffer for blorp
1376 * operations and our dynamic state stream may re-use data from previous
1377 * command buffers. In order to prevent stale cache data, we flush the VF
1378 * cache. We could do this on every blorp call but that's not really
1379 * needed as all of the data will get written by the CPU prior to the GPU
1380 * executing anything. The chances are fairly high that they will use
1381 * blorp at least once per primary command buffer so it shouldn't be
1382 * wasted.
1383 */
1384 if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY)
1385 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1386
1387 /* We send an "Indirect State Pointers Disable" packet at
1388 * EndCommandBuffer, so all push contant packets are ignored during a
1389 * context restore. Documentation says after that command, we need to
1390 * emit push constants again before any rendering operation. So we
1391 * flag them dirty here to make sure they get emitted.
1392 */
1393 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1394
1395 VkResult result = VK_SUCCESS;
1396 if (cmd_buffer->usage_flags &
1397 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1398 assert(pBeginInfo->pInheritanceInfo);
1399 cmd_buffer->state.pass =
1400 anv_render_pass_from_handle(pBeginInfo->pInheritanceInfo->renderPass);
1401 cmd_buffer->state.subpass =
1402 &cmd_buffer->state.pass->subpasses[pBeginInfo->pInheritanceInfo->subpass];
1403
1404 /* This is optional in the inheritance info. */
1405 cmd_buffer->state.framebuffer =
1406 anv_framebuffer_from_handle(pBeginInfo->pInheritanceInfo->framebuffer);
1407
1408 result = genX(cmd_buffer_setup_attachments)(cmd_buffer,
1409 cmd_buffer->state.pass, NULL);
1410
1411 /* Record that HiZ is enabled if we can. */
1412 if (cmd_buffer->state.framebuffer) {
1413 const struct anv_image_view * const iview =
1414 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
1415
1416 if (iview) {
1417 VkImageLayout layout =
1418 cmd_buffer->state.subpass->depth_stencil_attachment->layout;
1419
1420 enum isl_aux_usage aux_usage =
1421 anv_layout_to_aux_usage(&cmd_buffer->device->info, iview->image,
1422 VK_IMAGE_ASPECT_DEPTH_BIT, layout);
1423
1424 cmd_buffer->state.hiz_enabled = aux_usage == ISL_AUX_USAGE_HIZ;
1425 }
1426 }
1427
1428 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
1429 }
1430
1431 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1432 if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
1433 const VkCommandBufferInheritanceConditionalRenderingInfoEXT *conditional_rendering_info =
1434 vk_find_struct_const(pBeginInfo->pInheritanceInfo->pNext, COMMAND_BUFFER_INHERITANCE_CONDITIONAL_RENDERING_INFO_EXT);
1435
1436 /* If secondary buffer supports conditional rendering
1437 * we should emit commands as if conditional rendering is enabled.
1438 */
1439 cmd_buffer->state.conditional_render_enabled =
1440 conditional_rendering_info && conditional_rendering_info->conditionalRenderingEnable;
1441 }
1442 #endif
1443
1444 return result;
1445 }
1446
1447 /* From the PRM, Volume 2a:
1448 *
1449 * "Indirect State Pointers Disable
1450 *
1451 * At the completion of the post-sync operation associated with this pipe
1452 * control packet, the indirect state pointers in the hardware are
1453 * considered invalid; the indirect pointers are not saved in the context.
1454 * If any new indirect state commands are executed in the command stream
1455 * while the pipe control is pending, the new indirect state commands are
1456 * preserved.
1457 *
1458 * [DevIVB+]: Using Invalidate State Pointer (ISP) only inhibits context
1459 * restoring of Push Constant (3DSTATE_CONSTANT_*) commands. Push Constant
1460 * commands are only considered as Indirect State Pointers. Once ISP is
1461 * issued in a context, SW must initialize by programming push constant
1462 * commands for all the shaders (at least to zero length) before attempting
1463 * any rendering operation for the same context."
1464 *
1465 * 3DSTATE_CONSTANT_* packets are restored during a context restore,
1466 * even though they point to a BO that has been already unreferenced at
1467 * the end of the previous batch buffer. This has been fine so far since
1468 * we are protected by these scratch page (every address not covered by
1469 * a BO should be pointing to the scratch page). But on CNL, it is
1470 * causing a GPU hang during context restore at the 3DSTATE_CONSTANT_*
1471 * instruction.
1472 *
1473 * The flag "Indirect State Pointers Disable" in PIPE_CONTROL tells the
1474 * hardware to ignore previous 3DSTATE_CONSTANT_* packets during a
1475 * context restore, so the mentioned hang doesn't happen. However,
1476 * software must program push constant commands for all stages prior to
1477 * rendering anything. So we flag them dirty in BeginCommandBuffer.
1478 *
1479 * Finally, we also make sure to stall at pixel scoreboard to make sure the
1480 * constants have been loaded into the EUs prior to disable the push constants
1481 * so that it doesn't hang a previous 3DPRIMITIVE.
1482 */
1483 static void
1484 emit_isp_disable(struct anv_cmd_buffer *cmd_buffer)
1485 {
1486 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1487 pc.StallAtPixelScoreboard = true;
1488 pc.CommandStreamerStallEnable = true;
1489 }
1490 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1491 pc.IndirectStatePointersDisable = true;
1492 pc.CommandStreamerStallEnable = true;
1493 }
1494 }
1495
1496 VkResult
1497 genX(EndCommandBuffer)(
1498 VkCommandBuffer commandBuffer)
1499 {
1500 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1501
1502 if (anv_batch_has_error(&cmd_buffer->batch))
1503 return cmd_buffer->batch.status;
1504
1505 /* We want every command buffer to start with the PMA fix in a known state,
1506 * so we disable it at the end of the command buffer.
1507 */
1508 genX(cmd_buffer_enable_pma_fix)(cmd_buffer, false);
1509
1510 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
1511
1512 emit_isp_disable(cmd_buffer);
1513
1514 anv_cmd_buffer_end_batch_buffer(cmd_buffer);
1515
1516 return VK_SUCCESS;
1517 }
1518
1519 void
1520 genX(CmdExecuteCommands)(
1521 VkCommandBuffer commandBuffer,
1522 uint32_t commandBufferCount,
1523 const VkCommandBuffer* pCmdBuffers)
1524 {
1525 ANV_FROM_HANDLE(anv_cmd_buffer, primary, commandBuffer);
1526
1527 assert(primary->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1528
1529 if (anv_batch_has_error(&primary->batch))
1530 return;
1531
1532 /* The secondary command buffers will assume that the PMA fix is disabled
1533 * when they begin executing. Make sure this is true.
1534 */
1535 genX(cmd_buffer_enable_pma_fix)(primary, false);
1536
1537 /* The secondary command buffer doesn't know which textures etc. have been
1538 * flushed prior to their execution. Apply those flushes now.
1539 */
1540 genX(cmd_buffer_apply_pipe_flushes)(primary);
1541
1542 for (uint32_t i = 0; i < commandBufferCount; i++) {
1543 ANV_FROM_HANDLE(anv_cmd_buffer, secondary, pCmdBuffers[i]);
1544
1545 assert(secondary->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY);
1546 assert(!anv_batch_has_error(&secondary->batch));
1547
1548 #if GEN_GEN >= 8 || GEN_IS_HASWELL
1549 if (secondary->state.conditional_render_enabled) {
1550 if (!primary->state.conditional_render_enabled) {
1551 /* Secondary buffer is constructed as if it will be executed
1552 * with conditional rendering, we should satisfy this dependency
1553 * regardless of conditional rendering being enabled in primary.
1554 */
1555 struct gen_mi_builder b;
1556 gen_mi_builder_init(&b, &primary->batch);
1557 gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
1558 gen_mi_imm(UINT64_MAX));
1559 }
1560 }
1561 #endif
1562
1563 if (secondary->usage_flags &
1564 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1565 /* If we're continuing a render pass from the primary, we need to
1566 * copy the surface states for the current subpass into the storage
1567 * we allocated for them in BeginCommandBuffer.
1568 */
1569 struct anv_bo *ss_bo =
1570 primary->device->surface_state_pool.block_pool.bo;
1571 struct anv_state src_state = primary->state.render_pass_states;
1572 struct anv_state dst_state = secondary->state.render_pass_states;
1573 assert(src_state.alloc_size == dst_state.alloc_size);
1574
1575 genX(cmd_buffer_so_memcpy)(primary,
1576 (struct anv_address) {
1577 .bo = ss_bo,
1578 .offset = dst_state.offset,
1579 },
1580 (struct anv_address) {
1581 .bo = ss_bo,
1582 .offset = src_state.offset,
1583 },
1584 src_state.alloc_size);
1585 }
1586
1587 anv_cmd_buffer_add_secondary(primary, secondary);
1588 }
1589
1590 /* The secondary may have selected a different pipeline (3D or compute) and
1591 * may have changed the current L3$ configuration. Reset our tracking
1592 * variables to invalid values to ensure that we re-emit these in the case
1593 * where we do any draws or compute dispatches from the primary after the
1594 * secondary has returned.
1595 */
1596 primary->state.current_pipeline = UINT32_MAX;
1597 primary->state.current_l3_config = NULL;
1598
1599 /* Each of the secondary command buffers will use its own state base
1600 * address. We need to re-emit state base address for the primary after
1601 * all of the secondaries are done.
1602 *
1603 * TODO: Maybe we want to make this a dirty bit to avoid extra state base
1604 * address calls?
1605 */
1606 genX(cmd_buffer_emit_state_base_address)(primary);
1607 }
1608
1609 #define IVB_L3SQCREG1_SQGHPCI_DEFAULT 0x00730000
1610 #define VLV_L3SQCREG1_SQGHPCI_DEFAULT 0x00d30000
1611 #define HSW_L3SQCREG1_SQGHPCI_DEFAULT 0x00610000
1612
1613 /**
1614 * Program the hardware to use the specified L3 configuration.
1615 */
1616 void
1617 genX(cmd_buffer_config_l3)(struct anv_cmd_buffer *cmd_buffer,
1618 const struct gen_l3_config *cfg)
1619 {
1620 assert(cfg);
1621 if (cfg == cmd_buffer->state.current_l3_config)
1622 return;
1623
1624 if (unlikely(INTEL_DEBUG & DEBUG_L3)) {
1625 intel_logd("L3 config transition: ");
1626 gen_dump_l3_config(cfg, stderr);
1627 }
1628
1629 const bool has_slm = cfg->n[GEN_L3P_SLM];
1630
1631 /* According to the hardware docs, the L3 partitioning can only be changed
1632 * while the pipeline is completely drained and the caches are flushed,
1633 * which involves a first PIPE_CONTROL flush which stalls the pipeline...
1634 */
1635 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1636 pc.DCFlushEnable = true;
1637 pc.PostSyncOperation = NoWrite;
1638 pc.CommandStreamerStallEnable = true;
1639 }
1640
1641 /* ...followed by a second pipelined PIPE_CONTROL that initiates
1642 * invalidation of the relevant caches. Note that because RO invalidation
1643 * happens at the top of the pipeline (i.e. right away as the PIPE_CONTROL
1644 * command is processed by the CS) we cannot combine it with the previous
1645 * stalling flush as the hardware documentation suggests, because that
1646 * would cause the CS to stall on previous rendering *after* RO
1647 * invalidation and wouldn't prevent the RO caches from being polluted by
1648 * concurrent rendering before the stall completes. This intentionally
1649 * doesn't implement the SKL+ hardware workaround suggesting to enable CS
1650 * stall on PIPE_CONTROLs with the texture cache invalidation bit set for
1651 * GPGPU workloads because the previous and subsequent PIPE_CONTROLs
1652 * already guarantee that there is no concurrent GPGPU kernel execution
1653 * (see SKL HSD 2132585).
1654 */
1655 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1656 pc.TextureCacheInvalidationEnable = true;
1657 pc.ConstantCacheInvalidationEnable = true;
1658 pc.InstructionCacheInvalidateEnable = true;
1659 pc.StateCacheInvalidationEnable = true;
1660 pc.PostSyncOperation = NoWrite;
1661 }
1662
1663 /* Now send a third stalling flush to make sure that invalidation is
1664 * complete when the L3 configuration registers are modified.
1665 */
1666 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1667 pc.DCFlushEnable = true;
1668 pc.PostSyncOperation = NoWrite;
1669 pc.CommandStreamerStallEnable = true;
1670 }
1671
1672 #if GEN_GEN >= 8
1673
1674 assert(!cfg->n[GEN_L3P_IS] && !cfg->n[GEN_L3P_C] && !cfg->n[GEN_L3P_T]);
1675
1676 uint32_t l3cr;
1677 anv_pack_struct(&l3cr, GENX(L3CNTLREG),
1678 .SLMEnable = has_slm,
1679 #if GEN_GEN == 11
1680 /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
1681 * in L3CNTLREG register. The default setting of the bit is not the
1682 * desirable behavior.
1683 */
1684 .ErrorDetectionBehaviorControl = true,
1685 .UseFullWays = true,
1686 #endif
1687 .URBAllocation = cfg->n[GEN_L3P_URB],
1688 .ROAllocation = cfg->n[GEN_L3P_RO],
1689 .DCAllocation = cfg->n[GEN_L3P_DC],
1690 .AllAllocation = cfg->n[GEN_L3P_ALL]);
1691
1692 /* Set up the L3 partitioning. */
1693 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG_num), l3cr);
1694
1695 #else
1696
1697 const bool has_dc = cfg->n[GEN_L3P_DC] || cfg->n[GEN_L3P_ALL];
1698 const bool has_is = cfg->n[GEN_L3P_IS] || cfg->n[GEN_L3P_RO] ||
1699 cfg->n[GEN_L3P_ALL];
1700 const bool has_c = cfg->n[GEN_L3P_C] || cfg->n[GEN_L3P_RO] ||
1701 cfg->n[GEN_L3P_ALL];
1702 const bool has_t = cfg->n[GEN_L3P_T] || cfg->n[GEN_L3P_RO] ||
1703 cfg->n[GEN_L3P_ALL];
1704
1705 assert(!cfg->n[GEN_L3P_ALL]);
1706
1707 /* When enabled SLM only uses a portion of the L3 on half of the banks,
1708 * the matching space on the remaining banks has to be allocated to a
1709 * client (URB for all validated configurations) set to the
1710 * lower-bandwidth 2-bank address hashing mode.
1711 */
1712 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1713 const bool urb_low_bw = has_slm && !devinfo->is_baytrail;
1714 assert(!urb_low_bw || cfg->n[GEN_L3P_URB] == cfg->n[GEN_L3P_SLM]);
1715
1716 /* Minimum number of ways that can be allocated to the URB. */
1717 const unsigned n0_urb = devinfo->is_baytrail ? 32 : 0;
1718 assert(cfg->n[GEN_L3P_URB] >= n0_urb);
1719
1720 uint32_t l3sqcr1, l3cr2, l3cr3;
1721 anv_pack_struct(&l3sqcr1, GENX(L3SQCREG1),
1722 .ConvertDC_UC = !has_dc,
1723 .ConvertIS_UC = !has_is,
1724 .ConvertC_UC = !has_c,
1725 .ConvertT_UC = !has_t);
1726 l3sqcr1 |=
1727 GEN_IS_HASWELL ? HSW_L3SQCREG1_SQGHPCI_DEFAULT :
1728 devinfo->is_baytrail ? VLV_L3SQCREG1_SQGHPCI_DEFAULT :
1729 IVB_L3SQCREG1_SQGHPCI_DEFAULT;
1730
1731 anv_pack_struct(&l3cr2, GENX(L3CNTLREG2),
1732 .SLMEnable = has_slm,
1733 .URBLowBandwidth = urb_low_bw,
1734 .URBAllocation = cfg->n[GEN_L3P_URB] - n0_urb,
1735 #if !GEN_IS_HASWELL
1736 .ALLAllocation = cfg->n[GEN_L3P_ALL],
1737 #endif
1738 .ROAllocation = cfg->n[GEN_L3P_RO],
1739 .DCAllocation = cfg->n[GEN_L3P_DC]);
1740
1741 anv_pack_struct(&l3cr3, GENX(L3CNTLREG3),
1742 .ISAllocation = cfg->n[GEN_L3P_IS],
1743 .ISLowBandwidth = 0,
1744 .CAllocation = cfg->n[GEN_L3P_C],
1745 .CLowBandwidth = 0,
1746 .TAllocation = cfg->n[GEN_L3P_T],
1747 .TLowBandwidth = 0);
1748
1749 /* Set up the L3 partitioning. */
1750 emit_lri(&cmd_buffer->batch, GENX(L3SQCREG1_num), l3sqcr1);
1751 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG2_num), l3cr2);
1752 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG3_num), l3cr3);
1753
1754 #if GEN_IS_HASWELL
1755 if (cmd_buffer->device->instance->physicalDevice.cmd_parser_version >= 4) {
1756 /* Enable L3 atomics on HSW if we have a DC partition, otherwise keep
1757 * them disabled to avoid crashing the system hard.
1758 */
1759 uint32_t scratch1, chicken3;
1760 anv_pack_struct(&scratch1, GENX(SCRATCH1),
1761 .L3AtomicDisable = !has_dc);
1762 anv_pack_struct(&chicken3, GENX(CHICKEN3),
1763 .L3AtomicDisableMask = true,
1764 .L3AtomicDisable = !has_dc);
1765 emit_lri(&cmd_buffer->batch, GENX(SCRATCH1_num), scratch1);
1766 emit_lri(&cmd_buffer->batch, GENX(CHICKEN3_num), chicken3);
1767 }
1768 #endif
1769
1770 #endif
1771
1772 cmd_buffer->state.current_l3_config = cfg;
1773 }
1774
1775 void
1776 genX(cmd_buffer_apply_pipe_flushes)(struct anv_cmd_buffer *cmd_buffer)
1777 {
1778 enum anv_pipe_bits bits = cmd_buffer->state.pending_pipe_bits;
1779
1780 /* Flushes are pipelined while invalidations are handled immediately.
1781 * Therefore, if we're flushing anything then we need to schedule a stall
1782 * before any invalidations can happen.
1783 */
1784 if (bits & ANV_PIPE_FLUSH_BITS)
1785 bits |= ANV_PIPE_NEEDS_CS_STALL_BIT;
1786
1787 /* If we're going to do an invalidate and we have a pending CS stall that
1788 * has yet to be resolved, we do the CS stall now.
1789 */
1790 if ((bits & ANV_PIPE_INVALIDATE_BITS) &&
1791 (bits & ANV_PIPE_NEEDS_CS_STALL_BIT)) {
1792 bits |= ANV_PIPE_CS_STALL_BIT;
1793 bits &= ~ANV_PIPE_NEEDS_CS_STALL_BIT;
1794 }
1795
1796 if (bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT)) {
1797 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1798 pipe.DepthCacheFlushEnable = bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1799 pipe.DCFlushEnable = bits & ANV_PIPE_DATA_CACHE_FLUSH_BIT;
1800 pipe.RenderTargetCacheFlushEnable =
1801 bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1802
1803 pipe.DepthStallEnable = bits & ANV_PIPE_DEPTH_STALL_BIT;
1804 pipe.CommandStreamerStallEnable = bits & ANV_PIPE_CS_STALL_BIT;
1805 pipe.StallAtPixelScoreboard = bits & ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
1806
1807 /*
1808 * According to the Broadwell documentation, any PIPE_CONTROL with the
1809 * "Command Streamer Stall" bit set must also have another bit set,
1810 * with five different options:
1811 *
1812 * - Render Target Cache Flush
1813 * - Depth Cache Flush
1814 * - Stall at Pixel Scoreboard
1815 * - Post-Sync Operation
1816 * - Depth Stall
1817 * - DC Flush Enable
1818 *
1819 * I chose "Stall at Pixel Scoreboard" since that's what we use in
1820 * mesa and it seems to work fine. The choice is fairly arbitrary.
1821 */
1822 if ((bits & ANV_PIPE_CS_STALL_BIT) &&
1823 !(bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_DEPTH_STALL_BIT |
1824 ANV_PIPE_STALL_AT_SCOREBOARD_BIT)))
1825 pipe.StallAtPixelScoreboard = true;
1826 }
1827
1828 /* If a render target flush was emitted, then we can toggle off the bit
1829 * saying that render target writes are ongoing.
1830 */
1831 if (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
1832 bits &= ~(ANV_PIPE_RENDER_TARGET_BUFFER_WRITES);
1833
1834 bits &= ~(ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT);
1835 }
1836
1837 if (bits & ANV_PIPE_INVALIDATE_BITS) {
1838 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1839 *
1840 * "If the VF Cache Invalidation Enable is set to a 1 in a
1841 * PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields sets to
1842 * 0, with the VF Cache Invalidation Enable set to 0 needs to be sent
1843 * prior to the PIPE_CONTROL with VF Cache Invalidation Enable set to
1844 * a 1."
1845 *
1846 * This appears to hang Broadwell, so we restrict it to just gen9.
1847 */
1848 if (GEN_GEN == 9 && (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT))
1849 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe);
1850
1851 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1852 pipe.StateCacheInvalidationEnable =
1853 bits & ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
1854 pipe.ConstantCacheInvalidationEnable =
1855 bits & ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
1856 pipe.VFCacheInvalidationEnable =
1857 bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1858 pipe.TextureCacheInvalidationEnable =
1859 bits & ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1860 pipe.InstructionCacheInvalidateEnable =
1861 bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT;
1862
1863 /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1864 *
1865 * "When VF Cache Invalidate is set “Post Sync Operation” must be
1866 * enabled to “Write Immediate Data” or “Write PS Depth Count” or
1867 * “Write Timestamp”.
1868 */
1869 if (GEN_GEN == 9 && pipe.VFCacheInvalidationEnable) {
1870 pipe.PostSyncOperation = WriteImmediateData;
1871 pipe.Address =
1872 (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
1873 }
1874 }
1875
1876 bits &= ~ANV_PIPE_INVALIDATE_BITS;
1877 }
1878
1879 cmd_buffer->state.pending_pipe_bits = bits;
1880 }
1881
1882 void genX(CmdPipelineBarrier)(
1883 VkCommandBuffer commandBuffer,
1884 VkPipelineStageFlags srcStageMask,
1885 VkPipelineStageFlags destStageMask,
1886 VkBool32 byRegion,
1887 uint32_t memoryBarrierCount,
1888 const VkMemoryBarrier* pMemoryBarriers,
1889 uint32_t bufferMemoryBarrierCount,
1890 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1891 uint32_t imageMemoryBarrierCount,
1892 const VkImageMemoryBarrier* pImageMemoryBarriers)
1893 {
1894 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1895
1896 /* XXX: Right now, we're really dumb and just flush whatever categories
1897 * the app asks for. One of these days we may make this a bit better
1898 * but right now that's all the hardware allows for in most areas.
1899 */
1900 VkAccessFlags src_flags = 0;
1901 VkAccessFlags dst_flags = 0;
1902
1903 for (uint32_t i = 0; i < memoryBarrierCount; i++) {
1904 src_flags |= pMemoryBarriers[i].srcAccessMask;
1905 dst_flags |= pMemoryBarriers[i].dstAccessMask;
1906 }
1907
1908 for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
1909 src_flags |= pBufferMemoryBarriers[i].srcAccessMask;
1910 dst_flags |= pBufferMemoryBarriers[i].dstAccessMask;
1911 }
1912
1913 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1914 src_flags |= pImageMemoryBarriers[i].srcAccessMask;
1915 dst_flags |= pImageMemoryBarriers[i].dstAccessMask;
1916 ANV_FROM_HANDLE(anv_image, image, pImageMemoryBarriers[i].image);
1917 const VkImageSubresourceRange *range =
1918 &pImageMemoryBarriers[i].subresourceRange;
1919
1920 uint32_t base_layer, layer_count;
1921 if (image->type == VK_IMAGE_TYPE_3D) {
1922 base_layer = 0;
1923 layer_count = anv_minify(image->extent.depth, range->baseMipLevel);
1924 } else {
1925 base_layer = range->baseArrayLayer;
1926 layer_count = anv_get_layerCount(image, range);
1927 }
1928
1929 if (range->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1930 transition_depth_buffer(cmd_buffer, image,
1931 pImageMemoryBarriers[i].oldLayout,
1932 pImageMemoryBarriers[i].newLayout);
1933 }
1934
1935 if (range->aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1936 transition_stencil_buffer(cmd_buffer, image,
1937 range->baseMipLevel,
1938 anv_get_levelCount(image, range),
1939 base_layer, layer_count,
1940 pImageMemoryBarriers[i].oldLayout,
1941 pImageMemoryBarriers[i].newLayout);
1942 }
1943
1944 if (range->aspectMask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1945 VkImageAspectFlags color_aspects =
1946 anv_image_expand_aspects(image, range->aspectMask);
1947 uint32_t aspect_bit;
1948 anv_foreach_image_aspect_bit(aspect_bit, image, color_aspects) {
1949 transition_color_buffer(cmd_buffer, image, 1UL << aspect_bit,
1950 range->baseMipLevel,
1951 anv_get_levelCount(image, range),
1952 base_layer, layer_count,
1953 pImageMemoryBarriers[i].oldLayout,
1954 pImageMemoryBarriers[i].newLayout);
1955 }
1956 }
1957 }
1958
1959 cmd_buffer->state.pending_pipe_bits |=
1960 anv_pipe_flush_bits_for_access_flags(src_flags) |
1961 anv_pipe_invalidate_bits_for_access_flags(dst_flags);
1962 }
1963
1964 static void
1965 cmd_buffer_alloc_push_constants(struct anv_cmd_buffer *cmd_buffer)
1966 {
1967 VkShaderStageFlags stages =
1968 cmd_buffer->state.gfx.base.pipeline->active_stages;
1969
1970 /* In order to avoid thrash, we assume that vertex and fragment stages
1971 * always exist. In the rare case where one is missing *and* the other
1972 * uses push concstants, this may be suboptimal. However, avoiding stalls
1973 * seems more important.
1974 */
1975 stages |= VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT;
1976
1977 if (stages == cmd_buffer->state.push_constant_stages)
1978 return;
1979
1980 #if GEN_GEN >= 8
1981 const unsigned push_constant_kb = 32;
1982 #elif GEN_IS_HASWELL
1983 const unsigned push_constant_kb = cmd_buffer->device->info.gt == 3 ? 32 : 16;
1984 #else
1985 const unsigned push_constant_kb = 16;
1986 #endif
1987
1988 const unsigned num_stages =
1989 util_bitcount(stages & VK_SHADER_STAGE_ALL_GRAPHICS);
1990 unsigned size_per_stage = push_constant_kb / num_stages;
1991
1992 /* Broadwell+ and Haswell gt3 require that the push constant sizes be in
1993 * units of 2KB. Incidentally, these are the same platforms that have
1994 * 32KB worth of push constant space.
1995 */
1996 if (push_constant_kb == 32)
1997 size_per_stage &= ~1u;
1998
1999 uint32_t kb_used = 0;
2000 for (int i = MESA_SHADER_VERTEX; i < MESA_SHADER_FRAGMENT; i++) {
2001 unsigned push_size = (stages & (1 << i)) ? size_per_stage : 0;
2002 anv_batch_emit(&cmd_buffer->batch,
2003 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
2004 alloc._3DCommandSubOpcode = 18 + i;
2005 alloc.ConstantBufferOffset = (push_size > 0) ? kb_used : 0;
2006 alloc.ConstantBufferSize = push_size;
2007 }
2008 kb_used += push_size;
2009 }
2010
2011 anv_batch_emit(&cmd_buffer->batch,
2012 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_PS), alloc) {
2013 alloc.ConstantBufferOffset = kb_used;
2014 alloc.ConstantBufferSize = push_constant_kb - kb_used;
2015 }
2016
2017 cmd_buffer->state.push_constant_stages = stages;
2018
2019 /* From the BDW PRM for 3DSTATE_PUSH_CONSTANT_ALLOC_VS:
2020 *
2021 * "The 3DSTATE_CONSTANT_VS must be reprogrammed prior to
2022 * the next 3DPRIMITIVE command after programming the
2023 * 3DSTATE_PUSH_CONSTANT_ALLOC_VS"
2024 *
2025 * Since 3DSTATE_PUSH_CONSTANT_ALLOC_VS is programmed as part of
2026 * pipeline setup, we need to dirty push constants.
2027 */
2028 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
2029 }
2030
2031 static const struct anv_descriptor *
2032 anv_descriptor_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
2033 const struct anv_pipeline_binding *binding)
2034 {
2035 assert(binding->set < MAX_SETS);
2036 const struct anv_descriptor_set *set =
2037 pipe_state->descriptors[binding->set];
2038 const uint32_t offset =
2039 set->layout->binding[binding->binding].descriptor_index;
2040 return &set->descriptors[offset + binding->index];
2041 }
2042
2043 static uint32_t
2044 dynamic_offset_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
2045 const struct anv_pipeline_binding *binding)
2046 {
2047 assert(binding->set < MAX_SETS);
2048 const struct anv_descriptor_set *set =
2049 pipe_state->descriptors[binding->set];
2050
2051 uint32_t dynamic_offset_idx =
2052 pipe_state->layout->set[binding->set].dynamic_offset_start +
2053 set->layout->binding[binding->binding].dynamic_offset_index +
2054 binding->index;
2055
2056 return pipe_state->dynamic_offsets[dynamic_offset_idx];
2057 }
2058
2059 static struct anv_address
2060 anv_descriptor_set_address(struct anv_cmd_buffer *cmd_buffer,
2061 struct anv_descriptor_set *set)
2062 {
2063 if (set->pool) {
2064 /* This is a normal descriptor set */
2065 return (struct anv_address) {
2066 .bo = &set->pool->bo,
2067 .offset = set->desc_mem.offset,
2068 };
2069 } else {
2070 /* This is a push descriptor set. We have to flag it as used on the GPU
2071 * so that the next time we push descriptors, we grab a new memory.
2072 */
2073 struct anv_push_descriptor_set *push_set =
2074 (struct anv_push_descriptor_set *)set;
2075 push_set->set_used_on_gpu = true;
2076
2077 return (struct anv_address) {
2078 .bo = cmd_buffer->dynamic_state_stream.state_pool->block_pool.bo,
2079 .offset = set->desc_mem.offset,
2080 };
2081 }
2082 }
2083
2084 static VkResult
2085 emit_binding_table(struct anv_cmd_buffer *cmd_buffer,
2086 gl_shader_stage stage,
2087 struct anv_state *bt_state)
2088 {
2089 struct anv_subpass *subpass = cmd_buffer->state.subpass;
2090 struct anv_cmd_pipeline_state *pipe_state;
2091 struct anv_pipeline *pipeline;
2092 uint32_t state_offset;
2093
2094 switch (stage) {
2095 case MESA_SHADER_COMPUTE:
2096 pipe_state = &cmd_buffer->state.compute.base;
2097 break;
2098 default:
2099 pipe_state = &cmd_buffer->state.gfx.base;
2100 break;
2101 }
2102 pipeline = pipe_state->pipeline;
2103
2104 if (!anv_pipeline_has_stage(pipeline, stage)) {
2105 *bt_state = (struct anv_state) { 0, };
2106 return VK_SUCCESS;
2107 }
2108
2109 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2110 if (map->surface_count == 0) {
2111 *bt_state = (struct anv_state) { 0, };
2112 return VK_SUCCESS;
2113 }
2114
2115 *bt_state = anv_cmd_buffer_alloc_binding_table(cmd_buffer,
2116 map->surface_count,
2117 &state_offset);
2118 uint32_t *bt_map = bt_state->map;
2119
2120 if (bt_state->map == NULL)
2121 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2122
2123 /* We only need to emit relocs if we're not using softpin. If we are using
2124 * softpin then we always keep all user-allocated memory objects resident.
2125 */
2126 const bool need_client_mem_relocs =
2127 !cmd_buffer->device->instance->physicalDevice.use_softpin;
2128
2129 for (uint32_t s = 0; s < map->surface_count; s++) {
2130 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[s];
2131
2132 struct anv_state surface_state;
2133
2134 if (binding->set == ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS) {
2135 /* Color attachment binding */
2136 assert(stage == MESA_SHADER_FRAGMENT);
2137 assert(binding->binding == 0);
2138 if (binding->index < subpass->color_count) {
2139 const unsigned att =
2140 subpass->color_attachments[binding->index].attachment;
2141
2142 /* From the Vulkan 1.0.46 spec:
2143 *
2144 * "If any color or depth/stencil attachments are
2145 * VK_ATTACHMENT_UNUSED, then no writes occur for those
2146 * attachments."
2147 */
2148 if (att == VK_ATTACHMENT_UNUSED) {
2149 surface_state = cmd_buffer->state.null_surface_state;
2150 } else {
2151 surface_state = cmd_buffer->state.attachments[att].color.state;
2152 }
2153 } else {
2154 surface_state = cmd_buffer->state.null_surface_state;
2155 }
2156
2157 bt_map[s] = surface_state.offset + state_offset;
2158 continue;
2159 } else if (binding->set == ANV_DESCRIPTOR_SET_SHADER_CONSTANTS) {
2160 struct anv_state surface_state =
2161 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2162
2163 struct anv_address constant_data = {
2164 .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2165 .offset = pipeline->shaders[stage]->constant_data.offset,
2166 };
2167 unsigned constant_data_size =
2168 pipeline->shaders[stage]->constant_data_size;
2169
2170 const enum isl_format format =
2171 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2172 anv_fill_buffer_surface_state(cmd_buffer->device,
2173 surface_state, format,
2174 constant_data, constant_data_size, 1);
2175
2176 bt_map[s] = surface_state.offset + state_offset;
2177 add_surface_reloc(cmd_buffer, surface_state, constant_data);
2178 continue;
2179 } else if (binding->set == ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS) {
2180 /* This is always the first binding for compute shaders */
2181 assert(stage == MESA_SHADER_COMPUTE && s == 0);
2182 if (!get_cs_prog_data(pipeline)->uses_num_work_groups)
2183 continue;
2184
2185 struct anv_state surface_state =
2186 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2187
2188 const enum isl_format format =
2189 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2190 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2191 format,
2192 cmd_buffer->state.compute.num_workgroups,
2193 12, 1);
2194 bt_map[s] = surface_state.offset + state_offset;
2195 if (need_client_mem_relocs) {
2196 add_surface_reloc(cmd_buffer, surface_state,
2197 cmd_buffer->state.compute.num_workgroups);
2198 }
2199 continue;
2200 } else if (binding->set == ANV_DESCRIPTOR_SET_DESCRIPTORS) {
2201 /* This is a descriptor set buffer so the set index is actually
2202 * given by binding->binding. (Yes, that's confusing.)
2203 */
2204 struct anv_descriptor_set *set =
2205 pipe_state->descriptors[binding->binding];
2206 assert(set->desc_mem.alloc_size);
2207 assert(set->desc_surface_state.alloc_size);
2208 bt_map[s] = set->desc_surface_state.offset + state_offset;
2209 add_surface_reloc(cmd_buffer, set->desc_surface_state,
2210 anv_descriptor_set_address(cmd_buffer, set));
2211 continue;
2212 }
2213
2214 const struct anv_descriptor *desc =
2215 anv_descriptor_for_binding(pipe_state, binding);
2216
2217 switch (desc->type) {
2218 case VK_DESCRIPTOR_TYPE_SAMPLER:
2219 /* Nothing for us to do here */
2220 continue;
2221
2222 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2223 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
2224 struct anv_surface_state sstate =
2225 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2226 desc->image_view->planes[binding->plane].general_sampler_surface_state :
2227 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2228 surface_state = sstate.state;
2229 assert(surface_state.alloc_size);
2230 if (need_client_mem_relocs)
2231 add_surface_state_relocs(cmd_buffer, sstate);
2232 break;
2233 }
2234 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2235 assert(stage == MESA_SHADER_FRAGMENT);
2236 if ((desc->image_view->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) == 0) {
2237 /* For depth and stencil input attachments, we treat it like any
2238 * old texture that a user may have bound.
2239 */
2240 struct anv_surface_state sstate =
2241 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2242 desc->image_view->planes[binding->plane].general_sampler_surface_state :
2243 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2244 surface_state = sstate.state;
2245 assert(surface_state.alloc_size);
2246 if (need_client_mem_relocs)
2247 add_surface_state_relocs(cmd_buffer, sstate);
2248 } else {
2249 /* For color input attachments, we create the surface state at
2250 * vkBeginRenderPass time so that we can include aux and clear
2251 * color information.
2252 */
2253 assert(binding->input_attachment_index < subpass->input_count);
2254 const unsigned subpass_att = binding->input_attachment_index;
2255 const unsigned att = subpass->input_attachments[subpass_att].attachment;
2256 surface_state = cmd_buffer->state.attachments[att].input.state;
2257 }
2258 break;
2259
2260 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
2261 struct anv_surface_state sstate = (binding->write_only)
2262 ? desc->image_view->planes[binding->plane].writeonly_storage_surface_state
2263 : desc->image_view->planes[binding->plane].storage_surface_state;
2264 surface_state = sstate.state;
2265 assert(surface_state.alloc_size);
2266 if (need_client_mem_relocs)
2267 add_surface_state_relocs(cmd_buffer, sstate);
2268 break;
2269 }
2270
2271 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2272 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2273 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2274 surface_state = desc->buffer_view->surface_state;
2275 assert(surface_state.alloc_size);
2276 if (need_client_mem_relocs) {
2277 add_surface_reloc(cmd_buffer, surface_state,
2278 desc->buffer_view->address);
2279 }
2280 break;
2281
2282 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2283 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
2284 /* Compute the offset within the buffer */
2285 uint32_t dynamic_offset =
2286 dynamic_offset_for_binding(pipe_state, binding);
2287 uint64_t offset = desc->offset + dynamic_offset;
2288 /* Clamp to the buffer size */
2289 offset = MIN2(offset, desc->buffer->size);
2290 /* Clamp the range to the buffer size */
2291 uint32_t range = MIN2(desc->range, desc->buffer->size - offset);
2292
2293 struct anv_address address =
2294 anv_address_add(desc->buffer->address, offset);
2295
2296 surface_state =
2297 anv_state_stream_alloc(&cmd_buffer->surface_state_stream, 64, 64);
2298 enum isl_format format =
2299 anv_isl_format_for_descriptor_type(desc->type);
2300
2301 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2302 format, address, range, 1);
2303 if (need_client_mem_relocs)
2304 add_surface_reloc(cmd_buffer, surface_state, address);
2305 break;
2306 }
2307
2308 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2309 surface_state = (binding->write_only)
2310 ? desc->buffer_view->writeonly_storage_surface_state
2311 : desc->buffer_view->storage_surface_state;
2312 assert(surface_state.alloc_size);
2313 if (need_client_mem_relocs) {
2314 add_surface_reloc(cmd_buffer, surface_state,
2315 desc->buffer_view->address);
2316 }
2317 break;
2318
2319 default:
2320 assert(!"Invalid descriptor type");
2321 continue;
2322 }
2323
2324 bt_map[s] = surface_state.offset + state_offset;
2325 }
2326
2327 #if GEN_GEN >= 11
2328 /* The PIPE_CONTROL command description says:
2329 *
2330 * "Whenever a Binding Table Index (BTI) used by a Render Taget Message
2331 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
2332 * Target Cache Flush by enabling this bit. When render target flush
2333 * is set due to new association of BTI, PS Scoreboard Stall bit must
2334 * be set in this packet."
2335 *
2336 * FINISHME: Currently we shuffle around the surface states in the binding
2337 * table based on if they are getting used or not. So, we've to do below
2338 * pipe control flush for every binding table upload. Make changes so
2339 * that we do it only when we modify render target surface states.
2340 */
2341 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2342 pc.RenderTargetCacheFlushEnable = true;
2343 pc.StallAtPixelScoreboard = true;
2344 }
2345 #endif
2346
2347 return VK_SUCCESS;
2348 }
2349
2350 static VkResult
2351 emit_samplers(struct anv_cmd_buffer *cmd_buffer,
2352 gl_shader_stage stage,
2353 struct anv_state *state)
2354 {
2355 struct anv_cmd_pipeline_state *pipe_state =
2356 stage == MESA_SHADER_COMPUTE ? &cmd_buffer->state.compute.base :
2357 &cmd_buffer->state.gfx.base;
2358 struct anv_pipeline *pipeline = pipe_state->pipeline;
2359
2360 if (!anv_pipeline_has_stage(pipeline, stage)) {
2361 *state = (struct anv_state) { 0, };
2362 return VK_SUCCESS;
2363 }
2364
2365 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2366 if (map->sampler_count == 0) {
2367 *state = (struct anv_state) { 0, };
2368 return VK_SUCCESS;
2369 }
2370
2371 uint32_t size = map->sampler_count * 16;
2372 *state = anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, size, 32);
2373
2374 if (state->map == NULL)
2375 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2376
2377 for (uint32_t s = 0; s < map->sampler_count; s++) {
2378 struct anv_pipeline_binding *binding = &map->sampler_to_descriptor[s];
2379 const struct anv_descriptor *desc =
2380 anv_descriptor_for_binding(pipe_state, binding);
2381
2382 if (desc->type != VK_DESCRIPTOR_TYPE_SAMPLER &&
2383 desc->type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
2384 continue;
2385
2386 struct anv_sampler *sampler = desc->sampler;
2387
2388 /* This can happen if we have an unfilled slot since TYPE_SAMPLER
2389 * happens to be zero.
2390 */
2391 if (sampler == NULL)
2392 continue;
2393
2394 memcpy(state->map + (s * 16),
2395 sampler->state[binding->plane], sizeof(sampler->state[0]));
2396 }
2397
2398 return VK_SUCCESS;
2399 }
2400
2401 static uint32_t
2402 flush_descriptor_sets(struct anv_cmd_buffer *cmd_buffer)
2403 {
2404 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2405
2406 VkShaderStageFlags dirty = cmd_buffer->state.descriptors_dirty &
2407 pipeline->active_stages;
2408
2409 VkResult result = VK_SUCCESS;
2410 anv_foreach_stage(s, dirty) {
2411 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2412 if (result != VK_SUCCESS)
2413 break;
2414 result = emit_binding_table(cmd_buffer, s,
2415 &cmd_buffer->state.binding_tables[s]);
2416 if (result != VK_SUCCESS)
2417 break;
2418 }
2419
2420 if (result != VK_SUCCESS) {
2421 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2422
2423 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2424 if (result != VK_SUCCESS)
2425 return 0;
2426
2427 /* Re-emit state base addresses so we get the new surface state base
2428 * address before we start emitting binding tables etc.
2429 */
2430 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2431
2432 /* Re-emit all active binding tables */
2433 dirty |= pipeline->active_stages;
2434 anv_foreach_stage(s, dirty) {
2435 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2436 if (result != VK_SUCCESS) {
2437 anv_batch_set_error(&cmd_buffer->batch, result);
2438 return 0;
2439 }
2440 result = emit_binding_table(cmd_buffer, s,
2441 &cmd_buffer->state.binding_tables[s]);
2442 if (result != VK_SUCCESS) {
2443 anv_batch_set_error(&cmd_buffer->batch, result);
2444 return 0;
2445 }
2446 }
2447 }
2448
2449 cmd_buffer->state.descriptors_dirty &= ~dirty;
2450
2451 return dirty;
2452 }
2453
2454 static void
2455 cmd_buffer_emit_descriptor_pointers(struct anv_cmd_buffer *cmd_buffer,
2456 uint32_t stages)
2457 {
2458 static const uint32_t sampler_state_opcodes[] = {
2459 [MESA_SHADER_VERTEX] = 43,
2460 [MESA_SHADER_TESS_CTRL] = 44, /* HS */
2461 [MESA_SHADER_TESS_EVAL] = 45, /* DS */
2462 [MESA_SHADER_GEOMETRY] = 46,
2463 [MESA_SHADER_FRAGMENT] = 47,
2464 [MESA_SHADER_COMPUTE] = 0,
2465 };
2466
2467 static const uint32_t binding_table_opcodes[] = {
2468 [MESA_SHADER_VERTEX] = 38,
2469 [MESA_SHADER_TESS_CTRL] = 39,
2470 [MESA_SHADER_TESS_EVAL] = 40,
2471 [MESA_SHADER_GEOMETRY] = 41,
2472 [MESA_SHADER_FRAGMENT] = 42,
2473 [MESA_SHADER_COMPUTE] = 0,
2474 };
2475
2476 anv_foreach_stage(s, stages) {
2477 assert(s < ARRAY_SIZE(binding_table_opcodes));
2478 assert(binding_table_opcodes[s] > 0);
2479
2480 if (cmd_buffer->state.samplers[s].alloc_size > 0) {
2481 anv_batch_emit(&cmd_buffer->batch,
2482 GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ssp) {
2483 ssp._3DCommandSubOpcode = sampler_state_opcodes[s];
2484 ssp.PointertoVSSamplerState = cmd_buffer->state.samplers[s].offset;
2485 }
2486 }
2487
2488 /* Always emit binding table pointers if we're asked to, since on SKL
2489 * this is what flushes push constants. */
2490 anv_batch_emit(&cmd_buffer->batch,
2491 GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), btp) {
2492 btp._3DCommandSubOpcode = binding_table_opcodes[s];
2493 btp.PointertoVSBindingTable = cmd_buffer->state.binding_tables[s].offset;
2494 }
2495 }
2496 }
2497
2498 static void
2499 cmd_buffer_flush_push_constants(struct anv_cmd_buffer *cmd_buffer,
2500 VkShaderStageFlags dirty_stages)
2501 {
2502 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2503 const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2504
2505 static const uint32_t push_constant_opcodes[] = {
2506 [MESA_SHADER_VERTEX] = 21,
2507 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2508 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2509 [MESA_SHADER_GEOMETRY] = 22,
2510 [MESA_SHADER_FRAGMENT] = 23,
2511 [MESA_SHADER_COMPUTE] = 0,
2512 };
2513
2514 VkShaderStageFlags flushed = 0;
2515
2516 anv_foreach_stage(stage, dirty_stages) {
2517 assert(stage < ARRAY_SIZE(push_constant_opcodes));
2518 assert(push_constant_opcodes[stage] > 0);
2519
2520 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_VS), c) {
2521 c._3DCommandSubOpcode = push_constant_opcodes[stage];
2522
2523 if (anv_pipeline_has_stage(pipeline, stage)) {
2524 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2525 const struct brw_stage_prog_data *prog_data =
2526 pipeline->shaders[stage]->prog_data;
2527 const struct anv_pipeline_bind_map *bind_map =
2528 &pipeline->shaders[stage]->bind_map;
2529
2530 /* The Skylake PRM contains the following restriction:
2531 *
2532 * "The driver must ensure The following case does not occur
2533 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
2534 * buffer 3 read length equal to zero committed followed by a
2535 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
2536 * zero committed."
2537 *
2538 * To avoid this, we program the buffers in the highest slots.
2539 * This way, slot 0 is only used if slot 3 is also used.
2540 */
2541 int n = 3;
2542
2543 for (int i = 3; i >= 0; i--) {
2544 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2545 if (range->length == 0)
2546 continue;
2547
2548 const unsigned surface =
2549 prog_data->binding_table.ubo_start + range->block;
2550
2551 assert(surface <= bind_map->surface_count);
2552 const struct anv_pipeline_binding *binding =
2553 &bind_map->surface_to_descriptor[surface];
2554
2555 struct anv_address read_addr;
2556 uint32_t read_len;
2557 if (binding->set == ANV_DESCRIPTOR_SET_SHADER_CONSTANTS) {
2558 struct anv_address constant_data = {
2559 .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2560 .offset = pipeline->shaders[stage]->constant_data.offset,
2561 };
2562 unsigned constant_data_size =
2563 pipeline->shaders[stage]->constant_data_size;
2564
2565 read_len = MIN2(range->length,
2566 DIV_ROUND_UP(constant_data_size, 32) - range->start);
2567 read_addr = anv_address_add(constant_data,
2568 range->start * 32);
2569 } else if (binding->set == ANV_DESCRIPTOR_SET_DESCRIPTORS) {
2570 /* This is a descriptor set buffer so the set index is
2571 * actually given by binding->binding. (Yes, that's
2572 * confusing.)
2573 */
2574 struct anv_descriptor_set *set =
2575 gfx_state->base.descriptors[binding->binding];
2576 struct anv_address desc_buffer_addr =
2577 anv_descriptor_set_address(cmd_buffer, set);
2578 const unsigned desc_buffer_size = set->desc_mem.alloc_size;
2579
2580 read_len = MIN2(range->length,
2581 DIV_ROUND_UP(desc_buffer_size, 32) - range->start);
2582 read_addr = anv_address_add(desc_buffer_addr,
2583 range->start * 32);
2584 } else {
2585 const struct anv_descriptor *desc =
2586 anv_descriptor_for_binding(&gfx_state->base, binding);
2587
2588 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2589 read_len = MIN2(range->length,
2590 DIV_ROUND_UP(desc->buffer_view->range, 32) - range->start);
2591 read_addr = anv_address_add(desc->buffer_view->address,
2592 range->start * 32);
2593 } else {
2594 assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2595
2596 uint32_t dynamic_offset =
2597 dynamic_offset_for_binding(&gfx_state->base, binding);
2598 uint32_t buf_offset =
2599 MIN2(desc->offset + dynamic_offset, desc->buffer->size);
2600 uint32_t buf_range =
2601 MIN2(desc->range, desc->buffer->size - buf_offset);
2602
2603 read_len = MIN2(range->length,
2604 DIV_ROUND_UP(buf_range, 32) - range->start);
2605 read_addr = anv_address_add(desc->buffer->address,
2606 buf_offset + range->start * 32);
2607 }
2608 }
2609
2610 if (read_len > 0) {
2611 c.ConstantBody.Buffer[n] = read_addr;
2612 c.ConstantBody.ReadLength[n] = read_len;
2613 n--;
2614 }
2615 }
2616
2617 struct anv_state state =
2618 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2619
2620 if (state.alloc_size > 0) {
2621 c.ConstantBody.Buffer[n] = (struct anv_address) {
2622 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2623 .offset = state.offset,
2624 };
2625 c.ConstantBody.ReadLength[n] =
2626 DIV_ROUND_UP(state.alloc_size, 32);
2627 }
2628 #else
2629 /* For Ivy Bridge, the push constants packets have a different
2630 * rule that would require us to iterate in the other direction
2631 * and possibly mess around with dynamic state base address.
2632 * Don't bother; just emit regular push constants at n = 0.
2633 */
2634 struct anv_state state =
2635 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2636
2637 if (state.alloc_size > 0) {
2638 c.ConstantBody.Buffer[0].offset = state.offset,
2639 c.ConstantBody.ReadLength[0] =
2640 DIV_ROUND_UP(state.alloc_size, 32);
2641 }
2642 #endif
2643 }
2644 }
2645
2646 flushed |= mesa_to_vk_shader_stage(stage);
2647 }
2648
2649 cmd_buffer->state.push_constants_dirty &= ~flushed;
2650 }
2651
2652 void
2653 genX(cmd_buffer_flush_state)(struct anv_cmd_buffer *cmd_buffer)
2654 {
2655 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2656 uint32_t *p;
2657
2658 uint32_t vb_emit = cmd_buffer->state.gfx.vb_dirty & pipeline->vb_used;
2659 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE)
2660 vb_emit |= pipeline->vb_used;
2661
2662 assert((pipeline->active_stages & VK_SHADER_STAGE_COMPUTE_BIT) == 0);
2663
2664 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
2665
2666 genX(flush_pipeline_select_3d)(cmd_buffer);
2667
2668 if (vb_emit) {
2669 const uint32_t num_buffers = __builtin_popcount(vb_emit);
2670 const uint32_t num_dwords = 1 + num_buffers * 4;
2671
2672 p = anv_batch_emitn(&cmd_buffer->batch, num_dwords,
2673 GENX(3DSTATE_VERTEX_BUFFERS));
2674 uint32_t vb, i = 0;
2675 for_each_bit(vb, vb_emit) {
2676 struct anv_buffer *buffer = cmd_buffer->state.vertex_bindings[vb].buffer;
2677 uint32_t offset = cmd_buffer->state.vertex_bindings[vb].offset;
2678
2679 struct GENX(VERTEX_BUFFER_STATE) state = {
2680 .VertexBufferIndex = vb,
2681
2682 .MOCS = anv_mocs_for_bo(cmd_buffer->device, buffer->address.bo),
2683 #if GEN_GEN <= 7
2684 .BufferAccessType = pipeline->vb[vb].instanced ? INSTANCEDATA : VERTEXDATA,
2685 .InstanceDataStepRate = pipeline->vb[vb].instance_divisor,
2686 #endif
2687
2688 .AddressModifyEnable = true,
2689 .BufferPitch = pipeline->vb[vb].stride,
2690 .BufferStartingAddress = anv_address_add(buffer->address, offset),
2691
2692 #if GEN_GEN >= 8
2693 .BufferSize = buffer->size - offset
2694 #else
2695 .EndAddress = anv_address_add(buffer->address, buffer->size - 1),
2696 #endif
2697 };
2698
2699 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, &p[1 + i * 4], &state);
2700 i++;
2701 }
2702 }
2703
2704 cmd_buffer->state.gfx.vb_dirty &= ~vb_emit;
2705
2706 #if GEN_GEN >= 8
2707 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_XFB_ENABLE) {
2708 /* We don't need any per-buffer dirty tracking because you're not
2709 * allowed to bind different XFB buffers while XFB is enabled.
2710 */
2711 for (unsigned idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
2712 struct anv_xfb_binding *xfb = &cmd_buffer->state.xfb_bindings[idx];
2713 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_SO_BUFFER), sob) {
2714 sob.SOBufferIndex = idx;
2715
2716 if (cmd_buffer->state.xfb_enabled && xfb->buffer && xfb->size != 0) {
2717 sob.SOBufferEnable = true;
2718 sob.MOCS = cmd_buffer->device->default_mocs,
2719 sob.StreamOffsetWriteEnable = false;
2720 sob.SurfaceBaseAddress = anv_address_add(xfb->buffer->address,
2721 xfb->offset);
2722 /* Size is in DWords - 1 */
2723 sob.SurfaceSize = xfb->size / 4 - 1;
2724 }
2725 }
2726 }
2727
2728 /* CNL and later require a CS stall after 3DSTATE_SO_BUFFER */
2729 if (GEN_GEN >= 10)
2730 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2731 }
2732 #endif
2733
2734 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE) {
2735 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
2736
2737 /* The exact descriptor layout is pulled from the pipeline, so we need
2738 * to re-emit binding tables on every pipeline change.
2739 */
2740 cmd_buffer->state.descriptors_dirty |= pipeline->active_stages;
2741
2742 /* If the pipeline changed, we may need to re-allocate push constant
2743 * space in the URB.
2744 */
2745 cmd_buffer_alloc_push_constants(cmd_buffer);
2746 }
2747
2748 #if GEN_GEN <= 7
2749 if (cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_VERTEX_BIT ||
2750 cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_VERTEX_BIT) {
2751 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
2752 *
2753 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth
2754 * stall needs to be sent just prior to any 3DSTATE_VS,
2755 * 3DSTATE_URB_VS, 3DSTATE_CONSTANT_VS,
2756 * 3DSTATE_BINDING_TABLE_POINTER_VS,
2757 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one
2758 * PIPE_CONTROL needs to be sent before any combination of VS
2759 * associated 3DSTATE."
2760 */
2761 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2762 pc.DepthStallEnable = true;
2763 pc.PostSyncOperation = WriteImmediateData;
2764 pc.Address =
2765 (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
2766 }
2767 }
2768 #endif
2769
2770 /* Render targets live in the same binding table as fragment descriptors */
2771 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_RENDER_TARGETS)
2772 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_FRAGMENT_BIT;
2773
2774 /* We emit the binding tables and sampler tables first, then emit push
2775 * constants and then finally emit binding table and sampler table
2776 * pointers. It has to happen in this order, since emitting the binding
2777 * tables may change the push constants (in case of storage images). After
2778 * emitting push constants, on SKL+ we have to emit the corresponding
2779 * 3DSTATE_BINDING_TABLE_POINTER_* for the push constants to take effect.
2780 */
2781 uint32_t dirty = 0;
2782 if (cmd_buffer->state.descriptors_dirty)
2783 dirty = flush_descriptor_sets(cmd_buffer);
2784
2785 if (dirty || cmd_buffer->state.push_constants_dirty) {
2786 /* Because we're pushing UBOs, we have to push whenever either
2787 * descriptors or push constants is dirty.
2788 */
2789 dirty |= cmd_buffer->state.push_constants_dirty;
2790 dirty &= ANV_STAGE_MASK & VK_SHADER_STAGE_ALL_GRAPHICS;
2791 cmd_buffer_flush_push_constants(cmd_buffer, dirty);
2792 }
2793
2794 if (dirty)
2795 cmd_buffer_emit_descriptor_pointers(cmd_buffer, dirty);
2796
2797 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT)
2798 gen8_cmd_buffer_emit_viewport(cmd_buffer);
2799
2800 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_VIEWPORT |
2801 ANV_CMD_DIRTY_PIPELINE)) {
2802 gen8_cmd_buffer_emit_depth_viewport(cmd_buffer,
2803 pipeline->depth_clamp_enable);
2804 }
2805
2806 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_SCISSOR |
2807 ANV_CMD_DIRTY_RENDER_TARGETS))
2808 gen7_cmd_buffer_emit_scissor(cmd_buffer);
2809
2810 genX(cmd_buffer_flush_dynamic_state)(cmd_buffer);
2811
2812 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
2813 }
2814
2815 static void
2816 emit_vertex_bo(struct anv_cmd_buffer *cmd_buffer,
2817 struct anv_address addr,
2818 uint32_t size, uint32_t index)
2819 {
2820 uint32_t *p = anv_batch_emitn(&cmd_buffer->batch, 5,
2821 GENX(3DSTATE_VERTEX_BUFFERS));
2822
2823 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, p + 1,
2824 &(struct GENX(VERTEX_BUFFER_STATE)) {
2825 .VertexBufferIndex = index,
2826 .AddressModifyEnable = true,
2827 .BufferPitch = 0,
2828 .MOCS = anv_mocs_for_bo(cmd_buffer->device, addr.bo),
2829 #if (GEN_GEN >= 8)
2830 .BufferStartingAddress = addr,
2831 .BufferSize = size
2832 #else
2833 .BufferStartingAddress = addr,
2834 .EndAddress = anv_address_add(addr, size),
2835 #endif
2836 });
2837 }
2838
2839 static void
2840 emit_base_vertex_instance_bo(struct anv_cmd_buffer *cmd_buffer,
2841 struct anv_address addr)
2842 {
2843 emit_vertex_bo(cmd_buffer, addr, 8, ANV_SVGS_VB_INDEX);
2844 }
2845
2846 static void
2847 emit_base_vertex_instance(struct anv_cmd_buffer *cmd_buffer,
2848 uint32_t base_vertex, uint32_t base_instance)
2849 {
2850 struct anv_state id_state =
2851 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 8, 4);
2852
2853 ((uint32_t *)id_state.map)[0] = base_vertex;
2854 ((uint32_t *)id_state.map)[1] = base_instance;
2855
2856 struct anv_address addr = {
2857 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2858 .offset = id_state.offset,
2859 };
2860
2861 emit_base_vertex_instance_bo(cmd_buffer, addr);
2862 }
2863
2864 static void
2865 emit_draw_index(struct anv_cmd_buffer *cmd_buffer, uint32_t draw_index)
2866 {
2867 struct anv_state state =
2868 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 4, 4);
2869
2870 ((uint32_t *)state.map)[0] = draw_index;
2871
2872 struct anv_address addr = {
2873 .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2874 .offset = state.offset,
2875 };
2876
2877 emit_vertex_bo(cmd_buffer, addr, 4, ANV_DRAWID_VB_INDEX);
2878 }
2879
2880 void genX(CmdDraw)(
2881 VkCommandBuffer commandBuffer,
2882 uint32_t vertexCount,
2883 uint32_t instanceCount,
2884 uint32_t firstVertex,
2885 uint32_t firstInstance)
2886 {
2887 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2888 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2889 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2890
2891 if (anv_batch_has_error(&cmd_buffer->batch))
2892 return;
2893
2894 genX(cmd_buffer_flush_state)(cmd_buffer);
2895
2896 if (cmd_buffer->state.conditional_render_enabled)
2897 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
2898
2899 if (vs_prog_data->uses_firstvertex ||
2900 vs_prog_data->uses_baseinstance)
2901 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
2902 if (vs_prog_data->uses_drawid)
2903 emit_draw_index(cmd_buffer, 0);
2904
2905 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2906 * different views. We need to multiply instanceCount by the view count.
2907 */
2908 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2909
2910 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2911 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
2912 prim.VertexAccessType = SEQUENTIAL;
2913 prim.PrimitiveTopologyType = pipeline->topology;
2914 prim.VertexCountPerInstance = vertexCount;
2915 prim.StartVertexLocation = firstVertex;
2916 prim.InstanceCount = instanceCount;
2917 prim.StartInstanceLocation = firstInstance;
2918 prim.BaseVertexLocation = 0;
2919 }
2920 }
2921
2922 void genX(CmdDrawIndexed)(
2923 VkCommandBuffer commandBuffer,
2924 uint32_t indexCount,
2925 uint32_t instanceCount,
2926 uint32_t firstIndex,
2927 int32_t vertexOffset,
2928 uint32_t firstInstance)
2929 {
2930 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2931 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2932 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2933
2934 if (anv_batch_has_error(&cmd_buffer->batch))
2935 return;
2936
2937 genX(cmd_buffer_flush_state)(cmd_buffer);
2938
2939 if (cmd_buffer->state.conditional_render_enabled)
2940 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
2941
2942 if (vs_prog_data->uses_firstvertex ||
2943 vs_prog_data->uses_baseinstance)
2944 emit_base_vertex_instance(cmd_buffer, vertexOffset, firstInstance);
2945 if (vs_prog_data->uses_drawid)
2946 emit_draw_index(cmd_buffer, 0);
2947
2948 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2949 * different views. We need to multiply instanceCount by the view count.
2950 */
2951 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2952
2953 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2954 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
2955 prim.VertexAccessType = RANDOM;
2956 prim.PrimitiveTopologyType = pipeline->topology;
2957 prim.VertexCountPerInstance = indexCount;
2958 prim.StartVertexLocation = firstIndex;
2959 prim.InstanceCount = instanceCount;
2960 prim.StartInstanceLocation = firstInstance;
2961 prim.BaseVertexLocation = vertexOffset;
2962 }
2963 }
2964
2965 /* Auto-Draw / Indirect Registers */
2966 #define GEN7_3DPRIM_END_OFFSET 0x2420
2967 #define GEN7_3DPRIM_START_VERTEX 0x2430
2968 #define GEN7_3DPRIM_VERTEX_COUNT 0x2434
2969 #define GEN7_3DPRIM_INSTANCE_COUNT 0x2438
2970 #define GEN7_3DPRIM_START_INSTANCE 0x243C
2971 #define GEN7_3DPRIM_BASE_VERTEX 0x2440
2972
2973 void genX(CmdDrawIndirectByteCountEXT)(
2974 VkCommandBuffer commandBuffer,
2975 uint32_t instanceCount,
2976 uint32_t firstInstance,
2977 VkBuffer counterBuffer,
2978 VkDeviceSize counterBufferOffset,
2979 uint32_t counterOffset,
2980 uint32_t vertexStride)
2981 {
2982 #if GEN_IS_HASWELL || GEN_GEN >= 8
2983 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2984 ANV_FROM_HANDLE(anv_buffer, counter_buffer, counterBuffer);
2985 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2986 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2987
2988 /* firstVertex is always zero for this draw function */
2989 const uint32_t firstVertex = 0;
2990
2991 if (anv_batch_has_error(&cmd_buffer->batch))
2992 return;
2993
2994 genX(cmd_buffer_flush_state)(cmd_buffer);
2995
2996 if (vs_prog_data->uses_firstvertex ||
2997 vs_prog_data->uses_baseinstance)
2998 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
2999 if (vs_prog_data->uses_drawid)
3000 emit_draw_index(cmd_buffer, 0);
3001
3002 /* Our implementation of VK_KHR_multiview uses instancing to draw the
3003 * different views. We need to multiply instanceCount by the view count.
3004 */
3005 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
3006
3007 struct gen_mi_builder b;
3008 gen_mi_builder_init(&b, &cmd_buffer->batch);
3009 struct gen_mi_value count =
3010 gen_mi_mem32(anv_address_add(counter_buffer->address,
3011 counterBufferOffset));
3012 if (counterOffset)
3013 count = gen_mi_isub(&b, count, gen_mi_imm(counterOffset));
3014 count = gen_mi_udiv32_imm(&b, count, vertexStride);
3015 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT), count);
3016
3017 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3018 gen_mi_imm(firstVertex));
3019 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT),
3020 gen_mi_imm(instanceCount));
3021 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3022 gen_mi_imm(firstInstance));
3023 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3024
3025 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3026 prim.IndirectParameterEnable = true;
3027 prim.VertexAccessType = SEQUENTIAL;
3028 prim.PrimitiveTopologyType = pipeline->topology;
3029 }
3030 #endif /* GEN_IS_HASWELL || GEN_GEN >= 8 */
3031 }
3032
3033 static void
3034 load_indirect_parameters(struct anv_cmd_buffer *cmd_buffer,
3035 struct anv_address addr,
3036 bool indexed)
3037 {
3038 struct gen_mi_builder b;
3039 gen_mi_builder_init(&b, &cmd_buffer->batch);
3040
3041 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT),
3042 gen_mi_mem32(anv_address_add(addr, 0)));
3043
3044 struct gen_mi_value instance_count = gen_mi_mem32(anv_address_add(addr, 4));
3045 unsigned view_count = anv_subpass_view_count(cmd_buffer->state.subpass);
3046 if (view_count > 1) {
3047 #if GEN_IS_HASWELL || GEN_GEN >= 8
3048 instance_count = gen_mi_imul_imm(&b, instance_count, view_count);
3049 #else
3050 anv_finishme("Multiview + indirect draw requires MI_MATH; "
3051 "MI_MATH is not supported on Ivy Bridge");
3052 #endif
3053 }
3054 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT), instance_count);
3055
3056 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3057 gen_mi_mem32(anv_address_add(addr, 8)));
3058
3059 if (indexed) {
3060 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX),
3061 gen_mi_mem32(anv_address_add(addr, 12)));
3062 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3063 gen_mi_mem32(anv_address_add(addr, 16)));
3064 } else {
3065 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3066 gen_mi_mem32(anv_address_add(addr, 12)));
3067 gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3068 }
3069 }
3070
3071 void genX(CmdDrawIndirect)(
3072 VkCommandBuffer commandBuffer,
3073 VkBuffer _buffer,
3074 VkDeviceSize offset,
3075 uint32_t drawCount,
3076 uint32_t stride)
3077 {
3078 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3079 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3080 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3081 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3082
3083 if (anv_batch_has_error(&cmd_buffer->batch))
3084 return;
3085
3086 genX(cmd_buffer_flush_state)(cmd_buffer);
3087
3088 if (cmd_buffer->state.conditional_render_enabled)
3089 genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3090
3091 for (uint32_t i = 0; i < drawCount; i++) {
3092 struct anv_address draw = anv_address_add(buffer->address, offset);
3093
3094 if (vs_prog_data->uses_firstvertex ||
3095 vs_prog_data->uses_baseinstance)
3096 emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3097 if (vs_prog_data->uses_drawid)
3098 emit_draw_index(cmd_buffer, i);
3099
3100 load_indirect_parameters(cmd_buffer, draw, false);
3101
3102 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3103 prim.IndirectParameterEnable = true;
3104 prim.PredicateEnable = cmd_buffer->state.conditional_render_enabled;
3105 prim.VertexAccessType = SEQUENTIAL;
3106 prim.PrimitiveTopologyType = pipeline->topology;
3107 }
3108
3109 offset += stride;
3110 }
3111 }
3112
3113 void genX(CmdDrawIndexedIndirect)(
3114 VkCommandBuffer commandBuffer,
3115 VkBuffer _buffer,
3116 VkDeviceSize offset,
3117 uint32_t drawCount,
3118 uint32_t stride)
3119 {
3120 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3121 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3122 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3123 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3124
3125 if (anv_batch_has_error(&cmd_buffer->batch))
3126 return;
3127
3128 genX(cmd_buffer_flush_state)(cmd_buffer);