genX_cmd_buffer.c revision b8e80941
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#include "util/fast_idiv_by_const.h"
31
32#include "common/gen_l3_config.h"
33#include "genxml/gen_macros.h"
34#include "genxml/genX_pack.h"
35
36/* We reserve GPR 14 and 15 for conditional rendering */
37#define GEN_MI_BUILDER_NUM_ALLOC_GPRS 14
38#define __gen_get_batch_dwords anv_batch_emit_dwords
39#define __gen_address_offset anv_address_add
40#include "common/gen_mi_builder.h"
41
42static void
43emit_lri(struct anv_batch *batch, uint32_t reg, uint32_t imm)
44{
45   anv_batch_emit(batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
46      lri.RegisterOffset   = reg;
47      lri.DataDWord        = imm;
48   }
49}
50
51void
52genX(cmd_buffer_emit_state_base_address)(struct anv_cmd_buffer *cmd_buffer)
53{
54   struct anv_device *device = cmd_buffer->device;
55
56   /* If we are emitting a new state base address we probably need to re-emit
57    * binding tables.
58    */
59   cmd_buffer->state.descriptors_dirty |= ~0;
60
61   /* Emit a render target cache flush.
62    *
63    * This isn't documented anywhere in the PRM.  However, it seems to be
64    * necessary prior to changing the surface state base adress.  Without
65    * this, we get GPU hangs when using multi-level command buffers which
66    * clear depth, reset state base address, and then go render stuff.
67    */
68   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
69      pc.DCFlushEnable = true;
70      pc.RenderTargetCacheFlushEnable = true;
71      pc.CommandStreamerStallEnable = true;
72   }
73
74   anv_batch_emit(&cmd_buffer->batch, GENX(STATE_BASE_ADDRESS), sba) {
75      sba.GeneralStateBaseAddress = (struct anv_address) { NULL, 0 };
76      sba.GeneralStateMOCS = GENX(MOCS);
77      sba.GeneralStateBaseAddressModifyEnable = true;
78
79      sba.StatelessDataPortAccessMOCS = GENX(MOCS);
80
81      sba.SurfaceStateBaseAddress =
82         anv_cmd_buffer_surface_base_address(cmd_buffer);
83      sba.SurfaceStateMOCS = GENX(MOCS);
84      sba.SurfaceStateBaseAddressModifyEnable = true;
85
86      sba.DynamicStateBaseAddress =
87         (struct anv_address) { device->dynamic_state_pool.block_pool.bo, 0 };
88      sba.DynamicStateMOCS = GENX(MOCS);
89      sba.DynamicStateBaseAddressModifyEnable = true;
90
91      sba.IndirectObjectBaseAddress = (struct anv_address) { NULL, 0 };
92      sba.IndirectObjectMOCS = GENX(MOCS);
93      sba.IndirectObjectBaseAddressModifyEnable = true;
94
95      sba.InstructionBaseAddress =
96         (struct anv_address) { device->instruction_state_pool.block_pool.bo, 0 };
97      sba.InstructionMOCS = GENX(MOCS);
98      sba.InstructionBaseAddressModifyEnable = true;
99
100#  if (GEN_GEN >= 8)
101      /* Broadwell requires that we specify a buffer size for a bunch of
102       * these fields.  However, since we will be growing the BO's live, we
103       * just set them all to the maximum.
104       */
105      sba.GeneralStateBufferSize                = 0xfffff;
106      sba.GeneralStateBufferSizeModifyEnable    = true;
107      sba.DynamicStateBufferSize                = 0xfffff;
108      sba.DynamicStateBufferSizeModifyEnable    = true;
109      sba.IndirectObjectBufferSize              = 0xfffff;
110      sba.IndirectObjectBufferSizeModifyEnable  = true;
111      sba.InstructionBufferSize                 = 0xfffff;
112      sba.InstructionBuffersizeModifyEnable     = true;
113#  else
114      /* On gen7, we have upper bounds instead.  According to the docs,
115       * setting an upper bound of zero means that no bounds checking is
116       * performed so, in theory, we should be able to leave them zero.
117       * However, border color is broken and the GPU bounds-checks anyway.
118       * To avoid this and other potential problems, we may as well set it
119       * for everything.
120       */
121      sba.GeneralStateAccessUpperBound =
122         (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
123      sba.GeneralStateAccessUpperBoundModifyEnable = true;
124      sba.DynamicStateAccessUpperBound =
125         (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
126      sba.DynamicStateAccessUpperBoundModifyEnable = true;
127      sba.InstructionAccessUpperBound =
128         (struct anv_address) { .bo = NULL, .offset = 0xfffff000 };
129      sba.InstructionAccessUpperBoundModifyEnable = true;
130#  endif
131#  if (GEN_GEN >= 9)
132      if (cmd_buffer->device->instance->physicalDevice.use_softpin) {
133         sba.BindlessSurfaceStateBaseAddress = (struct anv_address) {
134            .bo = device->surface_state_pool.block_pool.bo,
135            .offset = 0,
136         };
137         sba.BindlessSurfaceStateSize = (1 << 20) - 1;
138      } else {
139         sba.BindlessSurfaceStateBaseAddress = ANV_NULL_ADDRESS;
140         sba.BindlessSurfaceStateSize = 0;
141      }
142      sba.BindlessSurfaceStateMOCS = GENX(MOCS);
143      sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
144#  endif
145#  if (GEN_GEN >= 10)
146      sba.BindlessSamplerStateBaseAddress = (struct anv_address) { NULL, 0 };
147      sba.BindlessSamplerStateMOCS = GENX(MOCS);
148      sba.BindlessSamplerStateBaseAddressModifyEnable = true;
149      sba.BindlessSamplerStateBufferSize = 0;
150#  endif
151   }
152
153   /* After re-setting the surface state base address, we have to do some
154    * cache flusing so that the sampler engine will pick up the new
155    * SURFACE_STATE objects and binding tables. From the Broadwell PRM,
156    * Shared Function > 3D Sampler > State > State Caching (page 96):
157    *
158    *    Coherency with system memory in the state cache, like the texture
159    *    cache is handled partially by software. It is expected that the
160    *    command stream or shader will issue Cache Flush operation or
161    *    Cache_Flush sampler message to ensure that the L1 cache remains
162    *    coherent with system memory.
163    *
164    *    [...]
165    *
166    *    Whenever the value of the Dynamic_State_Base_Addr,
167    *    Surface_State_Base_Addr are altered, the L1 state cache must be
168    *    invalidated to ensure the new surface or sampler state is fetched
169    *    from system memory.
170    *
171    * The PIPE_CONTROL command has a "State Cache Invalidation Enable" bit
172    * which, according the PIPE_CONTROL instruction documentation in the
173    * Broadwell PRM:
174    *
175    *    Setting this bit is independent of any other bit in this packet.
176    *    This bit controls the invalidation of the L1 and L2 state caches
177    *    at the top of the pipe i.e. at the parsing time.
178    *
179    * Unfortunately, experimentation seems to indicate that state cache
180    * invalidation through a PIPE_CONTROL does nothing whatsoever in
181    * regards to surface state and binding tables.  In stead, it seems that
182    * invalidating the texture cache is what is actually needed.
183    *
184    * XXX:  As far as we have been able to determine through
185    * experimentation, shows that flush the texture cache appears to be
186    * sufficient.  The theory here is that all of the sampling/rendering
187    * units cache the binding table in the texture cache.  However, we have
188    * yet to be able to actually confirm this.
189    */
190   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
191      pc.TextureCacheInvalidationEnable = true;
192      pc.ConstantCacheInvalidationEnable = true;
193      pc.StateCacheInvalidationEnable = true;
194   }
195}
196
197static void
198add_surface_reloc(struct anv_cmd_buffer *cmd_buffer,
199                  struct anv_state state, struct anv_address addr)
200{
201   const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
202
203   VkResult result =
204      anv_reloc_list_add(&cmd_buffer->surface_relocs, &cmd_buffer->pool->alloc,
205                         state.offset + isl_dev->ss.addr_offset,
206                         addr.bo, addr.offset);
207   if (result != VK_SUCCESS)
208      anv_batch_set_error(&cmd_buffer->batch, result);
209}
210
211static void
212add_surface_state_relocs(struct anv_cmd_buffer *cmd_buffer,
213                         struct anv_surface_state state)
214{
215   const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
216
217   assert(!anv_address_is_null(state.address));
218   add_surface_reloc(cmd_buffer, state.state, state.address);
219
220   if (!anv_address_is_null(state.aux_address)) {
221      VkResult result =
222         anv_reloc_list_add(&cmd_buffer->surface_relocs,
223                            &cmd_buffer->pool->alloc,
224                            state.state.offset + isl_dev->ss.aux_addr_offset,
225                            state.aux_address.bo, state.aux_address.offset);
226      if (result != VK_SUCCESS)
227         anv_batch_set_error(&cmd_buffer->batch, result);
228   }
229
230   if (!anv_address_is_null(state.clear_address)) {
231      VkResult result =
232         anv_reloc_list_add(&cmd_buffer->surface_relocs,
233                            &cmd_buffer->pool->alloc,
234                            state.state.offset +
235                            isl_dev->ss.clear_color_state_offset,
236                            state.clear_address.bo, state.clear_address.offset);
237      if (result != VK_SUCCESS)
238         anv_batch_set_error(&cmd_buffer->batch, result);
239   }
240}
241
242static void
243color_attachment_compute_aux_usage(struct anv_device * device,
244                                   struct anv_cmd_state * cmd_state,
245                                   uint32_t att, VkRect2D render_area,
246                                   union isl_color_value *fast_clear_color)
247{
248   struct anv_attachment_state *att_state = &cmd_state->attachments[att];
249   struct anv_image_view *iview = cmd_state->framebuffer->attachments[att];
250
251   assert(iview->n_planes == 1);
252
253   if (iview->planes[0].isl.base_array_layer >=
254       anv_image_aux_layers(iview->image, VK_IMAGE_ASPECT_COLOR_BIT,
255                            iview->planes[0].isl.base_level)) {
256      /* There is no aux buffer which corresponds to the level and layer(s)
257       * being accessed.
258       */
259      att_state->aux_usage = ISL_AUX_USAGE_NONE;
260      att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
261      att_state->fast_clear = false;
262      return;
263   }
264
265   att_state->aux_usage =
266      anv_layout_to_aux_usage(&device->info, iview->image,
267                              VK_IMAGE_ASPECT_COLOR_BIT,
268                              VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
269
270   /* If we don't have aux, then we should have returned early in the layer
271    * check above.  If we got here, we must have something.
272    */
273   assert(att_state->aux_usage != ISL_AUX_USAGE_NONE);
274
275   if (att_state->aux_usage == ISL_AUX_USAGE_CCS_E ||
276       att_state->aux_usage == ISL_AUX_USAGE_MCS) {
277      att_state->input_aux_usage = att_state->aux_usage;
278   } else {
279      /* From the Sky Lake PRM, RENDER_SURFACE_STATE::AuxiliarySurfaceMode:
280       *
281       *    "If Number of Multisamples is MULTISAMPLECOUNT_1, AUX_CCS_D
282       *    setting is only allowed if Surface Format supported for Fast
283       *    Clear. In addition, if the surface is bound to the sampling
284       *    engine, Surface Format must be supported for Render Target
285       *    Compression for surfaces bound to the sampling engine."
286       *
287       * In other words, we can only sample from a fast-cleared image if it
288       * also supports color compression.
289       */
290      if (isl_format_supports_ccs_e(&device->info, iview->planes[0].isl.format)) {
291         att_state->input_aux_usage = ISL_AUX_USAGE_CCS_D;
292
293         /* While fast-clear resolves and partial resolves are fairly cheap in the
294          * case where you render to most of the pixels, full resolves are not
295          * because they potentially involve reading and writing the entire
296          * framebuffer.  If we can't texture with CCS_E, we should leave it off and
297          * limit ourselves to fast clears.
298          */
299         if (cmd_state->pass->attachments[att].first_subpass_layout ==
300             VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL) {
301            anv_perf_warn(device->instance, iview->image,
302                          "Not temporarily enabling CCS_E.");
303         }
304      } else {
305         att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
306      }
307   }
308
309   assert(iview->image->planes[0].aux_surface.isl.usage &
310          (ISL_SURF_USAGE_CCS_BIT | ISL_SURF_USAGE_MCS_BIT));
311
312   union isl_color_value clear_color = {};
313   anv_clear_color_from_att_state(&clear_color, att_state, iview);
314
315   att_state->clear_color_is_zero_one =
316      isl_color_value_is_zero_one(clear_color, iview->planes[0].isl.format);
317   att_state->clear_color_is_zero =
318      isl_color_value_is_zero(clear_color, iview->planes[0].isl.format);
319
320   if (att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT) {
321      /* Start by getting the fast clear type.  We use the first subpass
322       * layout here because we don't want to fast-clear if the first subpass
323       * to use the attachment can't handle fast-clears.
324       */
325      enum anv_fast_clear_type fast_clear_type =
326         anv_layout_to_fast_clear_type(&device->info, iview->image,
327                                       VK_IMAGE_ASPECT_COLOR_BIT,
328                                       cmd_state->pass->attachments[att].first_subpass_layout);
329      switch (fast_clear_type) {
330      case ANV_FAST_CLEAR_NONE:
331         att_state->fast_clear = false;
332         break;
333      case ANV_FAST_CLEAR_DEFAULT_VALUE:
334         att_state->fast_clear = att_state->clear_color_is_zero;
335         break;
336      case ANV_FAST_CLEAR_ANY:
337         att_state->fast_clear = true;
338         break;
339      }
340
341      /* Potentially, we could do partial fast-clears but doing so has crazy
342       * alignment restrictions.  It's easier to just restrict to full size
343       * fast clears for now.
344       */
345      if (render_area.offset.x != 0 ||
346          render_area.offset.y != 0 ||
347          render_area.extent.width != iview->extent.width ||
348          render_area.extent.height != iview->extent.height)
349         att_state->fast_clear = false;
350
351      /* On Broadwell and earlier, we can only handle 0/1 clear colors */
352      if (GEN_GEN <= 8 && !att_state->clear_color_is_zero_one)
353         att_state->fast_clear = false;
354
355      /* We only allow fast clears to the first slice of an image (level 0,
356       * layer 0) and only for the entire slice.  This guarantees us that, at
357       * any given time, there is only one clear color on any given image at
358       * any given time.  At the time of our testing (Jan 17, 2018), there
359       * were no known applications which would benefit from fast-clearing
360       * more than just the first slice.
361       */
362      if (att_state->fast_clear &&
363          (iview->planes[0].isl.base_level > 0 ||
364           iview->planes[0].isl.base_array_layer > 0)) {
365         anv_perf_warn(device->instance, iview->image,
366                       "Rendering with multi-lod or multi-layer framebuffer "
367                       "with LOAD_OP_LOAD and baseMipLevel > 0 or "
368                       "baseArrayLayer > 0.  Not fast clearing.");
369         att_state->fast_clear = false;
370      } else if (att_state->fast_clear && cmd_state->framebuffer->layers > 1) {
371         anv_perf_warn(device->instance, iview->image,
372                       "Rendering to a multi-layer framebuffer with "
373                       "LOAD_OP_CLEAR.  Only fast-clearing the first slice");
374      }
375
376      if (att_state->fast_clear)
377         *fast_clear_color = clear_color;
378   } else {
379      att_state->fast_clear = false;
380   }
381}
382
383static void
384depth_stencil_attachment_compute_aux_usage(struct anv_device *device,
385                                           struct anv_cmd_state *cmd_state,
386                                           uint32_t att, VkRect2D render_area)
387{
388   struct anv_render_pass_attachment *pass_att =
389      &cmd_state->pass->attachments[att];
390   struct anv_attachment_state *att_state = &cmd_state->attachments[att];
391   struct anv_image_view *iview = cmd_state->framebuffer->attachments[att];
392
393   /* These will be initialized after the first subpass transition. */
394   att_state->aux_usage = ISL_AUX_USAGE_NONE;
395   att_state->input_aux_usage = ISL_AUX_USAGE_NONE;
396
397   if (GEN_GEN == 7) {
398      /* We don't do any HiZ or depth fast-clears on gen7 yet */
399      att_state->fast_clear = false;
400      return;
401   }
402
403   if (!(att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
404      /* If we're just clearing stencil, we can always HiZ clear */
405      att_state->fast_clear = true;
406      return;
407   }
408
409   /* Default to false for now */
410   att_state->fast_clear = false;
411
412   /* We must have depth in order to have HiZ */
413   if (!(iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT))
414      return;
415
416   const enum isl_aux_usage first_subpass_aux_usage =
417      anv_layout_to_aux_usage(&device->info, iview->image,
418                              VK_IMAGE_ASPECT_DEPTH_BIT,
419                              pass_att->first_subpass_layout);
420   if (first_subpass_aux_usage != ISL_AUX_USAGE_HIZ)
421      return;
422
423   if (!blorp_can_hiz_clear_depth(GEN_GEN,
424                                  iview->planes[0].isl.format,
425                                  iview->image->samples,
426                                  render_area.offset.x,
427                                  render_area.offset.y,
428                                  render_area.offset.x +
429                                  render_area.extent.width,
430                                  render_area.offset.y +
431                                  render_area.extent.height))
432      return;
433
434   if (att_state->clear_value.depthStencil.depth != ANV_HZ_FC_VAL)
435      return;
436
437   if (GEN_GEN == 8 && anv_can_sample_with_hiz(&device->info, iview->image)) {
438      /* Only gen9+ supports returning ANV_HZ_FC_VAL when sampling a
439       * fast-cleared portion of a HiZ buffer. Testing has revealed that Gen8
440       * only supports returning 0.0f. Gens prior to gen8 do not support this
441       * feature at all.
442       */
443      return;
444   }
445
446   /* If we got here, then we can fast clear */
447   att_state->fast_clear = true;
448}
449
450static bool
451need_input_attachment_state(const struct anv_render_pass_attachment *att)
452{
453   if (!(att->usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT))
454      return false;
455
456   /* We only allocate input attachment states for color surfaces. Compression
457    * is not yet enabled for depth textures and stencil doesn't allow
458    * compression so we can just use the texture surface state from the view.
459    */
460   return vk_format_is_color(att->format);
461}
462
463/* Transitions a HiZ-enabled depth buffer from one layout to another. Unless
464 * the initial layout is undefined, the HiZ buffer and depth buffer will
465 * represent the same data at the end of this operation.
466 */
467static void
468transition_depth_buffer(struct anv_cmd_buffer *cmd_buffer,
469                        const struct anv_image *image,
470                        VkImageLayout initial_layout,
471                        VkImageLayout final_layout)
472{
473   const bool hiz_enabled = ISL_AUX_USAGE_HIZ ==
474      anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
475                              VK_IMAGE_ASPECT_DEPTH_BIT, initial_layout);
476   const bool enable_hiz = ISL_AUX_USAGE_HIZ ==
477      anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
478                              VK_IMAGE_ASPECT_DEPTH_BIT, final_layout);
479
480   enum isl_aux_op hiz_op;
481   if (hiz_enabled && !enable_hiz) {
482      hiz_op = ISL_AUX_OP_FULL_RESOLVE;
483   } else if (!hiz_enabled && enable_hiz) {
484      hiz_op = ISL_AUX_OP_AMBIGUATE;
485   } else {
486      assert(hiz_enabled == enable_hiz);
487      /* If the same buffer will be used, no resolves are necessary. */
488      hiz_op = ISL_AUX_OP_NONE;
489   }
490
491   if (hiz_op != ISL_AUX_OP_NONE)
492      anv_image_hiz_op(cmd_buffer, image, VK_IMAGE_ASPECT_DEPTH_BIT,
493                       0, 0, 1, hiz_op);
494}
495
496#define MI_PREDICATE_SRC0    0x2400
497#define MI_PREDICATE_SRC1    0x2408
498#define MI_PREDICATE_RESULT  0x2418
499
500static void
501set_image_compressed_bit(struct anv_cmd_buffer *cmd_buffer,
502                         const struct anv_image *image,
503                         VkImageAspectFlagBits aspect,
504                         uint32_t level,
505                         uint32_t base_layer, uint32_t layer_count,
506                         bool compressed)
507{
508   uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
509
510   /* We only have compression tracking for CCS_E */
511   if (image->planes[plane].aux_usage != ISL_AUX_USAGE_CCS_E)
512      return;
513
514   for (uint32_t a = 0; a < layer_count; a++) {
515      uint32_t layer = base_layer + a;
516      anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
517         sdi.Address = anv_image_get_compression_state_addr(cmd_buffer->device,
518                                                            image, aspect,
519                                                            level, layer);
520         sdi.ImmediateData = compressed ? UINT32_MAX : 0;
521      }
522   }
523}
524
525static void
526set_image_fast_clear_state(struct anv_cmd_buffer *cmd_buffer,
527                           const struct anv_image *image,
528                           VkImageAspectFlagBits aspect,
529                           enum anv_fast_clear_type fast_clear)
530{
531   anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
532      sdi.Address = anv_image_get_fast_clear_type_addr(cmd_buffer->device,
533                                                       image, aspect);
534      sdi.ImmediateData = fast_clear;
535   }
536
537   /* Whenever we have fast-clear, we consider that slice to be compressed.
538    * This makes building predicates much easier.
539    */
540   if (fast_clear != ANV_FAST_CLEAR_NONE)
541      set_image_compressed_bit(cmd_buffer, image, aspect, 0, 0, 1, true);
542}
543
544#if GEN_IS_HASWELL || GEN_GEN >= 8
545static inline uint32_t
546mi_alu(uint32_t opcode, uint32_t operand1, uint32_t operand2)
547{
548   struct GENX(MI_MATH_ALU_INSTRUCTION) instr = {
549      .ALUOpcode = opcode,
550      .Operand1 = operand1,
551      .Operand2 = operand2,
552   };
553
554   uint32_t dw;
555   GENX(MI_MATH_ALU_INSTRUCTION_pack)(NULL, &dw, &instr);
556
557   return dw;
558}
559#endif
560
561/* This is only really practical on haswell and above because it requires
562 * MI math in order to get it correct.
563 */
564#if GEN_GEN >= 8 || GEN_IS_HASWELL
565static void
566anv_cmd_compute_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
567                                  const struct anv_image *image,
568                                  VkImageAspectFlagBits aspect,
569                                  uint32_t level, uint32_t array_layer,
570                                  enum isl_aux_op resolve_op,
571                                  enum anv_fast_clear_type fast_clear_supported)
572{
573   struct gen_mi_builder b;
574   gen_mi_builder_init(&b, &cmd_buffer->batch);
575
576   const struct gen_mi_value fast_clear_type =
577      gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
578                                                      image, aspect));
579
580   if (resolve_op == ISL_AUX_OP_FULL_RESOLVE) {
581      /* In this case, we're doing a full resolve which means we want the
582       * resolve to happen if any compression (including fast-clears) is
583       * present.
584       *
585       * In order to simplify the logic a bit, we make the assumption that,
586       * if the first slice has been fast-cleared, it is also marked as
587       * compressed.  See also set_image_fast_clear_state.
588       */
589      const struct gen_mi_value compression_state =
590         gen_mi_mem32(anv_image_get_compression_state_addr(cmd_buffer->device,
591                                                           image, aspect,
592                                                           level, array_layer));
593      gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
594                       compression_state);
595      gen_mi_store(&b, compression_state, gen_mi_imm(0));
596
597      if (level == 0 && array_layer == 0) {
598         /* If the predicate is true, we want to write 0 to the fast clear type
599          * and, if it's false, leave it alone.  We can do this by writing
600          *
601          * clear_type = clear_type & ~predicate;
602          */
603         struct gen_mi_value new_fast_clear_type =
604            gen_mi_iand(&b, fast_clear_type,
605                            gen_mi_inot(&b, gen_mi_reg64(MI_PREDICATE_SRC0)));
606         gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
607      }
608   } else if (level == 0 && array_layer == 0) {
609      /* In this case, we are doing a partial resolve to get rid of fast-clear
610       * colors.  We don't care about the compression state but we do care
611       * about how much fast clear is allowed by the final layout.
612       */
613      assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
614      assert(fast_clear_supported < ANV_FAST_CLEAR_ANY);
615
616      /* We need to compute (fast_clear_supported < image->fast_clear) */
617      struct gen_mi_value pred =
618         gen_mi_ult(&b, gen_mi_imm(fast_clear_supported), fast_clear_type);
619      gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
620                       gen_mi_value_ref(&b, pred));
621
622      /* If the predicate is true, we want to write 0 to the fast clear type
623       * and, if it's false, leave it alone.  We can do this by writing
624       *
625       * clear_type = clear_type & ~predicate;
626       */
627      struct gen_mi_value new_fast_clear_type =
628         gen_mi_iand(&b, fast_clear_type, gen_mi_inot(&b, pred));
629      gen_mi_store(&b, fast_clear_type, new_fast_clear_type);
630   } else {
631      /* In this case, we're trying to do a partial resolve on a slice that
632       * doesn't have clear color.  There's nothing to do.
633       */
634      assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
635      return;
636   }
637
638   /* Set src1 to 0 and use a != condition */
639   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
640
641   anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
642      mip.LoadOperation    = LOAD_LOADINV;
643      mip.CombineOperation = COMBINE_SET;
644      mip.CompareOperation = COMPARE_SRCS_EQUAL;
645   }
646}
647#endif /* GEN_GEN >= 8 || GEN_IS_HASWELL */
648
649#if GEN_GEN <= 8
650static void
651anv_cmd_simple_resolve_predicate(struct anv_cmd_buffer *cmd_buffer,
652                                 const struct anv_image *image,
653                                 VkImageAspectFlagBits aspect,
654                                 uint32_t level, uint32_t array_layer,
655                                 enum isl_aux_op resolve_op,
656                                 enum anv_fast_clear_type fast_clear_supported)
657{
658   struct gen_mi_builder b;
659   gen_mi_builder_init(&b, &cmd_buffer->batch);
660
661   struct gen_mi_value fast_clear_type_mem =
662      gen_mi_mem32(anv_image_get_fast_clear_type_addr(cmd_buffer->device,
663                                                      image, aspect));
664
665   /* This only works for partial resolves and only when the clear color is
666    * all or nothing.  On the upside, this emits less command streamer code
667    * and works on Ivybridge and Bay Trail.
668    */
669   assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
670   assert(fast_clear_supported != ANV_FAST_CLEAR_ANY);
671
672   /* We don't support fast clears on anything other than the first slice. */
673   if (level > 0 || array_layer > 0)
674      return;
675
676   /* On gen8, we don't have a concept of default clear colors because we
677    * can't sample from CCS surfaces.  It's enough to just load the fast clear
678    * state into the predicate register.
679    */
680   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), fast_clear_type_mem);
681   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
682   gen_mi_store(&b, fast_clear_type_mem, gen_mi_imm(0));
683
684   anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
685      mip.LoadOperation    = LOAD_LOADINV;
686      mip.CombineOperation = COMBINE_SET;
687      mip.CompareOperation = COMPARE_SRCS_EQUAL;
688   }
689}
690#endif /* GEN_GEN <= 8 */
691
692static void
693anv_cmd_predicated_ccs_resolve(struct anv_cmd_buffer *cmd_buffer,
694                               const struct anv_image *image,
695                               enum isl_format format,
696                               VkImageAspectFlagBits aspect,
697                               uint32_t level, uint32_t array_layer,
698                               enum isl_aux_op resolve_op,
699                               enum anv_fast_clear_type fast_clear_supported)
700{
701   const uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
702
703#if GEN_GEN >= 9
704   anv_cmd_compute_resolve_predicate(cmd_buffer, image,
705                                     aspect, level, array_layer,
706                                     resolve_op, fast_clear_supported);
707#else /* GEN_GEN <= 8 */
708   anv_cmd_simple_resolve_predicate(cmd_buffer, image,
709                                    aspect, level, array_layer,
710                                    resolve_op, fast_clear_supported);
711#endif
712
713   /* CCS_D only supports full resolves and BLORP will assert on us if we try
714    * to do a partial resolve on a CCS_D surface.
715    */
716   if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
717       image->planes[plane].aux_usage == ISL_AUX_USAGE_NONE)
718      resolve_op = ISL_AUX_OP_FULL_RESOLVE;
719
720   anv_image_ccs_op(cmd_buffer, image, format, aspect, level,
721                    array_layer, 1, resolve_op, NULL, true);
722}
723
724static void
725anv_cmd_predicated_mcs_resolve(struct anv_cmd_buffer *cmd_buffer,
726                               const struct anv_image *image,
727                               enum isl_format format,
728                               VkImageAspectFlagBits aspect,
729                               uint32_t array_layer,
730                               enum isl_aux_op resolve_op,
731                               enum anv_fast_clear_type fast_clear_supported)
732{
733   assert(aspect == VK_IMAGE_ASPECT_COLOR_BIT);
734   assert(resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE);
735
736#if GEN_GEN >= 8 || GEN_IS_HASWELL
737   anv_cmd_compute_resolve_predicate(cmd_buffer, image,
738                                     aspect, 0, array_layer,
739                                     resolve_op, fast_clear_supported);
740
741   anv_image_mcs_op(cmd_buffer, image, format, aspect,
742                    array_layer, 1, resolve_op, NULL, true);
743#else
744   unreachable("MCS resolves are unsupported on Ivybridge and Bay Trail");
745#endif
746}
747
748void
749genX(cmd_buffer_mark_image_written)(struct anv_cmd_buffer *cmd_buffer,
750                                    const struct anv_image *image,
751                                    VkImageAspectFlagBits aspect,
752                                    enum isl_aux_usage aux_usage,
753                                    uint32_t level,
754                                    uint32_t base_layer,
755                                    uint32_t layer_count)
756{
757   /* The aspect must be exactly one of the image aspects. */
758   assert(util_bitcount(aspect) == 1 && (aspect & image->aspects));
759
760   /* The only compression types with more than just fast-clears are MCS,
761    * CCS_E, and HiZ.  With HiZ we just trust the layout and don't actually
762    * track the current fast-clear and compression state.  This leaves us
763    * with just MCS and CCS_E.
764    */
765   if (aux_usage != ISL_AUX_USAGE_CCS_E &&
766       aux_usage != ISL_AUX_USAGE_MCS)
767      return;
768
769   set_image_compressed_bit(cmd_buffer, image, aspect,
770                            level, base_layer, layer_count, true);
771}
772
773static void
774init_fast_clear_color(struct anv_cmd_buffer *cmd_buffer,
775                      const struct anv_image *image,
776                      VkImageAspectFlagBits aspect)
777{
778   assert(cmd_buffer && image);
779   assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
780
781   set_image_fast_clear_state(cmd_buffer, image, aspect,
782                              ANV_FAST_CLEAR_NONE);
783
784   /* Initialize the struct fields that are accessed for fast-clears so that
785    * the HW restrictions on the field values are satisfied.
786    */
787   struct anv_address addr =
788      anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
789
790   if (GEN_GEN >= 9) {
791      const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
792      const unsigned num_dwords = GEN_GEN >= 10 ?
793                                  isl_dev->ss.clear_color_state_size / 4 :
794                                  isl_dev->ss.clear_value_size / 4;
795      for (unsigned i = 0; i < num_dwords; i++) {
796         anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
797            sdi.Address = addr;
798            sdi.Address.offset += i * 4;
799            sdi.ImmediateData = 0;
800         }
801      }
802   } else {
803      anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_DATA_IMM), sdi) {
804         sdi.Address = addr;
805         if (GEN_GEN >= 8 || GEN_IS_HASWELL) {
806            /* Pre-SKL, the dword containing the clear values also contains
807             * other fields, so we need to initialize those fields to match the
808             * values that would be in a color attachment.
809             */
810            sdi.ImmediateData = ISL_CHANNEL_SELECT_RED   << 25 |
811                                ISL_CHANNEL_SELECT_GREEN << 22 |
812                                ISL_CHANNEL_SELECT_BLUE  << 19 |
813                                ISL_CHANNEL_SELECT_ALPHA << 16;
814         } else if (GEN_GEN == 7) {
815            /* On IVB, the dword containing the clear values also contains
816             * other fields that must be zero or can be zero.
817             */
818            sdi.ImmediateData = 0;
819         }
820      }
821   }
822}
823
824/* Copy the fast-clear value dword(s) between a surface state object and an
825 * image's fast clear state buffer.
826 */
827static void
828genX(copy_fast_clear_dwords)(struct anv_cmd_buffer *cmd_buffer,
829                             struct anv_state surface_state,
830                             const struct anv_image *image,
831                             VkImageAspectFlagBits aspect,
832                             bool copy_from_surface_state)
833{
834   assert(cmd_buffer && image);
835   assert(image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
836
837   struct anv_address ss_clear_addr = {
838      .bo = cmd_buffer->device->surface_state_pool.block_pool.bo,
839      .offset = surface_state.offset +
840                cmd_buffer->device->isl_dev.ss.clear_value_offset,
841   };
842   const struct anv_address entry_addr =
843      anv_image_get_clear_color_addr(cmd_buffer->device, image, aspect);
844   unsigned copy_size = cmd_buffer->device->isl_dev.ss.clear_value_size;
845
846#if GEN_GEN == 7
847   /* On gen7, the combination of commands used here(MI_LOAD_REGISTER_MEM
848    * and MI_STORE_REGISTER_MEM) can cause GPU hangs if any rendering is
849    * in-flight when they are issued even if the memory touched is not
850    * currently active for rendering.  The weird bit is that it is not the
851    * MI_LOAD/STORE_REGISTER_MEM commands which hang but rather the in-flight
852    * rendering hangs such that the next stalling command after the
853    * MI_LOAD/STORE_REGISTER_MEM commands will catch the hang.
854    *
855    * It is unclear exactly why this hang occurs.  Both MI commands come with
856    * warnings about the 3D pipeline but that doesn't seem to fully explain
857    * it.  My (Jason's) best theory is that it has something to do with the
858    * fact that we're using a GPU state register as our temporary and that
859    * something with reading/writing it is causing problems.
860    *
861    * In order to work around this issue, we emit a PIPE_CONTROL with the
862    * command streamer stall bit set.
863    */
864   cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
865   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
866#endif
867
868   struct gen_mi_builder b;
869   gen_mi_builder_init(&b, &cmd_buffer->batch);
870
871   if (copy_from_surface_state) {
872      gen_mi_memcpy(&b, entry_addr, ss_clear_addr, copy_size);
873   } else {
874      gen_mi_memcpy(&b, ss_clear_addr, entry_addr, copy_size);
875
876      /* Updating a surface state object may require that the state cache be
877       * invalidated. From the SKL PRM, Shared Functions -> State -> State
878       * Caching:
879       *
880       *    Whenever the RENDER_SURFACE_STATE object in memory pointed to by
881       *    the Binding Table Pointer (BTP) and Binding Table Index (BTI) is
882       *    modified [...], the L1 state cache must be invalidated to ensure
883       *    the new surface or sampler state is fetched from system memory.
884       *
885       * In testing, SKL doesn't actually seem to need this, but HSW does.
886       */
887      cmd_buffer->state.pending_pipe_bits |=
888         ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
889   }
890}
891
892/**
893 * @brief Transitions a color buffer from one layout to another.
894 *
895 * See section 6.1.1. Image Layout Transitions of the Vulkan 1.0.50 spec for
896 * more information.
897 *
898 * @param level_count VK_REMAINING_MIP_LEVELS isn't supported.
899 * @param layer_count VK_REMAINING_ARRAY_LAYERS isn't supported. For 3D images,
900 *                    this represents the maximum layers to transition at each
901 *                    specified miplevel.
902 */
903static void
904transition_color_buffer(struct anv_cmd_buffer *cmd_buffer,
905                        const struct anv_image *image,
906                        VkImageAspectFlagBits aspect,
907                        const uint32_t base_level, uint32_t level_count,
908                        uint32_t base_layer, uint32_t layer_count,
909                        VkImageLayout initial_layout,
910                        VkImageLayout final_layout)
911{
912   const struct gen_device_info *devinfo = &cmd_buffer->device->info;
913   /* Validate the inputs. */
914   assert(cmd_buffer);
915   assert(image && image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV);
916   /* These values aren't supported for simplicity's sake. */
917   assert(level_count != VK_REMAINING_MIP_LEVELS &&
918          layer_count != VK_REMAINING_ARRAY_LAYERS);
919   /* Ensure the subresource range is valid. */
920   UNUSED uint64_t last_level_num = base_level + level_count;
921   const uint32_t max_depth = anv_minify(image->extent.depth, base_level);
922   UNUSED const uint32_t image_layers = MAX2(image->array_size, max_depth);
923   assert((uint64_t)base_layer + layer_count  <= image_layers);
924   assert(last_level_num <= image->levels);
925   /* The spec disallows these final layouts. */
926   assert(final_layout != VK_IMAGE_LAYOUT_UNDEFINED &&
927          final_layout != VK_IMAGE_LAYOUT_PREINITIALIZED);
928
929   /* No work is necessary if the layout stays the same or if this subresource
930    * range lacks auxiliary data.
931    */
932   if (initial_layout == final_layout)
933      return;
934
935   uint32_t plane = anv_image_aspect_to_plane(image->aspects, aspect);
936
937   if (image->planes[plane].shadow_surface.isl.size_B > 0 &&
938       final_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
939      /* This surface is a linear compressed image with a tiled shadow surface
940       * for texturing.  The client is about to use it in READ_ONLY_OPTIMAL so
941       * we need to ensure the shadow copy is up-to-date.
942       */
943      assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
944      assert(image->planes[plane].surface.isl.tiling == ISL_TILING_LINEAR);
945      assert(image->planes[plane].shadow_surface.isl.tiling != ISL_TILING_LINEAR);
946      assert(isl_format_is_compressed(image->planes[plane].surface.isl.format));
947      assert(plane == 0);
948      anv_image_copy_to_shadow(cmd_buffer, image,
949                               base_level, level_count,
950                               base_layer, layer_count);
951   }
952
953   if (base_layer >= anv_image_aux_layers(image, aspect, base_level))
954      return;
955
956   assert(image->tiling == VK_IMAGE_TILING_OPTIMAL);
957
958   if (initial_layout == VK_IMAGE_LAYOUT_UNDEFINED ||
959       initial_layout == VK_IMAGE_LAYOUT_PREINITIALIZED) {
960      /* A subresource in the undefined layout may have been aliased and
961       * populated with any arrangement of bits. Therefore, we must initialize
962       * the related aux buffer and clear buffer entry with desirable values.
963       * An initial layout of PREINITIALIZED is the same as UNDEFINED for
964       * images with VK_IMAGE_TILING_OPTIMAL.
965       *
966       * Initialize the relevant clear buffer entries.
967       */
968      if (base_level == 0 && base_layer == 0)
969         init_fast_clear_color(cmd_buffer, image, aspect);
970
971      /* Initialize the aux buffers to enable correct rendering.  In order to
972       * ensure that things such as storage images work correctly, aux buffers
973       * need to be initialized to valid data.
974       *
975       * Having an aux buffer with invalid data is a problem for two reasons:
976       *
977       *  1) Having an invalid value in the buffer can confuse the hardware.
978       *     For instance, with CCS_E on SKL, a two-bit CCS value of 2 is
979       *     invalid and leads to the hardware doing strange things.  It
980       *     doesn't hang as far as we can tell but rendering corruption can
981       *     occur.
982       *
983       *  2) If this transition is into the GENERAL layout and we then use the
984       *     image as a storage image, then we must have the aux buffer in the
985       *     pass-through state so that, if we then go to texture from the
986       *     image, we get the results of our storage image writes and not the
987       *     fast clear color or other random data.
988       *
989       * For CCS both of the problems above are real demonstrable issues.  In
990       * that case, the only thing we can do is to perform an ambiguate to
991       * transition the aux surface into the pass-through state.
992       *
993       * For MCS, (2) is never an issue because we don't support multisampled
994       * storage images.  In theory, issue (1) is a problem with MCS but we've
995       * never seen it in the wild.  For 4x and 16x, all bit patters could, in
996       * theory, be interpreted as something but we don't know that all bit
997       * patterns are actually valid.  For 2x and 8x, you could easily end up
998       * with the MCS referring to an invalid plane because not all bits of
999       * the MCS value are actually used.  Even though we've never seen issues
1000       * in the wild, it's best to play it safe and initialize the MCS.  We
1001       * can use a fast-clear for MCS because we only ever touch from render
1002       * and texture (no image load store).
1003       */
1004      if (image->samples == 1) {
1005         for (uint32_t l = 0; l < level_count; l++) {
1006            const uint32_t level = base_level + l;
1007
1008            uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1009            if (base_layer >= aux_layers)
1010               break; /* We will only get fewer layers as level increases */
1011            uint32_t level_layer_count =
1012               MIN2(layer_count, aux_layers - base_layer);
1013
1014            anv_image_ccs_op(cmd_buffer, image,
1015                             image->planes[plane].surface.isl.format,
1016                             aspect, level, base_layer, level_layer_count,
1017                             ISL_AUX_OP_AMBIGUATE, NULL, false);
1018
1019            if (image->planes[plane].aux_usage == ISL_AUX_USAGE_CCS_E) {
1020               set_image_compressed_bit(cmd_buffer, image, aspect,
1021                                        level, base_layer, level_layer_count,
1022                                        false);
1023            }
1024         }
1025      } else {
1026         if (image->samples == 4 || image->samples == 16) {
1027            anv_perf_warn(cmd_buffer->device->instance, image,
1028                          "Doing a potentially unnecessary fast-clear to "
1029                          "define an MCS buffer.");
1030         }
1031
1032         assert(base_level == 0 && level_count == 1);
1033         anv_image_mcs_op(cmd_buffer, image,
1034                          image->planes[plane].surface.isl.format,
1035                          aspect, base_layer, layer_count,
1036                          ISL_AUX_OP_FAST_CLEAR, NULL, false);
1037      }
1038      return;
1039   }
1040
1041   const enum isl_aux_usage initial_aux_usage =
1042      anv_layout_to_aux_usage(devinfo, image, aspect, initial_layout);
1043   const enum isl_aux_usage final_aux_usage =
1044      anv_layout_to_aux_usage(devinfo, image, aspect, final_layout);
1045
1046   /* The current code assumes that there is no mixing of CCS_E and CCS_D.
1047    * We can handle transitions between CCS_D/E to and from NONE.  What we
1048    * don't yet handle is switching between CCS_E and CCS_D within a given
1049    * image.  Doing so in a performant way requires more detailed aux state
1050    * tracking such as what is done in i965.  For now, just assume that we
1051    * only have one type of compression.
1052    */
1053   assert(initial_aux_usage == ISL_AUX_USAGE_NONE ||
1054          final_aux_usage == ISL_AUX_USAGE_NONE ||
1055          initial_aux_usage == final_aux_usage);
1056
1057   /* If initial aux usage is NONE, there is nothing to resolve */
1058   if (initial_aux_usage == ISL_AUX_USAGE_NONE)
1059      return;
1060
1061   enum isl_aux_op resolve_op = ISL_AUX_OP_NONE;
1062
1063   /* If the initial layout supports more fast clear than the final layout
1064    * then we need at least a partial resolve.
1065    */
1066   const enum anv_fast_clear_type initial_fast_clear =
1067      anv_layout_to_fast_clear_type(devinfo, image, aspect, initial_layout);
1068   const enum anv_fast_clear_type final_fast_clear =
1069      anv_layout_to_fast_clear_type(devinfo, image, aspect, final_layout);
1070   if (final_fast_clear < initial_fast_clear)
1071      resolve_op = ISL_AUX_OP_PARTIAL_RESOLVE;
1072
1073   if (initial_aux_usage == ISL_AUX_USAGE_CCS_E &&
1074       final_aux_usage != ISL_AUX_USAGE_CCS_E)
1075      resolve_op = ISL_AUX_OP_FULL_RESOLVE;
1076
1077   if (resolve_op == ISL_AUX_OP_NONE)
1078      return;
1079
1080   /* Perform a resolve to synchronize data between the main and aux buffer.
1081    * Before we begin, we must satisfy the cache flushing requirement specified
1082    * in the Sky Lake PRM Vol. 7, "MCS Buffer for Render Target(s)":
1083    *
1084    *    Any transition from any value in {Clear, Render, Resolve} to a
1085    *    different value in {Clear, Render, Resolve} requires end of pipe
1086    *    synchronization.
1087    *
1088    * We perform a flush of the write cache before and after the clear and
1089    * resolve operations to meet this requirement.
1090    *
1091    * Unlike other drawing, fast clear operations are not properly
1092    * synchronized. The first PIPE_CONTROL here likely ensures that the
1093    * contents of the previous render or clear hit the render target before we
1094    * resolve and the second likely ensures that the resolve is complete before
1095    * we do any more rendering or clearing.
1096    */
1097   cmd_buffer->state.pending_pipe_bits |=
1098      ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1099
1100   for (uint32_t l = 0; l < level_count; l++) {
1101      uint32_t level = base_level + l;
1102
1103      uint32_t aux_layers = anv_image_aux_layers(image, aspect, level);
1104      if (base_layer >= aux_layers)
1105         break; /* We will only get fewer layers as level increases */
1106      uint32_t level_layer_count =
1107         MIN2(layer_count, aux_layers - base_layer);
1108
1109      for (uint32_t a = 0; a < level_layer_count; a++) {
1110         uint32_t array_layer = base_layer + a;
1111         if (image->samples == 1) {
1112            anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
1113                                           image->planes[plane].surface.isl.format,
1114                                           aspect, level, array_layer, resolve_op,
1115                                           final_fast_clear);
1116         } else {
1117            /* We only support fast-clear on the first layer so partial
1118             * resolves should not be used on other layers as they will use
1119             * the clear color stored in memory that is only valid for layer0.
1120             */
1121            if (resolve_op == ISL_AUX_OP_PARTIAL_RESOLVE &&
1122                array_layer != 0)
1123               continue;
1124
1125            anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
1126                                           image->planes[plane].surface.isl.format,
1127                                           aspect, array_layer, resolve_op,
1128                                           final_fast_clear);
1129         }
1130      }
1131   }
1132
1133   cmd_buffer->state.pending_pipe_bits |=
1134      ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT | ANV_PIPE_CS_STALL_BIT;
1135}
1136
1137/**
1138 * Setup anv_cmd_state::attachments for vkCmdBeginRenderPass.
1139 */
1140static VkResult
1141genX(cmd_buffer_setup_attachments)(struct anv_cmd_buffer *cmd_buffer,
1142                                   struct anv_render_pass *pass,
1143                                   const VkRenderPassBeginInfo *begin)
1144{
1145   const struct isl_device *isl_dev = &cmd_buffer->device->isl_dev;
1146   struct anv_cmd_state *state = &cmd_buffer->state;
1147
1148   vk_free(&cmd_buffer->pool->alloc, state->attachments);
1149
1150   if (pass->attachment_count > 0) {
1151      state->attachments = vk_alloc(&cmd_buffer->pool->alloc,
1152                                    pass->attachment_count *
1153                                         sizeof(state->attachments[0]),
1154                                    8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1155      if (state->attachments == NULL) {
1156         /* Propagate VK_ERROR_OUT_OF_HOST_MEMORY to vkEndCommandBuffer */
1157         return anv_batch_set_error(&cmd_buffer->batch,
1158                                    VK_ERROR_OUT_OF_HOST_MEMORY);
1159      }
1160   } else {
1161      state->attachments = NULL;
1162   }
1163
1164   /* Reserve one for the NULL state. */
1165   unsigned num_states = 1;
1166   for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1167      if (vk_format_is_color(pass->attachments[i].format))
1168         num_states++;
1169
1170      if (need_input_attachment_state(&pass->attachments[i]))
1171         num_states++;
1172   }
1173
1174   const uint32_t ss_stride = align_u32(isl_dev->ss.size, isl_dev->ss.align);
1175   state->render_pass_states =
1176      anv_state_stream_alloc(&cmd_buffer->surface_state_stream,
1177                             num_states * ss_stride, isl_dev->ss.align);
1178
1179   struct anv_state next_state = state->render_pass_states;
1180   next_state.alloc_size = isl_dev->ss.size;
1181
1182   state->null_surface_state = next_state;
1183   next_state.offset += ss_stride;
1184   next_state.map += ss_stride;
1185
1186   for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1187      if (vk_format_is_color(pass->attachments[i].format)) {
1188         state->attachments[i].color.state = next_state;
1189         next_state.offset += ss_stride;
1190         next_state.map += ss_stride;
1191      }
1192
1193      if (need_input_attachment_state(&pass->attachments[i])) {
1194         state->attachments[i].input.state = next_state;
1195         next_state.offset += ss_stride;
1196         next_state.map += ss_stride;
1197      }
1198   }
1199   assert(next_state.offset == state->render_pass_states.offset +
1200                               state->render_pass_states.alloc_size);
1201
1202   if (begin) {
1203      ANV_FROM_HANDLE(anv_framebuffer, framebuffer, begin->framebuffer);
1204      assert(pass->attachment_count == framebuffer->attachment_count);
1205
1206      isl_null_fill_state(isl_dev, state->null_surface_state.map,
1207                          isl_extent3d(framebuffer->width,
1208                                       framebuffer->height,
1209                                       framebuffer->layers));
1210
1211      for (uint32_t i = 0; i < pass->attachment_count; ++i) {
1212         struct anv_render_pass_attachment *att = &pass->attachments[i];
1213         VkImageAspectFlags att_aspects = vk_format_aspects(att->format);
1214         VkImageAspectFlags clear_aspects = 0;
1215         VkImageAspectFlags load_aspects = 0;
1216
1217         if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1218            /* color attachment */
1219            if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1220               clear_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1221            } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1222               load_aspects |= VK_IMAGE_ASPECT_COLOR_BIT;
1223            }
1224         } else {
1225            /* depthstencil attachment */
1226            if (att_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
1227               if (att->load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1228                  clear_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1229               } else if (att->load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1230                  load_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1231               }
1232            }
1233            if (att_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) {
1234               if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_CLEAR) {
1235                  clear_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1236               } else if (att->stencil_load_op == VK_ATTACHMENT_LOAD_OP_LOAD) {
1237                  load_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1238               }
1239            }
1240         }
1241
1242         state->attachments[i].current_layout = att->initial_layout;
1243         state->attachments[i].pending_clear_aspects = clear_aspects;
1244         state->attachments[i].pending_load_aspects = load_aspects;
1245         if (clear_aspects)
1246            state->attachments[i].clear_value = begin->pClearValues[i];
1247
1248         struct anv_image_view *iview = framebuffer->attachments[i];
1249         anv_assert(iview->vk_format == att->format);
1250
1251         const uint32_t num_layers = iview->planes[0].isl.array_len;
1252         state->attachments[i].pending_clear_views = (1 << num_layers) - 1;
1253
1254         union isl_color_value clear_color = { .u32 = { 0, } };
1255         if (att_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1256            anv_assert(iview->n_planes == 1);
1257            assert(att_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
1258            color_attachment_compute_aux_usage(cmd_buffer->device,
1259                                               state, i, begin->renderArea,
1260                                               &clear_color);
1261
1262            anv_image_fill_surface_state(cmd_buffer->device,
1263                                         iview->image,
1264                                         VK_IMAGE_ASPECT_COLOR_BIT,
1265                                         &iview->planes[0].isl,
1266                                         ISL_SURF_USAGE_RENDER_TARGET_BIT,
1267                                         state->attachments[i].aux_usage,
1268                                         &clear_color,
1269                                         0,
1270                                         &state->attachments[i].color,
1271                                         NULL);
1272
1273            add_surface_state_relocs(cmd_buffer, state->attachments[i].color);
1274         } else {
1275            depth_stencil_attachment_compute_aux_usage(cmd_buffer->device,
1276                                                       state, i,
1277                                                       begin->renderArea);
1278         }
1279
1280         if (need_input_attachment_state(&pass->attachments[i])) {
1281            anv_image_fill_surface_state(cmd_buffer->device,
1282                                         iview->image,
1283                                         VK_IMAGE_ASPECT_COLOR_BIT,
1284                                         &iview->planes[0].isl,
1285                                         ISL_SURF_USAGE_TEXTURE_BIT,
1286                                         state->attachments[i].input_aux_usage,
1287                                         &clear_color,
1288                                         0,
1289                                         &state->attachments[i].input,
1290                                         NULL);
1291
1292            add_surface_state_relocs(cmd_buffer, state->attachments[i].input);
1293         }
1294      }
1295   }
1296
1297   return VK_SUCCESS;
1298}
1299
1300VkResult
1301genX(BeginCommandBuffer)(
1302    VkCommandBuffer                             commandBuffer,
1303    const VkCommandBufferBeginInfo*             pBeginInfo)
1304{
1305   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1306
1307   /* If this is the first vkBeginCommandBuffer, we must *initialize* the
1308    * command buffer's state. Otherwise, we must *reset* its state. In both
1309    * cases we reset it.
1310    *
1311    * From the Vulkan 1.0 spec:
1312    *
1313    *    If a command buffer is in the executable state and the command buffer
1314    *    was allocated from a command pool with the
1315    *    VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT flag set, then
1316    *    vkBeginCommandBuffer implicitly resets the command buffer, behaving
1317    *    as if vkResetCommandBuffer had been called with
1318    *    VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT not set. It then puts
1319    *    the command buffer in the recording state.
1320    */
1321   anv_cmd_buffer_reset(cmd_buffer);
1322
1323   cmd_buffer->usage_flags = pBeginInfo->flags;
1324
1325   assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY ||
1326          !(cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT));
1327
1328   genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
1329
1330   /* We sometimes store vertex data in the dynamic state buffer for blorp
1331    * operations and our dynamic state stream may re-use data from previous
1332    * command buffers.  In order to prevent stale cache data, we flush the VF
1333    * cache.  We could do this on every blorp call but that's not really
1334    * needed as all of the data will get written by the CPU prior to the GPU
1335    * executing anything.  The chances are fairly high that they will use
1336    * blorp at least once per primary command buffer so it shouldn't be
1337    * wasted.
1338    */
1339   if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY)
1340      cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1341
1342   /* We send an "Indirect State Pointers Disable" packet at
1343    * EndCommandBuffer, so all push contant packets are ignored during a
1344    * context restore. Documentation says after that command, we need to
1345    * emit push constants again before any rendering operation. So we
1346    * flag them dirty here to make sure they get emitted.
1347    */
1348   cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1349
1350   VkResult result = VK_SUCCESS;
1351   if (cmd_buffer->usage_flags &
1352       VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1353      assert(pBeginInfo->pInheritanceInfo);
1354      cmd_buffer->state.pass =
1355         anv_render_pass_from_handle(pBeginInfo->pInheritanceInfo->renderPass);
1356      cmd_buffer->state.subpass =
1357         &cmd_buffer->state.pass->subpasses[pBeginInfo->pInheritanceInfo->subpass];
1358
1359      /* This is optional in the inheritance info. */
1360      cmd_buffer->state.framebuffer =
1361         anv_framebuffer_from_handle(pBeginInfo->pInheritanceInfo->framebuffer);
1362
1363      result = genX(cmd_buffer_setup_attachments)(cmd_buffer,
1364                                                  cmd_buffer->state.pass, NULL);
1365
1366      /* Record that HiZ is enabled if we can. */
1367      if (cmd_buffer->state.framebuffer) {
1368         const struct anv_image_view * const iview =
1369            anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
1370
1371         if (iview) {
1372            VkImageLayout layout =
1373                cmd_buffer->state.subpass->depth_stencil_attachment->layout;
1374
1375            enum isl_aux_usage aux_usage =
1376               anv_layout_to_aux_usage(&cmd_buffer->device->info, iview->image,
1377                                       VK_IMAGE_ASPECT_DEPTH_BIT, layout);
1378
1379            cmd_buffer->state.hiz_enabled = aux_usage == ISL_AUX_USAGE_HIZ;
1380         }
1381      }
1382
1383      cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
1384   }
1385
1386#if GEN_GEN >= 8 || GEN_IS_HASWELL
1387   if (cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
1388      const VkCommandBufferInheritanceConditionalRenderingInfoEXT *conditional_rendering_info =
1389         vk_find_struct_const(pBeginInfo->pInheritanceInfo->pNext, COMMAND_BUFFER_INHERITANCE_CONDITIONAL_RENDERING_INFO_EXT);
1390
1391      /* If secondary buffer supports conditional rendering
1392       * we should emit commands as if conditional rendering is enabled.
1393       */
1394      cmd_buffer->state.conditional_render_enabled =
1395         conditional_rendering_info && conditional_rendering_info->conditionalRenderingEnable;
1396   }
1397#endif
1398
1399   return result;
1400}
1401
1402/* From the PRM, Volume 2a:
1403 *
1404 *    "Indirect State Pointers Disable
1405 *
1406 *    At the completion of the post-sync operation associated with this pipe
1407 *    control packet, the indirect state pointers in the hardware are
1408 *    considered invalid; the indirect pointers are not saved in the context.
1409 *    If any new indirect state commands are executed in the command stream
1410 *    while the pipe control is pending, the new indirect state commands are
1411 *    preserved.
1412 *
1413 *    [DevIVB+]: Using Invalidate State Pointer (ISP) only inhibits context
1414 *    restoring of Push Constant (3DSTATE_CONSTANT_*) commands. Push Constant
1415 *    commands are only considered as Indirect State Pointers. Once ISP is
1416 *    issued in a context, SW must initialize by programming push constant
1417 *    commands for all the shaders (at least to zero length) before attempting
1418 *    any rendering operation for the same context."
1419 *
1420 * 3DSTATE_CONSTANT_* packets are restored during a context restore,
1421 * even though they point to a BO that has been already unreferenced at
1422 * the end of the previous batch buffer. This has been fine so far since
1423 * we are protected by these scratch page (every address not covered by
1424 * a BO should be pointing to the scratch page). But on CNL, it is
1425 * causing a GPU hang during context restore at the 3DSTATE_CONSTANT_*
1426 * instruction.
1427 *
1428 * The flag "Indirect State Pointers Disable" in PIPE_CONTROL tells the
1429 * hardware to ignore previous 3DSTATE_CONSTANT_* packets during a
1430 * context restore, so the mentioned hang doesn't happen. However,
1431 * software must program push constant commands for all stages prior to
1432 * rendering anything. So we flag them dirty in BeginCommandBuffer.
1433 *
1434 * Finally, we also make sure to stall at pixel scoreboard to make sure the
1435 * constants have been loaded into the EUs prior to disable the push constants
1436 * so that it doesn't hang a previous 3DPRIMITIVE.
1437 */
1438static void
1439emit_isp_disable(struct anv_cmd_buffer *cmd_buffer)
1440{
1441   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1442         pc.StallAtPixelScoreboard = true;
1443         pc.CommandStreamerStallEnable = true;
1444   }
1445   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1446         pc.IndirectStatePointersDisable = true;
1447         pc.CommandStreamerStallEnable = true;
1448   }
1449}
1450
1451VkResult
1452genX(EndCommandBuffer)(
1453    VkCommandBuffer                             commandBuffer)
1454{
1455   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1456
1457   if (anv_batch_has_error(&cmd_buffer->batch))
1458      return cmd_buffer->batch.status;
1459
1460   /* We want every command buffer to start with the PMA fix in a known state,
1461    * so we disable it at the end of the command buffer.
1462    */
1463   genX(cmd_buffer_enable_pma_fix)(cmd_buffer, false);
1464
1465   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
1466
1467   emit_isp_disable(cmd_buffer);
1468
1469   anv_cmd_buffer_end_batch_buffer(cmd_buffer);
1470
1471   return VK_SUCCESS;
1472}
1473
1474void
1475genX(CmdExecuteCommands)(
1476    VkCommandBuffer                             commandBuffer,
1477    uint32_t                                    commandBufferCount,
1478    const VkCommandBuffer*                      pCmdBuffers)
1479{
1480   ANV_FROM_HANDLE(anv_cmd_buffer, primary, commandBuffer);
1481
1482   assert(primary->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1483
1484   if (anv_batch_has_error(&primary->batch))
1485      return;
1486
1487   /* The secondary command buffers will assume that the PMA fix is disabled
1488    * when they begin executing.  Make sure this is true.
1489    */
1490   genX(cmd_buffer_enable_pma_fix)(primary, false);
1491
1492   /* The secondary command buffer doesn't know which textures etc. have been
1493    * flushed prior to their execution.  Apply those flushes now.
1494    */
1495   genX(cmd_buffer_apply_pipe_flushes)(primary);
1496
1497   for (uint32_t i = 0; i < commandBufferCount; i++) {
1498      ANV_FROM_HANDLE(anv_cmd_buffer, secondary, pCmdBuffers[i]);
1499
1500      assert(secondary->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY);
1501      assert(!anv_batch_has_error(&secondary->batch));
1502
1503#if GEN_GEN >= 8 || GEN_IS_HASWELL
1504      if (secondary->state.conditional_render_enabled) {
1505         if (!primary->state.conditional_render_enabled) {
1506            /* Secondary buffer is constructed as if it will be executed
1507             * with conditional rendering, we should satisfy this dependency
1508             * regardless of conditional rendering being enabled in primary.
1509             */
1510            struct gen_mi_builder b;
1511            gen_mi_builder_init(&b, &primary->batch);
1512            gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
1513                             gen_mi_imm(UINT64_MAX));
1514         }
1515      }
1516#endif
1517
1518      if (secondary->usage_flags &
1519          VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) {
1520         /* If we're continuing a render pass from the primary, we need to
1521          * copy the surface states for the current subpass into the storage
1522          * we allocated for them in BeginCommandBuffer.
1523          */
1524         struct anv_bo *ss_bo =
1525            primary->device->surface_state_pool.block_pool.bo;
1526         struct anv_state src_state = primary->state.render_pass_states;
1527         struct anv_state dst_state = secondary->state.render_pass_states;
1528         assert(src_state.alloc_size == dst_state.alloc_size);
1529
1530         genX(cmd_buffer_so_memcpy)(primary,
1531                                    (struct anv_address) {
1532                                       .bo = ss_bo,
1533                                       .offset = dst_state.offset,
1534                                    },
1535                                    (struct anv_address) {
1536                                       .bo = ss_bo,
1537                                       .offset = src_state.offset,
1538                                    },
1539                                    src_state.alloc_size);
1540      }
1541
1542      anv_cmd_buffer_add_secondary(primary, secondary);
1543   }
1544
1545   /* The secondary may have selected a different pipeline (3D or compute) and
1546    * may have changed the current L3$ configuration.  Reset our tracking
1547    * variables to invalid values to ensure that we re-emit these in the case
1548    * where we do any draws or compute dispatches from the primary after the
1549    * secondary has returned.
1550    */
1551   primary->state.current_pipeline = UINT32_MAX;
1552   primary->state.current_l3_config = NULL;
1553
1554   /* Each of the secondary command buffers will use its own state base
1555    * address.  We need to re-emit state base address for the primary after
1556    * all of the secondaries are done.
1557    *
1558    * TODO: Maybe we want to make this a dirty bit to avoid extra state base
1559    * address calls?
1560    */
1561   genX(cmd_buffer_emit_state_base_address)(primary);
1562}
1563
1564#define IVB_L3SQCREG1_SQGHPCI_DEFAULT     0x00730000
1565#define VLV_L3SQCREG1_SQGHPCI_DEFAULT     0x00d30000
1566#define HSW_L3SQCREG1_SQGHPCI_DEFAULT     0x00610000
1567
1568/**
1569 * Program the hardware to use the specified L3 configuration.
1570 */
1571void
1572genX(cmd_buffer_config_l3)(struct anv_cmd_buffer *cmd_buffer,
1573                           const struct gen_l3_config *cfg)
1574{
1575   assert(cfg);
1576   if (cfg == cmd_buffer->state.current_l3_config)
1577      return;
1578
1579   if (unlikely(INTEL_DEBUG & DEBUG_L3)) {
1580      intel_logd("L3 config transition: ");
1581      gen_dump_l3_config(cfg, stderr);
1582   }
1583
1584   const bool has_slm = cfg->n[GEN_L3P_SLM];
1585
1586   /* According to the hardware docs, the L3 partitioning can only be changed
1587    * while the pipeline is completely drained and the caches are flushed,
1588    * which involves a first PIPE_CONTROL flush which stalls the pipeline...
1589    */
1590   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1591      pc.DCFlushEnable = true;
1592      pc.PostSyncOperation = NoWrite;
1593      pc.CommandStreamerStallEnable = true;
1594   }
1595
1596   /* ...followed by a second pipelined PIPE_CONTROL that initiates
1597    * invalidation of the relevant caches.  Note that because RO invalidation
1598    * happens at the top of the pipeline (i.e. right away as the PIPE_CONTROL
1599    * command is processed by the CS) we cannot combine it with the previous
1600    * stalling flush as the hardware documentation suggests, because that
1601    * would cause the CS to stall on previous rendering *after* RO
1602    * invalidation and wouldn't prevent the RO caches from being polluted by
1603    * concurrent rendering before the stall completes.  This intentionally
1604    * doesn't implement the SKL+ hardware workaround suggesting to enable CS
1605    * stall on PIPE_CONTROLs with the texture cache invalidation bit set for
1606    * GPGPU workloads because the previous and subsequent PIPE_CONTROLs
1607    * already guarantee that there is no concurrent GPGPU kernel execution
1608    * (see SKL HSD 2132585).
1609    */
1610   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1611      pc.TextureCacheInvalidationEnable = true;
1612      pc.ConstantCacheInvalidationEnable = true;
1613      pc.InstructionCacheInvalidateEnable = true;
1614      pc.StateCacheInvalidationEnable = true;
1615      pc.PostSyncOperation = NoWrite;
1616   }
1617
1618   /* Now send a third stalling flush to make sure that invalidation is
1619    * complete when the L3 configuration registers are modified.
1620    */
1621   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
1622      pc.DCFlushEnable = true;
1623      pc.PostSyncOperation = NoWrite;
1624      pc.CommandStreamerStallEnable = true;
1625   }
1626
1627#if GEN_GEN >= 8
1628
1629   assert(!cfg->n[GEN_L3P_IS] && !cfg->n[GEN_L3P_C] && !cfg->n[GEN_L3P_T]);
1630
1631   uint32_t l3cr;
1632   anv_pack_struct(&l3cr, GENX(L3CNTLREG),
1633                   .SLMEnable = has_slm,
1634#if GEN_GEN == 11
1635   /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
1636    * in L3CNTLREG register. The default setting of the bit is not the
1637    * desirable behavior.
1638   */
1639                   .ErrorDetectionBehaviorControl = true,
1640                   .UseFullWays = true,
1641#endif
1642                   .URBAllocation = cfg->n[GEN_L3P_URB],
1643                   .ROAllocation = cfg->n[GEN_L3P_RO],
1644                   .DCAllocation = cfg->n[GEN_L3P_DC],
1645                   .AllAllocation = cfg->n[GEN_L3P_ALL]);
1646
1647   /* Set up the L3 partitioning. */
1648   emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG_num), l3cr);
1649
1650#else
1651
1652   const bool has_dc = cfg->n[GEN_L3P_DC] || cfg->n[GEN_L3P_ALL];
1653   const bool has_is = cfg->n[GEN_L3P_IS] || cfg->n[GEN_L3P_RO] ||
1654                       cfg->n[GEN_L3P_ALL];
1655   const bool has_c = cfg->n[GEN_L3P_C] || cfg->n[GEN_L3P_RO] ||
1656                      cfg->n[GEN_L3P_ALL];
1657   const bool has_t = cfg->n[GEN_L3P_T] || cfg->n[GEN_L3P_RO] ||
1658                      cfg->n[GEN_L3P_ALL];
1659
1660   assert(!cfg->n[GEN_L3P_ALL]);
1661
1662   /* When enabled SLM only uses a portion of the L3 on half of the banks,
1663    * the matching space on the remaining banks has to be allocated to a
1664    * client (URB for all validated configurations) set to the
1665    * lower-bandwidth 2-bank address hashing mode.
1666    */
1667   const struct gen_device_info *devinfo = &cmd_buffer->device->info;
1668   const bool urb_low_bw = has_slm && !devinfo->is_baytrail;
1669   assert(!urb_low_bw || cfg->n[GEN_L3P_URB] == cfg->n[GEN_L3P_SLM]);
1670
1671   /* Minimum number of ways that can be allocated to the URB. */
1672   MAYBE_UNUSED const unsigned n0_urb = devinfo->is_baytrail ? 32 : 0;
1673   assert(cfg->n[GEN_L3P_URB] >= n0_urb);
1674
1675   uint32_t l3sqcr1, l3cr2, l3cr3;
1676   anv_pack_struct(&l3sqcr1, GENX(L3SQCREG1),
1677                   .ConvertDC_UC = !has_dc,
1678                   .ConvertIS_UC = !has_is,
1679                   .ConvertC_UC = !has_c,
1680                   .ConvertT_UC = !has_t);
1681   l3sqcr1 |=
1682      GEN_IS_HASWELL ? HSW_L3SQCREG1_SQGHPCI_DEFAULT :
1683      devinfo->is_baytrail ? VLV_L3SQCREG1_SQGHPCI_DEFAULT :
1684      IVB_L3SQCREG1_SQGHPCI_DEFAULT;
1685
1686   anv_pack_struct(&l3cr2, GENX(L3CNTLREG2),
1687                   .SLMEnable = has_slm,
1688                   .URBLowBandwidth = urb_low_bw,
1689                   .URBAllocation = cfg->n[GEN_L3P_URB] - n0_urb,
1690#if !GEN_IS_HASWELL
1691                   .ALLAllocation = cfg->n[GEN_L3P_ALL],
1692#endif
1693                   .ROAllocation = cfg->n[GEN_L3P_RO],
1694                   .DCAllocation = cfg->n[GEN_L3P_DC]);
1695
1696   anv_pack_struct(&l3cr3, GENX(L3CNTLREG3),
1697                   .ISAllocation = cfg->n[GEN_L3P_IS],
1698                   .ISLowBandwidth = 0,
1699                   .CAllocation = cfg->n[GEN_L3P_C],
1700                   .CLowBandwidth = 0,
1701                   .TAllocation = cfg->n[GEN_L3P_T],
1702                   .TLowBandwidth = 0);
1703
1704   /* Set up the L3 partitioning. */
1705   emit_lri(&cmd_buffer->batch, GENX(L3SQCREG1_num), l3sqcr1);
1706   emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG2_num), l3cr2);
1707   emit_lri(&cmd_buffer->batch, GENX(L3CNTLREG3_num), l3cr3);
1708
1709#if GEN_IS_HASWELL
1710   if (cmd_buffer->device->instance->physicalDevice.cmd_parser_version >= 4) {
1711      /* Enable L3 atomics on HSW if we have a DC partition, otherwise keep
1712       * them disabled to avoid crashing the system hard.
1713       */
1714      uint32_t scratch1, chicken3;
1715      anv_pack_struct(&scratch1, GENX(SCRATCH1),
1716                      .L3AtomicDisable = !has_dc);
1717      anv_pack_struct(&chicken3, GENX(CHICKEN3),
1718                      .L3AtomicDisableMask = true,
1719                      .L3AtomicDisable = !has_dc);
1720      emit_lri(&cmd_buffer->batch, GENX(SCRATCH1_num), scratch1);
1721      emit_lri(&cmd_buffer->batch, GENX(CHICKEN3_num), chicken3);
1722   }
1723#endif
1724
1725#endif
1726
1727   cmd_buffer->state.current_l3_config = cfg;
1728}
1729
1730void
1731genX(cmd_buffer_apply_pipe_flushes)(struct anv_cmd_buffer *cmd_buffer)
1732{
1733   enum anv_pipe_bits bits = cmd_buffer->state.pending_pipe_bits;
1734
1735   /* Flushes are pipelined while invalidations are handled immediately.
1736    * Therefore, if we're flushing anything then we need to schedule a stall
1737    * before any invalidations can happen.
1738    */
1739   if (bits & ANV_PIPE_FLUSH_BITS)
1740      bits |= ANV_PIPE_NEEDS_CS_STALL_BIT;
1741
1742   /* If we're going to do an invalidate and we have a pending CS stall that
1743    * has yet to be resolved, we do the CS stall now.
1744    */
1745   if ((bits & ANV_PIPE_INVALIDATE_BITS) &&
1746       (bits & ANV_PIPE_NEEDS_CS_STALL_BIT)) {
1747      bits |= ANV_PIPE_CS_STALL_BIT;
1748      bits &= ~ANV_PIPE_NEEDS_CS_STALL_BIT;
1749   }
1750
1751   if (bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT)) {
1752      anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1753         pipe.DepthCacheFlushEnable = bits & ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
1754         pipe.DCFlushEnable = bits & ANV_PIPE_DATA_CACHE_FLUSH_BIT;
1755         pipe.RenderTargetCacheFlushEnable =
1756            bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
1757
1758         pipe.DepthStallEnable = bits & ANV_PIPE_DEPTH_STALL_BIT;
1759         pipe.CommandStreamerStallEnable = bits & ANV_PIPE_CS_STALL_BIT;
1760         pipe.StallAtPixelScoreboard = bits & ANV_PIPE_STALL_AT_SCOREBOARD_BIT;
1761
1762         /*
1763          * According to the Broadwell documentation, any PIPE_CONTROL with the
1764          * "Command Streamer Stall" bit set must also have another bit set,
1765          * with five different options:
1766          *
1767          *  - Render Target Cache Flush
1768          *  - Depth Cache Flush
1769          *  - Stall at Pixel Scoreboard
1770          *  - Post-Sync Operation
1771          *  - Depth Stall
1772          *  - DC Flush Enable
1773          *
1774          * I chose "Stall at Pixel Scoreboard" since that's what we use in
1775          * mesa and it seems to work fine. The choice is fairly arbitrary.
1776          */
1777         if ((bits & ANV_PIPE_CS_STALL_BIT) &&
1778             !(bits & (ANV_PIPE_FLUSH_BITS | ANV_PIPE_DEPTH_STALL_BIT |
1779                       ANV_PIPE_STALL_AT_SCOREBOARD_BIT)))
1780            pipe.StallAtPixelScoreboard = true;
1781      }
1782
1783      /* If a render target flush was emitted, then we can toggle off the bit
1784       * saying that render target writes are ongoing.
1785       */
1786      if (bits & ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT)
1787         bits &= ~(ANV_PIPE_RENDER_TARGET_BUFFER_WRITES);
1788
1789      bits &= ~(ANV_PIPE_FLUSH_BITS | ANV_PIPE_CS_STALL_BIT);
1790   }
1791
1792   if (bits & ANV_PIPE_INVALIDATE_BITS) {
1793      /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1794       *
1795       *    "If the VF Cache Invalidation Enable is set to a 1 in a
1796       *    PIPE_CONTROL, a separate Null PIPE_CONTROL, all bitfields sets to
1797       *    0, with the VF Cache Invalidation Enable set to 0 needs to be sent
1798       *    prior to the PIPE_CONTROL with VF Cache Invalidation Enable set to
1799       *    a 1."
1800       *
1801       * This appears to hang Broadwell, so we restrict it to just gen9.
1802       */
1803      if (GEN_GEN == 9 && (bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT))
1804         anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe);
1805
1806      anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
1807         pipe.StateCacheInvalidationEnable =
1808            bits & ANV_PIPE_STATE_CACHE_INVALIDATE_BIT;
1809         pipe.ConstantCacheInvalidationEnable =
1810            bits & ANV_PIPE_CONSTANT_CACHE_INVALIDATE_BIT;
1811         pipe.VFCacheInvalidationEnable =
1812            bits & ANV_PIPE_VF_CACHE_INVALIDATE_BIT;
1813         pipe.TextureCacheInvalidationEnable =
1814            bits & ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT;
1815         pipe.InstructionCacheInvalidateEnable =
1816            bits & ANV_PIPE_INSTRUCTION_CACHE_INVALIDATE_BIT;
1817
1818         /* From the SKL PRM, Vol. 2a, "PIPE_CONTROL",
1819          *
1820          *    "When VF Cache Invalidate is set “Post Sync Operation” must be
1821          *    enabled to “Write Immediate Data” or “Write PS Depth Count” or
1822          *    “Write Timestamp”.
1823          */
1824         if (GEN_GEN == 9 && pipe.VFCacheInvalidationEnable) {
1825            pipe.PostSyncOperation = WriteImmediateData;
1826            pipe.Address =
1827               (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
1828         }
1829      }
1830
1831      bits &= ~ANV_PIPE_INVALIDATE_BITS;
1832   }
1833
1834   cmd_buffer->state.pending_pipe_bits = bits;
1835}
1836
1837void genX(CmdPipelineBarrier)(
1838    VkCommandBuffer                             commandBuffer,
1839    VkPipelineStageFlags                        srcStageMask,
1840    VkPipelineStageFlags                        destStageMask,
1841    VkBool32                                    byRegion,
1842    uint32_t                                    memoryBarrierCount,
1843    const VkMemoryBarrier*                      pMemoryBarriers,
1844    uint32_t                                    bufferMemoryBarrierCount,
1845    const VkBufferMemoryBarrier*                pBufferMemoryBarriers,
1846    uint32_t                                    imageMemoryBarrierCount,
1847    const VkImageMemoryBarrier*                 pImageMemoryBarriers)
1848{
1849   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
1850
1851   /* XXX: Right now, we're really dumb and just flush whatever categories
1852    * the app asks for.  One of these days we may make this a bit better
1853    * but right now that's all the hardware allows for in most areas.
1854    */
1855   VkAccessFlags src_flags = 0;
1856   VkAccessFlags dst_flags = 0;
1857
1858   for (uint32_t i = 0; i < memoryBarrierCount; i++) {
1859      src_flags |= pMemoryBarriers[i].srcAccessMask;
1860      dst_flags |= pMemoryBarriers[i].dstAccessMask;
1861   }
1862
1863   for (uint32_t i = 0; i < bufferMemoryBarrierCount; i++) {
1864      src_flags |= pBufferMemoryBarriers[i].srcAccessMask;
1865      dst_flags |= pBufferMemoryBarriers[i].dstAccessMask;
1866   }
1867
1868   for (uint32_t i = 0; i < imageMemoryBarrierCount; i++) {
1869      src_flags |= pImageMemoryBarriers[i].srcAccessMask;
1870      dst_flags |= pImageMemoryBarriers[i].dstAccessMask;
1871      ANV_FROM_HANDLE(anv_image, image, pImageMemoryBarriers[i].image);
1872      const VkImageSubresourceRange *range =
1873         &pImageMemoryBarriers[i].subresourceRange;
1874
1875      if (range->aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1876         transition_depth_buffer(cmd_buffer, image,
1877                                 pImageMemoryBarriers[i].oldLayout,
1878                                 pImageMemoryBarriers[i].newLayout);
1879      } else if (range->aspectMask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
1880         VkImageAspectFlags color_aspects =
1881            anv_image_expand_aspects(image, range->aspectMask);
1882         uint32_t aspect_bit;
1883
1884         uint32_t base_layer, layer_count;
1885         if (image->type == VK_IMAGE_TYPE_3D) {
1886            base_layer = 0;
1887            layer_count = anv_minify(image->extent.depth, range->baseMipLevel);
1888         } else {
1889            base_layer = range->baseArrayLayer;
1890            layer_count = anv_get_layerCount(image, range);
1891         }
1892
1893         anv_foreach_image_aspect_bit(aspect_bit, image, color_aspects) {
1894            transition_color_buffer(cmd_buffer, image, 1UL << aspect_bit,
1895                                    range->baseMipLevel,
1896                                    anv_get_levelCount(image, range),
1897                                    base_layer, layer_count,
1898                                    pImageMemoryBarriers[i].oldLayout,
1899                                    pImageMemoryBarriers[i].newLayout);
1900         }
1901      }
1902   }
1903
1904   cmd_buffer->state.pending_pipe_bits |=
1905      anv_pipe_flush_bits_for_access_flags(src_flags) |
1906      anv_pipe_invalidate_bits_for_access_flags(dst_flags);
1907}
1908
1909static void
1910cmd_buffer_alloc_push_constants(struct anv_cmd_buffer *cmd_buffer)
1911{
1912   VkShaderStageFlags stages =
1913      cmd_buffer->state.gfx.base.pipeline->active_stages;
1914
1915   /* In order to avoid thrash, we assume that vertex and fragment stages
1916    * always exist.  In the rare case where one is missing *and* the other
1917    * uses push concstants, this may be suboptimal.  However, avoiding stalls
1918    * seems more important.
1919    */
1920   stages |= VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT;
1921
1922   if (stages == cmd_buffer->state.push_constant_stages)
1923      return;
1924
1925#if GEN_GEN >= 8
1926   const unsigned push_constant_kb = 32;
1927#elif GEN_IS_HASWELL
1928   const unsigned push_constant_kb = cmd_buffer->device->info.gt == 3 ? 32 : 16;
1929#else
1930   const unsigned push_constant_kb = 16;
1931#endif
1932
1933   const unsigned num_stages =
1934      util_bitcount(stages & VK_SHADER_STAGE_ALL_GRAPHICS);
1935   unsigned size_per_stage = push_constant_kb / num_stages;
1936
1937   /* Broadwell+ and Haswell gt3 require that the push constant sizes be in
1938    * units of 2KB.  Incidentally, these are the same platforms that have
1939    * 32KB worth of push constant space.
1940    */
1941   if (push_constant_kb == 32)
1942      size_per_stage &= ~1u;
1943
1944   uint32_t kb_used = 0;
1945   for (int i = MESA_SHADER_VERTEX; i < MESA_SHADER_FRAGMENT; i++) {
1946      unsigned push_size = (stages & (1 << i)) ? size_per_stage : 0;
1947      anv_batch_emit(&cmd_buffer->batch,
1948                     GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
1949         alloc._3DCommandSubOpcode  = 18 + i;
1950         alloc.ConstantBufferOffset = (push_size > 0) ? kb_used : 0;
1951         alloc.ConstantBufferSize   = push_size;
1952      }
1953      kb_used += push_size;
1954   }
1955
1956   anv_batch_emit(&cmd_buffer->batch,
1957                  GENX(3DSTATE_PUSH_CONSTANT_ALLOC_PS), alloc) {
1958      alloc.ConstantBufferOffset = kb_used;
1959      alloc.ConstantBufferSize = push_constant_kb - kb_used;
1960   }
1961
1962   cmd_buffer->state.push_constant_stages = stages;
1963
1964   /* From the BDW PRM for 3DSTATE_PUSH_CONSTANT_ALLOC_VS:
1965    *
1966    *    "The 3DSTATE_CONSTANT_VS must be reprogrammed prior to
1967    *    the next 3DPRIMITIVE command after programming the
1968    *    3DSTATE_PUSH_CONSTANT_ALLOC_VS"
1969    *
1970    * Since 3DSTATE_PUSH_CONSTANT_ALLOC_VS is programmed as part of
1971    * pipeline setup, we need to dirty push constants.
1972    */
1973   cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_ALL_GRAPHICS;
1974}
1975
1976static const struct anv_descriptor *
1977anv_descriptor_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
1978                           const struct anv_pipeline_binding *binding)
1979{
1980   assert(binding->set < MAX_SETS);
1981   const struct anv_descriptor_set *set =
1982      pipe_state->descriptors[binding->set];
1983   const uint32_t offset =
1984      set->layout->binding[binding->binding].descriptor_index;
1985   return &set->descriptors[offset + binding->index];
1986}
1987
1988static uint32_t
1989dynamic_offset_for_binding(const struct anv_cmd_pipeline_state *pipe_state,
1990                           const struct anv_pipeline_binding *binding)
1991{
1992   assert(binding->set < MAX_SETS);
1993   const struct anv_descriptor_set *set =
1994      pipe_state->descriptors[binding->set];
1995
1996   uint32_t dynamic_offset_idx =
1997      pipe_state->layout->set[binding->set].dynamic_offset_start +
1998      set->layout->binding[binding->binding].dynamic_offset_index +
1999      binding->index;
2000
2001   return pipe_state->dynamic_offsets[dynamic_offset_idx];
2002}
2003
2004static struct anv_address
2005anv_descriptor_set_address(struct anv_cmd_buffer *cmd_buffer,
2006                           struct anv_descriptor_set *set)
2007{
2008   if (set->pool) {
2009      /* This is a normal descriptor set */
2010      return (struct anv_address) {
2011         .bo = &set->pool->bo,
2012         .offset = set->desc_mem.offset,
2013      };
2014   } else {
2015      /* This is a push descriptor set.  We have to flag it as used on the GPU
2016       * so that the next time we push descriptors, we grab a new memory.
2017       */
2018      struct anv_push_descriptor_set *push_set =
2019         (struct anv_push_descriptor_set *)set;
2020      push_set->set_used_on_gpu = true;
2021
2022      return (struct anv_address) {
2023         .bo = cmd_buffer->dynamic_state_stream.state_pool->block_pool.bo,
2024         .offset = set->desc_mem.offset,
2025      };
2026   }
2027}
2028
2029static VkResult
2030emit_binding_table(struct anv_cmd_buffer *cmd_buffer,
2031                   gl_shader_stage stage,
2032                   struct anv_state *bt_state)
2033{
2034   struct anv_subpass *subpass = cmd_buffer->state.subpass;
2035   struct anv_cmd_pipeline_state *pipe_state;
2036   struct anv_pipeline *pipeline;
2037   uint32_t state_offset;
2038
2039   switch (stage) {
2040   case  MESA_SHADER_COMPUTE:
2041      pipe_state = &cmd_buffer->state.compute.base;
2042      break;
2043   default:
2044      pipe_state = &cmd_buffer->state.gfx.base;
2045      break;
2046   }
2047   pipeline = pipe_state->pipeline;
2048
2049   if (!anv_pipeline_has_stage(pipeline, stage)) {
2050      *bt_state = (struct anv_state) { 0, };
2051      return VK_SUCCESS;
2052   }
2053
2054   struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2055   if (map->surface_count == 0) {
2056      *bt_state = (struct anv_state) { 0, };
2057      return VK_SUCCESS;
2058   }
2059
2060   *bt_state = anv_cmd_buffer_alloc_binding_table(cmd_buffer,
2061                                                  map->surface_count,
2062                                                  &state_offset);
2063   uint32_t *bt_map = bt_state->map;
2064
2065   if (bt_state->map == NULL)
2066      return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2067
2068   /* We only need to emit relocs if we're not using softpin.  If we are using
2069    * softpin then we always keep all user-allocated memory objects resident.
2070    */
2071   const bool need_client_mem_relocs =
2072      !cmd_buffer->device->instance->physicalDevice.use_softpin;
2073
2074   for (uint32_t s = 0; s < map->surface_count; s++) {
2075      struct anv_pipeline_binding *binding = &map->surface_to_descriptor[s];
2076
2077      struct anv_state surface_state;
2078
2079      if (binding->set == ANV_DESCRIPTOR_SET_COLOR_ATTACHMENTS) {
2080         /* Color attachment binding */
2081         assert(stage == MESA_SHADER_FRAGMENT);
2082         assert(binding->binding == 0);
2083         if (binding->index < subpass->color_count) {
2084            const unsigned att =
2085               subpass->color_attachments[binding->index].attachment;
2086
2087            /* From the Vulkan 1.0.46 spec:
2088             *
2089             *    "If any color or depth/stencil attachments are
2090             *    VK_ATTACHMENT_UNUSED, then no writes occur for those
2091             *    attachments."
2092             */
2093            if (att == VK_ATTACHMENT_UNUSED) {
2094               surface_state = cmd_buffer->state.null_surface_state;
2095            } else {
2096               surface_state = cmd_buffer->state.attachments[att].color.state;
2097            }
2098         } else {
2099            surface_state = cmd_buffer->state.null_surface_state;
2100         }
2101
2102         bt_map[s] = surface_state.offset + state_offset;
2103         continue;
2104      } else if (binding->set == ANV_DESCRIPTOR_SET_SHADER_CONSTANTS) {
2105         struct anv_state surface_state =
2106            anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2107
2108         struct anv_address constant_data = {
2109            .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2110            .offset = pipeline->shaders[stage]->constant_data.offset,
2111         };
2112         unsigned constant_data_size =
2113            pipeline->shaders[stage]->constant_data_size;
2114
2115         const enum isl_format format =
2116            anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
2117         anv_fill_buffer_surface_state(cmd_buffer->device,
2118                                       surface_state, format,
2119                                       constant_data, constant_data_size, 1);
2120
2121         bt_map[s] = surface_state.offset + state_offset;
2122         add_surface_reloc(cmd_buffer, surface_state, constant_data);
2123         continue;
2124      } else if (binding->set == ANV_DESCRIPTOR_SET_NUM_WORK_GROUPS) {
2125         /* This is always the first binding for compute shaders */
2126         assert(stage == MESA_SHADER_COMPUTE && s == 0);
2127         if (!get_cs_prog_data(pipeline)->uses_num_work_groups)
2128            continue;
2129
2130         struct anv_state surface_state =
2131            anv_cmd_buffer_alloc_surface_state(cmd_buffer);
2132
2133         const enum isl_format format =
2134            anv_isl_format_for_descriptor_type(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
2135         anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2136                                       format,
2137                                       cmd_buffer->state.compute.num_workgroups,
2138                                       12, 1);
2139         bt_map[s] = surface_state.offset + state_offset;
2140         if (need_client_mem_relocs) {
2141            add_surface_reloc(cmd_buffer, surface_state,
2142                              cmd_buffer->state.compute.num_workgroups);
2143         }
2144         continue;
2145      } else if (binding->set == ANV_DESCRIPTOR_SET_DESCRIPTORS) {
2146         /* This is a descriptor set buffer so the set index is actually
2147          * given by binding->binding.  (Yes, that's confusing.)
2148          */
2149         struct anv_descriptor_set *set =
2150            pipe_state->descriptors[binding->binding];
2151         assert(set->desc_mem.alloc_size);
2152         assert(set->desc_surface_state.alloc_size);
2153         bt_map[s] = set->desc_surface_state.offset + state_offset;
2154         add_surface_reloc(cmd_buffer, set->desc_surface_state,
2155                           anv_descriptor_set_address(cmd_buffer, set));
2156         continue;
2157      }
2158
2159      const struct anv_descriptor *desc =
2160         anv_descriptor_for_binding(pipe_state, binding);
2161
2162      switch (desc->type) {
2163      case VK_DESCRIPTOR_TYPE_SAMPLER:
2164         /* Nothing for us to do here */
2165         continue;
2166
2167      case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
2168      case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: {
2169         struct anv_surface_state sstate =
2170            (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2171            desc->image_view->planes[binding->plane].general_sampler_surface_state :
2172            desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2173         surface_state = sstate.state;
2174         assert(surface_state.alloc_size);
2175         if (need_client_mem_relocs)
2176            add_surface_state_relocs(cmd_buffer, sstate);
2177         break;
2178      }
2179      case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
2180         assert(stage == MESA_SHADER_FRAGMENT);
2181         if ((desc->image_view->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) == 0) {
2182            /* For depth and stencil input attachments, we treat it like any
2183             * old texture that a user may have bound.
2184             */
2185            struct anv_surface_state sstate =
2186               (desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
2187               desc->image_view->planes[binding->plane].general_sampler_surface_state :
2188               desc->image_view->planes[binding->plane].optimal_sampler_surface_state;
2189            surface_state = sstate.state;
2190            assert(surface_state.alloc_size);
2191            if (need_client_mem_relocs)
2192               add_surface_state_relocs(cmd_buffer, sstate);
2193         } else {
2194            /* For color input attachments, we create the surface state at
2195             * vkBeginRenderPass time so that we can include aux and clear
2196             * color information.
2197             */
2198            assert(binding->input_attachment_index < subpass->input_count);
2199            const unsigned subpass_att = binding->input_attachment_index;
2200            const unsigned att = subpass->input_attachments[subpass_att].attachment;
2201            surface_state = cmd_buffer->state.attachments[att].input.state;
2202         }
2203         break;
2204
2205      case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
2206         struct anv_surface_state sstate = (binding->write_only)
2207            ? desc->image_view->planes[binding->plane].writeonly_storage_surface_state
2208            : desc->image_view->planes[binding->plane].storage_surface_state;
2209         surface_state = sstate.state;
2210         assert(surface_state.alloc_size);
2211         if (need_client_mem_relocs)
2212            add_surface_state_relocs(cmd_buffer, sstate);
2213         break;
2214      }
2215
2216      case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
2217      case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
2218      case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
2219         surface_state = desc->buffer_view->surface_state;
2220         assert(surface_state.alloc_size);
2221         if (need_client_mem_relocs) {
2222            add_surface_reloc(cmd_buffer, surface_state,
2223                              desc->buffer_view->address);
2224         }
2225         break;
2226
2227      case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
2228      case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
2229         /* Compute the offset within the buffer */
2230         uint32_t dynamic_offset =
2231            dynamic_offset_for_binding(pipe_state, binding);
2232         uint64_t offset = desc->offset + dynamic_offset;
2233         /* Clamp to the buffer size */
2234         offset = MIN2(offset, desc->buffer->size);
2235         /* Clamp the range to the buffer size */
2236         uint32_t range = MIN2(desc->range, desc->buffer->size - offset);
2237
2238         struct anv_address address =
2239            anv_address_add(desc->buffer->address, offset);
2240
2241         surface_state =
2242            anv_state_stream_alloc(&cmd_buffer->surface_state_stream, 64, 64);
2243         enum isl_format format =
2244            anv_isl_format_for_descriptor_type(desc->type);
2245
2246         anv_fill_buffer_surface_state(cmd_buffer->device, surface_state,
2247                                       format, address, range, 1);
2248         if (need_client_mem_relocs)
2249            add_surface_reloc(cmd_buffer, surface_state, address);
2250         break;
2251      }
2252
2253      case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
2254         surface_state = (binding->write_only)
2255            ? desc->buffer_view->writeonly_storage_surface_state
2256            : desc->buffer_view->storage_surface_state;
2257         assert(surface_state.alloc_size);
2258         if (need_client_mem_relocs) {
2259            add_surface_reloc(cmd_buffer, surface_state,
2260                              desc->buffer_view->address);
2261         }
2262         break;
2263
2264      default:
2265         assert(!"Invalid descriptor type");
2266         continue;
2267      }
2268
2269      bt_map[s] = surface_state.offset + state_offset;
2270   }
2271
2272#if GEN_GEN >= 11
2273   /* The PIPE_CONTROL command description says:
2274    *
2275    *    "Whenever a Binding Table Index (BTI) used by a Render Taget Message
2276    *     points to a different RENDER_SURFACE_STATE, SW must issue a Render
2277    *     Target Cache Flush by enabling this bit. When render target flush
2278    *     is set due to new association of BTI, PS Scoreboard Stall bit must
2279    *     be set in this packet."
2280    *
2281    * FINISHME: Currently we shuffle around the surface states in the binding
2282    * table based on if they are getting used or not. So, we've to do below
2283    * pipe control flush for every binding table upload. Make changes so
2284    * that we do it only when we modify render target surface states.
2285    */
2286   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2287      pc.RenderTargetCacheFlushEnable  = true;
2288      pc.StallAtPixelScoreboard        = true;
2289   }
2290#endif
2291
2292   return VK_SUCCESS;
2293}
2294
2295static VkResult
2296emit_samplers(struct anv_cmd_buffer *cmd_buffer,
2297              gl_shader_stage stage,
2298              struct anv_state *state)
2299{
2300   struct anv_cmd_pipeline_state *pipe_state =
2301      stage == MESA_SHADER_COMPUTE ? &cmd_buffer->state.compute.base :
2302                                     &cmd_buffer->state.gfx.base;
2303   struct anv_pipeline *pipeline = pipe_state->pipeline;
2304
2305   if (!anv_pipeline_has_stage(pipeline, stage)) {
2306      *state = (struct anv_state) { 0, };
2307      return VK_SUCCESS;
2308   }
2309
2310   struct anv_pipeline_bind_map *map = &pipeline->shaders[stage]->bind_map;
2311   if (map->sampler_count == 0) {
2312      *state = (struct anv_state) { 0, };
2313      return VK_SUCCESS;
2314   }
2315
2316   uint32_t size = map->sampler_count * 16;
2317   *state = anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, size, 32);
2318
2319   if (state->map == NULL)
2320      return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2321
2322   for (uint32_t s = 0; s < map->sampler_count; s++) {
2323      struct anv_pipeline_binding *binding = &map->sampler_to_descriptor[s];
2324      const struct anv_descriptor *desc =
2325         anv_descriptor_for_binding(pipe_state, binding);
2326
2327      if (desc->type != VK_DESCRIPTOR_TYPE_SAMPLER &&
2328          desc->type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
2329         continue;
2330
2331      struct anv_sampler *sampler = desc->sampler;
2332
2333      /* This can happen if we have an unfilled slot since TYPE_SAMPLER
2334       * happens to be zero.
2335       */
2336      if (sampler == NULL)
2337         continue;
2338
2339      memcpy(state->map + (s * 16),
2340             sampler->state[binding->plane], sizeof(sampler->state[0]));
2341   }
2342
2343   return VK_SUCCESS;
2344}
2345
2346static uint32_t
2347flush_descriptor_sets(struct anv_cmd_buffer *cmd_buffer)
2348{
2349   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2350
2351   VkShaderStageFlags dirty = cmd_buffer->state.descriptors_dirty &
2352                              pipeline->active_stages;
2353
2354   VkResult result = VK_SUCCESS;
2355   anv_foreach_stage(s, dirty) {
2356      result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2357      if (result != VK_SUCCESS)
2358         break;
2359      result = emit_binding_table(cmd_buffer, s,
2360                                  &cmd_buffer->state.binding_tables[s]);
2361      if (result != VK_SUCCESS)
2362         break;
2363   }
2364
2365   if (result != VK_SUCCESS) {
2366      assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
2367
2368      result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
2369      if (result != VK_SUCCESS)
2370         return 0;
2371
2372      /* Re-emit state base addresses so we get the new surface state base
2373       * address before we start emitting binding tables etc.
2374       */
2375      genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
2376
2377      /* Re-emit all active binding tables */
2378      dirty |= pipeline->active_stages;
2379      anv_foreach_stage(s, dirty) {
2380         result = emit_samplers(cmd_buffer, s, &cmd_buffer->state.samplers[s]);
2381         if (result != VK_SUCCESS) {
2382            anv_batch_set_error(&cmd_buffer->batch, result);
2383            return 0;
2384         }
2385         result = emit_binding_table(cmd_buffer, s,
2386                                     &cmd_buffer->state.binding_tables[s]);
2387         if (result != VK_SUCCESS) {
2388            anv_batch_set_error(&cmd_buffer->batch, result);
2389            return 0;
2390         }
2391      }
2392   }
2393
2394   cmd_buffer->state.descriptors_dirty &= ~dirty;
2395
2396   return dirty;
2397}
2398
2399static void
2400cmd_buffer_emit_descriptor_pointers(struct anv_cmd_buffer *cmd_buffer,
2401                                    uint32_t stages)
2402{
2403   static const uint32_t sampler_state_opcodes[] = {
2404      [MESA_SHADER_VERTEX]                      = 43,
2405      [MESA_SHADER_TESS_CTRL]                   = 44, /* HS */
2406      [MESA_SHADER_TESS_EVAL]                   = 45, /* DS */
2407      [MESA_SHADER_GEOMETRY]                    = 46,
2408      [MESA_SHADER_FRAGMENT]                    = 47,
2409      [MESA_SHADER_COMPUTE]                     = 0,
2410   };
2411
2412   static const uint32_t binding_table_opcodes[] = {
2413      [MESA_SHADER_VERTEX]                      = 38,
2414      [MESA_SHADER_TESS_CTRL]                   = 39,
2415      [MESA_SHADER_TESS_EVAL]                   = 40,
2416      [MESA_SHADER_GEOMETRY]                    = 41,
2417      [MESA_SHADER_FRAGMENT]                    = 42,
2418      [MESA_SHADER_COMPUTE]                     = 0,
2419   };
2420
2421   anv_foreach_stage(s, stages) {
2422      assert(s < ARRAY_SIZE(binding_table_opcodes));
2423      assert(binding_table_opcodes[s] > 0);
2424
2425      if (cmd_buffer->state.samplers[s].alloc_size > 0) {
2426         anv_batch_emit(&cmd_buffer->batch,
2427                        GENX(3DSTATE_SAMPLER_STATE_POINTERS_VS), ssp) {
2428            ssp._3DCommandSubOpcode = sampler_state_opcodes[s];
2429            ssp.PointertoVSSamplerState = cmd_buffer->state.samplers[s].offset;
2430         }
2431      }
2432
2433      /* Always emit binding table pointers if we're asked to, since on SKL
2434       * this is what flushes push constants. */
2435      anv_batch_emit(&cmd_buffer->batch,
2436                     GENX(3DSTATE_BINDING_TABLE_POINTERS_VS), btp) {
2437         btp._3DCommandSubOpcode = binding_table_opcodes[s];
2438         btp.PointertoVSBindingTable = cmd_buffer->state.binding_tables[s].offset;
2439      }
2440   }
2441}
2442
2443static void
2444cmd_buffer_flush_push_constants(struct anv_cmd_buffer *cmd_buffer,
2445                                VkShaderStageFlags dirty_stages)
2446{
2447   const struct anv_cmd_graphics_state *gfx_state = &cmd_buffer->state.gfx;
2448   const struct anv_pipeline *pipeline = gfx_state->base.pipeline;
2449
2450   static const uint32_t push_constant_opcodes[] = {
2451      [MESA_SHADER_VERTEX]                      = 21,
2452      [MESA_SHADER_TESS_CTRL]                   = 25, /* HS */
2453      [MESA_SHADER_TESS_EVAL]                   = 26, /* DS */
2454      [MESA_SHADER_GEOMETRY]                    = 22,
2455      [MESA_SHADER_FRAGMENT]                    = 23,
2456      [MESA_SHADER_COMPUTE]                     = 0,
2457   };
2458
2459   VkShaderStageFlags flushed = 0;
2460
2461   anv_foreach_stage(stage, dirty_stages) {
2462      assert(stage < ARRAY_SIZE(push_constant_opcodes));
2463      assert(push_constant_opcodes[stage] > 0);
2464
2465      anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CONSTANT_VS), c) {
2466         c._3DCommandSubOpcode = push_constant_opcodes[stage];
2467
2468         if (anv_pipeline_has_stage(pipeline, stage)) {
2469#if GEN_GEN >= 8 || GEN_IS_HASWELL
2470            const struct brw_stage_prog_data *prog_data =
2471               pipeline->shaders[stage]->prog_data;
2472            const struct anv_pipeline_bind_map *bind_map =
2473               &pipeline->shaders[stage]->bind_map;
2474
2475            /* The Skylake PRM contains the following restriction:
2476             *
2477             *    "The driver must ensure The following case does not occur
2478             *     without a flush to the 3D engine: 3DSTATE_CONSTANT_* with
2479             *     buffer 3 read length equal to zero committed followed by a
2480             *     3DSTATE_CONSTANT_* with buffer 0 read length not equal to
2481             *     zero committed."
2482             *
2483             * To avoid this, we program the buffers in the highest slots.
2484             * This way, slot 0 is only used if slot 3 is also used.
2485             */
2486            int n = 3;
2487
2488            for (int i = 3; i >= 0; i--) {
2489               const struct brw_ubo_range *range = &prog_data->ubo_ranges[i];
2490               if (range->length == 0)
2491                  continue;
2492
2493               const unsigned surface =
2494                  prog_data->binding_table.ubo_start + range->block;
2495
2496               assert(surface <= bind_map->surface_count);
2497               const struct anv_pipeline_binding *binding =
2498                  &bind_map->surface_to_descriptor[surface];
2499
2500               struct anv_address read_addr;
2501               uint32_t read_len;
2502               if (binding->set == ANV_DESCRIPTOR_SET_SHADER_CONSTANTS) {
2503                  struct anv_address constant_data = {
2504                     .bo = pipeline->device->dynamic_state_pool.block_pool.bo,
2505                     .offset = pipeline->shaders[stage]->constant_data.offset,
2506                  };
2507                  unsigned constant_data_size =
2508                     pipeline->shaders[stage]->constant_data_size;
2509
2510                  read_len = MIN2(range->length,
2511                     DIV_ROUND_UP(constant_data_size, 32) - range->start);
2512                  read_addr = anv_address_add(constant_data,
2513                                              range->start * 32);
2514               } else if (binding->set == ANV_DESCRIPTOR_SET_DESCRIPTORS) {
2515                  /* This is a descriptor set buffer so the set index is
2516                   * actually given by binding->binding.  (Yes, that's
2517                   * confusing.)
2518                   */
2519                  struct anv_descriptor_set *set =
2520                     gfx_state->base.descriptors[binding->binding];
2521                  struct anv_address desc_buffer_addr =
2522                     anv_descriptor_set_address(cmd_buffer, set);
2523                  const unsigned desc_buffer_size = set->desc_mem.alloc_size;
2524
2525                  read_len = MIN2(range->length,
2526                     DIV_ROUND_UP(desc_buffer_size, 32) - range->start);
2527                  read_addr = anv_address_add(desc_buffer_addr,
2528                                              range->start * 32);
2529               } else {
2530                  const struct anv_descriptor *desc =
2531                     anv_descriptor_for_binding(&gfx_state->base, binding);
2532
2533                  if (desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) {
2534                     read_len = MIN2(range->length,
2535                        DIV_ROUND_UP(desc->buffer_view->range, 32) - range->start);
2536                     read_addr = anv_address_add(desc->buffer_view->address,
2537                                                 range->start * 32);
2538                  } else {
2539                     assert(desc->type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
2540
2541                     uint32_t dynamic_offset =
2542                        dynamic_offset_for_binding(&gfx_state->base, binding);
2543                     uint32_t buf_offset =
2544                        MIN2(desc->offset + dynamic_offset, desc->buffer->size);
2545                     uint32_t buf_range =
2546                        MIN2(desc->range, desc->buffer->size - buf_offset);
2547
2548                     read_len = MIN2(range->length,
2549                        DIV_ROUND_UP(buf_range, 32) - range->start);
2550                     read_addr = anv_address_add(desc->buffer->address,
2551                                                 buf_offset + range->start * 32);
2552                  }
2553               }
2554
2555               if (read_len > 0) {
2556                  c.ConstantBody.Buffer[n] = read_addr;
2557                  c.ConstantBody.ReadLength[n] = read_len;
2558                  n--;
2559               }
2560            }
2561
2562            struct anv_state state =
2563               anv_cmd_buffer_push_constants(cmd_buffer, stage);
2564
2565            if (state.alloc_size > 0) {
2566               c.ConstantBody.Buffer[n] = (struct anv_address) {
2567                  .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2568                  .offset = state.offset,
2569               };
2570               c.ConstantBody.ReadLength[n] =
2571                  DIV_ROUND_UP(state.alloc_size, 32);
2572            }
2573#else
2574            /* For Ivy Bridge, the push constants packets have a different
2575             * rule that would require us to iterate in the other direction
2576             * and possibly mess around with dynamic state base address.
2577             * Don't bother; just emit regular push constants at n = 0.
2578             */
2579            struct anv_state state =
2580               anv_cmd_buffer_push_constants(cmd_buffer, stage);
2581
2582            if (state.alloc_size > 0) {
2583               c.ConstantBody.Buffer[0].offset = state.offset,
2584               c.ConstantBody.ReadLength[0] =
2585                  DIV_ROUND_UP(state.alloc_size, 32);
2586            }
2587#endif
2588         }
2589      }
2590
2591      flushed |= mesa_to_vk_shader_stage(stage);
2592   }
2593
2594   cmd_buffer->state.push_constants_dirty &= ~flushed;
2595}
2596
2597void
2598genX(cmd_buffer_flush_state)(struct anv_cmd_buffer *cmd_buffer)
2599{
2600   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2601   uint32_t *p;
2602
2603   uint32_t vb_emit = cmd_buffer->state.gfx.vb_dirty & pipeline->vb_used;
2604   if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE)
2605      vb_emit |= pipeline->vb_used;
2606
2607   assert((pipeline->active_stages & VK_SHADER_STAGE_COMPUTE_BIT) == 0);
2608
2609   genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
2610
2611   genX(flush_pipeline_select_3d)(cmd_buffer);
2612
2613   if (vb_emit) {
2614      const uint32_t num_buffers = __builtin_popcount(vb_emit);
2615      const uint32_t num_dwords = 1 + num_buffers * 4;
2616
2617      p = anv_batch_emitn(&cmd_buffer->batch, num_dwords,
2618                          GENX(3DSTATE_VERTEX_BUFFERS));
2619      uint32_t vb, i = 0;
2620      for_each_bit(vb, vb_emit) {
2621         struct anv_buffer *buffer = cmd_buffer->state.vertex_bindings[vb].buffer;
2622         uint32_t offset = cmd_buffer->state.vertex_bindings[vb].offset;
2623
2624         struct GENX(VERTEX_BUFFER_STATE) state = {
2625            .VertexBufferIndex = vb,
2626
2627            .MOCS = anv_mocs_for_bo(cmd_buffer->device, buffer->address.bo),
2628#if GEN_GEN <= 7
2629            .BufferAccessType = pipeline->vb[vb].instanced ? INSTANCEDATA : VERTEXDATA,
2630            .InstanceDataStepRate = pipeline->vb[vb].instance_divisor,
2631#endif
2632
2633            .AddressModifyEnable = true,
2634            .BufferPitch = pipeline->vb[vb].stride,
2635            .BufferStartingAddress = anv_address_add(buffer->address, offset),
2636
2637#if GEN_GEN >= 8
2638            .BufferSize = buffer->size - offset
2639#else
2640            .EndAddress = anv_address_add(buffer->address, buffer->size - 1),
2641#endif
2642         };
2643
2644         GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, &p[1 + i * 4], &state);
2645         i++;
2646      }
2647   }
2648
2649   cmd_buffer->state.gfx.vb_dirty &= ~vb_emit;
2650
2651#if GEN_GEN >= 8
2652   if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_XFB_ENABLE) {
2653      /* We don't need any per-buffer dirty tracking because you're not
2654       * allowed to bind different XFB buffers while XFB is enabled.
2655       */
2656      for (unsigned idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
2657         struct anv_xfb_binding *xfb = &cmd_buffer->state.xfb_bindings[idx];
2658         anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_SO_BUFFER), sob) {
2659            sob.SOBufferIndex = idx;
2660
2661            if (cmd_buffer->state.xfb_enabled && xfb->buffer && xfb->size != 0) {
2662               sob.SOBufferEnable = true;
2663               sob.MOCS = cmd_buffer->device->default_mocs,
2664               sob.StreamOffsetWriteEnable = false;
2665               sob.SurfaceBaseAddress = anv_address_add(xfb->buffer->address,
2666                                                        xfb->offset);
2667               /* Size is in DWords - 1 */
2668               sob.SurfaceSize = xfb->size / 4 - 1;
2669            }
2670         }
2671      }
2672
2673      /* CNL and later require a CS stall after 3DSTATE_SO_BUFFER */
2674      if (GEN_GEN >= 10)
2675         cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
2676   }
2677#endif
2678
2679   if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_PIPELINE) {
2680      anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
2681
2682      /* The exact descriptor layout is pulled from the pipeline, so we need
2683       * to re-emit binding tables on every pipeline change.
2684       */
2685      cmd_buffer->state.descriptors_dirty |= pipeline->active_stages;
2686
2687      /* If the pipeline changed, we may need to re-allocate push constant
2688       * space in the URB.
2689       */
2690      cmd_buffer_alloc_push_constants(cmd_buffer);
2691   }
2692
2693#if GEN_GEN <= 7
2694   if (cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_VERTEX_BIT ||
2695       cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_VERTEX_BIT) {
2696      /* From the IVB PRM Vol. 2, Part 1, Section 3.2.1:
2697       *
2698       *    "A PIPE_CONTROL with Post-Sync Operation set to 1h and a depth
2699       *    stall needs to be sent just prior to any 3DSTATE_VS,
2700       *    3DSTATE_URB_VS, 3DSTATE_CONSTANT_VS,
2701       *    3DSTATE_BINDING_TABLE_POINTER_VS,
2702       *    3DSTATE_SAMPLER_STATE_POINTER_VS command.  Only one
2703       *    PIPE_CONTROL needs to be sent before any combination of VS
2704       *    associated 3DSTATE."
2705       */
2706      anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
2707         pc.DepthStallEnable  = true;
2708         pc.PostSyncOperation = WriteImmediateData;
2709         pc.Address           =
2710            (struct anv_address) { &cmd_buffer->device->workaround_bo, 0 };
2711      }
2712   }
2713#endif
2714
2715   /* Render targets live in the same binding table as fragment descriptors */
2716   if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_RENDER_TARGETS)
2717      cmd_buffer->state.descriptors_dirty |= VK_SHADER_STAGE_FRAGMENT_BIT;
2718
2719   /* We emit the binding tables and sampler tables first, then emit push
2720    * constants and then finally emit binding table and sampler table
2721    * pointers.  It has to happen in this order, since emitting the binding
2722    * tables may change the push constants (in case of storage images). After
2723    * emitting push constants, on SKL+ we have to emit the corresponding
2724    * 3DSTATE_BINDING_TABLE_POINTER_* for the push constants to take effect.
2725    */
2726   uint32_t dirty = 0;
2727   if (cmd_buffer->state.descriptors_dirty)
2728      dirty = flush_descriptor_sets(cmd_buffer);
2729
2730   if (dirty || cmd_buffer->state.push_constants_dirty) {
2731      /* Because we're pushing UBOs, we have to push whenever either
2732       * descriptors or push constants is dirty.
2733       */
2734      dirty |= cmd_buffer->state.push_constants_dirty;
2735      dirty &= ANV_STAGE_MASK & VK_SHADER_STAGE_ALL_GRAPHICS;
2736      cmd_buffer_flush_push_constants(cmd_buffer, dirty);
2737   }
2738
2739   if (dirty)
2740      cmd_buffer_emit_descriptor_pointers(cmd_buffer, dirty);
2741
2742   if (cmd_buffer->state.gfx.dirty & ANV_CMD_DIRTY_DYNAMIC_VIEWPORT)
2743      gen8_cmd_buffer_emit_viewport(cmd_buffer);
2744
2745   if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_VIEWPORT |
2746                                  ANV_CMD_DIRTY_PIPELINE)) {
2747      gen8_cmd_buffer_emit_depth_viewport(cmd_buffer,
2748                                          pipeline->depth_clamp_enable);
2749   }
2750
2751   if (cmd_buffer->state.gfx.dirty & (ANV_CMD_DIRTY_DYNAMIC_SCISSOR |
2752                                      ANV_CMD_DIRTY_RENDER_TARGETS))
2753      gen7_cmd_buffer_emit_scissor(cmd_buffer);
2754
2755   genX(cmd_buffer_flush_dynamic_state)(cmd_buffer);
2756
2757   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
2758}
2759
2760static void
2761emit_vertex_bo(struct anv_cmd_buffer *cmd_buffer,
2762               struct anv_address addr,
2763               uint32_t size, uint32_t index)
2764{
2765   uint32_t *p = anv_batch_emitn(&cmd_buffer->batch, 5,
2766                                 GENX(3DSTATE_VERTEX_BUFFERS));
2767
2768   GENX(VERTEX_BUFFER_STATE_pack)(&cmd_buffer->batch, p + 1,
2769      &(struct GENX(VERTEX_BUFFER_STATE)) {
2770         .VertexBufferIndex = index,
2771         .AddressModifyEnable = true,
2772         .BufferPitch = 0,
2773         .MOCS = anv_mocs_for_bo(cmd_buffer->device, addr.bo),
2774#if (GEN_GEN >= 8)
2775         .BufferStartingAddress = addr,
2776         .BufferSize = size
2777#else
2778         .BufferStartingAddress = addr,
2779         .EndAddress = anv_address_add(addr, size),
2780#endif
2781      });
2782}
2783
2784static void
2785emit_base_vertex_instance_bo(struct anv_cmd_buffer *cmd_buffer,
2786                             struct anv_address addr)
2787{
2788   emit_vertex_bo(cmd_buffer, addr, 8, ANV_SVGS_VB_INDEX);
2789}
2790
2791static void
2792emit_base_vertex_instance(struct anv_cmd_buffer *cmd_buffer,
2793                          uint32_t base_vertex, uint32_t base_instance)
2794{
2795   struct anv_state id_state =
2796      anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 8, 4);
2797
2798   ((uint32_t *)id_state.map)[0] = base_vertex;
2799   ((uint32_t *)id_state.map)[1] = base_instance;
2800
2801   struct anv_address addr = {
2802      .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2803      .offset = id_state.offset,
2804   };
2805
2806   emit_base_vertex_instance_bo(cmd_buffer, addr);
2807}
2808
2809static void
2810emit_draw_index(struct anv_cmd_buffer *cmd_buffer, uint32_t draw_index)
2811{
2812   struct anv_state state =
2813      anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 4, 4);
2814
2815   ((uint32_t *)state.map)[0] = draw_index;
2816
2817   struct anv_address addr = {
2818      .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
2819      .offset = state.offset,
2820   };
2821
2822   emit_vertex_bo(cmd_buffer, addr, 4, ANV_DRAWID_VB_INDEX);
2823}
2824
2825void genX(CmdDraw)(
2826    VkCommandBuffer                             commandBuffer,
2827    uint32_t                                    vertexCount,
2828    uint32_t                                    instanceCount,
2829    uint32_t                                    firstVertex,
2830    uint32_t                                    firstInstance)
2831{
2832   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2833   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2834   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2835
2836   if (anv_batch_has_error(&cmd_buffer->batch))
2837      return;
2838
2839   genX(cmd_buffer_flush_state)(cmd_buffer);
2840
2841   if (cmd_buffer->state.conditional_render_enabled)
2842      genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
2843
2844   if (vs_prog_data->uses_firstvertex ||
2845       vs_prog_data->uses_baseinstance)
2846      emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
2847   if (vs_prog_data->uses_drawid)
2848      emit_draw_index(cmd_buffer, 0);
2849
2850   /* Our implementation of VK_KHR_multiview uses instancing to draw the
2851    * different views.  We need to multiply instanceCount by the view count.
2852    */
2853   instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2854
2855   anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2856      prim.PredicateEnable          = cmd_buffer->state.conditional_render_enabled;
2857      prim.VertexAccessType         = SEQUENTIAL;
2858      prim.PrimitiveTopologyType    = pipeline->topology;
2859      prim.VertexCountPerInstance   = vertexCount;
2860      prim.StartVertexLocation      = firstVertex;
2861      prim.InstanceCount            = instanceCount;
2862      prim.StartInstanceLocation    = firstInstance;
2863      prim.BaseVertexLocation       = 0;
2864   }
2865}
2866
2867void genX(CmdDrawIndexed)(
2868    VkCommandBuffer                             commandBuffer,
2869    uint32_t                                    indexCount,
2870    uint32_t                                    instanceCount,
2871    uint32_t                                    firstIndex,
2872    int32_t                                     vertexOffset,
2873    uint32_t                                    firstInstance)
2874{
2875   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2876   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2877   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2878
2879   if (anv_batch_has_error(&cmd_buffer->batch))
2880      return;
2881
2882   genX(cmd_buffer_flush_state)(cmd_buffer);
2883
2884   if (cmd_buffer->state.conditional_render_enabled)
2885      genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
2886
2887   if (vs_prog_data->uses_firstvertex ||
2888       vs_prog_data->uses_baseinstance)
2889      emit_base_vertex_instance(cmd_buffer, vertexOffset, firstInstance);
2890   if (vs_prog_data->uses_drawid)
2891      emit_draw_index(cmd_buffer, 0);
2892
2893   /* Our implementation of VK_KHR_multiview uses instancing to draw the
2894    * different views.  We need to multiply instanceCount by the view count.
2895    */
2896   instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2897
2898   anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2899      prim.PredicateEnable          = cmd_buffer->state.conditional_render_enabled;
2900      prim.VertexAccessType         = RANDOM;
2901      prim.PrimitiveTopologyType    = pipeline->topology;
2902      prim.VertexCountPerInstance   = indexCount;
2903      prim.StartVertexLocation      = firstIndex;
2904      prim.InstanceCount            = instanceCount;
2905      prim.StartInstanceLocation    = firstInstance;
2906      prim.BaseVertexLocation       = vertexOffset;
2907   }
2908}
2909
2910/* Auto-Draw / Indirect Registers */
2911#define GEN7_3DPRIM_END_OFFSET          0x2420
2912#define GEN7_3DPRIM_START_VERTEX        0x2430
2913#define GEN7_3DPRIM_VERTEX_COUNT        0x2434
2914#define GEN7_3DPRIM_INSTANCE_COUNT      0x2438
2915#define GEN7_3DPRIM_START_INSTANCE      0x243C
2916#define GEN7_3DPRIM_BASE_VERTEX         0x2440
2917
2918void genX(CmdDrawIndirectByteCountEXT)(
2919    VkCommandBuffer                             commandBuffer,
2920    uint32_t                                    instanceCount,
2921    uint32_t                                    firstInstance,
2922    VkBuffer                                    counterBuffer,
2923    VkDeviceSize                                counterBufferOffset,
2924    uint32_t                                    counterOffset,
2925    uint32_t                                    vertexStride)
2926{
2927#if GEN_IS_HASWELL || GEN_GEN >= 8
2928   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
2929   ANV_FROM_HANDLE(anv_buffer, counter_buffer, counterBuffer);
2930   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
2931   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
2932
2933   /* firstVertex is always zero for this draw function */
2934   const uint32_t firstVertex = 0;
2935
2936   if (anv_batch_has_error(&cmd_buffer->batch))
2937      return;
2938
2939   genX(cmd_buffer_flush_state)(cmd_buffer);
2940
2941   if (vs_prog_data->uses_firstvertex ||
2942       vs_prog_data->uses_baseinstance)
2943      emit_base_vertex_instance(cmd_buffer, firstVertex, firstInstance);
2944   if (vs_prog_data->uses_drawid)
2945      emit_draw_index(cmd_buffer, 0);
2946
2947   /* Our implementation of VK_KHR_multiview uses instancing to draw the
2948    * different views.  We need to multiply instanceCount by the view count.
2949    */
2950   instanceCount *= anv_subpass_view_count(cmd_buffer->state.subpass);
2951
2952   struct gen_mi_builder b;
2953   gen_mi_builder_init(&b, &cmd_buffer->batch);
2954   struct gen_mi_value count =
2955      gen_mi_mem32(anv_address_add(counter_buffer->address,
2956                                   counterBufferOffset));
2957   if (counterOffset)
2958      count = gen_mi_isub(&b, count, gen_mi_imm(counterOffset));
2959   count = gen_mi_udiv32_imm(&b, count, vertexStride);
2960   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT), count);
2961
2962   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
2963                    gen_mi_imm(firstVertex));
2964   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT),
2965                    gen_mi_imm(instanceCount));
2966   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
2967                    gen_mi_imm(firstInstance));
2968   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
2969
2970   anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
2971      prim.IndirectParameterEnable  = true;
2972      prim.VertexAccessType         = SEQUENTIAL;
2973      prim.PrimitiveTopologyType    = pipeline->topology;
2974   }
2975#endif /* GEN_IS_HASWELL || GEN_GEN >= 8 */
2976}
2977
2978static void
2979load_indirect_parameters(struct anv_cmd_buffer *cmd_buffer,
2980                         struct anv_address addr,
2981                         bool indexed)
2982{
2983   struct gen_mi_builder b;
2984   gen_mi_builder_init(&b, &cmd_buffer->batch);
2985
2986   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_VERTEX_COUNT),
2987                    gen_mi_mem32(anv_address_add(addr, 0)));
2988
2989   struct gen_mi_value instance_count = gen_mi_mem32(anv_address_add(addr, 4));
2990   unsigned view_count = anv_subpass_view_count(cmd_buffer->state.subpass);
2991   if (view_count > 1) {
2992#if GEN_IS_HASWELL || GEN_GEN >= 8
2993      instance_count = gen_mi_imul_imm(&b, instance_count, view_count);
2994#else
2995      anv_finishme("Multiview + indirect draw requires MI_MATH; "
2996                   "MI_MATH is not supported on Ivy Bridge");
2997#endif
2998   }
2999   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_INSTANCE_COUNT), instance_count);
3000
3001   gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_VERTEX),
3002                    gen_mi_mem32(anv_address_add(addr, 8)));
3003
3004   if (indexed) {
3005      gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX),
3006                       gen_mi_mem32(anv_address_add(addr, 12)));
3007      gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3008                       gen_mi_mem32(anv_address_add(addr, 16)));
3009   } else {
3010      gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_START_INSTANCE),
3011                       gen_mi_mem32(anv_address_add(addr, 12)));
3012      gen_mi_store(&b, gen_mi_reg32(GEN7_3DPRIM_BASE_VERTEX), gen_mi_imm(0));
3013   }
3014}
3015
3016void genX(CmdDrawIndirect)(
3017    VkCommandBuffer                             commandBuffer,
3018    VkBuffer                                    _buffer,
3019    VkDeviceSize                                offset,
3020    uint32_t                                    drawCount,
3021    uint32_t                                    stride)
3022{
3023   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3024   ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3025   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3026   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3027
3028   if (anv_batch_has_error(&cmd_buffer->batch))
3029      return;
3030
3031   genX(cmd_buffer_flush_state)(cmd_buffer);
3032
3033   if (cmd_buffer->state.conditional_render_enabled)
3034      genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3035
3036   for (uint32_t i = 0; i < drawCount; i++) {
3037      struct anv_address draw = anv_address_add(buffer->address, offset);
3038
3039      if (vs_prog_data->uses_firstvertex ||
3040          vs_prog_data->uses_baseinstance)
3041         emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3042      if (vs_prog_data->uses_drawid)
3043         emit_draw_index(cmd_buffer, i);
3044
3045      load_indirect_parameters(cmd_buffer, draw, false);
3046
3047      anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3048         prim.IndirectParameterEnable  = true;
3049         prim.PredicateEnable          = cmd_buffer->state.conditional_render_enabled;
3050         prim.VertexAccessType         = SEQUENTIAL;
3051         prim.PrimitiveTopologyType    = pipeline->topology;
3052      }
3053
3054      offset += stride;
3055   }
3056}
3057
3058void genX(CmdDrawIndexedIndirect)(
3059    VkCommandBuffer                             commandBuffer,
3060    VkBuffer                                    _buffer,
3061    VkDeviceSize                                offset,
3062    uint32_t                                    drawCount,
3063    uint32_t                                    stride)
3064{
3065   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3066   ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3067   struct anv_pipeline *pipeline = cmd_buffer->state.gfx.base.pipeline;
3068   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3069
3070   if (anv_batch_has_error(&cmd_buffer->batch))
3071      return;
3072
3073   genX(cmd_buffer_flush_state)(cmd_buffer);
3074
3075   if (cmd_buffer->state.conditional_render_enabled)
3076      genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3077
3078   for (uint32_t i = 0; i < drawCount; i++) {
3079      struct anv_address draw = anv_address_add(buffer->address, offset);
3080
3081      /* TODO: We need to stomp base vertex to 0 somehow */
3082      if (vs_prog_data->uses_firstvertex ||
3083          vs_prog_data->uses_baseinstance)
3084         emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
3085      if (vs_prog_data->uses_drawid)
3086         emit_draw_index(cmd_buffer, i);
3087
3088      load_indirect_parameters(cmd_buffer, draw, true);
3089
3090      anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3091         prim.IndirectParameterEnable  = true;
3092         prim.PredicateEnable          = cmd_buffer->state.conditional_render_enabled;
3093         prim.VertexAccessType         = RANDOM;
3094         prim.PrimitiveTopologyType    = pipeline->topology;
3095      }
3096
3097      offset += stride;
3098   }
3099}
3100
3101#define TMP_DRAW_COUNT_REG 0x2670 /* MI_ALU_REG14 */
3102
3103static void
3104prepare_for_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3105                                 struct anv_address count_address,
3106                                 const bool conditional_render_enabled)
3107{
3108   struct gen_mi_builder b;
3109   gen_mi_builder_init(&b, &cmd_buffer->batch);
3110
3111   if (conditional_render_enabled) {
3112#if GEN_GEN >= 8 || GEN_IS_HASWELL
3113      gen_mi_store(&b, gen_mi_reg64(TMP_DRAW_COUNT_REG),
3114                       gen_mi_mem32(count_address));
3115#endif
3116   } else {
3117      /* Upload the current draw count from the draw parameters buffer to
3118       * MI_PREDICATE_SRC0.
3119       */
3120      gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
3121                       gen_mi_mem32(count_address));
3122
3123      gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC1 + 4), gen_mi_imm(0));
3124   }
3125}
3126
3127static void
3128emit_draw_count_predicate(struct anv_cmd_buffer *cmd_buffer,
3129                          uint32_t draw_index)
3130{
3131   struct gen_mi_builder b;
3132   gen_mi_builder_init(&b, &cmd_buffer->batch);
3133
3134   /* Upload the index of the current primitive to MI_PREDICATE_SRC1. */
3135   gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC1), gen_mi_imm(draw_index));
3136
3137   if (draw_index == 0) {
3138      anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3139         mip.LoadOperation    = LOAD_LOADINV;
3140         mip.CombineOperation = COMBINE_SET;
3141         mip.CompareOperation = COMPARE_SRCS_EQUAL;
3142      }
3143   } else {
3144      /* While draw_index < draw_count the predicate's result will be
3145       *  (draw_index == draw_count) ^ TRUE = TRUE
3146       * When draw_index == draw_count the result is
3147       *  (TRUE) ^ TRUE = FALSE
3148       * After this all results will be:
3149       *  (FALSE) ^ FALSE = FALSE
3150       */
3151      anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3152         mip.LoadOperation    = LOAD_LOAD;
3153         mip.CombineOperation = COMBINE_XOR;
3154         mip.CompareOperation = COMPARE_SRCS_EQUAL;
3155      }
3156   }
3157}
3158
3159#if GEN_GEN >= 8 || GEN_IS_HASWELL
3160static void
3161emit_draw_count_predicate_with_conditional_render(
3162                          struct anv_cmd_buffer *cmd_buffer,
3163                          uint32_t draw_index)
3164{
3165   struct gen_mi_builder b;
3166   gen_mi_builder_init(&b, &cmd_buffer->batch);
3167
3168   struct gen_mi_value pred = gen_mi_ult(&b, gen_mi_imm(draw_index),
3169                                         gen_mi_reg64(TMP_DRAW_COUNT_REG));
3170   pred = gen_mi_iand(&b, pred, gen_mi_reg64(ANV_PREDICATE_RESULT_REG));
3171
3172#if GEN_GEN >= 8
3173   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_RESULT), pred);
3174#else
3175   /* MI_PREDICATE_RESULT is not whitelisted in i915 command parser
3176    * so we emit MI_PREDICATE to set it.
3177    */
3178
3179   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), pred);
3180   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3181
3182   anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
3183      mip.LoadOperation    = LOAD_LOADINV;
3184      mip.CombineOperation = COMBINE_SET;
3185      mip.CompareOperation = COMPARE_SRCS_EQUAL;
3186   }
3187#endif
3188}
3189#endif
3190
3191void genX(CmdDrawIndirectCountKHR)(
3192    VkCommandBuffer                             commandBuffer,
3193    VkBuffer                                    _buffer,
3194    VkDeviceSize                                offset,
3195    VkBuffer                                    _countBuffer,
3196    VkDeviceSize                                countBufferOffset,
3197    uint32_t                                    maxDrawCount,
3198    uint32_t                                    stride)
3199{
3200   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3201   ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3202   ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3203   struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3204   struct anv_pipeline *pipeline = cmd_state->gfx.base.pipeline;
3205   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3206
3207   if (anv_batch_has_error(&cmd_buffer->batch))
3208      return;
3209
3210   genX(cmd_buffer_flush_state)(cmd_buffer);
3211
3212   struct anv_address count_address =
3213      anv_address_add(count_buffer->address, countBufferOffset);
3214
3215   prepare_for_draw_count_predicate(cmd_buffer, count_address,
3216                                    cmd_state->conditional_render_enabled);
3217
3218   for (uint32_t i = 0; i < maxDrawCount; i++) {
3219      struct anv_address draw = anv_address_add(buffer->address, offset);
3220
3221#if GEN_GEN >= 8 || GEN_IS_HASWELL
3222      if (cmd_state->conditional_render_enabled) {
3223         emit_draw_count_predicate_with_conditional_render(cmd_buffer, i);
3224      } else {
3225         emit_draw_count_predicate(cmd_buffer, i);
3226      }
3227#else
3228      emit_draw_count_predicate(cmd_buffer, i);
3229#endif
3230
3231      if (vs_prog_data->uses_firstvertex ||
3232          vs_prog_data->uses_baseinstance)
3233         emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 8));
3234      if (vs_prog_data->uses_drawid)
3235         emit_draw_index(cmd_buffer, i);
3236
3237      load_indirect_parameters(cmd_buffer, draw, false);
3238
3239      anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3240         prim.IndirectParameterEnable  = true;
3241         prim.PredicateEnable          = true;
3242         prim.VertexAccessType         = SEQUENTIAL;
3243         prim.PrimitiveTopologyType    = pipeline->topology;
3244      }
3245
3246      offset += stride;
3247   }
3248}
3249
3250void genX(CmdDrawIndexedIndirectCountKHR)(
3251    VkCommandBuffer                             commandBuffer,
3252    VkBuffer                                    _buffer,
3253    VkDeviceSize                                offset,
3254    VkBuffer                                    _countBuffer,
3255    VkDeviceSize                                countBufferOffset,
3256    uint32_t                                    maxDrawCount,
3257    uint32_t                                    stride)
3258{
3259   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3260   ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3261   ANV_FROM_HANDLE(anv_buffer, count_buffer, _countBuffer);
3262   struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3263   struct anv_pipeline *pipeline = cmd_state->gfx.base.pipeline;
3264   const struct brw_vs_prog_data *vs_prog_data = get_vs_prog_data(pipeline);
3265
3266   if (anv_batch_has_error(&cmd_buffer->batch))
3267      return;
3268
3269   genX(cmd_buffer_flush_state)(cmd_buffer);
3270
3271   struct anv_address count_address =
3272      anv_address_add(count_buffer->address, countBufferOffset);
3273
3274   prepare_for_draw_count_predicate(cmd_buffer, count_address,
3275                                    cmd_state->conditional_render_enabled);
3276
3277   for (uint32_t i = 0; i < maxDrawCount; i++) {
3278      struct anv_address draw = anv_address_add(buffer->address, offset);
3279
3280#if GEN_GEN >= 8 || GEN_IS_HASWELL
3281      if (cmd_state->conditional_render_enabled) {
3282         emit_draw_count_predicate_with_conditional_render(cmd_buffer, i);
3283      } else {
3284         emit_draw_count_predicate(cmd_buffer, i);
3285      }
3286#else
3287      emit_draw_count_predicate(cmd_buffer, i);
3288#endif
3289
3290      /* TODO: We need to stomp base vertex to 0 somehow */
3291      if (vs_prog_data->uses_firstvertex ||
3292          vs_prog_data->uses_baseinstance)
3293         emit_base_vertex_instance_bo(cmd_buffer, anv_address_add(draw, 12));
3294      if (vs_prog_data->uses_drawid)
3295         emit_draw_index(cmd_buffer, i);
3296
3297      load_indirect_parameters(cmd_buffer, draw, true);
3298
3299      anv_batch_emit(&cmd_buffer->batch, GENX(3DPRIMITIVE), prim) {
3300         prim.IndirectParameterEnable  = true;
3301         prim.PredicateEnable          = true;
3302         prim.VertexAccessType         = RANDOM;
3303         prim.PrimitiveTopologyType    = pipeline->topology;
3304      }
3305
3306      offset += stride;
3307   }
3308}
3309
3310void genX(CmdBeginTransformFeedbackEXT)(
3311    VkCommandBuffer                             commandBuffer,
3312    uint32_t                                    firstCounterBuffer,
3313    uint32_t                                    counterBufferCount,
3314    const VkBuffer*                             pCounterBuffers,
3315    const VkDeviceSize*                         pCounterBufferOffsets)
3316{
3317   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3318
3319   assert(firstCounterBuffer < MAX_XFB_BUFFERS);
3320   assert(counterBufferCount <= MAX_XFB_BUFFERS);
3321   assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
3322
3323   /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
3324    *
3325    *    "Ssoftware must ensure that no HW stream output operations can be in
3326    *    process or otherwise pending at the point that the MI_LOAD/STORE
3327    *    commands are processed. This will likely require a pipeline flush."
3328    */
3329   cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3330   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3331
3332   for (uint32_t idx = 0; idx < MAX_XFB_BUFFERS; idx++) {
3333      /* If we have a counter buffer, this is a resume so we need to load the
3334       * value into the streamout offset register.  Otherwise, this is a begin
3335       * and we need to reset it to zero.
3336       */
3337      if (pCounterBuffers &&
3338          idx >= firstCounterBuffer &&
3339          idx - firstCounterBuffer < counterBufferCount &&
3340          pCounterBuffers[idx - firstCounterBuffer] != VK_NULL_HANDLE) {
3341         uint32_t cb_idx = idx - firstCounterBuffer;
3342         ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
3343         uint64_t offset = pCounterBufferOffsets ?
3344                           pCounterBufferOffsets[cb_idx] : 0;
3345
3346         anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
3347            lrm.RegisterAddress  = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3348            lrm.MemoryAddress    = anv_address_add(counter_buffer->address,
3349                                                   offset);
3350         }
3351      } else {
3352         anv_batch_emit(&cmd_buffer->batch, GENX(MI_LOAD_REGISTER_IMM), lri) {
3353            lri.RegisterOffset   = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3354            lri.DataDWord        = 0;
3355         }
3356      }
3357   }
3358
3359   cmd_buffer->state.xfb_enabled = true;
3360   cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
3361}
3362
3363void genX(CmdEndTransformFeedbackEXT)(
3364    VkCommandBuffer                             commandBuffer,
3365    uint32_t                                    firstCounterBuffer,
3366    uint32_t                                    counterBufferCount,
3367    const VkBuffer*                             pCounterBuffers,
3368    const VkDeviceSize*                         pCounterBufferOffsets)
3369{
3370   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3371
3372   assert(firstCounterBuffer < MAX_XFB_BUFFERS);
3373   assert(counterBufferCount <= MAX_XFB_BUFFERS);
3374   assert(firstCounterBuffer + counterBufferCount <= MAX_XFB_BUFFERS);
3375
3376   /* From the SKL PRM Vol. 2c, SO_WRITE_OFFSET:
3377    *
3378    *    "Ssoftware must ensure that no HW stream output operations can be in
3379    *    process or otherwise pending at the point that the MI_LOAD/STORE
3380    *    commands are processed. This will likely require a pipeline flush."
3381    */
3382   cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3383   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3384
3385   for (uint32_t cb_idx = 0; cb_idx < counterBufferCount; cb_idx++) {
3386      unsigned idx = firstCounterBuffer + cb_idx;
3387
3388      /* If we have a counter buffer, this is a resume so we need to load the
3389       * value into the streamout offset register.  Otherwise, this is a begin
3390       * and we need to reset it to zero.
3391       */
3392      if (pCounterBuffers &&
3393          cb_idx < counterBufferCount &&
3394          pCounterBuffers[cb_idx] != VK_NULL_HANDLE) {
3395         ANV_FROM_HANDLE(anv_buffer, counter_buffer, pCounterBuffers[cb_idx]);
3396         uint64_t offset = pCounterBufferOffsets ?
3397                           pCounterBufferOffsets[cb_idx] : 0;
3398
3399         anv_batch_emit(&cmd_buffer->batch, GENX(MI_STORE_REGISTER_MEM), srm) {
3400            srm.MemoryAddress    = anv_address_add(counter_buffer->address,
3401                                                   offset);
3402            srm.RegisterAddress  = GENX(SO_WRITE_OFFSET0_num) + idx * 4;
3403         }
3404      }
3405   }
3406
3407   cmd_buffer->state.xfb_enabled = false;
3408   cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_XFB_ENABLE;
3409}
3410
3411static VkResult
3412flush_compute_descriptor_set(struct anv_cmd_buffer *cmd_buffer)
3413{
3414   struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3415   struct anv_state surfaces = { 0, }, samplers = { 0, };
3416   VkResult result;
3417
3418   result = emit_binding_table(cmd_buffer, MESA_SHADER_COMPUTE, &surfaces);
3419   if (result != VK_SUCCESS) {
3420      assert(result == VK_ERROR_OUT_OF_DEVICE_MEMORY);
3421
3422      result = anv_cmd_buffer_new_binding_table_block(cmd_buffer);
3423      if (result != VK_SUCCESS)
3424         return result;
3425
3426      /* Re-emit state base addresses so we get the new surface state base
3427       * address before we start emitting binding tables etc.
3428       */
3429      genX(cmd_buffer_emit_state_base_address)(cmd_buffer);
3430
3431      result = emit_binding_table(cmd_buffer, MESA_SHADER_COMPUTE, &surfaces);
3432      if (result != VK_SUCCESS) {
3433         anv_batch_set_error(&cmd_buffer->batch, result);
3434         return result;
3435      }
3436   }
3437
3438   result = emit_samplers(cmd_buffer, MESA_SHADER_COMPUTE, &samplers);
3439   if (result != VK_SUCCESS) {
3440      anv_batch_set_error(&cmd_buffer->batch, result);
3441      return result;
3442   }
3443
3444   uint32_t iface_desc_data_dw[GENX(INTERFACE_DESCRIPTOR_DATA_length)];
3445   struct GENX(INTERFACE_DESCRIPTOR_DATA) desc = {
3446      .BindingTablePointer = surfaces.offset,
3447      .SamplerStatePointer = samplers.offset,
3448   };
3449   GENX(INTERFACE_DESCRIPTOR_DATA_pack)(NULL, iface_desc_data_dw, &desc);
3450
3451   struct anv_state state =
3452      anv_cmd_buffer_merge_dynamic(cmd_buffer, iface_desc_data_dw,
3453                                   pipeline->interface_descriptor_data,
3454                                   GENX(INTERFACE_DESCRIPTOR_DATA_length),
3455                                   64);
3456
3457   uint32_t size = GENX(INTERFACE_DESCRIPTOR_DATA_length) * sizeof(uint32_t);
3458   anv_batch_emit(&cmd_buffer->batch,
3459                  GENX(MEDIA_INTERFACE_DESCRIPTOR_LOAD), mid) {
3460      mid.InterfaceDescriptorTotalLength        = size;
3461      mid.InterfaceDescriptorDataStartAddress   = state.offset;
3462   }
3463
3464   return VK_SUCCESS;
3465}
3466
3467void
3468genX(cmd_buffer_flush_compute_state)(struct anv_cmd_buffer *cmd_buffer)
3469{
3470   struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3471   MAYBE_UNUSED VkResult result;
3472
3473   assert(pipeline->active_stages == VK_SHADER_STAGE_COMPUTE_BIT);
3474
3475   genX(cmd_buffer_config_l3)(cmd_buffer, pipeline->urb.l3_config);
3476
3477   genX(flush_pipeline_select_gpgpu)(cmd_buffer);
3478
3479   if (cmd_buffer->state.compute.pipeline_dirty) {
3480      /* From the Sky Lake PRM Vol 2a, MEDIA_VFE_STATE:
3481       *
3482       *    "A stalling PIPE_CONTROL is required before MEDIA_VFE_STATE unless
3483       *    the only bits that are changed are scoreboard related: Scoreboard
3484       *    Enable, Scoreboard Type, Scoreboard Mask, Scoreboard * Delta. For
3485       *    these scoreboard related states, a MEDIA_STATE_FLUSH is
3486       *    sufficient."
3487       */
3488      cmd_buffer->state.pending_pipe_bits |= ANV_PIPE_CS_STALL_BIT;
3489      genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3490
3491      anv_batch_emit_batch(&cmd_buffer->batch, &pipeline->batch);
3492   }
3493
3494   if ((cmd_buffer->state.descriptors_dirty & VK_SHADER_STAGE_COMPUTE_BIT) ||
3495       cmd_buffer->state.compute.pipeline_dirty) {
3496      /* FIXME: figure out descriptors for gen7 */
3497      result = flush_compute_descriptor_set(cmd_buffer);
3498      if (result != VK_SUCCESS)
3499         return;
3500
3501      cmd_buffer->state.descriptors_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
3502   }
3503
3504   if (cmd_buffer->state.push_constants_dirty & VK_SHADER_STAGE_COMPUTE_BIT) {
3505      struct anv_state push_state =
3506         anv_cmd_buffer_cs_push_constants(cmd_buffer);
3507
3508      if (push_state.alloc_size) {
3509         anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_CURBE_LOAD), curbe) {
3510            curbe.CURBETotalDataLength    = push_state.alloc_size;
3511            curbe.CURBEDataStartAddress   = push_state.offset;
3512         }
3513      }
3514
3515      cmd_buffer->state.push_constants_dirty &= ~VK_SHADER_STAGE_COMPUTE_BIT;
3516   }
3517
3518   cmd_buffer->state.compute.pipeline_dirty = false;
3519
3520   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
3521}
3522
3523#if GEN_GEN == 7
3524
3525static VkResult
3526verify_cmd_parser(const struct anv_device *device,
3527                  int required_version,
3528                  const char *function)
3529{
3530   if (device->instance->physicalDevice.cmd_parser_version < required_version) {
3531      return vk_errorf(device->instance, device->instance,
3532                       VK_ERROR_FEATURE_NOT_PRESENT,
3533                       "cmd parser version %d is required for %s",
3534                       required_version, function);
3535   } else {
3536      return VK_SUCCESS;
3537   }
3538}
3539
3540#endif
3541
3542static void
3543anv_cmd_buffer_push_base_group_id(struct anv_cmd_buffer *cmd_buffer,
3544                                  uint32_t baseGroupX,
3545                                  uint32_t baseGroupY,
3546                                  uint32_t baseGroupZ)
3547{
3548   if (anv_batch_has_error(&cmd_buffer->batch))
3549      return;
3550
3551   struct anv_push_constants *push =
3552      &cmd_buffer->state.push_constants[MESA_SHADER_COMPUTE];
3553   if (push->base_work_group_id[0] != baseGroupX ||
3554       push->base_work_group_id[1] != baseGroupY ||
3555       push->base_work_group_id[2] != baseGroupZ) {
3556      push->base_work_group_id[0] = baseGroupX;
3557      push->base_work_group_id[1] = baseGroupY;
3558      push->base_work_group_id[2] = baseGroupZ;
3559
3560      cmd_buffer->state.push_constants_dirty |= VK_SHADER_STAGE_COMPUTE_BIT;
3561   }
3562}
3563
3564void genX(CmdDispatch)(
3565    VkCommandBuffer                             commandBuffer,
3566    uint32_t                                    x,
3567    uint32_t                                    y,
3568    uint32_t                                    z)
3569{
3570   genX(CmdDispatchBase)(commandBuffer, 0, 0, 0, x, y, z);
3571}
3572
3573void genX(CmdDispatchBase)(
3574    VkCommandBuffer                             commandBuffer,
3575    uint32_t                                    baseGroupX,
3576    uint32_t                                    baseGroupY,
3577    uint32_t                                    baseGroupZ,
3578    uint32_t                                    groupCountX,
3579    uint32_t                                    groupCountY,
3580    uint32_t                                    groupCountZ)
3581{
3582   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3583   struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3584   const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3585
3586   anv_cmd_buffer_push_base_group_id(cmd_buffer, baseGroupX,
3587                                     baseGroupY, baseGroupZ);
3588
3589   if (anv_batch_has_error(&cmd_buffer->batch))
3590      return;
3591
3592   if (prog_data->uses_num_work_groups) {
3593      struct anv_state state =
3594         anv_cmd_buffer_alloc_dynamic_state(cmd_buffer, 12, 4);
3595      uint32_t *sizes = state.map;
3596      sizes[0] = groupCountX;
3597      sizes[1] = groupCountY;
3598      sizes[2] = groupCountZ;
3599      cmd_buffer->state.compute.num_workgroups = (struct anv_address) {
3600         .bo = cmd_buffer->device->dynamic_state_pool.block_pool.bo,
3601         .offset = state.offset,
3602      };
3603   }
3604
3605   genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3606
3607   if (cmd_buffer->state.conditional_render_enabled)
3608      genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3609
3610   anv_batch_emit(&cmd_buffer->batch, GENX(GPGPU_WALKER), ggw) {
3611      ggw.PredicateEnable              = cmd_buffer->state.conditional_render_enabled;
3612      ggw.SIMDSize                     = prog_data->simd_size / 16;
3613      ggw.ThreadDepthCounterMaximum    = 0;
3614      ggw.ThreadHeightCounterMaximum   = 0;
3615      ggw.ThreadWidthCounterMaximum    = prog_data->threads - 1;
3616      ggw.ThreadGroupIDXDimension      = groupCountX;
3617      ggw.ThreadGroupIDYDimension      = groupCountY;
3618      ggw.ThreadGroupIDZDimension      = groupCountZ;
3619      ggw.RightExecutionMask           = pipeline->cs_right_mask;
3620      ggw.BottomExecutionMask          = 0xffffffff;
3621   }
3622
3623   anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_STATE_FLUSH), msf);
3624}
3625
3626#define GPGPU_DISPATCHDIMX 0x2500
3627#define GPGPU_DISPATCHDIMY 0x2504
3628#define GPGPU_DISPATCHDIMZ 0x2508
3629
3630void genX(CmdDispatchIndirect)(
3631    VkCommandBuffer                             commandBuffer,
3632    VkBuffer                                    _buffer,
3633    VkDeviceSize                                offset)
3634{
3635   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
3636   ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3637   struct anv_pipeline *pipeline = cmd_buffer->state.compute.base.pipeline;
3638   const struct brw_cs_prog_data *prog_data = get_cs_prog_data(pipeline);
3639   struct anv_address addr = anv_address_add(buffer->address, offset);
3640   struct anv_batch *batch = &cmd_buffer->batch;
3641
3642   anv_cmd_buffer_push_base_group_id(cmd_buffer, 0, 0, 0);
3643
3644#if GEN_GEN == 7
3645   /* Linux 4.4 added command parser version 5 which allows the GPGPU
3646    * indirect dispatch registers to be written.
3647    */
3648   if (verify_cmd_parser(cmd_buffer->device, 5,
3649                         "vkCmdDispatchIndirect") != VK_SUCCESS)
3650      return;
3651#endif
3652
3653   if (prog_data->uses_num_work_groups)
3654      cmd_buffer->state.compute.num_workgroups = addr;
3655
3656   genX(cmd_buffer_flush_compute_state)(cmd_buffer);
3657
3658   struct gen_mi_builder b;
3659   gen_mi_builder_init(&b, &cmd_buffer->batch);
3660
3661   struct gen_mi_value size_x = gen_mi_mem32(anv_address_add(addr, 0));
3662   struct gen_mi_value size_y = gen_mi_mem32(anv_address_add(addr, 4));
3663   struct gen_mi_value size_z = gen_mi_mem32(anv_address_add(addr, 8));
3664
3665   gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMX), size_x);
3666   gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMY), size_y);
3667   gen_mi_store(&b, gen_mi_reg32(GPGPU_DISPATCHDIMZ), size_z);
3668
3669#if GEN_GEN <= 7
3670   /* predicate = (compute_dispatch_indirect_x_size == 0); */
3671   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0), size_x);
3672   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
3673   anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3674      mip.LoadOperation    = LOAD_LOAD;
3675      mip.CombineOperation = COMBINE_SET;
3676      mip.CompareOperation = COMPARE_SRCS_EQUAL;
3677   }
3678
3679   /* predicate |= (compute_dispatch_indirect_y_size == 0); */
3680   gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_y);
3681   anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3682      mip.LoadOperation    = LOAD_LOAD;
3683      mip.CombineOperation = COMBINE_OR;
3684      mip.CompareOperation = COMPARE_SRCS_EQUAL;
3685   }
3686
3687   /* predicate |= (compute_dispatch_indirect_z_size == 0); */
3688   gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0), size_z);
3689   anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3690      mip.LoadOperation    = LOAD_LOAD;
3691      mip.CombineOperation = COMBINE_OR;
3692      mip.CompareOperation = COMPARE_SRCS_EQUAL;
3693   }
3694
3695   /* predicate = !predicate; */
3696   anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3697      mip.LoadOperation    = LOAD_LOADINV;
3698      mip.CombineOperation = COMBINE_OR;
3699      mip.CompareOperation = COMPARE_FALSE;
3700   }
3701
3702#if GEN_IS_HASWELL
3703   if (cmd_buffer->state.conditional_render_enabled) {
3704      /* predicate &= !(conditional_rendering_predicate == 0); */
3705      gen_mi_store(&b, gen_mi_reg32(MI_PREDICATE_SRC0),
3706                       gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
3707      anv_batch_emit(batch, GENX(MI_PREDICATE), mip) {
3708         mip.LoadOperation    = LOAD_LOADINV;
3709         mip.CombineOperation = COMBINE_AND;
3710         mip.CompareOperation = COMPARE_SRCS_EQUAL;
3711      }
3712   }
3713#endif
3714
3715#else /* GEN_GEN > 7 */
3716   if (cmd_buffer->state.conditional_render_enabled)
3717      genX(cmd_emit_conditional_render_predicate)(cmd_buffer);
3718#endif
3719
3720   anv_batch_emit(batch, GENX(GPGPU_WALKER), ggw) {
3721      ggw.IndirectParameterEnable      = true;
3722      ggw.PredicateEnable              = GEN_GEN <= 7 ||
3723                                         cmd_buffer->state.conditional_render_enabled;
3724      ggw.SIMDSize                     = prog_data->simd_size / 16;
3725      ggw.ThreadDepthCounterMaximum    = 0;
3726      ggw.ThreadHeightCounterMaximum   = 0;
3727      ggw.ThreadWidthCounterMaximum    = prog_data->threads - 1;
3728      ggw.RightExecutionMask           = pipeline->cs_right_mask;
3729      ggw.BottomExecutionMask          = 0xffffffff;
3730   }
3731
3732   anv_batch_emit(batch, GENX(MEDIA_STATE_FLUSH), msf);
3733}
3734
3735static void
3736genX(flush_pipeline_select)(struct anv_cmd_buffer *cmd_buffer,
3737                            uint32_t pipeline)
3738{
3739   UNUSED const struct gen_device_info *devinfo = &cmd_buffer->device->info;
3740
3741   if (cmd_buffer->state.current_pipeline == pipeline)
3742      return;
3743
3744#if GEN_GEN >= 8 && GEN_GEN < 10
3745   /* From the Broadwell PRM, Volume 2a: Instructions, PIPELINE_SELECT:
3746    *
3747    *   Software must clear the COLOR_CALC_STATE Valid field in
3748    *   3DSTATE_CC_STATE_POINTERS command prior to send a PIPELINE_SELECT
3749    *   with Pipeline Select set to GPGPU.
3750    *
3751    * The internal hardware docs recommend the same workaround for Gen9
3752    * hardware too.
3753    */
3754   if (pipeline == GPGPU)
3755      anv_batch_emit(&cmd_buffer->batch, GENX(3DSTATE_CC_STATE_POINTERS), t);
3756#endif
3757
3758#if GEN_GEN == 9
3759   if (pipeline == _3D) {
3760      /* There is a mid-object preemption workaround which requires you to
3761       * re-emit MEDIA_VFE_STATE after switching from GPGPU to 3D.  However,
3762       * even without preemption, we have issues with geometry flickering when
3763       * GPGPU and 3D are back-to-back and this seems to fix it.  We don't
3764       * really know why.
3765       */
3766      const uint32_t subslices =
3767         MAX2(cmd_buffer->device->instance->physicalDevice.subslice_total, 1);
3768      anv_batch_emit(&cmd_buffer->batch, GENX(MEDIA_VFE_STATE), vfe) {
3769         vfe.MaximumNumberofThreads =
3770            devinfo->max_cs_threads * subslices - 1;
3771         vfe.NumberofURBEntries     = 2;
3772         vfe.URBEntryAllocationSize = 2;
3773      }
3774   }
3775#endif
3776
3777   /* From "BXML » GT » MI » vol1a GPU Overview » [Instruction]
3778    * PIPELINE_SELECT [DevBWR+]":
3779    *
3780    *   Project: DEVSNB+
3781    *
3782    *   Software must ensure all the write caches are flushed through a
3783    *   stalling PIPE_CONTROL command followed by another PIPE_CONTROL
3784    *   command to invalidate read only caches prior to programming
3785    *   MI_PIPELINE_SELECT command to change the Pipeline Select Mode.
3786    */
3787   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
3788      pc.RenderTargetCacheFlushEnable  = true;
3789      pc.DepthCacheFlushEnable         = true;
3790      pc.DCFlushEnable                 = true;
3791      pc.PostSyncOperation             = NoWrite;
3792      pc.CommandStreamerStallEnable    = true;
3793   }
3794
3795   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
3796      pc.TextureCacheInvalidationEnable   = true;
3797      pc.ConstantCacheInvalidationEnable  = true;
3798      pc.StateCacheInvalidationEnable     = true;
3799      pc.InstructionCacheInvalidateEnable = true;
3800      pc.PostSyncOperation                = NoWrite;
3801   }
3802
3803   anv_batch_emit(&cmd_buffer->batch, GENX(PIPELINE_SELECT), ps) {
3804#if GEN_GEN >= 9
3805      ps.MaskBits = 3;
3806#endif
3807      ps.PipelineSelection = pipeline;
3808   }
3809
3810#if GEN_GEN == 9
3811   if (devinfo->is_geminilake) {
3812      /* Project: DevGLK
3813       *
3814       * "This chicken bit works around a hardware issue with barrier logic
3815       *  encountered when switching between GPGPU and 3D pipelines.  To
3816       *  workaround the issue, this mode bit should be set after a pipeline
3817       *  is selected."
3818       */
3819      uint32_t scec;
3820      anv_pack_struct(&scec, GENX(SLICE_COMMON_ECO_CHICKEN1),
3821                      .GLKBarrierMode =
3822                          pipeline == GPGPU ? GLK_BARRIER_MODE_GPGPU
3823                                            : GLK_BARRIER_MODE_3D_HULL,
3824                      .GLKBarrierModeMask = 1);
3825      emit_lri(&cmd_buffer->batch, GENX(SLICE_COMMON_ECO_CHICKEN1_num), scec);
3826   }
3827#endif
3828
3829   cmd_buffer->state.current_pipeline = pipeline;
3830}
3831
3832void
3833genX(flush_pipeline_select_3d)(struct anv_cmd_buffer *cmd_buffer)
3834{
3835   genX(flush_pipeline_select)(cmd_buffer, _3D);
3836}
3837
3838void
3839genX(flush_pipeline_select_gpgpu)(struct anv_cmd_buffer *cmd_buffer)
3840{
3841   genX(flush_pipeline_select)(cmd_buffer, GPGPU);
3842}
3843
3844void
3845genX(cmd_buffer_emit_gen7_depth_flush)(struct anv_cmd_buffer *cmd_buffer)
3846{
3847   if (GEN_GEN >= 8)
3848      return;
3849
3850   /* From the Haswell PRM, documentation for 3DSTATE_DEPTH_BUFFER:
3851    *
3852    *    "Restriction: Prior to changing Depth/Stencil Buffer state (i.e., any
3853    *    combination of 3DSTATE_DEPTH_BUFFER, 3DSTATE_CLEAR_PARAMS,
3854    *    3DSTATE_STENCIL_BUFFER, 3DSTATE_HIER_DEPTH_BUFFER) SW must first
3855    *    issue a pipelined depth stall (PIPE_CONTROL with Depth Stall bit
3856    *    set), followed by a pipelined depth cache flush (PIPE_CONTROL with
3857    *    Depth Flush Bit set, followed by another pipelined depth stall
3858    *    (PIPE_CONTROL with Depth Stall Bit set), unless SW can otherwise
3859    *    guarantee that the pipeline from WM onwards is already flushed (e.g.,
3860    *    via a preceding MI_FLUSH)."
3861    */
3862   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3863      pipe.DepthStallEnable = true;
3864   }
3865   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3866      pipe.DepthCacheFlushEnable = true;
3867   }
3868   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pipe) {
3869      pipe.DepthStallEnable = true;
3870   }
3871}
3872
3873static void
3874cmd_buffer_emit_depth_stencil(struct anv_cmd_buffer *cmd_buffer)
3875{
3876   struct anv_device *device = cmd_buffer->device;
3877   const struct anv_image_view *iview =
3878      anv_cmd_buffer_get_depth_stencil_view(cmd_buffer);
3879   const struct anv_image *image = iview ? iview->image : NULL;
3880
3881   /* FIXME: Width and Height are wrong */
3882
3883   genX(cmd_buffer_emit_gen7_depth_flush)(cmd_buffer);
3884
3885   uint32_t *dw = anv_batch_emit_dwords(&cmd_buffer->batch,
3886                                        device->isl_dev.ds.size / 4);
3887   if (dw == NULL)
3888      return;
3889
3890   struct isl_depth_stencil_hiz_emit_info info = { };
3891
3892   if (iview)
3893      info.view = &iview->planes[0].isl;
3894
3895   if (image && (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT)) {
3896      uint32_t depth_plane =
3897         anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_DEPTH_BIT);
3898      const struct anv_surface *surface = &image->planes[depth_plane].surface;
3899
3900      info.depth_surf = &surface->isl;
3901
3902      info.depth_address =
3903         anv_batch_emit_reloc(&cmd_buffer->batch,
3904                              dw + device->isl_dev.ds.depth_offset / 4,
3905                              image->planes[depth_plane].address.bo,
3906                              image->planes[depth_plane].address.offset +
3907                              surface->offset);
3908      info.mocs =
3909         anv_mocs_for_bo(device, image->planes[depth_plane].address.bo);
3910
3911      const uint32_t ds =
3912         cmd_buffer->state.subpass->depth_stencil_attachment->attachment;
3913      info.hiz_usage = cmd_buffer->state.attachments[ds].aux_usage;
3914      if (info.hiz_usage == ISL_AUX_USAGE_HIZ) {
3915         info.hiz_surf = &image->planes[depth_plane].aux_surface.isl;
3916
3917         info.hiz_address =
3918            anv_batch_emit_reloc(&cmd_buffer->batch,
3919                                 dw + device->isl_dev.ds.hiz_offset / 4,
3920                                 image->planes[depth_plane].address.bo,
3921                                 image->planes[depth_plane].address.offset +
3922                                 image->planes[depth_plane].aux_surface.offset);
3923
3924         info.depth_clear_value = ANV_HZ_FC_VAL;
3925      }
3926   }
3927
3928   if (image && (image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT)) {
3929      uint32_t stencil_plane =
3930         anv_image_aspect_to_plane(image->aspects, VK_IMAGE_ASPECT_STENCIL_BIT);
3931      const struct anv_surface *surface = &image->planes[stencil_plane].surface;
3932
3933      info.stencil_surf = &surface->isl;
3934
3935      info.stencil_address =
3936         anv_batch_emit_reloc(&cmd_buffer->batch,
3937                              dw + device->isl_dev.ds.stencil_offset / 4,
3938                              image->planes[stencil_plane].address.bo,
3939                              image->planes[stencil_plane].address.offset +
3940                              surface->offset);
3941      info.mocs =
3942         anv_mocs_for_bo(device, image->planes[stencil_plane].address.bo);
3943   }
3944
3945   isl_emit_depth_stencil_hiz_s(&device->isl_dev, dw, &info);
3946
3947   cmd_buffer->state.hiz_enabled = info.hiz_usage == ISL_AUX_USAGE_HIZ;
3948}
3949
3950/**
3951 * This ANDs the view mask of the current subpass with the pending clear
3952 * views in the attachment to get the mask of views active in the subpass
3953 * that still need to be cleared.
3954 */
3955static inline uint32_t
3956get_multiview_subpass_clear_mask(const struct anv_cmd_state *cmd_state,
3957                                 const struct anv_attachment_state *att_state)
3958{
3959   return cmd_state->subpass->view_mask & att_state->pending_clear_views;
3960}
3961
3962static inline bool
3963do_first_layer_clear(const struct anv_cmd_state *cmd_state,
3964                     const struct anv_attachment_state *att_state)
3965{
3966   if (!cmd_state->subpass->view_mask)
3967      return true;
3968
3969   uint32_t pending_clear_mask =
3970      get_multiview_subpass_clear_mask(cmd_state, att_state);
3971
3972   return pending_clear_mask & 1;
3973}
3974
3975static inline bool
3976current_subpass_is_last_for_attachment(const struct anv_cmd_state *cmd_state,
3977                                       uint32_t att_idx)
3978{
3979   const uint32_t last_subpass_idx =
3980      cmd_state->pass->attachments[att_idx].last_subpass_idx;
3981   const struct anv_subpass *last_subpass =
3982      &cmd_state->pass->subpasses[last_subpass_idx];
3983   return last_subpass == cmd_state->subpass;
3984}
3985
3986static void
3987cmd_buffer_begin_subpass(struct anv_cmd_buffer *cmd_buffer,
3988                         uint32_t subpass_id)
3989{
3990   struct anv_cmd_state *cmd_state = &cmd_buffer->state;
3991   struct anv_subpass *subpass = &cmd_state->pass->subpasses[subpass_id];
3992   cmd_state->subpass = subpass;
3993
3994   cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_RENDER_TARGETS;
3995
3996   /* Our implementation of VK_KHR_multiview uses instancing to draw the
3997    * different views.  If the client asks for instancing, we need to use the
3998    * Instance Data Step Rate to ensure that we repeat the client's
3999    * per-instance data once for each view.  Since this bit is in
4000    * VERTEX_BUFFER_STATE on gen7, we need to dirty vertex buffers at the top
4001    * of each subpass.
4002    */
4003   if (GEN_GEN == 7)
4004      cmd_buffer->state.gfx.vb_dirty |= ~0;
4005
4006   /* It is possible to start a render pass with an old pipeline.  Because the
4007    * render pass and subpass index are both baked into the pipeline, this is
4008    * highly unlikely.  In order to do so, it requires that you have a render
4009    * pass with a single subpass and that you use that render pass twice
4010    * back-to-back and use the same pipeline at the start of the second render
4011    * pass as at the end of the first.  In order to avoid unpredictable issues
4012    * with this edge case, we just dirty the pipeline at the start of every
4013    * subpass.
4014    */
4015   cmd_buffer->state.gfx.dirty |= ANV_CMD_DIRTY_PIPELINE;
4016
4017   /* Accumulate any subpass flushes that need to happen before the subpass */
4018   cmd_buffer->state.pending_pipe_bits |=
4019      cmd_buffer->state.pass->subpass_flushes[subpass_id];
4020
4021   VkRect2D render_area = cmd_buffer->state.render_area;
4022   struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
4023
4024   bool is_multiview = subpass->view_mask != 0;
4025
4026   for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
4027      const uint32_t a = subpass->attachments[i].attachment;
4028      if (a == VK_ATTACHMENT_UNUSED)
4029         continue;
4030
4031      assert(a < cmd_state->pass->attachment_count);
4032      struct anv_attachment_state *att_state = &cmd_state->attachments[a];
4033
4034      struct anv_image_view *iview = fb->attachments[a];
4035      const struct anv_image *image = iview->image;
4036
4037      /* A resolve is necessary before use as an input attachment if the clear
4038       * color or auxiliary buffer usage isn't supported by the sampler.
4039       */
4040      const bool input_needs_resolve =
4041            (att_state->fast_clear && !att_state->clear_color_is_zero_one) ||
4042            att_state->input_aux_usage != att_state->aux_usage;
4043
4044      VkImageLayout target_layout;
4045      if (iview->aspect_mask & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV &&
4046          !input_needs_resolve) {
4047         /* Layout transitions before the final only help to enable sampling
4048          * as an input attachment. If the input attachment supports sampling
4049          * using the auxiliary surface, we can skip such transitions by
4050          * making the target layout one that is CCS-aware.
4051          */
4052         target_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
4053      } else {
4054         target_layout = subpass->attachments[i].layout;
4055      }
4056
4057      if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
4058         assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4059
4060         uint32_t base_layer, layer_count;
4061         if (image->type == VK_IMAGE_TYPE_3D) {
4062            base_layer = 0;
4063            layer_count = anv_minify(iview->image->extent.depth,
4064                                     iview->planes[0].isl.base_level);
4065         } else {
4066            base_layer = iview->planes[0].isl.base_array_layer;
4067            layer_count = fb->layers;
4068         }
4069
4070         transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4071                                 iview->planes[0].isl.base_level, 1,
4072                                 base_layer, layer_count,
4073                                 att_state->current_layout, target_layout);
4074      } else if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4075         transition_depth_buffer(cmd_buffer, image,
4076                                 att_state->current_layout, target_layout);
4077         att_state->aux_usage =
4078            anv_layout_to_aux_usage(&cmd_buffer->device->info, image,
4079                                    VK_IMAGE_ASPECT_DEPTH_BIT, target_layout);
4080      }
4081      att_state->current_layout = target_layout;
4082
4083      if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_COLOR_BIT) {
4084         assert(att_state->pending_clear_aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4085
4086         /* Multi-planar images are not supported as attachments */
4087         assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4088         assert(image->n_planes == 1);
4089
4090         uint32_t base_clear_layer = iview->planes[0].isl.base_array_layer;
4091         uint32_t clear_layer_count = fb->layers;
4092
4093         if (att_state->fast_clear &&
4094             do_first_layer_clear(cmd_state, att_state)) {
4095            /* We only support fast-clears on the first layer */
4096            assert(iview->planes[0].isl.base_level == 0);
4097            assert(iview->planes[0].isl.base_array_layer == 0);
4098
4099            union isl_color_value clear_color = {};
4100            anv_clear_color_from_att_state(&clear_color, att_state, iview);
4101            if (iview->image->samples == 1) {
4102               anv_image_ccs_op(cmd_buffer, image,
4103                                iview->planes[0].isl.format,
4104                                VK_IMAGE_ASPECT_COLOR_BIT,
4105                                0, 0, 1, ISL_AUX_OP_FAST_CLEAR,
4106                                &clear_color,
4107                                false);
4108            } else {
4109               anv_image_mcs_op(cmd_buffer, image,
4110                                iview->planes[0].isl.format,
4111                                VK_IMAGE_ASPECT_COLOR_BIT,
4112                                0, 1, ISL_AUX_OP_FAST_CLEAR,
4113                                &clear_color,
4114                                false);
4115            }
4116            base_clear_layer++;
4117            clear_layer_count--;
4118            if (is_multiview)
4119               att_state->pending_clear_views &= ~1;
4120
4121            if (att_state->clear_color_is_zero) {
4122               /* This image has the auxiliary buffer enabled. We can mark the
4123                * subresource as not needing a resolve because the clear color
4124                * will match what's in every RENDER_SURFACE_STATE object when
4125                * it's being used for sampling.
4126                */
4127               set_image_fast_clear_state(cmd_buffer, iview->image,
4128                                          VK_IMAGE_ASPECT_COLOR_BIT,
4129                                          ANV_FAST_CLEAR_DEFAULT_VALUE);
4130            } else {
4131               set_image_fast_clear_state(cmd_buffer, iview->image,
4132                                          VK_IMAGE_ASPECT_COLOR_BIT,
4133                                          ANV_FAST_CLEAR_ANY);
4134            }
4135         }
4136
4137         /* From the VkFramebufferCreateInfo spec:
4138          *
4139          * "If the render pass uses multiview, then layers must be one and each
4140          *  attachment requires a number of layers that is greater than the
4141          *  maximum bit index set in the view mask in the subpasses in which it
4142          *  is used."
4143          *
4144          * So if multiview is active we ignore the number of layers in the
4145          * framebuffer and instead we honor the view mask from the subpass.
4146          */
4147         if (is_multiview) {
4148            assert(image->n_planes == 1);
4149            uint32_t pending_clear_mask =
4150               get_multiview_subpass_clear_mask(cmd_state, att_state);
4151
4152            uint32_t layer_idx;
4153            for_each_bit(layer_idx, pending_clear_mask) {
4154               uint32_t layer =
4155                  iview->planes[0].isl.base_array_layer + layer_idx;
4156
4157               anv_image_clear_color(cmd_buffer, image,
4158                                     VK_IMAGE_ASPECT_COLOR_BIT,
4159                                     att_state->aux_usage,
4160                                     iview->planes[0].isl.format,
4161                                     iview->planes[0].isl.swizzle,
4162                                     iview->planes[0].isl.base_level,
4163                                     layer, 1,
4164                                     render_area,
4165                                     vk_to_isl_color(att_state->clear_value.color));
4166            }
4167
4168            att_state->pending_clear_views &= ~pending_clear_mask;
4169         } else if (clear_layer_count > 0) {
4170            assert(image->n_planes == 1);
4171            anv_image_clear_color(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4172                                  att_state->aux_usage,
4173                                  iview->planes[0].isl.format,
4174                                  iview->planes[0].isl.swizzle,
4175                                  iview->planes[0].isl.base_level,
4176                                  base_clear_layer, clear_layer_count,
4177                                  render_area,
4178                                  vk_to_isl_color(att_state->clear_value.color));
4179         }
4180      } else if (att_state->pending_clear_aspects & (VK_IMAGE_ASPECT_DEPTH_BIT |
4181                                                     VK_IMAGE_ASPECT_STENCIL_BIT)) {
4182         if (att_state->fast_clear && !is_multiview) {
4183            /* We currently only support HiZ for single-layer images */
4184            if (att_state->pending_clear_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4185               assert(iview->image->planes[0].aux_usage == ISL_AUX_USAGE_HIZ);
4186               assert(iview->planes[0].isl.base_level == 0);
4187               assert(iview->planes[0].isl.base_array_layer == 0);
4188               assert(fb->layers == 1);
4189            }
4190
4191            anv_image_hiz_clear(cmd_buffer, image,
4192                                att_state->pending_clear_aspects,
4193                                iview->planes[0].isl.base_level,
4194                                iview->planes[0].isl.base_array_layer,
4195                                fb->layers, render_area,
4196                                att_state->clear_value.depthStencil.stencil);
4197         } else if (is_multiview) {
4198            uint32_t pending_clear_mask =
4199              get_multiview_subpass_clear_mask(cmd_state, att_state);
4200
4201            uint32_t layer_idx;
4202            for_each_bit(layer_idx, pending_clear_mask) {
4203               uint32_t layer =
4204                  iview->planes[0].isl.base_array_layer + layer_idx;
4205
4206               anv_image_clear_depth_stencil(cmd_buffer, image,
4207                                             att_state->pending_clear_aspects,
4208                                             att_state->aux_usage,
4209                                             iview->planes[0].isl.base_level,
4210                                             layer, 1,
4211                                             render_area,
4212                                             att_state->clear_value.depthStencil.depth,
4213                                             att_state->clear_value.depthStencil.stencil);
4214            }
4215
4216            att_state->pending_clear_views &= ~pending_clear_mask;
4217         } else {
4218            anv_image_clear_depth_stencil(cmd_buffer, image,
4219                                          att_state->pending_clear_aspects,
4220                                          att_state->aux_usage,
4221                                          iview->planes[0].isl.base_level,
4222                                          iview->planes[0].isl.base_array_layer,
4223                                          fb->layers, render_area,
4224                                          att_state->clear_value.depthStencil.depth,
4225                                          att_state->clear_value.depthStencil.stencil);
4226         }
4227      } else  {
4228         assert(att_state->pending_clear_aspects == 0);
4229      }
4230
4231      if (GEN_GEN < 10 &&
4232          (att_state->pending_load_aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
4233          image->planes[0].aux_surface.isl.size_B > 0 &&
4234          iview->planes[0].isl.base_level == 0 &&
4235          iview->planes[0].isl.base_array_layer == 0) {
4236         if (att_state->aux_usage != ISL_AUX_USAGE_NONE) {
4237            genX(copy_fast_clear_dwords)(cmd_buffer, att_state->color.state,
4238                                         image, VK_IMAGE_ASPECT_COLOR_BIT,
4239                                         false /* copy to ss */);
4240         }
4241
4242         if (need_input_attachment_state(&cmd_state->pass->attachments[a]) &&
4243             att_state->input_aux_usage != ISL_AUX_USAGE_NONE) {
4244            genX(copy_fast_clear_dwords)(cmd_buffer, att_state->input.state,
4245                                         image, VK_IMAGE_ASPECT_COLOR_BIT,
4246                                         false /* copy to ss */);
4247         }
4248      }
4249
4250      if (subpass->attachments[i].usage ==
4251          VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) {
4252         /* We assume that if we're starting a subpass, we're going to do some
4253          * rendering so we may end up with compressed data.
4254          */
4255         genX(cmd_buffer_mark_image_written)(cmd_buffer, iview->image,
4256                                             VK_IMAGE_ASPECT_COLOR_BIT,
4257                                             att_state->aux_usage,
4258                                             iview->planes[0].isl.base_level,
4259                                             iview->planes[0].isl.base_array_layer,
4260                                             fb->layers);
4261      } else if (subpass->attachments[i].usage ==
4262                 VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) {
4263         /* We may be writing depth or stencil so we need to mark the surface.
4264          * Unfortunately, there's no way to know at this point whether the
4265          * depth or stencil tests used will actually write to the surface.
4266          *
4267          * Even though stencil may be plane 1, it always shares a base_level
4268          * with depth.
4269          */
4270         const struct isl_view *ds_view = &iview->planes[0].isl;
4271         if (iview->aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
4272            genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
4273                                                VK_IMAGE_ASPECT_DEPTH_BIT,
4274                                                att_state->aux_usage,
4275                                                ds_view->base_level,
4276                                                ds_view->base_array_layer,
4277                                                fb->layers);
4278         }
4279         if (iview->aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
4280            /* Even though stencil may be plane 1, it always shares a
4281             * base_level with depth.
4282             */
4283            genX(cmd_buffer_mark_image_written)(cmd_buffer, image,
4284                                                VK_IMAGE_ASPECT_STENCIL_BIT,
4285                                                ISL_AUX_USAGE_NONE,
4286                                                ds_view->base_level,
4287                                                ds_view->base_array_layer,
4288                                                fb->layers);
4289         }
4290      }
4291
4292      /* If multiview is enabled, then we are only done clearing when we no
4293       * longer have pending layers to clear, or when we have processed the
4294       * last subpass that uses this attachment.
4295       */
4296      if (!is_multiview ||
4297          att_state->pending_clear_views == 0 ||
4298          current_subpass_is_last_for_attachment(cmd_state, a)) {
4299         att_state->pending_clear_aspects = 0;
4300      }
4301
4302      att_state->pending_load_aspects = 0;
4303   }
4304
4305   cmd_buffer_emit_depth_stencil(cmd_buffer);
4306}
4307
4308static enum blorp_filter
4309vk_to_blorp_resolve_mode(VkResolveModeFlagBitsKHR vk_mode)
4310{
4311   switch (vk_mode) {
4312   case VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR:
4313      return BLORP_FILTER_SAMPLE_0;
4314   case VK_RESOLVE_MODE_AVERAGE_BIT_KHR:
4315      return BLORP_FILTER_AVERAGE;
4316   case VK_RESOLVE_MODE_MIN_BIT_KHR:
4317      return BLORP_FILTER_MIN_SAMPLE;
4318   case VK_RESOLVE_MODE_MAX_BIT_KHR:
4319      return BLORP_FILTER_MAX_SAMPLE;
4320   default:
4321      return BLORP_FILTER_NONE;
4322   }
4323}
4324
4325static void
4326cmd_buffer_end_subpass(struct anv_cmd_buffer *cmd_buffer)
4327{
4328   struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4329   struct anv_subpass *subpass = cmd_state->subpass;
4330   uint32_t subpass_id = anv_get_subpass_id(&cmd_buffer->state);
4331   struct anv_framebuffer *fb = cmd_buffer->state.framebuffer;
4332
4333   if (subpass->has_color_resolve) {
4334      /* We are about to do some MSAA resolves.  We need to flush so that the
4335       * result of writes to the MSAA color attachments show up in the sampler
4336       * when we blit to the single-sampled resolve target.
4337       */
4338      cmd_buffer->state.pending_pipe_bits |=
4339         ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
4340         ANV_PIPE_RENDER_TARGET_CACHE_FLUSH_BIT;
4341
4342      for (uint32_t i = 0; i < subpass->color_count; ++i) {
4343         uint32_t src_att = subpass->color_attachments[i].attachment;
4344         uint32_t dst_att = subpass->resolve_attachments[i].attachment;
4345
4346         if (dst_att == VK_ATTACHMENT_UNUSED)
4347            continue;
4348
4349         assert(src_att < cmd_buffer->state.pass->attachment_count);
4350         assert(dst_att < cmd_buffer->state.pass->attachment_count);
4351
4352         if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
4353            /* From the Vulkan 1.0 spec:
4354             *
4355             *    If the first use of an attachment in a render pass is as a
4356             *    resolve attachment, then the loadOp is effectively ignored
4357             *    as the resolve is guaranteed to overwrite all pixels in the
4358             *    render area.
4359             */
4360            cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
4361         }
4362
4363         struct anv_image_view *src_iview = fb->attachments[src_att];
4364         struct anv_image_view *dst_iview = fb->attachments[dst_att];
4365
4366         const VkRect2D render_area = cmd_buffer->state.render_area;
4367
4368         enum isl_aux_usage src_aux_usage =
4369            cmd_buffer->state.attachments[src_att].aux_usage;
4370         enum isl_aux_usage dst_aux_usage =
4371            cmd_buffer->state.attachments[dst_att].aux_usage;
4372
4373         assert(src_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT &&
4374                dst_iview->aspect_mask == VK_IMAGE_ASPECT_COLOR_BIT);
4375
4376         anv_image_msaa_resolve(cmd_buffer,
4377                                src_iview->image, src_aux_usage,
4378                                src_iview->planes[0].isl.base_level,
4379                                src_iview->planes[0].isl.base_array_layer,
4380                                dst_iview->image, dst_aux_usage,
4381                                dst_iview->planes[0].isl.base_level,
4382                                dst_iview->planes[0].isl.base_array_layer,
4383                                VK_IMAGE_ASPECT_COLOR_BIT,
4384                                render_area.offset.x, render_area.offset.y,
4385                                render_area.offset.x, render_area.offset.y,
4386                                render_area.extent.width,
4387                                render_area.extent.height,
4388                                fb->layers, BLORP_FILTER_NONE);
4389      }
4390   }
4391
4392   if (subpass->ds_resolve_attachment) {
4393      /* We are about to do some MSAA resolves.  We need to flush so that the
4394       * result of writes to the MSAA depth attachments show up in the sampler
4395       * when we blit to the single-sampled resolve target.
4396       */
4397      cmd_buffer->state.pending_pipe_bits |=
4398         ANV_PIPE_TEXTURE_CACHE_INVALIDATE_BIT |
4399         ANV_PIPE_DEPTH_CACHE_FLUSH_BIT;
4400
4401      uint32_t src_att = subpass->depth_stencil_attachment->attachment;
4402      uint32_t dst_att = subpass->ds_resolve_attachment->attachment;
4403
4404      assert(src_att < cmd_buffer->state.pass->attachment_count);
4405      assert(dst_att < cmd_buffer->state.pass->attachment_count);
4406
4407      if (cmd_buffer->state.attachments[dst_att].pending_clear_aspects) {
4408         /* From the Vulkan 1.0 spec:
4409          *
4410          *    If the first use of an attachment in a render pass is as a
4411          *    resolve attachment, then the loadOp is effectively ignored
4412          *    as the resolve is guaranteed to overwrite all pixels in the
4413          *    render area.
4414          */
4415         cmd_buffer->state.attachments[dst_att].pending_clear_aspects = 0;
4416      }
4417
4418      struct anv_image_view *src_iview = fb->attachments[src_att];
4419      struct anv_image_view *dst_iview = fb->attachments[dst_att];
4420
4421      const VkRect2D render_area = cmd_buffer->state.render_area;
4422
4423      if ((src_iview->image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) &&
4424          subpass->depth_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
4425
4426         struct anv_attachment_state *src_state =
4427            &cmd_state->attachments[src_att];
4428         struct anv_attachment_state *dst_state =
4429            &cmd_state->attachments[dst_att];
4430
4431         /* MSAA resolves sample from the source attachment.  Transition the
4432          * depth attachment first to get rid of any HiZ that we may not be
4433          * able to handle.
4434          */
4435         transition_depth_buffer(cmd_buffer, src_iview->image,
4436                                 src_state->current_layout,
4437                                 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
4438         src_state->aux_usage =
4439            anv_layout_to_aux_usage(&cmd_buffer->device->info, src_iview->image,
4440                                    VK_IMAGE_ASPECT_DEPTH_BIT,
4441                                    VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
4442         src_state->current_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
4443
4444         /* MSAA resolves write to the resolve attachment as if it were any
4445          * other transfer op.  Transition the resolve attachment accordingly.
4446          */
4447         VkImageLayout dst_initial_layout = dst_state->current_layout;
4448
4449         /* If our render area is the entire size of the image, we're going to
4450          * blow it all away so we can claim the initial layout is UNDEFINED
4451          * and we'll get a HiZ ambiguate instead of a resolve.
4452          */
4453         if (dst_iview->image->type != VK_IMAGE_TYPE_3D &&
4454             render_area.offset.x == 0 && render_area.offset.y == 0 &&
4455             render_area.extent.width == dst_iview->extent.width &&
4456             render_area.extent.height == dst_iview->extent.height)
4457            dst_initial_layout = VK_IMAGE_LAYOUT_UNDEFINED;
4458
4459         transition_depth_buffer(cmd_buffer, dst_iview->image,
4460                                 dst_initial_layout,
4461                                 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
4462         dst_state->aux_usage =
4463            anv_layout_to_aux_usage(&cmd_buffer->device->info, dst_iview->image,
4464                                    VK_IMAGE_ASPECT_DEPTH_BIT,
4465                                    VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
4466         dst_state->current_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
4467
4468         enum blorp_filter filter =
4469            vk_to_blorp_resolve_mode(subpass->depth_resolve_mode);
4470
4471         anv_image_msaa_resolve(cmd_buffer,
4472                                src_iview->image, src_state->aux_usage,
4473                                src_iview->planes[0].isl.base_level,
4474                                src_iview->planes[0].isl.base_array_layer,
4475                                dst_iview->image, dst_state->aux_usage,
4476                                dst_iview->planes[0].isl.base_level,
4477                                dst_iview->planes[0].isl.base_array_layer,
4478                                VK_IMAGE_ASPECT_DEPTH_BIT,
4479                                render_area.offset.x, render_area.offset.y,
4480                                render_area.offset.x, render_area.offset.y,
4481                                render_area.extent.width,
4482                                render_area.extent.height,
4483                                fb->layers, filter);
4484      }
4485
4486      if ((src_iview->image->aspects & VK_IMAGE_ASPECT_STENCIL_BIT) &&
4487          subpass->stencil_resolve_mode != VK_RESOLVE_MODE_NONE_KHR) {
4488
4489         enum isl_aux_usage src_aux_usage = ISL_AUX_USAGE_NONE;
4490         enum isl_aux_usage dst_aux_usage = ISL_AUX_USAGE_NONE;
4491
4492         enum blorp_filter filter =
4493            vk_to_blorp_resolve_mode(subpass->stencil_resolve_mode);
4494
4495         anv_image_msaa_resolve(cmd_buffer,
4496                                src_iview->image, src_aux_usage,
4497                                src_iview->planes[0].isl.base_level,
4498                                src_iview->planes[0].isl.base_array_layer,
4499                                dst_iview->image, dst_aux_usage,
4500                                dst_iview->planes[0].isl.base_level,
4501                                dst_iview->planes[0].isl.base_array_layer,
4502                                VK_IMAGE_ASPECT_STENCIL_BIT,
4503                                render_area.offset.x, render_area.offset.y,
4504                                render_area.offset.x, render_area.offset.y,
4505                                render_area.extent.width,
4506                                render_area.extent.height,
4507                                fb->layers, filter);
4508      }
4509   }
4510
4511   for (uint32_t i = 0; i < subpass->attachment_count; ++i) {
4512      const uint32_t a = subpass->attachments[i].attachment;
4513      if (a == VK_ATTACHMENT_UNUSED)
4514         continue;
4515
4516      if (cmd_state->pass->attachments[a].last_subpass_idx != subpass_id)
4517         continue;
4518
4519      assert(a < cmd_state->pass->attachment_count);
4520      struct anv_attachment_state *att_state = &cmd_state->attachments[a];
4521      struct anv_image_view *iview = fb->attachments[a];
4522      const struct anv_image *image = iview->image;
4523
4524      if ((image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) &&
4525          image->vk_format != iview->vk_format) {
4526         enum anv_fast_clear_type fast_clear_type =
4527            anv_layout_to_fast_clear_type(&cmd_buffer->device->info,
4528                                          image, VK_IMAGE_ASPECT_COLOR_BIT,
4529                                          att_state->current_layout);
4530
4531         /* If any clear color was used, flush it down the aux surfaces. If we
4532          * don't do it now using the view's format we might use the clear
4533          * color incorrectly in the following resolves (for example with an
4534          * SRGB view & a UNORM image).
4535          */
4536         if (fast_clear_type != ANV_FAST_CLEAR_NONE) {
4537            anv_perf_warn(cmd_buffer->device->instance, fb,
4538                          "Doing a partial resolve to get rid of clear color at the "
4539                          "end of a renderpass due to an image/view format mismatch");
4540
4541            uint32_t base_layer, layer_count;
4542            if (image->type == VK_IMAGE_TYPE_3D) {
4543               base_layer = 0;
4544               layer_count = anv_minify(iview->image->extent.depth,
4545                                        iview->planes[0].isl.base_level);
4546            } else {
4547               base_layer = iview->planes[0].isl.base_array_layer;
4548               layer_count = fb->layers;
4549            }
4550
4551            for (uint32_t a = 0; a < layer_count; a++) {
4552               uint32_t array_layer = base_layer + a;
4553               if (image->samples == 1) {
4554                  anv_cmd_predicated_ccs_resolve(cmd_buffer, image,
4555                                                 iview->planes[0].isl.format,
4556                                                 VK_IMAGE_ASPECT_COLOR_BIT,
4557                                                 iview->planes[0].isl.base_level,
4558                                                 array_layer,
4559                                                 ISL_AUX_OP_PARTIAL_RESOLVE,
4560                                                 ANV_FAST_CLEAR_NONE);
4561               } else {
4562                  anv_cmd_predicated_mcs_resolve(cmd_buffer, image,
4563                                                 iview->planes[0].isl.format,
4564                                                 VK_IMAGE_ASPECT_COLOR_BIT,
4565                                                 base_layer,
4566                                                 ISL_AUX_OP_PARTIAL_RESOLVE,
4567                                                 ANV_FAST_CLEAR_NONE);
4568               }
4569            }
4570         }
4571      }
4572
4573      /* Transition the image into the final layout for this render pass */
4574      VkImageLayout target_layout =
4575         cmd_state->pass->attachments[a].final_layout;
4576
4577      if (image->aspects & VK_IMAGE_ASPECT_ANY_COLOR_BIT_ANV) {
4578         assert(image->aspects == VK_IMAGE_ASPECT_COLOR_BIT);
4579
4580         uint32_t base_layer, layer_count;
4581         if (image->type == VK_IMAGE_TYPE_3D) {
4582            base_layer = 0;
4583            layer_count = anv_minify(iview->image->extent.depth,
4584                                     iview->planes[0].isl.base_level);
4585         } else {
4586            base_layer = iview->planes[0].isl.base_array_layer;
4587            layer_count = fb->layers;
4588         }
4589
4590         transition_color_buffer(cmd_buffer, image, VK_IMAGE_ASPECT_COLOR_BIT,
4591                                 iview->planes[0].isl.base_level, 1,
4592                                 base_layer, layer_count,
4593                                 att_state->current_layout, target_layout);
4594      } else if (image->aspects & VK_IMAGE_ASPECT_DEPTH_BIT) {
4595         transition_depth_buffer(cmd_buffer, image,
4596                                 att_state->current_layout, target_layout);
4597      }
4598   }
4599
4600   /* Accumulate any subpass flushes that need to happen after the subpass.
4601    * Yes, they do get accumulated twice in the NextSubpass case but since
4602    * genX_CmdNextSubpass just calls end/begin back-to-back, we just end up
4603    * ORing the bits in twice so it's harmless.
4604    */
4605   cmd_buffer->state.pending_pipe_bits |=
4606      cmd_buffer->state.pass->subpass_flushes[subpass_id + 1];
4607}
4608
4609void genX(CmdBeginRenderPass)(
4610    VkCommandBuffer                             commandBuffer,
4611    const VkRenderPassBeginInfo*                pRenderPassBegin,
4612    VkSubpassContents                           contents)
4613{
4614   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4615   ANV_FROM_HANDLE(anv_render_pass, pass, pRenderPassBegin->renderPass);
4616   ANV_FROM_HANDLE(anv_framebuffer, framebuffer, pRenderPassBegin->framebuffer);
4617
4618   cmd_buffer->state.framebuffer = framebuffer;
4619   cmd_buffer->state.pass = pass;
4620   cmd_buffer->state.render_area = pRenderPassBegin->renderArea;
4621   VkResult result =
4622      genX(cmd_buffer_setup_attachments)(cmd_buffer, pass, pRenderPassBegin);
4623
4624   /* If we failed to setup the attachments we should not try to go further */
4625   if (result != VK_SUCCESS) {
4626      assert(anv_batch_has_error(&cmd_buffer->batch));
4627      return;
4628   }
4629
4630   genX(flush_pipeline_select_3d)(cmd_buffer);
4631
4632   cmd_buffer_begin_subpass(cmd_buffer, 0);
4633}
4634
4635void genX(CmdBeginRenderPass2KHR)(
4636    VkCommandBuffer                             commandBuffer,
4637    const VkRenderPassBeginInfo*                pRenderPassBeginInfo,
4638    const VkSubpassBeginInfoKHR*                pSubpassBeginInfo)
4639{
4640   genX(CmdBeginRenderPass)(commandBuffer, pRenderPassBeginInfo,
4641                            pSubpassBeginInfo->contents);
4642}
4643
4644void genX(CmdNextSubpass)(
4645    VkCommandBuffer                             commandBuffer,
4646    VkSubpassContents                           contents)
4647{
4648   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4649
4650   if (anv_batch_has_error(&cmd_buffer->batch))
4651      return;
4652
4653   assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
4654
4655   uint32_t prev_subpass = anv_get_subpass_id(&cmd_buffer->state);
4656   cmd_buffer_end_subpass(cmd_buffer);
4657   cmd_buffer_begin_subpass(cmd_buffer, prev_subpass + 1);
4658}
4659
4660void genX(CmdNextSubpass2KHR)(
4661    VkCommandBuffer                             commandBuffer,
4662    const VkSubpassBeginInfoKHR*                pSubpassBeginInfo,
4663    const VkSubpassEndInfoKHR*                  pSubpassEndInfo)
4664{
4665   genX(CmdNextSubpass)(commandBuffer, pSubpassBeginInfo->contents);
4666}
4667
4668void genX(CmdEndRenderPass)(
4669    VkCommandBuffer                             commandBuffer)
4670{
4671   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4672
4673   if (anv_batch_has_error(&cmd_buffer->batch))
4674      return;
4675
4676   cmd_buffer_end_subpass(cmd_buffer);
4677
4678   cmd_buffer->state.hiz_enabled = false;
4679
4680#ifndef NDEBUG
4681   anv_dump_add_framebuffer(cmd_buffer, cmd_buffer->state.framebuffer);
4682#endif
4683
4684   /* Remove references to render pass specific state. This enables us to
4685    * detect whether or not we're in a renderpass.
4686    */
4687   cmd_buffer->state.framebuffer = NULL;
4688   cmd_buffer->state.pass = NULL;
4689   cmd_buffer->state.subpass = NULL;
4690}
4691
4692void genX(CmdEndRenderPass2KHR)(
4693    VkCommandBuffer                             commandBuffer,
4694    const VkSubpassEndInfoKHR*                  pSubpassEndInfo)
4695{
4696   genX(CmdEndRenderPass)(commandBuffer);
4697}
4698
4699void
4700genX(cmd_emit_conditional_render_predicate)(struct anv_cmd_buffer *cmd_buffer)
4701{
4702#if GEN_GEN >= 8 || GEN_IS_HASWELL
4703   struct gen_mi_builder b;
4704   gen_mi_builder_init(&b, &cmd_buffer->batch);
4705
4706   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC0),
4707                    gen_mi_reg32(ANV_PREDICATE_RESULT_REG));
4708   gen_mi_store(&b, gen_mi_reg64(MI_PREDICATE_SRC1), gen_mi_imm(0));
4709
4710   anv_batch_emit(&cmd_buffer->batch, GENX(MI_PREDICATE), mip) {
4711      mip.LoadOperation    = LOAD_LOADINV;
4712      mip.CombineOperation = COMBINE_SET;
4713      mip.CompareOperation = COMPARE_SRCS_EQUAL;
4714   }
4715#endif
4716}
4717
4718#if GEN_GEN >= 8 || GEN_IS_HASWELL
4719void genX(CmdBeginConditionalRenderingEXT)(
4720   VkCommandBuffer                             commandBuffer,
4721   const VkConditionalRenderingBeginInfoEXT*   pConditionalRenderingBegin)
4722{
4723   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4724   ANV_FROM_HANDLE(anv_buffer, buffer, pConditionalRenderingBegin->buffer);
4725   struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4726   struct anv_address value_address =
4727      anv_address_add(buffer->address, pConditionalRenderingBegin->offset);
4728
4729   const bool isInverted = pConditionalRenderingBegin->flags &
4730                           VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT;
4731
4732   cmd_state->conditional_render_enabled = true;
4733
4734   genX(cmd_buffer_apply_pipe_flushes)(cmd_buffer);
4735
4736   struct gen_mi_builder b;
4737   gen_mi_builder_init(&b, &cmd_buffer->batch);
4738
4739   /* Section 19.4 of the Vulkan 1.1.85 spec says:
4740    *
4741    *    If the value of the predicate in buffer memory changes
4742    *    while conditional rendering is active, the rendering commands
4743    *    may be discarded in an implementation-dependent way.
4744    *    Some implementations may latch the value of the predicate
4745    *    upon beginning conditional rendering while others
4746    *    may read it before every rendering command.
4747    *
4748    * So it's perfectly fine to read a value from the buffer once.
4749    */
4750   struct gen_mi_value value =  gen_mi_mem32(value_address);
4751
4752   /* Precompute predicate result, it is necessary to support secondary
4753    * command buffers since it is unknown if conditional rendering is
4754    * inverted when populating them.
4755    */
4756   gen_mi_store(&b, gen_mi_reg64(ANV_PREDICATE_RESULT_REG),
4757                    isInverted ? gen_mi_uge(&b, gen_mi_imm(0), value) :
4758                                 gen_mi_ult(&b, gen_mi_imm(0), value));
4759}
4760
4761void genX(CmdEndConditionalRenderingEXT)(
4762	VkCommandBuffer                             commandBuffer)
4763{
4764   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4765   struct anv_cmd_state *cmd_state = &cmd_buffer->state;
4766
4767   cmd_state->conditional_render_enabled = false;
4768}
4769#endif
4770
4771/* Set of stage bits for which are pipelined, i.e. they get queued by the
4772 * command streamer for later execution.
4773 */
4774#define ANV_PIPELINE_STAGE_PIPELINED_BITS \
4775   (VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | \
4776    VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | \
4777    VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | \
4778    VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | \
4779    VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | \
4780    VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | \
4781    VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | \
4782    VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | \
4783    VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | \
4784    VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | \
4785    VK_PIPELINE_STAGE_TRANSFER_BIT | \
4786    VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | \
4787    VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | \
4788    VK_PIPELINE_STAGE_ALL_COMMANDS_BIT)
4789
4790void genX(CmdSetEvent)(
4791    VkCommandBuffer                             commandBuffer,
4792    VkEvent                                     _event,
4793    VkPipelineStageFlags                        stageMask)
4794{
4795   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4796   ANV_FROM_HANDLE(anv_event, event, _event);
4797
4798   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4799      if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
4800         pc.StallAtPixelScoreboard = true;
4801         pc.CommandStreamerStallEnable = true;
4802      }
4803
4804      pc.DestinationAddressType  = DAT_PPGTT,
4805      pc.PostSyncOperation       = WriteImmediateData,
4806      pc.Address = (struct anv_address) {
4807         cmd_buffer->device->dynamic_state_pool.block_pool.bo,
4808         event->state.offset
4809      };
4810      pc.ImmediateData           = VK_EVENT_SET;
4811   }
4812}
4813
4814void genX(CmdResetEvent)(
4815    VkCommandBuffer                             commandBuffer,
4816    VkEvent                                     _event,
4817    VkPipelineStageFlags                        stageMask)
4818{
4819   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4820   ANV_FROM_HANDLE(anv_event, event, _event);
4821
4822   anv_batch_emit(&cmd_buffer->batch, GENX(PIPE_CONTROL), pc) {
4823      if (stageMask & ANV_PIPELINE_STAGE_PIPELINED_BITS) {
4824         pc.StallAtPixelScoreboard = true;
4825         pc.CommandStreamerStallEnable = true;
4826      }
4827
4828      pc.DestinationAddressType  = DAT_PPGTT;
4829      pc.PostSyncOperation       = WriteImmediateData;
4830      pc.Address = (struct anv_address) {
4831         cmd_buffer->device->dynamic_state_pool.block_pool.bo,
4832         event->state.offset
4833      };
4834      pc.ImmediateData           = VK_EVENT_RESET;
4835   }
4836}
4837
4838void genX(CmdWaitEvents)(
4839    VkCommandBuffer                             commandBuffer,
4840    uint32_t                                    eventCount,
4841    const VkEvent*                              pEvents,
4842    VkPipelineStageFlags                        srcStageMask,
4843    VkPipelineStageFlags                        destStageMask,
4844    uint32_t                                    memoryBarrierCount,
4845    const VkMemoryBarrier*                      pMemoryBarriers,
4846    uint32_t                                    bufferMemoryBarrierCount,
4847    const VkBufferMemoryBarrier*                pBufferMemoryBarriers,
4848    uint32_t                                    imageMemoryBarrierCount,
4849    const VkImageMemoryBarrier*                 pImageMemoryBarriers)
4850{
4851#if GEN_GEN >= 8
4852   ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer, commandBuffer);
4853
4854   for (uint32_t i = 0; i < eventCount; i++) {
4855      ANV_FROM_HANDLE(anv_event, event, pEvents[i]);
4856
4857      anv_batch_emit(&cmd_buffer->batch, GENX(MI_SEMAPHORE_WAIT), sem) {
4858         sem.WaitMode            = PollingMode,
4859         sem.CompareOperation    = COMPARE_SAD_EQUAL_SDD,
4860         sem.SemaphoreDataDword  = VK_EVENT_SET,
4861         sem.SemaphoreAddress = (struct anv_address) {
4862            cmd_buffer->device->dynamic_state_pool.block_pool.bo,
4863            event->state.offset
4864         };
4865      }
4866   }
4867#else
4868   anv_finishme("Implement events on gen7");
4869#endif
4870
4871   genX(CmdPipelineBarrier)(commandBuffer, srcStageMask, destStageMask,
4872                            false, /* byRegion */
4873                            memoryBarrierCount, pMemoryBarriers,
4874                            bufferMemoryBarrierCount, pBufferMemoryBarriers,
4875                            imageMemoryBarrierCount, pImageMemoryBarriers);
4876}
4877