OSDN Git Service

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