anv: Only copy clear dwords if we're rendering to the first slice
[mesa.git] / src / intel / vulkan / genX_cmd_buffer.c
1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <assert.h>
25 #include <stdbool.h>
26
27 #include "anv_private.h"
28 #include "vk_format_info.h"
29 #include "vk_util.h"
30
31 #include "common/gen_l3_config.h"
32 #include "genxml/gen_macros.h"
33 #include "genxml/genX_pack.h"
34
35 static void
36 emit_lrm(struct anv_batch *batch,
37 uint32_t reg, struct anv_bo *bo, uint32_t offset)
38 {
39 anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
40 lrm.RegisterAddress = reg;
41 lrm.MemoryAddress = (struct anv_address) { bo, offset };
42 }
43 }
44
45 static void
46 emit_lri(struct anv_batch *batch, uint32_t reg, uint32_t imm)
47 {
48 anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
49 lri.RegisterOffset = reg;
50 lri.DataDWord = imm;
51 }
52 }
53
54 #if GEN_IS_HASWELL || GEN_GEN >= 8
55 static void
56 emit_lrr(struct anv_batch *batch, uint32_t dst, uint32_t src)
57 {
58 anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_REG), lrr) {
59 lrr.SourceRegisterAddress = src;
60 lrr.DestinationRegisterAddress = dst;
61 }
62 }
63 #endif
64
65 void
66 genX(cmd_buffer_emit_state_base_address)(struct anv_cmd_buffer *cmd_buffer)
67 {
68 struct anv_device *device = cmd_buffer->device;
69
70 /* Emit a render target cache flush.
71 *
72 * This isn't documented anywhere in the PRM. However, it seems to be
73 * necessary prior to changing the surface state base adress. Without
74 * this, we get GPU hangs when using multi-level command buffers which
75 * clear depth, reset state base address, and then go render stuff.
76 */
77 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
78 pc.DCFlushEnable = true;
79 pc.RenderTargetCacheFlushEnable = true;
80 pc.CommandStreamerStallEnable = true;
81 }
82
83 anv_batch_emit(&cmd_buffer->batch, GENX(STATE_BASE_ADDRESS), sba) {
84 sba.GeneralStateBaseAddress = (struct anv_address) { NULL, 0 };
85 sba.GeneralStateMemoryObjectControlState = GENX(MOCS);
86 sba.GeneralStateBaseAddressModifyEnable = true;
87
88 sba.SurfaceStateBaseAddress =
89 anv_cmd_buffer_surface_base_address(cmd_buffer);
90 sba.SurfaceStateMemoryObjectControlState = GENX(MOCS);
91 sba.SurfaceStateBaseAddressModifyEnable = true;
92
93 sba.DynamicStateBaseAddress =
94 (struct anv_address) { &device->dynamic_state_pool.block_pool.bo, 0 };
95 sba.DynamicStateMemoryObjectControlState = GENX(MOCS);
96 sba.DynamicStateBaseAddressModifyEnable = true;
97
98 sba.IndirectObjectBaseAddress = (struct anv_address) { NULL, 0 };
99 sba.IndirectObjectMemoryObjectControlState = GENX(MOCS);
100 sba.IndirectObjectBaseAddressModifyEnable = true;
101
102 sba.InstructionBaseAddress =
103 (struct anv_address) { &device->instruction_state_pool.block_pool.bo, 0 };
104 sba.InstructionMemoryObjectControlState = GENX(MOCS);
105 sba.InstructionBaseAddressModifyEnable = true;
106
107 # if (GEN_GEN >= 8)
108 /* Broadwell requires that we specify a buffer size for a bunch of
109 * these fields. However, since we will be growing the BO's live, we
110 * just set them all to the maximum.
111 */
112 sba.GeneralStateBufferSize = 0xfffff;
113 sba.GeneralStateBufferSizeModifyEnable = true;
114 sba.DynamicStateBufferSize = 0xfffff;
115 sba.DynamicStateBufferSizeModifyEnable = true;
116 sba.IndirectObjectBufferSize = 0xfffff;
117 sba.IndirectObjectBufferSizeModifyEnable = true;
118 sba.InstructionBufferSize = 0xfffff;
119 sba.InstructionBuffersizeModifyEnable = true;
120 # endif
121 }
122
123 /* After re-setting the surface state base address, we have to do some
124 * cache flusing so that the sampler engine will pick up the new
125 * SURFACE_STATE objects and binding tables. From the Broadwell PRM,
126 * Shared Function > 3D Sampler > State > State Caching (page 96):
127 *
128 * Coherency with system memory in the state cache, like the texture
129 * cache is handled partially by software. It is expected that the
130 * command stream or shader will issue Cache Flush operation or
131 * Cache_Flush sampler message to ensure that the L1 cache remains
132 * coherent with system memory.
133 *
134 * [...]
135 *
136 * Whenever the value of the Dynamic_State_Base_Addr,
137 * Surface_State_Base_Addr are altered, the L1 state cache must be
138 * invalidated to ensure the new surface or sampler state is fetched
139 * from system memory.
140 *
141 * The PIPE_CONTROL command has a "State Cache Invalidation Enable" bit
142 * which, according the PIPE_CONTROL instruction documentation in the
143 * Broadwell PRM:
144 *
145 * Setting this bit is independent of any other bit in this packet.
146 * This bit controls the invalidation of the L1 and L2 state caches
147 * at the top of the pipe i.e. at the parsing time.
148 *
149 * Unfortunately, experimentation seems to indicate that state cache
150 * invalidation through a PIPE_CONTROL does nothing whatsoever in
151 * regards to surface state and binding tables. In stead, it seems that
152 * invalidating the texture cache is what is actually needed.
153 *
154 * XXX: As far as we have been able to determine through
155 * experimentation, shows that flush the texture cache appears to be
156 * sufficient. The theory here is that all of the sampling/rendering
157 * units cache the binding table in the texture cache. However, we have
158 * yet to be able to actually confirm this.
159 */
160 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
161 pc.TextureCacheInvalidationEnable = true;
162 pc.ConstantCacheInvalidationEnable = true;
163 pc.StateCacheInvalidationEnable = true;
164 }
165 }
166
167 static void
168 add_surface_state_reloc(struct anv_cmd_buffer *cmd_buffer,
169 struct anv_state state,
170 struct anv_bo *bo, uint32_t offset)
171 {
172 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
173
174 VkResult result =
175 anv_reloc_list_add(&cmd_buffer->surface_relocs, &cmd_buffer->pool->alloc,
176 state.offset + isl_dev->ss.addr_offset, bo, offset);
177 if (result != VK_SUCCESS)
178 anv_batch_set_error(&cmd_buffer->batch, result);
179 }
180
181 static void
182 add_image_view_relocs(struct anv_cmd_buffer *cmd_buffer,
183 const struct anv_image_view *image_view,
184 const uint32_t plane,
185 struct anv_surface_state state)
186 {
187 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
188 const struct anv_image *image = image_view->image;
189 uint32_t image_plane = image_view->planes[plane].image_plane;
190
191 add_surface_state_reloc(cmd_buffer, state.state,
192 image->planes[image_plane].bo, state.address);
193
194 if (state.aux_address) {
195 VkResult result =
196 anv_reloc_list_add(&cmd_buffer->surface_relocs,
197 &cmd_buffer->pool->alloc,
198 state.state.offset + isl_dev->ss.aux_addr_offset,
199 image->planes[image_plane].bo, state.aux_address);
200 if (result != VK_SUCCESS)
201 anv_batch_set_error(&cmd_buffer->batch, result);
202 }
203 }
204
205 static void
206 color_attachment_compute_aux_usage(struct anv_device * device,
207 struct anv_cmd_state * cmd_state,
208 uint32_t att, VkRect2D render_area,
209 union isl_color_value *fast_clear_color)
210 {
211 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
212 struct anv_image_view *iview = cmd_state->framebuffer->attachments[att];
213
214 assert(iview->n_planes == 1);
215
216 if (iview->planes[0].isl.base_array_layer >=
217 anv_image_aux_layers(iview->image, VK_IMAGE_ASPECT_COLOR_BIT,
218 iview->planes[0].isl.base_level)) {
219 /* There is no aux buffer which corresponds to the level and layer(s)
220 * being accessed.
221 */
222 att_state->aux_usage = ISL_AUX_USAGE_NONE;
223 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
224 att_state->fast_clear = false;
225 return;
226 }
227
228 att_state->aux_usage =
229 anv_layout_to_aux_usage(&device->info, iview->image,
230 VK_IMAGE_ASPECT_COLOR_BIT,
231 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
232
233 /* If we don't have aux, then we should have returned early in the layer
234 * check above. If we got here, we must have something.
235 */
236 assert(att_state->aux_usage != ISL_AUX_USAGE_NONE);
237
238 if (att_state->aux_usage == ISL_AUX_USAGE_MCS) {
239 att_state->input_aux_usage = ISL_AUX_USAGE_MCS;
240 att_state->fast_clear = false;
241 return;
242 }
243
244 if (att_state->aux_usage == ISL_AUX_USAGE_CCS_E) {
245 att_state->input_aux_usage = ISL_AUX_USAGE_CCS_E;
246 } else {
247 /* From the Sky Lake PRM, RENDER_SURFACE_STATE::AuxiliarySurfaceMode:
248 *
249 * "If Number of Multisamples is MULTISAMPLECOUNT_1, AUX_CCS_D
250 * setting is only allowed if Surface Format supported for Fast
251 * Clear. In addition, if the surface is bound to the sampling
252 * engine, Surface Format must be supported for Render Target
253 * Compression for surfaces bound to the sampling engine."
254 *
255 * In other words, we can only sample from a fast-cleared image if it
256 * also supports color compression.
257 */
258 if (isl_format_supports_ccs_e(&device->info, iview->planes[0].isl.format)) {
259 att_state->input_aux_usage = ISL_AUX_USAGE_CCS_D;
260
261 /* While fast-clear resolves and partial resolves are fairly cheap in the
262 * case where you render to most of the pixels, full resolves are not
263 * because they potentially involve reading and writing the entire
264 * framebuffer. If we can't texture with CCS_E, we should leave it off and
265 * limit ourselves to fast clears.
266 */
267 if (cmd_state->pass->attachments[att].first_subpass_layout ==
268 VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
269 anv_perf_warn(device->instance, iview->image,
270 "Not temporarily enabling CCS_E.");
271 }
272 } else {
273 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
274 }
275 }
276
277 assert(iview->image->planes[0].aux_surface.isl.usage & ISL_SURF_USAGE_CCS_BIT);
278
279 const struct isl_format_layout *view_fmtl =
280 isl_format_get_layout(iview->planes[0].isl.format);
281 union isl_color_value clear_color = {};
282
283 #define COPY_CLEAR_COLOR_CHANNEL(c, i) \
284 if (view_fmtl->channels.c.bits) \
285 clear_color.u32[i] = att_state->clear_value.color.uint32[i]
286
287 COPY_CLEAR_COLOR_CHANNEL(r, 0);
288 COPY_CLEAR_COLOR_CHANNEL(g, 1);
289 COPY_CLEAR_COLOR_CHANNEL(b, 2);
290 COPY_CLEAR_COLOR_CHANNEL(a, 3);
291
292 #undef COPY_CLEAR_COLOR_CHANNEL
293
294 att_state->clear_color_is_zero_one =
295 isl_color_value_is_zero_one(clear_color, iview->planes[0].isl.format);
296 att_state->clear_color_is_zero =
297 isl_color_value_is_zero(clear_color, iview->planes[0].isl.format);
298
299 if (att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
300 /* Start by getting the fast clear type. We use the first subpass
301 * layout here because we don't want to fast-clear if the first subpass
302 * to use the attachment can't handle fast-clears.
303 */
304 enum anv_fast_clear_type fast_clear_type =
305 anv_layout_to_fast_clear_type(&device->info, iview->image,
306 VK_IMAGE_ASPECT_COLOR_BIT,
307 cmd_state->pass->attachments[att].first_subpass_layout);
308 switch (fast_clear_type) {
309 case ANV_FAST_CLEAR_NONE:
310 att_state->fast_clear = false;
311 break;
312 case ANV_FAST_CLEAR_DEFAULT_VALUE:
313 att_state->fast_clear = att_state->clear_color_is_zero;
314 break;
315 case ANV_FAST_CLEAR_ANY:
316 att_state->fast_clear = true;
317 break;
318 }
319
320 /* Potentially, we could do partial fast-clears but doing so has crazy
321 * alignment restrictions. It's easier to just restrict to full size
322 * fast clears for now.
323 */
324 if (render_area.offset.x != 0 ||
325 render_area.offset.y != 0 ||
326 render_area.extent.width != iview->extent.width ||
327 render_area.extent.height != iview->extent.height)
328 att_state->fast_clear = false;
329
330 /* On Broadwell and earlier, we can only handle 0/1 clear colors */
331 if (GEN_GEN <= 8 && !att_state->clear_color_is_zero_one)
332 att_state->fast_clear = false;
333
334 /* We only allow fast clears to the first slice of an image (level 0,
335 * layer 0) and only for the entire slice. This guarantees us that, at
336 * any given time, there is only one clear color on any given image at
337 * any given time. At the time of our testing (Jan 17, 2018), there
338 * were no known applications which would benefit from fast-clearing
339 * more than just the first slice.
340 */
341 if (att_state->fast_clear &&
342 (iview->planes[0].isl.base_level > 0 ||
343 iview->planes[0].isl.base_array_layer > 0)) {
344 anv_perf_warn(device->instance, iview->image,
345 "Rendering with multi-lod or multi-layer framebuffer "
346 "with LOAD_OP_LOAD and baseMipLevel > 0 or "
347 "baseArrayLayer > 0. Not fast clearing.");
348 att_state->fast_clear = false;
349 } else if (att_state->fast_clear && cmd_state->framebuffer->layers > 1) {
350 anv_perf_warn(device->instance, iview->image,
351 "Rendering to a multi-layer framebuffer with "
352 "LOAD_OP_CLEAR. Only fast-clearing the first slice");
353 }
354
355 if (att_state->fast_clear)
356 *fast_clear_color = clear_color;
357 } else {
358 att_state->fast_clear = false;
359 }
360 }
361
362 static void
363 depth_stencil_attachment_compute_aux_usage(struct anv_device *device,
364 struct anv_cmd_state *cmd_state,
365 uint32_t att, VkRect2D render_area)
366 {
367 struct anv_render_pass_attachment *pass_att =
368 &cmd_state->pass->attachments[att];
369 struct anv_attachment_state *att_state = &cmd_state->attachments[att];
370 struct anv_image_view *iview = cmd_state->framebuffer->attachments[att];
371
372 /* These will be initialized after the first subpass transition. */
373 att_state->aux_usage = ISL_AUX_USAGE_NONE;
374 att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
375
376 if (GEN_GEN == 7) {
377 /* We don't do any HiZ or depth fast-clears on gen7 yet */
378 att_state->fast_clear = false;
379 return;
380 }
381
382 if (!(att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
383 /* If we're just clearing stencil, we can always HiZ clear */
384 att_state->fast_clear = true;
385 return;
386 }
387
388 /* Default to false for now */
389 att_state->fast_clear = false;
390
391 /* We must have depth in order to have HiZ */
392 if (!(iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
393 return;
394
395 const enum isl_aux_usage first_subpass_aux_usage =
396 anv_layout_to_aux_usage(&device->info, iview->image,
397 VK_IMAGE_ASPECT_DEPTH_BIT,
398 pass_att->first_subpass_layout);
399 if (first_subpass_aux_usage != ISL_AUX_USAGE_HIZ)
400 return;
401
402 if (!blorp_can_hiz_clear_depth(GEN_GEN,
403 iview->planes[0].isl.format,
404 iview->image->samples,
405 render_area.offset.x,
406 render_area.offset.y,
407 render_area.offset.x +
408 render_area.extent.width,
409 render_area.offset.y +
410 render_area.extent.height))
411 return;
412
413 if (att_state->clear_value.depthStencil.depth != ANV_HZ_FC_VAL)
414 return;
415
416 if (GEN_GEN == 8 && anv_can_sample_with_hiz(&device->info, iview->image)) {
417 /* Only gen9+ supports returning ANV_HZ_FC_VAL when sampling a
418 * fast-cleared portion of a HiZ buffer. Testing has revealed that Gen8
419 * only supports returning 0.0f. Gens prior to gen8 do not support this
420 * feature at all.
421 */
422 return;
423 }
424
425 /* If we got here, then we can fast clear */
426 att_state->fast_clear = true;
427 }
428
429 static bool
430 need_input_attachment_state(const struct anv_render_pass_attachment *att)
431 {
432 if (!(att->usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT))
433 return false;
434
435 /* We only allocate input attachment states for color surfaces. Compression
436 * is not yet enabled for depth textures and stencil doesn't allow
437 * compression so we can just use the texture surface state from the view.
438 */
439 return vk_format_is_color(att->format);
440 }
441
442 /* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
443 * the initial layout is undefined, the HiZ buffer and depth buffer will
444 * represent the same data at the end of this operation.
445 */
446 static void
447 transition_depth_buffer(struct anv_cmd_buffer *cmd_buffer,
448 const struct anv_image *image,
449 VkImageLayout initial_layout,
450 VkImageLayout final_layout)
451 {
452 const bool hiz_enabled = ISL_AUX_USAGE_HIZ ==
453 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
454 VK_IMAGE_ASPECT_DEPTH_BIT, initial_layout);
455 const bool enable_hiz = ISL_AUX_USAGE_HIZ ==
456 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
457 VK_IMAGE_ASPECT_DEPTH_BIT, final_layout);
458
459 enum isl_aux_op hiz_op;
460 if (hiz_enabled && !enable_hiz) {
461 hiz_op = ISL_AUX_OP_FULL_RESOLVE;
462 } else if (!hiz_enabled && enable_hiz) {
463 hiz_op = ISL_AUX_OP_AMBIGUATE;
464 } else {
465 assert(hiz_enabled == enable_hiz);
466 /* If the same buffer will be used, no resolves are necessary. */
467 hiz_op = ISL_AUX_OP_NONE;
468 }
469
470 if (hiz_op != ISL_AUX_OP_NONE)
471 anv_image_hiz_op(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
472 0, 0, 1, hiz_op);
473 }
474
475 #define MI_PREDICATE_SRC0 0x2400
476 #define MI_PREDICATE_SRC1 0x2408
477
478 static void
479 set_image_compressed_bit(struct anv_cmd_buffer *cmd_buffer,
480 const struct anv_image *image,
481 VkImageAspectFlagBits aspect,
482 uint32_t level,
483 uint32_t base_layer, uint32_t layer_count,
484 bool compressed)
485 {
486 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
487
488 /* We only have compression tracking for CCS_E */
489 if (image->planes[plane].aux_usage != ISL_AUX_USAGE_CCS_E)
490 return;
491
492 for (uint32_t a = 0; a < layer_count; a++) {
493 uint32_t layer = base_layer + a;
494 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
495 sdi.Address = anv_image_get_compression_state_addr(cmd_buffer->device,
496 image, aspect,
497 level, layer);
498 sdi.ImmediateData = compressed ? UINT32_MAX : 0;
499 }
500 }
501 }
502
503 static void
504 set_image_fast_clear_state(struct anv_cmd_buffer *cmd_buffer,
505 const struct anv_image *image,
506 VkImageAspectFlagBits aspect,
507 enum anv_fast_clear_type fast_clear)
508 {
509 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
510 sdi.Address = anv_image_get_fast_clear_type_addr(cmd_buffer->device,
511 image, aspect);
512 sdi.ImmediateData = fast_clear;
513 }
514
515 /* Whenever we have fast-clear, we consider that slice to be compressed.
516 * This makes building predicates much easier.
517 */
518 if (fast_clear != ANV_FAST_CLEAR_NONE)
519 set_image_compressed_bit(cmd_buffer, image, aspect, 0, 0, 1, true);
520 }
521
522 #if GEN_IS_HASWELL || GEN_GEN >= 8
523 static inline uint32_t
524 mi_alu(uint32_t opcode, uint32_t operand1, uint32_t operand2)
525 {
526 struct GENX(MI_MATH_ALU_INSTRUCTION) instr = {
527 .ALUOpcode = opcode,
528 .Operand1 = operand1,
529 .Operand2 = operand2,
530 };
531
532 uint32_t dw;
533 GENX(MI_MATH_ALU_INSTRUCTION_pack)(NULL, &dw, &instr);
534
535 return dw;
536 }
537 #endif
538
539 #define CS_GPR(n) (0x2600 + (n) * 8)
540
541 static void
542 anv_cmd_predicated_ccs_resolve(struct anv_cmd_buffer *cmd_buffer,
543 const struct anv_image *image,
544 VkImageAspectFlagBits aspect,
545 uint32_t level, uint32_t array_layer,
546 enum isl_aux_op resolve_op,
547 enum anv_fast_clear_type fast_clear_supported)
548 {
549 const uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
550 struct anv_address fast_clear_type_addr =
551 anv_image_get_fast_clear_type_addr(cmd_buffer->device, image, aspect);
552
553 #if GEN_GEN >= 9
554 /* Name some registers */
555 const int image_fc_reg = MI_ALU_REG0;
556 const int fc_imm_reg = MI_ALU_REG1;
557 const int pred_reg = MI_ALU_REG2;
558
559 uint32_t *dw;
560
561 if (resolve_op == ISL_AUX_OP_FULL_RESOLVE) {
562 /* In this case, we're doing a full resolve which means we want the
563 * resolve to happen if any compression (including fast-clears) is
564 * present.
565 *
566 * In order to simplify the logic a bit, we make the assumption that,
567 * if the first slice has been fast-cleared, it is also marked as
568 * compressed. See also set_image_fast_clear_state.
569 */
570 struct anv_address compression_state_addr =
571 anv_image_get_compression_state_addr(cmd_buffer->device, image,
572 aspect, level, array_layer);
573 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
574 lrm.RegisterAddress = MI_PREDICATE_SRC0;
575 lrm.MemoryAddress = compression_state_addr;
576 }
577 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
578 sdi.Address = compression_state_addr;
579 sdi.ImmediateData = 0;
580 }
581
582 if (level == 0 && array_layer == 0) {
583 /* If the predicate is true, we want to write 0 to the fast clear type
584 * and, if it's false, leave it alone. We can do this by writing
585 *
586 * clear_type = clear_type & ~predicate;
587 */
588 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
589 lrm.RegisterAddress = CS_GPR(image_fc_reg);
590 lrm.MemoryAddress = fast_clear_type_addr;
591 }
592 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_REG), lrr) {
593 lrr.DestinationRegisterAddress = CS_GPR(pred_reg);
594 lrr.SourceRegisterAddress = MI_PREDICATE_SRC0;
595 }
596
597 dw = anv_batch_emitn(&cmd_buffer->batch, 5, GENX(MI_MATH));
598 dw[1] = mi_alu(MI_ALU_LOAD, MI_ALU_SRCA, image_fc_reg);
599 dw[2] = mi_alu(MI_ALU_LOADINV, MI_ALU_SRCB, pred_reg);
600 dw[3] = mi_alu(MI_ALU_AND, 0, 0);
601 dw[4] = mi_alu(MI_ALU_STORE, image_fc_reg, MI_ALU_ACCU);
602
603 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_REGISTER_MEM), srm) {
604 srm.MemoryAddress = fast_clear_type_addr;
605 srm.RegisterAddress = CS_GPR(image_fc_reg);
606 }
607 }
608 } else if (level == 0 && array_layer == 0) {
609 /* In this case, we are doing a partial resolve to get rid of fast-clear
610 * colors. We don't care about the compression state but we do care
611 * about how much fast clear is allowed by the final layout.
612 */
613 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
614 assert(fast_clear_supported < ANV_FAST_CLEAR_ANY);
615
616 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
617 lrm.RegisterAddress = CS_GPR(image_fc_reg);
618 lrm.MemoryAddress = fast_clear_type_addr;
619 }
620 emit_lri(&cmd_buffer->batch, CS_GPR(image_fc_reg) + 4, 0);
621
622 emit_lri(&cmd_buffer->batch, CS_GPR(fc_imm_reg), fast_clear_supported);
623 emit_lri(&cmd_buffer->batch, CS_GPR(fc_imm_reg) + 4, 0);
624
625 /* We need to compute (fast_clear_supported < image->fast_clear).
626 * We do this by subtracting and storing the carry bit.
627 */
628 dw = anv_batch_emitn(&cmd_buffer->batch, 5, GENX(MI_MATH));
629 dw[1] = mi_alu(MI_ALU_LOAD, MI_ALU_SRCA, fc_imm_reg);
630 dw[2] = mi_alu(MI_ALU_LOAD, MI_ALU_SRCB, image_fc_reg);
631 dw[3] = mi_alu(MI_ALU_SUB, 0, 0);
632 dw[4] = mi_alu(MI_ALU_STORE, pred_reg, MI_ALU_CF);
633
634 /* Store the predicate */
635 emit_lrr(&cmd_buffer->batch, MI_PREDICATE_SRC0, CS_GPR(pred_reg));
636
637 /* If the predicate is true, we want to write 0 to the fast clear type
638 * and, if it's false, leave it alone. We can do this by writing
639 *
640 * clear_type = clear_type & ~predicate;
641 */
642 dw = anv_batch_emitn(&cmd_buffer->batch, 5, GENX(MI_MATH));
643 dw[1] = mi_alu(MI_ALU_LOAD, MI_ALU_SRCA, image_fc_reg);
644 dw[2] = mi_alu(MI_ALU_LOADINV, MI_ALU_SRCB, pred_reg);
645 dw[3] = mi_alu(MI_ALU_AND, 0, 0);
646 dw[4] = mi_alu(MI_ALU_STORE, image_fc_reg, MI_ALU_ACCU);
647
648 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_REGISTER_MEM), srm) {
649 srm.RegisterAddress = CS_GPR(image_fc_reg);
650 srm.MemoryAddress = fast_clear_type_addr;
651 }
652 } else {
653 /* In this case, we're trying to do a partial resolve on a slice that
654 * doesn't have clear color. There's nothing to do.
655 */
656 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
657 return;
658 }
659
660 #else /* GEN_GEN <= 8 */
661 assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
662 assert(fast_clear_supported != ANV_FAST_CLEAR_ANY);
663
664 /* We don't support fast clears on anything other than the first slice. */
665 if (level > 0 || array_layer > 0)
666 return;
667
668 /* On gen8, we don't have a concept of default clear colors because we
669 * can't sample from CCS surfaces. It's enough to just load the fast clear
670 * state into the predicate register.
671 */
672 anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
673 lrm.RegisterAddress = MI_PREDICATE_SRC0;
674 lrm.MemoryAddress = fast_clear_type_addr;
675 }
676 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
677 sdi.Address = fast_clear_type_addr;
678 sdi.ImmediateData = 0;
679 }
680 #endif
681
682 /* We use the first half of src0 for the actual predicate. Set the second
683 * half of src0 and all of src1 to 0 as the predicate operation will be
684 * doing an implicit src0 != src1.
685 */
686 emit_lri(&cmd_buffer->batch, MI_PREDICATE_SRC0 + 4, 0);
687 emit_lri(&cmd_buffer->batch, MI_PREDICATE_SRC1 , 0);
688 emit_lri(&cmd_buffer->batch, MI_PREDICATE_SRC1 + 4, 0);
689
690 anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
691 mip.LoadOperation = LOAD_LOADINV;
692 mip.CombineOperation = COMBINE_SET;
693 mip.CompareOperation = COMPARE_SRCS_EQUAL;
694 }
695
696 /* CCS_D only supports full resolves and BLORP will assert on us if we try
697 * to do a partial resolve on a CCS_D surface.
698 */
699 if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
700 image->planes[plane].aux_usage == ISL_AUX_USAGE_NONE)
701 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
702
703 anv_image_ccs_op(cmd_buffer, image, aspect, level,
704 array_layer, 1, resolve_op, true);
705 }
706
707 void
708 genX(cmd_buffer_mark_image_written)(struct anv_cmd_buffer *cmd_buffer,
709 const struct anv_image *image,
710 VkImageAspectFlagBits aspect,
711 enum isl_aux_usage aux_usage,
712 uint32_t level,
713 uint32_t base_layer,
714 uint32_t layer_count)
715 {
716 /* The aspect must be exactly one of the image aspects. */
717 assert(_mesa_bitcount(aspect) == 1 && (aspect & image->aspects));
718
719 /* The only compression types with more than just fast-clears are MCS,
720 * CCS_E, and HiZ. With HiZ we just trust the layout and don't actually
721 * track the current fast-clear and compression state. This leaves us
722 * with just MCS and CCS_E.
723 */
724 if (aux_usage != ISL_AUX_USAGE_CCS_E &&
725 aux_usage != ISL_AUX_USAGE_MCS)
726 return;
727
728 set_image_compressed_bit(cmd_buffer, image, aspect,
729 level, base_layer, layer_count, true);
730 }
731
732 static void
733 init_fast_clear_color(struct anv_cmd_buffer *cmd_buffer,
734 const struct anv_image *image,
735 VkImageAspectFlagBits aspect)
736 {
737 assert(cmd_buffer && image);
738 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
739
740 set_image_fast_clear_state(cmd_buffer, image, aspect,
741 ANV_FAST_CLEAR_NONE);
742
743 /* The fast clear value dword(s) will be copied into a surface state object.
744 * Ensure that the restrictions of the fields in the dword(s) are followed.
745 *
746 * CCS buffers on SKL+ can have any value set for the clear colors.
747 */
748 if (image->samples == 1 && GEN_GEN >= 9)
749 return;
750
751 /* Other combinations of auxiliary buffers and platforms require specific
752 * values in the clear value dword(s).
753 */
754 struct anv_address addr =
755 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
756 unsigned i = 0;
757 for (; i < cmd_buffer->device->isl_dev.ss.clear_value_size; i += 4) {
758 anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
759 sdi.Address = addr;
760
761 if (GEN_GEN >= 9) {
762 /* MCS buffers on SKL+ can only have 1/0 clear colors. */
763 assert(image->samples > 1);
764 sdi.ImmediateData = 0;
765 } else if (GEN_VERSIONx10 >= 75) {
766 /* Pre-SKL, the dword containing the clear values also contains
767 * other fields, so we need to initialize those fields to match the
768 * values that would be in a color attachment.
769 */
770 assert(i == 0);
771 sdi.ImmediateData = ISL_CHANNEL_SELECT_RED << 25 |
772 ISL_CHANNEL_SELECT_GREEN << 22 |
773 ISL_CHANNEL_SELECT_BLUE << 19 |
774 ISL_CHANNEL_SELECT_ALPHA << 16;
775 } else if (GEN_VERSIONx10 == 70) {
776 /* On IVB, the dword containing the clear values also contains
777 * other fields that must be zero or can be zero.
778 */
779 assert(i == 0);
780 sdi.ImmediateData = 0;
781 }
782 }
783
784 addr.offset += 4;
785 }
786 }
787
788 /* Copy the fast-clear value dword(s) between a surface state object and an
789 * image's fast clear state buffer.
790 */
791 static void
792 genX(copy_fast_clear_dwords)(struct anv_cmd_buffer *cmd_buffer,
793 struct anv_state surface_state,
794 const struct anv_image *image,
795 VkImageAspectFlagBits aspect,
796 bool copy_from_surface_state)
797 {
798 assert(cmd_buffer && image);
799 assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
800
801 struct anv_bo *ss_bo =
802 &cmd_buffer->device->surface_state_pool.block_pool.bo;
803 uint32_t ss_clear_offset = surface_state.offset +
804 cmd_buffer->device->isl_dev.ss.clear_value_offset;
805 const struct anv_address entry_addr =
806 anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
807 unsigned copy_size = cmd_buffer->device->isl_dev.ss.clear_value_size;
808
809 if (copy_from_surface_state) {
810 genX(cmd_buffer_mi_memcpy)(cmd_buffer, entry_addr.bo, entry_addr.offset,
811 ss_bo, ss_clear_offset, copy_size);
812 } else {
813 genX(cmd_buffer_mi_memcpy)(cmd_buffer, ss_bo, ss_clear_offset,
814 entry_addr.bo, entry_addr.offset, copy_size);
815
816 /* Updating a surface state object may require that the state cache be
817 * invalidated. From the SKL PRM, Shared Functions -> State -> State
818 * Caching:
819 *
820 * Whenever the RENDER_SURFACE_STATE object in memory pointed to by
821 * the Binding Table Pointer (BTP) and Binding Table Index (BTI) is
822 * modified [...], the L1 state cache must be invalidated to ensure
823 * the new surface or sampler state is fetched from system memory.
824 *
825 * In testing, SKL doesn't actually seem to need this, but HSW does.
826 */
827 cmd_buffer->state.pending_pipe_bits |=
828 ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
829 }
830 }
831
832 /**
833 * @brief Transitions a color buffer from one layout to another.
834 *
835 * See section 6.1.1. Image Layout Transitions of the Vulkan 1.0.50 spec for
836 * more information.
837 *
838 * @param level_count VK_REMAINING_MIP_LEVELS isn't supported.
839 * @param layer_count VK_REMAINING_ARRAY_LAYERS isn't supported. For 3D images,
840 * this represents the maximum layers to transition at each
841 * specified miplevel.
842 */
843 static void
844 transition_color_buffer(struct anv_cmd_buffer *cmd_buffer,
845 const struct anv_image *image,
846 VkImageAspectFlagBits aspect,
847 const uint32_t base_level, uint32_t level_count,
848 uint32_t base_layer, uint32_t layer_count,
849 VkImageLayout initial_layout,
850 VkImageLayout final_layout)
851 {
852 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
853 /* Validate the inputs. */
854 assert(cmd_buffer);
855 assert(image && image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
856 /* These values aren't supported for simplicity's sake. */
857 assert(level_count != VK_REMAINING_MIP_LEVELS &&
858 layer_count != VK_REMAINING_ARRAY_LAYERS);
859 /* Ensure the subresource range is valid. */
860 uint64_t last_level_num = base_level + level_count;
861 const uint32_t max_depth = anv_minify(image->extent.depth, base_level);
862 UNUSED const uint32_t image_layers = MAX2(image->array_size, max_depth);
863 assert((uint64_t)base_layer + layer_count <= image_layers);
864 assert(last_level_num <= image->levels);
865 /* The spec disallows these final layouts. */
866 assert(final_layout != VK_IMAGE_LAYOUT_UNDEFINED &&
867 final_layout != VK_IMAGE_LAYOUT_PREINITIALIZED);
868
869 /* No work is necessary if the layout stays the same or if this subresource
870 * range lacks auxiliary data.
871 */
872 if (initial_layout == final_layout)
873 return;
874
875 uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
876
877 if (image->planes[plane].shadow_surface.isl.size > 0 &&
878 final_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
879 /* This surface is a linear compressed image with a tiled shadow surface
880 * for texturing. The client is about to use it in READ_ONLY_OPTIMAL so
881 * we need to ensure the shadow copy is up-to-date.
882 */
883 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
884 assert(image->planes[plane].surface.isl.tiling == ISL_TILING_LINEAR);
885 assert(image->planes[plane].shadow_surface.isl.tiling != ISL_TILING_LINEAR);
886 assert(isl_format_is_compressed(image->planes[plane].surface.isl.format));
887 assert(plane == 0);
888 anv_image_copy_to_shadow(cmd_buffer, image,
889 base_level, level_count,
890 base_layer, layer_count);
891 }
892
893 if (base_layer >= anv_image_aux_layers(image, aspect, base_level))
894 return;
895
896 assert(image->tiling == VK_IMAGE_TILING_OPTIMAL);
897
898 if (initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ||
899 initial_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
900 /* A subresource in the undefined layout may have been aliased and
901 * populated with any arrangement of bits. Therefore, we must initialize
902 * the related aux buffer and clear buffer entry with desirable values.
903 * An initial layout of PREINITIALIZED is the same as UNDEFINED for
904 * images with VK_IMAGE_TILING_OPTIMAL.
905 *
906 * Initialize the relevant clear buffer entries.
907 */
908 if (base_level == 0 && base_layer == 0)
909 init_fast_clear_color(cmd_buffer, image, aspect);
910
911 /* Initialize the aux buffers to enable correct rendering. In order to
912 * ensure that things such as storage images work correctly, aux buffers
913 * need to be initialized to valid data.
914 *
915 * Having an aux buffer with invalid data is a problem for two reasons:
916 *
917 * 1) Having an invalid value in the buffer can confuse the hardware.
918 * For instance, with CCS_E on SKL, a two-bit CCS value of 2 is
919 * invalid and leads to the hardware doing strange things. It
920 * doesn't hang as far as we can tell but rendering corruption can
921 * occur.
922 *
923 * 2) If this transition is into the GENERAL layout and we then use the
924 * image as a storage image, then we must have the aux buffer in the
925 * pass-through state so that, if we then go to texture from the
926 * image, we get the results of our storage image writes and not the
927 * fast clear color or other random data.
928 *
929 * For CCS both of the problems above are real demonstrable issues. In
930 * that case, the only thing we can do is to perform an ambiguate to
931 * transition the aux surface into the pass-through state.
932 *
933 * For MCS, (2) is never an issue because we don't support multisampled
934 * storage images. In theory, issue (1) is a problem with MCS but we've
935 * never seen it in the wild. For 4x and 16x, all bit patters could, in
936 * theory, be interpreted as something but we don't know that all bit
937 * patterns are actually valid. For 2x and 8x, you could easily end up
938 * with the MCS referring to an invalid plane because not all bits of
939 * the MCS value are actually used. Even though we've never seen issues
940 * in the wild, it's best to play it safe and initialize the MCS. We
941 * can use a fast-clear for MCS because we only ever touch from render
942 * and texture (no image load store).
943 */
944 if (image->samples == 1) {
945 for (uint32_t l = 0; l < level_count; l++) {
946 const uint32_t level = base_level + l;
947
948 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
949 if (base_layer >= aux_layers)
950 break; /* We will only get fewer layers as level increases */
951 uint32_t level_layer_count =
952 MIN2(layer_count, aux_layers - base_layer);
953
954 anv_image_ccs_op(cmd_buffer, image, aspect, level,
955 base_layer, level_layer_count,
956 ISL_AUX_OP_AMBIGUATE, false);
957
958 if (image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_E) {
959 set_image_compressed_bit(cmd_buffer, image, aspect,
960 level, base_layer, level_layer_count,
961 false);
962 }
963 }
964 } else {
965 if (image->samples == 4 || image->samples == 16) {
966 anv_perf_warn(cmd_buffer->device->instance, image,
967 "Doing a potentially unnecessary fast-clear to "
968 "define an MCS buffer.");
969 }
970
971 assert(base_level == 0 && level_count == 1);
972 anv_image_mcs_op(cmd_buffer, image, aspect,
973 base_layer, layer_count,
974 ISL_AUX_OP_FAST_CLEAR, false);
975 }
976 return;
977 }
978
979 const enum isl_aux_usage initial_aux_usage =
980 anv_layout_to_aux_usage(devinfo, image, aspect, initial_layout);
981 const enum isl_aux_usage final_aux_usage =
982 anv_layout_to_aux_usage(devinfo, image, aspect, final_layout);
983
984 /* The current code assumes that there is no mixing of CCS_E and CCS_D.
985 * We can handle transitions between CCS_D/E to and from NONE. What we
986 * don't yet handle is switching between CCS_E and CCS_D within a given
987 * image. Doing so in a performant way requires more detailed aux state
988 * tracking such as what is done in i965. For now, just assume that we
989 * only have one type of compression.
990 */
991 assert(initial_aux_usage == ISL_AUX_USAGE_NONE ||
992 final_aux_usage == ISL_AUX_USAGE_NONE ||
993 initial_aux_usage == final_aux_usage);
994
995 /* If initial aux usage is NONE, there is nothing to resolve */
996 if (initial_aux_usage == ISL_AUX_USAGE_NONE)
997 return;
998
999 enum isl_aux_op resolve_op = ISL_AUX_OP_NONE;
1000
1001 /* If the initial layout supports more fast clear than the final layout
1002 * then we need at least a partial resolve.
1003 */
1004 const enum anv_fast_clear_type initial_fast_clear =
1005 anv_layout_to_fast_clear_type(devinfo, image, aspect, initial_layout);
1006 const enum anv_fast_clear_type final_fast_clear =
1007 anv_layout_to_fast_clear_type(devinfo, image, aspect, final_layout);
1008 if (final_fast_clear < initial_fast_clear)
1009 resolve_op = ISL_AUX_OP_PARTIAL_RESOLVE;
1010
1011 if (initial_aux_usage == ISL_AUX_USAGE_CCS_E &&
1012 final_aux_usage != ISL_AUX_USAGE_CCS_E)
1013 resolve_op = ISL_AUX_OP_FULL_RESOLVE;
1014
1015 if (resolve_op == ISL_AUX_OP_NONE)
1016 return;
1017
1018 /* Perform a resolve to synchronize data between the main and aux buffer.
1019 * Before we begin, we must satisfy the cache flushing requirement specified
1020 * in the Sky Lake PRM Vol. 7, "MCS Buffer for Render Target(s)":
1021 *
1022 * Any transition from any value in {Clear, Render, Resolve} to a
1023 * different value in {Clear, Render, Resolve} requires end of pipe
1024 * synchronization.
1025 *
1026 * We perform a flush of the write cache before and after the clear and
1027 * resolve operations to meet this requirement.
1028 *
1029 * Unlike other drawing, fast clear operations are not properly
1030 * synchronized. The first PIPE_CONTROL here likely ensures that the
1031 * contents of the previous render or clear hit the render target before we
1032 * resolve and the second likely ensures that the resolve is complete before
1033 * we do any more rendering or clearing.
1034 */
1035 cmd_buffer->state.pending_pipe_bits |=
1036 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1037
1038 for (uint32_t l = 0; l < level_count; l++) {
1039 uint32_t level = base_level + l;
1040
1041 uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1042 if (base_layer >= aux_layers)
1043 break; /* We will only get fewer layers as level increases */
1044 uint32_t level_layer_count =
1045 MIN2(layer_count, aux_layers - base_layer);
1046
1047 for (uint32_t a = 0; a < level_layer_count; a++) {
1048 uint32_t array_layer = base_layer + a;
1049 anv_cmd_predicated_ccs_resolve(cmd_buffer, image, aspect,
1050 level, array_layer, resolve_op,
1051 final_fast_clear);
1052 }
1053 }
1054
1055 cmd_buffer->state.pending_pipe_bits |=
1056 ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1057 }
1058
1059 /**
1060 * Setup anv_cmd_state::attachments for vkCmdBeginRenderPass.
1061 */
1062 static VkResult
1063 genX(cmd_buffer_setup_attachments)(struct anv_cmd_buffer *cmd_buffer,
1064 struct anv_render_pass *pass,
1065 const VkRenderPassBeginInfo *begin)
1066 {
1067 const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
1068 struct anv_cmd_state *state = &cmd_buffer->state;
1069
1070 vk_free(&cmd_buffer->pool->alloc, state->attachments);
1071
1072 if (pass->attachment_count > 0) {
1073 state->attachments = vk_alloc(&cmd_buffer->pool->alloc,
1074 pass->attachment_count *
1075 sizeof(state->attachments[0]),
1076 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1077 if (state->attachments == NULL) {
1078 /* Propagate VK_ERROR_OUT_OF_HOST_MEMORY to vkEndCommandBuffer */
1079 return anv_batch_set_error(&cmd_buffer->batch,
1080 VK_ERROR_OUT_OF_HOST_MEMORY);
1081 }
1082 } else {
1083 state->attachments = NULL;
1084 }
1085
1086 /* Reserve one for the NULL state. */
1087 unsigned num_states = 1;
1088 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1089 if (vk_format_is_color(pass->attachments[i].format))
1090 num_states++;
1091
1092 if (need_input_attachment_state(&pass->attachments[i]))
1093 num_states++;
1094 }
1095
1096 const uint32_t ss_stride = align_u32(isl_dev->ss.size, isl_dev->ss.align);
1097 state->render_pass_states =
1098 anv_state_stream_alloc(&cmd_buffer->surface_state_stream,
1099 num_states * ss_stride, isl_dev->ss.align);
1100
1101 struct anv_state next_state = state->render_pass_states;
1102 next_state.alloc_size = isl_dev->ss.size;
1103
1104 state->null_surface_state = next_state;
1105 next_state.offset += ss_stride;
1106 next_state.map += ss_stride;
1107
1108 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1109 if (vk_format_is_color(pass->attachments[i].format)) {
1110 state->attachments[i].color.state = next_state;
1111 next_state.offset += ss_stride;
1112 next_state.map += ss_stride;
1113 }
1114
1115 if (need_input_attachment_state(&pass->attachments[i])) {
1116 state->attachments[i].input.state = next_state;
1117 next_state.offset += ss_stride;
1118 next_state.map += ss_stride;
1119 }
1120 }
1121 assert(next_state.offset == state->render_pass_states.offset +
1122 state->render_pass_states.alloc_size);
1123
1124 if (begin) {
1125 ANV_FROM_HANDLE(anv_framebuffer, framebuffer, begin->framebuffer);
1126 assert(pass->attachment_count == framebuffer->attachment_count);
1127
1128 isl_null_fill_state(isl_dev, state->null_surface_state.map,
1129 isl_extent3d(framebuffer->width,
1130 framebuffer->height,
1131 framebuffer->layers));
1132
1133 for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1134 struct anv_render_pass_attachment *att = &pass->attachments[i];
1135 VkImageAspectFlags att_aspects = vk_format_aspects(att->format);
1136 VkImageAspectFlags clear_aspects = 0;
1137 VkImageAspectFlags load_aspects = 0;
1138
1139 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1140 /* color attachment */
1141 if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1142 clear_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1143 } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1144 load_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1145 }
1146 } else {
1147 /* depthstencil attachment */
1148 if (att_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
1149 if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1150 clear_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1151 } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1152 load_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1153 }
1154 }
1155 if (att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
1156 if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1157 clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1158 } else if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1159 load_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1160 }
1161 }
1162 }
1163
1164 state->attachments[i].current_layout = att->initial_layout;
1165 state->attachments[i].pending_clear_aspects = clear_aspects;
1166 state->attachments[i].pending_load_aspects = load_aspects;
1167 if (clear_aspects)
1168 state->attachments[i].clear_value = begin->pClearValues[i];
1169
1170 struct anv_image_view *iview = framebuffer->attachments[i];
1171 anv_assert(iview->vk_format == att->format);
1172 anv_assert(iview->n_planes == 1);
1173
1174 union isl_color_value clear_color = { .u32 = { 0, } };
1175 if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1176 assert(att_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1177 color_attachment_compute_aux_usage(cmd_buffer->device,
1178 state, i, begin->renderArea,
1179 &clear_color);
1180
1181 anv_image_fill_surface_state(cmd_buffer->device,
1182 iview->image,
1183 VK_IMAGE_ASPECT_COLOR_BIT,
1184 &iview->planes[0].isl,
1185 ISL_SURF_USAGE_RENDER_TARGET_BIT,
1186 state->attachments[i].aux_usage,
1187 &clear_color,
1188 0,
1189 &state->attachments[i].color,
1190 NULL);
1191
1192 add_image_view_relocs(cmd_buffer, iview, 0,
1193 state->attachments[i].color);
1194 } else {
1195 depth_stencil_attachment_compute_aux_usage(cmd_buffer->device,
1196 state, i,
1197 begin->renderArea);
1198 }
1199
1200 if (need_input_attachment_state(&pass->attachments[i])) {
1201 anv_image_fill_surface_state(cmd_buffer->device,
1202 iview->image,
1203 VK_IMAGE_ASPECT_COLOR_BIT,
1204 &iview->planes[0].isl,
1205 ISL_SURF_USAGE_TEXTURE_BIT,
1206 state->attachments[i].input_aux_usage,
1207 &clear_color,
1208 0,
1209 &state->attachments[i].input,
1210 NULL);
1211
1212 add_image_view_relocs(cmd_buffer, iview, 0,
1213 state->attachments[i].input);
1214 }
1215 }
1216 }
1217
1218 return VK_SUCCESS;
1219 }
1220
1221 VkResult
1222 genX(BeginCommandBuffer)(
1223 VkCommandBuffer commandBuffer,
1224 const VkCommandBufferBeginInfo* pBeginInfo)
1225 {
1226 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1227
1228 /* If this is the first vkBeginCommandBuffer, we must *initialize* the
1229 * command buffer's state. Otherwise, we must *reset* its state. In both
1230 * cases we reset it.
1231 *
1232 * From the Vulkan 1.0 spec:
1233 *
1234 * If a command buffer is in the executable state and the command buffer
1235 * was allocated from a command pool with the
1236 * VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, then
1237 * vkBeginCommandBuffer implicitly resets the command buffer, behaving
1238 * as if vkResetCommandBuffer had been called with
1239 * VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT not set. It then puts
1240 * the command buffer in the recording state.
1241 */
1242 anv_cmd_buffer_reset(cmd_buffer);
1243
1244 cmd_buffer->usage_flags = pBeginInfo->flags;
1245
1246 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY ||
1247 !(cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT));
1248
1249 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
1250
1251 /* We sometimes store vertex data in the dynamic state buffer for blorp
1252 * operations and our dynamic state stream may re-use data from previous
1253 * command buffers. In order to prevent stale cache data, we flush the VF
1254 * cache. We could do this on every blorp call but that's not really
1255 * needed as all of the data will get written by the CPU prior to the GPU
1256 * executing anything. The chances are fairly high that they will use
1257 * blorp at least once per primary command buffer so it shouldn't be
1258 * wasted.
1259 */
1260 if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY)
1261 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1262
1263 /* We send an "Indirect State Pointers Disable" packet at
1264 * EndCommandBuffer, so all push contant packets are ignored during a
1265 * context restore. Documentation says after that command, we need to
1266 * emit push constants again before any rendering operation. So we
1267 * flag them dirty here to make sure they get emitted.
1268 */
1269 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1270
1271 VkResult result = VK_SUCCESS;
1272 if (cmd_buffer->usage_flags &
1273 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1274 assert(pBeginInfo->pInheritanceInfo);
1275 cmd_buffer->state.pass =
1276 anv_render_pass_from_handle(pBeginInfo->pInheritanceInfo->renderPass);
1277 cmd_buffer->state.subpass =
1278 &cmd_buffer->state.pass->subpasses[pBeginInfo->pInheritanceInfo->subpass];
1279
1280 /* This is optional in the inheritance info. */
1281 cmd_buffer->state.framebuffer =
1282 anv_framebuffer_from_handle(pBeginInfo->pInheritanceInfo->framebuffer);
1283
1284 result = genX(cmd_buffer_setup_attachments)(cmd_buffer,
1285 cmd_buffer->state.pass, NULL);
1286
1287 /* Record that HiZ is enabled if we can. */
1288 if (cmd_buffer->state.framebuffer) {
1289 const struct anv_image_view * const iview =
1290 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
1291
1292 if (iview) {
1293 VkImageLayout layout =
1294 cmd_buffer->state.subpass->depth_stencil_attachment.layout;
1295
1296 enum isl_aux_usage aux_usage =
1297 anv_layout_to_aux_usage(&cmd_buffer->device->info, iview->image,
1298 VK_IMAGE_ASPECT_DEPTH_BIT, layout);
1299
1300 cmd_buffer->state.hiz_enabled = aux_usage == ISL_AUX_USAGE_HIZ;
1301 }
1302 }
1303
1304 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
1305 }
1306
1307 return result;
1308 }
1309
1310 /* From the PRM, Volume 2a:
1311 *
1312 * "Indirect State Pointers Disable
1313 *
1314 * At the completion of the post-sync operation associated with this pipe
1315 * control packet, the indirect state pointers in the hardware are
1316 * considered invalid; the indirect pointers are not saved in the context.
1317 * If any new indirect state commands are executed in the command stream
1318 * while the pipe control is pending, the new indirect state commands are
1319 * preserved.
1320 *
1321 * [DevIVB+]: Using Invalidate State Pointer (ISP) only inhibits context
1322 * restoring of Push Constant (3DSTATE_CONSTANT_*) commands. Push Constant
1323 * commands are only considered as Indirect State Pointers. Once ISP is
1324 * issued in a context, SW must initialize by programming push constant
1325 * commands for all the shaders (at least to zero length) before attempting
1326 * any rendering operation for the same context."
1327 *
1328 * 3DSTATE_CONSTANT_* packets are restored during a context restore,
1329 * even though they point to a BO that has been already unreferenced at
1330 * the end of the previous batch buffer. This has been fine so far since
1331 * we are protected by these scratch page (every address not covered by
1332 * a BO should be pointing to the scratch page). But on CNL, it is
1333 * causing a GPU hang during context restore at the 3DSTATE_CONSTANT_*
1334 * instruction.
1335 *
1336 * The flag "Indirect State Pointers Disable" in PIPE_CONTROL tells the
1337 * hardware to ignore previous 3DSTATE_CONSTANT_* packets during a
1338 * context restore, so the mentioned hang doesn't happen. However,
1339 * software must program push constant commands for all stages prior to
1340 * rendering anything. So we flag them dirty in BeginCommandBuffer.
1341 */
1342 static void
1343 emit_isp_disable(struct anv_cmd_buffer *cmd_buffer)
1344 {
1345 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1346 pc.IndirectStatePointersDisable = true;
1347 pc.CommandStreamerStallEnable = true;
1348 }
1349 }
1350
1351 VkResult
1352 genX(EndCommandBuffer)(
1353 VkCommandBuffer commandBuffer)
1354 {
1355 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1356
1357 if (anv_batch_has_error(&cmd_buffer->batch))
1358 return cmd_buffer->batch.status;
1359
1360 /* We want every command buffer to start with the PMA fix in a known state,
1361 * so we disable it at the end of the command buffer.
1362 */
1363 genX(cmd_buffer_enable_pma_fix)(cmd_buffer, false);
1364
1365 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
1366
1367 emit_isp_disable(cmd_buffer);
1368
1369 anv_cmd_buffer_end_batch_buffer(cmd_buffer);
1370
1371 return VK_SUCCESS;
1372 }
1373
1374 void
1375 genX(CmdExecuteCommands)(
1376 VkCommandBuffer commandBuffer,
1377 uint32_t commandBufferCount,
1378 const VkCommandBuffer* pCmdBuffers)
1379 {
1380 ANV_FROM_HANDLE(anv_cmd_buffer, primary, commandBuffer);
1381
1382 assert(primary->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1383
1384 if (anv_batch_has_error(&primary->batch))
1385 return;
1386
1387 /* The secondary command buffers will assume that the PMA fix is disabled
1388 * when they begin executing. Make sure this is true.
1389 */
1390 genX(cmd_buffer_enable_pma_fix)(primary, false);
1391
1392 /* The secondary command buffer doesn't know which textures etc. have been
1393 * flushed prior to their execution. Apply those flushes now.
1394 */
1395 genX(cmd_buffer_apply_pipe_flushes)(primary);
1396
1397 for (uint32_t i = 0; i < commandBufferCount; i++) {
1398 ANV_FROM_HANDLE(anv_cmd_buffer, secondary, pCmdBuffers[i]);
1399
1400 assert(secondary->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY);
1401 assert(!anv_batch_has_error(&secondary->batch));
1402
1403 if (secondary->usage_flags &
1404 VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1405 /* If we're continuing a render pass from the primary, we need to
1406 * copy the surface states for the current subpass into the storage
1407 * we allocated for them in BeginCommandBuffer.
1408 */
1409 struct anv_bo *ss_bo =
1410 &primary->device->surface_state_pool.block_pool.bo;
1411 struct anv_state src_state = primary->state.render_pass_states;
1412 struct anv_state dst_state = secondary->state.render_pass_states;
1413 assert(src_state.alloc_size == dst_state.alloc_size);
1414
1415 genX(cmd_buffer_so_memcpy)(primary, ss_bo, dst_state.offset,
1416 ss_bo, src_state.offset,
1417 src_state.alloc_size);
1418 }
1419
1420 anv_cmd_buffer_add_secondary(primary, secondary);
1421 }
1422
1423 /* The secondary may have selected a different pipeline (3D or compute) and
1424 * may have changed the current L3$ configuration. Reset our tracking
1425 * variables to invalid values to ensure that we re-emit these in the case
1426 * where we do any draws or compute dispatches from the primary after the
1427 * secondary has returned.
1428 */
1429 primary->state.current_pipeline = UINT32_MAX;
1430 primary->state.current_l3_config = NULL;
1431
1432 /* Each of the secondary command buffers will use its own state base
1433 * address. We need to re-emit state base address for the primary after
1434 * all of the secondaries are done.
1435 *
1436 * TODO: Maybe we want to make this a dirty bit to avoid extra state base
1437 * address calls?
1438 */
1439 genX(cmd_buffer_emit_state_base_address)(primary);
1440 }
1441
1442 #define IVB_L3SQCREG1_SQGHPCI_DEFAULT 0x00730000
1443 #define VLV_L3SQCREG1_SQGHPCI_DEFAULT 0x00d30000
1444 #define HSW_L3SQCREG1_SQGHPCI_DEFAULT 0x00610000
1445
1446 /**
1447 * Program the hardware to use the specified L3 configuration.
1448 */
1449 void
1450 genX(cmd_buffer_config_l3)(struct anv_cmd_buffer *cmd_buffer,
1451 const struct gen_l3_config *cfg)
1452 {
1453 assert(cfg);
1454 if (cfg == cmd_buffer->state.current_l3_config)
1455 return;
1456
1457 if (unlikely(INTEL_DEBUG & DEBUG_L3)) {
1458 intel_logd("L3 config transition: ");
1459 gen_dump_l3_config(cfg, stderr);
1460 }
1461
1462 const bool has_slm = cfg->n[GEN_L3P_SLM];
1463
1464 /* According to the hardware docs, the L3 partitioning can only be changed
1465 * while the pipeline is completely drained and the caches are flushed,
1466 * which involves a first PIPE_CONTROL flush which stalls the pipeline...
1467 */
1468 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1469 pc.DCFlushEnable = true;
1470 pc.PostSyncOperation = NoWrite;
1471 pc.CommandStreamerStallEnable = true;
1472 }
1473
1474 /* ...followed by a second pipelined PIPE_CONTROL that initiates
1475 * invalidation of the relevant caches. Note that because RO invalidation
1476 * happens at the top of the pipeline (i.e. right away as the PIPE_CONTROL
1477 * command is processed by the CS) we cannot combine it with the previous
1478 * stalling flush as the hardware documentation suggests, because that
1479 * would cause the CS to stall on previous rendering *after* RO
1480 * invalidation and wouldn't prevent the RO caches from being polluted by
1481 * concurrent rendering before the stall completes. This intentionally
1482 * doesn't implement the SKL+ hardware workaround suggesting to enable CS
1483 * stall on PIPE_CONTROLs with the texture cache invalidation bit set for
1484 * GPGPU workloads because the previous and subsequent PIPE_CONTROLs
1485 * already guarantee that there is no concurrent GPGPU kernel execution
1486 * (see SKL HSD 2132585).
1487 */
1488 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1489 pc.TextureCacheInvalidationEnable = true;
1490 pc.ConstantCacheInvalidationEnable = true;
1491 pc.InstructionCacheInvalidateEnable = true;
1492 pc.StateCacheInvalidationEnable = true;
1493 pc.PostSyncOperation = NoWrite;
1494 }
1495
1496 /* Now send a third stalling flush to make sure that invalidation is
1497 * complete when the L3 configuration registers are modified.
1498 */
1499 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1500 pc.DCFlushEnable = true;
1501 pc.PostSyncOperation = NoWrite;
1502 pc.CommandStreamerStallEnable = true;
1503 }
1504
1505 #if GEN_GEN >= 8
1506
1507 assert(!cfg->n[GEN_L3P_IS] && !cfg->n[GEN_L3P_C] && !cfg->n[GEN_L3P_T]);
1508
1509 uint32_t l3cr;
1510 anv_pack_struct(&l3cr, GENX(L3CNTLREG),
1511 .SLMEnable = has_slm,
1512 .URBAllocation = cfg->n[GEN_L3P_URB],
1513 .ROAllocation = cfg->n[GEN_L3P_RO],
1514 .DCAllocation = cfg->n[GEN_L3P_DC],
1515 .AllAllocation = cfg->n[GEN_L3P_ALL]);
1516
1517 /* Set up the L3 partitioning. */
1518 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG_num), l3cr);
1519
1520 #else
1521
1522 const bool has_dc = cfg->n[GEN_L3P_DC] || cfg->n[GEN_L3P_ALL];
1523 const bool has_is = cfg->n[GEN_L3P_IS] || cfg->n[GEN_L3P_RO] ||
1524 cfg->n[GEN_L3P_ALL];
1525 const bool has_c = cfg->n[GEN_L3P_C] || cfg->n[GEN_L3P_RO] ||
1526 cfg->n[GEN_L3P_ALL];
1527 const bool has_t = cfg->n[GEN_L3P_T] || cfg->n[GEN_L3P_RO] ||
1528 cfg->n[GEN_L3P_ALL];
1529
1530 assert(!cfg->n[GEN_L3P_ALL]);
1531
1532 /* When enabled SLM only uses a portion of the L3 on half of the banks,
1533 * the matching space on the remaining banks has to be allocated to a
1534 * client (URB for all validated configurations) set to the
1535 * lower-bandwidth 2-bank address hashing mode.
1536 */
1537 const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1538 const bool urb_low_bw = has_slm && !devinfo->is_baytrail;
1539 assert(!urb_low_bw || cfg->n[GEN_L3P_URB] == cfg->n[GEN_L3P_SLM]);
1540
1541 /* Minimum number of ways that can be allocated to the URB. */
1542 MAYBE_UNUSED const unsigned n0_urb = devinfo->is_baytrail ? 32 : 0;
1543 assert(cfg->n[GEN_L3P_URB] >= n0_urb);
1544
1545 uint32_t l3sqcr1, l3cr2, l3cr3;
1546 anv_pack_struct(&l3sqcr1, GENX(L3SQCREG1),
1547 .ConvertDC_UC = !has_dc,
1548 .ConvertIS_UC = !has_is,
1549 .ConvertC_UC = !has_c,
1550 .ConvertT_UC = !has_t);
1551 l3sqcr1 |=
1552 GEN_IS_HASWELL ? HSW_L3SQCREG1_SQGHPCI_DEFAULT :
1553 devinfo->is_baytrail ? VLV_L3SQCREG1_SQGHPCI_DEFAULT :
1554 IVB_L3SQCREG1_SQGHPCI_DEFAULT;
1555
1556 anv_pack_struct(&l3cr2, GENX(L3CNTLREG2),
1557 .SLMEnable = has_slm,
1558 .URBLowBandwidth = urb_low_bw,
1559 .URBAllocation = cfg->n[GEN_L3P_URB] - n0_urb,
1560 #if !GEN_IS_HASWELL
1561 .ALLAllocation = cfg->n[GEN_L3P_ALL],
1562 #endif
1563 .ROAllocation = cfg->n[GEN_L3P_RO],
1564 .DCAllocation = cfg->n[GEN_L3P_DC]);
1565
1566 anv_pack_struct(&l3cr3, GENX(L3CNTLREG3),
1567 .ISAllocation = cfg->n[GEN_L3P_IS],
1568 .ISLowBandwidth = 0,
1569 .CAllocation = cfg->n[GEN_L3P_C],
1570 .CLowBandwidth = 0,
1571 .TAllocation = cfg->n[GEN_L3P_T],
1572 .TLowBandwidth = 0);
1573
1574 /* Set up the L3 partitioning. */
1575 emit_lri(&cmd_buffer->batch, GENX(L3SQCREG1_num), l3sqcr1);
1576 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG2_num), l3cr2);
1577 emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG3_num), l3cr3);
1578
1579 #if GEN_IS_HASWELL
1580 if (cmd_buffer->device->instance->physicalDevice.cmd_parser_version >= 4) {
1581 /* Enable L3 atomics on HSW if we have a DC partition, otherwise keep
1582 * them disabled to avoid crashing the system hard.
1583 */
1584 uint32_t scratch1, chicken3;
1585 anv_pack_struct(&scratch1, GENX(SCRATCH1),
1586 .L3AtomicDisable = !has_dc);
1587 anv_pack_struct(&chicken3, GENX(CHICKEN3),
1588 .L3AtomicDisableMask = true,
1589 .L3AtomicDisable = !has_dc);
1590 emit_lri(&cmd_buffer->batch, GENX(SCRATCH1_num), scratch1);
1591 emit_lri(&cmd_buffer->batch, GENX(CHICKEN3_num), chicken3);
1592 }
1593 #endif
1594
1595 #endif
1596
1597 cmd_buffer->state.current_l3_config = cfg;
1598 }
1599
1600 void
1601 genX(cmd_buffer_apply_pipe_flushes)(struct anv_cmd_buffer *cmd_buffer)
1602 {
1603 enum anv_pipe_bits bits = cmd_buffer->state.pending_pipe_bits;
1604
1605 /* Flushes are pipelined while invalidations are handled immediately.
1606 * Therefore, if we're flushing anything then we need to schedule a stall
1607 * before any invalidations can happen.
1608 */
1609 if (bits & ANV_PIPE_FLUSH_BITS)
1610 bits |= ANV_PIPE_NEEDS_CS_STALL_BIT;
1611
1612 /* If we're going to do an invalidate and we have a pending CS stall that
1613 * has yet to be resolved, we do the CS stall now.
1614 */
1615 if ((bits & ANV_PIPE_INVALIDATE_BITS) &&
1616 (bits & ANV_PIPE_NEEDS_CS_STALL_BIT)) {
1617 bits |= ANV_PIPE_CS_STALL_BIT;
1618 bits &= ~ANV_PIPE_NEEDS_CS_STALL_BIT;
1619 }
1620
1621 if (bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT)) {
1622 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1623 pipe.DepthCacheFlushEnable = bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1624 pipe.DCFlushEnable = bits & ANV_PIPE_DATA_CACHE_FLUSH_BIT;
1625 pipe.RenderTargetCacheFlushEnable =
1626 bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1627
1628 pipe.DepthStallEnable = bits & ANV_PIPE_DEPTH_STALL_BIT;
1629 pipe.CommandStreamerStallEnable = bits & ANV_PIPE_CS_STALL_BIT;
1630 pipe.StallAtPixelScoreboard = bits & ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
1631
1632 /*
1633 * According to the Broadwell documentation, any PIPE_CONTROL with the
1634 * "Command Streamer Stall" bit set must also have another bit set,
1635 * with five different options:
1636 *
1637 * - Render Target Cache Flush
1638 * - Depth Cache Flush
1639 * - Stall at Pixel Scoreboard
1640 * - Post-Sync Operation
1641 * - Depth Stall
1642 * - DC Flush Enable
1643 *
1644 * I chose "Stall at Pixel Scoreboard" since that's what we use in
1645 * mesa and it seems to work fine. The choice is fairly arbitrary.
1646 */
1647 if ((bits & ANV_PIPE_CS_STALL_BIT) &&
1648 !(bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_DEPTH_STALL_BIT |
1649 ANV_PIPE_STALL_AT_SCOREBOARD_BIT)))
1650 pipe.StallAtPixelScoreboard = true;
1651 }
1652
1653 bits &= ~(ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT);
1654 }
1655
1656 if (bits & ANV_PIPE_INVALIDATE_BITS) {
1657 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1658 pipe.StateCacheInvalidationEnable =
1659 bits & ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
1660 pipe.ConstantCacheInvalidationEnable =
1661 bits & ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
1662 pipe.VFCacheInvalidationEnable =
1663 bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1664 pipe.TextureCacheInvalidationEnable =
1665 bits & ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1666 pipe.InstructionCacheInvalidateEnable =
1667 bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT;
1668 }
1669
1670 bits &= ~ANV_PIPE_INVALIDATE_BITS;
1671 }
1672
1673 cmd_buffer->state.pending_pipe_bits = bits;
1674 }
1675
1676 void genX(CmdPipelineBarrier)(
1677 VkCommandBuffer commandBuffer,
1678 VkPipelineStageFlags srcStageMask,
1679 VkPipelineStageFlags destStageMask,
1680 VkBool32 byRegion,
1681 uint32_t memoryBarrierCount,
1682 const VkMemoryBarrier* pMemoryBarriers,
1683 uint32_t bufferMemoryBarrierCount,
1684 const VkBufferMemoryBarrier* pBufferMemoryBarriers,
1685 uint32_t imageMemoryBarrierCount,
1686 const VkImageMemoryBarrier* pImageMemoryBarriers)
1687 {
1688 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1689
1690 /* XXX: Right now, we're really dumb and just flush whatever categories
1691 * the app asks for. One of these days we may make this a bit better
1692 * but right now that's all the hardware allows for in most areas.
1693 */
1694 VkAccessFlags src_flags = 0;
1695 VkAccessFlags dst_flags = 0;
1696
1697 for (uint32_t i = 0; i < memoryBarrierCount; i++) {
1698 src_flags |= pMemoryBarriers[i].srcAccessMask;
1699 dst_flags |= pMemoryBarriers[i].dstAccessMask;
1700 }
1701
1702 for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
1703 src_flags |= pBufferMemoryBarriers[i].srcAccessMask;
1704 dst_flags |= pBufferMemoryBarriers[i].dstAccessMask;
1705 }
1706
1707 for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1708 src_flags |= pImageMemoryBarriers[i].srcAccessMask;
1709 dst_flags |= pImageMemoryBarriers[i].dstAccessMask;
1710 ANV_FROM_HANDLE(anv_image, image, pImageMemoryBarriers[i].image);
1711 const VkImageSubresourceRange *range =
1712 &pImageMemoryBarriers[i].subresourceRange;
1713
1714 if (range->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1715 transition_depth_buffer(cmd_buffer, image,
1716 pImageMemoryBarriers[i].oldLayout,
1717 pImageMemoryBarriers[i].newLayout);
1718 } else if (range->aspectMask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1719 VkImageAspectFlags color_aspects =
1720 anv_image_expand_aspects(image, range->aspectMask);
1721 uint32_t aspect_bit;
1722
1723 uint32_t base_layer, layer_count;
1724 if (image->type == VK_IMAGE_TYPE_3D) {
1725 base_layer = 0;
1726 layer_count = anv_minify(image->extent.depth, range->baseMipLevel);
1727 } else {
1728 base_layer = range->baseArrayLayer;
1729 layer_count = anv_get_layerCount(image, range);
1730 }
1731
1732 anv_foreach_image_aspect_bit(aspect_bit, image, color_aspects) {
1733 transition_color_buffer(cmd_buffer, image, 1UL << aspect_bit,
1734 range->baseMipLevel,
1735 anv_get_levelCount(image, range),
1736 base_layer, layer_count,
1737 pImageMemoryBarriers[i].oldLayout,
1738 pImageMemoryBarriers[i].newLayout);
1739 }
1740 }
1741 }
1742
1743 cmd_buffer->state.pending_pipe_bits |=
1744 anv_pipe_flush_bits_for_access_flags(src_flags) |
1745 anv_pipe_invalidate_bits_for_access_flags(dst_flags);
1746 }
1747
1748 static void
1749 cmd_buffer_alloc_push_constants(struct anv_cmd_buffer *cmd_buffer)
1750 {
1751 VkShaderStageFlags stages =
1752 cmd_buffer->state.gfx.base.pipeline->active_stages;
1753
1754 /* In order to avoid thrash, we assume that vertex and fragment stages
1755 * always exist. In the rare case where one is missing *and* the other
1756 * uses push concstants, this may be suboptimal. However, avoiding stalls
1757 * seems more important.
1758 */
1759 stages |= VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT;
1760
1761 if (stages == cmd_buffer->state.push_constant_stages)
1762 return;
1763
1764 #if GEN_GEN >= 8
1765 const unsigned push_constant_kb = 32;
1766 #elif GEN_IS_HASWELL
1767 const unsigned push_constant_kb = cmd_buffer->device->info.gt == 3 ? 32 : 16;
1768 #else
1769 const unsigned push_constant_kb = 16;
1770 #endif
1771
1772 const unsigned num_stages =
1773 _mesa_bitcount(stages & VK_SHADER_STAGE_ALL_GRAPHICS);
1774 unsigned size_per_stage = push_constant_kb / num_stages;
1775
1776 /* Broadwell+ and Haswell gt3 require that the push constant sizes be in
1777 * units of 2KB. Incidentally, these are the same platforms that have
1778 * 32KB worth of push constant space.
1779 */
1780 if (push_constant_kb == 32)
1781 size_per_stage &= ~1u;
1782
1783 uint32_t kb_used = 0;
1784 for (int i = MESA_SHADER_VERTEX; i < MESA_SHADER_FRAGMENT; i++) {
1785 unsigned push_size = (stages & (1 << i)) ? size_per_stage : 0;
1786 anv_batch_emit(&cmd_buffer->batch,
1787 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
1788 alloc._3DCommandSubOpcode = 18 + i;
1789 alloc.ConstantBufferOffset = (push_size > 0) ? kb_used : 0;
1790 alloc.ConstantBufferSize = push_size;
1791 }
1792 kb_used += push_size;
1793 }
1794
1795 anv_batch_emit(&cmd_buffer->batch,
1796 GENX(3DSTATE_PUSH_CONSTANT_ALLOC_PS), alloc) {
1797 alloc.ConstantBufferOffset = kb_used;
1798 alloc.ConstantBufferSize = push_constant_kb - kb_used;
1799 }
1800
1801 cmd_buffer->state.push_constant_stages = stages;
1802
1803 /* From the BDW PRM for 3DSTATE_PUSH_CONSTANT_ALLOC_VS:
1804 *
1805 * "The 3DSTATE_CONSTANT_VS must be reprogrammed prior to
1806 * the next 3DPRIMITIVE command after programming the
1807 * 3DSTATE_PUSH_CONSTANT_ALLOC_VS"
1808 *
1809 * Since 3DSTATE_PUSH_CONSTANT_ALLOC_VS is programmed as part of
1810 * pipeline setup, we need to dirty push constants.
1811 */
1812 cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1813 }
1814
1815 static const struct anv_descriptor *
1816 anv_descriptor_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
1817 const struct anv_pipeline_binding *binding)
1818 {
1819 assert(binding->set < MAX_SETS);
1820 const struct anv_descriptor_set *set =
1821 pipe_state->descriptors[binding->set];
1822 const uint32_t offset =
1823 set->layout->binding[binding->binding].descriptor_index;
1824 return &set->descriptors[offset + binding->index];
1825 }
1826
1827 static uint32_t
1828 dynamic_offset_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
1829 const struct anv_pipeline_binding *binding)
1830 {
1831 assert(binding->set < MAX_SETS);
1832 const struct anv_descriptor_set *set =
1833 pipe_state->descriptors[binding->set];
1834
1835 uint32_t dynamic_offset_idx =
1836 pipe_state->layout->set[binding->set].dynamic_offset_start +
1837 set->layout->binding[binding->binding].dynamic_offset_index +
1838 binding->index;
1839
1840 return pipe_state->dynamic_offsets[dynamic_offset_idx];
1841 }
1842
1843 static VkResult
1844 emit_binding_table(struct anv_cmd_buffer *cmd_buffer,
1845 gl_shader_stage stage,
1846 struct anv_state *bt_state)
1847 {
1848 struct anv_subpass *subpass = cmd_buffer->state.subpass;
1849 struct anv_cmd_pipeline_state *pipe_state;
1850 struct anv_pipeline *pipeline;
1851 uint32_t bias, state_offset;
1852
1853 switch (stage) {
1854 case MESA_SHADER_COMPUTE:
1855 pipe_state = &cmd_buffer->state.compute.base;
1856 bias = 1;
1857 break;
1858 default:
1859 pipe_state = &cmd_buffer->state.gfx.base;
1860 bias = 0;
1861 break;
1862 }
1863 pipeline = pipe_state->pipeline;
1864
1865 if (!anv_pipeline_has_stage(pipeline, stage)) {
1866 *bt_state = (struct anv_state) { 0, };
1867 return VK_SUCCESS;
1868 }
1869
1870 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
1871 if (bias + map->surface_count == 0) {
1872 *bt_state = (struct anv_state) { 0, };
1873 return VK_SUCCESS;
1874 }
1875
1876 *bt_state = anv_cmd_buffer_alloc_binding_table(cmd_buffer,
1877 bias + map->surface_count,
1878 &state_offset);
1879 uint32_t *bt_map = bt_state->map;
1880
1881 if (bt_state->map == NULL)
1882 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1883
1884 if (stage == MESA_SHADER_COMPUTE &&
1885 get_cs_prog_data(pipeline)->uses_num_work_groups) {
1886 struct anv_bo *bo = cmd_buffer->state.compute.num_workgroups.bo;
1887 uint32_t bo_offset = cmd_buffer->state.compute.num_workgroups.offset;
1888
1889 struct anv_state surface_state;
1890 surface_state =
1891 anv_cmd_buffer_alloc_surface_state(cmd_buffer);
1892
1893 const enum isl_format format =
1894 anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
1895 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
1896 format, bo_offset, 12, 1);
1897
1898 bt_map[0] = surface_state.offset + state_offset;
1899 add_surface_state_reloc(cmd_buffer, surface_state, bo, bo_offset);
1900 }
1901
1902 if (map->surface_count == 0)
1903 goto out;
1904
1905 if (map->image_count > 0) {
1906 VkResult result =
1907 anv_cmd_buffer_ensure_push_constant_field(cmd_buffer, stage, images);
1908 if (result != VK_SUCCESS)
1909 return result;
1910
1911 cmd_buffer->state.push_constants_dirty |= 1 << stage;
1912 }
1913
1914 uint32_t image = 0;
1915 for (uint32_t s = 0; s < map->surface_count; s++) {
1916 struct anv_pipeline_binding *binding = &map->surface_to_descriptor[s];
1917
1918 struct anv_state surface_state;
1919
1920 if (binding->set == ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS) {
1921 /* Color attachment binding */
1922 assert(stage == MESA_SHADER_FRAGMENT);
1923 assert(binding->binding == 0);
1924 if (binding->index < subpass->color_count) {
1925 const unsigned att =
1926 subpass->color_attachments[binding->index].attachment;
1927
1928 /* From the Vulkan 1.0.46 spec:
1929 *
1930 * "If any color or depth/stencil attachments are
1931 * VK_ATTACHMENT_UNUSED, then no writes occur for those
1932 * attachments."
1933 */
1934 if (att == VK_ATTACHMENT_UNUSED) {
1935 surface_state = cmd_buffer->state.null_surface_state;
1936 } else {
1937 surface_state = cmd_buffer->state.attachments[att].color.state;
1938 }
1939 } else {
1940 surface_state = cmd_buffer->state.null_surface_state;
1941 }
1942
1943 bt_map[bias + s] = surface_state.offset + state_offset;
1944 continue;
1945 }
1946
1947 const struct anv_descriptor *desc =
1948 anv_descriptor_for_binding(pipe_state, binding);
1949
1950 switch (desc->type) {
1951 case VK_DESCRIPTOR_TYPE_SAMPLER:
1952 /* Nothing for us to do here */
1953 continue;
1954
1955 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
1956 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
1957 struct anv_surface_state sstate =
1958 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
1959 desc->image_view->planes[binding->plane].general_sampler_surface_state :
1960 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
1961 surface_state = sstate.state;
1962 assert(surface_state.alloc_size);
1963 add_image_view_relocs(cmd_buffer, desc->image_view,
1964 binding->plane, sstate);
1965 break;
1966 }
1967 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
1968 assert(stage == MESA_SHADER_FRAGMENT);
1969 if ((desc->image_view->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) == 0) {
1970 /* For depth and stencil input attachments, we treat it like any
1971 * old texture that a user may have bound.
1972 */
1973 struct anv_surface_state sstate =
1974 (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
1975 desc->image_view->planes[binding->plane].general_sampler_surface_state :
1976 desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
1977 surface_state = sstate.state;
1978 assert(surface_state.alloc_size);
1979 add_image_view_relocs(cmd_buffer, desc->image_view,
1980 binding->plane, sstate);
1981 } else {
1982 /* For color input attachments, we create the surface state at
1983 * vkBeginRenderPass time so that we can include aux and clear
1984 * color information.
1985 */
1986 assert(binding->input_attachment_index < subpass->input_count);
1987 const unsigned subpass_att = binding->input_attachment_index;
1988 const unsigned att = subpass->input_attachments[subpass_att].attachment;
1989 surface_state = cmd_buffer->state.attachments[att].input.state;
1990 }
1991 break;
1992
1993 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
1994 struct anv_surface_state sstate = (binding->write_only)
1995 ? desc->image_view->planes[binding->plane].writeonly_storage_surface_state
1996 : desc->image_view->planes[binding->plane].storage_surface_state;
1997 surface_state = sstate.state;
1998 assert(surface_state.alloc_size);
1999 add_image_view_relocs(cmd_buffer, desc->image_view,
2000 binding->plane, sstate);
2001
2002 struct brw_image_param *image_param =
2003 &cmd_buffer->state.push_constants[stage]->images[image++];
2004
2005 *image_param = desc->image_view->planes[binding->plane].storage_image_param;
2006 image_param->surface_idx = bias + s;
2007 break;
2008 }
2009
2010 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2011 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2012 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2013 surface_state = desc->buffer_view->surface_state;
2014 assert(surface_state.alloc_size);
2015 add_surface_state_reloc(cmd_buffer, surface_state,
2016 desc->buffer_view->bo,
2017 desc->buffer_view->offset);
2018 break;
2019
2020 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2021 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
2022 /* Compute the offset within the buffer */
2023 uint32_t dynamic_offset =
2024 dynamic_offset_for_binding(pipe_state, binding);
2025 uint64_t offset = desc->offset + dynamic_offset;
2026 /* Clamp to the buffer size */
2027 offset = MIN2(offset, desc->buffer->size);
2028 /* Clamp the range to the buffer size */
2029 uint32_t range = MIN2(desc->range, desc->buffer->size - offset);
2030
2031 surface_state =
2032 anv_state_stream_alloc(&cmd_buffer->surface_state_stream, 64, 64);
2033 enum isl_format format =
2034 anv_isl_format_for_descriptor_type(desc->type);
2035
2036 anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2037 format, offset, range, 1);
2038 add_surface_state_reloc(cmd_buffer, surface_state,
2039 desc->buffer->bo,
2040 desc->buffer->offset + offset);
2041 break;
2042 }
2043
2044 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2045 surface_state = (binding->write_only)
2046 ? desc->buffer_view->writeonly_storage_surface_state
2047 : desc->buffer_view->storage_surface_state;
2048 assert(surface_state.alloc_size);
2049 add_surface_state_reloc(cmd_buffer, surface_state,
2050 desc->buffer_view->bo,
2051 desc->buffer_view->offset);
2052
2053 struct brw_image_param *image_param =
2054 &cmd_buffer->state.push_constants[stage]->images[image++];
2055
2056 *image_param = desc->buffer_view->storage_image_param;
2057 image_param->surface_idx = bias + s;
2058 break;
2059
2060 default:
2061 assert(!"Invalid descriptor type");
2062 continue;
2063 }
2064
2065 bt_map[bias + s] = surface_state.offset + state_offset;
2066 }
2067 assert(image == map->image_count);
2068
2069 out:
2070 anv_state_flush(cmd_buffer->device, *bt_state);
2071
2072 #if GEN_GEN >= 11
2073 /* The PIPE_CONTROL command description says:
2074 *
2075 * "Whenever a Binding Table Index (BTI) used by a Render Taget Message
2076 * points to a different RENDER_SURFACE_STATE, SW must issue a Render
2077 * Target Cache Flush by enabling this bit. When render target flush
2078 * is set due to new association of BTI, PS Scoreboard Stall bit must
2079 * be set in this packet."
2080 *
2081 * FINISHME: Currently we shuffle around the surface states in the binding
2082 * table based on if they are getting used or not. So, we've to do below
2083 * pipe control flush for every binding table upload. Make changes so
2084 * that we do it only when we modify render target surface states.
2085 */
2086 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2087 pc.RenderTargetCacheFlushEnable = true;
2088 pc.StallAtPixelScoreboard = true;
2089 }
2090 #endif
2091
2092 return VK_SUCCESS;
2093 }
2094
2095 static VkResult
2096 emit_samplers(struct anv_cmd_buffer *cmd_buffer,
2097 gl_shader_stage stage,
2098 struct anv_state *state)
2099 {
2100 struct anv_cmd_pipeline_state *pipe_state =
2101 stage == MESA_SHADER_COMPUTE ? &cmd_buffer->state.compute.base :
2102 &cmd_buffer->state.gfx.base;
2103 struct anv_pipeline *pipeline = pipe_state->pipeline;
2104
2105 if (!anv_pipeline_has_stage(pipeline, stage)) {
2106 *state = (struct anv_state) { 0, };
2107 return VK_SUCCESS;
2108 }
2109
2110 struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2111 if (map->sampler_count == 0) {
2112 *state = (struct anv_state) { 0, };
2113 return VK_SUCCESS;
2114 }
2115
2116 uint32_t size = map->sampler_count * 16;
2117 *state = anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, size, 32);
2118
2119 if (state->map == NULL)
2120 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2121
2122 for (uint32_t s = 0; s < map->sampler_count; s++) {
2123 struct anv_pipeline_binding *binding = &map->sampler_to_descriptor[s];
2124 const struct anv_descriptor *desc =
2125 anv_descriptor_for_binding(pipe_state, binding);
2126
2127 if (desc->type != VK_DESCRIPTOR_TYPE_SAMPLER &&
2128 desc->type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
2129 continue;
2130
2131 struct anv_sampler *sampler = desc->sampler;
2132
2133 /* This can happen if we have an unfilled slot since TYPE_SAMPLER
2134 * happens to be zero.
2135 */
2136 if (sampler == NULL)
2137 continue;
2138
2139 memcpy(state->map + (s * 16),
2140 sampler->state[binding->plane], sizeof(sampler->state[0]));
2141 }
2142
2143 anv_state_flush(cmd_buffer->device, *state);
2144
2145 return VK_SUCCESS;
2146 }
2147
2148 static uint32_t
2149 flush_descriptor_sets(struct anv_cmd_buffer *cmd_buffer)
2150 {
2151 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2152
2153 VkShaderStageFlags dirty = cmd_buffer->state.descriptors_dirty &
2154 pipeline->active_stages;
2155
2156 VkResult result = VK_SUCCESS;
2157 anv_foreach_stage(s, dirty) {
2158 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2159 if (result != VK_SUCCESS)
2160 break;
2161 result = emit_binding_table(cmd_buffer, s,
2162 &cmd_buffer->state.binding_tables[s]);
2163 if (result != VK_SUCCESS)
2164 break;
2165 }
2166
2167 if (result != VK_SUCCESS) {
2168 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2169
2170 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2171 if (result != VK_SUCCESS)
2172 return 0;
2173
2174 /* Re-emit state base addresses so we get the new surface state base
2175 * address before we start emitting binding tables etc.
2176 */
2177 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2178
2179 /* Re-emit all active binding tables */
2180 dirty |= pipeline->active_stages;
2181 anv_foreach_stage(s, dirty) {
2182 result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2183 if (result != VK_SUCCESS) {
2184 anv_batch_set_error(&cmd_buffer->batch, result);
2185 return 0;
2186 }
2187 result = emit_binding_table(cmd_buffer, s,
2188 &cmd_buffer->state.binding_tables[s]);
2189 if (result != VK_SUCCESS) {
2190 anv_batch_set_error(&cmd_buffer->batch, result);
2191 return 0;
2192 }
2193 }
2194 }
2195
2196 cmd_buffer->state.descriptors_dirty &= ~dirty;
2197
2198 return dirty;
2199 }
2200
2201 static void
2202 cmd_buffer_emit_descriptor_pointers(struct anv_cmd_buffer *cmd_buffer,
2203 uint32_t stages)
2204 {
2205 static const uint32_t sampler_state_opcodes[] = {
2206 [MESA_SHADER_VERTEX] = 43,
2207 [MESA_SHADER_TESS_CTRL] = 44, /* HS */
2208 [MESA_SHADER_TESS_EVAL] = 45, /* DS */
2209 [MESA_SHADER_GEOMETRY] = 46,
2210 [MESA_SHADER_FRAGMENT] = 47,
2211 [MESA_SHADER_COMPUTE] = 0,
2212 };
2213
2214 static const uint32_t binding_table_opcodes[] = {
2215 [MESA_SHADER_VERTEX] = 38,
2216 [MESA_SHADER_TESS_CTRL] = 39,
2217 [MESA_SHADER_TESS_EVAL] = 40,
2218 [MESA_SHADER_GEOMETRY] = 41,
2219 [MESA_SHADER_FRAGMENT] = 42,
2220 [MESA_SHADER_COMPUTE] = 0,
2221 };
2222
2223 anv_foreach_stage(s, stages) {
2224 assert(s < ARRAY_SIZE(binding_table_opcodes));
2225 assert(binding_table_opcodes[s] > 0);
2226
2227 if (cmd_buffer->state.samplers[s].alloc_size > 0) {
2228 anv_batch_emit(&cmd_buffer->batch,
2229 GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ssp) {
2230 ssp._3DCommandSubOpcode = sampler_state_opcodes[s];
2231 ssp.PointertoVSSamplerState = cmd_buffer->state.samplers[s].offset;
2232 }
2233 }
2234
2235 /* Always emit binding table pointers if we're asked to, since on SKL
2236 * this is what flushes push constants. */
2237 anv_batch_emit(&cmd_buffer->batch,
2238 GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), btp) {
2239 btp._3DCommandSubOpcode = binding_table_opcodes[s];
2240 btp.PointertoVSBindingTable = cmd_buffer->state.binding_tables[s].offset;
2241 }
2242 }
2243 }
2244
2245 static void
2246 cmd_buffer_flush_push_constants(struct anv_cmd_buffer *cmd_buffer,
2247 VkShaderStageFlags dirty_stages)
2248 {
2249 const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2250 const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2251
2252 static const uint32_t push_constant_opcodes[] = {
2253 [MESA_SHADER_VERTEX] = 21,
2254 [MESA_SHADER_TESS_CTRL] = 25, /* HS */
2255 [MESA_SHADER_TESS_EVAL] = 26, /* DS */
2256 [MESA_SHADER_GEOMETRY] = 22,
2257 [MESA_SHADER_FRAGMENT] = 23,
2258 [MESA_SHADER_COMPUTE] = 0,
2259 };
2260
2261 VkShaderStageFlags flushed = 0;
2262
2263 anv_foreach_stage(stage, dirty_stages) {
2264 assert(stage < ARRAY_SIZE(push_constant_opcodes));
2265 assert(push_constant_opcodes[stage] > 0);
2266
2267 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_VS), c) {
2268 c._3DCommandSubOpcode = push_constant_opcodes[stage];
2269
2270 if (anv_pipeline_has_stage(pipeline, stage)) {
2271 #if GEN_GEN >= 8 || GEN_IS_HASWELL
2272 const struct brw_stage_prog_data *prog_data =
2273 pipeline->shaders[stage]->prog_data;
2274 const struct anv_pipeline_bind_map *bind_map =
2275 &pipeline->shaders[stage]->bind_map;
2276
2277 /* The Skylake PRM contains the following restriction:
2278 *
2279 * "The driver must ensure The following case does not occur
2280 * without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
2281 * buffer 3 read length equal to zero committed followed by a
2282 * 3DSTATE_CONSTANT_* with buffer 0 read length not equal to
2283 * zero committed."
2284 *
2285 * To avoid this, we program the buffers in the highest slots.
2286 * This way, slot 0 is only used if slot 3 is also used.
2287 */
2288 int n = 3;
2289
2290 for (int i = 3; i >= 0; i--) {
2291 const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2292 if (range->length == 0)
2293 continue;
2294
2295 const unsigned surface =
2296 prog_data->binding_table.ubo_start + range->block;
2297
2298 assert(surface <= bind_map->surface_count);
2299 const struct anv_pipeline_binding *binding =
2300 &bind_map->surface_to_descriptor[surface];
2301
2302 const struct anv_descriptor *desc =
2303 anv_descriptor_for_binding(&gfx_state->base, binding);
2304
2305 struct anv_address read_addr;
2306 uint32_t read_len;
2307 if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2308 read_len = MIN2(range->length,
2309 DIV_ROUND_UP(desc->buffer_view->range, 32) - range->start);
2310 read_addr = (struct anv_address) {
2311 .bo = desc->buffer_view->bo,
2312 .offset = desc->buffer_view->offset +
2313 range->start * 32,
2314 };
2315 } else {
2316 assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2317
2318 uint32_t dynamic_offset =
2319 dynamic_offset_for_binding(&gfx_state->base, binding);
2320 uint32_t buf_offset =
2321 MIN2(desc->offset + dynamic_offset, desc->buffer->size);
2322 uint32_t buf_range =
2323 MIN2(desc->range, desc->buffer->size - buf_offset);
2324
2325 read_len = MIN2(range->length,
2326 DIV_ROUND_UP(buf_range, 32) - range->start);
2327 read_addr = (struct anv_address) {
2328 .bo = desc->buffer->bo,
2329 .offset = desc->buffer->offset + buf_offset +
2330 range->start * 32,
2331 };
2332 }
2333
2334 if (read_len > 0) {
2335 c.ConstantBody.Buffer[n] = read_addr;
2336 c.ConstantBody.ReadLength[n] = read_len;
2337 n--;
2338 }
2339 }
2340
2341 struct anv_state state =
2342 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2343
2344 if (state.alloc_size > 0) {
2345 c.ConstantBody.Buffer[n] = (struct anv_address) {
2346 .bo = &cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2347 .offset = state.offset,
2348 };
2349 c.ConstantBody.ReadLength[n] =
2350 DIV_ROUND_UP(state.alloc_size, 32);
2351 }
2352 #else
2353 /* For Ivy Bridge, the push constants packets have a different
2354 * rule that would require us to iterate in the other direction
2355 * and possibly mess around with dynamic state base address.
2356 * Don't bother; just emit regular push constants at n = 0.
2357 */
2358 struct anv_state state =
2359 anv_cmd_buffer_push_constants(cmd_buffer, stage);
2360
2361 if (state.alloc_size > 0) {
2362 c.ConstantBody.Buffer[0].offset = state.offset,
2363 c.ConstantBody.ReadLength[0] =
2364 DIV_ROUND_UP(state.alloc_size, 32);
2365 }
2366 #endif
2367 }
2368 }
2369
2370 flushed |= mesa_to_vk_shader_stage(stage);
2371 }
2372
2373 cmd_buffer->state.push_constants_dirty &= ~flushed;
2374 }
2375
2376 void
2377 genX(cmd_buffer_flush_state)(struct anv_cmd_buffer *cmd_buffer)
2378 {
2379 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2380 uint32_t *p;
2381
2382 uint32_t vb_emit = cmd_buffer->state.gfx.vb_dirty & pipeline->vb_used;
2383
2384 assert((pipeline->active_stages & VK_SHADER_STAGE_COMPUTE_BIT) == 0);
2385
2386 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
2387
2388 genX(flush_pipeline_select_3d)(cmd_buffer);
2389
2390 if (vb_emit) {
2391 const uint32_t num_buffers = __builtin_popcount(vb_emit);
2392 const uint32_t num_dwords = 1 + num_buffers * 4;
2393
2394 p = anv_batch_emitn(&cmd_buffer->batch, num_dwords,
2395 GENX(3DSTATE_VERTEX_BUFFERS));
2396 uint32_t vb, i = 0;
2397 for_each_bit(vb, vb_emit) {
2398 struct anv_buffer *buffer = cmd_buffer->state.vertex_bindings[vb].buffer;
2399 uint32_t offset = cmd_buffer->state.vertex_bindings[vb].offset;
2400
2401 struct GENX(VERTEX_BUFFER_STATE) state = {
2402 .VertexBufferIndex = vb,
2403
2404 #if GEN_GEN >= 8
2405 .MemoryObjectControlState = GENX(MOCS),
2406 #else
2407 .BufferAccessType = pipeline->instancing_enable[vb] ? INSTANCEDATA : VERTEXDATA,
2408 /* Our implementation of VK_KHR_multiview uses instancing to draw
2409 * the different views. If the client asks for instancing, we
2410 * need to use the Instance Data Step Rate to ensure that we
2411 * repeat the client's per-instance data once for each view.
2412 */
2413 .InstanceDataStepRate = anv_subpass_view_count(pipeline->subpass),
2414 .VertexBufferMemoryObjectControlState = GENX(MOCS),
2415 #endif
2416
2417 .AddressModifyEnable = true,
2418 .BufferPitch = pipeline->binding_stride[vb],
2419 .BufferStartingAddress = { buffer->bo, buffer->offset + offset },
2420
2421 #if GEN_GEN >= 8
2422 .BufferSize = buffer->size - offset
2423 #else
2424 .EndAddress = { buffer->bo, buffer->offset + buffer->size - 1},
2425 #endif
2426 };
2427
2428 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, &p[1 + i * 4], &state);
2429 i++;
2430 }
2431 }
2432
2433 cmd_buffer->state.gfx.vb_dirty &= ~vb_emit;
2434
2435 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE) {
2436 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
2437
2438 /* The exact descriptor layout is pulled from the pipeline, so we need
2439 * to re-emit binding tables on every pipeline change.
2440 */
2441 cmd_buffer->state.descriptors_dirty |= pipeline->active_stages;
2442
2443 /* If the pipeline changed, we may need to re-allocate push constant
2444 * space in the URB.
2445 */
2446 cmd_buffer_alloc_push_constants(cmd_buffer);
2447 }
2448
2449 #if GEN_GEN <= 7
2450 if (cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_VERTEX_BIT ||
2451 cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_VERTEX_BIT) {
2452 /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
2453 *
2454 * "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth
2455 * stall needs to be sent just prior to any 3DSTATE_VS,
2456 * 3DSTATE_URB_VS, 3DSTATE_CONSTANT_VS,
2457 * 3DSTATE_BINDING_TABLE_POINTER_VS,
2458 * 3DSTATE_SAMPLER_STATE_POINTER_VS command. Only one
2459 * PIPE_CONTROL needs to be sent before any combination of VS
2460 * associated 3DSTATE."
2461 */
2462 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2463 pc.DepthStallEnable = true;
2464 pc.PostSyncOperation = WriteImmediateData;
2465 pc.Address =
2466 (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
2467 }
2468 }
2469 #endif
2470
2471 /* Render targets live in the same binding table as fragment descriptors */
2472 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_RENDER_TARGETS)
2473 cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_FRAGMENT_BIT;
2474
2475 /* We emit the binding tables and sampler tables first, then emit push
2476 * constants and then finally emit binding table and sampler table
2477 * pointers. It has to happen in this order, since emitting the binding
2478 * tables may change the push constants (in case of storage images). After
2479 * emitting push constants, on SKL+ we have to emit the corresponding
2480 * 3DSTATE_BINDING_TABLE_POINTER_* for the push constants to take effect.
2481 */
2482 uint32_t dirty = 0;
2483 if (cmd_buffer->state.descriptors_dirty)
2484 dirty = flush_descriptor_sets(cmd_buffer);
2485
2486 if (dirty || cmd_buffer->state.push_constants_dirty) {
2487 /* Because we're pushing UBOs, we have to push whenever either
2488 * descriptors or push constants is dirty.
2489 */
2490 dirty |= cmd_buffer->state.push_constants_dirty;
2491 dirty &= ANV_STAGE_MASK & VK_SHADER_STAGE_ALL_GRAPHICS;
2492 cmd_buffer_flush_push_constants(cmd_buffer, dirty);
2493 }
2494
2495 if (dirty)
2496 cmd_buffer_emit_descriptor_pointers(cmd_buffer, dirty);
2497
2498 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT)
2499 gen8_cmd_buffer_emit_viewport(cmd_buffer);
2500
2501 if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_VIEWPORT |
2502 ANV_CMD_DIRTY_PIPELINE)) {
2503 gen8_cmd_buffer_emit_depth_viewport(cmd_buffer,
2504 pipeline->depth_clamp_enable);
2505 }
2506
2507 if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_DYNAMIC_SCISSOR)
2508 gen7_cmd_buffer_emit_scissor(cmd_buffer);
2509
2510 genX(cmd_buffer_flush_dynamic_state)(cmd_buffer);
2511
2512 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
2513 }
2514
2515 static void
2516 emit_vertex_bo(struct anv_cmd_buffer *cmd_buffer,
2517 struct anv_bo *bo, uint32_t offset,
2518 uint32_t size, uint32_t index)
2519 {
2520 uint32_t *p = anv_batch_emitn(&cmd_buffer->batch, 5,
2521 GENX(3DSTATE_VERTEX_BUFFERS));
2522
2523 GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, p + 1,
2524 &(struct GENX(VERTEX_BUFFER_STATE)) {
2525 .VertexBufferIndex = index,
2526 .AddressModifyEnable = true,
2527 .BufferPitch = 0,
2528 #if (GEN_GEN >= 8)
2529 .MemoryObjectControlState = GENX(MOCS),
2530 .BufferStartingAddress = { bo, offset },
2531 .BufferSize = size
2532 #else
2533 .VertexBufferMemoryObjectControlState = GENX(MOCS),
2534 .BufferStartingAddress = { bo, offset },
2535 .EndAddress = { bo, offset + size },
2536 #endif
2537 });
2538 }
2539
2540 static void
2541 emit_base_vertex_instance_bo(struct anv_cmd_buffer *cmd_buffer,
2542 struct anv_bo *bo, uint32_t offset)
2543 {
2544 emit_vertex_bo(cmd_buffer, bo, offset, 8, ANV_SVGS_VB_INDEX);
2545 }
2546
2547 static void
2548 emit_base_vertex_instance(struct anv_cmd_buffer *cmd_buffer,
2549 uint32_t base_vertex, uint32_t base_instance)
2550 {
2551 struct anv_state id_state =
2552 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 8, 4);
2553
2554 ((uint32_t *)id_state.map)[0] = base_vertex;
2555 ((uint32_t *)id_state.map)[1] = base_instance;
2556
2557 anv_state_flush(cmd_buffer->device, id_state);
2558
2559 emit_base_vertex_instance_bo(cmd_buffer,
2560 &cmd_buffer->device->dynamic_state_pool.block_pool.bo, id_state.offset);
2561 }
2562
2563 static void
2564 emit_draw_index(struct anv_cmd_buffer *cmd_buffer, uint32_t draw_index)
2565 {
2566 struct anv_state state =
2567 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 4, 4);
2568
2569 ((uint32_t *)state.map)[0] = draw_index;
2570
2571 anv_state_flush(cmd_buffer->device, state);
2572
2573 emit_vertex_bo(cmd_buffer,
2574 &cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2575 state.offset, 4, ANV_DRAWID_VB_INDEX);
2576 }
2577
2578 void genX(CmdDraw)(
2579 VkCommandBuffer commandBuffer,
2580 uint32_t vertexCount,
2581 uint32_t instanceCount,
2582 uint32_t firstVertex,
2583 uint32_t firstInstance)
2584 {
2585 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2586 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2587 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2588
2589 if (anv_batch_has_error(&cmd_buffer->batch))
2590 return;
2591
2592 genX(cmd_buffer_flush_state)(cmd_buffer);
2593
2594 if (vs_prog_data->uses_basevertex || vs_prog_data->uses_baseinstance)
2595 emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
2596 if (vs_prog_data->uses_drawid)
2597 emit_draw_index(cmd_buffer, 0);
2598
2599 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2600 * different views. We need to multiply instanceCount by the view count.
2601 */
2602 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2603
2604 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2605 prim.VertexAccessType = SEQUENTIAL;
2606 prim.PrimitiveTopologyType = pipeline->topology;
2607 prim.VertexCountPerInstance = vertexCount;
2608 prim.StartVertexLocation = firstVertex;
2609 prim.InstanceCount = instanceCount;
2610 prim.StartInstanceLocation = firstInstance;
2611 prim.BaseVertexLocation = 0;
2612 }
2613 }
2614
2615 void genX(CmdDrawIndexed)(
2616 VkCommandBuffer commandBuffer,
2617 uint32_t indexCount,
2618 uint32_t instanceCount,
2619 uint32_t firstIndex,
2620 int32_t vertexOffset,
2621 uint32_t firstInstance)
2622 {
2623 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2624 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2625 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2626
2627 if (anv_batch_has_error(&cmd_buffer->batch))
2628 return;
2629
2630 genX(cmd_buffer_flush_state)(cmd_buffer);
2631
2632 if (vs_prog_data->uses_basevertex || vs_prog_data->uses_baseinstance)
2633 emit_base_vertex_instance(cmd_buffer, vertexOffset, firstInstance);
2634 if (vs_prog_data->uses_drawid)
2635 emit_draw_index(cmd_buffer, 0);
2636
2637 /* Our implementation of VK_KHR_multiview uses instancing to draw the
2638 * different views. We need to multiply instanceCount by the view count.
2639 */
2640 instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2641
2642 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2643 prim.VertexAccessType = RANDOM;
2644 prim.PrimitiveTopologyType = pipeline->topology;
2645 prim.VertexCountPerInstance = indexCount;
2646 prim.StartVertexLocation = firstIndex;
2647 prim.InstanceCount = instanceCount;
2648 prim.StartInstanceLocation = firstInstance;
2649 prim.BaseVertexLocation = vertexOffset;
2650 }
2651 }
2652
2653 /* Auto-Draw / Indirect Registers */
2654 #define GEN7_3DPRIM_END_OFFSET 0x2420
2655 #define GEN7_3DPRIM_START_VERTEX 0x2430
2656 #define GEN7_3DPRIM_VERTEX_COUNT 0x2434
2657 #define GEN7_3DPRIM_INSTANCE_COUNT 0x2438
2658 #define GEN7_3DPRIM_START_INSTANCE 0x243C
2659 #define GEN7_3DPRIM_BASE_VERTEX 0x2440
2660
2661 /* MI_MATH only exists on Haswell+ */
2662 #if GEN_IS_HASWELL || GEN_GEN >= 8
2663
2664 /* Emit dwords to multiply GPR0 by N */
2665 static void
2666 build_alu_multiply_gpr0(uint32_t *dw, unsigned *dw_count, uint32_t N)
2667 {
2668 VK_OUTARRAY_MAKE(out, dw, dw_count);
2669
2670 #define append_alu(opcode, operand1, operand2) \
2671 vk_outarray_append(&out, alu_dw) *alu_dw = mi_alu(opcode, operand1, operand2)
2672
2673 assert(N > 0);
2674 unsigned top_bit = 31 - __builtin_clz(N);
2675 for (int i = top_bit - 1; i >= 0; i--) {
2676 /* We get our initial data in GPR0 and we write the final data out to
2677 * GPR0 but we use GPR1 as our scratch register.
2678 */
2679 unsigned src_reg = i == top_bit - 1 ? MI_ALU_REG0 : MI_ALU_REG1;
2680 unsigned dst_reg = i == 0 ? MI_ALU_REG0 : MI_ALU_REG1;
2681
2682 /* Shift the current value left by 1 */
2683 append_alu(MI_ALU_LOAD, MI_ALU_SRCA, src_reg);
2684 append_alu(MI_ALU_LOAD, MI_ALU_SRCB, src_reg);
2685 append_alu(MI_ALU_ADD, 0, 0);
2686
2687 if (N & (1 << i)) {
2688 /* Store ACCU to R1 and add R0 to R1 */
2689 append_alu(MI_ALU_STORE, MI_ALU_REG1, MI_ALU_ACCU);
2690 append_alu(MI_ALU_LOAD, MI_ALU_SRCA, MI_ALU_REG0);
2691 append_alu(MI_ALU_LOAD, MI_ALU_SRCB, MI_ALU_REG1);
2692 append_alu(MI_ALU_ADD, 0, 0);
2693 }
2694
2695 append_alu(MI_ALU_STORE, dst_reg, MI_ALU_ACCU);
2696 }
2697
2698 #undef append_alu
2699 }
2700
2701 static void
2702 emit_mul_gpr0(struct anv_batch *batch, uint32_t N)
2703 {
2704 uint32_t num_dwords;
2705 build_alu_multiply_gpr0(NULL, &num_dwords, N);
2706
2707 uint32_t *dw = anv_batch_emitn(batch, 1 + num_dwords, GENX(MI_MATH));
2708 build_alu_multiply_gpr0(dw + 1, &num_dwords, N);
2709 }
2710
2711 #endif /* GEN_IS_HASWELL || GEN_GEN >= 8 */
2712
2713 static void
2714 load_indirect_parameters(struct anv_cmd_buffer *cmd_buffer,
2715 struct anv_buffer *buffer, uint64_t offset,
2716 bool indexed)
2717 {
2718 struct anv_batch *batch = &cmd_buffer->batch;
2719 struct anv_bo *bo = buffer->bo;
2720 uint32_t bo_offset = buffer->offset + offset;
2721
2722 emit_lrm(batch, GEN7_3DPRIM_VERTEX_COUNT, bo, bo_offset);
2723
2724 unsigned view_count = anv_subpass_view_count(cmd_buffer->state.subpass);
2725 if (view_count > 1) {
2726 #if GEN_IS_HASWELL || GEN_GEN >= 8
2727 emit_lrm(batch, CS_GPR(0), bo, bo_offset + 4);
2728 emit_mul_gpr0(batch, view_count);
2729 emit_lrr(batch, GEN7_3DPRIM_INSTANCE_COUNT, CS_GPR(0));
2730 #else
2731 anv_finishme("Multiview + indirect draw requires MI_MATH; "
2732 "MI_MATH is not supported on Ivy Bridge");
2733 emit_lrm(batch, GEN7_3DPRIM_INSTANCE_COUNT, bo, bo_offset + 4);
2734 #endif
2735 } else {
2736 emit_lrm(batch, GEN7_3DPRIM_INSTANCE_COUNT, bo, bo_offset + 4);
2737 }
2738
2739 emit_lrm(batch, GEN7_3DPRIM_START_VERTEX, bo, bo_offset + 8);
2740
2741 if (indexed) {
2742 emit_lrm(batch, GEN7_3DPRIM_BASE_VERTEX, bo, bo_offset + 12);
2743 emit_lrm(batch, GEN7_3DPRIM_START_INSTANCE, bo, bo_offset + 16);
2744 } else {
2745 emit_lrm(batch, GEN7_3DPRIM_START_INSTANCE, bo, bo_offset + 12);
2746 emit_lri(batch, GEN7_3DPRIM_BASE_VERTEX, 0);
2747 }
2748 }
2749
2750 void genX(CmdDrawIndirect)(
2751 VkCommandBuffer commandBuffer,
2752 VkBuffer _buffer,
2753 VkDeviceSize offset,
2754 uint32_t drawCount,
2755 uint32_t stride)
2756 {
2757 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2758 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2759 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2760 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2761
2762 if (anv_batch_has_error(&cmd_buffer->batch))
2763 return;
2764
2765 genX(cmd_buffer_flush_state)(cmd_buffer);
2766
2767 for (uint32_t i = 0; i < drawCount; i++) {
2768 struct anv_bo *bo = buffer->bo;
2769 uint32_t bo_offset = buffer->offset + offset;
2770
2771 if (vs_prog_data->uses_basevertex || vs_prog_data->uses_baseinstance)
2772 emit_base_vertex_instance_bo(cmd_buffer, bo, bo_offset + 8);
2773 if (vs_prog_data->uses_drawid)
2774 emit_draw_index(cmd_buffer, i);
2775
2776 load_indirect_parameters(cmd_buffer, buffer, offset, false);
2777
2778 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2779 prim.IndirectParameterEnable = true;
2780 prim.VertexAccessType = SEQUENTIAL;
2781 prim.PrimitiveTopologyType = pipeline->topology;
2782 }
2783
2784 offset += stride;
2785 }
2786 }
2787
2788 void genX(CmdDrawIndexedIndirect)(
2789 VkCommandBuffer commandBuffer,
2790 VkBuffer _buffer,
2791 VkDeviceSize offset,
2792 uint32_t drawCount,
2793 uint32_t stride)
2794 {
2795 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2796 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2797 struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2798 const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2799
2800 if (anv_batch_has_error(&cmd_buffer->batch))
2801 return;
2802
2803 genX(cmd_buffer_flush_state)(cmd_buffer);
2804
2805 for (uint32_t i = 0; i < drawCount; i++) {
2806 struct anv_bo *bo = buffer->bo;
2807 uint32_t bo_offset = buffer->offset + offset;
2808
2809 /* TODO: We need to stomp base vertex to 0 somehow */
2810 if (vs_prog_data->uses_basevertex || vs_prog_data->uses_baseinstance)
2811 emit_base_vertex_instance_bo(cmd_buffer, bo, bo_offset + 12);
2812 if (vs_prog_data->uses_drawid)
2813 emit_draw_index(cmd_buffer, i);
2814
2815 load_indirect_parameters(cmd_buffer, buffer, offset, true);
2816
2817 anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2818 prim.IndirectParameterEnable = true;
2819 prim.VertexAccessType = RANDOM;
2820 prim.PrimitiveTopologyType = pipeline->topology;
2821 }
2822
2823 offset += stride;
2824 }
2825 }
2826
2827 static VkResult
2828 flush_compute_descriptor_set(struct anv_cmd_buffer *cmd_buffer)
2829 {
2830 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
2831 struct anv_state surfaces = { 0, }, samplers = { 0, };
2832 VkResult result;
2833
2834 result = emit_binding_table(cmd_buffer, MESA_SHADER_COMPUTE, &surfaces);
2835 if (result != VK_SUCCESS) {
2836 assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2837
2838 result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2839 if (result != VK_SUCCESS)
2840 return result;
2841
2842 /* Re-emit state base addresses so we get the new surface state base
2843 * address before we start emitting binding tables etc.
2844 */
2845 genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2846
2847 result = emit_binding_table(cmd_buffer, MESA_SHADER_COMPUTE, &surfaces);
2848 if (result != VK_SUCCESS) {
2849 anv_batch_set_error(&cmd_buffer->batch, result);
2850 return result;
2851 }
2852 }
2853
2854 result = emit_samplers(cmd_buffer, MESA_SHADER_COMPUTE, &samplers);
2855 if (result != VK_SUCCESS) {
2856 anv_batch_set_error(&cmd_buffer->batch, result);
2857 return result;
2858 }
2859
2860 uint32_t iface_desc_data_dw[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
2861 struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
2862 .BindingTablePointer = surfaces.offset,
2863 .SamplerStatePointer = samplers.offset,
2864 };
2865 GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL, iface_desc_data_dw, &desc);
2866
2867 struct anv_state state =
2868 anv_cmd_buffer_merge_dynamic(cmd_buffer, iface_desc_data_dw,
2869 pipeline->interface_descriptor_data,
2870 GENX(INTERFACE_DESCRIPTOR_DATA_length),
2871 64);
2872
2873 uint32_t size = GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
2874 anv_batch_emit(&cmd_buffer->batch,
2875 GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), mid) {
2876 mid.InterfaceDescriptorTotalLength = size;
2877 mid.InterfaceDescriptorDataStartAddress = state.offset;
2878 }
2879
2880 return VK_SUCCESS;
2881 }
2882
2883 void
2884 genX(cmd_buffer_flush_compute_state)(struct anv_cmd_buffer *cmd_buffer)
2885 {
2886 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
2887 MAYBE_UNUSED VkResult result;
2888
2889 assert(pipeline->active_stages == VK_SHADER_STAGE_COMPUTE_BIT);
2890
2891 genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
2892
2893 genX(flush_pipeline_select_gpgpu)(cmd_buffer);
2894
2895 if (cmd_buffer->state.compute.pipeline_dirty) {
2896 /* From the Sky Lake PRM Vol 2a, MEDIA_VFE_STATE:
2897 *
2898 * "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
2899 * the only bits that are changed are scoreboard related: Scoreboard
2900 * Enable, Scoreboard Type, Scoreboard Mask, Scoreboard * Delta. For
2901 * these scoreboard related states, a MEDIA_STATE_FLUSH is
2902 * sufficient."
2903 */
2904 cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2905 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
2906
2907 anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
2908 }
2909
2910 if ((cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_COMPUTE_BIT) ||
2911 cmd_buffer->state.compute.pipeline_dirty) {
2912 /* FIXME: figure out descriptors for gen7 */
2913 result = flush_compute_descriptor_set(cmd_buffer);
2914 if (result != VK_SUCCESS)
2915 return;
2916
2917 cmd_buffer->state.descriptors_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
2918 }
2919
2920 if (cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_COMPUTE_BIT) {
2921 struct anv_state push_state =
2922 anv_cmd_buffer_cs_push_constants(cmd_buffer);
2923
2924 if (push_state.alloc_size) {
2925 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_CURBE_LOAD), curbe) {
2926 curbe.CURBETotalDataLength = push_state.alloc_size;
2927 curbe.CURBEDataStartAddress = push_state.offset;
2928 }
2929 }
2930 }
2931
2932 cmd_buffer->state.compute.pipeline_dirty = false;
2933
2934 genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
2935 }
2936
2937 #if GEN_GEN == 7
2938
2939 static VkResult
2940 verify_cmd_parser(const struct anv_device *device,
2941 int required_version,
2942 const char *function)
2943 {
2944 if (device->instance->physicalDevice.cmd_parser_version < required_version) {
2945 return vk_errorf(device->instance, device->instance,
2946 VK_ERROR_FEATURE_NOT_PRESENT,
2947 "cmd parser version %d is required for %s",
2948 required_version, function);
2949 } else {
2950 return VK_SUCCESS;
2951 }
2952 }
2953
2954 #endif
2955
2956 void genX(CmdDispatch)(
2957 VkCommandBuffer commandBuffer,
2958 uint32_t x,
2959 uint32_t y,
2960 uint32_t z)
2961 {
2962 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2963 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
2964 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
2965
2966 if (anv_batch_has_error(&cmd_buffer->batch))
2967 return;
2968
2969 if (prog_data->uses_num_work_groups) {
2970 struct anv_state state =
2971 anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 12, 4);
2972 uint32_t *sizes = state.map;
2973 sizes[0] = x;
2974 sizes[1] = y;
2975 sizes[2] = z;
2976 anv_state_flush(cmd_buffer->device, state);
2977 cmd_buffer->state.compute.num_workgroups = (struct anv_address) {
2978 .bo = &cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2979 .offset = state.offset,
2980 };
2981 }
2982
2983 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
2984
2985 anv_batch_emit(&cmd_buffer->batch, GENX(GPGPU_WALKER), ggw) {
2986 ggw.SIMDSize = prog_data->simd_size / 16;
2987 ggw.ThreadDepthCounterMaximum = 0;
2988 ggw.ThreadHeightCounterMaximum = 0;
2989 ggw.ThreadWidthCounterMaximum = prog_data->threads - 1;
2990 ggw.ThreadGroupIDXDimension = x;
2991 ggw.ThreadGroupIDYDimension = y;
2992 ggw.ThreadGroupIDZDimension = z;
2993 ggw.RightExecutionMask = pipeline->cs_right_mask;
2994 ggw.BottomExecutionMask = 0xffffffff;
2995 }
2996
2997 anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_STATE_FLUSH), msf);
2998 }
2999
3000 #define GPGPU_DISPATCHDIMX 0x2500
3001 #define GPGPU_DISPATCHDIMY 0x2504
3002 #define GPGPU_DISPATCHDIMZ 0x2508
3003
3004 void genX(CmdDispatchIndirect)(
3005 VkCommandBuffer commandBuffer,
3006 VkBuffer _buffer,
3007 VkDeviceSize offset)
3008 {
3009 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3010 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3011 struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3012 const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3013 struct anv_bo *bo = buffer->bo;
3014 uint32_t bo_offset = buffer->offset + offset;
3015 struct anv_batch *batch = &cmd_buffer->batch;
3016
3017 #if GEN_GEN == 7
3018 /* Linux 4.4 added command parser version 5 which allows the GPGPU
3019 * indirect dispatch registers to be written.
3020 */
3021 if (verify_cmd_parser(cmd_buffer->device, 5,
3022 "vkCmdDispatchIndirect") != VK_SUCCESS)
3023 return;
3024 #endif
3025
3026 if (prog_data->uses_num_work_groups) {
3027 cmd_buffer->state.compute.num_workgroups = (struct anv_address) {
3028 .bo = bo,
3029 .offset = bo_offset,
3030 };
3031 }
3032
3033 genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3034
3035 emit_lrm(batch, GPGPU_DISPATCHDIMX, bo, bo_offset);
3036 emit_lrm(batch, GPGPU_DISPATCHDIMY, bo, bo_offset + 4);
3037 emit_lrm(batch, GPGPU_DISPATCHDIMZ, bo, bo_offset + 8);
3038
3039 #if GEN_GEN <= 7
3040 /* Clear upper 32-bits of SRC0 and all 64-bits of SRC1 */
3041 emit_lri(batch, MI_PREDICATE_SRC0 + 4, 0);
3042 emit_lri(batch, MI_PREDICATE_SRC1 + 0, 0);
3043 emit_lri(batch, MI_PREDICATE_SRC1 + 4, 0);
3044
3045 /* Load compute_dispatch_indirect_x_size into SRC0 */
3046 emit_lrm(batch, MI_PREDICATE_SRC0, bo, bo_offset + 0);
3047
3048 /* predicate = (compute_dispatch_indirect_x_size == 0); */
3049 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3050 mip.LoadOperation = LOAD_LOAD;
3051 mip.CombineOperation = COMBINE_SET;
3052 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3053 }
3054
3055 /* Load compute_dispatch_indirect_y_size into SRC0 */
3056 emit_lrm(batch, MI_PREDICATE_SRC0, bo, bo_offset + 4);
3057
3058 /* predicate |= (compute_dispatch_indirect_y_size == 0); */
3059 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3060 mip.LoadOperation = LOAD_LOAD;
3061 mip.CombineOperation = COMBINE_OR;
3062 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3063 }
3064
3065 /* Load compute_dispatch_indirect_z_size into SRC0 */
3066 emit_lrm(batch, MI_PREDICATE_SRC0, bo, bo_offset + 8);
3067
3068 /* predicate |= (compute_dispatch_indirect_z_size == 0); */
3069 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3070 mip.LoadOperation = LOAD_LOAD;
3071 mip.CombineOperation = COMBINE_OR;
3072 mip.CompareOperation = COMPARE_SRCS_EQUAL;
3073 }
3074
3075 /* predicate = !predicate; */
3076 #define COMPARE_FALSE 1
3077 anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3078 mip.LoadOperation = LOAD_LOADINV;
3079 mip.CombineOperation = COMBINE_OR;
3080 mip.CompareOperation = COMPARE_FALSE;
3081 }
3082 #endif
3083
3084 anv_batch_emit(batch, GENX(GPGPU_WALKER), ggw) {
3085 ggw.IndirectParameterEnable = true;
3086 ggw.PredicateEnable = GEN_GEN <= 7;
3087 ggw.SIMDSize = prog_data->simd_size / 16;
3088 ggw.ThreadDepthCounterMaximum = 0;
3089 ggw.ThreadHeightCounterMaximum = 0;
3090 ggw.ThreadWidthCounterMaximum = prog_data->threads - 1;
3091 ggw.RightExecutionMask = pipeline->cs_right_mask;
3092 ggw.BottomExecutionMask = 0xffffffff;
3093 }
3094
3095 anv_batch_emit(batch, GENX(MEDIA_STATE_FLUSH), msf);
3096 }
3097
3098 static void
3099 genX(flush_pipeline_select)(struct anv_cmd_buffer *cmd_buffer,
3100 uint32_t pipeline)
3101 {
3102 UNUSED const struct gen_device_info *devinfo = &cmd_buffer->device->info;
3103
3104 if (cmd_buffer->state.current_pipeline == pipeline)
3105 return;
3106
3107 #if GEN_GEN >= 8 && GEN_GEN < 10
3108 /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
3109 *
3110 * Software must clear the COLOR_CALC_STATE Valid field in
3111 * 3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
3112 * with Pipeline Select set to GPGPU.
3113 *
3114 * The internal hardware docs recommend the same workaround for Gen9
3115 * hardware too.
3116 */
3117 if (pipeline == GPGPU)
3118 anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
3119 #endif
3120
3121 /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
3122 * PIPELINE_SELECT [DevBWR+]":
3123 *
3124 * Project: DEVSNB+
3125 *
3126 * Software must ensure all the write caches are flushed through a
3127 * stalling PIPE_CONTROL command followed by another PIPE_CONTROL
3128 * command to invalidate read only caches prior to programming
3129 * MI_PIPELINE_SELECT command to change the Pipeline Select Mode.
3130 */
3131 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
3132 pc.RenderTargetCacheFlushEnable = true;
3133 pc.DepthCacheFlushEnable = true;
3134 pc.DCFlushEnable = true;
3135 pc.PostSyncOperation = NoWrite;
3136 pc.CommandStreamerStallEnable = true;
3137 }
3138
3139 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
3140 pc.TextureCacheInvalidationEnable = true;
3141 pc.ConstantCacheInvalidationEnable = true;
3142 pc.StateCacheInvalidationEnable = true;
3143 pc.InstructionCacheInvalidateEnable = true;
3144 pc.PostSyncOperation = NoWrite;
3145 }
3146
3147 anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
3148 #if GEN_GEN >= 9
3149 ps.MaskBits = 3;
3150 #endif
3151 ps.PipelineSelection = pipeline;
3152 }
3153
3154 #if GEN_GEN == 9
3155 if (devinfo->is_geminilake) {
3156 /* Project: DevGLK
3157 *
3158 * "This chicken bit works around a hardware issue with barrier logic
3159 * encountered when switching between GPGPU and 3D pipelines. To
3160 * workaround the issue, this mode bit should be set after a pipeline
3161 * is selected."
3162 */
3163 uint32_t scec;
3164 anv_pack_struct(&scec, GENX(SLICE_COMMON_ECO_CHICKEN1),
3165 .GLKBarrierMode =
3166 pipeline == GPGPU ? GLK_BARRIER_MODE_GPGPU
3167 : GLK_BARRIER_MODE_3D_HULL,
3168 .GLKBarrierModeMask = 1);
3169 emit_lri(&cmd_buffer->batch, GENX(SLICE_COMMON_ECO_CHICKEN1_num), scec);
3170 }
3171 #endif
3172
3173 cmd_buffer->state.current_pipeline = pipeline;
3174 }
3175
3176 void
3177 genX(flush_pipeline_select_3d)(struct anv_cmd_buffer *cmd_buffer)
3178 {
3179 genX(flush_pipeline_select)(cmd_buffer, _3D);
3180 }
3181
3182 void
3183 genX(flush_pipeline_select_gpgpu)(struct anv_cmd_buffer *cmd_buffer)
3184 {
3185 genX(flush_pipeline_select)(cmd_buffer, GPGPU);
3186 }
3187
3188 void
3189 genX(cmd_buffer_emit_gen7_depth_flush)(struct anv_cmd_buffer *cmd_buffer)
3190 {
3191 if (GEN_GEN >= 8)
3192 return;
3193
3194 /* From the Haswell PRM, documentation for 3DSTATE_DEPTH_BUFFER:
3195 *
3196 * "Restriction: Prior to changing Depth/Stencil Buffer state (i.e., any
3197 * combination of 3DSTATE_DEPTH_BUFFER, 3DSTATE_CLEAR_PARAMS,
3198 * 3DSTATE_STENCIL_BUFFER, 3DSTATE_HIER_DEPTH_BUFFER) SW must first
3199 * issue a pipelined depth stall (PIPE_CONTROL with Depth Stall bit
3200 * set), followed by a pipelined depth cache flush (PIPE_CONTROL with
3201 * Depth Flush Bit set, followed by another pipelined depth stall
3202 * (PIPE_CONTROL with Depth Stall Bit set), unless SW can otherwise
3203 * guarantee that the pipeline from WM onwards is already flushed (e.g.,
3204 * via a preceding MI_FLUSH)."
3205 */
3206 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3207 pipe.DepthStallEnable = true;
3208 }
3209 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3210 pipe.DepthCacheFlushEnable = true;
3211 }
3212 anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3213 pipe.DepthStallEnable = true;
3214 }
3215 }
3216
3217 static void
3218 cmd_buffer_emit_depth_stencil(struct anv_cmd_buffer *cmd_buffer)
3219 {
3220 struct anv_device *device = cmd_buffer->device;
3221 const struct anv_image_view *iview =
3222 anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
3223 const struct anv_image *image = iview ? iview->image : NULL;
3224
3225 /* FIXME: Width and Height are wrong */
3226
3227 genX(cmd_buffer_emit_gen7_depth_flush)(cmd_buffer);
3228
3229 uint32_t *dw = anv_batch_emit_dwords(&cmd_buffer->batch,
3230 device->isl_dev.ds.size / 4);
3231 if (dw == NULL)
3232 return;
3233
3234 struct isl_depth_stencil_hiz_emit_info info = {
3235 .mocs = device->default_mocs,
3236 };
3237
3238 if (iview)
3239 info.view = &iview->planes[0].isl;
3240
3241 if (image && (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
3242 uint32_t depth_plane =
3243 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_DEPTH_BIT);
3244 const struct anv_surface *surface = &image->planes[depth_plane].surface;
3245
3246 info.depth_surf = &surface->isl;
3247
3248 info.depth_address =
3249 anv_batch_emit_reloc(&cmd_buffer->batch,
3250 dw + device->isl_dev.ds.depth_offset / 4,
3251 image->planes[depth_plane].bo,
3252 image->planes[depth_plane].bo_offset +
3253 surface->offset);
3254
3255 const uint32_t ds =
3256 cmd_buffer->state.subpass->depth_stencil_attachment.attachment;
3257 info.hiz_usage = cmd_buffer->state.attachments[ds].aux_usage;
3258 if (info.hiz_usage == ISL_AUX_USAGE_HIZ) {
3259 info.hiz_surf = &image->planes[depth_plane].aux_surface.isl;
3260
3261 info.hiz_address =
3262 anv_batch_emit_reloc(&cmd_buffer->batch,
3263 dw + device->isl_dev.ds.hiz_offset / 4,
3264 image->planes[depth_plane].bo,
3265 image->planes[depth_plane].bo_offset +
3266 image->planes[depth_plane].aux_surface.offset);
3267
3268 info.depth_clear_value = ANV_HZ_FC_VAL;
3269 }
3270 }
3271
3272 if (image && (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
3273 uint32_t stencil_plane =
3274 anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_STENCIL_BIT);
3275 const struct anv_surface *surface = &image->planes[stencil_plane].surface;
3276
3277 info.stencil_surf = &surface->isl;
3278
3279 info.stencil_address =
3280 anv_batch_emit_reloc(&cmd_buffer->batch,
3281 dw + device->isl_dev.ds.stencil_offset / 4,
3282 image->planes[stencil_plane].bo,
3283 image->planes[stencil_plane].bo_offset + surface->offset);
3284 }
3285
3286 isl_emit_depth_stencil_hiz_s(&device->isl_dev, dw, &info);
3287
3288 cmd_buffer->state.hiz_enabled = info.hiz_usage == ISL_AUX_USAGE_HIZ;
3289 }
3290
3291 static void
3292 cmd_buffer_begin_subpass(struct anv_cmd_buffer *cmd_buffer,
3293 uint32_t subpass_id)
3294 {
3295 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3296 struct anv_subpass *subpass = &cmd_state->pass->subpasses[subpass_id];
3297 cmd_state->subpass = subpass;
3298
3299 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
3300
3301 /* Our implementation of VK_KHR_multiview uses instancing to draw the
3302 * different views. If the client asks for instancing, we need to use the
3303 * Instance Data Step Rate to ensure that we repeat the client's
3304 * per-instance data once for each view. Since this bit is in
3305 * VERTEX_BUFFER_STATE on gen7, we need to dirty vertex buffers at the top
3306 * of each subpass.
3307 */
3308 if (GEN_GEN == 7)
3309 cmd_buffer->state.gfx.vb_dirty |= ~0;
3310
3311 /* It is possible to start a render pass with an old pipeline. Because the
3312 * render pass and subpass index are both baked into the pipeline, this is
3313 * highly unlikely. In order to do so, it requires that you have a render
3314 * pass with a single subpass and that you use that render pass twice
3315 * back-to-back and use the same pipeline at the start of the second render
3316 * pass as at the end of the first. In order to avoid unpredictable issues
3317 * with this edge case, we just dirty the pipeline at the start of every
3318 * subpass.
3319 */
3320 cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_PIPELINE;
3321
3322 /* Accumulate any subpass flushes that need to happen before the subpass */
3323 cmd_buffer->state.pending_pipe_bits |=
3324 cmd_buffer->state.pass->subpass_flushes[subpass_id];
3325
3326 VkRect2D render_area = cmd_buffer->state.render_area;
3327 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
3328
3329 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
3330 const uint32_t a = subpass->attachments[i].attachment;
3331 if (a == VK_ATTACHMENT_UNUSED)
3332 continue;
3333
3334 assert(a < cmd_state->pass->attachment_count);
3335 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
3336
3337 struct anv_image_view *iview = fb->attachments[a];
3338 const struct anv_image *image = iview->image;
3339
3340 /* A resolve is necessary before use as an input attachment if the clear
3341 * color or auxiliary buffer usage isn't supported by the sampler.
3342 */
3343 const bool input_needs_resolve =
3344 (att_state->fast_clear && !att_state->clear_color_is_zero_one) ||
3345 att_state->input_aux_usage != att_state->aux_usage;
3346
3347 VkImageLayout target_layout;
3348 if (iview->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV &&
3349 !input_needs_resolve) {
3350 /* Layout transitions before the final only help to enable sampling
3351 * as an input attachment. If the input attachment supports sampling
3352 * using the auxiliary surface, we can skip such transitions by
3353 * making the target layout one that is CCS-aware.
3354 */
3355 target_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
3356 } else {
3357 target_layout = subpass->attachments[i].layout;
3358 }
3359
3360 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
3361 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
3362
3363 uint32_t base_layer, layer_count;
3364 if (image->type == VK_IMAGE_TYPE_3D) {
3365 base_layer = 0;
3366 layer_count = anv_minify(iview->image->extent.depth,
3367 iview->planes[0].isl.base_level);
3368 } else {
3369 base_layer = iview->planes[0].isl.base_array_layer;
3370 layer_count = fb->layers;
3371 }
3372
3373 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
3374 iview->planes[0].isl.base_level, 1,
3375 base_layer, layer_count,
3376 att_state->current_layout, target_layout);
3377 } else if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
3378 transition_depth_buffer(cmd_buffer, image,
3379 att_state->current_layout, target_layout);
3380 att_state->aux_usage =
3381 anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
3382 VK_IMAGE_ASPECT_DEPTH_BIT, target_layout);
3383 }
3384 att_state->current_layout = target_layout;
3385
3386 if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
3387 assert(att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
3388
3389 /* Multi-planar images are not supported as attachments */
3390 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
3391 assert(image->n_planes == 1);
3392
3393 uint32_t base_clear_layer = iview->planes[0].isl.base_array_layer;
3394 uint32_t clear_layer_count = fb->layers;
3395
3396 if (att_state->fast_clear) {
3397 /* We only support fast-clears on the first layer */
3398 assert(iview->planes[0].isl.base_level == 0);
3399 assert(iview->planes[0].isl.base_array_layer == 0);
3400
3401 anv_image_ccs_op(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
3402 0, 0, 1, ISL_AUX_OP_FAST_CLEAR, false);
3403 base_clear_layer++;
3404 clear_layer_count--;
3405
3406 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->color.state,
3407 image, VK_IMAGE_ASPECT_COLOR_BIT,
3408 true /* copy from ss */);
3409
3410 if (att_state->clear_color_is_zero) {
3411 /* This image has the auxiliary buffer enabled. We can mark the
3412 * subresource as not needing a resolve because the clear color
3413 * will match what's in every RENDER_SURFACE_STATE object when
3414 * it's being used for sampling.
3415 */
3416 set_image_fast_clear_state(cmd_buffer, iview->image,
3417 VK_IMAGE_ASPECT_COLOR_BIT,
3418 ANV_FAST_CLEAR_DEFAULT_VALUE);
3419 } else {
3420 set_image_fast_clear_state(cmd_buffer, iview->image,
3421 VK_IMAGE_ASPECT_COLOR_BIT,
3422 ANV_FAST_CLEAR_ANY);
3423 }
3424 }
3425
3426 if (clear_layer_count > 0) {
3427 assert(image->n_planes == 1);
3428 anv_image_clear_color(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
3429 att_state->aux_usage,
3430 iview->planes[0].isl.format,
3431 iview->planes[0].isl.swizzle,
3432 iview->planes[0].isl.base_level,
3433 base_clear_layer, clear_layer_count,
3434 render_area,
3435 vk_to_isl_color(att_state->clear_value.color));
3436 }
3437 } else if (att_state->pending_clear_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT |
3438 VK_IMAGE_ASPECT_STENCIL_BIT)) {
3439 if (att_state->fast_clear) {
3440 /* We currently only support HiZ for single-layer images */
3441 assert(iview->planes[0].isl.base_level == 0);
3442 assert(iview->planes[0].isl.base_array_layer == 0);
3443 assert(fb->layers == 1);
3444
3445 anv_image_hiz_clear(cmd_buffer, image,
3446 att_state->pending_clear_aspects,
3447 iview->planes[0].isl.base_level,
3448 iview->planes[0].isl.base_array_layer,
3449 fb->layers, render_area,
3450 att_state->clear_value.depthStencil.stencil);
3451 } else {
3452 anv_image_clear_depth_stencil(cmd_buffer, image,
3453 att_state->pending_clear_aspects,
3454 att_state->aux_usage,
3455 iview->planes[0].isl.base_level,
3456 iview->planes[0].isl.base_array_layer,
3457 fb->layers, render_area,
3458 att_state->clear_value.depthStencil.depth,
3459 att_state->clear_value.depthStencil.stencil);
3460 }
3461 } else {
3462 assert(att_state->pending_clear_aspects == 0);
3463 }
3464
3465 if ((att_state->pending_load_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
3466 image->planes[0].aux_surface.isl.size > 0 &&
3467 iview->planes[0].isl.base_level == 0 &&
3468 iview->planes[0].isl.base_array_layer == 0) {
3469 if (att_state->aux_usage != ISL_AUX_USAGE_NONE) {
3470 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->color.state,
3471 image, VK_IMAGE_ASPECT_COLOR_BIT,
3472 false /* copy to ss */);
3473 }
3474
3475 if (need_input_attachment_state(&cmd_state->pass->attachments[a]) &&
3476 att_state->input_aux_usage != ISL_AUX_USAGE_NONE) {
3477 genX(copy_fast_clear_dwords)(cmd_buffer, att_state->input.state,
3478 image, VK_IMAGE_ASPECT_COLOR_BIT,
3479 false /* copy to ss */);
3480 }
3481 }
3482
3483 if (subpass->attachments[i].usage ==
3484 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
3485 /* We assume that if we're starting a subpass, we're going to do some
3486 * rendering so we may end up with compressed data.
3487 */
3488 genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
3489 VK_IMAGE_ASPECT_COLOR_BIT,
3490 att_state->aux_usage,
3491 iview->planes[0].isl.base_level,
3492 iview->planes[0].isl.base_array_layer,
3493 fb->layers);
3494 } else if (subpass->attachments[i].usage ==
3495 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
3496 /* We may be writing depth or stencil so we need to mark the surface.
3497 * Unfortunately, there's no way to know at this point whether the
3498 * depth or stencil tests used will actually write to the surface.
3499 *
3500 * Even though stencil may be plane 1, it always shares a base_level
3501 * with depth.
3502 */
3503 const struct isl_view *ds_view = &iview->planes[0].isl;
3504 if (iview->aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
3505 genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
3506 VK_IMAGE_ASPECT_DEPTH_BIT,
3507 att_state->aux_usage,
3508 ds_view->base_level,
3509 ds_view->base_array_layer,
3510 fb->layers);
3511 }
3512 if (iview->aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
3513 /* Even though stencil may be plane 1, it always shares a
3514 * base_level with depth.
3515 */
3516 genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
3517 VK_IMAGE_ASPECT_STENCIL_BIT,
3518 ISL_AUX_USAGE_NONE,
3519 ds_view->base_level,
3520 ds_view->base_array_layer,
3521 fb->layers);
3522 }
3523 }
3524
3525 att_state->pending_clear_aspects = 0;
3526 att_state->pending_load_aspects = 0;
3527 }
3528
3529 cmd_buffer_emit_depth_stencil(cmd_buffer);
3530 }
3531
3532 static void
3533 cmd_buffer_end_subpass(struct anv_cmd_buffer *cmd_buffer)
3534 {
3535 struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3536 struct anv_subpass *subpass = cmd_state->subpass;
3537 uint32_t subpass_id = anv_get_subpass_id(&cmd_buffer->state);
3538
3539 anv_cmd_buffer_resolve_subpass(cmd_buffer);
3540
3541 struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
3542 for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
3543 const uint32_t a = subpass->attachments[i].attachment;
3544 if (a == VK_ATTACHMENT_UNUSED)
3545 continue;
3546
3547 if (cmd_state->pass->attachments[a].last_subpass_idx != subpass_id)
3548 continue;
3549
3550 assert(a < cmd_state->pass->attachment_count);
3551 struct anv_attachment_state *att_state = &cmd_state->attachments[a];
3552 struct anv_image_view *iview = fb->attachments[a];
3553 const struct anv_image *image = iview->image;
3554
3555 /* Transition the image into the final layout for this render pass */
3556 VkImageLayout target_layout =
3557 cmd_state->pass->attachments[a].final_layout;
3558
3559 if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
3560 assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
3561
3562 uint32_t base_layer, layer_count;
3563 if (image->type == VK_IMAGE_TYPE_3D) {
3564 base_layer = 0;
3565 layer_count = anv_minify(iview->image->extent.depth,
3566 iview->planes[0].isl.base_level);
3567 } else {
3568 base_layer = iview->planes[0].isl.base_array_layer;
3569 layer_count = fb->layers;
3570 }
3571
3572 transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
3573 iview->planes[0].isl.base_level, 1,
3574 base_layer, layer_count,
3575 att_state->current_layout, target_layout);
3576 } else if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
3577 transition_depth_buffer(cmd_buffer, image,
3578 att_state->current_layout, target_layout);
3579 }
3580 }
3581
3582 /* Accumulate any subpass flushes that need to happen after the subpass.
3583 * Yes, they do get accumulated twice in the NextSubpass case but since
3584 * genX_CmdNextSubpass just calls end/begin back-to-back, we just end up
3585 * ORing the bits in twice so it's harmless.
3586 */
3587 cmd_buffer->state.pending_pipe_bits |=
3588 cmd_buffer->state.pass->subpass_flushes[subpass_id + 1];
3589 }
3590
3591 void genX(CmdBeginRenderPass)(
3592 VkCommandBuffer commandBuffer,
3593 const VkRenderPassBeginInfo* pRenderPassBegin,
3594 VkSubpassContents contents)
3595 {
3596 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3597 ANV_FROM_HANDLE(anv_render_pass, pass, pRenderPassBegin->renderPass);
3598 ANV_FROM_HANDLE(anv_framebuffer, framebuffer, pRenderPassBegin->framebuffer);
3599
3600 cmd_buffer->state.framebuffer = framebuffer;
3601 cmd_buffer->state.pass = pass;
3602 cmd_buffer->state.render_area = pRenderPassBegin->renderArea;
3603 VkResult result =
3604 genX(cmd_buffer_setup_attachments)(cmd_buffer, pass, pRenderPassBegin);
3605
3606 /* If we failed to setup the attachments we should not try to go further */
3607 if (result != VK_SUCCESS) {
3608 assert(anv_batch_has_error(&cmd_buffer->batch));
3609 return;
3610 }
3611
3612 genX(flush_pipeline_select_3d)(cmd_buffer);
3613
3614 cmd_buffer_begin_subpass(cmd_buffer, 0);
3615 }
3616
3617 void genX(CmdNextSubpass)(
3618 VkCommandBuffer commandBuffer,
3619 VkSubpassContents contents)
3620 {
3621 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3622
3623 if (anv_batch_has_error(&cmd_buffer->batch))
3624 return;
3625
3626 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
3627
3628 uint32_t prev_subpass = anv_get_subpass_id(&cmd_buffer->state);
3629 cmd_buffer_end_subpass(cmd_buffer);
3630 cmd_buffer_begin_subpass(cmd_buffer, prev_subpass + 1);
3631 }
3632
3633 void genX(CmdEndRenderPass)(
3634 VkCommandBuffer commandBuffer)
3635 {
3636 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3637
3638 if (anv_batch_has_error(&cmd_buffer->batch))
3639 return;
3640
3641 cmd_buffer_end_subpass(cmd_buffer);
3642
3643 cmd_buffer->state.hiz_enabled = false;
3644
3645 #ifndef NDEBUG
3646 anv_dump_add_framebuffer(cmd_buffer, cmd_buffer->state.framebuffer);
3647 #endif
3648
3649 /* Remove references to render pass specific state. This enables us to
3650 * detect whether or not we're in a renderpass.
3651 */
3652 cmd_buffer->state.framebuffer = NULL;
3653 cmd_buffer->state.pass = NULL;
3654 cmd_buffer->state.subpass = NULL;
3655 }