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