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