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