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