OSDN Git Service

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