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