Home | History | Annotate | Download | only in radeonsi
      1 /*
      2  * Copyright 2012 Advanced Micro Devices, Inc.
      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  * on the rights to use, copy, modify, merge, publish, distribute, sub
      8  * license, and/or sell copies of the Software, and to permit persons to whom
      9  * the 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 NON-INFRINGEMENT. IN NO EVENT SHALL
     18  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
     19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
     20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
     21  * USE OR OTHER DEALINGS IN THE SOFTWARE.
     22  */
     23 
     24 #include "si_pipe.h"
     25 #include "radeon/r600_cs.h"
     26 #include "sid.h"
     27 #include "gfx9d.h"
     28 
     29 #include "util/u_index_modify.h"
     30 #include "util/u_log.h"
     31 #include "util/u_upload_mgr.h"
     32 #include "util/u_prim.h"
     33 
     34 #include "ac_debug.h"
     35 
     36 /* special primitive types */
     37 #define SI_PRIM_RECTANGLE_LIST	PIPE_PRIM_MAX
     38 
     39 static unsigned si_conv_pipe_prim(unsigned mode)
     40 {
     41         static const unsigned prim_conv[] = {
     42 		[PIPE_PRIM_POINTS]			= V_008958_DI_PT_POINTLIST,
     43 		[PIPE_PRIM_LINES]			= V_008958_DI_PT_LINELIST,
     44 		[PIPE_PRIM_LINE_LOOP]			= V_008958_DI_PT_LINELOOP,
     45 		[PIPE_PRIM_LINE_STRIP]			= V_008958_DI_PT_LINESTRIP,
     46 		[PIPE_PRIM_TRIANGLES]			= V_008958_DI_PT_TRILIST,
     47 		[PIPE_PRIM_TRIANGLE_STRIP]		= V_008958_DI_PT_TRISTRIP,
     48 		[PIPE_PRIM_TRIANGLE_FAN]		= V_008958_DI_PT_TRIFAN,
     49 		[PIPE_PRIM_QUADS]			= V_008958_DI_PT_QUADLIST,
     50 		[PIPE_PRIM_QUAD_STRIP]			= V_008958_DI_PT_QUADSTRIP,
     51 		[PIPE_PRIM_POLYGON]			= V_008958_DI_PT_POLYGON,
     52 		[PIPE_PRIM_LINES_ADJACENCY]		= V_008958_DI_PT_LINELIST_ADJ,
     53 		[PIPE_PRIM_LINE_STRIP_ADJACENCY]	= V_008958_DI_PT_LINESTRIP_ADJ,
     54 		[PIPE_PRIM_TRIANGLES_ADJACENCY]		= V_008958_DI_PT_TRILIST_ADJ,
     55 		[PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY]	= V_008958_DI_PT_TRISTRIP_ADJ,
     56 		[PIPE_PRIM_PATCHES]			= V_008958_DI_PT_PATCH,
     57 		[SI_PRIM_RECTANGLE_LIST]		= V_008958_DI_PT_RECTLIST
     58         };
     59 	assert(mode < ARRAY_SIZE(prim_conv));
     60 	return prim_conv[mode];
     61 }
     62 
     63 static unsigned si_conv_prim_to_gs_out(unsigned mode)
     64 {
     65 	static const int prim_conv[] = {
     66 		[PIPE_PRIM_POINTS]			= V_028A6C_OUTPRIM_TYPE_POINTLIST,
     67 		[PIPE_PRIM_LINES]			= V_028A6C_OUTPRIM_TYPE_LINESTRIP,
     68 		[PIPE_PRIM_LINE_LOOP]			= V_028A6C_OUTPRIM_TYPE_LINESTRIP,
     69 		[PIPE_PRIM_LINE_STRIP]			= V_028A6C_OUTPRIM_TYPE_LINESTRIP,
     70 		[PIPE_PRIM_TRIANGLES]			= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     71 		[PIPE_PRIM_TRIANGLE_STRIP]		= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     72 		[PIPE_PRIM_TRIANGLE_FAN]		= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     73 		[PIPE_PRIM_QUADS]			= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     74 		[PIPE_PRIM_QUAD_STRIP]			= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     75 		[PIPE_PRIM_POLYGON]			= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     76 		[PIPE_PRIM_LINES_ADJACENCY]		= V_028A6C_OUTPRIM_TYPE_LINESTRIP,
     77 		[PIPE_PRIM_LINE_STRIP_ADJACENCY]	= V_028A6C_OUTPRIM_TYPE_LINESTRIP,
     78 		[PIPE_PRIM_TRIANGLES_ADJACENCY]		= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     79 		[PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY]	= V_028A6C_OUTPRIM_TYPE_TRISTRIP,
     80 		[PIPE_PRIM_PATCHES]			= V_028A6C_OUTPRIM_TYPE_POINTLIST,
     81 		[SI_PRIM_RECTANGLE_LIST]		= V_028A6C_OUTPRIM_TYPE_TRISTRIP
     82 	};
     83 	assert(mode < ARRAY_SIZE(prim_conv));
     84 
     85 	return prim_conv[mode];
     86 }
     87 
     88 /**
     89  * This calculates the LDS size for tessellation shaders (VS, TCS, TES).
     90  * LS.LDS_SIZE is shared by all 3 shader stages.
     91  *
     92  * The information about LDS and other non-compile-time parameters is then
     93  * written to userdata SGPRs.
     94  */
     95 static void si_emit_derived_tess_state(struct si_context *sctx,
     96 				       const struct pipe_draw_info *info,
     97 				       unsigned *num_patches)
     98 {
     99 	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
    100 	struct si_shader *ls_current;
    101 	struct si_shader_selector *ls;
    102 	/* The TES pointer will only be used for sctx->last_tcs.
    103 	 * It would be wrong to think that TCS = TES. */
    104 	struct si_shader_selector *tcs =
    105 		sctx->tcs_shader.cso ? sctx->tcs_shader.cso : sctx->tes_shader.cso;
    106 	unsigned tess_uses_primid = sctx->ia_multi_vgt_param_key.u.tess_uses_prim_id;
    107 	bool has_primid_instancing_bug = sctx->b.chip_class == SI &&
    108 					 sctx->b.screen->info.max_se == 1;
    109 	unsigned tes_sh_base = sctx->shader_pointers.sh_base[PIPE_SHADER_TESS_EVAL];
    110 	unsigned num_tcs_input_cp = info->vertices_per_patch;
    111 	unsigned num_tcs_output_cp, num_tcs_inputs, num_tcs_outputs;
    112 	unsigned num_tcs_patch_outputs;
    113 	unsigned input_vertex_size, output_vertex_size, pervertex_output_patch_size;
    114 	unsigned input_patch_size, output_patch_size, output_patch0_offset;
    115 	unsigned perpatch_output_offset, lds_size;
    116 	unsigned tcs_in_layout, tcs_out_layout, tcs_out_offsets;
    117 	unsigned offchip_layout, hardware_lds_size, ls_hs_config;
    118 
    119 	/* Since GFX9 has merged LS-HS in the TCS state, set LS = TCS. */
    120 	if (sctx->b.chip_class >= GFX9) {
    121 		if (sctx->tcs_shader.cso)
    122 			ls_current = sctx->tcs_shader.current;
    123 		else
    124 			ls_current = sctx->fixed_func_tcs_shader.current;
    125 
    126 		ls = ls_current->key.part.tcs.ls;
    127 	} else {
    128 		ls_current = sctx->vs_shader.current;
    129 		ls = sctx->vs_shader.cso;
    130 	}
    131 
    132 	if (sctx->last_ls == ls_current &&
    133 	    sctx->last_tcs == tcs &&
    134 	    sctx->last_tes_sh_base == tes_sh_base &&
    135 	    sctx->last_num_tcs_input_cp == num_tcs_input_cp &&
    136 	    (!has_primid_instancing_bug ||
    137 	     (sctx->last_tess_uses_primid == tess_uses_primid))) {
    138 		*num_patches = sctx->last_num_patches;
    139 		return;
    140 	}
    141 
    142 	sctx->last_ls = ls_current;
    143 	sctx->last_tcs = tcs;
    144 	sctx->last_tes_sh_base = tes_sh_base;
    145 	sctx->last_num_tcs_input_cp = num_tcs_input_cp;
    146 	sctx->last_tess_uses_primid = tess_uses_primid;
    147 
    148 	/* This calculates how shader inputs and outputs among VS, TCS, and TES
    149 	 * are laid out in LDS. */
    150 	num_tcs_inputs = util_last_bit64(ls->outputs_written);
    151 
    152 	if (sctx->tcs_shader.cso) {
    153 		num_tcs_outputs = util_last_bit64(tcs->outputs_written);
    154 		num_tcs_output_cp = tcs->info.properties[TGSI_PROPERTY_TCS_VERTICES_OUT];
    155 		num_tcs_patch_outputs = util_last_bit64(tcs->patch_outputs_written);
    156 	} else {
    157 		/* No TCS. Route varyings from LS to TES. */
    158 		num_tcs_outputs = num_tcs_inputs;
    159 		num_tcs_output_cp = num_tcs_input_cp;
    160 		num_tcs_patch_outputs = 2; /* TESSINNER + TESSOUTER */
    161 	}
    162 
    163 	input_vertex_size = num_tcs_inputs * 16;
    164 	output_vertex_size = num_tcs_outputs * 16;
    165 
    166 	input_patch_size = num_tcs_input_cp * input_vertex_size;
    167 
    168 	pervertex_output_patch_size = num_tcs_output_cp * output_vertex_size;
    169 	output_patch_size = pervertex_output_patch_size + num_tcs_patch_outputs * 16;
    170 
    171 	/* Ensure that we only need one wave per SIMD so we don't need to check
    172 	 * resource usage. Also ensures that the number of tcs in and out
    173 	 * vertices per threadgroup are at most 256.
    174 	 */
    175 	*num_patches = 64 / MAX2(num_tcs_input_cp, num_tcs_output_cp) * 4;
    176 
    177 	/* Make sure that the data fits in LDS. This assumes the shaders only
    178 	 * use LDS for the inputs and outputs.
    179 	 *
    180 	 * While CIK can use 64K per threadgroup, there is a hang on Stoney
    181 	 * with 2 CUs if we use more than 32K. The closed Vulkan driver also
    182 	 * uses 32K at most on all GCN chips.
    183 	 */
    184 	hardware_lds_size = 32768;
    185 	*num_patches = MIN2(*num_patches, hardware_lds_size / (input_patch_size +
    186 	                                                       output_patch_size));
    187 
    188 	/* Make sure the output data fits in the offchip buffer */
    189 	*num_patches = MIN2(*num_patches,
    190 			    (sctx->screen->tess_offchip_block_dw_size * 4) /
    191 			    output_patch_size);
    192 
    193 	/* Not necessary for correctness, but improves performance. The
    194 	 * specific value is taken from the proprietary driver.
    195 	 */
    196 	*num_patches = MIN2(*num_patches, 40);
    197 
    198 	if (sctx->b.chip_class == SI) {
    199 		/* SI bug workaround, related to power management. Limit LS-HS
    200 		 * threadgroups to only one wave.
    201 		 */
    202 		unsigned one_wave = 64 / MAX2(num_tcs_input_cp, num_tcs_output_cp);
    203 		*num_patches = MIN2(*num_patches, one_wave);
    204 	}
    205 
    206 	/* The VGT HS block increments the patch ID unconditionally
    207 	 * within a single threadgroup. This results in incorrect
    208 	 * patch IDs when instanced draws are used.
    209 	 *
    210 	 * The intended solution is to restrict threadgroups to
    211 	 * a single instance by setting SWITCH_ON_EOI, which
    212 	 * should cause IA to split instances up. However, this
    213 	 * doesn't work correctly on SI when there is no other
    214 	 * SE to switch to.
    215 	 */
    216 	if (has_primid_instancing_bug && tess_uses_primid)
    217 		*num_patches = 1;
    218 
    219 	sctx->last_num_patches = *num_patches;
    220 
    221 	output_patch0_offset = input_patch_size * *num_patches;
    222 	perpatch_output_offset = output_patch0_offset + pervertex_output_patch_size;
    223 
    224 	/* Compute userdata SGPRs. */
    225 	assert(((input_vertex_size / 4) & ~0xff) == 0);
    226 	assert(((output_vertex_size / 4) & ~0xff) == 0);
    227 	assert(((input_patch_size / 4) & ~0x1fff) == 0);
    228 	assert(((output_patch_size / 4) & ~0x1fff) == 0);
    229 	assert(((output_patch0_offset / 16) & ~0xffff) == 0);
    230 	assert(((perpatch_output_offset / 16) & ~0xffff) == 0);
    231 	assert(num_tcs_input_cp <= 32);
    232 	assert(num_tcs_output_cp <= 32);
    233 
    234 	tcs_in_layout = S_VS_STATE_LS_OUT_PATCH_SIZE(input_patch_size / 4) |
    235 			S_VS_STATE_LS_OUT_VERTEX_SIZE(input_vertex_size / 4);
    236 	tcs_out_layout = output_patch_size / 4;
    237 	tcs_out_offsets = (output_patch0_offset / 16) |
    238 			  ((perpatch_output_offset / 16) << 16);
    239 	offchip_layout = *num_patches |
    240 			 (num_tcs_output_cp << 6) |
    241 			 (pervertex_output_patch_size * *num_patches << 12);
    242 
    243 	/* Compute the LDS size. */
    244 	lds_size = output_patch0_offset + output_patch_size * *num_patches;
    245 
    246 	if (sctx->b.chip_class >= CIK) {
    247 		assert(lds_size <= 65536);
    248 		lds_size = align(lds_size, 512) / 512;
    249 	} else {
    250 		assert(lds_size <= 32768);
    251 		lds_size = align(lds_size, 256) / 256;
    252 	}
    253 
    254 	/* Set SI_SGPR_VS_STATE_BITS. */
    255 	sctx->current_vs_state &= C_VS_STATE_LS_OUT_PATCH_SIZE &
    256 				  C_VS_STATE_LS_OUT_VERTEX_SIZE;
    257 	sctx->current_vs_state |= tcs_in_layout;
    258 
    259 	if (sctx->b.chip_class >= GFX9) {
    260 		unsigned hs_rsrc2 = ls_current->config.rsrc2 |
    261 				    S_00B42C_LDS_SIZE(lds_size);
    262 
    263 		radeon_set_sh_reg(cs, R_00B42C_SPI_SHADER_PGM_RSRC2_HS, hs_rsrc2);
    264 
    265 		/* Set userdata SGPRs for merged LS-HS. */
    266 		radeon_set_sh_reg_seq(cs,
    267 				      R_00B430_SPI_SHADER_USER_DATA_LS_0 +
    268 				      GFX9_SGPR_TCS_OFFCHIP_LAYOUT * 4, 3);
    269 		radeon_emit(cs, offchip_layout);
    270 		radeon_emit(cs, tcs_out_offsets);
    271 		radeon_emit(cs, tcs_out_layout | (num_tcs_input_cp << 26));
    272 	} else {
    273 		unsigned ls_rsrc2 = ls_current->config.rsrc2;
    274 
    275 		si_multiwave_lds_size_workaround(sctx->screen, &lds_size);
    276 		ls_rsrc2 |= S_00B52C_LDS_SIZE(lds_size);
    277 
    278 		/* Due to a hw bug, RSRC2_LS must be written twice with another
    279 		 * LS register written in between. */
    280 		if (sctx->b.chip_class == CIK && sctx->b.family != CHIP_HAWAII)
    281 			radeon_set_sh_reg(cs, R_00B52C_SPI_SHADER_PGM_RSRC2_LS, ls_rsrc2);
    282 		radeon_set_sh_reg_seq(cs, R_00B528_SPI_SHADER_PGM_RSRC1_LS, 2);
    283 		radeon_emit(cs, ls_current->config.rsrc1);
    284 		radeon_emit(cs, ls_rsrc2);
    285 
    286 		/* Set userdata SGPRs for TCS. */
    287 		radeon_set_sh_reg_seq(cs,
    288 			R_00B430_SPI_SHADER_USER_DATA_HS_0 + GFX6_SGPR_TCS_OFFCHIP_LAYOUT * 4, 4);
    289 		radeon_emit(cs, offchip_layout);
    290 		radeon_emit(cs, tcs_out_offsets);
    291 		radeon_emit(cs, tcs_out_layout | (num_tcs_input_cp << 26));
    292 		radeon_emit(cs, tcs_in_layout);
    293 	}
    294 
    295 	/* Set userdata SGPRs for TES. */
    296 	radeon_set_sh_reg_seq(cs, tes_sh_base + SI_SGPR_TES_OFFCHIP_LAYOUT * 4, 2);
    297 	radeon_emit(cs, offchip_layout);
    298 	radeon_emit(cs, r600_resource(sctx->tess_offchip_ring)->gpu_address >> 16);
    299 
    300 	ls_hs_config = S_028B58_NUM_PATCHES(*num_patches) |
    301 		       S_028B58_HS_NUM_INPUT_CP(num_tcs_input_cp) |
    302 		       S_028B58_HS_NUM_OUTPUT_CP(num_tcs_output_cp);
    303 
    304 	if (sctx->b.chip_class >= CIK)
    305 		radeon_set_context_reg_idx(cs, R_028B58_VGT_LS_HS_CONFIG, 2,
    306 					   ls_hs_config);
    307 	else
    308 		radeon_set_context_reg(cs, R_028B58_VGT_LS_HS_CONFIG,
    309 				       ls_hs_config);
    310 }
    311 
    312 static unsigned si_num_prims_for_vertices(const struct pipe_draw_info *info)
    313 {
    314 	switch (info->mode) {
    315 	case PIPE_PRIM_PATCHES:
    316 		return info->count / info->vertices_per_patch;
    317 	case SI_PRIM_RECTANGLE_LIST:
    318 		return info->count / 3;
    319 	default:
    320 		return u_prims_for_vertices(info->mode, info->count);
    321 	}
    322 }
    323 
    324 static unsigned
    325 si_get_init_multi_vgt_param(struct si_screen *sscreen,
    326 			    union si_vgt_param_key *key)
    327 {
    328 	STATIC_ASSERT(sizeof(union si_vgt_param_key) == 4);
    329 	unsigned max_primgroup_in_wave = 2;
    330 
    331 	/* SWITCH_ON_EOP(0) is always preferable. */
    332 	bool wd_switch_on_eop = false;
    333 	bool ia_switch_on_eop = false;
    334 	bool ia_switch_on_eoi = false;
    335 	bool partial_vs_wave = false;
    336 	bool partial_es_wave = false;
    337 
    338 	if (key->u.uses_tess) {
    339 		/* SWITCH_ON_EOI must be set if PrimID is used. */
    340 		if (key->u.tess_uses_prim_id)
    341 			ia_switch_on_eoi = true;
    342 
    343 		/* Bug with tessellation and GS on Bonaire and older 2 SE chips. */
    344 		if ((sscreen->info.family == CHIP_TAHITI ||
    345 		     sscreen->info.family == CHIP_PITCAIRN ||
    346 		     sscreen->info.family == CHIP_BONAIRE) &&
    347 		    key->u.uses_gs)
    348 			partial_vs_wave = true;
    349 
    350 		/* Needed for 028B6C_DISTRIBUTION_MODE != 0 */
    351 		if (sscreen->has_distributed_tess) {
    352 			if (key->u.uses_gs) {
    353 				if (sscreen->info.chip_class <= VI)
    354 					partial_es_wave = true;
    355 
    356 				/* GPU hang workaround. */
    357 				if (sscreen->info.family == CHIP_TONGA ||
    358 				    sscreen->info.family == CHIP_FIJI ||
    359 				    sscreen->info.family == CHIP_POLARIS10 ||
    360 				    sscreen->info.family == CHIP_POLARIS11 ||
    361 				    sscreen->info.family == CHIP_POLARIS12)
    362 					partial_vs_wave = true;
    363 			} else {
    364 				partial_vs_wave = true;
    365 			}
    366 		}
    367 	}
    368 
    369 	/* This is a hardware requirement. */
    370 	if (key->u.line_stipple_enabled ||
    371 	    (sscreen->debug_flags & DBG(SWITCH_ON_EOP))) {
    372 		ia_switch_on_eop = true;
    373 		wd_switch_on_eop = true;
    374 	}
    375 
    376 	if (sscreen->info.chip_class >= CIK) {
    377 		/* WD_SWITCH_ON_EOP has no effect on GPUs with less than
    378 		 * 4 shader engines. Set 1 to pass the assertion below.
    379 		 * The other cases are hardware requirements.
    380 		 *
    381 		 * Polaris supports primitive restart with WD_SWITCH_ON_EOP=0
    382 		 * for points, line strips, and tri strips.
    383 		 */
    384 		if (sscreen->info.max_se < 4 ||
    385 		    key->u.prim == PIPE_PRIM_POLYGON ||
    386 		    key->u.prim == PIPE_PRIM_LINE_LOOP ||
    387 		    key->u.prim == PIPE_PRIM_TRIANGLE_FAN ||
    388 		    key->u.prim == PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY ||
    389 		    (key->u.primitive_restart &&
    390 		     (sscreen->info.family < CHIP_POLARIS10 ||
    391 		      (key->u.prim != PIPE_PRIM_POINTS &&
    392 		       key->u.prim != PIPE_PRIM_LINE_STRIP &&
    393 		       key->u.prim != PIPE_PRIM_TRIANGLE_STRIP))) ||
    394 		    key->u.count_from_stream_output)
    395 			wd_switch_on_eop = true;
    396 
    397 		/* Hawaii hangs if instancing is enabled and WD_SWITCH_ON_EOP is 0.
    398 		 * We don't know that for indirect drawing, so treat it as
    399 		 * always problematic. */
    400 		if (sscreen->info.family == CHIP_HAWAII &&
    401 		    key->u.uses_instancing)
    402 			wd_switch_on_eop = true;
    403 
    404 		/* Performance recommendation for 4 SE Gfx7-8 parts if
    405 		 * instances are smaller than a primgroup.
    406 		 * Assume indirect draws always use small instances.
    407 		 * This is needed for good VS wave utilization.
    408 		 */
    409 		if (sscreen->info.chip_class <= VI &&
    410 		    sscreen->info.max_se == 4 &&
    411 		    key->u.multi_instances_smaller_than_primgroup)
    412 			wd_switch_on_eop = true;
    413 
    414 		/* Required on CIK and later. */
    415 		if (sscreen->info.max_se > 2 && !wd_switch_on_eop)
    416 			ia_switch_on_eoi = true;
    417 
    418 		/* Required by Hawaii and, for some special cases, by VI. */
    419 		if (ia_switch_on_eoi &&
    420 		    (sscreen->info.family == CHIP_HAWAII ||
    421 		     (sscreen->info.chip_class == VI &&
    422 		      (key->u.uses_gs || max_primgroup_in_wave != 2))))
    423 			partial_vs_wave = true;
    424 
    425 		/* Instancing bug on Bonaire. */
    426 		if (sscreen->info.family == CHIP_BONAIRE && ia_switch_on_eoi &&
    427 		    key->u.uses_instancing)
    428 			partial_vs_wave = true;
    429 
    430 		/* If the WD switch is false, the IA switch must be false too. */
    431 		assert(wd_switch_on_eop || !ia_switch_on_eop);
    432 	}
    433 
    434 	/* If SWITCH_ON_EOI is set, PARTIAL_ES_WAVE must be set too. */
    435 	if (sscreen->info.chip_class <= VI && ia_switch_on_eoi)
    436 		partial_es_wave = true;
    437 
    438 	return S_028AA8_SWITCH_ON_EOP(ia_switch_on_eop) |
    439 		S_028AA8_SWITCH_ON_EOI(ia_switch_on_eoi) |
    440 		S_028AA8_PARTIAL_VS_WAVE_ON(partial_vs_wave) |
    441 		S_028AA8_PARTIAL_ES_WAVE_ON(partial_es_wave) |
    442 		S_028AA8_WD_SWITCH_ON_EOP(sscreen->info.chip_class >= CIK ? wd_switch_on_eop : 0) |
    443 		/* The following field was moved to VGT_SHADER_STAGES_EN in GFX9. */
    444 		S_028AA8_MAX_PRIMGRP_IN_WAVE(sscreen->info.chip_class == VI ?
    445 					     max_primgroup_in_wave : 0) |
    446 		S_030960_EN_INST_OPT_BASIC(sscreen->info.chip_class >= GFX9) |
    447 		S_030960_EN_INST_OPT_ADV(sscreen->info.chip_class >= GFX9);
    448 }
    449 
    450 void si_init_ia_multi_vgt_param_table(struct si_context *sctx)
    451 {
    452 	for (int prim = 0; prim <= SI_PRIM_RECTANGLE_LIST; prim++)
    453 	for (int uses_instancing = 0; uses_instancing < 2; uses_instancing++)
    454 	for (int multi_instances = 0; multi_instances < 2; multi_instances++)
    455 	for (int primitive_restart = 0; primitive_restart < 2; primitive_restart++)
    456 	for (int count_from_so = 0; count_from_so < 2; count_from_so++)
    457 	for (int line_stipple = 0; line_stipple < 2; line_stipple++)
    458 	for (int uses_tess = 0; uses_tess < 2; uses_tess++)
    459 	for (int tess_uses_primid = 0; tess_uses_primid < 2; tess_uses_primid++)
    460 	for (int uses_gs = 0; uses_gs < 2; uses_gs++) {
    461 		union si_vgt_param_key key;
    462 
    463 		key.index = 0;
    464 		key.u.prim = prim;
    465 		key.u.uses_instancing = uses_instancing;
    466 		key.u.multi_instances_smaller_than_primgroup = multi_instances;
    467 		key.u.primitive_restart = primitive_restart;
    468 		key.u.count_from_stream_output = count_from_so;
    469 		key.u.line_stipple_enabled = line_stipple;
    470 		key.u.uses_tess = uses_tess;
    471 		key.u.tess_uses_prim_id = tess_uses_primid;
    472 		key.u.uses_gs = uses_gs;
    473 
    474 		sctx->ia_multi_vgt_param[key.index] =
    475 			si_get_init_multi_vgt_param(sctx->screen, &key);
    476 	}
    477 }
    478 
    479 static unsigned si_get_ia_multi_vgt_param(struct si_context *sctx,
    480 					  const struct pipe_draw_info *info,
    481 					  unsigned num_patches)
    482 {
    483 	union si_vgt_param_key key = sctx->ia_multi_vgt_param_key;
    484 	unsigned primgroup_size;
    485 	unsigned ia_multi_vgt_param;
    486 
    487 	if (sctx->tes_shader.cso) {
    488 		primgroup_size = num_patches; /* must be a multiple of NUM_PATCHES */
    489 	} else if (sctx->gs_shader.cso) {
    490 		primgroup_size = 64; /* recommended with a GS */
    491 	} else {
    492 		primgroup_size = 128; /* recommended without a GS and tess */
    493 	}
    494 
    495 	key.u.prim = info->mode;
    496 	key.u.uses_instancing = info->indirect || info->instance_count > 1;
    497 	key.u.multi_instances_smaller_than_primgroup =
    498 		info->indirect ||
    499 		(info->instance_count > 1 &&
    500 		 (info->count_from_stream_output ||
    501 		  si_num_prims_for_vertices(info) < primgroup_size));
    502 	key.u.primitive_restart = info->primitive_restart;
    503 	key.u.count_from_stream_output = info->count_from_stream_output != NULL;
    504 
    505 	ia_multi_vgt_param = sctx->ia_multi_vgt_param[key.index] |
    506 			     S_028AA8_PRIMGROUP_SIZE(primgroup_size - 1);
    507 
    508 	if (sctx->gs_shader.cso) {
    509 		/* GS requirement. */
    510 		if (sctx->b.chip_class <= VI &&
    511 		    SI_GS_PER_ES / primgroup_size >= sctx->screen->gs_table_depth - 3)
    512 			ia_multi_vgt_param |= S_028AA8_PARTIAL_ES_WAVE_ON(1);
    513 
    514 		/* GS hw bug with single-primitive instances and SWITCH_ON_EOI.
    515 		 * The hw doc says all multi-SE chips are affected, but Vulkan
    516 		 * only applies it to Hawaii. Do what Vulkan does.
    517 		 */
    518 		if (sctx->b.family == CHIP_HAWAII &&
    519 		    G_028AA8_SWITCH_ON_EOI(ia_multi_vgt_param) &&
    520 		    (info->indirect ||
    521 		     (info->instance_count > 1 &&
    522 		      (info->count_from_stream_output ||
    523 		       si_num_prims_for_vertices(info) <= 1))))
    524 			sctx->b.flags |= SI_CONTEXT_VGT_FLUSH;
    525 	}
    526 
    527 	return ia_multi_vgt_param;
    528 }
    529 
    530 /* rast_prim is the primitive type after GS. */
    531 static void si_emit_rasterizer_prim_state(struct si_context *sctx)
    532 {
    533 	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
    534 	enum pipe_prim_type rast_prim = sctx->current_rast_prim;
    535 	struct si_state_rasterizer *rs = sctx->emitted.named.rasterizer;
    536 
    537 	/* Skip this if not rendering lines. */
    538 	if (rast_prim != PIPE_PRIM_LINES &&
    539 	    rast_prim != PIPE_PRIM_LINE_LOOP &&
    540 	    rast_prim != PIPE_PRIM_LINE_STRIP &&
    541 	    rast_prim != PIPE_PRIM_LINES_ADJACENCY &&
    542 	    rast_prim != PIPE_PRIM_LINE_STRIP_ADJACENCY)
    543 		return;
    544 
    545 	if (rast_prim == sctx->last_rast_prim &&
    546 	    rs->pa_sc_line_stipple == sctx->last_sc_line_stipple)
    547 		return;
    548 
    549 	/* For lines, reset the stipple pattern at each primitive. Otherwise,
    550 	 * reset the stipple pattern at each packet (line strips, line loops).
    551 	 */
    552 	radeon_set_context_reg(cs, R_028A0C_PA_SC_LINE_STIPPLE,
    553 		rs->pa_sc_line_stipple |
    554 		S_028A0C_AUTO_RESET_CNTL(rast_prim == PIPE_PRIM_LINES ? 1 : 2));
    555 
    556 	sctx->last_rast_prim = rast_prim;
    557 	sctx->last_sc_line_stipple = rs->pa_sc_line_stipple;
    558 }
    559 
    560 static void si_emit_vs_state(struct si_context *sctx,
    561 			     const struct pipe_draw_info *info)
    562 {
    563 	sctx->current_vs_state &= C_VS_STATE_INDEXED;
    564 	sctx->current_vs_state |= S_VS_STATE_INDEXED(!!info->index_size);
    565 
    566 	if (sctx->num_vs_blit_sgprs) {
    567 		/* Re-emit the state after we leave u_blitter. */
    568 		sctx->last_vs_state = ~0;
    569 		return;
    570 	}
    571 
    572 	if (sctx->current_vs_state != sctx->last_vs_state) {
    573 		struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
    574 
    575 		radeon_set_sh_reg(cs,
    576 			sctx->shader_pointers.sh_base[PIPE_SHADER_VERTEX] +
    577 			SI_SGPR_VS_STATE_BITS * 4,
    578 			sctx->current_vs_state);
    579 
    580 		sctx->last_vs_state = sctx->current_vs_state;
    581 	}
    582 }
    583 
    584 static void si_emit_draw_registers(struct si_context *sctx,
    585 				   const struct pipe_draw_info *info,
    586 				   unsigned num_patches)
    587 {
    588 	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
    589 	unsigned prim = si_conv_pipe_prim(info->mode);
    590 	unsigned gs_out_prim = si_conv_prim_to_gs_out(sctx->current_rast_prim);
    591 	unsigned ia_multi_vgt_param;
    592 
    593 	ia_multi_vgt_param = si_get_ia_multi_vgt_param(sctx, info, num_patches);
    594 
    595 	/* Draw state. */
    596 	if (ia_multi_vgt_param != sctx->last_multi_vgt_param) {
    597 		if (sctx->b.chip_class >= GFX9)
    598 			radeon_set_uconfig_reg_idx(cs, R_030960_IA_MULTI_VGT_PARAM, 4, ia_multi_vgt_param);
    599 		else if (sctx->b.chip_class >= CIK)
    600 			radeon_set_context_reg_idx(cs, R_028AA8_IA_MULTI_VGT_PARAM, 1, ia_multi_vgt_param);
    601 		else
    602 			radeon_set_context_reg(cs, R_028AA8_IA_MULTI_VGT_PARAM, ia_multi_vgt_param);
    603 
    604 		sctx->last_multi_vgt_param = ia_multi_vgt_param;
    605 	}
    606 	if (prim != sctx->last_prim) {
    607 		if (sctx->b.chip_class >= CIK)
    608 			radeon_set_uconfig_reg_idx(cs, R_030908_VGT_PRIMITIVE_TYPE, 1, prim);
    609 		else
    610 			radeon_set_config_reg(cs, R_008958_VGT_PRIMITIVE_TYPE, prim);
    611 
    612 		sctx->last_prim = prim;
    613 	}
    614 
    615 	if (gs_out_prim != sctx->last_gs_out_prim) {
    616 		radeon_set_context_reg(cs, R_028A6C_VGT_GS_OUT_PRIM_TYPE, gs_out_prim);
    617 		sctx->last_gs_out_prim = gs_out_prim;
    618 	}
    619 
    620 	/* Primitive restart. */
    621 	if (info->primitive_restart != sctx->last_primitive_restart_en) {
    622 		if (sctx->b.chip_class >= GFX9)
    623 			radeon_set_uconfig_reg(cs, R_03092C_VGT_MULTI_PRIM_IB_RESET_EN,
    624 					       info->primitive_restart);
    625 		else
    626 			radeon_set_context_reg(cs, R_028A94_VGT_MULTI_PRIM_IB_RESET_EN,
    627 					       info->primitive_restart);
    628 
    629 		sctx->last_primitive_restart_en = info->primitive_restart;
    630 
    631 	}
    632 	if (info->primitive_restart &&
    633 	    (info->restart_index != sctx->last_restart_index ||
    634 	     sctx->last_restart_index == SI_RESTART_INDEX_UNKNOWN)) {
    635 		radeon_set_context_reg(cs, R_02840C_VGT_MULTI_PRIM_IB_RESET_INDX,
    636 				       info->restart_index);
    637 		sctx->last_restart_index = info->restart_index;
    638 	}
    639 }
    640 
    641 static void si_emit_draw_packets(struct si_context *sctx,
    642 				 const struct pipe_draw_info *info,
    643 				 struct pipe_resource *indexbuf,
    644 				 unsigned index_size,
    645 				 unsigned index_offset)
    646 {
    647 	struct pipe_draw_indirect_info *indirect = info->indirect;
    648 	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
    649 	unsigned sh_base_reg = sctx->shader_pointers.sh_base[PIPE_SHADER_VERTEX];
    650 	bool render_cond_bit = sctx->b.render_cond && !sctx->b.render_cond_force_off;
    651 	uint32_t index_max_size = 0;
    652 	uint64_t index_va = 0;
    653 
    654 	if (info->count_from_stream_output) {
    655 		struct si_streamout_target *t =
    656 			(struct si_streamout_target*)info->count_from_stream_output;
    657 		uint64_t va = t->buf_filled_size->gpu_address +
    658 			      t->buf_filled_size_offset;
    659 
    660 		radeon_set_context_reg(cs, R_028B30_VGT_STRMOUT_DRAW_OPAQUE_VERTEX_STRIDE,
    661 				       t->stride_in_dw);
    662 
    663 		radeon_emit(cs, PKT3(PKT3_COPY_DATA, 4, 0));
    664 		radeon_emit(cs, COPY_DATA_SRC_SEL(COPY_DATA_MEM) |
    665 			    COPY_DATA_DST_SEL(COPY_DATA_REG) |
    666 			    COPY_DATA_WR_CONFIRM);
    667 		radeon_emit(cs, va);     /* src address lo */
    668 		radeon_emit(cs, va >> 32); /* src address hi */
    669 		radeon_emit(cs, R_028B2C_VGT_STRMOUT_DRAW_OPAQUE_BUFFER_FILLED_SIZE >> 2);
    670 		radeon_emit(cs, 0); /* unused */
    671 
    672 		radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
    673 				      t->buf_filled_size, RADEON_USAGE_READ,
    674 				      RADEON_PRIO_SO_FILLED_SIZE);
    675 	}
    676 
    677 	/* draw packet */
    678 	if (index_size) {
    679 		if (index_size != sctx->last_index_size) {
    680 			unsigned index_type;
    681 
    682 			/* index type */
    683 			switch (index_size) {
    684 			case 1:
    685 				index_type = V_028A7C_VGT_INDEX_8;
    686 				break;
    687 			case 2:
    688 				index_type = V_028A7C_VGT_INDEX_16 |
    689 					     (SI_BIG_ENDIAN && sctx->b.chip_class <= CIK ?
    690 						      V_028A7C_VGT_DMA_SWAP_16_BIT : 0);
    691 				break;
    692 			case 4:
    693 				index_type = V_028A7C_VGT_INDEX_32 |
    694 					     (SI_BIG_ENDIAN && sctx->b.chip_class <= CIK ?
    695 						      V_028A7C_VGT_DMA_SWAP_32_BIT : 0);
    696 				break;
    697 			default:
    698 				assert(!"unreachable");
    699 				return;
    700 			}
    701 
    702 			if (sctx->b.chip_class >= GFX9) {
    703 				radeon_set_uconfig_reg_idx(cs, R_03090C_VGT_INDEX_TYPE,
    704 							   2, index_type);
    705 			} else {
    706 				radeon_emit(cs, PKT3(PKT3_INDEX_TYPE, 0, 0));
    707 				radeon_emit(cs, index_type);
    708 			}
    709 
    710 			sctx->last_index_size = index_size;
    711 		}
    712 
    713 		index_max_size = (indexbuf->width0 - index_offset) /
    714 				  index_size;
    715 		index_va = r600_resource(indexbuf)->gpu_address + index_offset;
    716 
    717 		radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
    718 				      (struct r600_resource *)indexbuf,
    719 				      RADEON_USAGE_READ, RADEON_PRIO_INDEX_BUFFER);
    720 	} else {
    721 		/* On CI and later, non-indexed draws overwrite VGT_INDEX_TYPE,
    722 		 * so the state must be re-emitted before the next indexed draw.
    723 		 */
    724 		if (sctx->b.chip_class >= CIK)
    725 			sctx->last_index_size = -1;
    726 	}
    727 
    728 	if (indirect) {
    729 		uint64_t indirect_va = r600_resource(indirect->buffer)->gpu_address;
    730 
    731 		assert(indirect_va % 8 == 0);
    732 
    733 		si_invalidate_draw_sh_constants(sctx);
    734 
    735 		radeon_emit(cs, PKT3(PKT3_SET_BASE, 2, 0));
    736 		radeon_emit(cs, 1);
    737 		radeon_emit(cs, indirect_va);
    738 		radeon_emit(cs, indirect_va >> 32);
    739 
    740 		radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
    741 				      (struct r600_resource *)indirect->buffer,
    742 				      RADEON_USAGE_READ, RADEON_PRIO_DRAW_INDIRECT);
    743 
    744 		unsigned di_src_sel = index_size ? V_0287F0_DI_SRC_SEL_DMA
    745 						    : V_0287F0_DI_SRC_SEL_AUTO_INDEX;
    746 
    747 		assert(indirect->offset % 4 == 0);
    748 
    749 		if (index_size) {
    750 			radeon_emit(cs, PKT3(PKT3_INDEX_BASE, 1, 0));
    751 			radeon_emit(cs, index_va);
    752 			radeon_emit(cs, index_va >> 32);
    753 
    754 			radeon_emit(cs, PKT3(PKT3_INDEX_BUFFER_SIZE, 0, 0));
    755 			radeon_emit(cs, index_max_size);
    756 		}
    757 
    758 		if (!sctx->screen->has_draw_indirect_multi) {
    759 			radeon_emit(cs, PKT3(index_size ? PKT3_DRAW_INDEX_INDIRECT
    760 							   : PKT3_DRAW_INDIRECT,
    761 					     3, render_cond_bit));
    762 			radeon_emit(cs, indirect->offset);
    763 			radeon_emit(cs, (sh_base_reg + SI_SGPR_BASE_VERTEX * 4 - SI_SH_REG_OFFSET) >> 2);
    764 			radeon_emit(cs, (sh_base_reg + SI_SGPR_START_INSTANCE * 4 - SI_SH_REG_OFFSET) >> 2);
    765 			radeon_emit(cs, di_src_sel);
    766 		} else {
    767 			uint64_t count_va = 0;
    768 
    769 			if (indirect->indirect_draw_count) {
    770 				struct r600_resource *params_buf =
    771 					(struct r600_resource *)indirect->indirect_draw_count;
    772 
    773 				radeon_add_to_buffer_list(
    774 					&sctx->b, &sctx->b.gfx, params_buf,
    775 					RADEON_USAGE_READ, RADEON_PRIO_DRAW_INDIRECT);
    776 
    777 				count_va = params_buf->gpu_address + indirect->indirect_draw_count_offset;
    778 			}
    779 
    780 			radeon_emit(cs, PKT3(index_size ? PKT3_DRAW_INDEX_INDIRECT_MULTI :
    781 							     PKT3_DRAW_INDIRECT_MULTI,
    782 					     8, render_cond_bit));
    783 			radeon_emit(cs, indirect->offset);
    784 			radeon_emit(cs, (sh_base_reg + SI_SGPR_BASE_VERTEX * 4 - SI_SH_REG_OFFSET) >> 2);
    785 			radeon_emit(cs, (sh_base_reg + SI_SGPR_START_INSTANCE * 4 - SI_SH_REG_OFFSET) >> 2);
    786 			radeon_emit(cs, ((sh_base_reg + SI_SGPR_DRAWID * 4 - SI_SH_REG_OFFSET) >> 2) |
    787 					S_2C3_DRAW_INDEX_ENABLE(1) |
    788 					S_2C3_COUNT_INDIRECT_ENABLE(!!indirect->indirect_draw_count));
    789 			radeon_emit(cs, indirect->draw_count);
    790 			radeon_emit(cs, count_va);
    791 			radeon_emit(cs, count_va >> 32);
    792 			radeon_emit(cs, indirect->stride);
    793 			radeon_emit(cs, di_src_sel);
    794 		}
    795 	} else {
    796 		int base_vertex;
    797 
    798 		radeon_emit(cs, PKT3(PKT3_NUM_INSTANCES, 0, 0));
    799 		radeon_emit(cs, info->instance_count);
    800 
    801 		/* Base vertex and start instance. */
    802 		base_vertex = index_size ? info->index_bias : info->start;
    803 
    804 		if (sctx->num_vs_blit_sgprs) {
    805 			/* Re-emit draw constants after we leave u_blitter. */
    806 			si_invalidate_draw_sh_constants(sctx);
    807 
    808 			/* Blit VS doesn't use BASE_VERTEX, START_INSTANCE, and DRAWID. */
    809 			radeon_set_sh_reg_seq(cs, sh_base_reg + SI_SGPR_VS_BLIT_DATA * 4,
    810 					      sctx->num_vs_blit_sgprs);
    811 			radeon_emit_array(cs, sctx->vs_blit_sh_data,
    812 					  sctx->num_vs_blit_sgprs);
    813 		} else if (base_vertex != sctx->last_base_vertex ||
    814 			   sctx->last_base_vertex == SI_BASE_VERTEX_UNKNOWN ||
    815 			   info->start_instance != sctx->last_start_instance ||
    816 			   info->drawid != sctx->last_drawid ||
    817 			   sh_base_reg != sctx->last_sh_base_reg) {
    818 			radeon_set_sh_reg_seq(cs, sh_base_reg + SI_SGPR_BASE_VERTEX * 4, 3);
    819 			radeon_emit(cs, base_vertex);
    820 			radeon_emit(cs, info->start_instance);
    821 			radeon_emit(cs, info->drawid);
    822 
    823 			sctx->last_base_vertex = base_vertex;
    824 			sctx->last_start_instance = info->start_instance;
    825 			sctx->last_drawid = info->drawid;
    826 			sctx->last_sh_base_reg = sh_base_reg;
    827 		}
    828 
    829 		if (index_size) {
    830 			index_va += info->start * index_size;
    831 
    832 			radeon_emit(cs, PKT3(PKT3_DRAW_INDEX_2, 4, render_cond_bit));
    833 			radeon_emit(cs, index_max_size);
    834 			radeon_emit(cs, index_va);
    835 			radeon_emit(cs, index_va >> 32);
    836 			radeon_emit(cs, info->count);
    837 			radeon_emit(cs, V_0287F0_DI_SRC_SEL_DMA);
    838 		} else {
    839 			radeon_emit(cs, PKT3(PKT3_DRAW_INDEX_AUTO, 1, render_cond_bit));
    840 			radeon_emit(cs, info->count);
    841 			radeon_emit(cs, V_0287F0_DI_SRC_SEL_AUTO_INDEX |
    842 				        S_0287F0_USE_OPAQUE(!!info->count_from_stream_output));
    843 		}
    844 	}
    845 }
    846 
    847 static void si_emit_surface_sync(struct r600_common_context *rctx,
    848 				 unsigned cp_coher_cntl)
    849 {
    850 	struct radeon_winsys_cs *cs = rctx->gfx.cs;
    851 
    852 	if (rctx->chip_class >= GFX9) {
    853 		/* Flush caches and wait for the caches to assert idle. */
    854 		radeon_emit(cs, PKT3(PKT3_ACQUIRE_MEM, 5, 0));
    855 		radeon_emit(cs, cp_coher_cntl);	/* CP_COHER_CNTL */
    856 		radeon_emit(cs, 0xffffffff);	/* CP_COHER_SIZE */
    857 		radeon_emit(cs, 0xffffff);	/* CP_COHER_SIZE_HI */
    858 		radeon_emit(cs, 0);		/* CP_COHER_BASE */
    859 		radeon_emit(cs, 0);		/* CP_COHER_BASE_HI */
    860 		radeon_emit(cs, 0x0000000A);	/* POLL_INTERVAL */
    861 	} else {
    862 		/* ACQUIRE_MEM is only required on a compute ring. */
    863 		radeon_emit(cs, PKT3(PKT3_SURFACE_SYNC, 3, 0));
    864 		radeon_emit(cs, cp_coher_cntl);   /* CP_COHER_CNTL */
    865 		radeon_emit(cs, 0xffffffff);      /* CP_COHER_SIZE */
    866 		radeon_emit(cs, 0);               /* CP_COHER_BASE */
    867 		radeon_emit(cs, 0x0000000A);      /* POLL_INTERVAL */
    868 	}
    869 }
    870 
    871 void si_emit_cache_flush(struct si_context *sctx)
    872 {
    873 	struct r600_common_context *rctx = &sctx->b;
    874 	struct radeon_winsys_cs *cs = rctx->gfx.cs;
    875 	uint32_t cp_coher_cntl = 0;
    876 	uint32_t flush_cb_db = rctx->flags & (SI_CONTEXT_FLUSH_AND_INV_CB |
    877 					      SI_CONTEXT_FLUSH_AND_INV_DB);
    878 
    879 	if (rctx->flags & SI_CONTEXT_FLUSH_AND_INV_CB)
    880 		sctx->b.num_cb_cache_flushes++;
    881 	if (rctx->flags & SI_CONTEXT_FLUSH_AND_INV_DB)
    882 		sctx->b.num_db_cache_flushes++;
    883 
    884 	/* SI has a bug that it always flushes ICACHE and KCACHE if either
    885 	 * bit is set. An alternative way is to write SQC_CACHES, but that
    886 	 * doesn't seem to work reliably. Since the bug doesn't affect
    887 	 * correctness (it only does more work than necessary) and
    888 	 * the performance impact is likely negligible, there is no plan
    889 	 * to add a workaround for it.
    890 	 */
    891 
    892 	if (rctx->flags & SI_CONTEXT_INV_ICACHE)
    893 		cp_coher_cntl |= S_0085F0_SH_ICACHE_ACTION_ENA(1);
    894 	if (rctx->flags & SI_CONTEXT_INV_SMEM_L1)
    895 		cp_coher_cntl |= S_0085F0_SH_KCACHE_ACTION_ENA(1);
    896 
    897 	if (rctx->chip_class <= VI) {
    898 		if (rctx->flags & SI_CONTEXT_FLUSH_AND_INV_CB) {
    899 			cp_coher_cntl |= S_0085F0_CB_ACTION_ENA(1) |
    900 					 S_0085F0_CB0_DEST_BASE_ENA(1) |
    901 					 S_0085F0_CB1_DEST_BASE_ENA(1) |
    902 					 S_0085F0_CB2_DEST_BASE_ENA(1) |
    903 					 S_0085F0_CB3_DEST_BASE_ENA(1) |
    904 					 S_0085F0_CB4_DEST_BASE_ENA(1) |
    905 					 S_0085F0_CB5_DEST_BASE_ENA(1) |
    906 					 S_0085F0_CB6_DEST_BASE_ENA(1) |
    907 					 S_0085F0_CB7_DEST_BASE_ENA(1);
    908 
    909 			/* Necessary for DCC */
    910 			if (rctx->chip_class == VI)
    911 				si_gfx_write_event_eop(rctx, V_028A90_FLUSH_AND_INV_CB_DATA_TS,
    912 							 0, EOP_DATA_SEL_DISCARD, NULL,
    913 							 0, 0, SI_NOT_QUERY);
    914 		}
    915 		if (rctx->flags & SI_CONTEXT_FLUSH_AND_INV_DB)
    916 			cp_coher_cntl |= S_0085F0_DB_ACTION_ENA(1) |
    917 					 S_0085F0_DB_DEST_BASE_ENA(1);
    918 	}
    919 
    920 	if (rctx->flags & SI_CONTEXT_FLUSH_AND_INV_CB) {
    921 		/* Flush CMASK/FMASK/DCC. SURFACE_SYNC will wait for idle. */
    922 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    923 		radeon_emit(cs, EVENT_TYPE(V_028A90_FLUSH_AND_INV_CB_META) | EVENT_INDEX(0));
    924 	}
    925 	if (rctx->flags & (SI_CONTEXT_FLUSH_AND_INV_DB |
    926 			   SI_CONTEXT_FLUSH_AND_INV_DB_META)) {
    927 		/* Flush HTILE. SURFACE_SYNC will wait for idle. */
    928 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    929 		radeon_emit(cs, EVENT_TYPE(V_028A90_FLUSH_AND_INV_DB_META) | EVENT_INDEX(0));
    930 	}
    931 
    932 	/* Wait for shader engines to go idle.
    933 	 * VS and PS waits are unnecessary if SURFACE_SYNC is going to wait
    934 	 * for everything including CB/DB cache flushes.
    935 	 */
    936 	if (!flush_cb_db) {
    937 		if (rctx->flags & SI_CONTEXT_PS_PARTIAL_FLUSH) {
    938 			radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    939 			radeon_emit(cs, EVENT_TYPE(V_028A90_PS_PARTIAL_FLUSH) | EVENT_INDEX(4));
    940 			/* Only count explicit shader flushes, not implicit ones
    941 			 * done by SURFACE_SYNC.
    942 			 */
    943 			rctx->num_vs_flushes++;
    944 			rctx->num_ps_flushes++;
    945 		} else if (rctx->flags & SI_CONTEXT_VS_PARTIAL_FLUSH) {
    946 			radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    947 			radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
    948 			rctx->num_vs_flushes++;
    949 		}
    950 	}
    951 
    952 	if (rctx->flags & SI_CONTEXT_CS_PARTIAL_FLUSH &&
    953 	    sctx->compute_is_busy) {
    954 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    955 		radeon_emit(cs, EVENT_TYPE(V_028A90_CS_PARTIAL_FLUSH | EVENT_INDEX(4)));
    956 		rctx->num_cs_flushes++;
    957 		sctx->compute_is_busy = false;
    958 	}
    959 
    960 	/* VGT state synchronization. */
    961 	if (rctx->flags & SI_CONTEXT_VGT_FLUSH) {
    962 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    963 		radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
    964 	}
    965 	if (rctx->flags & SI_CONTEXT_VGT_STREAMOUT_SYNC) {
    966 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
    967 		radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_STREAMOUT_SYNC) | EVENT_INDEX(0));
    968 	}
    969 
    970 	/* GFX9: Wait for idle if we're flushing CB or DB. ACQUIRE_MEM doesn't
    971 	 * wait for idle on GFX9. We have to use a TS event.
    972 	 */
    973 	if (sctx->b.chip_class >= GFX9 && flush_cb_db) {
    974 		uint64_t va;
    975 		unsigned tc_flags, cb_db_event;
    976 
    977 		/* Set the CB/DB flush event. */
    978 		switch (flush_cb_db) {
    979 		case SI_CONTEXT_FLUSH_AND_INV_CB:
    980 			cb_db_event = V_028A90_FLUSH_AND_INV_CB_DATA_TS;
    981 			break;
    982 		case SI_CONTEXT_FLUSH_AND_INV_DB:
    983 			cb_db_event = V_028A90_FLUSH_AND_INV_DB_DATA_TS;
    984 			break;
    985 		default:
    986 			/* both CB & DB */
    987 			cb_db_event = V_028A90_CACHE_FLUSH_AND_INV_TS_EVENT;
    988 		}
    989 
    990 		/* These are the only allowed combinations. If you need to
    991 		 * do multiple operations at once, do them separately.
    992 		 * All operations that invalidate L2 also seem to invalidate
    993 		 * metadata. Volatile (VOL) and WC flushes are not listed here.
    994 		 *
    995 		 * TC    | TC_WB         = writeback & invalidate L2 & L1
    996 		 * TC    | TC_WB | TC_NC = writeback & invalidate L2 for MTYPE == NC
    997 		 *         TC_WB | TC_NC = writeback L2 for MTYPE == NC
    998 		 * TC            | TC_NC = invalidate L2 for MTYPE == NC
    999 		 * TC    | TC_MD         = writeback & invalidate L2 metadata (DCC, etc.)
   1000 		 * TCL1                  = invalidate L1
   1001 		 */
   1002 		tc_flags = 0;
   1003 
   1004 		if (rctx->flags & SI_CONTEXT_INV_L2_METADATA) {
   1005 			tc_flags = EVENT_TC_ACTION_ENA |
   1006 				   EVENT_TC_MD_ACTION_ENA;
   1007 		}
   1008 
   1009 		/* Ideally flush TC together with CB/DB. */
   1010 		if (rctx->flags & SI_CONTEXT_INV_GLOBAL_L2) {
   1011 			/* Writeback and invalidate everything in L2 & L1. */
   1012 			tc_flags = EVENT_TC_ACTION_ENA |
   1013 				   EVENT_TC_WB_ACTION_ENA;
   1014 
   1015 			/* Clear the flags. */
   1016 			rctx->flags &= ~(SI_CONTEXT_INV_GLOBAL_L2 |
   1017 					 SI_CONTEXT_WRITEBACK_GLOBAL_L2 |
   1018 					 SI_CONTEXT_INV_VMEM_L1);
   1019 			sctx->b.num_L2_invalidates++;
   1020 		}
   1021 
   1022 		/* Do the flush (enqueue the event and wait for it). */
   1023 		va = sctx->wait_mem_scratch->gpu_address;
   1024 		sctx->wait_mem_number++;
   1025 
   1026 		si_gfx_write_event_eop(rctx, cb_db_event, tc_flags,
   1027 					 EOP_DATA_SEL_VALUE_32BIT,
   1028 					 sctx->wait_mem_scratch, va,
   1029 					 sctx->wait_mem_number, SI_NOT_QUERY);
   1030 		si_gfx_wait_fence(rctx, va, sctx->wait_mem_number, 0xffffffff);
   1031 	}
   1032 
   1033 	/* Make sure ME is idle (it executes most packets) before continuing.
   1034 	 * This prevents read-after-write hazards between PFP and ME.
   1035 	 */
   1036 	if (cp_coher_cntl ||
   1037 	    (rctx->flags & (SI_CONTEXT_CS_PARTIAL_FLUSH |
   1038 			    SI_CONTEXT_INV_VMEM_L1 |
   1039 			    SI_CONTEXT_INV_GLOBAL_L2 |
   1040 			    SI_CONTEXT_WRITEBACK_GLOBAL_L2))) {
   1041 		radeon_emit(cs, PKT3(PKT3_PFP_SYNC_ME, 0, 0));
   1042 		radeon_emit(cs, 0);
   1043 	}
   1044 
   1045 	/* SI-CI-VI only:
   1046 	 *   When one of the CP_COHER_CNTL.DEST_BASE flags is set, SURFACE_SYNC
   1047 	 *   waits for idle, so it should be last. SURFACE_SYNC is done in PFP.
   1048 	 *
   1049 	 * cp_coher_cntl should contain all necessary flags except TC flags
   1050 	 * at this point.
   1051 	 *
   1052 	 * SI-CIK don't support L2 write-back.
   1053 	 */
   1054 	if (rctx->flags & SI_CONTEXT_INV_GLOBAL_L2 ||
   1055 	    (rctx->chip_class <= CIK &&
   1056 	     (rctx->flags & SI_CONTEXT_WRITEBACK_GLOBAL_L2))) {
   1057 		/* Invalidate L1 & L2. (L1 is always invalidated on SI)
   1058 		 * WB must be set on VI+ when TC_ACTION is set.
   1059 		 */
   1060 		si_emit_surface_sync(rctx, cp_coher_cntl |
   1061 				     S_0085F0_TC_ACTION_ENA(1) |
   1062 				     S_0085F0_TCL1_ACTION_ENA(1) |
   1063 				     S_0301F0_TC_WB_ACTION_ENA(rctx->chip_class >= VI));
   1064 		cp_coher_cntl = 0;
   1065 		sctx->b.num_L2_invalidates++;
   1066 	} else {
   1067 		/* L1 invalidation and L2 writeback must be done separately,
   1068 		 * because both operations can't be done together.
   1069 		 */
   1070 		if (rctx->flags & SI_CONTEXT_WRITEBACK_GLOBAL_L2) {
   1071 			/* WB = write-back
   1072 			 * NC = apply to non-coherent MTYPEs
   1073 			 *      (i.e. MTYPE <= 1, which is what we use everywhere)
   1074 			 *
   1075 			 * WB doesn't work without NC.
   1076 			 */
   1077 			si_emit_surface_sync(rctx, cp_coher_cntl |
   1078 					     S_0301F0_TC_WB_ACTION_ENA(1) |
   1079 					     S_0301F0_TC_NC_ACTION_ENA(1));
   1080 			cp_coher_cntl = 0;
   1081 			sctx->b.num_L2_writebacks++;
   1082 		}
   1083 		if (rctx->flags & SI_CONTEXT_INV_VMEM_L1) {
   1084 			/* Invalidate per-CU VMEM L1. */
   1085 			si_emit_surface_sync(rctx, cp_coher_cntl |
   1086 					     S_0085F0_TCL1_ACTION_ENA(1));
   1087 			cp_coher_cntl = 0;
   1088 		}
   1089 	}
   1090 
   1091 	/* If TC flushes haven't cleared this... */
   1092 	if (cp_coher_cntl)
   1093 		si_emit_surface_sync(rctx, cp_coher_cntl);
   1094 
   1095 	if (rctx->flags & SI_CONTEXT_START_PIPELINE_STATS) {
   1096 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
   1097 		radeon_emit(cs, EVENT_TYPE(V_028A90_PIPELINESTAT_START) |
   1098 			        EVENT_INDEX(0));
   1099 	} else if (rctx->flags & SI_CONTEXT_STOP_PIPELINE_STATS) {
   1100 		radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
   1101 		radeon_emit(cs, EVENT_TYPE(V_028A90_PIPELINESTAT_STOP) |
   1102 			        EVENT_INDEX(0));
   1103 	}
   1104 
   1105 	rctx->flags = 0;
   1106 }
   1107 
   1108 static void si_get_draw_start_count(struct si_context *sctx,
   1109 				    const struct pipe_draw_info *info,
   1110 				    unsigned *start, unsigned *count)
   1111 {
   1112 	struct pipe_draw_indirect_info *indirect = info->indirect;
   1113 
   1114 	if (indirect) {
   1115 		unsigned indirect_count;
   1116 		struct pipe_transfer *transfer;
   1117 		unsigned begin, end;
   1118 		unsigned map_size;
   1119 		unsigned *data;
   1120 
   1121 		if (indirect->indirect_draw_count) {
   1122 			data = pipe_buffer_map_range(&sctx->b.b,
   1123 					indirect->indirect_draw_count,
   1124 					indirect->indirect_draw_count_offset,
   1125 					sizeof(unsigned),
   1126 					PIPE_TRANSFER_READ, &transfer);
   1127 
   1128 			indirect_count = *data;
   1129 
   1130 			pipe_buffer_unmap(&sctx->b.b, transfer);
   1131 		} else {
   1132 			indirect_count = indirect->draw_count;
   1133 		}
   1134 
   1135 		if (!indirect_count) {
   1136 			*start = *count = 0;
   1137 			return;
   1138 		}
   1139 
   1140 		map_size = (indirect_count - 1) * indirect->stride + 3 * sizeof(unsigned);
   1141 		data = pipe_buffer_map_range(&sctx->b.b, indirect->buffer,
   1142 					     indirect->offset, map_size,
   1143 					     PIPE_TRANSFER_READ, &transfer);
   1144 
   1145 		begin = UINT_MAX;
   1146 		end = 0;
   1147 
   1148 		for (unsigned i = 0; i < indirect_count; ++i) {
   1149 			unsigned count = data[0];
   1150 			unsigned start = data[2];
   1151 
   1152 			if (count > 0) {
   1153 				begin = MIN2(begin, start);
   1154 				end = MAX2(end, start + count);
   1155 			}
   1156 
   1157 			data += indirect->stride / sizeof(unsigned);
   1158 		}
   1159 
   1160 		pipe_buffer_unmap(&sctx->b.b, transfer);
   1161 
   1162 		if (begin < end) {
   1163 			*start = begin;
   1164 			*count = end - begin;
   1165 		} else {
   1166 			*start = *count = 0;
   1167 		}
   1168 	} else {
   1169 		*start = info->start;
   1170 		*count = info->count;
   1171 	}
   1172 }
   1173 
   1174 static void si_emit_all_states(struct si_context *sctx, const struct pipe_draw_info *info,
   1175 			       unsigned skip_atom_mask)
   1176 {
   1177 	/* Emit state atoms. */
   1178 	unsigned mask = sctx->dirty_atoms & ~skip_atom_mask;
   1179 	while (mask) {
   1180 		struct r600_atom *atom = sctx->atoms.array[u_bit_scan(&mask)];
   1181 
   1182 		atom->emit(&sctx->b, atom);
   1183 	}
   1184 	sctx->dirty_atoms &= skip_atom_mask;
   1185 
   1186 	/* Emit states. */
   1187 	mask = sctx->dirty_states;
   1188 	while (mask) {
   1189 		unsigned i = u_bit_scan(&mask);
   1190 		struct si_pm4_state *state = sctx->queued.array[i];
   1191 
   1192 		if (!state || sctx->emitted.array[i] == state)
   1193 			continue;
   1194 
   1195 		si_pm4_emit(sctx, state);
   1196 		sctx->emitted.array[i] = state;
   1197 	}
   1198 	sctx->dirty_states = 0;
   1199 
   1200 	/* Emit draw states. */
   1201 	unsigned num_patches = 0;
   1202 
   1203 	si_emit_rasterizer_prim_state(sctx);
   1204 	if (sctx->tes_shader.cso)
   1205 		si_emit_derived_tess_state(sctx, info, &num_patches);
   1206 	si_emit_vs_state(sctx, info);
   1207 	si_emit_draw_registers(sctx, info, num_patches);
   1208 }
   1209 
   1210 void si_draw_vbo(struct pipe_context *ctx, const struct pipe_draw_info *info)
   1211 {
   1212 	struct si_context *sctx = (struct si_context *)ctx;
   1213 	struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
   1214 	struct pipe_resource *indexbuf = info->index.resource;
   1215 	unsigned dirty_tex_counter;
   1216 	enum pipe_prim_type rast_prim;
   1217 	unsigned index_size = info->index_size;
   1218 	unsigned index_offset = info->indirect ? info->start * index_size : 0;
   1219 
   1220 	if (likely(!info->indirect)) {
   1221 		/* SI-CI treat instance_count==0 as instance_count==1. There is
   1222 		 * no workaround for indirect draws, but we can at least skip
   1223 		 * direct draws.
   1224 		 */
   1225 		if (unlikely(!info->instance_count))
   1226 			return;
   1227 
   1228 		/* Handle count == 0. */
   1229 		if (unlikely(!info->count &&
   1230 			     (index_size || !info->count_from_stream_output)))
   1231 			return;
   1232 	}
   1233 
   1234 	if (unlikely(!sctx->vs_shader.cso)) {
   1235 		assert(0);
   1236 		return;
   1237 	}
   1238 	if (unlikely(!sctx->ps_shader.cso && (!rs || !rs->rasterizer_discard))) {
   1239 		assert(0);
   1240 		return;
   1241 	}
   1242 	if (unlikely(!!sctx->tes_shader.cso != (info->mode == PIPE_PRIM_PATCHES))) {
   1243 		assert(0);
   1244 		return;
   1245 	}
   1246 
   1247 	/* Recompute and re-emit the texture resource states if needed. */
   1248 	dirty_tex_counter = p_atomic_read(&sctx->b.screen->dirty_tex_counter);
   1249 	if (unlikely(dirty_tex_counter != sctx->b.last_dirty_tex_counter)) {
   1250 		sctx->b.last_dirty_tex_counter = dirty_tex_counter;
   1251 		sctx->framebuffer.dirty_cbufs |=
   1252 			((1 << sctx->framebuffer.state.nr_cbufs) - 1);
   1253 		sctx->framebuffer.dirty_zsbuf = true;
   1254 		si_mark_atom_dirty(sctx, &sctx->framebuffer.atom);
   1255 		si_update_all_texture_descriptors(sctx);
   1256 	}
   1257 
   1258 	si_decompress_textures(sctx, u_bit_consecutive(0, SI_NUM_GRAPHICS_SHADERS));
   1259 
   1260 	/* Set the rasterization primitive type.
   1261 	 *
   1262 	 * This must be done after si_decompress_textures, which can call
   1263 	 * draw_vbo recursively, and before si_update_shaders, which uses
   1264 	 * current_rast_prim for this draw_vbo call. */
   1265 	if (sctx->gs_shader.cso)
   1266 		rast_prim = sctx->gs_shader.cso->gs_output_prim;
   1267 	else if (sctx->tes_shader.cso) {
   1268 		if (sctx->tes_shader.cso->info.properties[TGSI_PROPERTY_TES_POINT_MODE])
   1269 			rast_prim = PIPE_PRIM_POINTS;
   1270 		else
   1271 			rast_prim = sctx->tes_shader.cso->info.properties[TGSI_PROPERTY_TES_PRIM_MODE];
   1272 	} else
   1273 		rast_prim = info->mode;
   1274 
   1275 	if (rast_prim != sctx->current_rast_prim) {
   1276 		bool old_is_poly = sctx->current_rast_prim >= PIPE_PRIM_TRIANGLES;
   1277 		bool new_is_poly = rast_prim >= PIPE_PRIM_TRIANGLES;
   1278 		if (old_is_poly != new_is_poly) {
   1279 			sctx->scissors.dirty_mask = (1 << SI_MAX_VIEWPORTS) - 1;
   1280 			si_mark_atom_dirty(sctx, &sctx->scissors.atom);
   1281 		}
   1282 
   1283 		sctx->current_rast_prim = rast_prim;
   1284 		sctx->do_update_shaders = true;
   1285 	}
   1286 
   1287 	if (sctx->tes_shader.cso &&
   1288 	    sctx->screen->has_ls_vgpr_init_bug) {
   1289 		/* Determine whether the LS VGPR fix should be applied.
   1290 		 *
   1291 		 * It is only required when num input CPs > num output CPs,
   1292 		 * which cannot happen with the fixed function TCS. We should
   1293 		 * also update this bit when switching from TCS to fixed
   1294 		 * function TCS.
   1295 		 */
   1296 		struct si_shader_selector *tcs = sctx->tcs_shader.cso;
   1297 		bool ls_vgpr_fix =
   1298 			tcs &&
   1299 			info->vertices_per_patch >
   1300 			tcs->info.properties[TGSI_PROPERTY_TCS_VERTICES_OUT];
   1301 
   1302 		if (ls_vgpr_fix != sctx->ls_vgpr_fix) {
   1303 			sctx->ls_vgpr_fix = ls_vgpr_fix;
   1304 			sctx->do_update_shaders = true;
   1305 		}
   1306 	}
   1307 
   1308 	if (sctx->gs_shader.cso) {
   1309 		/* Determine whether the GS triangle strip adjacency fix should
   1310 		 * be applied. Rotate every other triangle if
   1311 		 * - triangle strips with adjacency are fed to the GS and
   1312 		 * - primitive restart is disabled (the rotation doesn't help
   1313 		 *   when the restart occurs after an odd number of triangles).
   1314 		 */
   1315 		bool gs_tri_strip_adj_fix =
   1316 			!sctx->tes_shader.cso &&
   1317 			info->mode == PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY &&
   1318 			!info->primitive_restart;
   1319 
   1320 		if (gs_tri_strip_adj_fix != sctx->gs_tri_strip_adj_fix) {
   1321 			sctx->gs_tri_strip_adj_fix = gs_tri_strip_adj_fix;
   1322 			sctx->do_update_shaders = true;
   1323 		}
   1324 	}
   1325 
   1326 	if (sctx->do_update_shaders && !si_update_shaders(sctx))
   1327 		return;
   1328 
   1329 	if (index_size) {
   1330 		/* Translate or upload, if needed. */
   1331 		/* 8-bit indices are supported on VI. */
   1332 		if (sctx->b.chip_class <= CIK && index_size == 1) {
   1333 			unsigned start, count, start_offset, size, offset;
   1334 			void *ptr;
   1335 
   1336 			si_get_draw_start_count(sctx, info, &start, &count);
   1337 			start_offset = start * 2;
   1338 			size = count * 2;
   1339 
   1340 			indexbuf = NULL;
   1341 			u_upload_alloc(ctx->stream_uploader, start_offset,
   1342 				       size,
   1343 				       si_optimal_tcc_alignment(sctx, size),
   1344 				       &offset, &indexbuf, &ptr);
   1345 			if (!indexbuf)
   1346 				return;
   1347 
   1348 			util_shorten_ubyte_elts_to_userptr(&sctx->b.b, info, 0, 0,
   1349 							   index_offset + start,
   1350 							   count, ptr);
   1351 
   1352 			/* info->start will be added by the drawing code */
   1353 			index_offset = offset - start_offset;
   1354 			index_size = 2;
   1355 		} else if (info->has_user_indices) {
   1356 			unsigned start_offset;
   1357 
   1358 			assert(!info->indirect);
   1359 			start_offset = info->start * index_size;
   1360 
   1361 			indexbuf = NULL;
   1362 			u_upload_data(ctx->stream_uploader, start_offset,
   1363 				      info->count * index_size,
   1364 				      sctx->screen->info.tcc_cache_line_size,
   1365 				      (char*)info->index.user + start_offset,
   1366 				      &index_offset, &indexbuf);
   1367 			if (!indexbuf)
   1368 				return;
   1369 
   1370 			/* info->start will be added by the drawing code */
   1371 			index_offset -= start_offset;
   1372 		} else if (sctx->b.chip_class <= CIK &&
   1373 			   r600_resource(indexbuf)->TC_L2_dirty) {
   1374 			/* VI reads index buffers through TC L2, so it doesn't
   1375 			 * need this. */
   1376 			sctx->b.flags |= SI_CONTEXT_WRITEBACK_GLOBAL_L2;
   1377 			r600_resource(indexbuf)->TC_L2_dirty = false;
   1378 		}
   1379 	}
   1380 
   1381 	if (info->indirect) {
   1382 		struct pipe_draw_indirect_info *indirect = info->indirect;
   1383 
   1384 		/* Add the buffer size for memory checking in need_cs_space. */
   1385 		si_context_add_resource_size(ctx, indirect->buffer);
   1386 
   1387 		/* Indirect buffers use TC L2 on GFX9, but not older hw. */
   1388 		if (sctx->b.chip_class <= VI) {
   1389 			if (r600_resource(indirect->buffer)->TC_L2_dirty) {
   1390 				sctx->b.flags |= SI_CONTEXT_WRITEBACK_GLOBAL_L2;
   1391 				r600_resource(indirect->buffer)->TC_L2_dirty = false;
   1392 			}
   1393 
   1394 			if (indirect->indirect_draw_count &&
   1395 			    r600_resource(indirect->indirect_draw_count)->TC_L2_dirty) {
   1396 				sctx->b.flags |= SI_CONTEXT_WRITEBACK_GLOBAL_L2;
   1397 				r600_resource(indirect->indirect_draw_count)->TC_L2_dirty = false;
   1398 			}
   1399 		}
   1400 	}
   1401 
   1402 	si_need_cs_space(sctx);
   1403 
   1404 	/* Since we've called r600_context_add_resource_size for vertex buffers,
   1405 	 * this must be called after si_need_cs_space, because we must let
   1406 	 * need_cs_space flush before we add buffers to the buffer list.
   1407 	 */
   1408 	if (!si_upload_vertex_buffer_descriptors(sctx))
   1409 		return;
   1410 
   1411 	/* Vega10/Raven scissor bug workaround. This must be done before VPORT
   1412 	 * scissor registers are changed. There is also a more efficient but
   1413 	 * more involved alternative workaround.
   1414 	 */
   1415 	if ((sctx->b.family == CHIP_VEGA10 || sctx->b.family == CHIP_RAVEN) &&
   1416 	    si_is_atom_dirty(sctx, &sctx->scissors.atom)) {
   1417 		sctx->b.flags |= SI_CONTEXT_PS_PARTIAL_FLUSH;
   1418 		si_emit_cache_flush(sctx);
   1419 	}
   1420 
   1421 	/* Use optimal packet order based on whether we need to sync the pipeline. */
   1422 	if (unlikely(sctx->b.flags & (SI_CONTEXT_FLUSH_AND_INV_CB |
   1423 				      SI_CONTEXT_FLUSH_AND_INV_DB |
   1424 				      SI_CONTEXT_PS_PARTIAL_FLUSH |
   1425 				      SI_CONTEXT_CS_PARTIAL_FLUSH))) {
   1426 		/* If we have to wait for idle, set all states first, so that all
   1427 		 * SET packets are processed in parallel with previous draw calls.
   1428 		 * Then upload descriptors, set shader pointers, and draw, and
   1429 		 * prefetch at the end. This ensures that the time the CUs
   1430 		 * are idle is very short. (there are only SET_SH packets between
   1431 		 * the wait and the draw)
   1432 		 */
   1433 		struct r600_atom *shader_pointers = &sctx->shader_pointers.atom;
   1434 		unsigned masked_atoms = 1u << shader_pointers->id;
   1435 
   1436 		if (unlikely(sctx->b.flags & SI_CONTEXT_FLUSH_FOR_RENDER_COND))
   1437 			masked_atoms |= 1u << sctx->b.render_cond_atom.id;
   1438 
   1439 		/* Emit all states except shader pointers and render condition. */
   1440 		si_emit_all_states(sctx, info, masked_atoms);
   1441 		si_emit_cache_flush(sctx);
   1442 
   1443 		/* <-- CUs are idle here. */
   1444 		if (!si_upload_graphics_shader_descriptors(sctx))
   1445 			return;
   1446 
   1447 		/* Set shader pointers after descriptors are uploaded. */
   1448 		if (si_is_atom_dirty(sctx, shader_pointers))
   1449 			shader_pointers->emit(&sctx->b, NULL);
   1450 		if (si_is_atom_dirty(sctx, &sctx->b.render_cond_atom))
   1451 			sctx->b.render_cond_atom.emit(&sctx->b, NULL);
   1452 		sctx->dirty_atoms = 0;
   1453 
   1454 		si_emit_draw_packets(sctx, info, indexbuf, index_size, index_offset);
   1455 		/* <-- CUs are busy here. */
   1456 
   1457 		/* Start prefetches after the draw has been started. Both will run
   1458 		 * in parallel, but starting the draw first is more important.
   1459 		 */
   1460 		if (sctx->b.chip_class >= CIK && sctx->prefetch_L2_mask)
   1461 			cik_emit_prefetch_L2(sctx);
   1462 	} else {
   1463 		/* If we don't wait for idle, start prefetches first, then set
   1464 		 * states, and draw at the end.
   1465 		 */
   1466 		if (sctx->b.flags)
   1467 			si_emit_cache_flush(sctx);
   1468 
   1469 		if (sctx->b.chip_class >= CIK && sctx->prefetch_L2_mask)
   1470 			cik_emit_prefetch_L2(sctx);
   1471 
   1472 		if (!si_upload_graphics_shader_descriptors(sctx))
   1473 			return;
   1474 
   1475 		si_emit_all_states(sctx, info, 0);
   1476 		si_emit_draw_packets(sctx, info, indexbuf, index_size, index_offset);
   1477 	}
   1478 
   1479 	if (unlikely(sctx->current_saved_cs)) {
   1480 		si_trace_emit(sctx);
   1481 		si_log_draw_state(sctx, sctx->b.log);
   1482 	}
   1483 
   1484 	/* Workaround for a VGT hang when streamout is enabled.
   1485 	 * It must be done after drawing. */
   1486 	if ((sctx->b.family == CHIP_HAWAII ||
   1487 	     sctx->b.family == CHIP_TONGA ||
   1488 	     sctx->b.family == CHIP_FIJI) &&
   1489 	    si_get_strmout_en(sctx)) {
   1490 		sctx->b.flags |= SI_CONTEXT_VGT_STREAMOUT_SYNC;
   1491 	}
   1492 
   1493 	if (unlikely(sctx->decompression_enabled)) {
   1494 		sctx->b.num_decompress_calls++;
   1495 	} else {
   1496 		sctx->b.num_draw_calls++;
   1497 		if (sctx->framebuffer.state.nr_cbufs > 1)
   1498 			sctx->b.num_mrt_draw_calls++;
   1499 		if (info->primitive_restart)
   1500 			sctx->b.num_prim_restart_calls++;
   1501 		if (G_0286E8_WAVESIZE(sctx->spi_tmpring_size))
   1502 			sctx->b.num_spill_draw_calls++;
   1503 	}
   1504 	if (index_size && indexbuf != info->index.resource)
   1505 		pipe_resource_reference(&indexbuf, NULL);
   1506 }
   1507 
   1508 void si_draw_rectangle(struct blitter_context *blitter,
   1509 		       void *vertex_elements_cso,
   1510 		       blitter_get_vs_func get_vs,
   1511 		       int x1, int y1, int x2, int y2,
   1512 		       float depth, unsigned num_instances,
   1513 		       enum blitter_attrib_type type,
   1514 		       const union blitter_attrib *attrib)
   1515 {
   1516 	struct pipe_context *pipe = util_blitter_get_pipe(blitter);
   1517 	struct si_context *sctx = (struct si_context*)pipe;
   1518 
   1519 	/* Pack position coordinates as signed int16. */
   1520 	sctx->vs_blit_sh_data[0] = (uint32_t)(x1 & 0xffff) |
   1521 				   ((uint32_t)(y1 & 0xffff) << 16);
   1522 	sctx->vs_blit_sh_data[1] = (uint32_t)(x2 & 0xffff) |
   1523 				   ((uint32_t)(y2 & 0xffff) << 16);
   1524 	sctx->vs_blit_sh_data[2] = fui(depth);
   1525 
   1526 	switch (type) {
   1527 	case UTIL_BLITTER_ATTRIB_COLOR:
   1528 		memcpy(&sctx->vs_blit_sh_data[3], attrib->color,
   1529 		       sizeof(float)*4);
   1530 		break;
   1531 	case UTIL_BLITTER_ATTRIB_TEXCOORD_XY:
   1532 	case UTIL_BLITTER_ATTRIB_TEXCOORD_XYZW:
   1533 		memcpy(&sctx->vs_blit_sh_data[3], &attrib->texcoord,
   1534 		       sizeof(attrib->texcoord));
   1535 		break;
   1536 	case UTIL_BLITTER_ATTRIB_NONE:;
   1537 	}
   1538 
   1539 	pipe->bind_vs_state(pipe, si_get_blit_vs(sctx, type, num_instances));
   1540 
   1541 	struct pipe_draw_info info = {};
   1542 	info.mode = SI_PRIM_RECTANGLE_LIST;
   1543 	info.count = 3;
   1544 	info.instance_count = num_instances;
   1545 
   1546 	/* Don't set per-stage shader pointers for VS. */
   1547 	sctx->shader_pointers_dirty &= ~SI_DESCS_SHADER_MASK(VERTEX);
   1548 	sctx->vertex_buffer_pointer_dirty = false;
   1549 
   1550 	si_draw_vbo(pipe, &info);
   1551 }
   1552 
   1553 void si_trace_emit(struct si_context *sctx)
   1554 {
   1555 	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
   1556 	uint64_t va = sctx->current_saved_cs->trace_buf->gpu_address;
   1557 	uint32_t trace_id = ++sctx->current_saved_cs->trace_id;
   1558 
   1559 	radeon_emit(cs, PKT3(PKT3_WRITE_DATA, 3, 0));
   1560 	radeon_emit(cs, S_370_DST_SEL(V_370_MEMORY_SYNC) |
   1561 		    S_370_WR_CONFIRM(1) |
   1562 		    S_370_ENGINE_SEL(V_370_ME));
   1563 	radeon_emit(cs, va);
   1564 	radeon_emit(cs, va >> 32);
   1565 	radeon_emit(cs, trace_id);
   1566 	radeon_emit(cs, PKT3(PKT3_NOP, 0, 0));
   1567 	radeon_emit(cs, AC_ENCODE_TRACE_POINT(trace_id));
   1568 
   1569 	if (sctx->b.log)
   1570 		u_log_flush(sctx->b.log);
   1571 }
   1572