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