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