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