iris: Pin HiZ buffers when rendering.
[mesa.git] / src / gallium / drivers / iris / iris_state.c
index f41bf1430c70cb6904b763b635219bc0466e19dd..45d90e42515f8c87f6e8ffbb8dcb10649e0e5cc4 100644 (file)
 #include "intel/common/gen_sample_positions.h"
 #include "iris_batch.h"
 #include "iris_context.h"
+#include "iris_defines.h"
 #include "iris_pipe.h"
 #include "iris_resource.h"
 
@@ -160,7 +161,19 @@ __gen_combine_address(struct iris_batch *batch, void *location,
 #include "genxml/gen_macros.h"
 #include "genxml/genX_bits.h"
 
-#define MOCS_WB (2 << 1)
+#if GEN_GEN == 8
+#define MOCS_PTE 0x18
+#define MOCS_WB 0x78
+#else
+#define MOCS_PTE (1 << 1)
+#define MOCS_WB  (2 << 1)
+#endif
+
+static uint32_t
+mocs(struct iris_bo *bo)
+{
+   return bo && bo->external ? MOCS_PTE : MOCS_WB;
+}
 
 /**
  * Statically assert that PIPE_* enums match the hardware packets.
@@ -486,7 +499,7 @@ _iris_emit_lri(struct iris_batch *batch, uint32_t reg, uint32_t val)
 #define iris_emit_lri(b, r, v) _iris_emit_lri(b, GENX(r##_num), v)
 
 static void
-_iris_emit_lrr(struct iris_batch *batch, uint32_t src, uint32_t dst)
+_iris_emit_lrr(struct iris_batch *batch, uint32_t dst, uint32_t src)
 {
    iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_REG), lrr) {
       lrr.SourceRegisterAddress = src;
@@ -575,15 +588,11 @@ init_state_base_address(struct iris_batch *batch)
     * updated occasionally.  See iris_binder.c for the details there.
     */
    iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
-   #if 0
-   // XXX: MOCS is stupid for this.
-      sba.GeneralStateMemoryObjectControlState            = MOCS_WB;
-      sba.StatelessDataPortAccessMemoryObjectControlState = MOCS_WB;
-      sba.DynamicStateMemoryObjectControlState            = MOCS_WB;
-      sba.IndirectObjectMemoryObjectControlState          = MOCS_WB;
-      sba.InstructionMemoryObjectControlState             = MOCS_WB;
-      sba.BindlessSurfaceStateMemoryObjectControlState    = MOCS_WB;
-   #endif
+      sba.GeneralStateMOCS            = MOCS_WB;
+      sba.StatelessDataPortAccessMOCS = MOCS_WB;
+      sba.DynamicStateMOCS            = MOCS_WB;
+      sba.IndirectObjectMOCS          = MOCS_WB;
+      sba.InstructionMOCS             = MOCS_WB;
 
       sba.GeneralStateBaseAddressModifyEnable   = true;
       sba.DynamicStateBaseAddressModifyEnable   = true;
@@ -591,7 +600,10 @@ init_state_base_address(struct iris_batch *batch)
       sba.InstructionBaseAddressModifyEnable    = true;
       sba.GeneralStateBufferSizeModifyEnable    = true;
       sba.DynamicStateBufferSizeModifyEnable    = true;
+#if (GEN_GEN >= 9)
       sba.BindlessSurfaceStateBaseAddressModifyEnable = true;
+      sba.BindlessSurfaceStateMOCS    = MOCS_WB;
+#endif
       sba.IndirectObjectBufferSizeModifyEnable  = true;
       sba.InstructionBuffersizeModifyEnable     = true;
 
@@ -605,6 +617,41 @@ init_state_base_address(struct iris_batch *batch)
    }
 }
 
+static void
+iris_emit_l3_config(struct iris_batch *batch, const struct gen_l3_config *cfg,
+                    bool has_slm, bool wants_dc_cache)
+{
+   uint32_t reg_val;
+   iris_pack_state(GENX(L3CNTLREG), &reg_val, reg) {
+      reg.SLMEnable = has_slm;
+#if GEN_GEN == 11
+      /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
+       * in L3CNTLREG register. The default setting of the bit is not the
+       * desirable behavior.
+       */
+      reg.ErrorDetectionBehaviorControl = true;
+#endif
+      reg.URBAllocation = cfg->n[GEN_L3P_URB];
+      reg.ROAllocation = cfg->n[GEN_L3P_RO];
+      reg.DCAllocation = cfg->n[GEN_L3P_DC];
+      reg.AllAllocation = cfg->n[GEN_L3P_ALL];
+   }
+   iris_emit_lri(batch, L3CNTLREG, reg_val);
+}
+
+static void
+iris_emit_default_l3_config(struct iris_batch *batch,
+                            const struct gen_device_info *devinfo,
+                            bool compute)
+{
+   bool wants_dc_cache = true;
+   bool has_slm = compute;
+   const struct gen_l3_weights w =
+      gen_get_default_l3_weights(devinfo, wants_dc_cache, has_slm);
+   const struct gen_l3_config *cfg = gen_get_l3_config(devinfo, w);
+   iris_emit_l3_config(batch, cfg, has_slm, wants_dc_cache);
+}
+
 /**
  * Upload the initial GPU state for a render context.
  *
@@ -622,14 +669,23 @@ iris_init_render_context(struct iris_screen *screen,
 
    emit_pipeline_select(batch, _3D);
 
+   iris_emit_default_l3_config(batch, devinfo, false);
+
    init_state_base_address(batch);
 
-   // XXX: INSTPM on Gen8
+#if GEN_GEN >= 9
    iris_pack_state(GENX(CS_DEBUG_MODE2), &reg_val, reg) {
       reg.CONSTANT_BUFFERAddressOffsetDisable = true;
       reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
    }
    iris_emit_lri(batch, CS_DEBUG_MODE2, reg_val);
+#else
+   iris_pack_state(GENX(INSTPM), &reg_val, reg) {
+      reg.CONSTANT_BUFFERAddressOffsetDisable = true;
+      reg.CONSTANT_BUFFERAddressOffsetDisableMask = true;
+   }
+   iris_emit_lri(batch, INSTPM, reg_val);
+#endif
 
 #if GEN_GEN == 9
    iris_pack_state(GENX(CACHE_MODE_1), &reg_val, reg) {
@@ -670,7 +726,9 @@ iris_init_render_context(struct iris_screen *screen,
       GEN_SAMPLE_POS_2X(pat._2xSample);
       GEN_SAMPLE_POS_4X(pat._4xSample);
       GEN_SAMPLE_POS_8X(pat._8xSample);
+#if GEN_GEN >= 9
       GEN_SAMPLE_POS_16X(pat._16xSample);
+#endif
    }
 
    /* Use the legacy AA line coverage computation. */
