si_state.c revision 0c135a773fafaf6707fb2cf6fff5d0d95727ea2f
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 * Authors:
24 *      Christian König <christian.koenig@amd.com>
25 */
26
27#include "si_pipe.h"
28#include "si_shader.h"
29#include "sid.h"
30#include "radeon/r600_cs.h"
31
32#include "util/u_dual_blend.h"
33#include "util/u_format.h"
34#include "util/u_format_s3tc.h"
35#include "util/u_memory.h"
36#include "util/u_pstipple.h"
37#include "util/u_resource.h"
38
39/* Initialize an external atom (owned by ../radeon). */
40static void
41si_init_external_atom(struct si_context *sctx, struct r600_atom *atom,
42		      struct r600_atom **list_elem)
43{
44	atom->id = list_elem - sctx->atoms.array + 1;
45	*list_elem = atom;
46}
47
48/* Initialize an atom owned by radeonsi.  */
49void si_init_atom(struct si_context *sctx, struct r600_atom *atom,
50		  struct r600_atom **list_elem,
51		  void (*emit_func)(struct si_context *ctx, struct r600_atom *state))
52{
53	atom->emit = (void*)emit_func;
54	atom->id = list_elem - sctx->atoms.array + 1; /* index+1 in the atom array */
55	*list_elem = atom;
56}
57
58static unsigned si_map_swizzle(unsigned swizzle)
59{
60	switch (swizzle) {
61	case PIPE_SWIZZLE_Y:
62		return V_008F0C_SQ_SEL_Y;
63	case PIPE_SWIZZLE_Z:
64		return V_008F0C_SQ_SEL_Z;
65	case PIPE_SWIZZLE_W:
66		return V_008F0C_SQ_SEL_W;
67	case PIPE_SWIZZLE_0:
68		return V_008F0C_SQ_SEL_0;
69	case PIPE_SWIZZLE_1:
70		return V_008F0C_SQ_SEL_1;
71	default: /* PIPE_SWIZZLE_X */
72		return V_008F0C_SQ_SEL_X;
73	}
74}
75
76static uint32_t S_FIXED(float value, uint32_t frac_bits)
77{
78	return value * (1 << frac_bits);
79}
80
81/* 12.4 fixed-point */
82static unsigned si_pack_float_12p4(float x)
83{
84	return x <= 0    ? 0 :
85	       x >= 4096 ? 0xffff : x * 16;
86}
87
88/*
89 * Inferred framebuffer and blender state.
90 *
91 * One of the reasons CB_TARGET_MASK must be derived from the framebuffer state
92 * is that:
93 * - The blend state mask is 0xf most of the time.
94 * - The COLOR1 format isn't INVALID because of possible dual-source blending,
95 *   so COLOR1 is enabled pretty much all the time.
96 * So CB_TARGET_MASK is the only register that can disable COLOR1.
97 *
98 * Another reason is to avoid a hang with dual source blending.
99 */
100static void si_emit_cb_render_state(struct si_context *sctx, struct r600_atom *atom)
101{
102	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
103	struct si_state_blend *blend = sctx->queued.named.blend;
104	uint32_t cb_target_mask = 0, i;
105
106	for (i = 0; i < sctx->framebuffer.state.nr_cbufs; i++)
107		if (sctx->framebuffer.state.cbufs[i])
108			cb_target_mask |= 0xf << (4*i);
109
110	if (blend)
111		cb_target_mask &= blend->cb_target_mask;
112
113	/* Avoid a hang that happens when dual source blending is enabled
114	 * but there is not enough color outputs. This is undefined behavior,
115	 * so disable color writes completely.
116	 *
117	 * Reproducible with Unigine Heaven 4.0 and drirc missing.
118	 */
119	if (blend && blend->dual_src_blend &&
120	    sctx->ps_shader.cso &&
121	    (sctx->ps_shader.cso->info.colors_written & 0x3) != 0x3)
122		cb_target_mask = 0;
123
124	radeon_set_context_reg(cs, R_028238_CB_TARGET_MASK, cb_target_mask);
125
126	/* STONEY-specific register settings. */
127	if (sctx->b.family == CHIP_STONEY) {
128		unsigned spi_shader_col_format =
129			sctx->ps_shader.cso ?
130			sctx->ps_shader.current->key.ps.epilog.spi_shader_col_format : 0;
131		unsigned sx_ps_downconvert = 0;
132		unsigned sx_blend_opt_epsilon = 0;
133		unsigned sx_blend_opt_control = 0;
134
135		for (i = 0; i < sctx->framebuffer.state.nr_cbufs; i++) {
136			struct r600_surface *surf =
137				(struct r600_surface*)sctx->framebuffer.state.cbufs[i];
138			unsigned format, swap, spi_format, colormask;
139			bool has_alpha, has_rgb;
140
141			if (!surf)
142				continue;
143
144			format = G_028C70_FORMAT(surf->cb_color_info);
145			swap = G_028C70_COMP_SWAP(surf->cb_color_info);
146			spi_format = (spi_shader_col_format >> (i * 4)) & 0xf;
147			colormask = (cb_target_mask >> (i * 4)) & 0xf;
148
149			/* Set if RGB and A are present. */
150			has_alpha = !G_028C74_FORCE_DST_ALPHA_1(surf->cb_color_attrib);
151
152			if (format == V_028C70_COLOR_8 ||
153			    format == V_028C70_COLOR_16 ||
154			    format == V_028C70_COLOR_32)
155				has_rgb = !has_alpha;
156			else
157				has_rgb = true;
158
159			/* Check the colormask and export format. */
160			if (!(colormask & (PIPE_MASK_RGBA & ~PIPE_MASK_A)))
161				has_rgb = false;
162			if (!(colormask & PIPE_MASK_A))
163				has_alpha = false;
164
165			if (spi_format == V_028714_SPI_SHADER_ZERO) {
166				has_rgb = false;
167				has_alpha = false;
168			}
169
170			/* Disable value checking for disabled channels. */
171			if (!has_rgb)
172				sx_blend_opt_control |= S_02875C_MRT0_COLOR_OPT_DISABLE(1) << (i * 4);
173			if (!has_alpha)
174				sx_blend_opt_control |= S_02875C_MRT0_ALPHA_OPT_DISABLE(1) << (i * 4);
175
176			/* Enable down-conversion for 32bpp and smaller formats. */
177			switch (format) {
178			case V_028C70_COLOR_8:
179			case V_028C70_COLOR_8_8:
180			case V_028C70_COLOR_8_8_8_8:
181				/* For 1 and 2-channel formats, use the superset thereof. */
182				if (spi_format == V_028714_SPI_SHADER_FP16_ABGR ||
183				    spi_format == V_028714_SPI_SHADER_UINT16_ABGR ||
184				    spi_format == V_028714_SPI_SHADER_SINT16_ABGR) {
185					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_8_8_8_8 << (i * 4);
186					sx_blend_opt_epsilon |= V_028758_8BIT_FORMAT << (i * 4);
187				}
188				break;
189
190			case V_028C70_COLOR_5_6_5:
191				if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
192					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_5_6_5 << (i * 4);
193					sx_blend_opt_epsilon |= V_028758_6BIT_FORMAT << (i * 4);
194				}
195				break;
196
197			case V_028C70_COLOR_1_5_5_5:
198				if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
199					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_1_5_5_5 << (i * 4);
200					sx_blend_opt_epsilon |= V_028758_5BIT_FORMAT << (i * 4);
201				}
202				break;
203
204			case V_028C70_COLOR_4_4_4_4:
205				if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
206					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_4_4_4_4 << (i * 4);
207					sx_blend_opt_epsilon |= V_028758_4BIT_FORMAT << (i * 4);
208				}
209				break;
210
211			case V_028C70_COLOR_32:
212				if (swap == V_0280A0_SWAP_STD &&
213				    spi_format == V_028714_SPI_SHADER_32_R)
214					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_32_R << (i * 4);
215				else if (swap == V_0280A0_SWAP_ALT_REV &&
216					 spi_format == V_028714_SPI_SHADER_32_AR)
217					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_32_A << (i * 4);
218				break;
219
220			case V_028C70_COLOR_16:
221			case V_028C70_COLOR_16_16:
222				/* For 1-channel formats, use the superset thereof. */
223				if (spi_format == V_028714_SPI_SHADER_UNORM16_ABGR ||
224				    spi_format == V_028714_SPI_SHADER_SNORM16_ABGR ||
225				    spi_format == V_028714_SPI_SHADER_UINT16_ABGR ||
226				    spi_format == V_028714_SPI_SHADER_SINT16_ABGR) {
227					if (swap == V_0280A0_SWAP_STD ||
228					    swap == V_0280A0_SWAP_STD_REV)
229						sx_ps_downconvert |= V_028754_SX_RT_EXPORT_16_16_GR << (i * 4);
230					else
231						sx_ps_downconvert |= V_028754_SX_RT_EXPORT_16_16_AR << (i * 4);
232				}
233				break;
234
235			case V_028C70_COLOR_10_11_11:
236				if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
237					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_10_11_11 << (i * 4);
238					sx_blend_opt_epsilon |= V_028758_11BIT_FORMAT << (i * 4);
239				}
240				break;
241
242			case V_028C70_COLOR_2_10_10_10:
243				if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
244					sx_ps_downconvert |= V_028754_SX_RT_EXPORT_2_10_10_10 << (i * 4);
245					sx_blend_opt_epsilon |= V_028758_10BIT_FORMAT << (i * 4);
246				}
247				break;
248			}
249		}
250
251		if (sctx->screen->b.debug_flags & DBG_NO_RB_PLUS) {
252			sx_ps_downconvert = 0;
253			sx_blend_opt_epsilon = 0;
254			sx_blend_opt_control = 0;
255		}
256
257		radeon_set_context_reg_seq(cs, R_028754_SX_PS_DOWNCONVERT, 3);
258		radeon_emit(cs, sx_ps_downconvert);	/* R_028754_SX_PS_DOWNCONVERT */
259		radeon_emit(cs, sx_blend_opt_epsilon);	/* R_028758_SX_BLEND_OPT_EPSILON */
260		radeon_emit(cs, sx_blend_opt_control);	/* R_02875C_SX_BLEND_OPT_CONTROL */
261	}
262}
263
264/*
265 * Blender functions
266 */
267
268static uint32_t si_translate_blend_function(int blend_func)
269{
270	switch (blend_func) {
271	case PIPE_BLEND_ADD:
272		return V_028780_COMB_DST_PLUS_SRC;
273	case PIPE_BLEND_SUBTRACT:
274		return V_028780_COMB_SRC_MINUS_DST;
275	case PIPE_BLEND_REVERSE_SUBTRACT:
276		return V_028780_COMB_DST_MINUS_SRC;
277	case PIPE_BLEND_MIN:
278		return V_028780_COMB_MIN_DST_SRC;
279	case PIPE_BLEND_MAX:
280		return V_028780_COMB_MAX_DST_SRC;
281	default:
282		R600_ERR("Unknown blend function %d\n", blend_func);
283		assert(0);
284		break;
285	}
286	return 0;
287}
288
289static uint32_t si_translate_blend_factor(int blend_fact)
290{
291	switch (blend_fact) {
292	case PIPE_BLENDFACTOR_ONE:
293		return V_028780_BLEND_ONE;
294	case PIPE_BLENDFACTOR_SRC_COLOR:
295		return V_028780_BLEND_SRC_COLOR;
296	case PIPE_BLENDFACTOR_SRC_ALPHA:
297		return V_028780_BLEND_SRC_ALPHA;
298	case PIPE_BLENDFACTOR_DST_ALPHA:
299		return V_028780_BLEND_DST_ALPHA;
300	case PIPE_BLENDFACTOR_DST_COLOR:
301		return V_028780_BLEND_DST_COLOR;
302	case PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE:
303		return V_028780_BLEND_SRC_ALPHA_SATURATE;
304	case PIPE_BLENDFACTOR_CONST_COLOR:
305		return V_028780_BLEND_CONSTANT_COLOR;
306	case PIPE_BLENDFACTOR_CONST_ALPHA:
307		return V_028780_BLEND_CONSTANT_ALPHA;
308	case PIPE_BLENDFACTOR_ZERO:
309		return V_028780_BLEND_ZERO;
310	case PIPE_BLENDFACTOR_INV_SRC_COLOR:
311		return V_028780_BLEND_ONE_MINUS_SRC_COLOR;
312	case PIPE_BLENDFACTOR_INV_SRC_ALPHA:
313		return V_028780_BLEND_ONE_MINUS_SRC_ALPHA;
314	case PIPE_BLENDFACTOR_INV_DST_ALPHA:
315		return V_028780_BLEND_ONE_MINUS_DST_ALPHA;
316	case PIPE_BLENDFACTOR_INV_DST_COLOR:
317		return V_028780_BLEND_ONE_MINUS_DST_COLOR;
318	case PIPE_BLENDFACTOR_INV_CONST_COLOR:
319		return V_028780_BLEND_ONE_MINUS_CONSTANT_COLOR;
320	case PIPE_BLENDFACTOR_INV_CONST_ALPHA:
321		return V_028780_BLEND_ONE_MINUS_CONSTANT_ALPHA;
322	case PIPE_BLENDFACTOR_SRC1_COLOR:
323		return V_028780_BLEND_SRC1_COLOR;
324	case PIPE_BLENDFACTOR_SRC1_ALPHA:
325		return V_028780_BLEND_SRC1_ALPHA;
326	case PIPE_BLENDFACTOR_INV_SRC1_COLOR:
327		return V_028780_BLEND_INV_SRC1_COLOR;
328	case PIPE_BLENDFACTOR_INV_SRC1_ALPHA:
329		return V_028780_BLEND_INV_SRC1_ALPHA;
330	default:
331		R600_ERR("Bad blend factor %d not supported!\n", blend_fact);
332		assert(0);
333		break;
334	}
335	return 0;
336}
337
338static uint32_t si_translate_blend_opt_function(int blend_func)
339{
340	switch (blend_func) {
341	case PIPE_BLEND_ADD:
342		return V_028760_OPT_COMB_ADD;
343	case PIPE_BLEND_SUBTRACT:
344		return V_028760_OPT_COMB_SUBTRACT;
345	case PIPE_BLEND_REVERSE_SUBTRACT:
346		return V_028760_OPT_COMB_REVSUBTRACT;
347	case PIPE_BLEND_MIN:
348		return V_028760_OPT_COMB_MIN;
349	case PIPE_BLEND_MAX:
350		return V_028760_OPT_COMB_MAX;
351	default:
352		return V_028760_OPT_COMB_BLEND_DISABLED;
353	}
354}
355
356static uint32_t si_translate_blend_opt_factor(int blend_fact, bool is_alpha)
357{
358	switch (blend_fact) {
359	case PIPE_BLENDFACTOR_ZERO:
360		return V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_ALL;
361	case PIPE_BLENDFACTOR_ONE:
362		return V_028760_BLEND_OPT_PRESERVE_ALL_IGNORE_NONE;
363	case PIPE_BLENDFACTOR_SRC_COLOR:
364		return is_alpha ? V_028760_BLEND_OPT_PRESERVE_A1_IGNORE_A0
365				: V_028760_BLEND_OPT_PRESERVE_C1_IGNORE_C0;
366	case PIPE_BLENDFACTOR_INV_SRC_COLOR:
367		return is_alpha ? V_028760_BLEND_OPT_PRESERVE_A0_IGNORE_A1
368				: V_028760_BLEND_OPT_PRESERVE_C0_IGNORE_C1;
369	case PIPE_BLENDFACTOR_SRC_ALPHA:
370		return V_028760_BLEND_OPT_PRESERVE_A1_IGNORE_A0;
371	case PIPE_BLENDFACTOR_INV_SRC_ALPHA:
372		return V_028760_BLEND_OPT_PRESERVE_A0_IGNORE_A1;
373	case PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE:
374		return is_alpha ? V_028760_BLEND_OPT_PRESERVE_ALL_IGNORE_NONE
375				: V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_A0;
376	default:
377		return V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
378	}
379}
380
381/**
382 * Get rid of DST in the blend factors by commuting the operands:
383 *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
384 */
385static void si_blend_remove_dst(unsigned *func, unsigned *src_factor,
386				unsigned *dst_factor, unsigned expected_dst,
387				unsigned replacement_src)
388{
389	if (*src_factor == expected_dst &&
390	    *dst_factor == PIPE_BLENDFACTOR_ZERO) {
391		*src_factor = PIPE_BLENDFACTOR_ZERO;
392		*dst_factor = replacement_src;
393
394		/* Commuting the operands requires reversing subtractions. */
395		if (*func == PIPE_BLEND_SUBTRACT)
396			*func = PIPE_BLEND_REVERSE_SUBTRACT;
397		else if (*func == PIPE_BLEND_REVERSE_SUBTRACT)
398			*func = PIPE_BLEND_SUBTRACT;
399	}
400}
401
402static bool si_blend_factor_uses_dst(unsigned factor)
403{
404	return factor == PIPE_BLENDFACTOR_DST_COLOR ||
405		factor == PIPE_BLENDFACTOR_DST_ALPHA ||
406		factor == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE ||
407		factor == PIPE_BLENDFACTOR_INV_DST_ALPHA ||
408		factor == PIPE_BLENDFACTOR_INV_DST_COLOR;
409}
410
411static void *si_create_blend_state_mode(struct pipe_context *ctx,
412					const struct pipe_blend_state *state,
413					unsigned mode)
414{
415	struct si_context *sctx = (struct si_context*)ctx;
416	struct si_state_blend *blend = CALLOC_STRUCT(si_state_blend);
417	struct si_pm4_state *pm4 = &blend->pm4;
418	uint32_t sx_mrt_blend_opt[8] = {0};
419	uint32_t color_control = 0;
420
421	if (!blend)
422		return NULL;
423
424	blend->alpha_to_coverage = state->alpha_to_coverage;
425	blend->alpha_to_one = state->alpha_to_one;
426	blend->dual_src_blend = util_blend_state_is_dual(state, 0);
427
428	if (state->logicop_enable) {
429		color_control |= S_028808_ROP3(state->logicop_func | (state->logicop_func << 4));
430	} else {
431		color_control |= S_028808_ROP3(0xcc);
432	}
433
434	si_pm4_set_reg(pm4, R_028B70_DB_ALPHA_TO_MASK,
435		       S_028B70_ALPHA_TO_MASK_ENABLE(state->alpha_to_coverage) |
436		       S_028B70_ALPHA_TO_MASK_OFFSET0(2) |
437		       S_028B70_ALPHA_TO_MASK_OFFSET1(2) |
438		       S_028B70_ALPHA_TO_MASK_OFFSET2(2) |
439		       S_028B70_ALPHA_TO_MASK_OFFSET3(2));
440
441	if (state->alpha_to_coverage)
442		blend->need_src_alpha_4bit |= 0xf;
443
444	blend->cb_target_mask = 0;
445	for (int i = 0; i < 8; i++) {
446		/* state->rt entries > 0 only written if independent blending */
447		const int j = state->independent_blend_enable ? i : 0;
448
449		unsigned eqRGB = state->rt[j].rgb_func;
450		unsigned srcRGB = state->rt[j].rgb_src_factor;
451		unsigned dstRGB = state->rt[j].rgb_dst_factor;
452		unsigned eqA = state->rt[j].alpha_func;
453		unsigned srcA = state->rt[j].alpha_src_factor;
454		unsigned dstA = state->rt[j].alpha_dst_factor;
455
456		unsigned srcRGB_opt, dstRGB_opt, srcA_opt, dstA_opt;
457		unsigned blend_cntl = 0;
458
459		sx_mrt_blend_opt[i] =
460			S_028760_COLOR_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED) |
461			S_028760_ALPHA_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED);
462
463		if (!state->rt[j].colormask)
464			continue;
465
466		/* cb_render_state will disable unused ones */
467		blend->cb_target_mask |= (unsigned)state->rt[j].colormask << (4 * i);
468
469		if (!state->rt[j].blend_enable) {
470			si_pm4_set_reg(pm4, R_028780_CB_BLEND0_CONTROL + i * 4, blend_cntl);
471			continue;
472		}
473
474		/* Blending optimizations for Stoney.
475		 * These transformations don't change the behavior.
476		 *
477		 * First, get rid of DST in the blend factors:
478		 *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
479		 */
480		si_blend_remove_dst(&eqRGB, &srcRGB, &dstRGB,
481				    PIPE_BLENDFACTOR_DST_COLOR,
482				    PIPE_BLENDFACTOR_SRC_COLOR);
483		si_blend_remove_dst(&eqA, &srcA, &dstA,
484				    PIPE_BLENDFACTOR_DST_COLOR,
485				    PIPE_BLENDFACTOR_SRC_COLOR);
486		si_blend_remove_dst(&eqA, &srcA, &dstA,
487				    PIPE_BLENDFACTOR_DST_ALPHA,
488				    PIPE_BLENDFACTOR_SRC_ALPHA);
489
490		/* Look up the ideal settings from tables. */
491		srcRGB_opt = si_translate_blend_opt_factor(srcRGB, false);
492		dstRGB_opt = si_translate_blend_opt_factor(dstRGB, false);
493		srcA_opt = si_translate_blend_opt_factor(srcA, true);
494		dstA_opt = si_translate_blend_opt_factor(dstA, true);
495
496		/* Handle interdependencies. */
497		if (si_blend_factor_uses_dst(srcRGB))
498			dstRGB_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
499		if (si_blend_factor_uses_dst(srcA))
500			dstA_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
501
502		if (srcRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE &&
503		    (dstRGB == PIPE_BLENDFACTOR_ZERO ||
504		     dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA ||
505		     dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE))
506			dstRGB_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_A0;
507
508		/* Set the final value. */
509		sx_mrt_blend_opt[i] =
510			S_028760_COLOR_SRC_OPT(srcRGB_opt) |
511			S_028760_COLOR_DST_OPT(dstRGB_opt) |
512			S_028760_COLOR_COMB_FCN(si_translate_blend_opt_function(eqRGB)) |
513			S_028760_ALPHA_SRC_OPT(srcA_opt) |
514			S_028760_ALPHA_DST_OPT(dstA_opt) |
515			S_028760_ALPHA_COMB_FCN(si_translate_blend_opt_function(eqA));
516
517		/* Set blend state. */
518		blend_cntl |= S_028780_ENABLE(1);
519		blend_cntl |= S_028780_COLOR_COMB_FCN(si_translate_blend_function(eqRGB));
520		blend_cntl |= S_028780_COLOR_SRCBLEND(si_translate_blend_factor(srcRGB));
521		blend_cntl |= S_028780_COLOR_DESTBLEND(si_translate_blend_factor(dstRGB));
522
523		if (srcA != srcRGB || dstA != dstRGB || eqA != eqRGB) {
524			blend_cntl |= S_028780_SEPARATE_ALPHA_BLEND(1);
525			blend_cntl |= S_028780_ALPHA_COMB_FCN(si_translate_blend_function(eqA));
526			blend_cntl |= S_028780_ALPHA_SRCBLEND(si_translate_blend_factor(srcA));
527			blend_cntl |= S_028780_ALPHA_DESTBLEND(si_translate_blend_factor(dstA));
528		}
529		si_pm4_set_reg(pm4, R_028780_CB_BLEND0_CONTROL + i * 4, blend_cntl);
530
531		blend->blend_enable_4bit |= 0xfu << (i * 4);
532
533		/* This is only important for formats without alpha. */
534		if (srcRGB == PIPE_BLENDFACTOR_SRC_ALPHA ||
535		    dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA ||
536		    srcRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE ||
537		    dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE ||
538		    srcRGB == PIPE_BLENDFACTOR_INV_SRC_ALPHA ||
539		    dstRGB == PIPE_BLENDFACTOR_INV_SRC_ALPHA)
540			blend->need_src_alpha_4bit |= 0xfu << (i * 4);
541	}
542
543	if (blend->cb_target_mask) {
544		color_control |= S_028808_MODE(mode);
545	} else {
546		color_control |= S_028808_MODE(V_028808_CB_DISABLE);
547	}
548
549	if (sctx->b.family == CHIP_STONEY) {
550		for (int i = 0; i < 8; i++)
551			si_pm4_set_reg(pm4, R_028760_SX_MRT0_BLEND_OPT + i * 4,
552				       sx_mrt_blend_opt[i]);
553
554		/* RB+ doesn't work with dual source blending, logic op, and RESOLVE. */
555		if (blend->dual_src_blend || state->logicop_enable ||
556		    mode == V_028808_CB_RESOLVE)
557			color_control |= S_028808_DISABLE_DUAL_QUAD(1);
558	}
559
560	si_pm4_set_reg(pm4, R_028808_CB_COLOR_CONTROL, color_control);
561	return blend;
562}
563
564static void *si_create_blend_state(struct pipe_context *ctx,
565				   const struct pipe_blend_state *state)
566{
567	return si_create_blend_state_mode(ctx, state, V_028808_CB_NORMAL);
568}
569
570static void si_bind_blend_state(struct pipe_context *ctx, void *state)
571{
572	struct si_context *sctx = (struct si_context *)ctx;
573	si_pm4_bind_state(sctx, blend, (struct si_state_blend *)state);
574	si_mark_atom_dirty(sctx, &sctx->cb_render_state);
575}
576
577static void si_delete_blend_state(struct pipe_context *ctx, void *state)
578{
579	struct si_context *sctx = (struct si_context *)ctx;
580	si_pm4_delete_state(sctx, blend, (struct si_state_blend *)state);
581}
582
583static void si_set_blend_color(struct pipe_context *ctx,
584			       const struct pipe_blend_color *state)
585{
586	struct si_context *sctx = (struct si_context *)ctx;
587
588	if (memcmp(&sctx->blend_color.state, state, sizeof(*state)) == 0)
589		return;
590
591	sctx->blend_color.state = *state;
592	si_mark_atom_dirty(sctx, &sctx->blend_color.atom);
593}
594
595static void si_emit_blend_color(struct si_context *sctx, struct r600_atom *atom)
596{
597	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
598
599	radeon_set_context_reg_seq(cs, R_028414_CB_BLEND_RED, 4);
600	radeon_emit_array(cs, (uint32_t*)sctx->blend_color.state.color, 4);
601}
602
603/*
604 * Clipping
605 */
606
607static void si_set_clip_state(struct pipe_context *ctx,
608			      const struct pipe_clip_state *state)
609{
610	struct si_context *sctx = (struct si_context *)ctx;
611	struct pipe_constant_buffer cb;
612
613	if (memcmp(&sctx->clip_state.state, state, sizeof(*state)) == 0)
614		return;
615
616	sctx->clip_state.state = *state;
617	si_mark_atom_dirty(sctx, &sctx->clip_state.atom);
618
619	cb.buffer = NULL;
620	cb.user_buffer = state->ucp;
621	cb.buffer_offset = 0;
622	cb.buffer_size = 4*4*8;
623	si_set_rw_buffer(sctx, SI_VS_CONST_CLIP_PLANES, &cb);
624	pipe_resource_reference(&cb.buffer, NULL);
625}
626
627static void si_emit_clip_state(struct si_context *sctx, struct r600_atom *atom)
628{
629	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
630
631	radeon_set_context_reg_seq(cs, R_0285BC_PA_CL_UCP_0_X, 6*4);
632	radeon_emit_array(cs, (uint32_t*)sctx->clip_state.state.ucp, 6*4);
633}
634
635#define SIX_BITS 0x3F
636
637static void si_emit_clip_regs(struct si_context *sctx, struct r600_atom *atom)
638{
639	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
640	struct tgsi_shader_info *info = si_get_vs_info(sctx);
641	unsigned window_space =
642	   info->properties[TGSI_PROPERTY_VS_WINDOW_SPACE_POSITION];
643	unsigned clipdist_mask =
644		info->writes_clipvertex ? SIX_BITS : info->clipdist_writemask;
645
646	radeon_set_context_reg(cs, R_02881C_PA_CL_VS_OUT_CNTL,
647		S_02881C_USE_VTX_POINT_SIZE(info->writes_psize) |
648		S_02881C_USE_VTX_EDGE_FLAG(info->writes_edgeflag) |
649		S_02881C_USE_VTX_RENDER_TARGET_INDX(info->writes_layer) |
650	        S_02881C_USE_VTX_VIEWPORT_INDX(info->writes_viewport_index) |
651		S_02881C_VS_OUT_CCDIST0_VEC_ENA((clipdist_mask & 0x0F) != 0) |
652		S_02881C_VS_OUT_CCDIST1_VEC_ENA((clipdist_mask & 0xF0) != 0) |
653		S_02881C_VS_OUT_MISC_VEC_ENA(info->writes_psize ||
654					    info->writes_edgeflag ||
655					    info->writes_layer ||
656					     info->writes_viewport_index) |
657		S_02881C_VS_OUT_MISC_SIDE_BUS_ENA(1) |
658		(sctx->queued.named.rasterizer->clip_plane_enable &
659		 clipdist_mask));
660	radeon_set_context_reg(cs, R_028810_PA_CL_CLIP_CNTL,
661		sctx->queued.named.rasterizer->pa_cl_clip_cntl |
662		(clipdist_mask ? 0 :
663		 sctx->queued.named.rasterizer->clip_plane_enable & SIX_BITS) |
664		S_028810_CLIP_DISABLE(window_space));
665
666	/* reuse needs to be set off if we write oViewport */
667	radeon_set_context_reg(cs, R_028AB4_VGT_REUSE_OFF,
668			       S_028AB4_REUSE_OFF(info->writes_viewport_index));
669}
670
671/*
672 * inferred state between framebuffer and rasterizer
673 */
674static void si_update_poly_offset_state(struct si_context *sctx)
675{
676	struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
677
678	if (!rs || !rs->uses_poly_offset || !sctx->framebuffer.state.zsbuf)
679		return;
680
681	switch (sctx->framebuffer.state.zsbuf->texture->format) {
682	case PIPE_FORMAT_Z16_UNORM:
683		si_pm4_bind_state(sctx, poly_offset, &rs->pm4_poly_offset[0]);
684		break;
685	default: /* 24-bit */
686		si_pm4_bind_state(sctx, poly_offset, &rs->pm4_poly_offset[1]);
687		break;
688	case PIPE_FORMAT_Z32_FLOAT:
689	case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
690		si_pm4_bind_state(sctx, poly_offset, &rs->pm4_poly_offset[2]);
691		break;
692	}
693}
694
695/*
696 * Rasterizer
697 */
698
699static uint32_t si_translate_fill(uint32_t func)
700{
701	switch(func) {
702	case PIPE_POLYGON_MODE_FILL:
703		return V_028814_X_DRAW_TRIANGLES;
704	case PIPE_POLYGON_MODE_LINE:
705		return V_028814_X_DRAW_LINES;
706	case PIPE_POLYGON_MODE_POINT:
707		return V_028814_X_DRAW_POINTS;
708	default:
709		assert(0);
710		return V_028814_X_DRAW_POINTS;
711	}
712}
713
714static void *si_create_rs_state(struct pipe_context *ctx,
715				const struct pipe_rasterizer_state *state)
716{
717	struct si_state_rasterizer *rs = CALLOC_STRUCT(si_state_rasterizer);
718	struct si_pm4_state *pm4 = &rs->pm4;
719	unsigned tmp, i;
720	float psize_min, psize_max;
721
722	if (!rs) {
723		return NULL;
724	}
725
726	rs->scissor_enable = state->scissor;
727	rs->two_side = state->light_twoside;
728	rs->multisample_enable = state->multisample;
729	rs->force_persample_interp = state->force_persample_interp;
730	rs->clip_plane_enable = state->clip_plane_enable;
731	rs->line_stipple_enable = state->line_stipple_enable;
732	rs->poly_stipple_enable = state->poly_stipple_enable;
733	rs->line_smooth = state->line_smooth;
734	rs->poly_smooth = state->poly_smooth;
735	rs->uses_poly_offset = state->offset_point || state->offset_line ||
736			       state->offset_tri;
737	rs->clamp_fragment_color = state->clamp_fragment_color;
738	rs->flatshade = state->flatshade;
739	rs->sprite_coord_enable = state->sprite_coord_enable;
740	rs->rasterizer_discard = state->rasterizer_discard;
741	rs->pa_sc_line_stipple = state->line_stipple_enable ?
742				S_028A0C_LINE_PATTERN(state->line_stipple_pattern) |
743				S_028A0C_REPEAT_COUNT(state->line_stipple_factor) : 0;
744	rs->pa_cl_clip_cntl =
745		S_028810_DX_CLIP_SPACE_DEF(state->clip_halfz) |
746		S_028810_ZCLIP_NEAR_DISABLE(!state->depth_clip) |
747		S_028810_ZCLIP_FAR_DISABLE(!state->depth_clip) |
748		S_028810_DX_RASTERIZATION_KILL(state->rasterizer_discard) |
749		S_028810_DX_LINEAR_ATTR_CLIP_ENA(1);
750
751	si_pm4_set_reg(pm4, R_0286D4_SPI_INTERP_CONTROL_0,
752		S_0286D4_FLAT_SHADE_ENA(1) |
753		S_0286D4_PNT_SPRITE_ENA(1) |
754		S_0286D4_PNT_SPRITE_OVRD_X(V_0286D4_SPI_PNT_SPRITE_SEL_S) |
755		S_0286D4_PNT_SPRITE_OVRD_Y(V_0286D4_SPI_PNT_SPRITE_SEL_T) |
756		S_0286D4_PNT_SPRITE_OVRD_Z(V_0286D4_SPI_PNT_SPRITE_SEL_0) |
757		S_0286D4_PNT_SPRITE_OVRD_W(V_0286D4_SPI_PNT_SPRITE_SEL_1) |
758		S_0286D4_PNT_SPRITE_TOP_1(state->sprite_coord_mode != PIPE_SPRITE_COORD_UPPER_LEFT));
759
760	/* point size 12.4 fixed point */
761	tmp = (unsigned)(state->point_size * 8.0);
762	si_pm4_set_reg(pm4, R_028A00_PA_SU_POINT_SIZE, S_028A00_HEIGHT(tmp) | S_028A00_WIDTH(tmp));
763
764	if (state->point_size_per_vertex) {
765		psize_min = util_get_min_point_size(state);
766		psize_max = 8192;
767	} else {
768		/* Force the point size to be as if the vertex output was disabled. */
769		psize_min = state->point_size;
770		psize_max = state->point_size;
771	}
772	/* Divide by two, because 0.5 = 1 pixel. */
773	si_pm4_set_reg(pm4, R_028A04_PA_SU_POINT_MINMAX,
774			S_028A04_MIN_SIZE(si_pack_float_12p4(psize_min/2)) |
775			S_028A04_MAX_SIZE(si_pack_float_12p4(psize_max/2)));
776
777	tmp = (unsigned)state->line_width * 8;
778	si_pm4_set_reg(pm4, R_028A08_PA_SU_LINE_CNTL, S_028A08_WIDTH(tmp));
779	si_pm4_set_reg(pm4, R_028A48_PA_SC_MODE_CNTL_0,
780		       S_028A48_LINE_STIPPLE_ENABLE(state->line_stipple_enable) |
781		       S_028A48_MSAA_ENABLE(state->multisample ||
782					    state->poly_smooth ||
783					    state->line_smooth) |
784		       S_028A48_VPORT_SCISSOR_ENABLE(1));
785
786	si_pm4_set_reg(pm4, R_028BE4_PA_SU_VTX_CNTL,
787		       S_028BE4_PIX_CENTER(state->half_pixel_center) |
788		       S_028BE4_QUANT_MODE(V_028BE4_X_16_8_FIXED_POINT_1_256TH));
789
790	si_pm4_set_reg(pm4, R_028B7C_PA_SU_POLY_OFFSET_CLAMP, fui(state->offset_clamp));
791	si_pm4_set_reg(pm4, R_028814_PA_SU_SC_MODE_CNTL,
792		S_028814_PROVOKING_VTX_LAST(!state->flatshade_first) |
793		S_028814_CULL_FRONT((state->cull_face & PIPE_FACE_FRONT) ? 1 : 0) |
794		S_028814_CULL_BACK((state->cull_face & PIPE_FACE_BACK) ? 1 : 0) |
795		S_028814_FACE(!state->front_ccw) |
796		S_028814_POLY_OFFSET_FRONT_ENABLE(util_get_offset(state, state->fill_front)) |
797		S_028814_POLY_OFFSET_BACK_ENABLE(util_get_offset(state, state->fill_back)) |
798		S_028814_POLY_OFFSET_PARA_ENABLE(state->offset_point || state->offset_line) |
799		S_028814_POLY_MODE(state->fill_front != PIPE_POLYGON_MODE_FILL ||
800				   state->fill_back != PIPE_POLYGON_MODE_FILL) |
801		S_028814_POLYMODE_FRONT_PTYPE(si_translate_fill(state->fill_front)) |
802		S_028814_POLYMODE_BACK_PTYPE(si_translate_fill(state->fill_back)));
803	si_pm4_set_reg(pm4, R_00B130_SPI_SHADER_USER_DATA_VS_0 +
804		       SI_SGPR_VS_STATE_BITS * 4, state->clamp_vertex_color);
805
806	/* Precalculate polygon offset states for 16-bit, 24-bit, and 32-bit zbuffers. */
807	for (i = 0; i < 3; i++) {
808		struct si_pm4_state *pm4 = &rs->pm4_poly_offset[i];
809		float offset_units = state->offset_units;
810		float offset_scale = state->offset_scale * 16.0f;
811		uint32_t pa_su_poly_offset_db_fmt_cntl = 0;
812
813		if (!state->offset_units_unscaled) {
814			switch (i) {
815			case 0: /* 16-bit zbuffer */
816				offset_units *= 4.0f;
817				pa_su_poly_offset_db_fmt_cntl =
818					S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
819				break;
820			case 1: /* 24-bit zbuffer */
821				offset_units *= 2.0f;
822				pa_su_poly_offset_db_fmt_cntl =
823					S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
824				break;
825			case 2: /* 32-bit zbuffer */
826				offset_units *= 1.0f;
827				pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
828								S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
829				break;
830			}
831		}
832
833		si_pm4_set_reg(pm4, R_028B80_PA_SU_POLY_OFFSET_FRONT_SCALE,
834			       fui(offset_scale));
835		si_pm4_set_reg(pm4, R_028B84_PA_SU_POLY_OFFSET_FRONT_OFFSET,
836			       fui(offset_units));
837		si_pm4_set_reg(pm4, R_028B88_PA_SU_POLY_OFFSET_BACK_SCALE,
838			       fui(offset_scale));
839		si_pm4_set_reg(pm4, R_028B8C_PA_SU_POLY_OFFSET_BACK_OFFSET,
840			       fui(offset_units));
841		si_pm4_set_reg(pm4, R_028B78_PA_SU_POLY_OFFSET_DB_FMT_CNTL,
842			       pa_su_poly_offset_db_fmt_cntl);
843	}
844
845	return rs;
846}
847
848static void si_bind_rs_state(struct pipe_context *ctx, void *state)
849{
850	struct si_context *sctx = (struct si_context *)ctx;
851	struct si_state_rasterizer *old_rs =
852		(struct si_state_rasterizer*)sctx->queued.named.rasterizer;
853	struct si_state_rasterizer *rs = (struct si_state_rasterizer *)state;
854
855	if (!state)
856		return;
857
858	if (sctx->framebuffer.nr_samples > 1 &&
859	    (!old_rs || old_rs->multisample_enable != rs->multisample_enable))
860		si_mark_atom_dirty(sctx, &sctx->db_render_state);
861
862	r600_set_scissor_enable(&sctx->b, rs->scissor_enable);
863
864	si_pm4_bind_state(sctx, rasterizer, rs);
865	si_update_poly_offset_state(sctx);
866
867	si_mark_atom_dirty(sctx, &sctx->clip_regs);
868}
869
870static void si_delete_rs_state(struct pipe_context *ctx, void *state)
871{
872	struct si_context *sctx = (struct si_context *)ctx;
873
874	if (sctx->queued.named.rasterizer == state)
875		si_pm4_bind_state(sctx, poly_offset, NULL);
876	si_pm4_delete_state(sctx, rasterizer, (struct si_state_rasterizer *)state);
877}
878
879/*
880 * infeered state between dsa and stencil ref
881 */
882static void si_emit_stencil_ref(struct si_context *sctx, struct r600_atom *atom)
883{
884	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
885	struct pipe_stencil_ref *ref = &sctx->stencil_ref.state;
886	struct si_dsa_stencil_ref_part *dsa = &sctx->stencil_ref.dsa_part;
887
888	radeon_set_context_reg_seq(cs, R_028430_DB_STENCILREFMASK, 2);
889	radeon_emit(cs, S_028430_STENCILTESTVAL(ref->ref_value[0]) |
890			S_028430_STENCILMASK(dsa->valuemask[0]) |
891			S_028430_STENCILWRITEMASK(dsa->writemask[0]) |
892			S_028430_STENCILOPVAL(1));
893	radeon_emit(cs, S_028434_STENCILTESTVAL_BF(ref->ref_value[1]) |
894			S_028434_STENCILMASK_BF(dsa->valuemask[1]) |
895			S_028434_STENCILWRITEMASK_BF(dsa->writemask[1]) |
896			S_028434_STENCILOPVAL_BF(1));
897}
898
899static void si_set_stencil_ref(struct pipe_context *ctx,
900			       const struct pipe_stencil_ref *state)
901{
902        struct si_context *sctx = (struct si_context *)ctx;
903
904	if (memcmp(&sctx->stencil_ref.state, state, sizeof(*state)) == 0)
905		return;
906
907	sctx->stencil_ref.state = *state;
908	si_mark_atom_dirty(sctx, &sctx->stencil_ref.atom);
909}
910
911
912/*
913 * DSA
914 */
915
916static uint32_t si_translate_stencil_op(int s_op)
917{
918	switch (s_op) {
919	case PIPE_STENCIL_OP_KEEP:
920		return V_02842C_STENCIL_KEEP;
921	case PIPE_STENCIL_OP_ZERO:
922		return V_02842C_STENCIL_ZERO;
923	case PIPE_STENCIL_OP_REPLACE:
924		return V_02842C_STENCIL_REPLACE_TEST;
925	case PIPE_STENCIL_OP_INCR:
926		return V_02842C_STENCIL_ADD_CLAMP;
927	case PIPE_STENCIL_OP_DECR:
928		return V_02842C_STENCIL_SUB_CLAMP;
929	case PIPE_STENCIL_OP_INCR_WRAP:
930		return V_02842C_STENCIL_ADD_WRAP;
931	case PIPE_STENCIL_OP_DECR_WRAP:
932		return V_02842C_STENCIL_SUB_WRAP;
933	case PIPE_STENCIL_OP_INVERT:
934		return V_02842C_STENCIL_INVERT;
935	default:
936		R600_ERR("Unknown stencil op %d", s_op);
937		assert(0);
938		break;
939	}
940	return 0;
941}
942
943static void *si_create_dsa_state(struct pipe_context *ctx,
944				 const struct pipe_depth_stencil_alpha_state *state)
945{
946	struct si_state_dsa *dsa = CALLOC_STRUCT(si_state_dsa);
947	struct si_pm4_state *pm4 = &dsa->pm4;
948	unsigned db_depth_control;
949	uint32_t db_stencil_control = 0;
950
951	if (!dsa) {
952		return NULL;
953	}
954
955	dsa->stencil_ref.valuemask[0] = state->stencil[0].valuemask;
956	dsa->stencil_ref.valuemask[1] = state->stencil[1].valuemask;
957	dsa->stencil_ref.writemask[0] = state->stencil[0].writemask;
958	dsa->stencil_ref.writemask[1] = state->stencil[1].writemask;
959
960	db_depth_control = S_028800_Z_ENABLE(state->depth.enabled) |
961		S_028800_Z_WRITE_ENABLE(state->depth.writemask) |
962		S_028800_ZFUNC(state->depth.func) |
963		S_028800_DEPTH_BOUNDS_ENABLE(state->depth.bounds_test);
964
965	/* stencil */
966	if (state->stencil[0].enabled) {
967		db_depth_control |= S_028800_STENCIL_ENABLE(1);
968		db_depth_control |= S_028800_STENCILFUNC(state->stencil[0].func);
969		db_stencil_control |= S_02842C_STENCILFAIL(si_translate_stencil_op(state->stencil[0].fail_op));
970		db_stencil_control |= S_02842C_STENCILZPASS(si_translate_stencil_op(state->stencil[0].zpass_op));
971		db_stencil_control |= S_02842C_STENCILZFAIL(si_translate_stencil_op(state->stencil[0].zfail_op));
972
973		if (state->stencil[1].enabled) {
974			db_depth_control |= S_028800_BACKFACE_ENABLE(1);
975			db_depth_control |= S_028800_STENCILFUNC_BF(state->stencil[1].func);
976			db_stencil_control |= S_02842C_STENCILFAIL_BF(si_translate_stencil_op(state->stencil[1].fail_op));
977			db_stencil_control |= S_02842C_STENCILZPASS_BF(si_translate_stencil_op(state->stencil[1].zpass_op));
978			db_stencil_control |= S_02842C_STENCILZFAIL_BF(si_translate_stencil_op(state->stencil[1].zfail_op));
979		}
980	}
981
982	/* alpha */
983	if (state->alpha.enabled) {
984		dsa->alpha_func = state->alpha.func;
985
986		si_pm4_set_reg(pm4, R_00B030_SPI_SHADER_USER_DATA_PS_0 +
987		               SI_SGPR_ALPHA_REF * 4, fui(state->alpha.ref_value));
988	} else {
989		dsa->alpha_func = PIPE_FUNC_ALWAYS;
990	}
991
992	si_pm4_set_reg(pm4, R_028800_DB_DEPTH_CONTROL, db_depth_control);
993	si_pm4_set_reg(pm4, R_02842C_DB_STENCIL_CONTROL, db_stencil_control);
994	if (state->depth.bounds_test) {
995		si_pm4_set_reg(pm4, R_028020_DB_DEPTH_BOUNDS_MIN, fui(state->depth.bounds_min));
996		si_pm4_set_reg(pm4, R_028024_DB_DEPTH_BOUNDS_MAX, fui(state->depth.bounds_max));
997	}
998
999	return dsa;
1000}
1001
1002static void si_bind_dsa_state(struct pipe_context *ctx, void *state)
1003{
1004        struct si_context *sctx = (struct si_context *)ctx;
1005        struct si_state_dsa *dsa = state;
1006
1007        if (!state)
1008                return;
1009
1010	si_pm4_bind_state(sctx, dsa, dsa);
1011
1012	if (memcmp(&dsa->stencil_ref, &sctx->stencil_ref.dsa_part,
1013		   sizeof(struct si_dsa_stencil_ref_part)) != 0) {
1014		sctx->stencil_ref.dsa_part = dsa->stencil_ref;
1015		si_mark_atom_dirty(sctx, &sctx->stencil_ref.atom);
1016	}
1017}
1018
1019static void si_delete_dsa_state(struct pipe_context *ctx, void *state)
1020{
1021	struct si_context *sctx = (struct si_context *)ctx;
1022	si_pm4_delete_state(sctx, dsa, (struct si_state_dsa *)state);
1023}
1024
1025static void *si_create_db_flush_dsa(struct si_context *sctx)
1026{
1027	struct pipe_depth_stencil_alpha_state dsa = {};
1028
1029	return sctx->b.b.create_depth_stencil_alpha_state(&sctx->b.b, &dsa);
1030}
1031
1032/* DB RENDER STATE */
1033
1034static void si_set_active_query_state(struct pipe_context *ctx, boolean enable)
1035{
1036	struct si_context *sctx = (struct si_context*)ctx;
1037
1038	/* Pipeline stat & streamout queries. */
1039	if (enable) {
1040		sctx->b.flags &= ~R600_CONTEXT_STOP_PIPELINE_STATS;
1041		sctx->b.flags |= R600_CONTEXT_START_PIPELINE_STATS;
1042	} else {
1043		sctx->b.flags &= ~R600_CONTEXT_START_PIPELINE_STATS;
1044		sctx->b.flags |= R600_CONTEXT_STOP_PIPELINE_STATS;
1045	}
1046
1047	/* Occlusion queries. */
1048	if (sctx->occlusion_queries_disabled != !enable) {
1049		sctx->occlusion_queries_disabled = !enable;
1050		si_mark_atom_dirty(sctx, &sctx->db_render_state);
1051	}
1052}
1053
1054static void si_set_occlusion_query_state(struct pipe_context *ctx, bool enable)
1055{
1056	struct si_context *sctx = (struct si_context*)ctx;
1057
1058	si_mark_atom_dirty(sctx, &sctx->db_render_state);
1059}
1060
1061static void si_emit_db_render_state(struct si_context *sctx, struct r600_atom *state)
1062{
1063	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
1064	struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
1065	unsigned db_shader_control;
1066
1067	radeon_set_context_reg_seq(cs, R_028000_DB_RENDER_CONTROL, 2);
1068
1069	/* DB_RENDER_CONTROL */
1070	if (sctx->dbcb_depth_copy_enabled ||
1071	    sctx->dbcb_stencil_copy_enabled) {
1072		radeon_emit(cs,
1073			    S_028000_DEPTH_COPY(sctx->dbcb_depth_copy_enabled) |
1074			    S_028000_STENCIL_COPY(sctx->dbcb_stencil_copy_enabled) |
1075			    S_028000_COPY_CENTROID(1) |
1076			    S_028000_COPY_SAMPLE(sctx->dbcb_copy_sample));
1077	} else if (sctx->db_flush_depth_inplace || sctx->db_flush_stencil_inplace) {
1078		radeon_emit(cs,
1079			    S_028000_DEPTH_COMPRESS_DISABLE(sctx->db_flush_depth_inplace) |
1080			    S_028000_STENCIL_COMPRESS_DISABLE(sctx->db_flush_stencil_inplace));
1081	} else {
1082		radeon_emit(cs,
1083			    S_028000_DEPTH_CLEAR_ENABLE(sctx->db_depth_clear) |
1084			    S_028000_STENCIL_CLEAR_ENABLE(sctx->db_stencil_clear));
1085	}
1086
1087	/* DB_COUNT_CONTROL (occlusion queries) */
1088	if (sctx->b.num_occlusion_queries > 0 &&
1089	    !sctx->occlusion_queries_disabled) {
1090		bool perfect = sctx->b.num_perfect_occlusion_queries > 0;
1091
1092		if (sctx->b.chip_class >= CIK) {
1093			radeon_emit(cs,
1094				    S_028004_PERFECT_ZPASS_COUNTS(perfect) |
1095				    S_028004_SAMPLE_RATE(sctx->framebuffer.log_samples) |
1096				    S_028004_ZPASS_ENABLE(1) |
1097				    S_028004_SLICE_EVEN_ENABLE(1) |
1098				    S_028004_SLICE_ODD_ENABLE(1));
1099		} else {
1100			radeon_emit(cs,
1101				    S_028004_PERFECT_ZPASS_COUNTS(perfect) |
1102				    S_028004_SAMPLE_RATE(sctx->framebuffer.log_samples));
1103		}
1104	} else {
1105		/* Disable occlusion queries. */
1106		if (sctx->b.chip_class >= CIK) {
1107			radeon_emit(cs, 0);
1108		} else {
1109			radeon_emit(cs, S_028004_ZPASS_INCREMENT_DISABLE(1));
1110		}
1111	}
1112
1113	/* DB_RENDER_OVERRIDE2 */
1114	radeon_set_context_reg(cs, R_028010_DB_RENDER_OVERRIDE2,
1115		S_028010_DISABLE_ZMASK_EXPCLEAR_OPTIMIZATION(sctx->db_depth_disable_expclear) |
1116		S_028010_DISABLE_SMEM_EXPCLEAR_OPTIMIZATION(sctx->db_stencil_disable_expclear) |
1117		S_028010_DECOMPRESS_Z_ON_FLUSH(sctx->framebuffer.nr_samples >= 4));
1118
1119	db_shader_control = S_02880C_ALPHA_TO_MASK_DISABLE(sctx->framebuffer.cb0_is_integer) |
1120		            sctx->ps_db_shader_control;
1121
1122	/* Bug workaround for smoothing (overrasterization) on SI. */
1123	if (sctx->b.chip_class == SI && sctx->smoothing_enabled) {
1124		db_shader_control &= C_02880C_Z_ORDER;
1125		db_shader_control |= S_02880C_Z_ORDER(V_02880C_LATE_Z);
1126	}
1127
1128	/* Disable the gl_SampleMask fragment shader output if MSAA is disabled. */
1129	if (sctx->framebuffer.nr_samples <= 1 || (rs && !rs->multisample_enable))
1130		db_shader_control &= C_02880C_MASK_EXPORT_ENABLE;
1131
1132	if (sctx->b.family == CHIP_STONEY &&
1133	    sctx->screen->b.debug_flags & DBG_NO_RB_PLUS)
1134		db_shader_control |= S_02880C_DUAL_QUAD_DISABLE(1);
1135
1136	radeon_set_context_reg(cs, R_02880C_DB_SHADER_CONTROL,
1137			       db_shader_control);
1138}
1139
1140/*
1141 * format translation
1142 */
1143static uint32_t si_translate_colorformat(enum pipe_format format)
1144{
1145	const struct util_format_description *desc = util_format_description(format);
1146
1147#define HAS_SIZE(x,y,z,w) \
1148	(desc->channel[0].size == (x) && desc->channel[1].size == (y) && \
1149         desc->channel[2].size == (z) && desc->channel[3].size == (w))
1150
1151	if (format == PIPE_FORMAT_R11G11B10_FLOAT) /* isn't plain */
1152		return V_028C70_COLOR_10_11_11;
1153
1154	if (desc->layout != UTIL_FORMAT_LAYOUT_PLAIN)
1155		return V_028C70_COLOR_INVALID;
1156
1157	/* hw cannot support mixed formats (except depth/stencil, since
1158	 * stencil is not written to). */
1159	if (desc->is_mixed && desc->colorspace != UTIL_FORMAT_COLORSPACE_ZS)
1160		return V_028C70_COLOR_INVALID;
1161
1162	switch (desc->nr_channels) {
1163	case 1:
1164		switch (desc->channel[0].size) {
1165		case 8:
1166			return V_028C70_COLOR_8;
1167		case 16:
1168			return V_028C70_COLOR_16;
1169		case 32:
1170			return V_028C70_COLOR_32;
1171		}
1172		break;
1173	case 2:
1174		if (desc->channel[0].size == desc->channel[1].size) {
1175			switch (desc->channel[0].size) {
1176			case 8:
1177				return V_028C70_COLOR_8_8;
1178			case 16:
1179				return V_028C70_COLOR_16_16;
1180			case 32:
1181				return V_028C70_COLOR_32_32;
1182			}
1183		} else if (HAS_SIZE(8,24,0,0)) {
1184			return V_028C70_COLOR_24_8;
1185		} else if (HAS_SIZE(24,8,0,0)) {
1186			return V_028C70_COLOR_8_24;
1187		}
1188		break;
1189	case 3:
1190		if (HAS_SIZE(5,6,5,0)) {
1191			return V_028C70_COLOR_5_6_5;
1192		} else if (HAS_SIZE(32,8,24,0)) {
1193			return V_028C70_COLOR_X24_8_32_FLOAT;
1194		}
1195		break;
1196	case 4:
1197		if (desc->channel[0].size == desc->channel[1].size &&
1198		    desc->channel[0].size == desc->channel[2].size &&
1199		    desc->channel[0].size == desc->channel[3].size) {
1200			switch (desc->channel[0].size) {
1201			case 4:
1202				return V_028C70_COLOR_4_4_4_4;
1203			case 8:
1204				return V_028C70_COLOR_8_8_8_8;
1205			case 16:
1206				return V_028C70_COLOR_16_16_16_16;
1207			case 32:
1208				return V_028C70_COLOR_32_32_32_32;
1209			}
1210		} else if (HAS_SIZE(5,5,5,1)) {
1211			return V_028C70_COLOR_1_5_5_5;
1212		} else if (HAS_SIZE(10,10,10,2)) {
1213			return V_028C70_COLOR_2_10_10_10;
1214		}
1215		break;
1216	}
1217	return V_028C70_COLOR_INVALID;
1218}
1219
1220static uint32_t si_colorformat_endian_swap(uint32_t colorformat)
1221{
1222	if (SI_BIG_ENDIAN) {
1223		switch(colorformat) {
1224		/* 8-bit buffers. */
1225		case V_028C70_COLOR_8:
1226			return V_028C70_ENDIAN_NONE;
1227
1228		/* 16-bit buffers. */
1229		case V_028C70_COLOR_5_6_5:
1230		case V_028C70_COLOR_1_5_5_5:
1231		case V_028C70_COLOR_4_4_4_4:
1232		case V_028C70_COLOR_16:
1233		case V_028C70_COLOR_8_8:
1234			return V_028C70_ENDIAN_8IN16;
1235
1236		/* 32-bit buffers. */
1237		case V_028C70_COLOR_8_8_8_8:
1238		case V_028C70_COLOR_2_10_10_10:
1239		case V_028C70_COLOR_8_24:
1240		case V_028C70_COLOR_24_8:
1241		case V_028C70_COLOR_16_16:
1242			return V_028C70_ENDIAN_8IN32;
1243
1244		/* 64-bit buffers. */
1245		case V_028C70_COLOR_16_16_16_16:
1246			return V_028C70_ENDIAN_8IN16;
1247
1248		case V_028C70_COLOR_32_32:
1249			return V_028C70_ENDIAN_8IN32;
1250
1251		/* 128-bit buffers. */
1252		case V_028C70_COLOR_32_32_32_32:
1253			return V_028C70_ENDIAN_8IN32;
1254		default:
1255			return V_028C70_ENDIAN_NONE; /* Unsupported. */
1256		}
1257	} else {
1258		return V_028C70_ENDIAN_NONE;
1259	}
1260}
1261
1262static uint32_t si_translate_dbformat(enum pipe_format format)
1263{
1264	switch (format) {
1265	case PIPE_FORMAT_Z16_UNORM:
1266		return V_028040_Z_16;
1267	case PIPE_FORMAT_S8_UINT_Z24_UNORM:
1268	case PIPE_FORMAT_X8Z24_UNORM:
1269	case PIPE_FORMAT_Z24X8_UNORM:
1270	case PIPE_FORMAT_Z24_UNORM_S8_UINT:
1271		return V_028040_Z_24; /* deprecated on SI */
1272	case PIPE_FORMAT_Z32_FLOAT:
1273	case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
1274		return V_028040_Z_32_FLOAT;
1275	default:
1276		return V_028040_Z_INVALID;
1277	}
1278}
1279
1280/*
1281 * Texture translation
1282 */
1283
1284static uint32_t si_translate_texformat(struct pipe_screen *screen,
1285				       enum pipe_format format,
1286				       const struct util_format_description *desc,
1287				       int first_non_void)
1288{
1289	struct si_screen *sscreen = (struct si_screen*)screen;
1290	bool enable_compressed_formats = (sscreen->b.info.drm_major == 2 &&
1291					  sscreen->b.info.drm_minor >= 31) ||
1292					 sscreen->b.info.drm_major == 3;
1293	bool uniform = true;
1294	int i;
1295
1296	/* Colorspace (return non-RGB formats directly). */
1297	switch (desc->colorspace) {
1298	/* Depth stencil formats */
1299	case UTIL_FORMAT_COLORSPACE_ZS:
1300		switch (format) {
1301		case PIPE_FORMAT_Z16_UNORM:
1302			return V_008F14_IMG_DATA_FORMAT_16;
1303		case PIPE_FORMAT_X24S8_UINT:
1304		case PIPE_FORMAT_Z24X8_UNORM:
1305		case PIPE_FORMAT_Z24_UNORM_S8_UINT:
1306			return V_008F14_IMG_DATA_FORMAT_8_24;
1307		case PIPE_FORMAT_X8Z24_UNORM:
1308		case PIPE_FORMAT_S8X24_UINT:
1309		case PIPE_FORMAT_S8_UINT_Z24_UNORM:
1310			return V_008F14_IMG_DATA_FORMAT_24_8;
1311		case PIPE_FORMAT_S8_UINT:
1312			return V_008F14_IMG_DATA_FORMAT_8;
1313		case PIPE_FORMAT_Z32_FLOAT:
1314			return V_008F14_IMG_DATA_FORMAT_32;
1315		case PIPE_FORMAT_X32_S8X24_UINT:
1316		case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
1317			return V_008F14_IMG_DATA_FORMAT_X24_8_32;
1318		default:
1319			goto out_unknown;
1320		}
1321
1322	case UTIL_FORMAT_COLORSPACE_YUV:
1323		goto out_unknown; /* TODO */
1324
1325	case UTIL_FORMAT_COLORSPACE_SRGB:
1326		if (desc->nr_channels != 4 && desc->nr_channels != 1)
1327			goto out_unknown;
1328		break;
1329
1330	default:
1331		break;
1332	}
1333
1334	if (desc->layout == UTIL_FORMAT_LAYOUT_RGTC) {
1335		if (!enable_compressed_formats)
1336			goto out_unknown;
1337
1338		switch (format) {
1339		case PIPE_FORMAT_RGTC1_SNORM:
1340		case PIPE_FORMAT_LATC1_SNORM:
1341		case PIPE_FORMAT_RGTC1_UNORM:
1342		case PIPE_FORMAT_LATC1_UNORM:
1343			return V_008F14_IMG_DATA_FORMAT_BC4;
1344		case PIPE_FORMAT_RGTC2_SNORM:
1345		case PIPE_FORMAT_LATC2_SNORM:
1346		case PIPE_FORMAT_RGTC2_UNORM:
1347		case PIPE_FORMAT_LATC2_UNORM:
1348			return V_008F14_IMG_DATA_FORMAT_BC5;
1349		default:
1350			goto out_unknown;
1351		}
1352	}
1353
1354	if (desc->layout == UTIL_FORMAT_LAYOUT_ETC &&
1355	    sscreen->b.family == CHIP_STONEY) {
1356		switch (format) {
1357		case PIPE_FORMAT_ETC1_RGB8:
1358		case PIPE_FORMAT_ETC2_RGB8:
1359		case PIPE_FORMAT_ETC2_SRGB8:
1360			return V_008F14_IMG_DATA_FORMAT_ETC2_RGB;
1361		case PIPE_FORMAT_ETC2_RGB8A1:
1362		case PIPE_FORMAT_ETC2_SRGB8A1:
1363			return V_008F14_IMG_DATA_FORMAT_ETC2_RGBA1;
1364		case PIPE_FORMAT_ETC2_RGBA8:
1365		case PIPE_FORMAT_ETC2_SRGBA8:
1366			return V_008F14_IMG_DATA_FORMAT_ETC2_RGBA;
1367		case PIPE_FORMAT_ETC2_R11_UNORM:
1368		case PIPE_FORMAT_ETC2_R11_SNORM:
1369			return V_008F14_IMG_DATA_FORMAT_ETC2_R;
1370		case PIPE_FORMAT_ETC2_RG11_UNORM:
1371		case PIPE_FORMAT_ETC2_RG11_SNORM:
1372			return V_008F14_IMG_DATA_FORMAT_ETC2_RG;
1373		default:
1374			goto out_unknown;
1375		}
1376	}
1377
1378	if (desc->layout == UTIL_FORMAT_LAYOUT_BPTC) {
1379		if (!enable_compressed_formats)
1380			goto out_unknown;
1381
1382		switch (format) {
1383		case PIPE_FORMAT_BPTC_RGBA_UNORM:
1384		case PIPE_FORMAT_BPTC_SRGBA:
1385			return V_008F14_IMG_DATA_FORMAT_BC7;
1386		case PIPE_FORMAT_BPTC_RGB_FLOAT:
1387		case PIPE_FORMAT_BPTC_RGB_UFLOAT:
1388			return V_008F14_IMG_DATA_FORMAT_BC6;
1389		default:
1390			goto out_unknown;
1391		}
1392	}
1393
1394	if (desc->layout == UTIL_FORMAT_LAYOUT_SUBSAMPLED) {
1395		switch (format) {
1396		case PIPE_FORMAT_R8G8_B8G8_UNORM:
1397		case PIPE_FORMAT_G8R8_B8R8_UNORM:
1398			return V_008F14_IMG_DATA_FORMAT_GB_GR;
1399		case PIPE_FORMAT_G8R8_G8B8_UNORM:
1400		case PIPE_FORMAT_R8G8_R8B8_UNORM:
1401			return V_008F14_IMG_DATA_FORMAT_BG_RG;
1402		default:
1403			goto out_unknown;
1404		}
1405	}
1406
1407	if (desc->layout == UTIL_FORMAT_LAYOUT_S3TC) {
1408		if (!enable_compressed_formats)
1409			goto out_unknown;
1410
1411		if (!util_format_s3tc_enabled) {
1412			goto out_unknown;
1413		}
1414
1415		switch (format) {
1416		case PIPE_FORMAT_DXT1_RGB:
1417		case PIPE_FORMAT_DXT1_RGBA:
1418		case PIPE_FORMAT_DXT1_SRGB:
1419		case PIPE_FORMAT_DXT1_SRGBA:
1420			return V_008F14_IMG_DATA_FORMAT_BC1;
1421		case PIPE_FORMAT_DXT3_RGBA:
1422		case PIPE_FORMAT_DXT3_SRGBA:
1423			return V_008F14_IMG_DATA_FORMAT_BC2;
1424		case PIPE_FORMAT_DXT5_RGBA:
1425		case PIPE_FORMAT_DXT5_SRGBA:
1426			return V_008F14_IMG_DATA_FORMAT_BC3;
1427		default:
1428			goto out_unknown;
1429		}
1430	}
1431
1432	if (format == PIPE_FORMAT_R9G9B9E5_FLOAT) {
1433		return V_008F14_IMG_DATA_FORMAT_5_9_9_9;
1434	} else if (format == PIPE_FORMAT_R11G11B10_FLOAT) {
1435		return V_008F14_IMG_DATA_FORMAT_10_11_11;
1436	}
1437
1438	/* R8G8Bx_SNORM - TODO CxV8U8 */
1439
1440	/* hw cannot support mixed formats (except depth/stencil, since only
1441	 * depth is read).*/
1442	if (desc->is_mixed && desc->colorspace != UTIL_FORMAT_COLORSPACE_ZS)
1443		goto out_unknown;
1444
1445	/* See whether the components are of the same size. */
1446	for (i = 1; i < desc->nr_channels; i++) {
1447		uniform = uniform && desc->channel[0].size == desc->channel[i].size;
1448	}
1449
1450	/* Non-uniform formats. */
1451	if (!uniform) {
1452		switch(desc->nr_channels) {
1453		case 3:
1454			if (desc->channel[0].size == 5 &&
1455			    desc->channel[1].size == 6 &&
1456			    desc->channel[2].size == 5) {
1457				return V_008F14_IMG_DATA_FORMAT_5_6_5;
1458			}
1459			goto out_unknown;
1460		case 4:
1461			if (desc->channel[0].size == 5 &&
1462			    desc->channel[1].size == 5 &&
1463			    desc->channel[2].size == 5 &&
1464			    desc->channel[3].size == 1) {
1465				return V_008F14_IMG_DATA_FORMAT_1_5_5_5;
1466			}
1467			if (desc->channel[0].size == 10 &&
1468			    desc->channel[1].size == 10 &&
1469			    desc->channel[2].size == 10 &&
1470			    desc->channel[3].size == 2) {
1471				return V_008F14_IMG_DATA_FORMAT_2_10_10_10;
1472			}
1473			goto out_unknown;
1474		}
1475		goto out_unknown;
1476	}
1477
1478	if (first_non_void < 0 || first_non_void > 3)
1479		goto out_unknown;
1480
1481	/* uniform formats */
1482	switch (desc->channel[first_non_void].size) {
1483	case 4:
1484		switch (desc->nr_channels) {
1485#if 0 /* Not supported for render targets */
1486		case 2:
1487			return V_008F14_IMG_DATA_FORMAT_4_4;
1488#endif
1489		case 4:
1490			return V_008F14_IMG_DATA_FORMAT_4_4_4_4;
1491		}
1492		break;
1493	case 8:
1494		switch (desc->nr_channels) {
1495		case 1:
1496			return V_008F14_IMG_DATA_FORMAT_8;
1497		case 2:
1498			return V_008F14_IMG_DATA_FORMAT_8_8;
1499		case 4:
1500			return V_008F14_IMG_DATA_FORMAT_8_8_8_8;
1501		}
1502		break;
1503	case 16:
1504		switch (desc->nr_channels) {
1505		case 1:
1506			return V_008F14_IMG_DATA_FORMAT_16;
1507		case 2:
1508			return V_008F14_IMG_DATA_FORMAT_16_16;
1509		case 4:
1510			return V_008F14_IMG_DATA_FORMAT_16_16_16_16;
1511		}
1512		break;
1513	case 32:
1514		switch (desc->nr_channels) {
1515		case 1:
1516			return V_008F14_IMG_DATA_FORMAT_32;
1517		case 2:
1518			return V_008F14_IMG_DATA_FORMAT_32_32;
1519#if 0 /* Not supported for render targets */
1520		case 3:
1521			return V_008F14_IMG_DATA_FORMAT_32_32_32;
1522#endif
1523		case 4:
1524			return V_008F14_IMG_DATA_FORMAT_32_32_32_32;
1525		}
1526	}
1527
1528out_unknown:
1529	/* R600_ERR("Unable to handle texformat %d %s\n", format, util_format_name(format)); */
1530	return ~0;
1531}
1532
1533static unsigned si_tex_wrap(unsigned wrap)
1534{
1535	switch (wrap) {
1536	default:
1537	case PIPE_TEX_WRAP_REPEAT:
1538		return V_008F30_SQ_TEX_WRAP;
1539	case PIPE_TEX_WRAP_CLAMP:
1540		return V_008F30_SQ_TEX_CLAMP_HALF_BORDER;
1541	case PIPE_TEX_WRAP_CLAMP_TO_EDGE:
1542		return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
1543	case PIPE_TEX_WRAP_CLAMP_TO_BORDER:
1544		return V_008F30_SQ_TEX_CLAMP_BORDER;
1545	case PIPE_TEX_WRAP_MIRROR_REPEAT:
1546		return V_008F30_SQ_TEX_MIRROR;
1547	case PIPE_TEX_WRAP_MIRROR_CLAMP:
1548		return V_008F30_SQ_TEX_MIRROR_ONCE_HALF_BORDER;
1549	case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE:
1550		return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
1551	case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER:
1552		return V_008F30_SQ_TEX_MIRROR_ONCE_BORDER;
1553	}
1554}
1555
1556static unsigned si_tex_mipfilter(unsigned filter)
1557{
1558	switch (filter) {
1559	case PIPE_TEX_MIPFILTER_NEAREST:
1560		return V_008F38_SQ_TEX_Z_FILTER_POINT;
1561	case PIPE_TEX_MIPFILTER_LINEAR:
1562		return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
1563	default:
1564	case PIPE_TEX_MIPFILTER_NONE:
1565		return V_008F38_SQ_TEX_Z_FILTER_NONE;
1566	}
1567}
1568
1569static unsigned si_tex_compare(unsigned compare)
1570{
1571	switch (compare) {
1572	default:
1573	case PIPE_FUNC_NEVER:
1574		return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
1575	case PIPE_FUNC_LESS:
1576		return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
1577	case PIPE_FUNC_EQUAL:
1578		return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
1579	case PIPE_FUNC_LEQUAL:
1580		return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
1581	case PIPE_FUNC_GREATER:
1582		return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
1583	case PIPE_FUNC_NOTEQUAL:
1584		return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
1585	case PIPE_FUNC_GEQUAL:
1586		return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
1587	case PIPE_FUNC_ALWAYS:
1588		return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
1589	}
1590}
1591
1592static unsigned si_tex_dim(unsigned res_target, unsigned view_target,
1593			   unsigned nr_samples)
1594{
1595	if (view_target == PIPE_TEXTURE_CUBE ||
1596	    view_target == PIPE_TEXTURE_CUBE_ARRAY)
1597		res_target = view_target;
1598
1599	switch (res_target) {
1600	default:
1601	case PIPE_TEXTURE_1D:
1602		return V_008F1C_SQ_RSRC_IMG_1D;
1603	case PIPE_TEXTURE_1D_ARRAY:
1604		return V_008F1C_SQ_RSRC_IMG_1D_ARRAY;
1605	case PIPE_TEXTURE_2D:
1606	case PIPE_TEXTURE_RECT:
1607		return nr_samples > 1 ? V_008F1C_SQ_RSRC_IMG_2D_MSAA :
1608					V_008F1C_SQ_RSRC_IMG_2D;
1609	case PIPE_TEXTURE_2D_ARRAY:
1610		return nr_samples > 1 ? V_008F1C_SQ_RSRC_IMG_2D_MSAA_ARRAY :
1611					V_008F1C_SQ_RSRC_IMG_2D_ARRAY;
1612	case PIPE_TEXTURE_3D:
1613		return V_008F1C_SQ_RSRC_IMG_3D;
1614	case PIPE_TEXTURE_CUBE:
1615	case PIPE_TEXTURE_CUBE_ARRAY:
1616		return V_008F1C_SQ_RSRC_IMG_CUBE;
1617	}
1618}
1619
1620/*
1621 * Format support testing
1622 */
1623
1624static bool si_is_sampler_format_supported(struct pipe_screen *screen, enum pipe_format format)
1625{
1626	return si_translate_texformat(screen, format, util_format_description(format),
1627				      util_format_get_first_non_void_channel(format)) != ~0U;
1628}
1629
1630static uint32_t si_translate_buffer_dataformat(struct pipe_screen *screen,
1631					       const struct util_format_description *desc,
1632					       int first_non_void)
1633{
1634	unsigned type;
1635	int i;
1636
1637	if (desc->format == PIPE_FORMAT_R11G11B10_FLOAT)
1638		return V_008F0C_BUF_DATA_FORMAT_10_11_11;
1639
1640	assert(first_non_void >= 0);
1641	type = desc->channel[first_non_void].type;
1642
1643	if (type == UTIL_FORMAT_TYPE_FIXED)
1644		return V_008F0C_BUF_DATA_FORMAT_INVALID;
1645
1646	if (desc->nr_channels == 4 &&
1647	    desc->channel[0].size == 10 &&
1648	    desc->channel[1].size == 10 &&
1649	    desc->channel[2].size == 10 &&
1650	    desc->channel[3].size == 2)
1651		return V_008F0C_BUF_DATA_FORMAT_2_10_10_10;
1652
1653	/* See whether the components are of the same size. */
1654	for (i = 0; i < desc->nr_channels; i++) {
1655		if (desc->channel[first_non_void].size != desc->channel[i].size)
1656			return V_008F0C_BUF_DATA_FORMAT_INVALID;
1657	}
1658
1659	switch (desc->channel[first_non_void].size) {
1660	case 8:
1661		switch (desc->nr_channels) {
1662		case 1:
1663			return V_008F0C_BUF_DATA_FORMAT_8;
1664		case 2:
1665			return V_008F0C_BUF_DATA_FORMAT_8_8;
1666		case 3:
1667		case 4:
1668			return V_008F0C_BUF_DATA_FORMAT_8_8_8_8;
1669		}
1670		break;
1671	case 16:
1672		switch (desc->nr_channels) {
1673		case 1:
1674			return V_008F0C_BUF_DATA_FORMAT_16;
1675		case 2:
1676			return V_008F0C_BUF_DATA_FORMAT_16_16;
1677		case 3:
1678		case 4:
1679			return V_008F0C_BUF_DATA_FORMAT_16_16_16_16;
1680		}
1681		break;
1682	case 32:
1683		/* From the Southern Islands ISA documentation about MTBUF:
1684		 * 'Memory reads of data in memory that is 32 or 64 bits do not
1685		 * undergo any format conversion.'
1686		 */
1687		if (type != UTIL_FORMAT_TYPE_FLOAT &&
1688		    !desc->channel[first_non_void].pure_integer)
1689			return V_008F0C_BUF_DATA_FORMAT_INVALID;
1690
1691		switch (desc->nr_channels) {
1692		case 1:
1693			return V_008F0C_BUF_DATA_FORMAT_32;
1694		case 2:
1695			return V_008F0C_BUF_DATA_FORMAT_32_32;
1696		case 3:
1697			return V_008F0C_BUF_DATA_FORMAT_32_32_32;
1698		case 4:
1699			return V_008F0C_BUF_DATA_FORMAT_32_32_32_32;
1700		}
1701		break;
1702	}
1703
1704	return V_008F0C_BUF_DATA_FORMAT_INVALID;
1705}
1706
1707static uint32_t si_translate_buffer_numformat(struct pipe_screen *screen,
1708					      const struct util_format_description *desc,
1709					      int first_non_void)
1710{
1711	if (desc->format == PIPE_FORMAT_R11G11B10_FLOAT)
1712		return V_008F0C_BUF_NUM_FORMAT_FLOAT;
1713
1714	assert(first_non_void >= 0);
1715
1716	switch (desc->channel[first_non_void].type) {
1717	case UTIL_FORMAT_TYPE_SIGNED:
1718		if (desc->channel[first_non_void].normalized)
1719			return V_008F0C_BUF_NUM_FORMAT_SNORM;
1720		else if (desc->channel[first_non_void].pure_integer)
1721			return V_008F0C_BUF_NUM_FORMAT_SINT;
1722		else
1723			return V_008F0C_BUF_NUM_FORMAT_SSCALED;
1724		break;
1725	case UTIL_FORMAT_TYPE_UNSIGNED:
1726		if (desc->channel[first_non_void].normalized)
1727			return V_008F0C_BUF_NUM_FORMAT_UNORM;
1728		else if (desc->channel[first_non_void].pure_integer)
1729			return V_008F0C_BUF_NUM_FORMAT_UINT;
1730		else
1731			return V_008F0C_BUF_NUM_FORMAT_USCALED;
1732		break;
1733	case UTIL_FORMAT_TYPE_FLOAT:
1734	default:
1735		return V_008F0C_BUF_NUM_FORMAT_FLOAT;
1736	}
1737}
1738
1739static bool si_is_vertex_format_supported(struct pipe_screen *screen, enum pipe_format format)
1740{
1741	const struct util_format_description *desc;
1742	int first_non_void;
1743	unsigned data_format;
1744
1745	desc = util_format_description(format);
1746	first_non_void = util_format_get_first_non_void_channel(format);
1747	data_format = si_translate_buffer_dataformat(screen, desc, first_non_void);
1748	return data_format != V_008F0C_BUF_DATA_FORMAT_INVALID;
1749}
1750
1751static bool si_is_colorbuffer_format_supported(enum pipe_format format)
1752{
1753	return si_translate_colorformat(format) != V_028C70_COLOR_INVALID &&
1754		r600_translate_colorswap(format, false) != ~0U;
1755}
1756
1757static bool si_is_zs_format_supported(enum pipe_format format)
1758{
1759	return si_translate_dbformat(format) != V_028040_Z_INVALID;
1760}
1761
1762static boolean si_is_format_supported(struct pipe_screen *screen,
1763				      enum pipe_format format,
1764				      enum pipe_texture_target target,
1765				      unsigned sample_count,
1766				      unsigned usage)
1767{
1768	unsigned retval = 0;
1769
1770	if (target >= PIPE_MAX_TEXTURE_TYPES) {
1771		R600_ERR("r600: unsupported texture type %d\n", target);
1772		return false;
1773	}
1774
1775	if (!util_format_is_supported(format, usage))
1776		return false;
1777
1778	if (sample_count > 1) {
1779		if (!screen->get_param(screen, PIPE_CAP_TEXTURE_MULTISAMPLE))
1780			return false;
1781
1782		if (usage & PIPE_BIND_SHADER_IMAGE)
1783			return false;
1784
1785		switch (sample_count) {
1786		case 2:
1787		case 4:
1788		case 8:
1789			break;
1790		case 16:
1791			if (format == PIPE_FORMAT_NONE)
1792				return true;
1793			else
1794				return false;
1795		default:
1796			return false;
1797		}
1798	}
1799
1800	if (usage & (PIPE_BIND_SAMPLER_VIEW |
1801		     PIPE_BIND_SHADER_IMAGE)) {
1802		if (target == PIPE_BUFFER) {
1803			if (si_is_vertex_format_supported(screen, format))
1804				retval |= usage & (PIPE_BIND_SAMPLER_VIEW |
1805						   PIPE_BIND_SHADER_IMAGE);
1806		} else {
1807			if (si_is_sampler_format_supported(screen, format))
1808				retval |= usage & (PIPE_BIND_SAMPLER_VIEW |
1809						   PIPE_BIND_SHADER_IMAGE);
1810		}
1811	}
1812
1813	if ((usage & (PIPE_BIND_RENDER_TARGET |
1814		      PIPE_BIND_DISPLAY_TARGET |
1815		      PIPE_BIND_SCANOUT |
1816		      PIPE_BIND_SHARED |
1817		      PIPE_BIND_BLENDABLE)) &&
1818	    si_is_colorbuffer_format_supported(format)) {
1819		retval |= usage &
1820			  (PIPE_BIND_RENDER_TARGET |
1821			   PIPE_BIND_DISPLAY_TARGET |
1822			   PIPE_BIND_SCANOUT |
1823			   PIPE_BIND_SHARED);
1824		if (!util_format_is_pure_integer(format) &&
1825		    !util_format_is_depth_or_stencil(format))
1826			retval |= usage & PIPE_BIND_BLENDABLE;
1827	}
1828
1829	if ((usage & PIPE_BIND_DEPTH_STENCIL) &&
1830	    si_is_zs_format_supported(format)) {
1831		retval |= PIPE_BIND_DEPTH_STENCIL;
1832	}
1833
1834	if ((usage & PIPE_BIND_VERTEX_BUFFER) &&
1835	    si_is_vertex_format_supported(screen, format)) {
1836		retval |= PIPE_BIND_VERTEX_BUFFER;
1837	}
1838
1839	if (usage & PIPE_BIND_TRANSFER_READ)
1840		retval |= PIPE_BIND_TRANSFER_READ;
1841	if (usage & PIPE_BIND_TRANSFER_WRITE)
1842		retval |= PIPE_BIND_TRANSFER_WRITE;
1843
1844	if ((usage & PIPE_BIND_LINEAR) &&
1845	    !util_format_is_compressed(format) &&
1846	    !(usage & PIPE_BIND_DEPTH_STENCIL))
1847		retval |= PIPE_BIND_LINEAR;
1848
1849	return retval == usage;
1850}
1851
1852/*
1853 * framebuffer handling
1854 */
1855
1856static void si_choose_spi_color_formats(struct r600_surface *surf,
1857					unsigned format, unsigned swap,
1858					unsigned ntype, bool is_depth)
1859{
1860	/* Alpha is needed for alpha-to-coverage.
1861	 * Blending may be with or without alpha.
1862	 */
1863	unsigned normal = 0; /* most optimal, may not support blending or export alpha */
1864	unsigned alpha = 0; /* exports alpha, but may not support blending */
1865	unsigned blend = 0; /* supports blending, but may not export alpha */
1866	unsigned blend_alpha = 0; /* least optimal, supports blending and exports alpha */
1867
1868	/* Choose the SPI color formats. These are required values for Stoney/RB+.
1869	 * Other chips have multiple choices, though they are not necessarily better.
1870	 */
1871	switch (format) {
1872	case V_028C70_COLOR_5_6_5:
1873	case V_028C70_COLOR_1_5_5_5:
1874	case V_028C70_COLOR_5_5_5_1:
1875	case V_028C70_COLOR_4_4_4_4:
1876	case V_028C70_COLOR_10_11_11:
1877	case V_028C70_COLOR_11_11_10:
1878	case V_028C70_COLOR_8:
1879	case V_028C70_COLOR_8_8:
1880	case V_028C70_COLOR_8_8_8_8:
1881	case V_028C70_COLOR_10_10_10_2:
1882	case V_028C70_COLOR_2_10_10_10:
1883		if (ntype == V_028C70_NUMBER_UINT)
1884			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_UINT16_ABGR;
1885		else if (ntype == V_028C70_NUMBER_SINT)
1886			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_SINT16_ABGR;
1887		else
1888			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_FP16_ABGR;
1889		break;
1890
1891	case V_028C70_COLOR_16:
1892	case V_028C70_COLOR_16_16:
1893	case V_028C70_COLOR_16_16_16_16:
1894		if (ntype == V_028C70_NUMBER_UNORM ||
1895		    ntype == V_028C70_NUMBER_SNORM) {
1896			/* UNORM16 and SNORM16 don't support blending */
1897			if (ntype == V_028C70_NUMBER_UNORM)
1898				normal = alpha = V_028714_SPI_SHADER_UNORM16_ABGR;
1899			else
1900				normal = alpha = V_028714_SPI_SHADER_SNORM16_ABGR;
1901
1902			/* Use 32 bits per channel for blending. */
1903			if (format == V_028C70_COLOR_16) {
1904				if (swap == V_028C70_SWAP_STD) { /* R */
1905					blend = V_028714_SPI_SHADER_32_R;
1906					blend_alpha = V_028714_SPI_SHADER_32_AR;
1907				} else if (swap == V_028C70_SWAP_ALT_REV) /* A */
1908					blend = blend_alpha = V_028714_SPI_SHADER_32_AR;
1909				else
1910					assert(0);
1911			} else if (format == V_028C70_COLOR_16_16) {
1912				if (swap == V_028C70_SWAP_STD) { /* RG */
1913					blend = V_028714_SPI_SHADER_32_GR;
1914					blend_alpha = V_028714_SPI_SHADER_32_ABGR;
1915				} else if (swap == V_028C70_SWAP_ALT) /* RA */
1916					blend = blend_alpha = V_028714_SPI_SHADER_32_AR;
1917				else
1918					assert(0);
1919			} else /* 16_16_16_16 */
1920				blend = blend_alpha = V_028714_SPI_SHADER_32_ABGR;
1921		} else if (ntype == V_028C70_NUMBER_UINT)
1922			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_UINT16_ABGR;
1923		else if (ntype == V_028C70_NUMBER_SINT)
1924			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_SINT16_ABGR;
1925		else if (ntype == V_028C70_NUMBER_FLOAT)
1926			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_FP16_ABGR;
1927		else
1928			assert(0);
1929		break;
1930
1931	case V_028C70_COLOR_32:
1932		if (swap == V_028C70_SWAP_STD) { /* R */
1933			blend = normal = V_028714_SPI_SHADER_32_R;
1934			alpha = blend_alpha = V_028714_SPI_SHADER_32_AR;
1935		} else if (swap == V_028C70_SWAP_ALT_REV) /* A */
1936			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_AR;
1937		else
1938			assert(0);
1939		break;
1940
1941	case V_028C70_COLOR_32_32:
1942		if (swap == V_028C70_SWAP_STD) { /* RG */
1943			blend = normal = V_028714_SPI_SHADER_32_GR;
1944			alpha = blend_alpha = V_028714_SPI_SHADER_32_ABGR;
1945		} else if (swap == V_028C70_SWAP_ALT) /* RA */
1946			alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_AR;
1947		else
1948			assert(0);
1949		break;
1950
1951	case V_028C70_COLOR_32_32_32_32:
1952	case V_028C70_COLOR_8_24:
1953	case V_028C70_COLOR_24_8:
1954	case V_028C70_COLOR_X24_8_32_FLOAT:
1955		alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_ABGR;
1956		break;
1957
1958	default:
1959		assert(0);
1960		return;
1961	}
1962
1963	/* The DB->CB copy needs 32_ABGR. */
1964	if (is_depth)
1965		alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_ABGR;
1966
1967	surf->spi_shader_col_format = normal;
1968	surf->spi_shader_col_format_alpha = alpha;
1969	surf->spi_shader_col_format_blend = blend;
1970	surf->spi_shader_col_format_blend_alpha = blend_alpha;
1971}
1972
1973static void si_initialize_color_surface(struct si_context *sctx,
1974					struct r600_surface *surf)
1975{
1976	struct r600_texture *rtex = (struct r600_texture*)surf->base.texture;
1977	unsigned color_info, color_attrib, color_view;
1978	unsigned format, swap, ntype, endian;
1979	const struct util_format_description *desc;
1980	int i;
1981	unsigned blend_clamp = 0, blend_bypass = 0;
1982
1983	color_view = S_028C6C_SLICE_START(surf->base.u.tex.first_layer) |
1984		     S_028C6C_SLICE_MAX(surf->base.u.tex.last_layer);
1985
1986	desc = util_format_description(surf->base.format);
1987	for (i = 0; i < 4; i++) {
1988		if (desc->channel[i].type != UTIL_FORMAT_TYPE_VOID) {
1989			break;
1990		}
1991	}
1992	if (i == 4 || desc->channel[i].type == UTIL_FORMAT_TYPE_FLOAT) {
1993		ntype = V_028C70_NUMBER_FLOAT;
1994	} else {
1995		ntype = V_028C70_NUMBER_UNORM;
1996		if (desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB)
1997			ntype = V_028C70_NUMBER_SRGB;
1998		else if (desc->channel[i].type == UTIL_FORMAT_TYPE_SIGNED) {
1999			if (desc->channel[i].pure_integer) {
2000				ntype = V_028C70_NUMBER_SINT;
2001			} else {
2002				assert(desc->channel[i].normalized);
2003				ntype = V_028C70_NUMBER_SNORM;
2004			}
2005		} else if (desc->channel[i].type == UTIL_FORMAT_TYPE_UNSIGNED) {
2006			if (desc->channel[i].pure_integer) {
2007				ntype = V_028C70_NUMBER_UINT;
2008			} else {
2009				assert(desc->channel[i].normalized);
2010				ntype = V_028C70_NUMBER_UNORM;
2011			}
2012		}
2013	}
2014
2015	format = si_translate_colorformat(surf->base.format);
2016	if (format == V_028C70_COLOR_INVALID) {
2017		R600_ERR("Invalid CB format: %d, disabling CB.\n", surf->base.format);
2018	}
2019	assert(format != V_028C70_COLOR_INVALID);
2020	swap = r600_translate_colorswap(surf->base.format, false);
2021	endian = si_colorformat_endian_swap(format);
2022
2023	/* blend clamp should be set for all NORM/SRGB types */
2024	if (ntype == V_028C70_NUMBER_UNORM ||
2025	    ntype == V_028C70_NUMBER_SNORM ||
2026	    ntype == V_028C70_NUMBER_SRGB)
2027		blend_clamp = 1;
2028
2029	/* set blend bypass according to docs if SINT/UINT or
2030	   8/24 COLOR variants */
2031	if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
2032	    format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
2033	    format == V_028C70_COLOR_X24_8_32_FLOAT) {
2034		blend_clamp = 0;
2035		blend_bypass = 1;
2036	}
2037
2038	if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
2039	    (format == V_028C70_COLOR_8 ||
2040	     format == V_028C70_COLOR_8_8 ||
2041	     format == V_028C70_COLOR_8_8_8_8))
2042		surf->color_is_int8 = true;
2043
2044	color_info = S_028C70_FORMAT(format) |
2045		S_028C70_COMP_SWAP(swap) |
2046		S_028C70_BLEND_CLAMP(blend_clamp) |
2047		S_028C70_BLEND_BYPASS(blend_bypass) |
2048		S_028C70_NUMBER_TYPE(ntype) |
2049		S_028C70_ENDIAN(endian);
2050
2051	/* Intensity is implemented as Red, so treat it that way. */
2052	color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == PIPE_SWIZZLE_1 ||
2053						  util_format_is_intensity(surf->base.format));
2054
2055	if (rtex->resource.b.b.nr_samples > 1) {
2056		unsigned log_samples = util_logbase2(rtex->resource.b.b.nr_samples);
2057
2058		color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
2059				S_028C74_NUM_FRAGMENTS(log_samples);
2060
2061		if (rtex->fmask.size) {
2062			color_info |= S_028C70_COMPRESSION(1);
2063			unsigned fmask_bankh = util_logbase2(rtex->fmask.bank_height);
2064
2065			if (sctx->b.chip_class == SI) {
2066				/* due to a hw bug, FMASK_BANK_HEIGHT must be set on SI too */
2067				color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
2068			}
2069		}
2070	}
2071
2072	surf->cb_color_view = color_view;
2073	surf->cb_color_info = color_info;
2074	surf->cb_color_attrib = color_attrib;
2075
2076	if (sctx->b.chip_class >= VI) {
2077		unsigned max_uncompressed_block_size = 2;
2078
2079		if (rtex->surface.nsamples > 1) {
2080			if (rtex->surface.bpe == 1)
2081				max_uncompressed_block_size = 0;
2082			else if (rtex->surface.bpe == 2)
2083				max_uncompressed_block_size = 1;
2084		}
2085
2086		surf->cb_dcc_control = S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
2087		                       S_028C78_INDEPENDENT_64B_BLOCKS(1);
2088	}
2089
2090	/* This must be set for fast clear to work without FMASK. */
2091	if (!rtex->fmask.size && sctx->b.chip_class == SI) {
2092		unsigned bankh = util_logbase2(rtex->surface.bankh);
2093		surf->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
2094	}
2095
2096	/* Determine pixel shader export format */
2097	si_choose_spi_color_formats(surf, format, swap, ntype, rtex->is_depth);
2098
2099	surf->color_initialized = true;
2100}
2101
2102static void si_init_depth_surface(struct si_context *sctx,
2103				  struct r600_surface *surf)
2104{
2105	struct r600_texture *rtex = (struct r600_texture*)surf->base.texture;
2106	unsigned level = surf->base.u.tex.level;
2107	struct radeon_surf_level *levelinfo = &rtex->surface.level[level];
2108	unsigned format;
2109	uint32_t z_info, s_info, db_depth_info;
2110	uint64_t z_offs, s_offs;
2111	uint32_t db_htile_data_base, db_htile_surface;
2112
2113	format = si_translate_dbformat(rtex->resource.b.b.format);
2114
2115	if (format == V_028040_Z_INVALID) {
2116		R600_ERR("Invalid DB format: %d, disabling DB.\n", rtex->resource.b.b.format);
2117	}
2118	assert(format != V_028040_Z_INVALID);
2119
2120	s_offs = z_offs = rtex->resource.gpu_address;
2121	z_offs += rtex->surface.level[level].offset;
2122	s_offs += rtex->surface.stencil_level[level].offset;
2123
2124	db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(1);
2125
2126	z_info = S_028040_FORMAT(format);
2127	if (rtex->resource.b.b.nr_samples > 1) {
2128		z_info |= S_028040_NUM_SAMPLES(util_logbase2(rtex->resource.b.b.nr_samples));
2129	}
2130
2131	if (rtex->surface.flags & RADEON_SURF_SBUFFER)
2132		s_info = S_028044_FORMAT(V_028044_STENCIL_8);
2133	else
2134		s_info = S_028044_FORMAT(V_028044_STENCIL_INVALID);
2135
2136	if (sctx->b.chip_class >= CIK) {
2137		struct radeon_info *info = &sctx->screen->b.info;
2138		unsigned index = rtex->surface.tiling_index[level];
2139		unsigned stencil_index = rtex->surface.stencil_tiling_index[level];
2140		unsigned macro_index = rtex->surface.macro_tile_index;
2141		unsigned tile_mode = info->si_tile_mode_array[index];
2142		unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
2143		unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
2144
2145		db_depth_info |=
2146			S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
2147			S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
2148			S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
2149			S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
2150			S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
2151			S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
2152		z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
2153		s_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
2154	} else {
2155		unsigned tile_mode_index = si_tile_mode_index(rtex, level, false);
2156		z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
2157		tile_mode_index = si_tile_mode_index(rtex, level, true);
2158		s_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
2159	}
2160
2161	/* HiZ aka depth buffer htile */
2162	/* use htile only for first level */
2163	if (rtex->htile_buffer && !level) {
2164		z_info |= S_028040_TILE_SURFACE_ENABLE(1) |
2165			  S_028040_ALLOW_EXPCLEAR(1);
2166
2167		if (rtex->surface.flags & RADEON_SURF_SBUFFER) {
2168			/* Workaround: For a not yet understood reason, the
2169			 * combination of MSAA, fast stencil clear and stencil
2170			 * decompress messes with subsequent stencil buffer
2171			 * uses. Problem was reproduced on Verde, Bonaire,
2172			 * Tonga, and Carrizo.
2173			 *
2174			 * Disabling EXPCLEAR works around the problem.
2175			 *
2176			 * Check piglit's arb_texture_multisample-stencil-clear
2177			 * test if you want to try changing this.
2178			 */
2179			if (rtex->resource.b.b.nr_samples <= 1)
2180				s_info |= S_028044_ALLOW_EXPCLEAR(1);
2181		} else
2182			/* Use all of the htile_buffer for depth if there's no stencil. */
2183			s_info |= S_028044_TILE_STENCIL_DISABLE(1);
2184
2185		uint64_t va = rtex->htile_buffer->gpu_address;
2186		db_htile_data_base = va >> 8;
2187		db_htile_surface = S_028ABC_FULL_CACHE(1);
2188	} else {
2189		db_htile_data_base = 0;
2190		db_htile_surface = 0;
2191	}
2192
2193	assert(levelinfo->nblk_x % 8 == 0 && levelinfo->nblk_y % 8 == 0);
2194
2195	surf->db_depth_view = S_028008_SLICE_START(surf->base.u.tex.first_layer) |
2196			      S_028008_SLICE_MAX(surf->base.u.tex.last_layer);
2197	surf->db_htile_data_base = db_htile_data_base;
2198	surf->db_depth_info = db_depth_info;
2199	surf->db_z_info = z_info;
2200	surf->db_stencil_info = s_info;
2201	surf->db_depth_base = z_offs >> 8;
2202	surf->db_stencil_base = s_offs >> 8;
2203	surf->db_depth_size = S_028058_PITCH_TILE_MAX((levelinfo->nblk_x / 8) - 1) |
2204			      S_028058_HEIGHT_TILE_MAX((levelinfo->nblk_y / 8) - 1);
2205	surf->db_depth_slice = S_02805C_SLICE_TILE_MAX((levelinfo->nblk_x *
2206							levelinfo->nblk_y) / 64 - 1);
2207	surf->db_htile_surface = db_htile_surface;
2208
2209	surf->depth_initialized = true;
2210}
2211
2212void si_dec_framebuffer_counters(const struct pipe_framebuffer_state *state)
2213{
2214	for (int i = 0; i < state->nr_cbufs; ++i) {
2215		struct r600_surface *surf = NULL;
2216		struct r600_texture *rtex;
2217
2218		if (!state->cbufs[i])
2219			continue;
2220		surf = (struct r600_surface*)state->cbufs[i];
2221		rtex = (struct r600_texture*)surf->base.texture;
2222
2223		p_atomic_dec(&rtex->framebuffers_bound);
2224	}
2225}
2226
2227static void si_set_framebuffer_state(struct pipe_context *ctx,
2228				     const struct pipe_framebuffer_state *state)
2229{
2230	struct si_context *sctx = (struct si_context *)ctx;
2231	struct pipe_constant_buffer constbuf = {0};
2232	struct r600_surface *surf = NULL;
2233	struct r600_texture *rtex;
2234	bool old_cb0_is_integer = sctx->framebuffer.cb0_is_integer;
2235	bool old_any_dst_linear = sctx->framebuffer.any_dst_linear;
2236	unsigned old_nr_samples = sctx->framebuffer.nr_samples;
2237	int i;
2238
2239	/* Only flush TC when changing the framebuffer state, because
2240	 * the only client not using TC that can change textures is
2241	 * the framebuffer.
2242	 *
2243	 * Flush all CB and DB caches here because all buffers can be used
2244	 * for write by both TC (with shader image stores) and CB/DB.
2245	 */
2246	sctx->b.flags |= SI_CONTEXT_INV_VMEM_L1 |
2247			 SI_CONTEXT_INV_GLOBAL_L2 |
2248			 SI_CONTEXT_FLUSH_AND_INV_FRAMEBUFFER |
2249			 SI_CONTEXT_CS_PARTIAL_FLUSH;
2250
2251	/* Take the maximum of the old and new count. If the new count is lower,
2252	 * dirtying is needed to disable the unbound colorbuffers.
2253	 */
2254	sctx->framebuffer.dirty_cbufs |=
2255		(1 << MAX2(sctx->framebuffer.state.nr_cbufs, state->nr_cbufs)) - 1;
2256	sctx->framebuffer.dirty_zsbuf |= sctx->framebuffer.state.zsbuf != state->zsbuf;
2257
2258	si_dec_framebuffer_counters(&sctx->framebuffer.state);
2259	util_copy_framebuffer_state(&sctx->framebuffer.state, state);
2260
2261	sctx->framebuffer.spi_shader_col_format = 0;
2262	sctx->framebuffer.spi_shader_col_format_alpha = 0;
2263	sctx->framebuffer.spi_shader_col_format_blend = 0;
2264	sctx->framebuffer.spi_shader_col_format_blend_alpha = 0;
2265	sctx->framebuffer.color_is_int8 = 0;
2266
2267	sctx->framebuffer.compressed_cb_mask = 0;
2268	sctx->framebuffer.nr_samples = util_framebuffer_get_num_samples(state);
2269	sctx->framebuffer.log_samples = util_logbase2(sctx->framebuffer.nr_samples);
2270	sctx->framebuffer.cb0_is_integer = state->nr_cbufs && state->cbufs[0] &&
2271				  util_format_is_pure_integer(state->cbufs[0]->format);
2272	sctx->framebuffer.any_dst_linear = false;
2273
2274	if (sctx->framebuffer.cb0_is_integer != old_cb0_is_integer)
2275		si_mark_atom_dirty(sctx, &sctx->db_render_state);
2276
2277	for (i = 0; i < state->nr_cbufs; i++) {
2278		if (!state->cbufs[i])
2279			continue;
2280
2281		surf = (struct r600_surface*)state->cbufs[i];
2282		rtex = (struct r600_texture*)surf->base.texture;
2283
2284		if (!surf->color_initialized) {
2285			si_initialize_color_surface(sctx, surf);
2286		}
2287
2288		sctx->framebuffer.spi_shader_col_format |=
2289			surf->spi_shader_col_format << (i * 4);
2290		sctx->framebuffer.spi_shader_col_format_alpha |=
2291			surf->spi_shader_col_format_alpha << (i * 4);
2292		sctx->framebuffer.spi_shader_col_format_blend |=
2293			surf->spi_shader_col_format_blend << (i * 4);
2294		sctx->framebuffer.spi_shader_col_format_blend_alpha |=
2295			surf->spi_shader_col_format_blend_alpha << (i * 4);
2296
2297		if (surf->color_is_int8)
2298			sctx->framebuffer.color_is_int8 |= 1 << i;
2299
2300		if (rtex->fmask.size && rtex->cmask.size) {
2301			sctx->framebuffer.compressed_cb_mask |= 1 << i;
2302		}
2303
2304		if (surf->level_info->mode == RADEON_SURF_MODE_LINEAR_ALIGNED)
2305			sctx->framebuffer.any_dst_linear = true;
2306
2307		r600_context_add_resource_size(ctx, surf->base.texture);
2308
2309		p_atomic_inc(&rtex->framebuffers_bound);
2310	}
2311	/* Set the second SPI format for possible dual-src blending. */
2312	if (i == 1 && surf) {
2313		sctx->framebuffer.spi_shader_col_format |=
2314			surf->spi_shader_col_format << (i * 4);
2315		sctx->framebuffer.spi_shader_col_format_alpha |=
2316			surf->spi_shader_col_format_alpha << (i * 4);
2317		sctx->framebuffer.spi_shader_col_format_blend |=
2318			surf->spi_shader_col_format_blend << (i * 4);
2319		sctx->framebuffer.spi_shader_col_format_blend_alpha |=
2320			surf->spi_shader_col_format_blend_alpha << (i * 4);
2321	}
2322
2323	if (state->zsbuf) {
2324		surf = (struct r600_surface*)state->zsbuf;
2325
2326		if (!surf->depth_initialized) {
2327			si_init_depth_surface(sctx, surf);
2328		}
2329		r600_context_add_resource_size(ctx, surf->base.texture);
2330	}
2331
2332	si_update_poly_offset_state(sctx);
2333	si_mark_atom_dirty(sctx, &sctx->cb_render_state);
2334	si_mark_atom_dirty(sctx, &sctx->framebuffer.atom);
2335
2336	if (sctx->framebuffer.any_dst_linear != old_any_dst_linear)
2337		si_mark_atom_dirty(sctx, &sctx->msaa_config);
2338
2339	if (sctx->framebuffer.nr_samples != old_nr_samples) {
2340		si_mark_atom_dirty(sctx, &sctx->msaa_config);
2341		si_mark_atom_dirty(sctx, &sctx->db_render_state);
2342
2343		/* Set sample locations as fragment shader constants. */
2344		switch (sctx->framebuffer.nr_samples) {
2345		case 1:
2346			constbuf.user_buffer = sctx->b.sample_locations_1x;
2347			break;
2348		case 2:
2349			constbuf.user_buffer = sctx->b.sample_locations_2x;
2350			break;
2351		case 4:
2352			constbuf.user_buffer = sctx->b.sample_locations_4x;
2353			break;
2354		case 8:
2355			constbuf.user_buffer = sctx->b.sample_locations_8x;
2356			break;
2357		case 16:
2358			constbuf.user_buffer = sctx->b.sample_locations_16x;
2359			break;
2360		default:
2361			R600_ERR("Requested an invalid number of samples %i.\n",
2362				 sctx->framebuffer.nr_samples);
2363			assert(0);
2364		}
2365		constbuf.buffer_size = sctx->framebuffer.nr_samples * 2 * 4;
2366		si_set_rw_buffer(sctx, SI_PS_CONST_SAMPLE_POSITIONS, &constbuf);
2367
2368		/* Smoothing (only possible with nr_samples == 1) uses the same
2369		 * sample locations as the MSAA it simulates.
2370		 *
2371		 * Therefore, don't update the sample locations when
2372		 * transitioning from no AA to smoothing-equivalent AA, and
2373		 * vice versa.
2374		 */
2375		if ((sctx->framebuffer.nr_samples != 1 ||
2376		     old_nr_samples != SI_NUM_SMOOTH_AA_SAMPLES) &&
2377		    (sctx->framebuffer.nr_samples != SI_NUM_SMOOTH_AA_SAMPLES ||
2378		     old_nr_samples != 1))
2379			si_mark_atom_dirty(sctx, &sctx->msaa_sample_locs);
2380	}
2381
2382	sctx->need_check_render_feedback = true;
2383}
2384
2385static void si_emit_framebuffer_state(struct si_context *sctx, struct r600_atom *atom)
2386{
2387	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
2388	struct pipe_framebuffer_state *state = &sctx->framebuffer.state;
2389	unsigned i, nr_cbufs = state->nr_cbufs;
2390	struct r600_texture *tex = NULL;
2391	struct r600_surface *cb = NULL;
2392	unsigned cb_color_info = 0;
2393
2394	/* Colorbuffers. */
2395	for (i = 0; i < nr_cbufs; i++) {
2396		unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
2397		unsigned cb_color_base, cb_color_fmask, cb_color_attrib;
2398		unsigned cb_color_pitch, cb_color_slice, cb_color_fmask_slice;
2399
2400		if (!(sctx->framebuffer.dirty_cbufs & (1 << i)))
2401			continue;
2402
2403		cb = (struct r600_surface*)state->cbufs[i];
2404		if (!cb) {
2405			radeon_set_context_reg(cs, R_028C70_CB_COLOR0_INFO + i * 0x3C,
2406					       S_028C70_FORMAT(V_028C70_COLOR_INVALID));
2407			continue;
2408		}
2409
2410		tex = (struct r600_texture *)cb->base.texture;
2411		radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
2412				      &tex->resource, RADEON_USAGE_READWRITE,
2413				      tex->surface.nsamples > 1 ?
2414					      RADEON_PRIO_COLOR_BUFFER_MSAA :
2415					      RADEON_PRIO_COLOR_BUFFER);
2416
2417		if (tex->cmask_buffer && tex->cmask_buffer != &tex->resource) {
2418			radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
2419				tex->cmask_buffer, RADEON_USAGE_READWRITE,
2420				RADEON_PRIO_CMASK);
2421		}
2422
2423		/* Compute mutable surface parameters. */
2424		pitch_tile_max = cb->level_info->nblk_x / 8 - 1;
2425		slice_tile_max = cb->level_info->nblk_x *
2426				 cb->level_info->nblk_y / 64 - 1;
2427		tile_mode_index = si_tile_mode_index(tex, cb->base.u.tex.level, false);
2428
2429		cb_color_base = (tex->resource.gpu_address + cb->level_info->offset) >> 8;
2430		cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
2431		cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
2432		cb_color_attrib = cb->cb_color_attrib |
2433				  S_028C74_TILE_MODE_INDEX(tile_mode_index);
2434
2435		if (tex->fmask.size) {
2436			if (sctx->b.chip_class >= CIK)
2437				cb_color_pitch |= S_028C64_FMASK_TILE_MAX(tex->fmask.pitch_in_pixels / 8 - 1);
2438			cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tex->fmask.tile_mode_index);
2439			cb_color_fmask = (tex->resource.gpu_address + tex->fmask.offset) >> 8;
2440			cb_color_fmask_slice = S_028C88_TILE_MAX(tex->fmask.slice_tile_max);
2441		} else {
2442			/* This must be set for fast clear to work without FMASK. */
2443			if (sctx->b.chip_class >= CIK)
2444				cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
2445			cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
2446			cb_color_fmask = cb_color_base;
2447			cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
2448		}
2449
2450		cb_color_info = cb->cb_color_info | tex->cb_color_info;
2451
2452		if (tex->dcc_offset && cb->level_info->dcc_enabled) {
2453			bool is_msaa_resolve_dst = state->cbufs[0] &&
2454						   state->cbufs[0]->texture->nr_samples > 1 &&
2455						   state->cbufs[1] == &cb->base &&
2456						   state->cbufs[1]->texture->nr_samples <= 1;
2457
2458			if (!is_msaa_resolve_dst)
2459				cb_color_info |= S_028C70_DCC_ENABLE(1);
2460		}
2461
2462		radeon_set_context_reg_seq(cs, R_028C60_CB_COLOR0_BASE + i * 0x3C,
2463					   sctx->b.chip_class >= VI ? 14 : 13);
2464		radeon_emit(cs, cb_color_base);		/* R_028C60_CB_COLOR0_BASE */
2465		radeon_emit(cs, cb_color_pitch);	/* R_028C64_CB_COLOR0_PITCH */
2466		radeon_emit(cs, cb_color_slice);	/* R_028C68_CB_COLOR0_SLICE */
2467		radeon_emit(cs, cb->cb_color_view);	/* R_028C6C_CB_COLOR0_VIEW */
2468		radeon_emit(cs, cb_color_info);		/* R_028C70_CB_COLOR0_INFO */
2469		radeon_emit(cs, cb_color_attrib);	/* R_028C74_CB_COLOR0_ATTRIB */
2470		radeon_emit(cs, cb->cb_dcc_control);	/* R_028C78_CB_COLOR0_DCC_CONTROL */
2471		radeon_emit(cs, tex->cmask.base_address_reg);	/* R_028C7C_CB_COLOR0_CMASK */
2472		radeon_emit(cs, tex->cmask.slice_tile_max);	/* R_028C80_CB_COLOR0_CMASK_SLICE */
2473		radeon_emit(cs, cb_color_fmask);		/* R_028C84_CB_COLOR0_FMASK */
2474		radeon_emit(cs, cb_color_fmask_slice);		/* R_028C88_CB_COLOR0_FMASK_SLICE */
2475		radeon_emit(cs, tex->color_clear_value[0]);	/* R_028C8C_CB_COLOR0_CLEAR_WORD0 */
2476		radeon_emit(cs, tex->color_clear_value[1]);	/* R_028C90_CB_COLOR0_CLEAR_WORD1 */
2477
2478		if (sctx->b.chip_class >= VI) /* R_028C94_CB_COLOR0_DCC_BASE */
2479			radeon_emit(cs, (tex->resource.gpu_address +
2480					 tex->dcc_offset +
2481				         tex->surface.level[cb->base.u.tex.level].dcc_offset) >> 8);
2482	}
2483	/* set CB_COLOR1_INFO for possible dual-src blending */
2484	if (i == 1 && state->cbufs[0] &&
2485	    sctx->framebuffer.dirty_cbufs & (1 << 0)) {
2486		radeon_set_context_reg(cs, R_028C70_CB_COLOR0_INFO + 1 * 0x3C,
2487				       cb_color_info);
2488		i++;
2489	}
2490	for (; i < 8 ; i++)
2491		if (sctx->framebuffer.dirty_cbufs & (1 << i))
2492			radeon_set_context_reg(cs, R_028C70_CB_COLOR0_INFO + i * 0x3C, 0);
2493
2494	/* ZS buffer. */
2495	if (state->zsbuf && sctx->framebuffer.dirty_zsbuf) {
2496		struct r600_surface *zb = (struct r600_surface*)state->zsbuf;
2497		struct r600_texture *rtex = (struct r600_texture*)zb->base.texture;
2498
2499		radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
2500				      &rtex->resource, RADEON_USAGE_READWRITE,
2501				      zb->base.texture->nr_samples > 1 ?
2502					      RADEON_PRIO_DEPTH_BUFFER_MSAA :
2503					      RADEON_PRIO_DEPTH_BUFFER);
2504
2505		if (zb->db_htile_data_base) {
2506			radeon_add_to_buffer_list(&sctx->b, &sctx->b.gfx,
2507					      rtex->htile_buffer, RADEON_USAGE_READWRITE,
2508					      RADEON_PRIO_HTILE);
2509		}
2510
2511		radeon_set_context_reg(cs, R_028008_DB_DEPTH_VIEW, zb->db_depth_view);
2512		radeon_set_context_reg(cs, R_028014_DB_HTILE_DATA_BASE, zb->db_htile_data_base);
2513
2514		radeon_set_context_reg_seq(cs, R_02803C_DB_DEPTH_INFO, 9);
2515		radeon_emit(cs, zb->db_depth_info);	/* R_02803C_DB_DEPTH_INFO */
2516		radeon_emit(cs, zb->db_z_info |		/* R_028040_DB_Z_INFO */
2517			    S_028040_ZRANGE_PRECISION(rtex->depth_clear_value != 0));
2518		radeon_emit(cs, zb->db_stencil_info);	/* R_028044_DB_STENCIL_INFO */
2519		radeon_emit(cs, zb->db_depth_base);	/* R_028048_DB_Z_READ_BASE */
2520		radeon_emit(cs, zb->db_stencil_base);	/* R_02804C_DB_STENCIL_READ_BASE */
2521		radeon_emit(cs, zb->db_depth_base);	/* R_028050_DB_Z_WRITE_BASE */
2522		radeon_emit(cs, zb->db_stencil_base);	/* R_028054_DB_STENCIL_WRITE_BASE */
2523		radeon_emit(cs, zb->db_depth_size);	/* R_028058_DB_DEPTH_SIZE */
2524		radeon_emit(cs, zb->db_depth_slice);	/* R_02805C_DB_DEPTH_SLICE */
2525
2526		radeon_set_context_reg_seq(cs, R_028028_DB_STENCIL_CLEAR, 2);
2527		radeon_emit(cs, rtex->stencil_clear_value); /* R_028028_DB_STENCIL_CLEAR */
2528		radeon_emit(cs, fui(rtex->depth_clear_value)); /* R_02802C_DB_DEPTH_CLEAR */
2529
2530		radeon_set_context_reg(cs, R_028ABC_DB_HTILE_SURFACE, zb->db_htile_surface);
2531	} else if (sctx->framebuffer.dirty_zsbuf) {
2532		radeon_set_context_reg_seq(cs, R_028040_DB_Z_INFO, 2);
2533		radeon_emit(cs, S_028040_FORMAT(V_028040_Z_INVALID)); /* R_028040_DB_Z_INFO */
2534		radeon_emit(cs, S_028044_FORMAT(V_028044_STENCIL_INVALID)); /* R_028044_DB_STENCIL_INFO */
2535	}
2536
2537	/* Framebuffer dimensions. */
2538        /* PA_SC_WINDOW_SCISSOR_TL is set in si_init_config() */
2539	radeon_set_context_reg(cs, R_028208_PA_SC_WINDOW_SCISSOR_BR,
2540			       S_028208_BR_X(state->width) | S_028208_BR_Y(state->height));
2541
2542	sctx->framebuffer.dirty_cbufs = 0;
2543	sctx->framebuffer.dirty_zsbuf = false;
2544}
2545
2546static void si_emit_msaa_sample_locs(struct si_context *sctx,
2547				     struct r600_atom *atom)
2548{
2549	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
2550	unsigned nr_samples = sctx->framebuffer.nr_samples;
2551
2552	cayman_emit_msaa_sample_locs(cs, nr_samples > 1 ? nr_samples :
2553						SI_NUM_SMOOTH_AA_SAMPLES);
2554}
2555
2556static void si_emit_msaa_config(struct si_context *sctx, struct r600_atom *atom)
2557{
2558	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
2559	unsigned num_tile_pipes = sctx->screen->b.info.num_tile_pipes;
2560	/* 33% faster rendering to linear color buffers */
2561	bool dst_is_linear = sctx->framebuffer.any_dst_linear;
2562	unsigned sc_mode_cntl_1 =
2563		S_028A4C_WALK_SIZE(dst_is_linear) |
2564		S_028A4C_WALK_FENCE_ENABLE(!dst_is_linear) |
2565		S_028A4C_WALK_FENCE_SIZE(num_tile_pipes == 2 ? 2 : 3) |
2566		/* always 1: */
2567		S_028A4C_WALK_ALIGN8_PRIM_FITS_ST(1) |
2568		S_028A4C_SUPERTILE_WALK_ORDER_ENABLE(1) |
2569		S_028A4C_TILE_WALK_ORDER_ENABLE(1) |
2570		S_028A4C_MULTI_SHADER_ENGINE_PRIM_DISCARD_ENABLE(1) |
2571		S_028A4C_FORCE_EOV_CNTDWN_ENABLE(1) |
2572		S_028A4C_FORCE_EOV_REZ_ENABLE(1);
2573
2574	cayman_emit_msaa_config(cs, sctx->framebuffer.nr_samples,
2575				sctx->ps_iter_samples,
2576				sctx->smoothing_enabled ? SI_NUM_SMOOTH_AA_SAMPLES : 0,
2577				sc_mode_cntl_1);
2578}
2579
2580static void si_set_min_samples(struct pipe_context *ctx, unsigned min_samples)
2581{
2582	struct si_context *sctx = (struct si_context *)ctx;
2583
2584	if (sctx->ps_iter_samples == min_samples)
2585		return;
2586
2587	sctx->ps_iter_samples = min_samples;
2588
2589	if (sctx->framebuffer.nr_samples > 1)
2590		si_mark_atom_dirty(sctx, &sctx->msaa_config);
2591}
2592
2593/*
2594 * Samplers
2595 */
2596
2597/**
2598 * Build the sampler view descriptor for a buffer texture.
2599 * @param state 256-bit descriptor; only the high 128 bits are filled in
2600 */
2601void
2602si_make_buffer_descriptor(struct si_screen *screen, struct r600_resource *buf,
2603			  enum pipe_format format,
2604			  unsigned first_element, unsigned last_element,
2605			  uint32_t *state)
2606{
2607	const struct util_format_description *desc;
2608	int first_non_void;
2609	uint64_t va;
2610	unsigned stride;
2611	unsigned num_records;
2612	unsigned num_format, data_format;
2613
2614	desc = util_format_description(format);
2615	first_non_void = util_format_get_first_non_void_channel(format);
2616	stride = desc->block.bits / 8;
2617	va = buf->gpu_address + first_element * stride;
2618	num_format = si_translate_buffer_numformat(&screen->b.b, desc, first_non_void);
2619	data_format = si_translate_buffer_dataformat(&screen->b.b, desc, first_non_void);
2620
2621	num_records = last_element + 1 - first_element;
2622	num_records = MIN2(num_records, buf->b.b.width0 / stride);
2623
2624	if (screen->b.chip_class >= VI)
2625		num_records *= stride;
2626
2627	state[4] = va;
2628	state[5] = S_008F04_BASE_ADDRESS_HI(va >> 32) |
2629		   S_008F04_STRIDE(stride);
2630	state[6] = num_records;
2631	state[7] = S_008F0C_DST_SEL_X(si_map_swizzle(desc->swizzle[0])) |
2632		   S_008F0C_DST_SEL_Y(si_map_swizzle(desc->swizzle[1])) |
2633		   S_008F0C_DST_SEL_Z(si_map_swizzle(desc->swizzle[2])) |
2634		   S_008F0C_DST_SEL_W(si_map_swizzle(desc->swizzle[3])) |
2635		   S_008F0C_NUM_FORMAT(num_format) |
2636		   S_008F0C_DATA_FORMAT(data_format);
2637}
2638
2639/**
2640 * Build the sampler view descriptor for a texture.
2641 */
2642void
2643si_make_texture_descriptor(struct si_screen *screen,
2644			   struct r600_texture *tex,
2645			   bool sampler,
2646			   enum pipe_texture_target target,
2647			   enum pipe_format pipe_format,
2648			   const unsigned char state_swizzle[4],
2649			   unsigned first_level, unsigned last_level,
2650			   unsigned first_layer, unsigned last_layer,
2651			   unsigned width, unsigned height, unsigned depth,
2652			   uint32_t *state,
2653			   uint32_t *fmask_state)
2654{
2655	struct pipe_resource *res = &tex->resource.b.b;
2656	const struct util_format_description *desc;
2657	unsigned char swizzle[4];
2658	int first_non_void;
2659	unsigned num_format, data_format, type;
2660	uint64_t va;
2661
2662	desc = util_format_description(pipe_format);
2663
2664	if (desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS) {
2665		const unsigned char swizzle_xxxx[4] = {0, 0, 0, 0};
2666		const unsigned char swizzle_yyyy[4] = {1, 1, 1, 1};
2667
2668		switch (pipe_format) {
2669		case PIPE_FORMAT_S8_UINT_Z24_UNORM:
2670		case PIPE_FORMAT_X24S8_UINT:
2671		case PIPE_FORMAT_X32_S8X24_UINT:
2672		case PIPE_FORMAT_X8Z24_UNORM:
2673			util_format_compose_swizzles(swizzle_yyyy, state_swizzle, swizzle);
2674			break;
2675		default:
2676			util_format_compose_swizzles(swizzle_xxxx, state_swizzle, swizzle);
2677		}
2678	} else {
2679		util_format_compose_swizzles(desc->swizzle, state_swizzle, swizzle);
2680	}
2681
2682	first_non_void = util_format_get_first_non_void_channel(pipe_format);
2683
2684	switch (pipe_format) {
2685	case PIPE_FORMAT_S8_UINT_Z24_UNORM:
2686		num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
2687		break;
2688	default:
2689		if (first_non_void < 0) {
2690			if (util_format_is_compressed(pipe_format)) {
2691				switch (pipe_format) {
2692				case PIPE_FORMAT_DXT1_SRGB:
2693				case PIPE_FORMAT_DXT1_SRGBA:
2694				case PIPE_FORMAT_DXT3_SRGBA:
2695				case PIPE_FORMAT_DXT5_SRGBA:
2696				case PIPE_FORMAT_BPTC_SRGBA:
2697				case PIPE_FORMAT_ETC2_SRGB8:
2698				case PIPE_FORMAT_ETC2_SRGB8A1:
2699				case PIPE_FORMAT_ETC2_SRGBA8:
2700					num_format = V_008F14_IMG_NUM_FORMAT_SRGB;
2701					break;
2702				case PIPE_FORMAT_RGTC1_SNORM:
2703				case PIPE_FORMAT_LATC1_SNORM:
2704				case PIPE_FORMAT_RGTC2_SNORM:
2705				case PIPE_FORMAT_LATC2_SNORM:
2706				case PIPE_FORMAT_ETC2_R11_SNORM:
2707				case PIPE_FORMAT_ETC2_RG11_SNORM:
2708				/* implies float, so use SNORM/UNORM to determine
2709				   whether data is signed or not */
2710				case PIPE_FORMAT_BPTC_RGB_FLOAT:
2711					num_format = V_008F14_IMG_NUM_FORMAT_SNORM;
2712					break;
2713				default:
2714					num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
2715					break;
2716				}
2717			} else if (desc->layout == UTIL_FORMAT_LAYOUT_SUBSAMPLED) {
2718				num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
2719			} else {
2720				num_format = V_008F14_IMG_NUM_FORMAT_FLOAT;
2721			}
2722		} else if (desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
2723			num_format = V_008F14_IMG_NUM_FORMAT_SRGB;
2724		} else {
2725			num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
2726
2727			switch (desc->channel[first_non_void].type) {
2728			case UTIL_FORMAT_TYPE_FLOAT:
2729				num_format = V_008F14_IMG_NUM_FORMAT_FLOAT;
2730				break;
2731			case UTIL_FORMAT_TYPE_SIGNED:
2732				if (desc->channel[first_non_void].normalized)
2733					num_format = V_008F14_IMG_NUM_FORMAT_SNORM;
2734				else if (desc->channel[first_non_void].pure_integer)
2735					num_format = V_008F14_IMG_NUM_FORMAT_SINT;
2736				else
2737					num_format = V_008F14_IMG_NUM_FORMAT_SSCALED;
2738				break;
2739			case UTIL_FORMAT_TYPE_UNSIGNED:
2740				if (desc->channel[first_non_void].normalized)
2741					num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
2742				else if (desc->channel[first_non_void].pure_integer)
2743					num_format = V_008F14_IMG_NUM_FORMAT_UINT;
2744				else
2745					num_format = V_008F14_IMG_NUM_FORMAT_USCALED;
2746			}
2747		}
2748	}
2749
2750	data_format = si_translate_texformat(&screen->b.b, pipe_format, desc, first_non_void);
2751	if (data_format == ~0) {
2752		data_format = 0;
2753	}
2754
2755	if (!sampler &&
2756	    (res->target == PIPE_TEXTURE_CUBE ||
2757	     res->target == PIPE_TEXTURE_CUBE_ARRAY ||
2758	     res->target == PIPE_TEXTURE_3D)) {
2759		/* For the purpose of shader images, treat cube maps and 3D
2760		 * textures as 2D arrays. For 3D textures, the address
2761		 * calculations for mipmaps are different, so we rely on the
2762		 * caller to effectively disable mipmaps.
2763		 */
2764		type = V_008F1C_SQ_RSRC_IMG_2D_ARRAY;
2765
2766		assert(res->target != PIPE_TEXTURE_3D || (first_level == 0 && last_level == 0));
2767	} else {
2768		type = si_tex_dim(res->target, target, res->nr_samples);
2769	}
2770
2771	if (type == V_008F1C_SQ_RSRC_IMG_1D_ARRAY) {
2772	        height = 1;
2773		depth = res->array_size;
2774	} else if (type == V_008F1C_SQ_RSRC_IMG_2D_ARRAY ||
2775		   type == V_008F1C_SQ_RSRC_IMG_2D_MSAA_ARRAY) {
2776		if (sampler || res->target != PIPE_TEXTURE_3D)
2777			depth = res->array_size;
2778	} else if (type == V_008F1C_SQ_RSRC_IMG_CUBE)
2779		depth = res->array_size / 6;
2780
2781	state[0] = 0;
2782	state[1] = (S_008F14_DATA_FORMAT(data_format) |
2783		    S_008F14_NUM_FORMAT(num_format));
2784	state[2] = (S_008F18_WIDTH(width - 1) |
2785		    S_008F18_HEIGHT(height - 1));
2786	state[3] = (S_008F1C_DST_SEL_X(si_map_swizzle(swizzle[0])) |
2787		    S_008F1C_DST_SEL_Y(si_map_swizzle(swizzle[1])) |
2788		    S_008F1C_DST_SEL_Z(si_map_swizzle(swizzle[2])) |
2789		    S_008F1C_DST_SEL_W(si_map_swizzle(swizzle[3])) |
2790		    S_008F1C_BASE_LEVEL(res->nr_samples > 1 ?
2791					0 : first_level) |
2792		    S_008F1C_LAST_LEVEL(res->nr_samples > 1 ?
2793					util_logbase2(res->nr_samples) :
2794					last_level) |
2795		    S_008F1C_POW2_PAD(res->last_level > 0) |
2796		    S_008F1C_TYPE(type));
2797	state[4] = S_008F20_DEPTH(depth - 1);
2798	state[5] = (S_008F24_BASE_ARRAY(first_layer) |
2799		    S_008F24_LAST_ARRAY(last_layer));
2800	state[6] = 0;
2801	state[7] = 0;
2802
2803	if (tex->dcc_offset) {
2804		unsigned swap = r600_translate_colorswap(pipe_format, false);
2805
2806		state[6] = S_008F28_ALPHA_IS_ON_MSB(swap <= 1);
2807	} else {
2808		/* The last dword is unused by hw. The shader uses it to clear
2809		 * bits in the first dword of sampler state.
2810		 */
2811		if (screen->b.chip_class <= CIK && res->nr_samples <= 1) {
2812			if (first_level == last_level)
2813				state[7] = C_008F30_MAX_ANISO_RATIO;
2814			else
2815				state[7] = 0xffffffff;
2816		}
2817	}
2818
2819	/* Initialize the sampler view for FMASK. */
2820	if (tex->fmask.size) {
2821		uint32_t fmask_format;
2822
2823		va = tex->resource.gpu_address + tex->fmask.offset;
2824
2825		switch (res->nr_samples) {
2826		case 2:
2827			fmask_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S2_F2;
2828			break;
2829		case 4:
2830			fmask_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S4_F4;
2831			break;
2832		case 8:
2833			fmask_format = V_008F14_IMG_DATA_FORMAT_FMASK32_S8_F8;
2834			break;
2835		default:
2836			assert(0);
2837			fmask_format = V_008F14_IMG_DATA_FORMAT_INVALID;
2838		}
2839
2840		fmask_state[0] = va >> 8;
2841		fmask_state[1] = S_008F14_BASE_ADDRESS_HI(va >> 40) |
2842				 S_008F14_DATA_FORMAT(fmask_format) |
2843				 S_008F14_NUM_FORMAT(V_008F14_IMG_NUM_FORMAT_UINT);
2844		fmask_state[2] = S_008F18_WIDTH(width - 1) |
2845				 S_008F18_HEIGHT(height - 1);
2846		fmask_state[3] = S_008F1C_DST_SEL_X(V_008F1C_SQ_SEL_X) |
2847				 S_008F1C_DST_SEL_Y(V_008F1C_SQ_SEL_X) |
2848				 S_008F1C_DST_SEL_Z(V_008F1C_SQ_SEL_X) |
2849				 S_008F1C_DST_SEL_W(V_008F1C_SQ_SEL_X) |
2850				 S_008F1C_TILING_INDEX(tex->fmask.tile_mode_index) |
2851				 S_008F1C_TYPE(si_tex_dim(res->target, target, 0));
2852		fmask_state[4] = S_008F20_DEPTH(depth - 1) |
2853				 S_008F20_PITCH(tex->fmask.pitch_in_pixels - 1);
2854		fmask_state[5] = S_008F24_BASE_ARRAY(first_layer) |
2855				 S_008F24_LAST_ARRAY(last_layer);
2856		fmask_state[6] = 0;
2857		fmask_state[7] = 0;
2858	}
2859}
2860
2861/**
2862 * Create a sampler view.
2863 *
2864 * @param ctx		context
2865 * @param texture	texture
2866 * @param state		sampler view template
2867 * @param width0	width0 override (for compressed textures as int)
2868 * @param height0	height0 override (for compressed textures as int)
2869 * @param force_level   set the base address to the level (for compressed textures)
2870 */
2871struct pipe_sampler_view *
2872si_create_sampler_view_custom(struct pipe_context *ctx,
2873			      struct pipe_resource *texture,
2874			      const struct pipe_sampler_view *state,
2875			      unsigned width0, unsigned height0,
2876			      unsigned force_level)
2877{
2878	struct si_context *sctx = (struct si_context*)ctx;
2879	struct si_sampler_view *view = CALLOC_STRUCT(si_sampler_view);
2880	struct r600_texture *tmp = (struct r600_texture*)texture;
2881	unsigned base_level, first_level, last_level;
2882	unsigned char state_swizzle[4];
2883	unsigned height, depth, width;
2884	unsigned last_layer = state->u.tex.last_layer;
2885	enum pipe_format pipe_format;
2886	const struct radeon_surf_level *surflevel;
2887
2888	if (!view)
2889		return NULL;
2890
2891	/* initialize base object */
2892	view->base = *state;
2893	view->base.texture = NULL;
2894	view->base.reference.count = 1;
2895	view->base.context = ctx;
2896
2897	/* NULL resource, obey swizzle (only ZERO and ONE make sense). */
2898	if (!texture) {
2899		view->state[3] = S_008F1C_DST_SEL_X(si_map_swizzle(state->swizzle_r)) |
2900				 S_008F1C_DST_SEL_Y(si_map_swizzle(state->swizzle_g)) |
2901				 S_008F1C_DST_SEL_Z(si_map_swizzle(state->swizzle_b)) |
2902				 S_008F1C_DST_SEL_W(si_map_swizzle(state->swizzle_a)) |
2903				 S_008F1C_TYPE(V_008F1C_SQ_RSRC_IMG_1D);
2904		return &view->base;
2905	}
2906
2907	pipe_resource_reference(&view->base.texture, texture);
2908
2909	if (state->format == PIPE_FORMAT_X24S8_UINT ||
2910	    state->format == PIPE_FORMAT_S8X24_UINT ||
2911	    state->format == PIPE_FORMAT_X32_S8X24_UINT ||
2912	    state->format == PIPE_FORMAT_S8_UINT)
2913		view->is_stencil_sampler = true;
2914
2915	/* Buffer resource. */
2916	if (texture->target == PIPE_BUFFER) {
2917		si_make_buffer_descriptor(sctx->screen,
2918					  (struct r600_resource *)texture,
2919					  state->format,
2920					  state->u.buf.first_element,
2921					  state->u.buf.last_element,
2922					  view->state);
2923
2924		LIST_ADDTAIL(&view->list, &sctx->b.texture_buffers);
2925		return &view->base;
2926	}
2927
2928	state_swizzle[0] = state->swizzle_r;
2929	state_swizzle[1] = state->swizzle_g;
2930	state_swizzle[2] = state->swizzle_b;
2931	state_swizzle[3] = state->swizzle_a;
2932
2933	base_level = 0;
2934	first_level = state->u.tex.first_level;
2935	last_level = state->u.tex.last_level;
2936	width = width0;
2937	height = height0;
2938	depth = texture->depth0;
2939
2940	if (force_level) {
2941		assert(force_level == first_level &&
2942		       force_level == last_level);
2943		base_level = force_level;
2944		first_level = 0;
2945		last_level = 0;
2946		width = u_minify(width, force_level);
2947		height = u_minify(height, force_level);
2948		depth = u_minify(depth, force_level);
2949	}
2950
2951	/* This is not needed if state trackers set last_layer correctly. */
2952	if (state->target == PIPE_TEXTURE_1D ||
2953	    state->target == PIPE_TEXTURE_2D ||
2954	    state->target == PIPE_TEXTURE_RECT ||
2955	    state->target == PIPE_TEXTURE_CUBE)
2956		last_layer = state->u.tex.first_layer;
2957
2958	/* Texturing with separate depth and stencil. */
2959	pipe_format = state->format;
2960	surflevel = tmp->surface.level;
2961
2962	if (tmp->is_depth && !tmp->is_flushing_texture) {
2963		switch (pipe_format) {
2964		case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
2965			pipe_format = PIPE_FORMAT_Z32_FLOAT;
2966			break;
2967		case PIPE_FORMAT_X8Z24_UNORM:
2968		case PIPE_FORMAT_S8_UINT_Z24_UNORM:
2969			/* Z24 is always stored like this. */
2970			pipe_format = PIPE_FORMAT_Z24X8_UNORM;
2971			break;
2972		case PIPE_FORMAT_X24S8_UINT:
2973		case PIPE_FORMAT_S8X24_UINT:
2974		case PIPE_FORMAT_X32_S8X24_UINT:
2975			pipe_format = PIPE_FORMAT_S8_UINT;
2976			surflevel = tmp->surface.stencil_level;
2977			break;
2978		default:;
2979		}
2980	}
2981
2982	si_make_texture_descriptor(sctx->screen, tmp, true,
2983				   state->target, pipe_format, state_swizzle,
2984				   first_level, last_level,
2985				   state->u.tex.first_layer, last_layer,
2986				   width, height, depth,
2987				   view->state, view->fmask_state);
2988
2989	view->base_level_info = &surflevel[base_level];
2990	view->base_level = base_level;
2991	view->block_width = util_format_get_blockwidth(pipe_format);
2992	return &view->base;
2993}
2994
2995static struct pipe_sampler_view *
2996si_create_sampler_view(struct pipe_context *ctx,
2997		       struct pipe_resource *texture,
2998		       const struct pipe_sampler_view *state)
2999{
3000	return si_create_sampler_view_custom(ctx, texture, state,
3001					     texture ? texture->width0 : 0,
3002					     texture ? texture->height0 : 0, 0);
3003}
3004
3005static void si_sampler_view_destroy(struct pipe_context *ctx,
3006				    struct pipe_sampler_view *state)
3007{
3008	struct si_sampler_view *view = (struct si_sampler_view *)state;
3009
3010	if (state->texture && state->texture->target == PIPE_BUFFER)
3011		LIST_DELINIT(&view->list);
3012
3013	pipe_resource_reference(&state->texture, NULL);
3014	FREE(view);
3015}
3016
3017static bool wrap_mode_uses_border_color(unsigned wrap, bool linear_filter)
3018{
3019	return wrap == PIPE_TEX_WRAP_CLAMP_TO_BORDER ||
3020	       wrap == PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER ||
3021	       (linear_filter &&
3022	        (wrap == PIPE_TEX_WRAP_CLAMP ||
3023		 wrap == PIPE_TEX_WRAP_MIRROR_CLAMP));
3024}
3025
3026static bool sampler_state_needs_border_color(const struct pipe_sampler_state *state)
3027{
3028	bool linear_filter = state->min_img_filter != PIPE_TEX_FILTER_NEAREST ||
3029			     state->mag_img_filter != PIPE_TEX_FILTER_NEAREST;
3030
3031	return (state->border_color.ui[0] || state->border_color.ui[1] ||
3032		state->border_color.ui[2] || state->border_color.ui[3]) &&
3033	       (wrap_mode_uses_border_color(state->wrap_s, linear_filter) ||
3034		wrap_mode_uses_border_color(state->wrap_t, linear_filter) ||
3035		wrap_mode_uses_border_color(state->wrap_r, linear_filter));
3036}
3037
3038static void *si_create_sampler_state(struct pipe_context *ctx,
3039				     const struct pipe_sampler_state *state)
3040{
3041	struct si_context *sctx = (struct si_context *)ctx;
3042	struct r600_common_screen *rscreen = sctx->b.screen;
3043	struct si_sampler_state *rstate = CALLOC_STRUCT(si_sampler_state);
3044	unsigned border_color_type, border_color_index = 0;
3045	unsigned max_aniso = rscreen->force_aniso >= 0 ? rscreen->force_aniso
3046						       : state->max_anisotropy;
3047	unsigned max_aniso_ratio = r600_tex_aniso_filter(max_aniso);
3048
3049	if (!rstate) {
3050		return NULL;
3051	}
3052
3053	if (!sampler_state_needs_border_color(state))
3054		border_color_type = V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
3055	else if (state->border_color.f[0] == 0 &&
3056		 state->border_color.f[1] == 0 &&
3057		 state->border_color.f[2] == 0 &&
3058		 state->border_color.f[3] == 0)
3059		border_color_type = V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
3060	else if (state->border_color.f[0] == 0 &&
3061		 state->border_color.f[1] == 0 &&
3062		 state->border_color.f[2] == 0 &&
3063		 state->border_color.f[3] == 1)
3064		border_color_type = V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
3065	else if (state->border_color.f[0] == 1 &&
3066		 state->border_color.f[1] == 1 &&
3067		 state->border_color.f[2] == 1 &&
3068		 state->border_color.f[3] == 1)
3069		border_color_type = V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
3070	else {
3071		int i;
3072
3073		border_color_type = V_008F3C_SQ_TEX_BORDER_COLOR_REGISTER;
3074
3075		/* Check if the border has been uploaded already. */
3076		for (i = 0; i < sctx->border_color_count; i++)
3077			if (memcmp(&sctx->border_color_table[i], &state->border_color,
3078				   sizeof(state->border_color)) == 0)
3079				break;
3080
3081		if (i >= SI_MAX_BORDER_COLORS) {
3082			/* Getting 4096 unique border colors is very unlikely. */
3083			fprintf(stderr, "radeonsi: The border color table is full. "
3084				"Any new border colors will be just black. "
3085				"Please file a bug.\n");
3086			border_color_type = V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
3087		} else {
3088			if (i == sctx->border_color_count) {
3089				/* Upload a new border color. */
3090				memcpy(&sctx->border_color_table[i], &state->border_color,
3091				       sizeof(state->border_color));
3092				util_memcpy_cpu_to_le32(&sctx->border_color_map[i],
3093							&state->border_color,
3094							sizeof(state->border_color));
3095				sctx->border_color_count++;
3096			}
3097
3098			border_color_index = i;
3099		}
3100	}
3101
3102	rstate->val[0] = (S_008F30_CLAMP_X(si_tex_wrap(state->wrap_s)) |
3103			  S_008F30_CLAMP_Y(si_tex_wrap(state->wrap_t)) |
3104			  S_008F30_CLAMP_Z(si_tex_wrap(state->wrap_r)) |
3105			  S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
3106			  S_008F30_DEPTH_COMPARE_FUNC(si_tex_compare(state->compare_func)) |
3107			  S_008F30_FORCE_UNNORMALIZED(!state->normalized_coords) |
3108			  S_008F30_DISABLE_CUBE_WRAP(!state->seamless_cube_map) |
3109			  S_008F30_COMPAT_MODE(sctx->b.chip_class >= VI));
3110	rstate->val[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(state->min_lod, 0, 15), 8)) |
3111			  S_008F34_MAX_LOD(S_FIXED(CLAMP(state->max_lod, 0, 15), 8)));
3112	rstate->val[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(state->lod_bias, -16, 16), 8)) |
3113			  S_008F38_XY_MAG_FILTER(eg_tex_filter(state->mag_img_filter, max_aniso)) |
3114			  S_008F38_XY_MIN_FILTER(eg_tex_filter(state->min_img_filter, max_aniso)) |
3115			  S_008F38_MIP_FILTER(si_tex_mipfilter(state->min_mip_filter)) |
3116			  S_008F38_MIP_POINT_PRECLAMP(1) |
3117			  S_008F38_DISABLE_LSB_CEIL(1) |
3118			  S_008F38_FILTER_PREC_FIX(1) |
3119			  S_008F38_ANISO_OVERRIDE(sctx->b.chip_class >= VI));
3120	rstate->val[3] = S_008F3C_BORDER_COLOR_PTR(border_color_index) |
3121			 S_008F3C_BORDER_COLOR_TYPE(border_color_type);
3122	return rstate;
3123}
3124
3125static void si_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
3126{
3127	struct si_context *sctx = (struct si_context *)ctx;
3128
3129	if (sctx->sample_mask.sample_mask == (uint16_t)sample_mask)
3130		return;
3131
3132	sctx->sample_mask.sample_mask = sample_mask;
3133	si_mark_atom_dirty(sctx, &sctx->sample_mask.atom);
3134}
3135
3136static void si_emit_sample_mask(struct si_context *sctx, struct r600_atom *atom)
3137{
3138	struct radeon_winsys_cs *cs = sctx->b.gfx.cs;
3139	unsigned mask = sctx->sample_mask.sample_mask;
3140
3141	radeon_set_context_reg_seq(cs, R_028C38_PA_SC_AA_MASK_X0Y0_X1Y0, 2);
3142	radeon_emit(cs, mask | (mask << 16));
3143	radeon_emit(cs, mask | (mask << 16));
3144}
3145
3146static void si_delete_sampler_state(struct pipe_context *ctx, void *state)
3147{
3148	free(state);
3149}
3150
3151/*
3152 * Vertex elements & buffers
3153 */
3154
3155static void *si_create_vertex_elements(struct pipe_context *ctx,
3156				       unsigned count,
3157				       const struct pipe_vertex_element *elements)
3158{
3159	struct si_vertex_element *v = CALLOC_STRUCT(si_vertex_element);
3160	int i;
3161
3162	assert(count <= SI_MAX_ATTRIBS);
3163	if (!v)
3164		return NULL;
3165
3166	v->count = count;
3167	for (i = 0; i < count; ++i) {
3168		const struct util_format_description *desc;
3169		unsigned data_format, num_format;
3170		int first_non_void;
3171
3172		desc = util_format_description(elements[i].src_format);
3173		first_non_void = util_format_get_first_non_void_channel(elements[i].src_format);
3174		data_format = si_translate_buffer_dataformat(ctx->screen, desc, first_non_void);
3175		num_format = si_translate_buffer_numformat(ctx->screen, desc, first_non_void);
3176
3177		v->rsrc_word3[i] = S_008F0C_DST_SEL_X(si_map_swizzle(desc->swizzle[0])) |
3178				   S_008F0C_DST_SEL_Y(si_map_swizzle(desc->swizzle[1])) |
3179				   S_008F0C_DST_SEL_Z(si_map_swizzle(desc->swizzle[2])) |
3180				   S_008F0C_DST_SEL_W(si_map_swizzle(desc->swizzle[3])) |
3181				   S_008F0C_NUM_FORMAT(num_format) |
3182				   S_008F0C_DATA_FORMAT(data_format);
3183		v->format_size[i] = desc->block.bits / 8;
3184	}
3185	memcpy(v->elements, elements, sizeof(struct pipe_vertex_element) * count);
3186
3187	return v;
3188}
3189
3190static void si_bind_vertex_elements(struct pipe_context *ctx, void *state)
3191{
3192	struct si_context *sctx = (struct si_context *)ctx;
3193	struct si_vertex_element *v = (struct si_vertex_element*)state;
3194
3195	sctx->vertex_elements = v;
3196	sctx->vertex_buffers_dirty = true;
3197}
3198
3199static void si_delete_vertex_element(struct pipe_context *ctx, void *state)
3200{
3201	struct si_context *sctx = (struct si_context *)ctx;
3202
3203	if (sctx->vertex_elements == state)
3204		sctx->vertex_elements = NULL;
3205	FREE(state);
3206}
3207
3208static void si_set_vertex_buffers(struct pipe_context *ctx,
3209				  unsigned start_slot, unsigned count,
3210				  const struct pipe_vertex_buffer *buffers)
3211{
3212	struct si_context *sctx = (struct si_context *)ctx;
3213	struct pipe_vertex_buffer *dst = sctx->vertex_buffer + start_slot;
3214	int i;
3215
3216	assert(start_slot + count <= ARRAY_SIZE(sctx->vertex_buffer));
3217
3218	if (buffers) {
3219		for (i = 0; i < count; i++) {
3220			const struct pipe_vertex_buffer *src = buffers + i;
3221			struct pipe_vertex_buffer *dsti = dst + i;
3222
3223			pipe_resource_reference(&dsti->buffer, src->buffer);
3224			dsti->buffer_offset = src->buffer_offset;
3225			dsti->stride = src->stride;
3226			r600_context_add_resource_size(ctx, src->buffer);
3227		}
3228	} else {
3229		for (i = 0; i < count; i++) {
3230			pipe_resource_reference(&dst[i].buffer, NULL);
3231		}
3232	}
3233	sctx->vertex_buffers_dirty = true;
3234}
3235
3236static void si_set_index_buffer(struct pipe_context *ctx,
3237				const struct pipe_index_buffer *ib)
3238{
3239	struct si_context *sctx = (struct si_context *)ctx;
3240
3241	if (ib) {
3242		pipe_resource_reference(&sctx->index_buffer.buffer, ib->buffer);
3243	        memcpy(&sctx->index_buffer, ib, sizeof(*ib));
3244		r600_context_add_resource_size(ctx, ib->buffer);
3245	} else {
3246		pipe_resource_reference(&sctx->index_buffer.buffer, NULL);
3247	}
3248}
3249
3250/*
3251 * Misc
3252 */
3253
3254static void si_set_tess_state(struct pipe_context *ctx,
3255			      const float default_outer_level[4],
3256			      const float default_inner_level[2])
3257{
3258	struct si_context *sctx = (struct si_context *)ctx;
3259	struct pipe_constant_buffer cb;
3260	float array[8];
3261
3262	memcpy(array, default_outer_level, sizeof(float) * 4);
3263	memcpy(array+4, default_inner_level, sizeof(float) * 2);
3264
3265	cb.buffer = NULL;
3266	cb.user_buffer = NULL;
3267	cb.buffer_size = sizeof(array);
3268
3269	si_upload_const_buffer(sctx, (struct r600_resource**)&cb.buffer,
3270			       (void*)array, sizeof(array),
3271			       &cb.buffer_offset);
3272
3273	si_set_rw_buffer(sctx, SI_HS_CONST_DEFAULT_TESS_LEVELS, &cb);
3274	pipe_resource_reference(&cb.buffer, NULL);
3275}
3276
3277static void si_texture_barrier(struct pipe_context *ctx)
3278{
3279	struct si_context *sctx = (struct si_context *)ctx;
3280
3281	sctx->b.flags |= SI_CONTEXT_INV_VMEM_L1 |
3282			 SI_CONTEXT_INV_GLOBAL_L2 |
3283			 SI_CONTEXT_FLUSH_AND_INV_CB |
3284			 SI_CONTEXT_CS_PARTIAL_FLUSH;
3285}
3286
3287static void si_memory_barrier(struct pipe_context *ctx, unsigned flags)
3288{
3289	struct si_context *sctx = (struct si_context *)ctx;
3290
3291	/* Subsequent commands must wait for all shader invocations to
3292	 * complete. */
3293	sctx->b.flags |= SI_CONTEXT_PS_PARTIAL_FLUSH |
3294	                 SI_CONTEXT_CS_PARTIAL_FLUSH;
3295
3296	if (flags & PIPE_BARRIER_CONSTANT_BUFFER)
3297		sctx->b.flags |= SI_CONTEXT_INV_SMEM_L1 |
3298				 SI_CONTEXT_INV_VMEM_L1;
3299
3300	if (flags & (PIPE_BARRIER_VERTEX_BUFFER |
3301		     PIPE_BARRIER_SHADER_BUFFER |
3302		     PIPE_BARRIER_TEXTURE |
3303		     PIPE_BARRIER_IMAGE |
3304		     PIPE_BARRIER_STREAMOUT_BUFFER |
3305		     PIPE_BARRIER_GLOBAL_BUFFER)) {
3306		/* As far as I can tell, L1 contents are written back to L2
3307		 * automatically at end of shader, but the contents of other
3308		 * L1 caches might still be stale. */
3309		sctx->b.flags |= SI_CONTEXT_INV_VMEM_L1;
3310	}
3311
3312	if (flags & PIPE_BARRIER_INDEX_BUFFER) {
3313		sctx->b.flags |= SI_CONTEXT_INV_VMEM_L1;
3314
3315		/* Indices are read through TC L2 since VI. */
3316		if (sctx->screen->b.chip_class <= CIK)
3317			sctx->b.flags |= SI_CONTEXT_INV_GLOBAL_L2;
3318	}
3319
3320	if (flags & PIPE_BARRIER_FRAMEBUFFER)
3321		sctx->b.flags |= SI_CONTEXT_FLUSH_AND_INV_FRAMEBUFFER;
3322
3323	if (flags & (PIPE_BARRIER_MAPPED_BUFFER |
3324		     PIPE_BARRIER_FRAMEBUFFER |
3325		     PIPE_BARRIER_INDIRECT_BUFFER)) {
3326		/* Not sure if INV_GLOBAL_L2 is the best thing here.
3327		 *
3328		 * We need to make sure that TC L1 & L2 are written back to
3329		 * memory, because neither CPU accesses nor CB fetches consider
3330		 * TC, but there's no need to invalidate any TC cache lines. */
3331		sctx->b.flags |= SI_CONTEXT_INV_GLOBAL_L2;
3332	}
3333}
3334
3335static void *si_create_blend_custom(struct si_context *sctx, unsigned mode)
3336{
3337	struct pipe_blend_state blend;
3338
3339	memset(&blend, 0, sizeof(blend));
3340	blend.independent_blend_enable = true;
3341	blend.rt[0].colormask = 0xf;
3342	return si_create_blend_state_mode(&sctx->b.b, &blend, mode);
3343}
3344
3345static void si_need_gfx_cs_space(struct pipe_context *ctx, unsigned num_dw,
3346				 bool include_draw_vbo)
3347{
3348	si_need_cs_space((struct si_context*)ctx);
3349}
3350
3351static void si_init_config(struct si_context *sctx);
3352
3353void si_init_state_functions(struct si_context *sctx)
3354{
3355	si_init_external_atom(sctx, &sctx->b.render_cond_atom, &sctx->atoms.s.render_cond);
3356	si_init_external_atom(sctx, &sctx->b.streamout.begin_atom, &sctx->atoms.s.streamout_begin);
3357	si_init_external_atom(sctx, &sctx->b.streamout.enable_atom, &sctx->atoms.s.streamout_enable);
3358	si_init_external_atom(sctx, &sctx->b.scissors.atom, &sctx->atoms.s.scissors);
3359	si_init_external_atom(sctx, &sctx->b.viewports.atom, &sctx->atoms.s.viewports);
3360
3361	si_init_atom(sctx, &sctx->cache_flush, &sctx->atoms.s.cache_flush, si_emit_cache_flush);
3362	si_init_atom(sctx, &sctx->framebuffer.atom, &sctx->atoms.s.framebuffer, si_emit_framebuffer_state);
3363	si_init_atom(sctx, &sctx->msaa_sample_locs, &sctx->atoms.s.msaa_sample_locs, si_emit_msaa_sample_locs);
3364	si_init_atom(sctx, &sctx->db_render_state, &sctx->atoms.s.db_render_state, si_emit_db_render_state);
3365	si_init_atom(sctx, &sctx->msaa_config, &sctx->atoms.s.msaa_config, si_emit_msaa_config);
3366	si_init_atom(sctx, &sctx->sample_mask.atom, &sctx->atoms.s.sample_mask, si_emit_sample_mask);
3367	si_init_atom(sctx, &sctx->cb_render_state, &sctx->atoms.s.cb_render_state, si_emit_cb_render_state);
3368	si_init_atom(sctx, &sctx->blend_color.atom, &sctx->atoms.s.blend_color, si_emit_blend_color);
3369	si_init_atom(sctx, &sctx->clip_regs, &sctx->atoms.s.clip_regs, si_emit_clip_regs);
3370	si_init_atom(sctx, &sctx->clip_state.atom, &sctx->atoms.s.clip_state, si_emit_clip_state);
3371	si_init_atom(sctx, &sctx->stencil_ref.atom, &sctx->atoms.s.stencil_ref, si_emit_stencil_ref);
3372
3373	sctx->b.b.create_blend_state = si_create_blend_state;
3374	sctx->b.b.bind_blend_state = si_bind_blend_state;
3375	sctx->b.b.delete_blend_state = si_delete_blend_state;
3376	sctx->b.b.set_blend_color = si_set_blend_color;
3377
3378	sctx->b.b.create_rasterizer_state = si_create_rs_state;
3379	sctx->b.b.bind_rasterizer_state = si_bind_rs_state;
3380	sctx->b.b.delete_rasterizer_state = si_delete_rs_state;
3381
3382	sctx->b.b.create_depth_stencil_alpha_state = si_create_dsa_state;
3383	sctx->b.b.bind_depth_stencil_alpha_state = si_bind_dsa_state;
3384	sctx->b.b.delete_depth_stencil_alpha_state = si_delete_dsa_state;
3385
3386	sctx->custom_dsa_flush = si_create_db_flush_dsa(sctx);
3387	sctx->custom_blend_resolve = si_create_blend_custom(sctx, V_028808_CB_RESOLVE);
3388	sctx->custom_blend_decompress = si_create_blend_custom(sctx, V_028808_CB_FMASK_DECOMPRESS);
3389	sctx->custom_blend_fastclear = si_create_blend_custom(sctx, V_028808_CB_ELIMINATE_FAST_CLEAR);
3390	sctx->custom_blend_dcc_decompress = si_create_blend_custom(sctx, V_028808_CB_DCC_DECOMPRESS);
3391
3392	sctx->b.b.set_clip_state = si_set_clip_state;
3393	sctx->b.b.set_stencil_ref = si_set_stencil_ref;
3394
3395	sctx->b.b.set_framebuffer_state = si_set_framebuffer_state;
3396	sctx->b.b.get_sample_position = cayman_get_sample_position;
3397
3398	sctx->b.b.create_sampler_state = si_create_sampler_state;
3399	sctx->b.b.delete_sampler_state = si_delete_sampler_state;
3400
3401	sctx->b.b.create_sampler_view = si_create_sampler_view;
3402	sctx->b.b.sampler_view_destroy = si_sampler_view_destroy;
3403
3404	sctx->b.b.set_sample_mask = si_set_sample_mask;
3405
3406	sctx->b.b.create_vertex_elements_state = si_create_vertex_elements;
3407	sctx->b.b.bind_vertex_elements_state = si_bind_vertex_elements;
3408	sctx->b.b.delete_vertex_elements_state = si_delete_vertex_element;
3409	sctx->b.b.set_vertex_buffers = si_set_vertex_buffers;
3410	sctx->b.b.set_index_buffer = si_set_index_buffer;
3411
3412	sctx->b.b.texture_barrier = si_texture_barrier;
3413	sctx->b.b.memory_barrier = si_memory_barrier;
3414	sctx->b.b.set_min_samples = si_set_min_samples;
3415	sctx->b.b.set_tess_state = si_set_tess_state;
3416
3417	sctx->b.b.set_active_query_state = si_set_active_query_state;
3418	sctx->b.set_occlusion_query_state = si_set_occlusion_query_state;
3419	sctx->b.need_gfx_cs_space = si_need_gfx_cs_space;
3420
3421	sctx->b.b.draw_vbo = si_draw_vbo;
3422
3423	si_init_config(sctx);
3424}
3425
3426static uint32_t si_get_bo_metadata_word1(struct r600_common_screen *rscreen)
3427{
3428	return (ATI_VENDOR_ID << 16) | rscreen->info.pci_id;
3429}
3430
3431static void si_query_opaque_metadata(struct r600_common_screen *rscreen,
3432				     struct r600_texture *rtex,
3433			             struct radeon_bo_metadata *md)
3434{
3435	struct si_screen *sscreen = (struct si_screen*)rscreen;
3436	struct pipe_resource *res = &rtex->resource.b.b;
3437	static const unsigned char swizzle[] = {
3438		PIPE_SWIZZLE_X,
3439		PIPE_SWIZZLE_Y,
3440		PIPE_SWIZZLE_Z,
3441		PIPE_SWIZZLE_W
3442	};
3443	uint32_t desc[8], i;
3444	bool is_array = util_resource_is_array_texture(res);
3445
3446	/* DRM 2.x.x doesn't support this. */
3447	if (rscreen->info.drm_major != 3)
3448		return;
3449
3450	assert(rtex->fmask.size == 0);
3451
3452	/* Metadata image format format version 1:
3453	 * [0] = 1 (metadata format identifier)
3454	 * [1] = (VENDOR_ID << 16) | PCI_ID
3455	 * [2:9] = image descriptor for the whole resource
3456	 *         [2] is always 0, because the base address is cleared
3457	 *         [9] is the DCC offset bits [39:8] from the beginning of
3458	 *             the buffer
3459	 * [10:10+LAST_LEVEL] = mipmap level offset bits [39:8] for each level
3460	 */
3461
3462	md->metadata[0] = 1; /* metadata image format version 1 */
3463
3464	/* TILE_MODE_INDEX is ambiguous without a PCI ID. */
3465	md->metadata[1] = si_get_bo_metadata_word1(rscreen);
3466
3467	si_make_texture_descriptor(sscreen, rtex, true,
3468				   res->target, res->format,
3469				   swizzle, 0, res->last_level, 0,
3470				   is_array ? res->array_size - 1 : 0,
3471				   res->width0, res->height0, res->depth0,
3472				   desc, NULL);
3473
3474	si_set_mutable_tex_desc_fields(rtex, &rtex->surface.level[0], 0, 0,
3475				       rtex->surface.blk_w, false, desc);
3476
3477	/* Clear the base address and set the relative DCC offset. */
3478	desc[0] = 0;
3479	desc[1] &= C_008F14_BASE_ADDRESS_HI;
3480	desc[7] = rtex->dcc_offset >> 8;
3481
3482	/* Dwords [2:9] contain the image descriptor. */
3483	memcpy(&md->metadata[2], desc, sizeof(desc));
3484
3485	/* Dwords [10:..] contain the mipmap level offsets. */
3486	for (i = 0; i <= res->last_level; i++)
3487		md->metadata[10+i] = rtex->surface.level[i].offset >> 8;
3488
3489	md->size_metadata = (11 + res->last_level) * 4;
3490}
3491
3492static void si_apply_opaque_metadata(struct r600_common_screen *rscreen,
3493				     struct r600_texture *rtex,
3494			             struct radeon_bo_metadata *md)
3495{
3496	uint32_t *desc = &md->metadata[2];
3497
3498	if (rscreen->chip_class < VI)
3499		return;
3500
3501	/* Return if DCC is enabled. The texture should be set up with it
3502	 * already.
3503	 */
3504	if (md->size_metadata >= 11 * 4 &&
3505	    md->metadata[0] != 0 &&
3506	    md->metadata[1] == si_get_bo_metadata_word1(rscreen) &&
3507	    G_008F28_COMPRESSION_EN(desc[6])) {
3508		assert(rtex->dcc_offset == ((uint64_t)desc[7] << 8));
3509		return;
3510	}
3511
3512	/* Disable DCC. These are always set by texture_from_handle and must
3513	 * be cleared here.
3514	 */
3515	rtex->dcc_offset = 0;
3516}
3517
3518void si_init_screen_state_functions(struct si_screen *sscreen)
3519{
3520	sscreen->b.b.is_format_supported = si_is_format_supported;
3521	sscreen->b.query_opaque_metadata = si_query_opaque_metadata;
3522	sscreen->b.apply_opaque_metadata = si_apply_opaque_metadata;
3523}
3524
3525static void
3526si_write_harvested_raster_configs(struct si_context *sctx,
3527				  struct si_pm4_state *pm4,
3528				  unsigned raster_config,
3529				  unsigned raster_config_1)
3530{
3531	unsigned sh_per_se = MAX2(sctx->screen->b.info.max_sh_per_se, 1);
3532	unsigned num_se = MAX2(sctx->screen->b.info.max_se, 1);
3533	unsigned rb_mask = sctx->screen->b.info.enabled_rb_mask;
3534	unsigned num_rb = MIN2(sctx->screen->b.info.num_render_backends, 16);
3535	unsigned rb_per_pkr = MIN2(num_rb / num_se / sh_per_se, 2);
3536	unsigned rb_per_se = num_rb / num_se;
3537	unsigned se_mask[4];
3538	unsigned se;
3539
3540	se_mask[0] = ((1 << rb_per_se) - 1);
3541	se_mask[1] = (se_mask[0] << rb_per_se);
3542	se_mask[2] = (se_mask[1] << rb_per_se);
3543	se_mask[3] = (se_mask[2] << rb_per_se);
3544
3545	se_mask[0] &= rb_mask;
3546	se_mask[1] &= rb_mask;
3547	se_mask[2] &= rb_mask;
3548	se_mask[3] &= rb_mask;
3549
3550	assert(num_se == 1 || num_se == 2 || num_se == 4);
3551	assert(sh_per_se == 1 || sh_per_se == 2);
3552	assert(rb_per_pkr == 1 || rb_per_pkr == 2);
3553
3554	/* XXX: I can't figure out what the *_XSEL and *_YSEL
3555	 * fields are for, so I'm leaving them as their default
3556	 * values. */
3557
3558	for (se = 0; se < num_se; se++) {
3559		unsigned raster_config_se = raster_config;
3560		unsigned pkr0_mask = ((1 << rb_per_pkr) - 1) << (se * rb_per_se);
3561		unsigned pkr1_mask = pkr0_mask << rb_per_pkr;
3562		int idx = (se / 2) * 2;
3563
3564		if ((num_se > 1) && (!se_mask[idx] || !se_mask[idx + 1])) {
3565			raster_config_se &= C_028350_SE_MAP;
3566
3567			if (!se_mask[idx]) {
3568				raster_config_se |=
3569					S_028350_SE_MAP(V_028350_RASTER_CONFIG_SE_MAP_3);
3570			} else {
3571				raster_config_se |=
3572					S_028350_SE_MAP(V_028350_RASTER_CONFIG_SE_MAP_0);
3573			}
3574		}
3575
3576		pkr0_mask &= rb_mask;
3577		pkr1_mask &= rb_mask;
3578		if (rb_per_se > 2 && (!pkr0_mask || !pkr1_mask)) {
3579			raster_config_se &= C_028350_PKR_MAP;
3580
3581			if (!pkr0_mask) {
3582				raster_config_se |=
3583					S_028350_PKR_MAP(V_028350_RASTER_CONFIG_PKR_MAP_3);
3584			} else {
3585				raster_config_se |=
3586					S_028350_PKR_MAP(V_028350_RASTER_CONFIG_PKR_MAP_0);
3587			}
3588		}
3589
3590		if (rb_per_se >= 2) {
3591			unsigned rb0_mask = 1 << (se * rb_per_se);
3592			unsigned rb1_mask = rb0_mask << 1;
3593
3594			rb0_mask &= rb_mask;
3595			rb1_mask &= rb_mask;
3596			if (!rb0_mask || !rb1_mask) {
3597				raster_config_se &= C_028350_RB_MAP_PKR0;
3598
3599				if (!rb0_mask) {
3600					raster_config_se |=
3601						S_028350_RB_MAP_PKR0(V_028350_RASTER_CONFIG_RB_MAP_3);
3602				} else {
3603					raster_config_se |=
3604						S_028350_RB_MAP_PKR0(V_028350_RASTER_CONFIG_RB_MAP_0);
3605				}
3606			}
3607
3608			if (rb_per_se > 2) {
3609				rb0_mask = 1 << (se * rb_per_se + rb_per_pkr);
3610				rb1_mask = rb0_mask << 1;
3611				rb0_mask &= rb_mask;
3612				rb1_mask &= rb_mask;
3613				if (!rb0_mask || !rb1_mask) {
3614					raster_config_se &= C_028350_RB_MAP_PKR1;
3615
3616					if (!rb0_mask) {
3617						raster_config_se |=
3618							S_028350_RB_MAP_PKR1(V_028350_RASTER_CONFIG_RB_MAP_3);
3619					} else {
3620						raster_config_se |=
3621							S_028350_RB_MAP_PKR1(V_028350_RASTER_CONFIG_RB_MAP_0);
3622					}
3623				}
3624			}
3625		}
3626
3627		/* GRBM_GFX_INDEX has a different offset on SI and CI+ */
3628		if (sctx->b.chip_class < CIK)
3629			si_pm4_set_reg(pm4, GRBM_GFX_INDEX,
3630				       SE_INDEX(se) | SH_BROADCAST_WRITES |
3631				       INSTANCE_BROADCAST_WRITES);
3632		else
3633			si_pm4_set_reg(pm4, R_030800_GRBM_GFX_INDEX,
3634				       S_030800_SE_INDEX(se) | S_030800_SH_BROADCAST_WRITES(1) |
3635				       S_030800_INSTANCE_BROADCAST_WRITES(1));
3636		si_pm4_set_reg(pm4, R_028350_PA_SC_RASTER_CONFIG, raster_config_se);
3637	}
3638
3639	/* GRBM_GFX_INDEX has a different offset on SI and CI+ */
3640	if (sctx->b.chip_class < CIK)
3641		si_pm4_set_reg(pm4, GRBM_GFX_INDEX,
3642			       SE_BROADCAST_WRITES | SH_BROADCAST_WRITES |
3643			       INSTANCE_BROADCAST_WRITES);
3644	else {
3645		si_pm4_set_reg(pm4, R_030800_GRBM_GFX_INDEX,
3646			       S_030800_SE_BROADCAST_WRITES(1) | S_030800_SH_BROADCAST_WRITES(1) |
3647			       S_030800_INSTANCE_BROADCAST_WRITES(1));
3648
3649		if ((num_se > 2) && ((!se_mask[0] && !se_mask[1]) ||
3650		                     (!se_mask[2] && !se_mask[3]))) {
3651			raster_config_1 &= C_028354_SE_PAIR_MAP;
3652
3653			if (!se_mask[0] && !se_mask[1]) {
3654				raster_config_1 |=
3655					S_028354_SE_PAIR_MAP(V_028354_RASTER_CONFIG_SE_PAIR_MAP_3);
3656			} else {
3657				raster_config_1 |=
3658					S_028354_SE_PAIR_MAP(V_028354_RASTER_CONFIG_SE_PAIR_MAP_0);
3659			}
3660		}
3661
3662		si_pm4_set_reg(pm4, R_028354_PA_SC_RASTER_CONFIG_1, raster_config_1);
3663	}
3664}
3665
3666static void si_init_config(struct si_context *sctx)
3667{
3668	struct si_screen *sscreen = sctx->screen;
3669	unsigned num_rb = MIN2(sctx->screen->b.info.num_render_backends, 16);
3670	unsigned rb_mask = sctx->screen->b.info.enabled_rb_mask;
3671	unsigned raster_config, raster_config_1;
3672	uint64_t border_color_va = sctx->border_color_buffer->gpu_address;
3673	struct si_pm4_state *pm4 = CALLOC_STRUCT(si_pm4_state);
3674	int i;
3675
3676	if (!pm4)
3677		return;
3678
3679	si_pm4_cmd_begin(pm4, PKT3_CONTEXT_CONTROL);
3680	si_pm4_cmd_add(pm4, CONTEXT_CONTROL_LOAD_ENABLE(1));
3681	si_pm4_cmd_add(pm4, CONTEXT_CONTROL_SHADOW_ENABLE(1));
3682	si_pm4_cmd_end(pm4, false);
3683
3684	si_pm4_set_reg(pm4, R_028A18_VGT_HOS_MAX_TESS_LEVEL, fui(64));
3685	si_pm4_set_reg(pm4, R_028A1C_VGT_HOS_MIN_TESS_LEVEL, fui(0));
3686
3687	/* FIXME calculate these values somehow ??? */
3688	si_pm4_set_reg(pm4, R_028A54_VGT_GS_PER_ES, SI_GS_PER_ES);
3689	si_pm4_set_reg(pm4, R_028A58_VGT_ES_PER_GS, 0x40);
3690	si_pm4_set_reg(pm4, R_028A5C_VGT_GS_PER_VS, 0x2);
3691
3692	si_pm4_set_reg(pm4, R_028A8C_VGT_PRIMITIVEID_RESET, 0x0);
3693	si_pm4_set_reg(pm4, R_028B28_VGT_STRMOUT_DRAW_OPAQUE_OFFSET, 0);
3694
3695	si_pm4_set_reg(pm4, R_028B98_VGT_STRMOUT_BUFFER_CONFIG, 0x0);
3696	si_pm4_set_reg(pm4, R_028AB8_VGT_VTX_CNT_EN, 0x0);
3697	if (sctx->b.chip_class < CIK)
3698		si_pm4_set_reg(pm4, R_008A14_PA_CL_ENHANCE, S_008A14_NUM_CLIP_SEQ(3) |
3699			       S_008A14_CLIP_VTX_REORDER_ENA(1));
3700
3701	si_pm4_set_reg(pm4, R_028BD4_PA_SC_CENTROID_PRIORITY_0, 0x76543210);
3702	si_pm4_set_reg(pm4, R_028BD8_PA_SC_CENTROID_PRIORITY_1, 0xfedcba98);
3703
3704	si_pm4_set_reg(pm4, R_02882C_PA_SU_PRIM_FILTER_CNTL, 0);
3705
3706	for (i = 0; i < 16; i++) {
3707		si_pm4_set_reg(pm4, R_0282D0_PA_SC_VPORT_ZMIN_0 + i*8, 0);
3708		si_pm4_set_reg(pm4, R_0282D4_PA_SC_VPORT_ZMAX_0 + i*8, fui(1.0));
3709	}
3710
3711	switch (sctx->screen->b.family) {
3712	case CHIP_TAHITI:
3713	case CHIP_PITCAIRN:
3714		raster_config = 0x2a00126a;
3715		raster_config_1 = 0x00000000;
3716		break;
3717	case CHIP_VERDE:
3718		raster_config = 0x0000124a;
3719		raster_config_1 = 0x00000000;
3720		break;
3721	case CHIP_OLAND:
3722		raster_config = 0x00000082;
3723		raster_config_1 = 0x00000000;
3724		break;
3725	case CHIP_HAINAN:
3726		raster_config = 0x00000000;
3727		raster_config_1 = 0x00000000;
3728		break;
3729	case CHIP_BONAIRE:
3730		raster_config = 0x16000012;
3731		raster_config_1 = 0x00000000;
3732		break;
3733	case CHIP_HAWAII:
3734		raster_config = 0x3a00161a;
3735		raster_config_1 = 0x0000002e;
3736		break;
3737	case CHIP_FIJI:
3738		if (sscreen->b.info.cik_macrotile_mode_array[0] == 0x000000e8) {
3739			/* old kernels with old tiling config */
3740			raster_config = 0x16000012;
3741			raster_config_1 = 0x0000002a;
3742		} else {
3743			raster_config = 0x3a00161a;
3744			raster_config_1 = 0x0000002e;
3745		}
3746		break;
3747	case CHIP_POLARIS10:
3748		raster_config = 0x16000012;
3749		raster_config_1 = 0x0000002a;
3750		break;
3751	case CHIP_POLARIS11:
3752		raster_config = 0x16000012;
3753		raster_config_1 = 0x00000000;
3754		break;
3755	case CHIP_TONGA:
3756		raster_config = 0x16000012;
3757		raster_config_1 = 0x0000002a;
3758		break;
3759	case CHIP_ICELAND:
3760		if (num_rb == 1)
3761			raster_config = 0x00000000;
3762		else
3763			raster_config = 0x00000002;
3764		raster_config_1 = 0x00000000;
3765		break;
3766	case CHIP_CARRIZO:
3767		raster_config = 0x00000002;
3768		raster_config_1 = 0x00000000;
3769		break;
3770	case CHIP_KAVERI:
3771		/* KV should be 0x00000002, but that causes problems with radeon */
3772		raster_config = 0x00000000; /* 0x00000002 */
3773		raster_config_1 = 0x00000000;
3774		break;
3775	case CHIP_KABINI:
3776	case CHIP_MULLINS:
3777	case CHIP_STONEY:
3778		raster_config = 0x00000000;
3779		raster_config_1 = 0x00000000;
3780		break;
3781	default:
3782		fprintf(stderr,
3783			"radeonsi: Unknown GPU, using 0 for raster_config\n");
3784		raster_config = 0x00000000;
3785		raster_config_1 = 0x00000000;
3786		break;
3787	}
3788
3789	/* Always use the default config when all backends are enabled
3790	 * (or when we failed to determine the enabled backends).
3791	 */
3792	if (!rb_mask || util_bitcount(rb_mask) >= num_rb) {
3793		si_pm4_set_reg(pm4, R_028350_PA_SC_RASTER_CONFIG,
3794			       raster_config);
3795		if (sctx->b.chip_class >= CIK)
3796			si_pm4_set_reg(pm4, R_028354_PA_SC_RASTER_CONFIG_1,
3797				       raster_config_1);
3798	} else {
3799		si_write_harvested_raster_configs(sctx, pm4, raster_config, raster_config_1);
3800	}
3801
3802	si_pm4_set_reg(pm4, R_028204_PA_SC_WINDOW_SCISSOR_TL, S_028204_WINDOW_OFFSET_DISABLE(1));
3803	si_pm4_set_reg(pm4, R_028240_PA_SC_GENERIC_SCISSOR_TL, S_028240_WINDOW_OFFSET_DISABLE(1));
3804	si_pm4_set_reg(pm4, R_028244_PA_SC_GENERIC_SCISSOR_BR,
3805		       S_028244_BR_X(16384) | S_028244_BR_Y(16384));
3806	si_pm4_set_reg(pm4, R_028030_PA_SC_SCREEN_SCISSOR_TL, 0);
3807	si_pm4_set_reg(pm4, R_028034_PA_SC_SCREEN_SCISSOR_BR,
3808		       S_028034_BR_X(16384) | S_028034_BR_Y(16384));
3809
3810	si_pm4_set_reg(pm4, R_02820C_PA_SC_CLIPRECT_RULE, 0xFFFF);
3811	si_pm4_set_reg(pm4, R_028230_PA_SC_EDGERULE,
3812		       S_028230_ER_TRI(0xA) |
3813		       S_028230_ER_POINT(0xA) |
3814		       S_028230_ER_RECT(0xA) |
3815		       /* Required by DX10_DIAMOND_TEST_ENA: */
3816		       S_028230_ER_LINE_LR(0x1A) |
3817		       S_028230_ER_LINE_RL(0x26) |
3818		       S_028230_ER_LINE_TB(0xA) |
3819		       S_028230_ER_LINE_BT(0xA));
3820	/* PA_SU_HARDWARE_SCREEN_OFFSET must be 0 due to hw bug on SI */
3821	si_pm4_set_reg(pm4, R_028234_PA_SU_HARDWARE_SCREEN_OFFSET, 0);
3822	si_pm4_set_reg(pm4, R_028820_PA_CL_NANINF_CNTL, 0);
3823	si_pm4_set_reg(pm4, R_028AC0_DB_SRESULTS_COMPARE_STATE0, 0x0);
3824	si_pm4_set_reg(pm4, R_028AC4_DB_SRESULTS_COMPARE_STATE1, 0x0);
3825	si_pm4_set_reg(pm4, R_028AC8_DB_PRELOAD_CONTROL, 0x0);
3826	si_pm4_set_reg(pm4, R_02800C_DB_RENDER_OVERRIDE,
3827		       S_02800C_FORCE_HIS_ENABLE0(V_02800C_FORCE_DISABLE) |
3828		       S_02800C_FORCE_HIS_ENABLE1(V_02800C_FORCE_DISABLE));
3829
3830	si_pm4_set_reg(pm4, R_028400_VGT_MAX_VTX_INDX, ~0);
3831	si_pm4_set_reg(pm4, R_028404_VGT_MIN_VTX_INDX, 0);
3832	si_pm4_set_reg(pm4, R_028408_VGT_INDX_OFFSET, 0);
3833
3834	if (sctx->b.chip_class >= CIK) {
3835		si_pm4_set_reg(pm4, R_00B51C_SPI_SHADER_PGM_RSRC3_LS, S_00B51C_CU_EN(0xffff));
3836		si_pm4_set_reg(pm4, R_00B41C_SPI_SHADER_PGM_RSRC3_HS, 0);
3837		si_pm4_set_reg(pm4, R_00B31C_SPI_SHADER_PGM_RSRC3_ES, S_00B31C_CU_EN(0xffff));
3838		si_pm4_set_reg(pm4, R_00B21C_SPI_SHADER_PGM_RSRC3_GS, S_00B21C_CU_EN(0xffff));
3839
3840		if (sscreen->b.info.num_good_compute_units /
3841		    (sscreen->b.info.max_se * sscreen->b.info.max_sh_per_se) <= 4) {
3842			/* Too few available compute units per SH. Disallowing
3843			 * VS to run on CU0 could hurt us more than late VS
3844			 * allocation would help.
3845			 *
3846			 * LATE_ALLOC_VS = 2 is the highest safe number.
3847			 */
3848			si_pm4_set_reg(pm4, R_00B118_SPI_SHADER_PGM_RSRC3_VS, S_00B118_CU_EN(0xffff));
3849			si_pm4_set_reg(pm4, R_00B11C_SPI_SHADER_LATE_ALLOC_VS, S_00B11C_LIMIT(2));
3850		} else {
3851			/* Set LATE_ALLOC_VS == 31. It should be less than
3852			 * the number of scratch waves. Limitations:
3853			 * - VS can't execute on CU0.
3854			 * - If HS writes outputs to LDS, LS can't execute on CU0.
3855			 */
3856			si_pm4_set_reg(pm4, R_00B118_SPI_SHADER_PGM_RSRC3_VS, S_00B118_CU_EN(0xfffe));
3857			si_pm4_set_reg(pm4, R_00B11C_SPI_SHADER_LATE_ALLOC_VS, S_00B11C_LIMIT(31));
3858		}
3859
3860		si_pm4_set_reg(pm4, R_00B01C_SPI_SHADER_PGM_RSRC3_PS, S_00B01C_CU_EN(0xffff));
3861	}
3862
3863	if (sctx->b.chip_class >= VI) {
3864		unsigned vgt_tess_distribution;
3865
3866		si_pm4_set_reg(pm4, R_028424_CB_DCC_CONTROL,
3867			       S_028424_OVERWRITE_COMBINER_MRT_SHARING_DISABLE(1) |
3868			       S_028424_OVERWRITE_COMBINER_WATERMARK(4));
3869		if (sctx->b.family < CHIP_POLARIS10)
3870			si_pm4_set_reg(pm4, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL, 30);
3871		si_pm4_set_reg(pm4, R_028C5C_VGT_OUT_DEALLOC_CNTL, 32);
3872
3873		vgt_tess_distribution =
3874			S_028B50_ACCUM_ISOLINE(32) |
3875			S_028B50_ACCUM_TRI(11) |
3876			S_028B50_ACCUM_QUAD(11) |
3877			S_028B50_DONUT_SPLIT(16);
3878
3879		/* Testing with Unigine Heaven extreme tesselation yielded best results
3880		 * with TRAP_SPLIT = 3.
3881		 */
3882		if (sctx->b.family == CHIP_FIJI ||
3883		    sctx->b.family >= CHIP_POLARIS10)
3884			vgt_tess_distribution |= S_028B50_TRAP_SPLIT(3);
3885
3886		si_pm4_set_reg(pm4, R_028B50_VGT_TESS_DISTRIBUTION, vgt_tess_distribution);
3887	} else {
3888		si_pm4_set_reg(pm4, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL, 14);
3889		si_pm4_set_reg(pm4, R_028C5C_VGT_OUT_DEALLOC_CNTL, 16);
3890	}
3891
3892	if (sctx->b.family == CHIP_STONEY)
3893		si_pm4_set_reg(pm4, R_028C40_PA_SC_SHADER_CONTROL, 0);
3894
3895	if (sctx->b.family >= CHIP_POLARIS10)
3896		si_pm4_set_reg(pm4, R_028830_PA_SU_SMALL_PRIM_FILTER_CNTL,
3897			       S_028830_SMALL_PRIM_FILTER_ENABLE(1) |
3898			       S_028830_LINE_FILTER_DISABLE(1)); /* line bug */
3899
3900	si_pm4_set_reg(pm4, R_028080_TA_BC_BASE_ADDR, border_color_va >> 8);
3901	if (sctx->b.chip_class >= CIK)
3902		si_pm4_set_reg(pm4, R_028084_TA_BC_BASE_ADDR_HI, border_color_va >> 40);
3903	si_pm4_add_bo(pm4, sctx->border_color_buffer, RADEON_USAGE_READ,
3904		      RADEON_PRIO_BORDER_COLORS);
3905
3906	si_pm4_upload_indirect_buffer(sctx, pm4);
3907	sctx->init_config = pm4;
3908}
3909