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