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