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