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