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