@@ -683,11 +741,11 @@ iris_init_render_context(struct iris_screen *screen,
    iris_emit_cmd(batch, GENX(3DSTATE_WM_HZ_OP), foo);
 
    /* No polygon stippling offsets are necessary. */
-   // XXX: may need to set an offset for origin-UL framebuffers
+   /* TODO: may need to set an offset for origin-UL framebuffers */
    iris_emit_cmd(batch, GENX(3DSTATE_POLY_STIPPLE_OFFSET), foo);
 
    /* Set a static partitioning of the push constant area. */
-   // XXX: this may be a bad idea...could starve the push ringbuffers...
+   /* TODO: this may be a bad idea...could starve the push ringbuffers... */
    for (int i = 0; i <= MESA_SHADER_FRAGMENT; i++) {
       iris_emit_cmd(batch, GENX(3DSTATE_PUSH_CONSTANT_ALLOC_VS), alloc) {
          alloc._3DCommandSubOpcode = 18 + i;
@@ -707,29 +765,7 @@ iris_init_compute_context(struct iris_screen *screen,
 
    emit_pipeline_select(batch, GPGPU);
 
-   const bool has_slm = true;
-   const bool wants_dc_cache = true;
-
-   const struct gen_l3_weights w =
-      gen_get_default_l3_weights(devinfo, wants_dc_cache, has_slm);
-   const struct gen_l3_config *cfg = gen_get_l3_config(devinfo, w);
-
-   uint32_t reg_val;
-   iris_pack_state(GENX(L3CNTLREG), &reg_val, reg) {
-      reg.SLMEnable = has_slm;
-#if GEN_GEN == 11
-      /* WA_1406697149: Bit 9 "Error Detection Behavior Control" must be set
-       * in L3CNTLREG register. The default setting of the bit is not the
-       * desirable behavior.
-       */
-      reg.ErrorDetectionBehaviorControl = true;
-#endif
-      reg.URBAllocation = cfg->n[GEN_L3P_URB];
-      reg.ROAllocation = cfg->n[GEN_L3P_RO];
-      reg.DCAllocation = cfg->n[GEN_L3P_DC];
-      reg.AllAllocation = cfg->n[GEN_L3P_ALL];
-   }
-   iris_emit_lri(batch, L3CNTLREG, reg_val);
+   iris_emit_default_l3_config(batch, devinfo, true);
 
    init_state_base_address(batch);
 
@@ -740,14 +776,11 @@ iris_init_compute_context(struct iris_screen *screen,
 }
 
 struct iris_vertex_buffer_state {
-   /** The 3DSTATE_VERTEX_BUFFERS hardware packet. */
-   uint32_t vertex_buffers[1 + 33 * GENX(VERTEX_BUFFER_STATE_length)];
+   /** The VERTEX_BUFFER_STATE hardware structure. */
+   uint32_t state[GENX(VERTEX_BUFFER_STATE_length)];
 
    /** The resource to source vertex data from. */
-   struct pipe_resource *resources[33];
-
-   /** The number of bound vertex buffers. */
-   unsigned num_buffers;
+   struct pipe_resource *resource;
 };
 
 struct iris_depth_buffer_state {
@@ -765,14 +798,11 @@ struct iris_depth_buffer_state {
  * packets which vary by generation.
  */
 struct iris_genx_state {
-   /** SF_CLIP_VIEWPORT */
-   uint32_t sf_cl_vp[GENX(SF_CLIP_VIEWPORT_length) * IRIS_MAX_VIEWPORTS];
+   struct iris_vertex_buffer_state vertex_buffers[33];
 
-   struct iris_vertex_buffer_state vertex_buffers;
    struct iris_depth_buffer_state depth_buffer;
 
    uint32_t so_buffers[4 * GENX(3DSTATE_SO_BUFFER_length)];
-   uint32_t streamout[4 * GENX(3DSTATE_STREAMOUT_length)];
 };
 
 /**
@@ -803,8 +833,28 @@ struct iris_blend_state {
                         BRW_MAX_DRAW_BUFFERS * GENX(BLEND_STATE_ENTRY_length)];
 
    bool alpha_to_coverage; /* for shader key */
+
+   /** Bitfield of whether blending is enabled for RT[i] - for aux resolves */
+   uint8_t blend_enables;
+
+   /** Bitfield of whether color writes are enabled for RT[i] */
+   uint8_t color_write_enables;
 };
 
+static enum pipe_blendfactor
+fix_blendfactor(enum pipe_blendfactor f, bool alpha_to_one)
+{
+   if (alpha_to_one) {
+      if (f == PIPE_BLENDFACTOR_SRC1_ALPHA)
+         return PIPE_BLENDFACTOR_ONE;
+
+      if (f == PIPE_BLENDFACTOR_INV_SRC1_ALPHA)
+         return PIPE_BLENDFACTOR_ZERO;
+   }
+
+   return f;
+}
+
 /**
  * The pipe->create_blend_state() driver hook.
  *
@@ -817,6 +867,10 @@ iris_create_blend_state(struct pipe_context *ctx,
    struct iris_blend_state *cso = malloc(sizeof(struct iris_blend_state));
    uint32_t *blend_entry = cso->blend_state + GENX(BLEND_STATE_length);
 
+   cso->blend_enables = 0;
+   cso->color_write_enables = 0;
+   STATIC_ASSERT(BRW_MAX_DRAW_BUFFERS <= 8);
+
    cso->alpha_to_coverage = state->alpha_to_coverage;
 
    bool indep_alpha_blend = false;
@@ -825,11 +879,25 @@ iris_create_blend_state(struct pipe_context *ctx,
       const struct pipe_rt_blend_state *rt =
          &state->rt[state->independent_blend_enable ? i : 0];
 
+      enum pipe_blendfactor src_rgb =
+         fix_blendfactor(rt->rgb_src_factor, state->alpha_to_one);
+      enum pipe_blendfactor src_alpha =
+         fix_blendfactor(rt->alpha_src_factor, state->alpha_to_one);
+      enum pipe_blendfactor dst_rgb =
+         fix_blendfactor(rt->rgb_dst_factor, state->alpha_to_one);
+      enum pipe_blendfactor dst_alpha =
+         fix_blendfactor(rt->alpha_dst_factor, state->alpha_to_one);
+
       if (rt->rgb_func != rt->alpha_func ||
-          rt->rgb_src_factor != rt->alpha_src_factor ||
-          rt->rgb_dst_factor != rt->alpha_dst_factor)
+          src_rgb != src_alpha || dst_rgb != dst_alpha)
          indep_alpha_blend = true;
 
+      if (rt->blend_enable)
+         cso->blend_enables |= 1u << i;
+
+      if (rt->colormask)
+         cso->color_write_enables |= 1u << i;
+
       iris_pack_state(GENX(BLEND_STATE_ENTRY), blend_entry, be) {
          be.LogicOpEnable = state->logicop_enable;
          be.LogicOpFunction = state->logicop_func;
@@ -843,10 +911,10 @@ iris_create_blend_state(struct pipe_context *ctx,
 
          be.ColorBlendFunction          = rt->rgb_func;
          be.AlphaBlendFunction          = rt->alpha_func;
-         be.SourceBlendFactor           = rt->rgb_src_factor;
-         be.SourceAlphaBlendFactor      = rt->alpha_src_factor;
-         be.DestinationBlendFactor      = rt->rgb_dst_factor;
-         be.DestinationAlphaBlendFactor = rt->alpha_dst_factor;
+         be.SourceBlendFactor           = src_rgb;
+         be.SourceAlphaBlendFactor      = src_alpha;
+         be.DestinationBlendFactor      = dst_rgb;
+         be.DestinationAlphaBlendFactor = dst_alpha;
 
          be.WriteDisableRed   = !(rt->colormask & PIPE_MASK_R);
          be.WriteDisableGreen = !(rt->colormask & PIPE_MASK_G);
@@ -864,10 +932,14 @@ iris_create_blend_state(struct pipe_context *ctx,
 
       pb.ColorBufferBlendEnable = state->rt[0].blend_enable;
 
-      pb.SourceBlendFactor           = state->rt[0].rgb_src_factor;
-      pb.SourceAlphaBlendFactor      = state->rt[0].alpha_src_factor;
-      pb.DestinationBlendFactor      = state->rt[0].rgb_dst_factor;
-      pb.DestinationAlphaBlendFactor = state->rt[0].alpha_dst_factor;
+      pb.SourceBlendFactor =
+         fix_blendfactor(state->rt[0].rgb_src_factor, state->alpha_to_one);
+      pb.SourceAlphaBlendFactor =
+         fix_blendfactor(state->rt[0].alpha_src_factor, state->alpha_to_one);
+      pb.DestinationBlendFactor =
+         fix_blendfactor(state->rt[0].rgb_dst_factor, state->alpha_to_one);
+      pb.DestinationAlphaBlendFactor =
+         fix_blendfactor(state->rt[0].alpha_dst_factor, state->alpha_to_one);
    }
 
    iris_pack_state(GENX(BLEND_STATE), cso->blend_state, bs) {
@@ -892,12 +964,35 @@ static void
 iris_bind_blend_state(struct pipe_context *ctx, void *state)
 {
    struct iris_context *ice = (struct iris_context *) ctx;
-   ice->state.cso_blend = state;
+   struct iris_blend_state *cso = state;
+
+   ice->state.cso_blend = cso;
+   ice->state.blend_enables = cso ? cso->blend_enables : 0;
+
    ice->state.dirty |= IRIS_DIRTY_PS_BLEND;
    ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
    ice->state.dirty |= ice->state.dirty_for_nos[IRIS_NOS_BLEND];
 }
 
+/**
+ * Return true if the FS writes to any color outputs which are not disabled
+ * via color masking.
+ */
+static bool
+has_writeable_rt(const struct iris_blend_state *cso_blend,
+                 const struct shader_info *fs_info)
+{
+   if (!fs_info)
+      return false;
+
+   unsigned rt_outputs = fs_info->outputs_written >> FRAG_RESULT_DATA0;
+
+   if (fs_info->outputs_written & BITFIELD64_BIT(FRAG_RESULT_COLOR))
+      rt_outputs = (1 << BRW_MAX_DRAW_BUFFERS) - 1;
+
+   return cso_blend->color_write_enables & rt_outputs;
+}
+
 /**
  * Gallium CSO for depth, stencil, and alpha testing state.
  */
@@ -1016,7 +1111,7 @@ struct iris_rasterizer_state {
    bool flatshade_first; /* for stream output */
    bool clamp_fragment_color; /* for shader state */
    bool light_twoside; /* for shader state */
-   bool rasterizer_discard; /* for 3DSTATE_STREAMOUT */
+   bool rasterizer_discard; /* for 3DSTATE_STREAMOUT and 3DSTATE_CLIP */
    bool half_pixel_center; /* for 3DSTATE_MULTISAMPLE */
    bool line_stipple_enable;
    bool poly_stipple_enable;
@@ -1066,22 +1161,6 @@ iris_create_rasterizer_state(struct pipe_context *ctx,
    struct iris_rasterizer_state *cso =
       malloc(sizeof(struct iris_rasterizer_state));
 
-#if 0
-   point_quad_rasterization -> SBE?
-
-   not necessary?
-   {
-      poly_smooth
-      force_persample_interp - ?
-      bottom_edge_rule
-
-      offset_units_unscaled - cap not exposed
-   }
-   #endif
-
-   // XXX: it may make more sense just to store the pipe_rasterizer_state,
-   // we're copying a lot of booleans here.  But we don't need all of them...
-
    cso->multisample = state->multisample;
    cso->force_persample_interp = state->force_persample_interp;
    cso->clip_halfz = state->clip_halfz;
@@ -1113,7 +1192,8 @@ iris_create_rasterizer_state(struct pipe_context *ctx,
          state->line_smooth ? _10pixels : _05pixels;
       sf.LastPixelEnable = state->line_last_pixel;
       sf.LineWidth = line_width;
-      sf.SmoothPointEnable = state->point_smooth || state->multisample;
+      sf.SmoothPointEnable = (state->point_smooth || state->multisample) &&
+                             !state->point_quad_rasterization;
       sf.PointWidthSource = state->point_size_per_vertex ? Vertex : State;
       sf.PointWidth = state->point_size;
 
@@ -1138,12 +1218,16 @@ iris_create_rasterizer_state(struct pipe_context *ctx,
       rr.GlobalDepthOffsetConstant = state->offset_units * 2;
       rr.GlobalDepthOffsetScale = state->offset_scale;
       rr.GlobalDepthOffsetClamp = state->offset_clamp;
-      rr.SmoothPointEnable = state->point_smooth || state->multisample;
+      rr.SmoothPointEnable = state->point_smooth;
       rr.AntialiasingEnable = state->line_smooth;
       rr.ScissorRectangleEnable = state->scissor;
+#if GEN_GEN >= 9
       rr.ViewportZNearClipTestEnable = state->depth_clip_near;
       rr.ViewportZFarClipTestEnable = state->depth_clip_far;
-      //rr.ConservativeRasterizationEnable = not yet supported by Gallium...
+#else
+      rr.ViewportZClipTestEnable = (state->depth_clip_near || state->depth_clip_far);
+#endif
+      /* TODO: ConservativeRasterizationEnable */
    }
 
    iris_pack_command(GENX(3DSTATE_CLIP), cso->clip, cl) {
@@ -1215,14 +1299,19 @@ iris_bind_rasterizer_state(struct pipe_context *ctx, void *state)
       if (cso_changed(line_stipple_enable) || cso_changed(poly_stipple_enable))
          ice->state.dirty |= IRIS_DIRTY_WM;
 
-      if (cso_changed(rasterizer_discard) || cso_changed(flatshade_first))
+      if (cso_changed(rasterizer_discard))
+         ice->state.dirty |= IRIS_DIRTY_STREAMOUT | IRIS_DIRTY_CLIP;
+
+      if (cso_changed(flatshade_first))
          ice->state.dirty |= IRIS_DIRTY_STREAMOUT;
 
       if (cso_changed(depth_clip_near) || cso_changed(depth_clip_far) ||
           cso_changed(clip_halfz))
          ice->state.dirty |= IRIS_DIRTY_CC_VIEWPORT;
 
-      if (cso_changed(sprite_coord_enable) || cso_changed(light_twoside))
+      if (cso_changed(sprite_coord_enable) ||
+          cso_changed(sprite_coord_mode) ||
+          cso_changed(light_twoside))
          ice->state.dirty |= IRIS_DIRTY_SBE;
    }
 
@@ -1372,14 +1461,11 @@ iris_bind_sampler_states(struct pipe_context *ctx,
    struct iris_shader_state *shs = &ice->state.shaders[stage];
 
    assert(start + count <= IRIS_MAX_TEXTURE_SAMPLERS);
-   shs->num_samplers = MAX2(shs->num_samplers, start + count);
 
    for (int i = 0; i < count; i++) {
       shs->samplers[start + i] = states[i];
    }
 
-   // XXX: count may include NULLs
-
    /* Assemble the SAMPLER_STATEs into a contiguous table that lives
     * in the dynamic state memory zone, so we can point to it via the
     * 3DSTATE_SAMPLER_STATE_POINTERS_* commands.
@@ -1449,7 +1535,7 @@ fill_buffer_surface_state(struct isl_device *isl_dev,
                           unsigned size)
 {
    const struct isl_format_layout *fmtl = isl_format_get_layout(format);
-   const unsigned cpp = fmtl->bpb / 8;
+   const unsigned cpp = format == ISL_FORMAT_RAW ? 1 : fmtl->bpb / 8;
 
    /* The ARB_texture_buffer_specification says:
     *
@@ -1475,7 +1561,58 @@ fill_buffer_surface_state(struct isl_device *isl_dev,
                          .size_B = final_size,
                          .format = format,
                          .stride_B = cpp,
-                         .mocs = MOCS_WB);
+                         .mocs = mocs(bo));
+}
+
+#define SURFACE_STATE_ALIGNMENT 64
+
+/**
+ * Allocate several contiguous SURFACE_STATE structures, one for each
+ * supported auxiliary surface mode.
+ */
+static void *
+alloc_surface_states(struct u_upload_mgr *mgr,
+                     struct iris_state_ref *ref,
+                     unsigned aux_usages)
+{
+   const unsigned surf_size = 4 * GENX(RENDER_SURFACE_STATE_length);
+
+   /* If this changes, update this to explicitly align pointers */
+   STATIC_ASSERT(surf_size == SURFACE_STATE_ALIGNMENT);
+
+   assert(aux_usages != 0);
+
+   void *map =
+      upload_state(mgr, ref, util_bitcount(aux_usages) * surf_size,
+                   SURFACE_STATE_ALIGNMENT);
+
+   ref->offset += iris_bo_offset_from_base_address(iris_resource_bo(ref->res));
+
+   return map;
+}
+
+static void
+fill_surface_state(struct isl_device *isl_dev,
+                   void *map,
+                   struct iris_resource *res,
+                   struct isl_view *view,
+                   unsigned aux_usage)
+{
+   struct isl_surf_fill_state_info f = {
+      .surf = &res->surf,
+      .view = view,
+      .mocs = mocs(res->bo),
+      .address = res->bo->gtt_offset,
+   };
+
+   if (aux_usage != ISL_AUX_USAGE_NONE) {
+      f.aux_surf = &res->aux.surf;
+      f.aux_usage = aux_usage;
+      f.aux_address = res->aux.bo->gtt_offset + res->aux.offset;
+      // XXX: clear color
+   }
+
+   isl_surf_fill_state_s(isl_dev, map, &f);
 }
 
 /**
@@ -1501,14 +1638,6 @@ iris_create_sampler_view(struct pipe_context *ctx,
    pipe_reference_init(&isv->base.reference, 1);
    pipe_resource_reference(&isv->base.texture, tex);
 
-   void *map = upload_state(ice->state.surface_uploader, &isv->surface_state,
-                            4 * GENX(RENDER_SURFACE_STATE_length), 64);
-   if (!unlikely(map))
-      return NULL;
-
-   struct iris_bo *state_bo = iris_resource_bo(isv->surface_state.res);
-   isv->surface_state.offset += iris_bo_offset_from_base_address(state_bo);
-
    if (util_format_is_depth_or_stencil(tmpl->format)) {
       struct iris_resource *zres, *sres;
       const struct util_format_description *desc =
@@ -1521,6 +1650,12 @@ iris_create_sampler_view(struct pipe_context *ctx,
 
    isv->res = (struct iris_resource *) tex;
 
+   void *map = alloc_surface_states(ice->state.surface_uploader,
+                                    &isv->surface_state,
+                                    isv->res->aux.possible_usages);
+   if (!unlikely(map))
+      return NULL;
+
    isl_surf_usage_flags_t usage = ISL_SURF_USAGE_TEXTURE_BIT;
 
    if (isv->base.target == PIPE_TEXTURE_CUBE ||
@@ -1550,12 +1685,15 @@ iris_create_sampler_view(struct pipe_context *ctx,
       isv->view.array_len =
          tmpl->u.tex.last_layer - tmpl->u.tex.first_layer + 1;
 
-      isl_surf_fill_state(&screen->isl_dev, map,
-                          .surf = &isv->res->surf, .view = &isv->view,
-                          .mocs = MOCS_WB,
-                          .address = isv->res->bo->gtt_offset);
-                          // .aux_surf =
-                          // .clear_color = clear_color,
+      unsigned aux_modes = isv->res->aux.possible_usages;
+      while (aux_modes) {
+         enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
+
+         fill_surface_state(&screen->isl_dev, map, isv->res, &isv->view,
+                            aux_usage);
+
+         map += SURFACE_STATE_ALIGNMENT;
+      }
    } else {
       fill_buffer_surface_state(&screen->isl_dev, isv->res->bo, map,
                                 isv->view.format, tmpl->u.buf.offset,
@@ -1644,24 +1782,54 @@ iris_create_surface(struct pipe_context *ctx,
       return psurf;
 
 
-   void *map = upload_state(ice->state.surface_uploader, &surf->surface_state,
-                            4 * GENX(RENDER_SURFACE_STATE_length), 64);
+   void *map = alloc_surface_states(ice->state.surface_uploader,
+                                    &surf->surface_state,
+                                    res->aux.possible_usages);
    if (!unlikely(map))
       return NULL;
 
-   struct iris_bo *state_bo = iris_resource_bo(surf->surface_state.res);
-   surf->surface_state.offset += iris_bo_offset_from_base_address(state_bo);
+   unsigned aux_modes = res->aux.possible_usages;
+   while (aux_modes) {
+      enum isl_aux_usage aux_usage = u_bit_scan(&aux_modes);
 
-   isl_surf_fill_state(&screen->isl_dev, map,
-                       .surf = &res->surf, .view = &surf->view,
-                       .mocs = MOCS_WB,
-                       .address = res->bo->gtt_offset);
-                       // .aux_surf =
-                       // .clear_color = clear_color,
+      fill_surface_state(&screen->isl_dev, map, res, &surf->view, aux_usage);
+
+      map += SURFACE_STATE_ALIGNMENT;
+   }
 
    return psurf;
 }
 
+#if GEN_GEN < 9
+static void
+fill_default_image_param(struct brw_image_param *param)
+{
+   memset(param, 0, sizeof(*param));
+   /* Set the swizzling shifts to all-ones to effectively disable swizzling --
+    * See emit_address_calculation() in brw_fs_surface_builder.cpp for a more
+    * detailed explanation of these parameters.
+    */
+   param->swizzling[0] = 0xff;
+   param->swizzling[1] = 0xff;
+}
+
+static void
+fill_buffer_image_param(struct brw_image_param *param,
+                        enum pipe_format pfmt,
+                        unsigned size)
+{
+   const unsigned cpp = util_format_get_blocksize(pfmt);
+
+   fill_default_image_param(param);
+   param->size[0] = size / cpp;
+   param->stride[0] = cpp;
+}
+#else
+#define isl_surf_fill_image_param(x, ...)
+#define fill_default_image_param(x, ...)
+#define fill_buffer_image_param(x, ...)
+#endif
+
 /**
  * The pipe->set_shader_images() driver hook.
  */
@@ -1677,7 +1845,7 @@ iris_set_shader_images(struct pipe_context *ctx,
    gl_shader_stage stage = stage_from_pipe(p_stage);
    struct iris_shader_state *shs = &ice->state.shaders[stage];
 
-   shs->num_images = MAX2(shs->num_images, start_slot + count);
+   shs->bound_image_views &= ~u_bit_consecutive(start_slot, count);
 
    for (unsigned i = 0; i < count; i++) {
       if (p_images && p_images[i].resource) {
@@ -1685,35 +1853,45 @@ iris_set_shader_images(struct pipe_context *ctx,
          struct iris_resource *res = (void *) img->resource;
          pipe_resource_reference(&shs->image[start_slot + i].res, &res->base);
 
+         shs->bound_image_views |= 1 << (start_slot + i);
+
          res->bind_history |= PIPE_BIND_SHADER_IMAGE;
 
          // XXX: these are not retained forever, use a separate uploader?
          void *map =
-            upload_state(ice->state.surface_uploader,
-                         &shs->image[start_slot + i].surface_state,
-                         4 * GENX(RENDER_SURFACE_STATE_length), 64);
+            alloc_surface_states(ice->state.surface_uploader,
+                                 &shs->image[start_slot + i].surface_state,
+                                 1 << ISL_AUX_USAGE_NONE);
          if (!unlikely(map)) {
             pipe_resource_reference(&shs->image[start_slot + i].res, NULL);
             return;
          }
 
-         struct iris_bo *surf_state_bo =
-            iris_resource_bo(shs->image[start_slot + i].surface_state.res);
-         shs->image[start_slot + i].surface_state.offset +=
-            iris_bo_offset_from_base_address(surf_state_bo);
-
          isl_surf_usage_flags_t usage = ISL_SURF_USAGE_STORAGE_BIT;
-         enum isl_format isl_format =
+         enum isl_format isl_fmt =
             iris_format_for_usage(devinfo, img->format, usage).fmt;
 
-         if (img->shader_access & PIPE_IMAGE_ACCESS_READ)
-            isl_format = isl_lower_storage_image_format(devinfo, isl_format);
+         bool untyped_fallback = false;
+
+         if (img->shader_access & PIPE_IMAGE_ACCESS_READ) {
+            /* On Gen8, try to use typed surfaces reads (which support a
+             * limited number of formats), and if not possible, fall back
+             * to untyped reads.
+             */
+            untyped_fallback = GEN_GEN == 8 &&
+               !isl_has_matching_typed_storage_image_format(devinfo, isl_fmt);
+
+            if (untyped_fallback)
+               isl_fmt = ISL_FORMAT_RAW;
+            else
+               isl_fmt = isl_lower_storage_image_format(devinfo, isl_fmt);
+         }
 
          shs->image[start_slot + i].access = img->shader_access;
 
          if (res->base.target != PIPE_BUFFER) {
             struct isl_view view = {
-               .format = isl_format,
+               .format = isl_fmt,
                .base_level = img->u.tex.level,
                .levels = 1,
                .base_array_layer = img->u.tex.first_layer,
@@ -1722,25 +1900,46 @@ iris_set_shader_images(struct pipe_context *ctx,
                .usage = usage,
             };
 
-            isl_surf_fill_state(&screen->isl_dev, map,
-                                .surf = &res->surf, .view = &view,
-                                .mocs = MOCS_WB,
-                                .address = res->bo->gtt_offset);
-                                // .aux_surf =
-                                // .clear_color = clear_color,
+            if (untyped_fallback) {
+               fill_buffer_surface_state(&screen->isl_dev, res->bo, map,
+                                         isl_fmt, 0, res->bo->size);
+            } else {
+               /* Images don't support compression */
+               unsigned aux_modes = 1 << ISL_AUX_USAGE_NONE;
+               while (aux_modes) {
+                  enum isl_aux_usage usage = u_bit_scan(&aux_modes);
+
+                  fill_surface_state(&screen->isl_dev, map, res, &view, usage);
+
+                  map += SURFACE_STATE_ALIGNMENT;
+               }
+            }
+
+            isl_surf_fill_image_param(&screen->isl_dev,
+                                      &shs->image[start_slot + i].param,
+                                      &res->surf, &view);
          } else {
             fill_buffer_surface_state(&screen->isl_dev, res->bo, map,
-                                      isl_format, img->u.buf.offset,
+                                      isl_fmt, img->u.buf.offset,
                                       img->u.buf.size);
+            fill_buffer_image_param(&shs->image[start_slot + i].param,
+                                    img->format, img->u.buf.size);
          }
       } else {
          pipe_resource_reference(&shs->image[start_slot + i].res, NULL);
          pipe_resource_reference(&shs->image[start_slot + i].surface_state.res,
                                  NULL);
+         fill_default_image_param(&shs->image[start_slot + i].param);
       }
    }
 
    ice->state.dirty |= IRIS_DIRTY_BINDINGS_VS << stage;
+
+   /* Broadwell also needs brw_image_params re-uploaded */
+   if (GEN_GEN < 9) {
+      ice->state.dirty |= IRIS_DIRTY_CONSTANTS_VS << stage;
+      shs->cbuf0_needs_upload = true;
+   }
 }
 
 
@@ -1757,20 +1956,17 @@ iris_set_sampler_views(struct pipe_context *ctx,
    gl_shader_stage stage = stage_from_pipe(p_stage);
    struct iris_shader_state *shs = &ice->state.shaders[stage];
 
-   unsigned i;
-   for (i = 0; i < count; i++) {
+   shs->bound_sampler_views &= ~u_bit_consecutive(start, count);
+
+   for (unsigned i = 0; i < count; i++) {
       pipe_sampler_view_reference((struct pipe_sampler_view **)
-                                  &shs->textures[i], views[i]);
+                                  &shs->textures[start + i], views[i]);
       struct iris_sampler_view *view = (void *) views[i];
-      if (view)
+      if (view) {
          view->res->bind_history |= PIPE_BIND_SAMPLER_VIEW;
+         shs->bound_sampler_views |= 1 << (start + i);
+      }
    }
-   for (; i < shs->num_textures; i++) {
-      pipe_sampler_view_reference((struct pipe_sampler_view **)
-                                  &shs->textures[i], NULL);
-   }
-
-   shs->num_textures = count;
 
    ice->state.dirty |= (IRIS_DIRTY_BINDINGS_VS << stage);
 }
@@ -1887,7 +2083,10 @@ iris_set_stencil_ref(struct pipe_context *ctx,
 {
    struct iris_context *ice = (struct iris_context *) ctx;
    memcpy(&ice->state.stencil_ref, state, sizeof(*state));
-   ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
+   if (GEN_GEN == 8)
+      ice->state.dirty |= IRIS_DIRTY_COLOR_CALC_STATE;
+   else
+      ice->state.dirty |= IRIS_DIRTY_WM_DEPTH_STENCIL;
 }
 
 static float
@@ -1896,7 +2095,6 @@ viewport_extent(const struct pipe_viewport_state *state, int axis, float sign)
    return copysignf(state->scale[axis], sign) + state->translate[axis];
 }
 
-#if 0
 static void
 calculate_guardband_size(uint32_t fb_width, uint32_t fb_height,
                          float m00, float m11, float m30, float m31,
@@ -1976,7 +2174,6 @@ calculate_guardband_size(uint32_t fb_width, uint32_t fb_height,
       *ymax = 0.0f;
    }
 }
-#endif
 
 /**
  * The pipe->set_viewport_states() driver hook.
@@ -1992,37 +2189,8 @@ iris_set_viewport_states(struct pipe_context *ctx,
                          const struct pipe_viewport_state *states)
 {
    struct iris_context *ice = (struct iris_context *) ctx;
-   struct iris_genx_state *genx = ice->state.genx;
-   uint32_t *vp_map =
-      &genx->sf_cl_vp[start_slot * GENX(SF_CLIP_VIEWPORT_length)];
 
-   for (unsigned i = 0; i < count; i++) {
-      const struct pipe_viewport_state *state = &states[i];
-
-      memcpy(&ice->state.viewports[start_slot + i], state, sizeof(*state));
-
-      iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
-         vp.ViewportMatrixElementm00 = state->scale[0];
-         vp.ViewportMatrixElementm11 = state->scale[1];
-         vp.ViewportMatrixElementm22 = state->scale[2];
-         vp.ViewportMatrixElementm30 = state->translate[0];
-         vp.ViewportMatrixElementm31 = state->translate[1];
-         vp.ViewportMatrixElementm32 = state->translate[2];
-         /* XXX: in i965 this is computed based on the drawbuffer size,
-          * but we don't have that here...
-          */
-         vp.XMinClipGuardband = -1.0;
-         vp.XMaxClipGuardband = 1.0;
-         vp.YMinClipGuardband = -1.0;
-         vp.YMaxClipGuardband = 1.0;
-         vp.XMinViewPort = viewport_extent(state, 0, -1.0f);
-         vp.XMaxViewPort = viewport_extent(state, 0,  1.0f) - 1;
-         vp.YMinViewPort = viewport_extent(state, 1, -1.0f);
-         vp.YMaxViewPort = viewport_extent(state, 1,  1.0f) - 1;
-      }
-
-      vp_map += GENX(SF_CLIP_VIEWPORT_length);
-   }
+   memcpy(&ice->state.viewports[start_slot], states, sizeof(*states) * count);
 
    ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
 
@@ -2049,6 +2217,7 @@ iris_set_framebuffer_state(struct pipe_context *ctx,
    struct iris_resource *stencil_res;
 
    unsigned samples = util_framebuffer_get_num_samples(state);
+   unsigned layers = util_framebuffer_get_num_layers(state);
 
    if (cso->samples != samples) {
       ice->state.dirty |= IRIS_DIRTY_MULTISAMPLE;
@@ -2058,12 +2227,17 @@ iris_set_framebuffer_state(struct pipe_context *ctx,
       ice->state.dirty |= IRIS_DIRTY_BLEND_STATE;
    }
 
-   if ((cso->layers == 0) != (state->layers == 0)) {
+   if ((cso->layers == 0) != (layers == 0)) {
       ice->state.dirty |= IRIS_DIRTY_CLIP;
    }
 
+   if (cso->width != state->width || cso->height != state->height) {
+      ice->state.dirty |= IRIS_DIRTY_SF_CL_VIEWPORT;
+   }
+
    util_copy_framebuffer_state(cso, state);
    cso->samples = samples;
+   cso->layers = layers;
 
    struct iris_depth_buffer_state *cso_z = &ice->state.genx->depth_buffer;
 
@@ -2075,10 +2249,7 @@ iris_set_framebuffer_state(struct pipe_context *ctx,
       .swizzle = ISL_SWIZZLE_IDENTITY,
    };
 
-   struct isl_depth_stencil_hiz_emit_info info = {
-      .view = &view,
-      .mocs = MOCS_WB,
-   };
+   struct isl_depth_stencil_hiz_emit_info info = { .view = &view };
 
    if (cso->zsbuf) {
       iris_get_depth_stencil_resources(cso->zsbuf->texture, &zres,
@@ -2094,17 +2265,25 @@ iris_set_framebuffer_state(struct pipe_context *ctx,
 
          info.depth_surf = &zres->surf;
          info.depth_address = zres->bo->gtt_offset;
-         info.hiz_usage = ISL_AUX_USAGE_NONE;
+         info.mocs = mocs(zres->bo);
 
          view.format = zres->surf.format;
+
+         if (iris_resource_level_has_hiz(zres, view.base_level)) {
+            info.hiz_usage = ISL_AUX_USAGE_HIZ;
+            info.hiz_surf = &zres->aux.surf;
+            info.hiz_address = zres->aux.bo->gtt_offset;
+         }
       }
 
       if (stencil_res) {
          view.usage |= ISL_SURF_USAGE_STENCIL_BIT;
          info.stencil_surf = &stencil_res->surf;
          info.stencil_address = stencil_res->bo->gtt_offset;
-         if (!zres)
+         if (!zres) {
             view.format = stencil_res->surf.format;
+            info.mocs = mocs(stencil_res->bo);
+         }
       }
    }
 
@@ -2174,7 +2353,7 @@ upload_ubo_surf_state(struct iris_context *ice,
                                         res->bo->size - cbuf->data.offset),
                          .format = ISL_FORMAT_R32G32B32A32_FLOAT,
                          .stride_B = 1,
-                         .mocs = MOCS_WB)
+                         .mocs = mocs(res->bo))
 }
 
 /**
@@ -2245,10 +2424,30 @@ upload_uniforms(struct iris_context *ice,
       uint32_t sysval = shader->system_values[i];
       uint32_t value = 0;
 
-      if (BRW_PARAM_BUILTIN_IS_CLIP_PLANE(sysval)) {
+      if (BRW_PARAM_DOMAIN(sysval) == BRW_PARAM_DOMAIN_IMAGE) {
+         unsigned img = BRW_PARAM_IMAGE_IDX(sysval);
+         unsigned offset = BRW_PARAM_IMAGE_OFFSET(sysval);
+         struct brw_image_param *param = &shs->image[img].param;
+
+         assert(offset < sizeof(struct brw_image_param));
+         value = ((uint32_t *) param)[offset];
+      } else if (sysval == BRW_PARAM_BUILTIN_ZERO) {
+         value = 0;
+      } else if (BRW_PARAM_BUILTIN_IS_CLIP_PLANE(sysval)) {
          int plane = BRW_PARAM_BUILTIN_CLIP_PLANE_IDX(sysval);
          int comp  = BRW_PARAM_BUILTIN_CLIP_PLANE_COMP(sysval);
          value = fui(ice->state.clip_planes.ucp[plane][comp]);
+      } else if (sysval == BRW_PARAM_BUILTIN_PATCH_VERTICES_IN) {
+         if (stage == MESA_SHADER_TESS_CTRL) {
+            value = ice->state.vertices_per_patch;
+         } else {
+            assert(stage == MESA_SHADER_TESS_EVAL);
+            const struct shader_info *tcs_info =
+               iris_get_shader_info(ice, MESA_SHADER_TESS_CTRL);
+            assert(tcs_info);
+
+            value = tcs_info->tess.tcs_vertices_out;
+         }
       } else {
          assert(!"unhandled system value");
       }
@@ -2311,7 +2510,7 @@ iris_set_shader_buffers(struct pipe_context *ctx,
                                        res->bo->size - buffer->buffer_offset),
                                .format = ISL_FORMAT_RAW,
                                .stride_B = 1,
-                               .mocs = MOCS_WB);
+                               .mocs = mocs(res->bo));
       } else {
          pipe_resource_reference(&shs->ssbo[start_slot + i], NULL);
          pipe_resource_reference(&shs->ssbo_surface_state[start_slot + i].res,
@@ -2328,13 +2527,6 @@ iris_delete_state(struct pipe_context *ctx, void *state)
    free(state);
 }
 
-static void
-iris_free_vertex_buffers(struct iris_vertex_buffer_state *cso)
-{
-   for (unsigned i = 0; i < cso->num_buffers; i++)
-      pipe_resource_reference(&cso->resources[i], NULL);
-}
-
 /**
  * The pipe->set_vertex_buffers() driver hook.
  *
@@ -2346,53 +2538,43 @@ iris_set_vertex_buffers(struct pipe_context *ctx,
                         const struct pipe_vertex_buffer *buffers)
 {
    struct iris_context *ice = (struct iris_context *) ctx;
-   struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
-
-   iris_free_vertex_buffers(&ice->state.genx->vertex_buffers);
-
-   if (!buffers)
-      count = 0;
-
-   cso->num_buffers = count;
+   struct iris_genx_state *genx = ice->state.genx;
 
-   iris_pack_command(GENX(3DSTATE_VERTEX_BUFFERS), cso->vertex_buffers, vb) {
-      vb.DWordLength = 4 * MAX2(cso->num_buffers, 1) - 1;
-   }
+   ice->state.bound_vertex_buffers &= ~u_bit_consecutive64(start_slot, count);
 
-   uint32_t *vb_pack_dest = &cso->vertex_buffers[1];
+   for (unsigned i = 0; i < count; i++) {
+      const struct pipe_vertex_buffer *buffer = buffers ? &buffers[i] : NULL;
+      struct iris_vertex_buffer_state *state =
+         &genx->vertex_buffers[start_slot + i];
 
-   if (count == 0) {
-      iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
-         vb.VertexBufferIndex = start_slot;
-         vb.NullVertexBuffer = true;
-         vb.AddressModifyEnable = true;
+      if (!buffer) {
+         pipe_resource_reference(&state->resource, NULL);
+         continue;
       }
-   }
 
-   for (unsigned i = 0; i < count; i++) {
-      assert(!buffers[i].is_user_buffer);
+      assert(!buffer->is_user_buffer);
 
-      pipe_resource_reference(&cso->resources[i], buffers[i].buffer.resource);
-      struct iris_resource *res = (void *) cso->resources[i];
+      pipe_resource_reference(&state->resource, buffer->buffer.resource);
+      struct iris_resource *res = (void *) state->resource;
 
-      if (res)
+      if (res) {
+         ice->state.bound_vertex_buffers |= 1ull << (start_slot + i);
          res->bind_history |= PIPE_BIND_VERTEX_BUFFER;
+      }
 
-      iris_pack_state(GENX(VERTEX_BUFFER_STATE), vb_pack_dest, vb) {
+      iris_pack_state(GENX(VERTEX_BUFFER_STATE), state->state, vb) {
          vb.VertexBufferIndex = start_slot + i;
-         vb.MOCS = MOCS_WB;
          vb.AddressModifyEnable = true;
-         vb.BufferPitch = buffers[i].stride;
+         vb.BufferPitch = buffer->stride;
          if (res) {
             vb.BufferSize = res->bo->size;
             vb.BufferStartingAddress =
-               ro_bo(NULL, res->bo->gtt_offset + buffers[i].buffer_offset);
+               ro_bo(NULL, res->bo->gtt_offset + (int) buffer->buffer_offset);
+            vb.MOCS = mocs(res->bo);
          } else {
             vb.NullVertexBuffer = true;
          }
       }
-
-      vb_pack_dest += GENX(VERTEX_BUFFER_STATE_length);
    }
 
    ice->state.dirty |= IRIS_DIRTY_VERTEX_BUFFERS;
@@ -2511,18 +2693,6 @@ iris_bind_vertex_elements_state(struct pipe_context *ctx, void *state)
    ice->state.dirty |= IRIS_DIRTY_VERTEX_ELEMENTS;
 }
 
-/**
- * Gallium CSO for stream output (transform feedback) targets.
- */
-struct iris_stream_output_target {
-   struct pipe_stream_output_target base;
-
-   uint32_t so_buffer[GENX(3DSTATE_SO_BUFFER_length)];
-
-   /** Storage holding the offset where we're writing in the buffer */
-   struct iris_state_ref offset;
-};
-
 /**
  * The pipe->create_stream_output_target() driver hook.
  *
@@ -2550,22 +2720,7 @@ iris_create_stream_output_target(struct pipe_context *ctx,
    cso->base.buffer_size = buffer_size;
    cso->base.context = ctx;
 
-   upload_state(ctx->stream_uploader, &cso->offset, 4 * sizeof(uint32_t), 4);
-
-   iris_pack_command(GENX(3DSTATE_SO_BUFFER), cso->so_buffer, sob) {
-      sob.SurfaceBaseAddress =
-         rw_bo(NULL, res->bo->gtt_offset + buffer_offset);
-      sob.SOBufferEnable = true;
-      sob.StreamOffsetWriteEnable = true;
-      sob.StreamOutputBufferOffsetAddressEnable = true;
-      sob.MOCS = MOCS_WB; // XXX: MOCS
-
-      sob.SurfaceSize = MAX2(buffer_size / 4, 1) - 1;
-
-      /* .SOBufferIndex, .StreamOffset, and .StreamOutputBufferOffsetAddress
-       * are filled in later when we have stream IDs.
-       */
-   }
+   upload_state(ctx->stream_uploader, &cso->offset, sizeof(uint32_t), 4);
 
    return &cso->base;
 }
@@ -2632,6 +2787,7 @@ iris_set_stream_output_targets(struct pipe_context *ctx,
       }
 
       struct iris_stream_output_target *tgt = (void *) targets[i];
+      struct iris_resource *res = (void *) tgt->base.buffer;
 
       /* Note that offsets[i] will either be 0, causing us to zero
        * the value in the buffer, or 0xFFFFFFFF, which happens to mean
@@ -2639,16 +2795,21 @@ iris_set_stream_output_targets(struct pipe_context *ctx,
        */
       assert(offsets[i] == 0 || offsets[i] == 0xFFFFFFFF);
 
-      uint32_t dynamic[GENX(3DSTATE_SO_BUFFER_length)];
-      iris_pack_state(GENX(3DSTATE_SO_BUFFER), dynamic, dyns) {
-         dyns.SOBufferIndex = i;
-         dyns.StreamOffset = offsets[i];
-         dyns.StreamOutputBufferOffsetAddress =
-            rw_bo(NULL, iris_resource_bo(tgt->offset.res)->gtt_offset + tgt->offset.offset + i * sizeof(uint32_t));
-      }
-
-      for (uint32_t j = 0; j < GENX(3DSTATE_SO_BUFFER_length); j++) {
-         so_buffers[j] = tgt->so_buffer[j] | dynamic[j];
+      iris_pack_command(GENX(3DSTATE_SO_BUFFER), so_buffers, sob) {
+         sob.SurfaceBaseAddress =
+            rw_bo(NULL, res->bo->gtt_offset + tgt->base.buffer_offset);
+         sob.SOBufferEnable = true;
+         sob.StreamOffsetWriteEnable = true;
+         sob.StreamOutputBufferOffsetAddressEnable = true;
+         sob.MOCS = mocs(res->bo);
+
+         sob.SurfaceSize = MAX2(tgt->base.buffer_size / 4, 1) - 1;
+
+         sob.SOBufferIndex = i;
+         sob.StreamOffset = offsets[i];
+         sob.StreamOutputBufferOffsetAddress =
+            rw_bo(NULL, iris_resource_bo(tgt->offset.res)->gtt_offset +
+                        tgt->offset.offset);
       }
    }
 
@@ -2864,8 +3025,6 @@ iris_emit_sbe_swiz(struct iris_batch *batch,
 
    /* XXX: this should be generated when putting programs in place */
 
-   // XXX: raster->sprite_coord_enable
-
    for (int fs_attr = 0; fs_attr < VARYING_SLOT_MAX; fs_attr++) {
       const int input_index = wm_prog_data->urb_setup[fs_attr];
       if (input_index < 0 || input_index >= 16)
@@ -2999,10 +3158,11 @@ iris_emit_sbe(struct iris_batch *batch, const struct iris_context *ice)
       sbe.ForceVertexURBEntryReadLength = true;
       sbe.ConstantInterpolationEnable = wm_prog_data->flat_inputs;
       sbe.PointSpriteTextureCoordinateEnable = sprite_coord_overrides;
-
+#if GEN_GEN >= 9
       for (int i = 0; i < 32; i++) {
          sbe.AttributeActiveComponentFormat[i] = ACTIVE_COMPONENT_XYZW;
       }
+#endif
    }
 
    iris_emit_sbe_swiz(batch, ice, urb_read_offset, sprite_coord_overrides);
@@ -3059,7 +3219,6 @@ static void
 iris_populate_fs_key(const struct iris_context *ice,
                      struct brw_wm_prog_key *key)
 {
-   /* XXX: dirty flags? */
    const struct pipe_framebuffer_state *fb = &ice->state.framebuffer;
    const struct iris_depth_stencil_alpha_state *zsa = ice->state.cso_zsa;
    const struct iris_rasterizer_state *rast = ice->state.cso_rast;
@@ -3080,10 +3239,8 @@ iris_populate_fs_key(const struct iris_context *ice,
 
    key->coherent_fb_fetch = true;
 
-   // XXX: uint64_t input_slots_valid; - for >16 inputs
-
-   // XXX: key->force_dual_color_blend for unigine
-   // XXX: respect hint for high_quality_derivatives:1;
+   /* TODO: support key->force_dual_color_blend for Unigine */
+   /* TODO: Respect glHint for key->high_quality_derivatives */
 }
 
 static void
@@ -3092,13 +3249,6 @@ iris_populate_cs_key(const struct iris_context *ice,
 {
 }
 
-#if 0
-   // XXX: these need to go in INIT_THREAD_DISPATCH_FIELDS
-   pkt.SamplerCount =                                                     \
-      DIV_ROUND_UP(CLAMP(stage_state->sampler_count, 0, 16), 4);          \
-
-#endif
-
 static uint64_t
 KSP(const struct iris_compiled_shader *shader)
 {
@@ -3106,9 +3256,12 @@ KSP(const struct iris_compiled_shader *shader)
    return iris_bo_offset_from_base_address(res->bo) + shader->assembly.offset;
 }
 
-// Gen11 workaround table #2056 WABTPPrefetchDisable suggests to disable
-// prefetching of binding tables in A0 and B0 steppings.  XXX: Revisit
-// this WA on C0 stepping.
+/* Gen11 workaround table #2056 WABTPPrefetchDisable suggests to disable
+ * prefetching of binding tables in A0 and B0 steppings.  XXX: Revisit
+ * this WA on C0 stepping.
+ *
+ * TODO: Fill out SamplerCount for prefetching?
+ */
 
 #define INIT_THREAD_DISPATCH_FIELDS(pkt, prefix, stage)                   \
    pkt.KernelStartPointer = KSP(shader);                                  \
@@ -3125,8 +3278,9 @@ KSP(const struct iris_compiled_shader *shader)
    pkt.Enable           = true;                                           \
                                                                           \
    if (prog_data->total_scratch) {                                        \
-      uint32_t scratch_addr =                                             \
+      struct iris_bo *bo =                                                \
          iris_get_scratch_space(ice, prog_data->total_scratch, stage);    \
+      uint32_t scratch_addr = bo->gtt_offset;                             \
       pkt.PerThreadScratchSpace = ffs(prog_data->total_scratch) - 11;     \
       pkt.ScratchSpaceBasePointer = rw_bo(NULL, scratch_addr);            \
    }
@@ -3274,15 +3428,13 @@ iris_store_fs_state(struct iris_context *ice,
 
    iris_pack_command(GENX(3DSTATE_PS), ps_state, ps) {
       ps.VectorMaskEnable = true;
-      //ps.SamplerCount = ...
       // XXX: WABTPPrefetchDisable, see above, drop at C0
       ps.BindingTableEntryCount = GEN_GEN == 11 ? 0 :
          prog_data->binding_table.size_bytes / 4;
       ps.FloatingPointMode = prog_data->use_alt_mode;
       ps.MaximumNumberofThreadsPerPSD = 64 - (GEN_GEN == 8 ? 2 : 1);
 
-      ps.PushConstantEnable = shader->num_system_values > 0 ||
-                              prog_data->ubo_ranges[0].length > 0;
+      ps.PushConstantEnable = prog_data->ubo_ranges[0].length > 0;
 
       /* From the documentation for this packet:
        * "If the PS kernel does not need the Position XY Offsets to
@@ -3320,9 +3472,10 @@ iris_store_fs_state(struct iris_context *ice,
          KSP(shader) + brw_wm_prog_data_prog_offset(wm_prog_data, ps, 2);
 
       if (prog_data->total_scratch) {
-         uint32_t scratch_addr =
+         struct iris_bo *bo =
             iris_get_scratch_space(ice, prog_data->total_scratch,
                                    MESA_SHADER_FRAGMENT);
+         uint32_t scratch_addr = bo->gtt_offset;
          ps.PerThreadScratchSpace = ffs(prog_data->total_scratch) - 11;
          ps.ScratchSpaceBasePointer = rw_bo(NULL, scratch_addr);
       }
@@ -3331,14 +3484,14 @@ iris_store_fs_state(struct iris_context *ice,
    iris_pack_command(GENX(3DSTATE_PS_EXTRA), psx_state, psx) {
       psx.PixelShaderValid = true;
       psx.PixelShaderComputedDepthMode = wm_prog_data->computed_depth_mode;
-      // XXX: alpha test / alpha to coverage :/
-      psx.PixelShaderKillsPixel = wm_prog_data->uses_kill ||
-                                  wm_prog_data->uses_omask;
+      psx.PixelShaderKillsPixel = wm_prog_data->uses_kill;
       psx.AttributeEnable = wm_prog_data->num_varying_inputs != 0;
       psx.PixelShaderUsesSourceDepth = wm_prog_data->uses_src_depth;
       psx.PixelShaderUsesSourceW = wm_prog_data->uses_src_w;
       psx.PixelShaderIsPerSample = wm_prog_data->persample_dispatch;
+      psx.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
 
+#if GEN_GEN >= 9
       if (wm_prog_data->uses_sample_mask) {
          /* TODO: conservative rasterization */
          if (wm_prog_data->post_depth_coverage)
@@ -3347,10 +3500,11 @@ iris_store_fs_state(struct iris_context *ice,
             psx.InputCoverageMaskState = ICMS_NORMAL;
       }
 
-      psx.oMaskPresenttoRenderTarget = wm_prog_data->uses_omask;
       psx.PixelShaderPullsBary = wm_prog_data->pulls_bary;
       psx.PixelShaderComputesStencil = wm_prog_data->computed_stencil;
-
+#else
+      psx.PixelShaderUsesInputCoverageMask = wm_prog_data->uses_sample_mask;
+#endif
       // XXX: UAV bit
    }
 }
@@ -3515,6 +3669,14 @@ use_null_fb_surface(struct iris_batch *batch, struct iris_context *ice)
    return ice->state.null_fb.offset;
 }
 
+static uint32_t
+surf_state_offset_for_aux(struct iris_resource *res,
+                          enum isl_aux_usage aux_usage)
+{
+   return SURFACE_STATE_ALIGNMENT *
+          util_bitcount(res->aux.possible_usages & ((1 << aux_usage) - 1));
+}
+
 /**
  * Add a surface to the validation list, as well as the buffer containing
  * the corresponding SURFACE_STATE.
@@ -3524,23 +3686,39 @@ use_null_fb_surface(struct iris_batch *batch, struct iris_context *ice)
 static uint32_t
 use_surface(struct iris_batch *batch,
             struct pipe_surface *p_surf,
-            bool writeable)
+            bool writeable,
+            enum isl_aux_usage aux_usage)
 {
    struct iris_surface *surf = (void *) p_surf;
+   struct iris_resource *res = (void *) p_surf->texture;
 
    iris_use_pinned_bo(batch, iris_resource_bo(p_surf->texture), writeable);
    iris_use_pinned_bo(batch, iris_resource_bo(surf->surface_state.res), false);
 
-   return surf->surface_state.offset;
+   if (res->aux.bo)
+      iris_use_pinned_bo(batch, res->aux.bo, writeable);
+
+   return surf->surface_state.offset +
+          surf_state_offset_for_aux(res, aux_usage);
 }
 
 static uint32_t
-use_sampler_view(struct iris_batch *batch, struct iris_sampler_view *isv)
+use_sampler_view(struct iris_context *ice,
+                 struct iris_batch *batch,
+                 struct iris_sampler_view *isv)
 {
+   // XXX: ASTC hacks
+   enum isl_aux_usage aux_usage =
+      iris_resource_texture_aux_usage(ice, isv->res, isv->view.format, 0);
+
    iris_use_pinned_bo(batch, isv->res->bo, false);
    iris_use_pinned_bo(batch, iris_resource_bo(isv->surface_state.res), false);
 
-   return isv->surface_state.offset;
+   if (isv->res->aux.bo)
+      iris_use_pinned_bo(batch, isv->res->aux.bo, false);
+
+   return isv->surface_state.offset +
+          surf_state_offset_for_aux(isv->res, aux_usage);
 }
 
 static uint32_t
@@ -3579,12 +3757,16 @@ use_image(struct iris_batch *batch, struct iris_context *ice,
    if (!shs->image[i].res)
       return use_null_surface(batch, ice);
 
+   struct iris_resource *res = (void *) shs->image[i].res;
    struct iris_state_ref *surf_state = &shs->image[i].surface_state;
+   bool write = shs->image[i].access & PIPE_IMAGE_ACCESS_WRITE;
 
-   iris_use_pinned_bo(batch, iris_resource_bo(shs->image[i].res),
-                      shs->image[i].access & PIPE_IMAGE_ACCESS_WRITE);
+   iris_use_pinned_bo(batch, res->bo, write);
    iris_use_pinned_bo(batch, iris_resource_bo(surf_state->res), false);
 
+   if (res->aux.bo)
+      iris_use_pinned_bo(batch, res->aux.bo, write);
+
    return surf_state->offset;
 }
 
@@ -3644,9 +3826,13 @@ iris_populate_binding_table(struct iris_context *ice,
       /* Note that cso_fb->nr_cbufs == fs_key->nr_color_regions. */
       if (cso_fb->nr_cbufs) {
          for (unsigned i = 0; i < cso_fb->nr_cbufs; i++) {
-            uint32_t addr =
-               cso_fb->cbufs[i] ? use_surface(batch, cso_fb->cbufs[i], true)
-                                : use_null_fb_surface(batch, ice);
+            uint32_t addr;
+            if (cso_fb->cbufs[i]) {
+               addr = use_surface(batch, cso_fb->cbufs[i], true,
+                                  ice->state.draw_aux_usage[i]);
+            } else {
+               addr = use_null_fb_surface(batch, ice);
+            }
             push_bt_entry(addr);
          }
       } else {
@@ -3655,11 +3841,13 @@ iris_populate_binding_table(struct iris_context *ice,
       }
    }
 
-   bt_assert(texture_start, info->num_textures > 0);
+   unsigned num_textures = util_last_bit(info->textures_used);
+
+   bt_assert(texture_start, num_textures > 0);
 
-   for (int i = 0; i < info->num_textures; i++) {
+   for (int i = 0; i < num_textures; i++) {
       struct iris_sampler_view *view = shs->textures[i];
-      uint32_t addr = view ? use_sampler_view(batch, view)
+      uint32_t addr = view ? use_sampler_view(ice, batch, view)
                            : use_null_surface(batch, ice);
       push_bt_entry(addr);
    }
@@ -3671,11 +3859,9 @@ iris_populate_binding_table(struct iris_context *ice,
       push_bt_entry(addr);
    }
 
-   const int num_ubos = iris_get_shader_num_ubos(ice, stage);
+   bt_assert(ubo_start, shader->num_cbufs > 0);
 
-   bt_assert(ubo_start, num_ubos > 0);
-
-   for (int i = 0; i < num_ubos; i++) {
+   for (int i = 0; i < shader->num_cbufs; i++) {
       uint32_t addr = use_const_buffer(batch, ice, &shs->constbuf[i]);
       push_bt_entry(addr);
    }
@@ -3695,7 +3881,7 @@ iris_populate_binding_table(struct iris_context *ice,
    }
 
 #if 0
-      // XXX: not implemented yet
+      /* XXX: YUV surfaces not implemented yet */
       bt_assert(plane_start[1], ...);
       bt_assert(plane_start[2], ...);
 #endif
@@ -3732,7 +3918,7 @@ iris_restore_render_saved_bos(struct iris_context *ice,
                               struct iris_batch *batch,
                               const struct pipe_draw_info *draw)
 {
-   // XXX: whack IRIS_SHADER_DIRTY_BINDING_TABLE on new batch
+   struct iris_genx_state *genx = ice->state.genx;
 
    const uint64_t clean = ~ice->state.dirty;
 
@@ -3756,6 +3942,19 @@ iris_restore_render_saved_bos(struct iris_context *ice,
       iris_use_optional_res(batch, ice->state.last_res.scissor, false);
    }
 
+   if (ice->state.streamout_active && (clean & IRIS_DIRTY_SO_BUFFERS)) {
+      for (int i = 0; i < 4; i++) {
+         struct iris_stream_output_target *tgt =
+            (void *) ice->state.so_target[i];
+         if (tgt) {
+            iris_use_pinned_bo(batch, iris_resource_bo(tgt->base.buffer),
+                               true);
+            iris_use_pinned_bo(batch, iris_resource_bo(tgt->offset.res),
+                               true);
+         }
+      }
+   }
+
    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
       if (!(clean & (IRIS_DIRTY_CONSTANTS_VS << stage)))
          continue;
@@ -3801,12 +4000,19 @@ iris_restore_render_saved_bos(struct iris_context *ice,
    for (int stage = 0; stage <= MESA_SHADER_FRAGMENT; stage++) {
       if (clean & (IRIS_DIRTY_VS << stage)) {
          struct iris_compiled_shader *shader = ice->shaders.prog[stage];
+
          if (shader) {
             struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
             iris_use_pinned_bo(batch, bo, false);
-         }
 
-         // XXX: scratch buffer
+            struct brw_stage_prog_data *prog_data = shader->prog_data;
+
+            if (prog_data->total_scratch > 0) {
+               struct iris_bo *bo =
+                  iris_get_scratch_space(ice, prog_data->total_scratch, stage);
+               iris_use_pinned_bo(batch, bo, true);
+            }
+         }
       }
    }
 
@@ -3817,11 +4023,23 @@ iris_restore_render_saved_bos(struct iris_context *ice,
          struct iris_resource *zres, *sres;
          iris_get_depth_stencil_resources(cso_fb->zsbuf->texture,
                                           &zres, &sres);
-         // XXX: might not be writable...
-         if (zres)
-            iris_use_pinned_bo(batch, zres->bo, true);
-         if (sres)
-            iris_use_pinned_bo(batch, sres->bo, true);
+         if (zres) {
+            iris_cache_flush_for_depth(batch, zres->bo);
+
+            iris_use_pinned_bo(batch, zres->bo,
+                               ice->state.depth_writes_enabled);
+            if (zres->aux.bo) {
+               iris_use_pinned_bo(batch, zres->aux.bo,
+                                  ice->state.depth_writes_enabled);
+            }
+         }
+
+         if (sres) {
+            iris_cache_flush_for_depth(batch, sres->bo);
+
+            iris_use_pinned_bo(batch, sres->bo,
+                               ice->state.stencil_writes_enabled);
+         }
       }
    }
 
@@ -3834,10 +4052,11 @@ iris_restore_render_saved_bos(struct iris_context *ice,
    }
 
    if (clean & IRIS_DIRTY_VERTEX_BUFFERS) {
-      struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
-      for (unsigned i = 0; i < cso->num_buffers; i++) {
-         struct iris_resource *res = (void *) cso->resources[i];
-         iris_use_pinned_bo(batch, res->bo, false);
+      uint64_t bound = ice->state.bound_vertex_buffers;
+      while (bound) {
+         const int i = u_bit_scan64(&bound);
+         struct pipe_resource *res = genx->vertex_buffers[i].resource;
+         iris_use_pinned_bo(batch, iris_resource_bo(res), false);
       }
    }
 }
@@ -3882,12 +4101,19 @@ iris_restore_compute_saved_bos(struct iris_context *ice,
 
    if (clean & IRIS_DIRTY_CS) {
       struct iris_compiled_shader *shader = ice->shaders.prog[stage];
+
       if (shader) {
          struct iris_bo *bo = iris_resource_bo(shader->assembly.res);
          iris_use_pinned_bo(batch, bo, false);
-      }
 
-      // XXX: scratch buffer
+         struct brw_stage_prog_data *prog_data = shader->prog_data;
+
+         if (prog_data->total_scratch > 0) {
+            struct iris_bo *bo =
+               iris_get_scratch_space(ice, prog_data->total_scratch, stage);
+            iris_use_pinned_bo(batch, bo, true);
+         }
+      }
    }
 }
 
@@ -3904,7 +4130,7 @@ iris_update_surface_base_address(struct iris_batch *batch,
    flush_for_state_base_change(batch);
 
    iris_emit_cmd(batch, GENX(STATE_BASE_ADDRESS), sba) {
-      // XXX: sba.SurfaceStateMemoryObjectControlState = MOCS_WB;
+      sba.SurfaceStateMOCS = MOCS_WB;
       sba.SurfaceStateBaseAddressModifyEnable = true;
       sba.SurfaceStateBaseAddress = ro_bo(binder->bo, 0);
    }
@@ -3960,18 +4186,53 @@ iris_upload_dirty_render_state(struct iris_context *ice,
    }
 
    if (dirty & IRIS_DIRTY_SF_CL_VIEWPORT) {
+      struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
+      uint32_t sf_cl_vp_address;
+      uint32_t *vp_map =
+         stream_state(batch, ice->state.dynamic_uploader,
+                      &ice->state.last_res.sf_cl_vp,
+                      4 * ice->state.num_viewports *
+                      GENX(SF_CLIP_VIEWPORT_length), 64, &sf_cl_vp_address);
+
+      for (unsigned i = 0; i < ice->state.num_viewports; i++) {
+         const struct pipe_viewport_state *state = &ice->state.viewports[i];
+         float gb_xmin, gb_xmax, gb_ymin, gb_ymax;
+
+         float vp_xmin = viewport_extent(state, 0, -1.0f);
+         float vp_xmax = viewport_extent(state, 0,  1.0f);
+         float vp_ymin = viewport_extent(state, 1, -1.0f);
+         float vp_ymax = viewport_extent(state, 1,  1.0f);
+
+         calculate_guardband_size(cso_fb->width, cso_fb->height,
+                                  state->scale[0], state->scale[1],
+                                  state->translate[0], state->translate[1],
+                                  &gb_xmin, &gb_xmax, &gb_ymin, &gb_ymax);
+
+         iris_pack_state(GENX(SF_CLIP_VIEWPORT), vp_map, vp) {
+            vp.ViewportMatrixElementm00 = state->scale[0];
+            vp.ViewportMatrixElementm11 = state->scale[1];
+            vp.ViewportMatrixElementm22 = state->scale[2];
+            vp.ViewportMatrixElementm30 = state->translate[0];
+            vp.ViewportMatrixElementm31 = state->translate[1];
+            vp.ViewportMatrixElementm32 = state->translate[2];
+            vp.XMinClipGuardband = gb_xmin;
+            vp.XMaxClipGuardband = gb_xmax;
+            vp.YMinClipGuardband = gb_ymin;
+            vp.YMaxClipGuardband = gb_ymax;
+            vp.XMinViewPort = MAX2(vp_xmin, 0);
+            vp.XMaxViewPort = MIN2(vp_xmax, cso_fb->width) - 1;
+            vp.YMinViewPort = MAX2(vp_ymin, 0);
+            vp.YMaxViewPort = MIN2(vp_ymax, cso_fb->height) - 1;
+         }
+
+         vp_map += GENX(SF_CLIP_VIEWPORT_length);
+      }
+
       iris_emit_cmd(batch, GENX(3DSTATE_VIEWPORT_STATE_POINTERS_SF_CLIP), ptr) {
-         ptr.SFClipViewportPointer =
-            emit_state(batch, ice->state.dynamic_uploader,
-                       &ice->state.last_res.sf_cl_vp,
-                       genx->sf_cl_vp, 4 * GENX(SF_CLIP_VIEWPORT_length) *
-                       ice->state.num_viewports, 64);
+         ptr.SFClipViewportPointer = sf_cl_vp_address;
       }
    }
 
-   /* XXX: L3 State */
-
-   // XXX: this is only flagged at setup, we assume a static configuration
    if (dirty & IRIS_DIRTY_URB) {
       iris_upload_urb_config(ice, batch);
    }
@@ -3981,7 +4242,14 @@ iris_upload_dirty_render_state(struct iris_context *ice,
       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
       struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
       const int header_dwords = GENX(BLEND_STATE_length);
-      const int rt_dwords = cso_fb->nr_cbufs * GENX(BLEND_STATE_ENTRY_length);
+
+      /* Always write at least one BLEND_STATE - the final RT message will
+       * reference BLEND_STATE[0] even if there aren't color writes.  There
+       * may still be alpha testing, computed depth, and so on.
+       */
+      const int rt_dwords =
+         MAX2(cso_fb->nr_cbufs, 1) * GENX(BLEND_STATE_ENTRY_length);
+
       uint32_t blend_offset;
       uint32_t *blend_map =
          stream_state(batch, ice->state.dynamic_uploader,
@@ -4005,6 +4273,9 @@ iris_upload_dirty_render_state(struct iris_context *ice,
 
    if (dirty & IRIS_DIRTY_COLOR_CALC_STATE) {
       struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
+#if GEN_GEN == 8
+      struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
+#endif
       uint32_t cc_offset;
       void *cc_map =
          stream_state(batch, ice->state.dynamic_uploader,
@@ -4018,6 +4289,10 @@ iris_upload_dirty_render_state(struct iris_context *ice,
          cc.BlendConstantColorGreen = ice->state.blend_color.color[1];
          cc.BlendConstantColorBlue  = ice->state.blend_color.color[2];
          cc.BlendConstantColorAlpha = ice->state.blend_color.color[3];
+#if GEN_GEN == 8
+        cc.StencilReferenceValue = p_stencil_refs->ref_value[0];
+        cc.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
+#endif
       }
       iris_emit_cmd(batch, GENX(3DSTATE_CC_STATE_POINTERS), ptr) {
          ptr.ColorCalcStatePointer = cc_offset;
@@ -4159,7 +4434,7 @@ iris_upload_dirty_render_state(struct iris_context *ice,
 
    if (dirty & IRIS_DIRTY_SAMPLE_MASK) {
       iris_emit_cmd(batch, GENX(3DSTATE_SAMPLE_MASK), ms) {
-         ms.SampleMask = MAX2(ice->state.sample_mask, 1);
+         ms.SampleMask = ice->state.sample_mask;
       }
    }
 
@@ -4235,13 +4510,11 @@ iris_upload_dirty_render_state(struct iris_context *ice,
       struct iris_rasterizer_state *cso_rast = ice->state.cso_rast;
       struct pipe_framebuffer_state *cso_fb = &ice->state.framebuffer;
 
-      bool reject = cso_rast->rasterizer_discard &&
-                    ice->state.prims_generated_query_active;
-
       uint32_t dynamic_clip[GENX(3DSTATE_CLIP_length)];
       iris_pack_command(GENX(3DSTATE_CLIP), &dynamic_clip, cl) {
          cl.StatisticsEnable = ice->state.statistics_counters_enabled;
-         cl.ClipMode = reject ? CLIPMODE_REJECT_ALL : CLIPMODE_NORMAL;
+         cl.ClipMode = cso_rast->rasterizer_discard ? CLIPMODE_REJECT_ALL
+                                                    : CLIPMODE_NORMAL;
          if (wm_prog_data->barycentric_interp_modes &
              BRW_BARYCENTRIC_NONPERSPECTIVE_BITS)
             cl.NonPerspectiveBarycentricEnable = true;
@@ -4260,7 +4533,6 @@ iris_upload_dirty_render_state(struct iris_context *ice,
 
    }
 
-   /* XXX: FS program updates needs to flag IRIS_DIRTY_WM */
    if (dirty & IRIS_DIRTY_WM) {
       struct iris_rasterizer_state *cso = ice->state.cso_rast;
       uint32_t dynamic_wm[GENX(3DSTATE_WM_length)];
@@ -4275,6 +4547,10 @@ iris_upload_dirty_render_state(struct iris_context *ice,
             wm.EarlyDepthStencilControl = EDSC_PREPS;
          else if (wm_prog_data->has_side_effects)
             wm.EarlyDepthStencilControl = EDSC_PSEXEC;
+
+         /* We could skip this bit if color writes are enabled. */
+         if (wm_prog_data->has_side_effects || wm_prog_data->uses_kill)
+            wm.ForceThreadDispatchEnable = ForceON;
       }
       iris_emit_merge(batch, cso->wm, dynamic_wm, ARRAY_SIZE(cso->wm));
    }
@@ -4286,9 +4562,12 @@ iris_upload_dirty_render_state(struct iris_context *ice,
    if (dirty & IRIS_DIRTY_PS_BLEND) {
       struct iris_blend_state *cso_blend = ice->state.cso_blend;
       struct iris_depth_stencil_alpha_state *cso_zsa = ice->state.cso_zsa;
+      const struct shader_info *fs_info =
+         iris_get_shader_info(ice, MESA_SHADER_FRAGMENT);
+
       uint32_t dynamic_pb[GENX(3DSTATE_PS_BLEND_length)];
       iris_pack_command(GENX(3DSTATE_PS_BLEND), &dynamic_pb, pb) {
-         pb.HasWriteableRT = true; // XXX: comes from somewhere :(
+         pb.HasWriteableRT = has_writeable_rt(cso_blend, fs_info);
          pb.AlphaTestEnable = cso_zsa->alpha.enabled;
       }
 
@@ -4298,14 +4577,17 @@ iris_upload_dirty_render_state(struct iris_context *ice,
 
    if (dirty & IRIS_DIRTY_WM_DEPTH_STENCIL) {
       struct iris_depth_stencil_alpha_state *cso = ice->state.cso_zsa;
+#if GEN_GEN >= 9
       struct pipe_stencil_ref *p_stencil_refs = &ice->state.stencil_ref;
-
       uint32_t stencil_refs[GENX(3DSTATE_WM_DEPTH_STENCIL_length)];
       iris_pack_command(GENX(3DSTATE_WM_DEPTH_STENCIL), &stencil_refs, wmds) {
          wmds.StencilReferenceValue = p_stencil_refs->ref_value[0];
          wmds.BackfaceStencilReferenceValue = p_stencil_refs->ref_value[1];
       }
       iris_emit_merge(batch, cso->wmds, stencil_refs, ARRAY_SIZE(cso->wmds));
+#else
+      iris_batch_emit(batch, cso->wmds, sizeof(cso->wmds));
+#endif
    }
 
    if (dirty & IRIS_DIRTY_SCISSOR_RECT) {
@@ -4331,11 +4613,19 @@ iris_upload_dirty_render_state(struct iris_context *ice,
          struct iris_resource *zres, *sres;
          iris_get_depth_stencil_resources(cso_fb->zsbuf->texture,
                                           &zres, &sres);
-         // XXX: might not be writable...
-         if (zres)
-            iris_use_pinned_bo(batch, zres->bo, true);
-         if (sres)
-            iris_use_pinned_bo(batch, sres->bo, true);
+         if (zres) {
+            iris_use_pinned_bo(batch, zres->bo,
+                               ice->state.depth_writes_enabled);
+            if (zres->aux.bo) {
+               iris_use_pinned_bo(batch, zres->aux.bo,
+                                  ice->state.depth_writes_enabled);
+            }
+         }
+
+         if (sres) {
+            iris_use_pinned_bo(batch, sres->bo,
+                               ice->state.stencil_writes_enabled);
+         }
       }
    }
 
@@ -4360,10 +4650,9 @@ iris_upload_dirty_render_state(struct iris_context *ice,
    }
 
    if (dirty & IRIS_DIRTY_VERTEX_BUFFERS) {
-      struct iris_vertex_buffer_state *cso = &ice->state.genx->vertex_buffers;
-      const unsigned vb_dwords = GENX(VERTEX_BUFFER_STATE_length);
+      int count = util_bitcount64(ice->state.bound_vertex_buffers);
 
-      if (cso->num_buffers > 0) {
+      if (count) {
          /* The VF cache designers cut corners, and made the cache key's
           * <VertexBufferIndex, Memory Address> tuple only consider the bottom
           * 32 bits of the address.  If you have two vertex buffers which get
@@ -4375,16 +4664,20 @@ iris_upload_dirty_render_state(struct iris_context *ice,
           */
          unsigned flush_flags = 0;
 
-         for (unsigned i = 0; i < cso->num_buffers; i++) {
+         uint64_t bound = ice->state.bound_vertex_buffers;
+         while (bound) {
+            const int i = u_bit_scan64(&bound);
             uint16_t high_bits = 0;
 
-            struct iris_resource *res = (void *) cso->resources[i];
+            struct iris_resource *res =
+               (void *) genx->vertex_buffers[i].resource;
             if (res) {
                iris_use_pinned_bo(batch, res->bo, false);
 
                high_bits = res->bo->gtt_offset >> 32ull;
                if (high_bits != ice->state.last_vbo_high_bits[i]) {
-                  flush_flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE;
+                  flush_flags |= PIPE_CONTROL_VF_CACHE_INVALIDATE |
+                                 PIPE_CONTROL_CS_STALL;
                   ice->state.last_vbo_high_bits[i] = high_bits;
                }
 
@@ -4402,8 +4695,22 @@ iris_upload_dirty_render_state(struct iris_context *ice,
          if (flush_flags)
             iris_emit_pipe_control_flush(batch, flush_flags);
 
-         iris_batch_emit(batch, cso->vertex_buffers, sizeof(uint32_t) *
-                         (1 + vb_dwords * cso->num_buffers));
+         const unsigned vb_dwords = GENX(VERTEX_BUFFER_STATE_length);
+
+         uint32_t *map =
+            iris_get_command_space(batch, 4 * (1 + vb_dwords * count));
+         _iris_pack_command(batch, GENX(3DSTATE_VERTEX_BUFFERS), map, vb) {
+            vb.DWordLength = (vb_dwords * count + 1) - 2;
+         }
+         map += 1;
+
+         bound = ice->state.bound_vertex_buffers;
+         while (bound) {
+            const int i = u_bit_scan64(&bound);
+            memcpy(map, genx->vertex_buffers[i].state,
+                   sizeof(uint32_t) * vb_dwords);
+            map += vb_dwords;
+         }
       }
    }
 
@@ -4445,7 +4752,7 @@ iris_upload_dirty_render_state(struct iris_context *ice,
       }
    }
 
-   // XXX: Gen8 - PMA fix
+   /* TODO: Gen8 PMA fix */
 }
 
 static void
@@ -4487,7 +4794,7 @@ iris_upload_render_state(struct iris_context *ice,
 
       iris_emit_cmd(batch, GENX(3DSTATE_INDEX_BUFFER), ib) {
          ib.IndexFormat = draw->index_size >> 1;
-         ib.MOCS = MOCS_WB;
+         ib.MOCS = mocs(bo);
          ib.BufferSize = bo->size;
          ib.BufferStartingAddress = ro_bo(bo, offset);
       }
@@ -4495,7 +4802,8 @@ iris_upload_render_state(struct iris_context *ice,
       /* The VF cache key only uses 32-bits, see vertex buffer comment above */
       uint16_t high_bits = bo->gtt_offset >> 32ull;
       if (high_bits != ice->state.last_index_bo_high_bits) {
-         iris_emit_pipe_control_flush(batch, PIPE_CONTROL_VF_CACHE_INVALIDATE);
+         iris_emit_pipe_control_flush(batch, PIPE_CONTROL_VF_CACHE_INVALIDATE |
+                                             PIPE_CONTROL_CS_STALL);
          ice->state.last_index_bo_high_bits = high_bits;
       }
    }
@@ -4545,28 +4853,50 @@ iris_upload_render_state(struct iris_context *ice,
             lri.DataDWord = 0;
          }
       }
+   } else if (draw->count_from_stream_output) {
+      struct iris_stream_output_target *so =
+         (void *) draw->count_from_stream_output;
+
+      /* XXX: Replace with actual cache tracking */
+      iris_emit_pipe_control_flush(batch, PIPE_CONTROL_CS_STALL);
+
+      iris_emit_cmd(batch, GENX(MI_LOAD_REGISTER_MEM), lrm) {
+         lrm.RegisterAddress = CS_GPR(0);
+         lrm.MemoryAddress =
+            ro_bo(iris_resource_bo(so->offset.res), so->offset.offset);
+      }
+      iris_math_div32_gpr0(ice, batch, so->stride);
+      _iris_emit_lrr(batch, _3DPRIM_VERTEX_COUNT, CS_GPR(0));
+
+      _iris_emit_lri(batch, _3DPRIM_START_VERTEX, 0);
+      _iris_emit_lri(batch, _3DPRIM_BASE_VERTEX, 0);
+      _iris_emit_lri(batch, _3DPRIM_START_INSTANCE, 0);
+      _iris_emit_lri(batch, _3DPRIM_INSTANCE_COUNT, draw->instance_count);
    }
 
    iris_emit_cmd(batch, GENX(3DPRIMITIVE), prim) {
-      prim.StartInstanceLocation = draw->start_instance;
-      prim.InstanceCount = draw->instance_count;
-      prim.VertexCountPerInstance = draw->count;
       prim.VertexAccessType = draw->index_size > 0 ? RANDOM : SEQUENTIAL;
       prim.PredicateEnable =
          ice->state.predicate == IRIS_PREDICATE_STATE_USE_BIT;
 
-      // XXX: this is probably bonkers.
-      prim.StartVertexLocation = draw->start;
+      if (draw->indirect || draw->count_from_stream_output) {
+         prim.IndirectParameterEnable = true;
+      } else {
+         prim.StartInstanceLocation = draw->start_instance;
+         prim.InstanceCount = draw->instance_count;
+         prim.VertexCountPerInstance = draw->count;
 
-      prim.IndirectParameterEnable = draw->indirect != NULL;
+         // XXX: this is probably bonkers.
+         prim.StartVertexLocation = draw->start;
 
-      if (draw->index_size) {
-         prim.BaseVertexLocation += draw->index_bias;
-      } else {
-         prim.StartVertexLocation += draw->index_bias;
-      }
+         if (draw->index_size) {
+            prim.BaseVertexLocation += draw->index_bias;
+         } else {
+            prim.StartVertexLocation += draw->index_bias;
+         }
 
-      //prim.BaseVertexLocation = ...;
+         //prim.BaseVertexLocation = ...;
+      }
    }
 }
 
@@ -4585,6 +4915,13 @@ iris_upload_compute_state(struct iris_context *ice,
    struct brw_stage_prog_data *prog_data = shader->prog_data;
    struct brw_cs_prog_data *cs_prog_data = (void *) prog_data;
 
+   /* Always pin the binder.  If we're emitting new binding table pointers,
+    * we need it.  If not, we're probably inheriting old tables via the
+    * context, and need it anyway.  Since true zero-bindings cases are
+    * practically non-existent, just pin it and avoid last_res tracking.
+    */
+   iris_use_pinned_bo(batch, ice->state.binder.bo, false);
+
    if ((dirty & IRIS_DIRTY_CONSTANTS_CS) && shs->cbuf0_needs_upload)
       upload_uniforms(ice, MESA_SHADER_COMPUTE);
 
@@ -4610,11 +4947,11 @@ iris_upload_compute_state(struct iris_context *ice,
 
       iris_emit_cmd(batch, GENX(MEDIA_VFE_STATE), vfe) {
          if (prog_data->total_scratch) {
-            uint32_t scratch_addr =
+            struct iris_bo *bo =
                iris_get_scratch_space(ice, prog_data->total_scratch,
                                       MESA_SHADER_COMPUTE);
             vfe.PerThreadScratchSpace = ffs(prog_data->total_scratch) - 11;
-            vfe.ScratchSpaceBasePointer = rw_bo(NULL, scratch_addr);
+            vfe.ScratchSpaceBasePointer = rw_bo(bo, 0);
          }
 
          vfe.MaximumNumberofThreads =
@@ -4623,22 +4960,20 @@ iris_upload_compute_state(struct iris_context *ice,
          vfe.ResetGatewayTimer =
             Resettingrelativetimerandlatchingtheglobaltimestamp;
 #endif
-
+#if GEN_GEN == 8
+         vfe.BypassGatewayControl = true;
+#endif
          vfe.NumberofURBEntries = 2;
          vfe.URBEntryAllocationSize = 2;
 
-         // XXX: Use Indirect Payload Storage?
          vfe.CURBEAllocationSize =
             ALIGN(cs_prog_data->push.per_thread.regs * cs_prog_data->threads +
                   cs_prog_data->push.cross_thread.regs, 2);
       }
    }
 
-   // XXX: hack iris_set_constant_buffers to upload these thread counts
-   // XXX: along with regular uniforms for compute shaders, somehow.
-
+   /* TODO: Combine subgroup-id with cbuf0 so we can push regular uniforms */
    uint32_t curbe_data_offset = 0;
-   // TODO: Move subgroup-id into uniforms ubo so we can push uniforms
    assert(cs_prog_data->push.cross_thread.dwords == 0 &&
           cs_prog_data->push.per_thread.dwords == 1 &&
           cs_prog_data->base.param[0] == BRW_PARAM_BUILTIN_SUBGROUP_ID);
@@ -4742,9 +5077,15 @@ iris_upload_compute_state(struct iris_context *ice,
 static void
 iris_destroy_state(struct iris_context *ice)
 {
-   iris_free_vertex_buffers(&ice->state.genx->vertex_buffers);
+   struct iris_genx_state *genx = ice->state.genx;
+
+   uint64_t bound_vbs = ice->state.bound_vertex_buffers;
+   while (bound_vbs) {
+      const int i = u_bit_scan64(&bound_vbs);
+      pipe_resource_reference(&genx->vertex_buffers[i].resource, NULL);
+   }
+   free(ice->state.genx);
 
-   // XXX: unreference resources/surfaces.
    for (unsigned i = 0; i < ice->state.framebuffer.nr_cbufs; i++) {
       pipe_surface_reference(&ice->state.framebuffer.cbufs[i], NULL);
    }
@@ -4753,9 +5094,28 @@ iris_destroy_state(struct iris_context *ice)
    for (int stage = 0; stage < MESA_SHADER_STAGES; stage++) {
       struct iris_shader_state *shs = &ice->state.shaders[stage];
       pipe_resource_reference(&shs->sampler_table.res, NULL);
+      for (int i = 0; i < PIPE_MAX_CONSTANT_BUFFERS; i++) {
+         pipe_resource_reference(&shs->constbuf[i].data.res, NULL);
+         pipe_resource_reference(&shs->constbuf[i].surface_state.res, NULL);
+      }
+      for (int i = 0; i < PIPE_MAX_SHADER_IMAGES; i++) {
+         pipe_resource_reference(&shs->image[i].res, NULL);
+         pipe_resource_reference(&shs->image[i].surface_state.res, NULL);
+      }
+      for (int i = 0; i < PIPE_MAX_SHADER_BUFFERS; i++) {
+         pipe_resource_reference(&shs->ssbo[i], NULL);
+         pipe_resource_reference(&shs->ssbo_surface_state[i].res, NULL);
+      }
+      for (int i = 0; i < IRIS_MAX_TEXTURE_SAMPLERS; i++) {
+         pipe_sampler_view_reference((struct pipe_sampler_view **)
+                                     &shs->textures[i], NULL);
+      }
    }
-   free(ice->state.genx);
 
+   pipe_resource_reference(&ice->state.grid_size.res, NULL);
+   pipe_resource_reference(&ice->state.grid_surf_state.res, NULL);
+
+   pipe_resource_reference(&ice->state.null_fb.res, NULL);
    pipe_resource_reference(&ice->state.unbound_tex.res, NULL);
 
    pipe_resource_reference(&ice->state.last_res.cc_vp, NULL);
@@ -4769,18 +5129,18 @@ iris_destroy_state(struct iris_context *ice)
 /* ------------------------------------------------------------------- */
 
 static void
-iris_load_register_reg32(struct iris_batch *batch, uint32_t src,
-                         uint32_t dst)
+iris_load_register_reg32(struct iris_batch *batch, uint32_t dst,
+                         uint32_t src)
 {
-   _iris_emit_lrr(batch, src, dst);
+   _iris_emit_lrr(batch, dst, src);
 }
 
 static void
-iris_load_register_reg64(struct iris_batch *batch, uint32_t src,
-                         uint32_t dst)
+iris_load_register_reg64(struct iris_batch *batch, uint32_t dst,
+                         uint32_t src)
 {
-   _iris_emit_lrr(batch, src, dst);
-   _iris_emit_lrr(batch, src + 4, dst + 4);
+   _iris_emit_lrr(batch, dst, src);
+   _iris_emit_lrr(batch, dst + 4, src + 4);
 }
 
 static void