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