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