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