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