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