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