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