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