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