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