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