OSDN Git Service

40c478f0a46e3ee907f30d990b57812be7ba55c5
[android-x86/external-mesa.git] / src / gallium / drivers / radeonsi / si_state.c
1 /*
2  * Copyright 2012 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * on the rights to use, copy, modify, merge, publish, distribute, sub
9  * license, and/or sell copies of the Software, and to permit persons to whom
10  * the Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22  * USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */
24
25 #include "si_build_pm4.h"
26 #include "gfx9d.h"
27 #include "si_query.h"
28
29 #include "util/u_dual_blend.h"
30 #include "util/u_format.h"
31 #include "util/u_format_s3tc.h"
32 #include "util/u_memory.h"
33 #include "util/u_resource.h"
34 #include "util/u_upload_mgr.h"
35
36 static unsigned si_map_swizzle(unsigned swizzle)
37 {
38         switch (swizzle) {
39         case PIPE_SWIZZLE_Y:
40                 return V_008F0C_SQ_SEL_Y;
41         case PIPE_SWIZZLE_Z:
42                 return V_008F0C_SQ_SEL_Z;
43         case PIPE_SWIZZLE_W:
44                 return V_008F0C_SQ_SEL_W;
45         case PIPE_SWIZZLE_0:
46                 return V_008F0C_SQ_SEL_0;
47         case PIPE_SWIZZLE_1:
48                 return V_008F0C_SQ_SEL_1;
49         default: /* PIPE_SWIZZLE_X */
50                 return V_008F0C_SQ_SEL_X;
51         }
52 }
53
54 /* 12.4 fixed-point */
55 static unsigned si_pack_float_12p4(float x)
56 {
57         return x <= 0    ? 0 :
58                x >= 4096 ? 0xffff : x * 16;
59 }
60
61 /*
62  * Inferred framebuffer and blender state.
63  *
64  * CB_TARGET_MASK is emitted here to avoid a hang with dual source blending
65  * if there is not enough PS outputs.
66  */
67 static void si_emit_cb_render_state(struct si_context *sctx)
68 {
69         struct radeon_cmdbuf *cs = sctx->gfx_cs;
70         struct si_state_blend *blend = sctx->queued.named.blend;
71         /* CB_COLORn_INFO.FORMAT=INVALID should disable unbound colorbuffers,
72          * but you never know. */
73         uint32_t cb_target_mask = sctx->framebuffer.colorbuf_enabled_4bit;
74         unsigned i;
75
76         if (blend)
77                 cb_target_mask &= blend->cb_target_mask;
78
79         /* Avoid a hang that happens when dual source blending is enabled
80          * but there is not enough color outputs. This is undefined behavior,
81          * so disable color writes completely.
82          *
83          * Reproducible with Unigine Heaven 4.0 and drirc missing.
84          */
85         if (blend && blend->dual_src_blend &&
86             sctx->ps_shader.cso &&
87             (sctx->ps_shader.cso->info.colors_written & 0x3) != 0x3)
88                 cb_target_mask = 0;
89
90         radeon_opt_set_context_reg(sctx, R_028238_CB_TARGET_MASK,
91                                    SI_TRACKED_CB_TARGET_MASK, cb_target_mask);
92
93         /* GFX9: Flush DFSM when CB_TARGET_MASK changes.
94          * I think we don't have to do anything between IBs.
95          */
96         if (sctx->screen->dfsm_allowed &&
97             sctx->last_cb_target_mask != cb_target_mask) {
98                 sctx->last_cb_target_mask = cb_target_mask;
99
100                 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
101                 radeon_emit(cs, EVENT_TYPE(V_028A90_FLUSH_DFSM) | EVENT_INDEX(0));
102         }
103
104         if (sctx->chip_class >= VI) {
105                 /* DCC MSAA workaround for blending.
106                  * Alternatively, we can set CB_COLORi_DCC_CONTROL.OVERWRITE_-
107                  * COMBINER_DISABLE, but that would be more complicated.
108                  */
109                 bool oc_disable = (sctx->chip_class == VI ||
110                                    sctx->chip_class == GFX9) &&
111                                   blend &&
112                                   blend->blend_enable_4bit & cb_target_mask &&
113                                   sctx->framebuffer.nr_samples >= 2;
114
115                 radeon_opt_set_context_reg(
116                                 sctx, R_028424_CB_DCC_CONTROL,
117                                 SI_TRACKED_CB_DCC_CONTROL,
118                                 S_028424_OVERWRITE_COMBINER_MRT_SHARING_DISABLE(1) |
119                                 S_028424_OVERWRITE_COMBINER_WATERMARK(4) |
120                                 S_028424_OVERWRITE_COMBINER_DISABLE(oc_disable));
121         }
122
123         /* RB+ register settings. */
124         if (sctx->screen->rbplus_allowed) {
125                 unsigned spi_shader_col_format =
126                         sctx->ps_shader.cso ?
127                         sctx->ps_shader.current->key.part.ps.epilog.spi_shader_col_format : 0;
128                 unsigned sx_ps_downconvert = 0;
129                 unsigned sx_blend_opt_epsilon = 0;
130                 unsigned sx_blend_opt_control = 0;
131
132                 for (i = 0; i < sctx->framebuffer.state.nr_cbufs; i++) {
133                         struct si_surface *surf =
134                                 (struct si_surface*)sctx->framebuffer.state.cbufs[i];
135                         unsigned format, swap, spi_format, colormask;
136                         bool has_alpha, has_rgb;
137
138                         if (!surf)
139                                 continue;
140
141                         format = G_028C70_FORMAT(surf->cb_color_info);
142                         swap = G_028C70_COMP_SWAP(surf->cb_color_info);
143                         spi_format = (spi_shader_col_format >> (i * 4)) & 0xf;
144                         colormask = (cb_target_mask >> (i * 4)) & 0xf;
145
146                         /* Set if RGB and A are present. */
147                         has_alpha = !G_028C74_FORCE_DST_ALPHA_1(surf->cb_color_attrib);
148
149                         if (format == V_028C70_COLOR_8 ||
150                             format == V_028C70_COLOR_16 ||
151                             format == V_028C70_COLOR_32)
152                                 has_rgb = !has_alpha;
153                         else
154                                 has_rgb = true;
155
156                         /* Check the colormask and export format. */
157                         if (!(colormask & (PIPE_MASK_RGBA & ~PIPE_MASK_A)))
158                                 has_rgb = false;
159                         if (!(colormask & PIPE_MASK_A))
160                                 has_alpha = false;
161
162                         if (spi_format == V_028714_SPI_SHADER_ZERO) {
163                                 has_rgb = false;
164                                 has_alpha = false;
165                         }
166
167                         /* Disable value checking for disabled channels. */
168                         if (!has_rgb)
169                                 sx_blend_opt_control |= S_02875C_MRT0_COLOR_OPT_DISABLE(1) << (i * 4);
170                         if (!has_alpha)
171                                 sx_blend_opt_control |= S_02875C_MRT0_ALPHA_OPT_DISABLE(1) << (i * 4);
172
173                         /* Enable down-conversion for 32bpp and smaller formats. */
174                         switch (format) {
175                         case V_028C70_COLOR_8:
176                         case V_028C70_COLOR_8_8:
177                         case V_028C70_COLOR_8_8_8_8:
178                                 /* For 1 and 2-channel formats, use the superset thereof. */
179                                 if (spi_format == V_028714_SPI_SHADER_FP16_ABGR ||
180                                     spi_format == V_028714_SPI_SHADER_UINT16_ABGR ||
181                                     spi_format == V_028714_SPI_SHADER_SINT16_ABGR) {
182                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_8_8_8_8 << (i * 4);
183                                         sx_blend_opt_epsilon |= V_028758_8BIT_FORMAT << (i * 4);
184                                 }
185                                 break;
186
187                         case V_028C70_COLOR_5_6_5:
188                                 if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
189                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_5_6_5 << (i * 4);
190                                         sx_blend_opt_epsilon |= V_028758_6BIT_FORMAT << (i * 4);
191                                 }
192                                 break;
193
194                         case V_028C70_COLOR_1_5_5_5:
195                                 if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
196                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_1_5_5_5 << (i * 4);
197                                         sx_blend_opt_epsilon |= V_028758_5BIT_FORMAT << (i * 4);
198                                 }
199                                 break;
200
201                         case V_028C70_COLOR_4_4_4_4:
202                                 if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
203                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_4_4_4_4 << (i * 4);
204                                         sx_blend_opt_epsilon |= V_028758_4BIT_FORMAT << (i * 4);
205                                 }
206                                 break;
207
208                         case V_028C70_COLOR_32:
209                                 if (swap == V_028C70_SWAP_STD &&
210                                     spi_format == V_028714_SPI_SHADER_32_R)
211                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_32_R << (i * 4);
212                                 else if (swap == V_028C70_SWAP_ALT_REV &&
213                                          spi_format == V_028714_SPI_SHADER_32_AR)
214                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_32_A << (i * 4);
215                                 break;
216
217                         case V_028C70_COLOR_16:
218                         case V_028C70_COLOR_16_16:
219                                 /* For 1-channel formats, use the superset thereof. */
220                                 if (spi_format == V_028714_SPI_SHADER_UNORM16_ABGR ||
221                                     spi_format == V_028714_SPI_SHADER_SNORM16_ABGR ||
222                                     spi_format == V_028714_SPI_SHADER_UINT16_ABGR ||
223                                     spi_format == V_028714_SPI_SHADER_SINT16_ABGR) {
224                                         if (swap == V_028C70_SWAP_STD ||
225                                             swap == V_028C70_SWAP_STD_REV)
226                                                 sx_ps_downconvert |= V_028754_SX_RT_EXPORT_16_16_GR << (i * 4);
227                                         else
228                                                 sx_ps_downconvert |= V_028754_SX_RT_EXPORT_16_16_AR << (i * 4);
229                                 }
230                                 break;
231
232                         case V_028C70_COLOR_10_11_11:
233                                 if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
234                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_10_11_11 << (i * 4);
235                                         sx_blend_opt_epsilon |= V_028758_11BIT_FORMAT << (i * 4);
236                                 }
237                                 break;
238
239                         case V_028C70_COLOR_2_10_10_10:
240                                 if (spi_format == V_028714_SPI_SHADER_FP16_ABGR) {
241                                         sx_ps_downconvert |= V_028754_SX_RT_EXPORT_2_10_10_10 << (i * 4);
242                                         sx_blend_opt_epsilon |= V_028758_10BIT_FORMAT << (i * 4);
243                                 }
244                                 break;
245                         }
246                 }
247
248                 /* SX_PS_DOWNCONVERT, SX_BLEND_OPT_EPSILON, SX_BLEND_OPT_CONTROL */
249                 radeon_opt_set_context_reg3(sctx, R_028754_SX_PS_DOWNCONVERT,
250                                             SI_TRACKED_SX_PS_DOWNCONVERT,
251                                             sx_ps_downconvert, sx_blend_opt_epsilon,
252                                             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                 PRINT_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                 PRINT_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 static void si_blend_check_commutativity(struct si_screen *sscreen,
374                                          struct si_state_blend *blend,
375                                          enum pipe_blend_func func,
376                                          enum pipe_blendfactor src,
377                                          enum pipe_blendfactor dst,
378                                          unsigned chanmask)
379 {
380         /* Src factor is allowed when it does not depend on Dst */
381         static const uint32_t src_allowed =
382                 (1u << PIPE_BLENDFACTOR_ONE) |
383                 (1u << PIPE_BLENDFACTOR_SRC_COLOR) |
384                 (1u << PIPE_BLENDFACTOR_SRC_ALPHA) |
385                 (1u << PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE) |
386                 (1u << PIPE_BLENDFACTOR_CONST_COLOR) |
387                 (1u << PIPE_BLENDFACTOR_CONST_ALPHA) |
388                 (1u << PIPE_BLENDFACTOR_SRC1_COLOR) |
389                 (1u << PIPE_BLENDFACTOR_SRC1_ALPHA) |
390                 (1u << PIPE_BLENDFACTOR_ZERO) |
391                 (1u << PIPE_BLENDFACTOR_INV_SRC_COLOR) |
392                 (1u << PIPE_BLENDFACTOR_INV_SRC_ALPHA) |
393                 (1u << PIPE_BLENDFACTOR_INV_CONST_COLOR) |
394                 (1u << PIPE_BLENDFACTOR_INV_CONST_ALPHA) |
395                 (1u << PIPE_BLENDFACTOR_INV_SRC1_COLOR) |
396                 (1u << PIPE_BLENDFACTOR_INV_SRC1_ALPHA);
397
398         if (dst == PIPE_BLENDFACTOR_ONE &&
399             (src_allowed & (1u << src))) {
400                 /* Addition is commutative, but floating point addition isn't
401                  * associative: subtle changes can be introduced via different
402                  * rounding.
403                  *
404                  * Out-of-order is also non-deterministic, which means that
405                  * this breaks OpenGL invariance requirements. So only enable
406                  * out-of-order additive blending if explicitly allowed by a
407                  * setting.
408                  */
409                 if (func == PIPE_BLEND_MAX || func == PIPE_BLEND_MIN ||
410                     (func == PIPE_BLEND_ADD && sscreen->commutative_blend_add))
411                         blend->commutative_4bit |= chanmask;
412         }
413 }
414
415 /**
416  * Get rid of DST in the blend factors by commuting the operands:
417  *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
418  */
419 static void si_blend_remove_dst(unsigned *func, unsigned *src_factor,
420                                 unsigned *dst_factor, unsigned expected_dst,
421                                 unsigned replacement_src)
422 {
423         if (*src_factor == expected_dst &&
424             *dst_factor == PIPE_BLENDFACTOR_ZERO) {
425                 *src_factor = PIPE_BLENDFACTOR_ZERO;
426                 *dst_factor = replacement_src;
427
428                 /* Commuting the operands requires reversing subtractions. */
429                 if (*func == PIPE_BLEND_SUBTRACT)
430                         *func = PIPE_BLEND_REVERSE_SUBTRACT;
431                 else if (*func == PIPE_BLEND_REVERSE_SUBTRACT)
432                         *func = PIPE_BLEND_SUBTRACT;
433         }
434 }
435
436 static bool si_blend_factor_uses_dst(unsigned factor)
437 {
438         return factor == PIPE_BLENDFACTOR_DST_COLOR ||
439                 factor == PIPE_BLENDFACTOR_DST_ALPHA ||
440                 factor == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE ||
441                 factor == PIPE_BLENDFACTOR_INV_DST_ALPHA ||
442                 factor == PIPE_BLENDFACTOR_INV_DST_COLOR;
443 }
444
445 static void *si_create_blend_state_mode(struct pipe_context *ctx,
446                                         const struct pipe_blend_state *state,
447                                         unsigned mode)
448 {
449         struct si_context *sctx = (struct si_context*)ctx;
450         struct si_state_blend *blend = CALLOC_STRUCT(si_state_blend);
451         struct si_pm4_state *pm4 = &blend->pm4;
452         uint32_t sx_mrt_blend_opt[8] = {0};
453         uint32_t color_control = 0;
454
455         if (!blend)
456                 return NULL;
457
458         blend->alpha_to_coverage = state->alpha_to_coverage;
459         blend->alpha_to_one = state->alpha_to_one;
460         blend->dual_src_blend = util_blend_state_is_dual(state, 0);
461         blend->logicop_enable = state->logicop_enable;
462
463         if (state->logicop_enable) {
464                 color_control |= S_028808_ROP3(state->logicop_func | (state->logicop_func << 4));
465         } else {
466                 color_control |= S_028808_ROP3(0xcc);
467         }
468
469         si_pm4_set_reg(pm4, R_028B70_DB_ALPHA_TO_MASK,
470                        S_028B70_ALPHA_TO_MASK_ENABLE(state->alpha_to_coverage) |
471                        S_028B70_ALPHA_TO_MASK_OFFSET0(2) |
472                        S_028B70_ALPHA_TO_MASK_OFFSET1(2) |
473                        S_028B70_ALPHA_TO_MASK_OFFSET2(2) |
474                        S_028B70_ALPHA_TO_MASK_OFFSET3(2));
475
476         if (state->alpha_to_coverage)
477                 blend->need_src_alpha_4bit |= 0xf;
478
479         blend->cb_target_mask = 0;
480         blend->cb_target_enabled_4bit = 0;
481
482         for (int i = 0; i < 8; i++) {
483                 /* state->rt entries > 0 only written if independent blending */
484                 const int j = state->independent_blend_enable ? i : 0;
485
486                 unsigned eqRGB = state->rt[j].rgb_func;
487                 unsigned srcRGB = state->rt[j].rgb_src_factor;
488                 unsigned dstRGB = state->rt[j].rgb_dst_factor;
489                 unsigned eqA = state->rt[j].alpha_func;
490                 unsigned srcA = state->rt[j].alpha_src_factor;
491                 unsigned dstA = state->rt[j].alpha_dst_factor;
492
493                 unsigned srcRGB_opt, dstRGB_opt, srcA_opt, dstA_opt;
494                 unsigned blend_cntl = 0;
495
496                 sx_mrt_blend_opt[i] =
497                         S_028760_COLOR_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED) |
498                         S_028760_ALPHA_COMB_FCN(V_028760_OPT_COMB_BLEND_DISABLED);
499
500                 /* Only set dual source blending for MRT0 to avoid a hang. */
501                 if (i >= 1 && blend->dual_src_blend) {
502                         /* Vulkan does this for dual source blending. */
503                         if (i == 1)
504                                 blend_cntl |= S_028780_ENABLE(1);
505
506                         si_pm4_set_reg(pm4, R_028780_CB_BLEND0_CONTROL + i * 4, blend_cntl);
507                         continue;
508                 }
509
510                 /* Only addition and subtraction equations are supported with
511                  * dual source blending.
512                  */
513                 if (blend->dual_src_blend &&
514                     (eqRGB == PIPE_BLEND_MIN || eqRGB == PIPE_BLEND_MAX ||
515                      eqA == PIPE_BLEND_MIN || eqA == PIPE_BLEND_MAX)) {
516                         assert(!"Unsupported equation for dual source blending");
517                         si_pm4_set_reg(pm4, R_028780_CB_BLEND0_CONTROL + i * 4, blend_cntl);
518                         continue;
519                 }
520
521                 /* cb_render_state will disable unused ones */
522                 blend->cb_target_mask |= (unsigned)state->rt[j].colormask << (4 * i);
523                 if (state->rt[j].colormask)
524                         blend->cb_target_enabled_4bit |= 0xf << (4 * i);
525
526                 if (!state->rt[j].colormask || !state->rt[j].blend_enable) {
527                         si_pm4_set_reg(pm4, R_028780_CB_BLEND0_CONTROL + i * 4, blend_cntl);
528                         continue;
529                 }
530
531                 si_blend_check_commutativity(sctx->screen, blend,
532                                              eqRGB, srcRGB, dstRGB, 0x7 << (4 * i));
533                 si_blend_check_commutativity(sctx->screen, blend,
534                                              eqA, srcA, dstA, 0x8 << (4 * i));
535
536                 /* Blending optimizations for RB+.
537                  * These transformations don't change the behavior.
538                  *
539                  * First, get rid of DST in the blend factors:
540                  *    func(src * DST, dst * 0) ---> func(src * 0, dst * SRC)
541                  */
542                 si_blend_remove_dst(&eqRGB, &srcRGB, &dstRGB,
543                                     PIPE_BLENDFACTOR_DST_COLOR,
544                                     PIPE_BLENDFACTOR_SRC_COLOR);
545                 si_blend_remove_dst(&eqA, &srcA, &dstA,
546                                     PIPE_BLENDFACTOR_DST_COLOR,
547                                     PIPE_BLENDFACTOR_SRC_COLOR);
548                 si_blend_remove_dst(&eqA, &srcA, &dstA,
549                                     PIPE_BLENDFACTOR_DST_ALPHA,
550                                     PIPE_BLENDFACTOR_SRC_ALPHA);
551
552                 /* Look up the ideal settings from tables. */
553                 srcRGB_opt = si_translate_blend_opt_factor(srcRGB, false);
554                 dstRGB_opt = si_translate_blend_opt_factor(dstRGB, false);
555                 srcA_opt = si_translate_blend_opt_factor(srcA, true);
556                 dstA_opt = si_translate_blend_opt_factor(dstA, true);
557
558                 /* Handle interdependencies. */
559                 if (si_blend_factor_uses_dst(srcRGB))
560                         dstRGB_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
561                 if (si_blend_factor_uses_dst(srcA))
562                         dstA_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_NONE;
563
564                 if (srcRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE &&
565                     (dstRGB == PIPE_BLENDFACTOR_ZERO ||
566                      dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA ||
567                      dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE))
568                         dstRGB_opt = V_028760_BLEND_OPT_PRESERVE_NONE_IGNORE_A0;
569
570                 /* Set the final value. */
571                 sx_mrt_blend_opt[i] =
572                         S_028760_COLOR_SRC_OPT(srcRGB_opt) |
573                         S_028760_COLOR_DST_OPT(dstRGB_opt) |
574                         S_028760_COLOR_COMB_FCN(si_translate_blend_opt_function(eqRGB)) |
575                         S_028760_ALPHA_SRC_OPT(srcA_opt) |
576                         S_028760_ALPHA_DST_OPT(dstA_opt) |
577                         S_028760_ALPHA_COMB_FCN(si_translate_blend_opt_function(eqA));
578
579                 /* Set blend state. */
580                 blend_cntl |= S_028780_ENABLE(1);
581                 blend_cntl |= S_028780_COLOR_COMB_FCN(si_translate_blend_function(eqRGB));
582                 blend_cntl |= S_028780_COLOR_SRCBLEND(si_translate_blend_factor(srcRGB));
583                 blend_cntl |= S_028780_COLOR_DESTBLEND(si_translate_blend_factor(dstRGB));
584
585                 if (srcA != srcRGB || dstA != dstRGB || eqA != eqRGB) {
586                         blend_cntl |= S_028780_SEPARATE_ALPHA_BLEND(1);
587                         blend_cntl |= S_028780_ALPHA_COMB_FCN(si_translate_blend_function(eqA));
588                         blend_cntl |= S_028780_ALPHA_SRCBLEND(si_translate_blend_factor(srcA));
589                         blend_cntl |= S_028780_ALPHA_DESTBLEND(si_translate_blend_factor(dstA));
590                 }
591                 si_pm4_set_reg(pm4, R_028780_CB_BLEND0_CONTROL + i * 4, blend_cntl);
592
593                 blend->blend_enable_4bit |= 0xfu << (i * 4);
594
595                 /* This is only important for formats without alpha. */
596                 if (srcRGB == PIPE_BLENDFACTOR_SRC_ALPHA ||
597                     dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA ||
598                     srcRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE ||
599                     dstRGB == PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE ||
600                     srcRGB == PIPE_BLENDFACTOR_INV_SRC_ALPHA ||
601                     dstRGB == PIPE_BLENDFACTOR_INV_SRC_ALPHA)
602                         blend->need_src_alpha_4bit |= 0xfu << (i * 4);
603         }
604
605         if (blend->cb_target_mask) {
606                 color_control |= S_028808_MODE(mode);
607         } else {
608                 color_control |= S_028808_MODE(V_028808_CB_DISABLE);
609         }
610
611         if (sctx->screen->rbplus_allowed) {
612                 /* Disable RB+ blend optimizations for dual source blending.
613                  * Vulkan does this.
614                  */
615                 if (blend->dual_src_blend) {
616                         for (int i = 0; i < 8; i++) {
617                                 sx_mrt_blend_opt[i] =
618                                         S_028760_COLOR_COMB_FCN(V_028760_OPT_COMB_NONE) |
619                                         S_028760_ALPHA_COMB_FCN(V_028760_OPT_COMB_NONE);
620                         }
621                 }
622
623                 for (int i = 0; i < 8; i++)
624                         si_pm4_set_reg(pm4, R_028760_SX_MRT0_BLEND_OPT + i * 4,
625                                        sx_mrt_blend_opt[i]);
626
627                 /* RB+ doesn't work with dual source blending, logic op, and RESOLVE. */
628                 if (blend->dual_src_blend || state->logicop_enable ||
629                     mode == V_028808_CB_RESOLVE)
630                         color_control |= S_028808_DISABLE_DUAL_QUAD(1);
631         }
632
633         si_pm4_set_reg(pm4, R_028808_CB_COLOR_CONTROL, color_control);
634         return blend;
635 }
636
637 static void *si_create_blend_state(struct pipe_context *ctx,
638                                    const struct pipe_blend_state *state)
639 {
640         return si_create_blend_state_mode(ctx, state, V_028808_CB_NORMAL);
641 }
642
643 static void si_bind_blend_state(struct pipe_context *ctx, void *state)
644 {
645         struct si_context *sctx = (struct si_context *)ctx;
646         struct si_state_blend *old_blend = sctx->queued.named.blend;
647         struct si_state_blend *blend = (struct si_state_blend *)state;
648
649         if (!state)
650                 return;
651
652         si_pm4_bind_state(sctx, blend, state);
653
654         if (!old_blend ||
655             old_blend->cb_target_mask != blend->cb_target_mask ||
656             old_blend->dual_src_blend != blend->dual_src_blend ||
657             (old_blend->blend_enable_4bit != blend->blend_enable_4bit &&
658              sctx->framebuffer.nr_samples >= 2 &&
659              sctx->screen->dcc_msaa_allowed))
660                 si_mark_atom_dirty(sctx, &sctx->atoms.s.cb_render_state);
661
662         if (!old_blend ||
663             old_blend->cb_target_mask != blend->cb_target_mask ||
664             old_blend->alpha_to_coverage != blend->alpha_to_coverage ||
665             old_blend->alpha_to_one != blend->alpha_to_one ||
666             old_blend->dual_src_blend != blend->dual_src_blend ||
667             old_blend->blend_enable_4bit != blend->blend_enable_4bit ||
668             old_blend->need_src_alpha_4bit != blend->need_src_alpha_4bit)
669                 sctx->do_update_shaders = true;
670
671         if (sctx->screen->dpbb_allowed &&
672             (!old_blend ||
673              old_blend->alpha_to_coverage != blend->alpha_to_coverage ||
674              old_blend->blend_enable_4bit != blend->blend_enable_4bit ||
675              old_blend->cb_target_enabled_4bit != blend->cb_target_enabled_4bit))
676                 si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
677
678         if (sctx->screen->has_out_of_order_rast &&
679             (!old_blend ||
680              (old_blend->blend_enable_4bit != blend->blend_enable_4bit ||
681               old_blend->cb_target_enabled_4bit != blend->cb_target_enabled_4bit ||
682               old_blend->commutative_4bit != blend->commutative_4bit ||
683               old_blend->logicop_enable != blend->logicop_enable)))
684                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
685 }
686
687 static void si_delete_blend_state(struct pipe_context *ctx, void *state)
688 {
689         struct si_context *sctx = (struct si_context *)ctx;
690         si_pm4_delete_state(sctx, blend, (struct si_state_blend *)state);
691 }
692
693 static void si_set_blend_color(struct pipe_context *ctx,
694                                const struct pipe_blend_color *state)
695 {
696         struct si_context *sctx = (struct si_context *)ctx;
697         static const struct pipe_blend_color zeros;
698
699         sctx->blend_color.state = *state;
700         sctx->blend_color.any_nonzeros = memcmp(state, &zeros, sizeof(*state)) != 0;
701         si_mark_atom_dirty(sctx, &sctx->atoms.s.blend_color);
702 }
703
704 static void si_emit_blend_color(struct si_context *sctx)
705 {
706         struct radeon_cmdbuf *cs = sctx->gfx_cs;
707
708         radeon_set_context_reg_seq(cs, R_028414_CB_BLEND_RED, 4);
709         radeon_emit_array(cs, (uint32_t*)sctx->blend_color.state.color, 4);
710 }
711
712 /*
713  * Clipping
714  */
715
716 static void si_set_clip_state(struct pipe_context *ctx,
717                               const struct pipe_clip_state *state)
718 {
719         struct si_context *sctx = (struct si_context *)ctx;
720         struct pipe_constant_buffer cb;
721         static const struct pipe_clip_state zeros;
722
723         if (memcmp(&sctx->clip_state.state, state, sizeof(*state)) == 0)
724                 return;
725
726         sctx->clip_state.state = *state;
727         sctx->clip_state.any_nonzeros = memcmp(state, &zeros, sizeof(*state)) != 0;
728         si_mark_atom_dirty(sctx, &sctx->atoms.s.clip_state);
729
730         cb.buffer = NULL;
731         cb.user_buffer = state->ucp;
732         cb.buffer_offset = 0;
733         cb.buffer_size = 4*4*8;
734         si_set_rw_buffer(sctx, SI_VS_CONST_CLIP_PLANES, &cb);
735         pipe_resource_reference(&cb.buffer, NULL);
736 }
737
738 static void si_emit_clip_state(struct si_context *sctx)
739 {
740         struct radeon_cmdbuf *cs = sctx->gfx_cs;
741
742         radeon_set_context_reg_seq(cs, R_0285BC_PA_CL_UCP_0_X, 6*4);
743         radeon_emit_array(cs, (uint32_t*)sctx->clip_state.state.ucp, 6*4);
744 }
745
746 static void si_emit_clip_regs(struct si_context *sctx)
747 {
748         struct si_shader *vs = si_get_vs_state(sctx);
749         struct si_shader_selector *vs_sel = vs->selector;
750         struct tgsi_shader_info *info = &vs_sel->info;
751         struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
752         unsigned window_space =
753            info->properties[TGSI_PROPERTY_VS_WINDOW_SPACE_POSITION];
754         unsigned clipdist_mask = vs_sel->clipdist_mask;
755         unsigned ucp_mask = clipdist_mask ? 0 : rs->clip_plane_enable & SIX_BITS;
756         unsigned culldist_mask = vs_sel->culldist_mask;
757         unsigned total_mask;
758
759         if (vs->key.opt.clip_disable) {
760                 assert(!info->culldist_writemask);
761                 clipdist_mask = 0;
762                 culldist_mask = 0;
763         }
764         total_mask = clipdist_mask | culldist_mask;
765
766         /* Clip distances on points have no effect, so need to be implemented
767          * as cull distances. This applies for the clipvertex case as well.
768          *
769          * Setting this for primitives other than points should have no adverse
770          * effects.
771          */
772         clipdist_mask &= rs->clip_plane_enable;
773         culldist_mask |= clipdist_mask;
774
775         radeon_opt_set_context_reg(sctx, R_02881C_PA_CL_VS_OUT_CNTL,
776                 SI_TRACKED_PA_CL_VS_OUT_CNTL,
777                 vs_sel->pa_cl_vs_out_cntl |
778                 S_02881C_VS_OUT_CCDIST0_VEC_ENA((total_mask & 0x0F) != 0) |
779                 S_02881C_VS_OUT_CCDIST1_VEC_ENA((total_mask & 0xF0) != 0) |
780                 clipdist_mask | (culldist_mask << 8));
781         radeon_opt_set_context_reg(sctx, R_028810_PA_CL_CLIP_CNTL,
782                 SI_TRACKED_PA_CL_CLIP_CNTL,
783                 rs->pa_cl_clip_cntl |
784                 ucp_mask |
785                 S_028810_CLIP_DISABLE(window_space));
786 }
787
788 /*
789  * inferred state between framebuffer and rasterizer
790  */
791 static void si_update_poly_offset_state(struct si_context *sctx)
792 {
793         struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
794
795         if (!rs || !rs->uses_poly_offset || !sctx->framebuffer.state.zsbuf) {
796                 si_pm4_bind_state(sctx, poly_offset, NULL);
797                 return;
798         }
799
800         /* Use the user format, not db_render_format, so that the polygon
801          * offset behaves as expected by applications.
802          */
803         switch (sctx->framebuffer.state.zsbuf->texture->format) {
804         case PIPE_FORMAT_Z16_UNORM:
805                 si_pm4_bind_state(sctx, poly_offset, &rs->pm4_poly_offset[0]);
806                 break;
807         default: /* 24-bit */
808                 si_pm4_bind_state(sctx, poly_offset, &rs->pm4_poly_offset[1]);
809                 break;
810         case PIPE_FORMAT_Z32_FLOAT:
811         case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
812                 si_pm4_bind_state(sctx, poly_offset, &rs->pm4_poly_offset[2]);
813                 break;
814         }
815 }
816
817 /*
818  * Rasterizer
819  */
820
821 static uint32_t si_translate_fill(uint32_t func)
822 {
823         switch(func) {
824         case PIPE_POLYGON_MODE_FILL:
825                 return V_028814_X_DRAW_TRIANGLES;
826         case PIPE_POLYGON_MODE_LINE:
827                 return V_028814_X_DRAW_LINES;
828         case PIPE_POLYGON_MODE_POINT:
829                 return V_028814_X_DRAW_POINTS;
830         default:
831                 assert(0);
832                 return V_028814_X_DRAW_POINTS;
833         }
834 }
835
836 static void *si_create_rs_state(struct pipe_context *ctx,
837                                 const struct pipe_rasterizer_state *state)
838 {
839         struct si_screen *sscreen = ((struct si_context *)ctx)->screen;
840         struct si_state_rasterizer *rs = CALLOC_STRUCT(si_state_rasterizer);
841         struct si_pm4_state *pm4 = &rs->pm4;
842         unsigned tmp, i;
843         float psize_min, psize_max;
844
845         if (!rs) {
846                 return NULL;
847         }
848
849         rs->scissor_enable = state->scissor;
850         rs->clip_halfz = state->clip_halfz;
851         rs->two_side = state->light_twoside;
852         rs->multisample_enable = state->multisample;
853         rs->force_persample_interp = state->force_persample_interp;
854         rs->clip_plane_enable = state->clip_plane_enable;
855         rs->line_stipple_enable = state->line_stipple_enable;
856         rs->poly_stipple_enable = state->poly_stipple_enable;
857         rs->line_smooth = state->line_smooth;
858         rs->line_width = state->line_width;
859         rs->poly_smooth = state->poly_smooth;
860         rs->uses_poly_offset = state->offset_point || state->offset_line ||
861                                state->offset_tri;
862         rs->clamp_fragment_color = state->clamp_fragment_color;
863         rs->clamp_vertex_color = state->clamp_vertex_color;
864         rs->flatshade = state->flatshade;
865         rs->sprite_coord_enable = state->sprite_coord_enable;
866         rs->rasterizer_discard = state->rasterizer_discard;
867         rs->pa_sc_line_stipple = state->line_stipple_enable ?
868                                 S_028A0C_LINE_PATTERN(state->line_stipple_pattern) |
869                                 S_028A0C_REPEAT_COUNT(state->line_stipple_factor) : 0;
870         rs->pa_cl_clip_cntl =
871                 S_028810_DX_CLIP_SPACE_DEF(state->clip_halfz) |
872                 S_028810_ZCLIP_NEAR_DISABLE(!state->depth_clip_near) |
873                 S_028810_ZCLIP_FAR_DISABLE(!state->depth_clip_far) |
874                 S_028810_DX_RASTERIZATION_KILL(state->rasterizer_discard) |
875                 S_028810_DX_LINEAR_ATTR_CLIP_ENA(1);
876
877         si_pm4_set_reg(pm4, R_0286D4_SPI_INTERP_CONTROL_0,
878                 S_0286D4_FLAT_SHADE_ENA(1) |
879                 S_0286D4_PNT_SPRITE_ENA(state->point_quad_rasterization) |
880                 S_0286D4_PNT_SPRITE_OVRD_X(V_0286D4_SPI_PNT_SPRITE_SEL_S) |
881                 S_0286D4_PNT_SPRITE_OVRD_Y(V_0286D4_SPI_PNT_SPRITE_SEL_T) |
882                 S_0286D4_PNT_SPRITE_OVRD_Z(V_0286D4_SPI_PNT_SPRITE_SEL_0) |
883                 S_0286D4_PNT_SPRITE_OVRD_W(V_0286D4_SPI_PNT_SPRITE_SEL_1) |
884                 S_0286D4_PNT_SPRITE_TOP_1(state->sprite_coord_mode != PIPE_SPRITE_COORD_UPPER_LEFT));
885
886         /* point size 12.4 fixed point */
887         tmp = (unsigned)(state->point_size * 8.0);
888         si_pm4_set_reg(pm4, R_028A00_PA_SU_POINT_SIZE, S_028A00_HEIGHT(tmp) | S_028A00_WIDTH(tmp));
889
890         if (state->point_size_per_vertex) {
891                 psize_min = util_get_min_point_size(state);
892                 psize_max = 8192;
893         } else {
894                 /* Force the point size to be as if the vertex output was disabled. */
895                 psize_min = state->point_size;
896                 psize_max = state->point_size;
897         }
898         rs->max_point_size = psize_max;
899
900         /* Divide by two, because 0.5 = 1 pixel. */
901         si_pm4_set_reg(pm4, R_028A04_PA_SU_POINT_MINMAX,
902                         S_028A04_MIN_SIZE(si_pack_float_12p4(psize_min/2)) |
903                         S_028A04_MAX_SIZE(si_pack_float_12p4(psize_max/2)));
904
905         si_pm4_set_reg(pm4, R_028A08_PA_SU_LINE_CNTL,
906                        S_028A08_WIDTH(si_pack_float_12p4(state->line_width/2)));
907         si_pm4_set_reg(pm4, R_028A48_PA_SC_MODE_CNTL_0,
908                        S_028A48_LINE_STIPPLE_ENABLE(state->line_stipple_enable) |
909                        S_028A48_MSAA_ENABLE(state->multisample ||
910                                             state->poly_smooth ||
911                                             state->line_smooth) |
912                        S_028A48_VPORT_SCISSOR_ENABLE(1) |
913                        S_028A48_ALTERNATE_RBS_PER_TILE(sscreen->info.chip_class >= GFX9));
914
915         si_pm4_set_reg(pm4, R_028BE4_PA_SU_VTX_CNTL,
916                        S_028BE4_PIX_CENTER(state->half_pixel_center) |
917                        S_028BE4_QUANT_MODE(V_028BE4_X_16_8_FIXED_POINT_1_256TH));
918
919         si_pm4_set_reg(pm4, R_028B7C_PA_SU_POLY_OFFSET_CLAMP, fui(state->offset_clamp));
920         si_pm4_set_reg(pm4, R_028814_PA_SU_SC_MODE_CNTL,
921                 S_028814_PROVOKING_VTX_LAST(!state->flatshade_first) |
922                 S_028814_CULL_FRONT((state->cull_face & PIPE_FACE_FRONT) ? 1 : 0) |
923                 S_028814_CULL_BACK((state->cull_face & PIPE_FACE_BACK) ? 1 : 0) |
924                 S_028814_FACE(!state->front_ccw) |
925                 S_028814_POLY_OFFSET_FRONT_ENABLE(util_get_offset(state, state->fill_front)) |
926                 S_028814_POLY_OFFSET_BACK_ENABLE(util_get_offset(state, state->fill_back)) |
927                 S_028814_POLY_OFFSET_PARA_ENABLE(state->offset_point || state->offset_line) |
928                 S_028814_POLY_MODE(state->fill_front != PIPE_POLYGON_MODE_FILL ||
929                                    state->fill_back != PIPE_POLYGON_MODE_FILL) |
930                 S_028814_POLYMODE_FRONT_PTYPE(si_translate_fill(state->fill_front)) |
931                 S_028814_POLYMODE_BACK_PTYPE(si_translate_fill(state->fill_back)));
932
933         if (!rs->uses_poly_offset)
934                 return rs;
935
936         rs->pm4_poly_offset = CALLOC(3, sizeof(struct si_pm4_state));
937         if (!rs->pm4_poly_offset) {
938                 FREE(rs);
939                 return NULL;
940         }
941
942         /* Precalculate polygon offset states for 16-bit, 24-bit, and 32-bit zbuffers. */
943         for (i = 0; i < 3; i++) {
944                 struct si_pm4_state *pm4 = &rs->pm4_poly_offset[i];
945                 float offset_units = state->offset_units;
946                 float offset_scale = state->offset_scale * 16.0f;
947                 uint32_t pa_su_poly_offset_db_fmt_cntl = 0;
948
949                 if (!state->offset_units_unscaled) {
950                         switch (i) {
951                         case 0: /* 16-bit zbuffer */
952                                 offset_units *= 4.0f;
953                                 pa_su_poly_offset_db_fmt_cntl =
954                                         S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
955                                 break;
956                         case 1: /* 24-bit zbuffer */
957                                 offset_units *= 2.0f;
958                                 pa_su_poly_offset_db_fmt_cntl =
959                                         S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
960                                 break;
961                         case 2: /* 32-bit zbuffer */
962                                 offset_units *= 1.0f;
963                                 pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
964                                                                 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
965                                 break;
966                         }
967                 }
968
969                 si_pm4_set_reg(pm4, R_028B80_PA_SU_POLY_OFFSET_FRONT_SCALE,
970                                fui(offset_scale));
971                 si_pm4_set_reg(pm4, R_028B84_PA_SU_POLY_OFFSET_FRONT_OFFSET,
972                                fui(offset_units));
973                 si_pm4_set_reg(pm4, R_028B88_PA_SU_POLY_OFFSET_BACK_SCALE,
974                                fui(offset_scale));
975                 si_pm4_set_reg(pm4, R_028B8C_PA_SU_POLY_OFFSET_BACK_OFFSET,
976                                fui(offset_units));
977                 si_pm4_set_reg(pm4, R_028B78_PA_SU_POLY_OFFSET_DB_FMT_CNTL,
978                                pa_su_poly_offset_db_fmt_cntl);
979         }
980
981         return rs;
982 }
983
984 static void si_bind_rs_state(struct pipe_context *ctx, void *state)
985 {
986         struct si_context *sctx = (struct si_context *)ctx;
987         struct si_state_rasterizer *old_rs =
988                 (struct si_state_rasterizer*)sctx->queued.named.rasterizer;
989         struct si_state_rasterizer *rs = (struct si_state_rasterizer *)state;
990
991         if (!state)
992                 return;
993
994         if (!old_rs || old_rs->multisample_enable != rs->multisample_enable) {
995                 si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
996
997                 /* Update the small primitive filter workaround if necessary. */
998                 if (sctx->screen->has_msaa_sample_loc_bug &&
999                     sctx->framebuffer.nr_samples > 1)
1000                         si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_sample_locs);
1001         }
1002
1003         sctx->current_vs_state &= C_VS_STATE_CLAMP_VERTEX_COLOR;
1004         sctx->current_vs_state |= S_VS_STATE_CLAMP_VERTEX_COLOR(rs->clamp_vertex_color);
1005
1006         si_pm4_bind_state(sctx, rasterizer, rs);
1007         si_update_poly_offset_state(sctx);
1008
1009         if (!old_rs ||
1010             old_rs->scissor_enable != rs->scissor_enable) {
1011                 sctx->scissors.dirty_mask = (1 << SI_MAX_VIEWPORTS) - 1;
1012                 si_mark_atom_dirty(sctx, &sctx->atoms.s.scissors);
1013         }
1014
1015         if (!old_rs ||
1016             old_rs->line_width != rs->line_width ||
1017             old_rs->max_point_size != rs->max_point_size)
1018                 si_mark_atom_dirty(sctx, &sctx->atoms.s.guardband);
1019
1020         if (!old_rs ||
1021             old_rs->clip_halfz != rs->clip_halfz) {
1022                 sctx->viewports.depth_range_dirty_mask = (1 << SI_MAX_VIEWPORTS) - 1;
1023                 si_mark_atom_dirty(sctx, &sctx->atoms.s.viewports);
1024         }
1025
1026         if (!old_rs ||
1027             old_rs->clip_plane_enable != rs->clip_plane_enable ||
1028             old_rs->pa_cl_clip_cntl != rs->pa_cl_clip_cntl)
1029                 si_mark_atom_dirty(sctx, &sctx->atoms.s.clip_regs);
1030
1031         sctx->ia_multi_vgt_param_key.u.line_stipple_enabled =
1032                 rs->line_stipple_enable;
1033
1034         if (!old_rs ||
1035             old_rs->clip_plane_enable != rs->clip_plane_enable ||
1036             old_rs->rasterizer_discard != rs->rasterizer_discard ||
1037             old_rs->sprite_coord_enable != rs->sprite_coord_enable ||
1038             old_rs->flatshade != rs->flatshade ||
1039             old_rs->two_side != rs->two_side ||
1040             old_rs->multisample_enable != rs->multisample_enable ||
1041             old_rs->poly_stipple_enable != rs->poly_stipple_enable ||
1042             old_rs->poly_smooth != rs->poly_smooth ||
1043             old_rs->line_smooth != rs->line_smooth ||
1044             old_rs->clamp_fragment_color != rs->clamp_fragment_color ||
1045             old_rs->force_persample_interp != rs->force_persample_interp)
1046                 sctx->do_update_shaders = true;
1047 }
1048
1049 static void si_delete_rs_state(struct pipe_context *ctx, void *state)
1050 {
1051         struct si_context *sctx = (struct si_context *)ctx;
1052         struct si_state_rasterizer *rs = (struct si_state_rasterizer *)state;
1053
1054         if (sctx->queued.named.rasterizer == state)
1055                 si_pm4_bind_state(sctx, poly_offset, NULL);
1056
1057         FREE(rs->pm4_poly_offset);
1058         si_pm4_delete_state(sctx, rasterizer, rs);
1059 }
1060
1061 /*
1062  * infeered state between dsa and stencil ref
1063  */
1064 static void si_emit_stencil_ref(struct si_context *sctx)
1065 {
1066         struct radeon_cmdbuf *cs = sctx->gfx_cs;
1067         struct pipe_stencil_ref *ref = &sctx->stencil_ref.state;
1068         struct si_dsa_stencil_ref_part *dsa = &sctx->stencil_ref.dsa_part;
1069
1070         radeon_set_context_reg_seq(cs, R_028430_DB_STENCILREFMASK, 2);
1071         radeon_emit(cs, S_028430_STENCILTESTVAL(ref->ref_value[0]) |
1072                         S_028430_STENCILMASK(dsa->valuemask[0]) |
1073                         S_028430_STENCILWRITEMASK(dsa->writemask[0]) |
1074                         S_028430_STENCILOPVAL(1));
1075         radeon_emit(cs, S_028434_STENCILTESTVAL_BF(ref->ref_value[1]) |
1076                         S_028434_STENCILMASK_BF(dsa->valuemask[1]) |
1077                         S_028434_STENCILWRITEMASK_BF(dsa->writemask[1]) |
1078                         S_028434_STENCILOPVAL_BF(1));
1079 }
1080
1081 static void si_set_stencil_ref(struct pipe_context *ctx,
1082                                const struct pipe_stencil_ref *state)
1083 {
1084         struct si_context *sctx = (struct si_context *)ctx;
1085
1086         if (memcmp(&sctx->stencil_ref.state, state, sizeof(*state)) == 0)
1087                 return;
1088
1089         sctx->stencil_ref.state = *state;
1090         si_mark_atom_dirty(sctx, &sctx->atoms.s.stencil_ref);
1091 }
1092
1093
1094 /*
1095  * DSA
1096  */
1097
1098 static uint32_t si_translate_stencil_op(int s_op)
1099 {
1100         switch (s_op) {
1101         case PIPE_STENCIL_OP_KEEP:
1102                 return V_02842C_STENCIL_KEEP;
1103         case PIPE_STENCIL_OP_ZERO:
1104                 return V_02842C_STENCIL_ZERO;
1105         case PIPE_STENCIL_OP_REPLACE:
1106                 return V_02842C_STENCIL_REPLACE_TEST;
1107         case PIPE_STENCIL_OP_INCR:
1108                 return V_02842C_STENCIL_ADD_CLAMP;
1109         case PIPE_STENCIL_OP_DECR:
1110                 return V_02842C_STENCIL_SUB_CLAMP;
1111         case PIPE_STENCIL_OP_INCR_WRAP:
1112                 return V_02842C_STENCIL_ADD_WRAP;
1113         case PIPE_STENCIL_OP_DECR_WRAP:
1114                 return V_02842C_STENCIL_SUB_WRAP;
1115         case PIPE_STENCIL_OP_INVERT:
1116                 return V_02842C_STENCIL_INVERT;
1117         default:
1118                 PRINT_ERR("Unknown stencil op %d", s_op);
1119                 assert(0);
1120                 break;
1121         }
1122         return 0;
1123 }
1124
1125 static bool si_dsa_writes_stencil(const struct pipe_stencil_state *s)
1126 {
1127         return s->enabled && s->writemask &&
1128                (s->fail_op  != PIPE_STENCIL_OP_KEEP ||
1129                 s->zfail_op != PIPE_STENCIL_OP_KEEP ||
1130                 s->zpass_op != PIPE_STENCIL_OP_KEEP);
1131 }
1132
1133 static bool si_order_invariant_stencil_op(enum pipe_stencil_op op)
1134 {
1135         /* REPLACE is normally order invariant, except when the stencil
1136          * reference value is written by the fragment shader. Tracking this
1137          * interaction does not seem worth the effort, so be conservative. */
1138         return op != PIPE_STENCIL_OP_INCR &&
1139                op != PIPE_STENCIL_OP_DECR &&
1140                op != PIPE_STENCIL_OP_REPLACE;
1141 }
1142
1143 /* Compute whether, assuming Z writes are disabled, this stencil state is order
1144  * invariant in the sense that the set of passing fragments as well as the
1145  * final stencil buffer result does not depend on the order of fragments. */
1146 static bool si_order_invariant_stencil_state(const struct pipe_stencil_state *state)
1147 {
1148         return !state->enabled || !state->writemask ||
1149                /* The following assumes that Z writes are disabled. */
1150                (state->func == PIPE_FUNC_ALWAYS &&
1151                 si_order_invariant_stencil_op(state->zpass_op) &&
1152                 si_order_invariant_stencil_op(state->zfail_op)) ||
1153                (state->func == PIPE_FUNC_NEVER &&
1154                 si_order_invariant_stencil_op(state->fail_op));
1155 }
1156
1157 static void *si_create_dsa_state(struct pipe_context *ctx,
1158                                  const struct pipe_depth_stencil_alpha_state *state)
1159 {
1160         struct si_context *sctx = (struct si_context *)ctx;
1161         struct si_state_dsa *dsa = CALLOC_STRUCT(si_state_dsa);
1162         struct si_pm4_state *pm4 = &dsa->pm4;
1163         unsigned db_depth_control;
1164         uint32_t db_stencil_control = 0;
1165
1166         if (!dsa) {
1167                 return NULL;
1168         }
1169
1170         dsa->stencil_ref.valuemask[0] = state->stencil[0].valuemask;
1171         dsa->stencil_ref.valuemask[1] = state->stencil[1].valuemask;
1172         dsa->stencil_ref.writemask[0] = state->stencil[0].writemask;
1173         dsa->stencil_ref.writemask[1] = state->stencil[1].writemask;
1174
1175         db_depth_control = S_028800_Z_ENABLE(state->depth.enabled) |
1176                 S_028800_Z_WRITE_ENABLE(state->depth.writemask) |
1177                 S_028800_ZFUNC(state->depth.func) |
1178                 S_028800_DEPTH_BOUNDS_ENABLE(state->depth.bounds_test);
1179
1180         /* stencil */
1181         if (state->stencil[0].enabled) {
1182                 db_depth_control |= S_028800_STENCIL_ENABLE(1);
1183                 db_depth_control |= S_028800_STENCILFUNC(state->stencil[0].func);
1184                 db_stencil_control |= S_02842C_STENCILFAIL(si_translate_stencil_op(state->stencil[0].fail_op));
1185                 db_stencil_control |= S_02842C_STENCILZPASS(si_translate_stencil_op(state->stencil[0].zpass_op));
1186                 db_stencil_control |= S_02842C_STENCILZFAIL(si_translate_stencil_op(state->stencil[0].zfail_op));
1187
1188                 if (state->stencil[1].enabled) {
1189                         db_depth_control |= S_028800_BACKFACE_ENABLE(1);
1190                         db_depth_control |= S_028800_STENCILFUNC_BF(state->stencil[1].func);
1191                         db_stencil_control |= S_02842C_STENCILFAIL_BF(si_translate_stencil_op(state->stencil[1].fail_op));
1192                         db_stencil_control |= S_02842C_STENCILZPASS_BF(si_translate_stencil_op(state->stencil[1].zpass_op));
1193                         db_stencil_control |= S_02842C_STENCILZFAIL_BF(si_translate_stencil_op(state->stencil[1].zfail_op));
1194                 }
1195         }
1196
1197         /* alpha */
1198         if (state->alpha.enabled) {
1199                 dsa->alpha_func = state->alpha.func;
1200
1201                 si_pm4_set_reg(pm4, R_00B030_SPI_SHADER_USER_DATA_PS_0 +
1202                                SI_SGPR_ALPHA_REF * 4, fui(state->alpha.ref_value));
1203         } else {
1204                 dsa->alpha_func = PIPE_FUNC_ALWAYS;
1205         }
1206
1207         si_pm4_set_reg(pm4, R_028800_DB_DEPTH_CONTROL, db_depth_control);
1208         if (state->stencil[0].enabled)
1209                 si_pm4_set_reg(pm4, R_02842C_DB_STENCIL_CONTROL, db_stencil_control);
1210         if (state->depth.bounds_test) {
1211                 si_pm4_set_reg(pm4, R_028020_DB_DEPTH_BOUNDS_MIN, fui(state->depth.bounds_min));
1212                 si_pm4_set_reg(pm4, R_028024_DB_DEPTH_BOUNDS_MAX, fui(state->depth.bounds_max));
1213         }
1214
1215         dsa->depth_enabled = state->depth.enabled;
1216         dsa->depth_write_enabled = state->depth.enabled &&
1217                                    state->depth.writemask;
1218         dsa->stencil_enabled = state->stencil[0].enabled;
1219         dsa->stencil_write_enabled = state->stencil[0].enabled &&
1220                                      (si_dsa_writes_stencil(&state->stencil[0]) ||
1221                                       si_dsa_writes_stencil(&state->stencil[1]));
1222         dsa->db_can_write = dsa->depth_write_enabled ||
1223                             dsa->stencil_write_enabled;
1224
1225         bool zfunc_is_ordered =
1226                 state->depth.func == PIPE_FUNC_NEVER ||
1227                 state->depth.func == PIPE_FUNC_LESS ||
1228                 state->depth.func == PIPE_FUNC_LEQUAL ||
1229                 state->depth.func == PIPE_FUNC_GREATER ||
1230                 state->depth.func == PIPE_FUNC_GEQUAL;
1231
1232         bool nozwrite_and_order_invariant_stencil =
1233                 !dsa->db_can_write ||
1234                 (!dsa->depth_write_enabled &&
1235                  si_order_invariant_stencil_state(&state->stencil[0]) &&
1236                  si_order_invariant_stencil_state(&state->stencil[1]));
1237
1238         dsa->order_invariance[1].zs =
1239                 nozwrite_and_order_invariant_stencil ||
1240                 (!dsa->stencil_write_enabled && zfunc_is_ordered);
1241         dsa->order_invariance[0].zs = !dsa->depth_write_enabled || zfunc_is_ordered;
1242
1243         dsa->order_invariance[1].pass_set =
1244                 nozwrite_and_order_invariant_stencil ||
1245                 (!dsa->stencil_write_enabled &&
1246                  (state->depth.func == PIPE_FUNC_ALWAYS ||
1247                   state->depth.func == PIPE_FUNC_NEVER));
1248         dsa->order_invariance[0].pass_set =
1249                 !dsa->depth_write_enabled ||
1250                 (state->depth.func == PIPE_FUNC_ALWAYS ||
1251                  state->depth.func == PIPE_FUNC_NEVER);
1252
1253         dsa->order_invariance[1].pass_last =
1254                 sctx->screen->assume_no_z_fights &&
1255                 !dsa->stencil_write_enabled &&
1256                 dsa->depth_write_enabled && zfunc_is_ordered;
1257         dsa->order_invariance[0].pass_last =
1258                 sctx->screen->assume_no_z_fights &&
1259                 dsa->depth_write_enabled && zfunc_is_ordered;
1260
1261         return dsa;
1262 }
1263
1264 static void si_bind_dsa_state(struct pipe_context *ctx, void *state)
1265 {
1266         struct si_context *sctx = (struct si_context *)ctx;
1267         struct si_state_dsa *old_dsa = sctx->queued.named.dsa;
1268         struct si_state_dsa *dsa = state;
1269
1270         if (!state)
1271                 return;
1272
1273         si_pm4_bind_state(sctx, dsa, dsa);
1274
1275         if (memcmp(&dsa->stencil_ref, &sctx->stencil_ref.dsa_part,
1276                    sizeof(struct si_dsa_stencil_ref_part)) != 0) {
1277                 sctx->stencil_ref.dsa_part = dsa->stencil_ref;
1278                 si_mark_atom_dirty(sctx, &sctx->atoms.s.stencil_ref);
1279         }
1280
1281         if (!old_dsa || old_dsa->alpha_func != dsa->alpha_func)
1282                 sctx->do_update_shaders = true;
1283
1284         if (sctx->screen->dpbb_allowed &&
1285             (!old_dsa ||
1286              (old_dsa->depth_enabled != dsa->depth_enabled ||
1287               old_dsa->stencil_enabled != dsa->stencil_enabled ||
1288               old_dsa->db_can_write != dsa->db_can_write)))
1289                 si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
1290
1291         if (sctx->screen->has_out_of_order_rast &&
1292             (!old_dsa ||
1293              memcmp(old_dsa->order_invariance, dsa->order_invariance,
1294                     sizeof(old_dsa->order_invariance))))
1295                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
1296 }
1297
1298 static void si_delete_dsa_state(struct pipe_context *ctx, void *state)
1299 {
1300         struct si_context *sctx = (struct si_context *)ctx;
1301         si_pm4_delete_state(sctx, dsa, (struct si_state_dsa *)state);
1302 }
1303
1304 static void *si_create_db_flush_dsa(struct si_context *sctx)
1305 {
1306         struct pipe_depth_stencil_alpha_state dsa = {};
1307
1308         return sctx->b.create_depth_stencil_alpha_state(&sctx->b, &dsa);
1309 }
1310
1311 /* DB RENDER STATE */
1312
1313 static void si_set_active_query_state(struct pipe_context *ctx, boolean enable)
1314 {
1315         struct si_context *sctx = (struct si_context*)ctx;
1316
1317         /* Pipeline stat & streamout queries. */
1318         if (enable) {
1319                 sctx->flags &= ~SI_CONTEXT_STOP_PIPELINE_STATS;
1320                 sctx->flags |= SI_CONTEXT_START_PIPELINE_STATS;
1321         } else {
1322                 sctx->flags &= ~SI_CONTEXT_START_PIPELINE_STATS;
1323                 sctx->flags |= SI_CONTEXT_STOP_PIPELINE_STATS;
1324         }
1325
1326         /* Occlusion queries. */
1327         if (sctx->occlusion_queries_disabled != !enable) {
1328                 sctx->occlusion_queries_disabled = !enable;
1329                 si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
1330         }
1331 }
1332
1333 void si_set_occlusion_query_state(struct si_context *sctx,
1334                                   bool old_perfect_enable)
1335 {
1336         si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
1337
1338         bool perfect_enable = sctx->num_perfect_occlusion_queries != 0;
1339
1340         if (perfect_enable != old_perfect_enable)
1341                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
1342 }
1343
1344 void si_save_qbo_state(struct si_context *sctx, struct si_qbo_state *st)
1345 {
1346         st->saved_compute = sctx->cs_shader_state.program;
1347
1348         si_get_pipe_constant_buffer(sctx, PIPE_SHADER_COMPUTE, 0, &st->saved_const0);
1349         si_get_shader_buffers(sctx, PIPE_SHADER_COMPUTE, 0, 3, st->saved_ssbo);
1350 }
1351
1352 static void si_emit_db_render_state(struct si_context *sctx)
1353 {
1354         struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
1355         unsigned db_shader_control, db_render_control, db_count_control;
1356
1357         /* DB_RENDER_CONTROL */
1358         if (sctx->dbcb_depth_copy_enabled ||
1359             sctx->dbcb_stencil_copy_enabled) {
1360                 db_render_control =
1361                         S_028000_DEPTH_COPY(sctx->dbcb_depth_copy_enabled) |
1362                         S_028000_STENCIL_COPY(sctx->dbcb_stencil_copy_enabled) |
1363                         S_028000_COPY_CENTROID(1) |
1364                         S_028000_COPY_SAMPLE(sctx->dbcb_copy_sample);
1365         } else if (sctx->db_flush_depth_inplace || sctx->db_flush_stencil_inplace) {
1366                 db_render_control =
1367                         S_028000_DEPTH_COMPRESS_DISABLE(sctx->db_flush_depth_inplace) |
1368                         S_028000_STENCIL_COMPRESS_DISABLE(sctx->db_flush_stencil_inplace);
1369         } else {
1370                 db_render_control =
1371                         S_028000_DEPTH_CLEAR_ENABLE(sctx->db_depth_clear) |
1372                         S_028000_STENCIL_CLEAR_ENABLE(sctx->db_stencil_clear);
1373         }
1374
1375         /* DB_COUNT_CONTROL (occlusion queries) */
1376         if (sctx->num_occlusion_queries > 0 &&
1377             !sctx->occlusion_queries_disabled) {
1378                 bool perfect = sctx->num_perfect_occlusion_queries > 0;
1379
1380                 if (sctx->chip_class >= CIK) {
1381                         unsigned log_sample_rate = sctx->framebuffer.log_samples;
1382
1383                         /* Stoney doesn't increment occlusion query counters
1384                          * if the sample rate is 16x. Use 8x sample rate instead.
1385                          */
1386                         if (sctx->family == CHIP_STONEY)
1387                                 log_sample_rate = MIN2(log_sample_rate, 3);
1388
1389                         db_count_control =
1390                                 S_028004_PERFECT_ZPASS_COUNTS(perfect) |
1391                                 S_028004_SAMPLE_RATE(log_sample_rate) |
1392                                 S_028004_ZPASS_ENABLE(1) |
1393                                 S_028004_SLICE_EVEN_ENABLE(1) |
1394                                 S_028004_SLICE_ODD_ENABLE(1);
1395                 } else {
1396                         db_count_control =
1397                                 S_028004_PERFECT_ZPASS_COUNTS(perfect) |
1398                                 S_028004_SAMPLE_RATE(sctx->framebuffer.log_samples);
1399                 }
1400         } else {
1401                 /* Disable occlusion queries. */
1402                 if (sctx->chip_class >= CIK) {
1403                         db_count_control = 0;
1404                 } else {
1405                         db_count_control = S_028004_ZPASS_INCREMENT_DISABLE(1);
1406                 }
1407         }
1408
1409         radeon_opt_set_context_reg2(sctx, R_028000_DB_RENDER_CONTROL,
1410                                     SI_TRACKED_DB_RENDER_CONTROL, db_render_control,
1411                                     db_count_control);
1412
1413         /* DB_RENDER_OVERRIDE2 */
1414         radeon_opt_set_context_reg(sctx,  R_028010_DB_RENDER_OVERRIDE2,
1415                 SI_TRACKED_DB_RENDER_OVERRIDE2,
1416                 S_028010_DISABLE_ZMASK_EXPCLEAR_OPTIMIZATION(sctx->db_depth_disable_expclear) |
1417                 S_028010_DISABLE_SMEM_EXPCLEAR_OPTIMIZATION(sctx->db_stencil_disable_expclear) |
1418                 S_028010_DECOMPRESS_Z_ON_FLUSH(sctx->framebuffer.nr_samples >= 4));
1419
1420         db_shader_control = sctx->ps_db_shader_control;
1421
1422         /* Bug workaround for smoothing (overrasterization) on SI. */
1423         if (sctx->chip_class == SI && sctx->smoothing_enabled) {
1424                 db_shader_control &= C_02880C_Z_ORDER;
1425                 db_shader_control |= S_02880C_Z_ORDER(V_02880C_LATE_Z);
1426         }
1427
1428         /* Disable the gl_SampleMask fragment shader output if MSAA is disabled. */
1429         if (!rs->multisample_enable)
1430                 db_shader_control &= C_02880C_MASK_EXPORT_ENABLE;
1431
1432         if (sctx->screen->has_rbplus &&
1433             !sctx->screen->rbplus_allowed)
1434                 db_shader_control |= S_02880C_DUAL_QUAD_DISABLE(1);
1435
1436         radeon_opt_set_context_reg(sctx, R_02880C_DB_SHADER_CONTROL,
1437                                    SI_TRACKED_DB_SHADER_CONTROL, db_shader_control);
1438 }
1439
1440 /*
1441  * format translation
1442  */
1443 static uint32_t si_translate_colorformat(enum pipe_format format)
1444 {
1445         const struct util_format_description *desc = util_format_description(format);
1446         if (!desc)
1447                 return V_028C70_COLOR_INVALID;
1448
1449 #define HAS_SIZE(x,y,z,w) \
1450         (desc->channel[0].size == (x) && desc->channel[1].size == (y) && \
1451          desc->channel[2].size == (z) && desc->channel[3].size == (w))
1452
1453         if (format == PIPE_FORMAT_R11G11B10_FLOAT) /* isn't plain */
1454                 return V_028C70_COLOR_10_11_11;
1455
1456         if (desc->layout != UTIL_FORMAT_LAYOUT_PLAIN)
1457                 return V_028C70_COLOR_INVALID;
1458
1459         /* hw cannot support mixed formats (except depth/stencil, since
1460          * stencil is not written to). */
1461         if (desc->is_mixed && desc->colorspace != UTIL_FORMAT_COLORSPACE_ZS)
1462                 return V_028C70_COLOR_INVALID;
1463
1464         switch (desc->nr_channels) {
1465         case 1:
1466                 switch (desc->channel[0].size) {
1467                 case 8:
1468                         return V_028C70_COLOR_8;
1469                 case 16:
1470                         return V_028C70_COLOR_16;
1471                 case 32:
1472                         return V_028C70_COLOR_32;
1473                 }
1474                 break;
1475         case 2:
1476                 if (desc->channel[0].size == desc->channel[1].size) {
1477                         switch (desc->channel[0].size) {
1478                         case 8:
1479                                 return V_028C70_COLOR_8_8;
1480                         case 16:
1481                                 return V_028C70_COLOR_16_16;
1482                         case 32:
1483                                 return V_028C70_COLOR_32_32;
1484                         }
1485                 } else if (HAS_SIZE(8,24,0,0)) {
1486                         return V_028C70_COLOR_24_8;
1487                 } else if (HAS_SIZE(24,8,0,0)) {
1488                         return V_028C70_COLOR_8_24;
1489                 }
1490                 break;
1491         case 3:
1492                 if (HAS_SIZE(5,6,5,0)) {
1493                         return V_028C70_COLOR_5_6_5;
1494                 } else if (HAS_SIZE(32,8,24,0)) {
1495                         return V_028C70_COLOR_X24_8_32_FLOAT;
1496                 }
1497                 break;
1498         case 4:
1499                 if (desc->channel[0].size == desc->channel[1].size &&
1500                     desc->channel[0].size == desc->channel[2].size &&
1501                     desc->channel[0].size == desc->channel[3].size) {
1502                         switch (desc->channel[0].size) {
1503                         case 4:
1504                                 return V_028C70_COLOR_4_4_4_4;
1505                         case 8:
1506                                 return V_028C70_COLOR_8_8_8_8;
1507                         case 16:
1508                                 return V_028C70_COLOR_16_16_16_16;
1509                         case 32:
1510                                 return V_028C70_COLOR_32_32_32_32;
1511                         }
1512                 } else if (HAS_SIZE(5,5,5,1)) {
1513                         return V_028C70_COLOR_1_5_5_5;
1514                 } else if (HAS_SIZE(1,5,5,5)) {
1515                         return V_028C70_COLOR_5_5_5_1;
1516                 } else if (HAS_SIZE(10,10,10,2)) {
1517                         return V_028C70_COLOR_2_10_10_10;
1518                 }
1519                 break;
1520         }
1521         return V_028C70_COLOR_INVALID;
1522 }
1523
1524 static uint32_t si_colorformat_endian_swap(uint32_t colorformat)
1525 {
1526         if (SI_BIG_ENDIAN) {
1527                 switch(colorformat) {
1528                 /* 8-bit buffers. */
1529                 case V_028C70_COLOR_8:
1530                         return V_028C70_ENDIAN_NONE;
1531
1532                 /* 16-bit buffers. */
1533                 case V_028C70_COLOR_5_6_5:
1534                 case V_028C70_COLOR_1_5_5_5:
1535                 case V_028C70_COLOR_4_4_4_4:
1536                 case V_028C70_COLOR_16:
1537                 case V_028C70_COLOR_8_8:
1538                         return V_028C70_ENDIAN_8IN16;
1539
1540                 /* 32-bit buffers. */
1541                 case V_028C70_COLOR_8_8_8_8:
1542                 case V_028C70_COLOR_2_10_10_10:
1543                 case V_028C70_COLOR_8_24:
1544                 case V_028C70_COLOR_24_8:
1545                 case V_028C70_COLOR_16_16:
1546                         return V_028C70_ENDIAN_8IN32;
1547
1548                 /* 64-bit buffers. */
1549                 case V_028C70_COLOR_16_16_16_16:
1550                         return V_028C70_ENDIAN_8IN16;
1551
1552                 case V_028C70_COLOR_32_32:
1553                         return V_028C70_ENDIAN_8IN32;
1554
1555                 /* 128-bit buffers. */
1556                 case V_028C70_COLOR_32_32_32_32:
1557                         return V_028C70_ENDIAN_8IN32;
1558                 default:
1559                         return V_028C70_ENDIAN_NONE; /* Unsupported. */
1560                 }
1561         } else {
1562                 return V_028C70_ENDIAN_NONE;
1563         }
1564 }
1565
1566 static uint32_t si_translate_dbformat(enum pipe_format format)
1567 {
1568         switch (format) {
1569         case PIPE_FORMAT_Z16_UNORM:
1570                 return V_028040_Z_16;
1571         case PIPE_FORMAT_S8_UINT_Z24_UNORM:
1572         case PIPE_FORMAT_X8Z24_UNORM:
1573         case PIPE_FORMAT_Z24X8_UNORM:
1574         case PIPE_FORMAT_Z24_UNORM_S8_UINT:
1575                 return V_028040_Z_24; /* deprecated on SI */
1576         case PIPE_FORMAT_Z32_FLOAT:
1577         case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
1578                 return V_028040_Z_32_FLOAT;
1579         default:
1580                 return V_028040_Z_INVALID;
1581         }
1582 }
1583
1584 /*
1585  * Texture translation
1586  */
1587
1588 static uint32_t si_translate_texformat(struct pipe_screen *screen,
1589                                        enum pipe_format format,
1590                                        const struct util_format_description *desc,
1591                                        int first_non_void)
1592 {
1593         struct si_screen *sscreen = (struct si_screen*)screen;
1594         bool uniform = true;
1595         int i;
1596
1597         /* Colorspace (return non-RGB formats directly). */
1598         switch (desc->colorspace) {
1599         /* Depth stencil formats */
1600         case UTIL_FORMAT_COLORSPACE_ZS:
1601                 switch (format) {
1602                 case PIPE_FORMAT_Z16_UNORM:
1603                         return V_008F14_IMG_DATA_FORMAT_16;
1604                 case PIPE_FORMAT_X24S8_UINT:
1605                 case PIPE_FORMAT_S8X24_UINT:
1606                         /*
1607                          * Implemented as an 8_8_8_8 data format to fix texture
1608                          * gathers in stencil sampling. This affects at least
1609                          * GL45-CTS.texture_cube_map_array.sampling on VI.
1610                          */
1611                         if (sscreen->info.chip_class <= VI)
1612                                 return V_008F14_IMG_DATA_FORMAT_8_8_8_8;
1613
1614                         if (format == PIPE_FORMAT_X24S8_UINT)
1615                                 return V_008F14_IMG_DATA_FORMAT_8_24;
1616                         else
1617                                 return V_008F14_IMG_DATA_FORMAT_24_8;
1618                 case PIPE_FORMAT_Z24X8_UNORM:
1619                 case PIPE_FORMAT_Z24_UNORM_S8_UINT:
1620                         return V_008F14_IMG_DATA_FORMAT_8_24;
1621                 case PIPE_FORMAT_X8Z24_UNORM:
1622                 case PIPE_FORMAT_S8_UINT_Z24_UNORM:
1623                         return V_008F14_IMG_DATA_FORMAT_24_8;
1624                 case PIPE_FORMAT_S8_UINT:
1625                         return V_008F14_IMG_DATA_FORMAT_8;
1626                 case PIPE_FORMAT_Z32_FLOAT:
1627                         return V_008F14_IMG_DATA_FORMAT_32;
1628                 case PIPE_FORMAT_X32_S8X24_UINT:
1629                 case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
1630                         return V_008F14_IMG_DATA_FORMAT_X24_8_32;
1631                 default:
1632                         goto out_unknown;
1633                 }
1634
1635         case UTIL_FORMAT_COLORSPACE_YUV:
1636                 goto out_unknown; /* TODO */
1637
1638         case UTIL_FORMAT_COLORSPACE_SRGB:
1639                 if (desc->nr_channels != 4 && desc->nr_channels != 1)
1640                         goto out_unknown;
1641                 break;
1642
1643         default:
1644                 break;
1645         }
1646
1647         if (desc->layout == UTIL_FORMAT_LAYOUT_RGTC) {
1648                 if (!sscreen->info.has_format_bc1_through_bc7)
1649                         goto out_unknown;
1650
1651                 switch (format) {
1652                 case PIPE_FORMAT_RGTC1_SNORM:
1653                 case PIPE_FORMAT_LATC1_SNORM:
1654                 case PIPE_FORMAT_RGTC1_UNORM:
1655                 case PIPE_FORMAT_LATC1_UNORM:
1656                         return V_008F14_IMG_DATA_FORMAT_BC4;
1657                 case PIPE_FORMAT_RGTC2_SNORM:
1658                 case PIPE_FORMAT_LATC2_SNORM:
1659                 case PIPE_FORMAT_RGTC2_UNORM:
1660                 case PIPE_FORMAT_LATC2_UNORM:
1661                         return V_008F14_IMG_DATA_FORMAT_BC5;
1662                 default:
1663                         goto out_unknown;
1664                 }
1665         }
1666
1667         if (desc->layout == UTIL_FORMAT_LAYOUT_ETC &&
1668             (sscreen->info.family == CHIP_STONEY ||
1669              sscreen->info.family == CHIP_VEGA10 ||
1670              sscreen->info.family == CHIP_RAVEN)) {
1671                 switch (format) {
1672                 case PIPE_FORMAT_ETC1_RGB8:
1673                 case PIPE_FORMAT_ETC2_RGB8:
1674                 case PIPE_FORMAT_ETC2_SRGB8:
1675                         return V_008F14_IMG_DATA_FORMAT_ETC2_RGB;
1676                 case PIPE_FORMAT_ETC2_RGB8A1:
1677                 case PIPE_FORMAT_ETC2_SRGB8A1:
1678                         return V_008F14_IMG_DATA_FORMAT_ETC2_RGBA1;
1679                 case PIPE_FORMAT_ETC2_RGBA8:
1680                 case PIPE_FORMAT_ETC2_SRGBA8:
1681                         return V_008F14_IMG_DATA_FORMAT_ETC2_RGBA;
1682                 case PIPE_FORMAT_ETC2_R11_UNORM:
1683                 case PIPE_FORMAT_ETC2_R11_SNORM:
1684                         return V_008F14_IMG_DATA_FORMAT_ETC2_R;
1685                 case PIPE_FORMAT_ETC2_RG11_UNORM:
1686                 case PIPE_FORMAT_ETC2_RG11_SNORM:
1687                         return V_008F14_IMG_DATA_FORMAT_ETC2_RG;
1688                 default:
1689                         goto out_unknown;
1690                 }
1691         }
1692
1693         if (desc->layout == UTIL_FORMAT_LAYOUT_BPTC) {
1694                 if (!sscreen->info.has_format_bc1_through_bc7)
1695                         goto out_unknown;
1696
1697                 switch (format) {
1698                 case PIPE_FORMAT_BPTC_RGBA_UNORM:
1699                 case PIPE_FORMAT_BPTC_SRGBA:
1700                         return V_008F14_IMG_DATA_FORMAT_BC7;
1701                 case PIPE_FORMAT_BPTC_RGB_FLOAT:
1702                 case PIPE_FORMAT_BPTC_RGB_UFLOAT:
1703                         return V_008F14_IMG_DATA_FORMAT_BC6;
1704                 default:
1705                         goto out_unknown;
1706                 }
1707         }
1708
1709         if (desc->layout == UTIL_FORMAT_LAYOUT_SUBSAMPLED) {
1710                 switch (format) {
1711                 case PIPE_FORMAT_R8G8_B8G8_UNORM:
1712                 case PIPE_FORMAT_G8R8_B8R8_UNORM:
1713                         return V_008F14_IMG_DATA_FORMAT_GB_GR;
1714                 case PIPE_FORMAT_G8R8_G8B8_UNORM:
1715                 case PIPE_FORMAT_R8G8_R8B8_UNORM:
1716                         return V_008F14_IMG_DATA_FORMAT_BG_RG;
1717                 default:
1718                         goto out_unknown;
1719                 }
1720         }
1721
1722         if (desc->layout == UTIL_FORMAT_LAYOUT_S3TC) {
1723                 if (!sscreen->info.has_format_bc1_through_bc7)
1724                         goto out_unknown;
1725
1726                 switch (format) {
1727                 case PIPE_FORMAT_DXT1_RGB:
1728                 case PIPE_FORMAT_DXT1_RGBA:
1729                 case PIPE_FORMAT_DXT1_SRGB:
1730                 case PIPE_FORMAT_DXT1_SRGBA:
1731                         return V_008F14_IMG_DATA_FORMAT_BC1;
1732                 case PIPE_FORMAT_DXT3_RGBA:
1733                 case PIPE_FORMAT_DXT3_SRGBA:
1734                         return V_008F14_IMG_DATA_FORMAT_BC2;
1735                 case PIPE_FORMAT_DXT5_RGBA:
1736                 case PIPE_FORMAT_DXT5_SRGBA:
1737                         return V_008F14_IMG_DATA_FORMAT_BC3;
1738                 default:
1739                         goto out_unknown;
1740                 }
1741         }
1742
1743         if (format == PIPE_FORMAT_R9G9B9E5_FLOAT) {
1744                 return V_008F14_IMG_DATA_FORMAT_5_9_9_9;
1745         } else if (format == PIPE_FORMAT_R11G11B10_FLOAT) {
1746                 return V_008F14_IMG_DATA_FORMAT_10_11_11;
1747         }
1748
1749         /* R8G8Bx_SNORM - TODO CxV8U8 */
1750
1751         /* hw cannot support mixed formats (except depth/stencil, since only
1752          * depth is read).*/
1753         if (desc->is_mixed && desc->colorspace != UTIL_FORMAT_COLORSPACE_ZS)
1754                 goto out_unknown;
1755
1756         /* See whether the components are of the same size. */
1757         for (i = 1; i < desc->nr_channels; i++) {
1758                 uniform = uniform && desc->channel[0].size == desc->channel[i].size;
1759         }
1760
1761         /* Non-uniform formats. */
1762         if (!uniform) {
1763                 switch(desc->nr_channels) {
1764                 case 3:
1765                         if (desc->channel[0].size == 5 &&
1766                             desc->channel[1].size == 6 &&
1767                             desc->channel[2].size == 5) {
1768                                 return V_008F14_IMG_DATA_FORMAT_5_6_5;
1769                         }
1770                         goto out_unknown;
1771                 case 4:
1772                         if (desc->channel[0].size == 5 &&
1773                             desc->channel[1].size == 5 &&
1774                             desc->channel[2].size == 5 &&
1775                             desc->channel[3].size == 1) {
1776                                 return V_008F14_IMG_DATA_FORMAT_1_5_5_5;
1777                         }
1778                         if (desc->channel[0].size == 1 &&
1779                             desc->channel[1].size == 5 &&
1780                             desc->channel[2].size == 5 &&
1781                             desc->channel[3].size == 5) {
1782                                 return V_008F14_IMG_DATA_FORMAT_5_5_5_1;
1783                         }
1784                         if (desc->channel[0].size == 10 &&
1785                             desc->channel[1].size == 10 &&
1786                             desc->channel[2].size == 10 &&
1787                             desc->channel[3].size == 2) {
1788                                 return V_008F14_IMG_DATA_FORMAT_2_10_10_10;
1789                         }
1790                         goto out_unknown;
1791                 }
1792                 goto out_unknown;
1793         }
1794
1795         if (first_non_void < 0 || first_non_void > 3)
1796                 goto out_unknown;
1797
1798         /* uniform formats */
1799         switch (desc->channel[first_non_void].size) {
1800         case 4:
1801                 switch (desc->nr_channels) {
1802 #if 0 /* Not supported for render targets */
1803                 case 2:
1804                         return V_008F14_IMG_DATA_FORMAT_4_4;
1805 #endif
1806                 case 4:
1807                         return V_008F14_IMG_DATA_FORMAT_4_4_4_4;
1808                 }
1809                 break;
1810         case 8:
1811                 switch (desc->nr_channels) {
1812                 case 1:
1813                         return V_008F14_IMG_DATA_FORMAT_8;
1814                 case 2:
1815                         return V_008F14_IMG_DATA_FORMAT_8_8;
1816                 case 4:
1817                         return V_008F14_IMG_DATA_FORMAT_8_8_8_8;
1818                 }
1819                 break;
1820         case 16:
1821                 switch (desc->nr_channels) {
1822                 case 1:
1823                         return V_008F14_IMG_DATA_FORMAT_16;
1824                 case 2:
1825                         return V_008F14_IMG_DATA_FORMAT_16_16;
1826                 case 4:
1827                         return V_008F14_IMG_DATA_FORMAT_16_16_16_16;
1828                 }
1829                 break;
1830         case 32:
1831                 switch (desc->nr_channels) {
1832                 case 1:
1833                         return V_008F14_IMG_DATA_FORMAT_32;
1834                 case 2:
1835                         return V_008F14_IMG_DATA_FORMAT_32_32;
1836 #if 0 /* Not supported for render targets */
1837                 case 3:
1838                         return V_008F14_IMG_DATA_FORMAT_32_32_32;
1839 #endif
1840                 case 4:
1841                         return V_008F14_IMG_DATA_FORMAT_32_32_32_32;
1842                 }
1843         }
1844
1845 out_unknown:
1846         return ~0;
1847 }
1848
1849 static unsigned si_tex_wrap(unsigned wrap)
1850 {
1851         switch (wrap) {
1852         default:
1853         case PIPE_TEX_WRAP_REPEAT:
1854                 return V_008F30_SQ_TEX_WRAP;
1855         case PIPE_TEX_WRAP_CLAMP:
1856                 return V_008F30_SQ_TEX_CLAMP_HALF_BORDER;
1857         case PIPE_TEX_WRAP_CLAMP_TO_EDGE:
1858                 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
1859         case PIPE_TEX_WRAP_CLAMP_TO_BORDER:
1860                 return V_008F30_SQ_TEX_CLAMP_BORDER;
1861         case PIPE_TEX_WRAP_MIRROR_REPEAT:
1862                 return V_008F30_SQ_TEX_MIRROR;
1863         case PIPE_TEX_WRAP_MIRROR_CLAMP:
1864                 return V_008F30_SQ_TEX_MIRROR_ONCE_HALF_BORDER;
1865         case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE:
1866                 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
1867         case PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER:
1868                 return V_008F30_SQ_TEX_MIRROR_ONCE_BORDER;
1869         }
1870 }
1871
1872 static unsigned si_tex_mipfilter(unsigned filter)
1873 {
1874         switch (filter) {
1875         case PIPE_TEX_MIPFILTER_NEAREST:
1876                 return V_008F38_SQ_TEX_Z_FILTER_POINT;
1877         case PIPE_TEX_MIPFILTER_LINEAR:
1878                 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
1879         default:
1880         case PIPE_TEX_MIPFILTER_NONE:
1881                 return V_008F38_SQ_TEX_Z_FILTER_NONE;
1882         }
1883 }
1884
1885 static unsigned si_tex_compare(unsigned compare)
1886 {
1887         switch (compare) {
1888         default:
1889         case PIPE_FUNC_NEVER:
1890                 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
1891         case PIPE_FUNC_LESS:
1892                 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
1893         case PIPE_FUNC_EQUAL:
1894                 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
1895         case PIPE_FUNC_LEQUAL:
1896                 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
1897         case PIPE_FUNC_GREATER:
1898                 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
1899         case PIPE_FUNC_NOTEQUAL:
1900                 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
1901         case PIPE_FUNC_GEQUAL:
1902                 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
1903         case PIPE_FUNC_ALWAYS:
1904                 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
1905         }
1906 }
1907
1908 static unsigned si_tex_dim(struct si_screen *sscreen, struct si_texture *tex,
1909                            unsigned view_target, unsigned nr_samples)
1910 {
1911         unsigned res_target = tex->buffer.b.b.target;
1912
1913         if (view_target == PIPE_TEXTURE_CUBE ||
1914             view_target == PIPE_TEXTURE_CUBE_ARRAY)
1915                 res_target = view_target;
1916         /* If interpreting cubemaps as something else, set 2D_ARRAY. */
1917         else if (res_target == PIPE_TEXTURE_CUBE ||
1918                  res_target == PIPE_TEXTURE_CUBE_ARRAY)
1919                 res_target = PIPE_TEXTURE_2D_ARRAY;
1920
1921         /* GFX9 allocates 1D textures as 2D. */
1922         if ((res_target == PIPE_TEXTURE_1D ||
1923              res_target == PIPE_TEXTURE_1D_ARRAY) &&
1924             sscreen->info.chip_class >= GFX9 &&
1925             tex->surface.u.gfx9.resource_type == RADEON_RESOURCE_2D) {
1926                 if (res_target == PIPE_TEXTURE_1D)
1927                         res_target = PIPE_TEXTURE_2D;
1928                 else
1929                         res_target = PIPE_TEXTURE_2D_ARRAY;
1930         }
1931
1932         switch (res_target) {
1933         default:
1934         case PIPE_TEXTURE_1D:
1935                 return V_008F1C_SQ_RSRC_IMG_1D;
1936         case PIPE_TEXTURE_1D_ARRAY:
1937                 return V_008F1C_SQ_RSRC_IMG_1D_ARRAY;
1938         case PIPE_TEXTURE_2D:
1939         case PIPE_TEXTURE_RECT:
1940                 return nr_samples > 1 ? V_008F1C_SQ_RSRC_IMG_2D_MSAA :
1941                                         V_008F1C_SQ_RSRC_IMG_2D;
1942         case PIPE_TEXTURE_2D_ARRAY:
1943                 return nr_samples > 1 ? V_008F1C_SQ_RSRC_IMG_2D_MSAA_ARRAY :
1944                                         V_008F1C_SQ_RSRC_IMG_2D_ARRAY;
1945         case PIPE_TEXTURE_3D:
1946                 return V_008F1C_SQ_RSRC_IMG_3D;
1947         case PIPE_TEXTURE_CUBE:
1948         case PIPE_TEXTURE_CUBE_ARRAY:
1949                 return V_008F1C_SQ_RSRC_IMG_CUBE;
1950         }
1951 }
1952
1953 /*
1954  * Format support testing
1955  */
1956
1957 static bool si_is_sampler_format_supported(struct pipe_screen *screen, enum pipe_format format)
1958 {
1959         const struct util_format_description *desc = util_format_description(format);
1960         if (!desc)
1961                 return false;
1962
1963         return si_translate_texformat(screen, format, desc,
1964                                       util_format_get_first_non_void_channel(format)) != ~0U;
1965 }
1966
1967 static uint32_t si_translate_buffer_dataformat(struct pipe_screen *screen,
1968                                                const struct util_format_description *desc,
1969                                                int first_non_void)
1970 {
1971         int i;
1972
1973         if (desc->format == PIPE_FORMAT_R11G11B10_FLOAT)
1974                 return V_008F0C_BUF_DATA_FORMAT_10_11_11;
1975
1976         assert(first_non_void >= 0);
1977
1978         if (desc->nr_channels == 4 &&
1979             desc->channel[0].size == 10 &&
1980             desc->channel[1].size == 10 &&
1981             desc->channel[2].size == 10 &&
1982             desc->channel[3].size == 2)
1983                 return V_008F0C_BUF_DATA_FORMAT_2_10_10_10;
1984
1985         /* See whether the components are of the same size. */
1986         for (i = 0; i < desc->nr_channels; i++) {
1987                 if (desc->channel[first_non_void].size != desc->channel[i].size)
1988                         return V_008F0C_BUF_DATA_FORMAT_INVALID;
1989         }
1990
1991         switch (desc->channel[first_non_void].size) {
1992         case 8:
1993                 switch (desc->nr_channels) {
1994                 case 1:
1995                 case 3: /* 3 loads */
1996                         return V_008F0C_BUF_DATA_FORMAT_8;
1997                 case 2:
1998                         return V_008F0C_BUF_DATA_FORMAT_8_8;
1999                 case 4:
2000                         return V_008F0C_BUF_DATA_FORMAT_8_8_8_8;
2001                 }
2002                 break;
2003         case 16:
2004                 switch (desc->nr_channels) {
2005                 case 1:
2006                 case 3: /* 3 loads */
2007                         return V_008F0C_BUF_DATA_FORMAT_16;
2008                 case 2:
2009                         return V_008F0C_BUF_DATA_FORMAT_16_16;
2010                 case 4:
2011                         return V_008F0C_BUF_DATA_FORMAT_16_16_16_16;
2012                 }
2013                 break;
2014         case 32:
2015                 switch (desc->nr_channels) {
2016                 case 1:
2017                         return V_008F0C_BUF_DATA_FORMAT_32;
2018                 case 2:
2019                         return V_008F0C_BUF_DATA_FORMAT_32_32;
2020                 case 3:
2021                         return V_008F0C_BUF_DATA_FORMAT_32_32_32;
2022                 case 4:
2023                         return V_008F0C_BUF_DATA_FORMAT_32_32_32_32;
2024                 }
2025                 break;
2026         case 64:
2027                 /* Legacy double formats. */
2028                 switch (desc->nr_channels) {
2029                 case 1: /* 1 load */
2030                         return V_008F0C_BUF_DATA_FORMAT_32_32;
2031                 case 2: /* 1 load */
2032                         return V_008F0C_BUF_DATA_FORMAT_32_32_32_32;
2033                 case 3: /* 3 loads */
2034                         return V_008F0C_BUF_DATA_FORMAT_32_32;
2035                 case 4: /* 2 loads */
2036                         return V_008F0C_BUF_DATA_FORMAT_32_32_32_32;
2037                 }
2038                 break;
2039         }
2040
2041         return V_008F0C_BUF_DATA_FORMAT_INVALID;
2042 }
2043
2044 static uint32_t si_translate_buffer_numformat(struct pipe_screen *screen,
2045                                               const struct util_format_description *desc,
2046                                               int first_non_void)
2047 {
2048         if (desc->format == PIPE_FORMAT_R11G11B10_FLOAT)
2049                 return V_008F0C_BUF_NUM_FORMAT_FLOAT;
2050
2051         assert(first_non_void >= 0);
2052
2053         switch (desc->channel[first_non_void].type) {
2054         case UTIL_FORMAT_TYPE_SIGNED:
2055         case UTIL_FORMAT_TYPE_FIXED:
2056                 if (desc->channel[first_non_void].size >= 32 ||
2057                     desc->channel[first_non_void].pure_integer)
2058                         return V_008F0C_BUF_NUM_FORMAT_SINT;
2059                 else if (desc->channel[first_non_void].normalized)
2060                         return V_008F0C_BUF_NUM_FORMAT_SNORM;
2061                 else
2062                         return V_008F0C_BUF_NUM_FORMAT_SSCALED;
2063                 break;
2064         case UTIL_FORMAT_TYPE_UNSIGNED:
2065                 if (desc->channel[first_non_void].size >= 32 ||
2066                     desc->channel[first_non_void].pure_integer)
2067                         return V_008F0C_BUF_NUM_FORMAT_UINT;
2068                 else if (desc->channel[first_non_void].normalized)
2069                         return V_008F0C_BUF_NUM_FORMAT_UNORM;
2070                 else
2071                         return V_008F0C_BUF_NUM_FORMAT_USCALED;
2072                 break;
2073         case UTIL_FORMAT_TYPE_FLOAT:
2074         default:
2075                 return V_008F0C_BUF_NUM_FORMAT_FLOAT;
2076         }
2077 }
2078
2079 static unsigned si_is_vertex_format_supported(struct pipe_screen *screen,
2080                                               enum pipe_format format,
2081                                               unsigned usage)
2082 {
2083         const struct util_format_description *desc;
2084         int first_non_void;
2085         unsigned data_format;
2086
2087         assert((usage & ~(PIPE_BIND_SHADER_IMAGE |
2088                           PIPE_BIND_SAMPLER_VIEW |
2089                           PIPE_BIND_VERTEX_BUFFER)) == 0);
2090
2091         desc = util_format_description(format);
2092         if (!desc)
2093                 return 0;
2094
2095         /* There are no native 8_8_8 or 16_16_16 data formats, and we currently
2096          * select 8_8_8_8 and 16_16_16_16 instead. This works reasonably well
2097          * for read-only access (with caveats surrounding bounds checks), but
2098          * obviously fails for write access which we have to implement for
2099          * shader images. Luckily, OpenGL doesn't expect this to be supported
2100          * anyway, and so the only impact is on PBO uploads / downloads, which
2101          * shouldn't be expected to be fast for GL_RGB anyway.
2102          */
2103         if (desc->block.bits == 3 * 8 ||
2104             desc->block.bits == 3 * 16) {
2105                 if (usage & (PIPE_BIND_SHADER_IMAGE | PIPE_BIND_SAMPLER_VIEW)) {
2106                     usage &= ~(PIPE_BIND_SHADER_IMAGE | PIPE_BIND_SAMPLER_VIEW);
2107                         if (!usage)
2108                                 return 0;
2109                 }
2110         }
2111
2112         first_non_void = util_format_get_first_non_void_channel(format);
2113         data_format = si_translate_buffer_dataformat(screen, desc, first_non_void);
2114         if (data_format == V_008F0C_BUF_DATA_FORMAT_INVALID)
2115                 return 0;
2116
2117         return usage;
2118 }
2119
2120 static bool si_is_colorbuffer_format_supported(enum pipe_format format)
2121 {
2122         return si_translate_colorformat(format) != V_028C70_COLOR_INVALID &&
2123                 si_translate_colorswap(format, false) != ~0U;
2124 }
2125
2126 static bool si_is_zs_format_supported(enum pipe_format format)
2127 {
2128         return si_translate_dbformat(format) != V_028040_Z_INVALID;
2129 }
2130
2131 static boolean si_is_format_supported(struct pipe_screen *screen,
2132                                       enum pipe_format format,
2133                                       enum pipe_texture_target target,
2134                                       unsigned sample_count,
2135                                       unsigned storage_sample_count,
2136                                       unsigned usage)
2137 {
2138         struct si_screen *sscreen = (struct si_screen *)screen;
2139         unsigned retval = 0;
2140
2141         if (target >= PIPE_MAX_TEXTURE_TYPES) {
2142                 PRINT_ERR("r600: unsupported texture type %d\n", target);
2143                 return false;
2144         }
2145
2146         if (MAX2(1, sample_count) < MAX2(1, storage_sample_count))
2147                 return false;
2148
2149         if (sample_count > 1) {
2150                 if (!screen->get_param(screen, PIPE_CAP_TEXTURE_MULTISAMPLE))
2151                         return false;
2152
2153                 if (usage & PIPE_BIND_SHADER_IMAGE)
2154                         return false;
2155
2156                 /* Only power-of-two sample counts are supported. */
2157                 if (!util_is_power_of_two_or_zero(sample_count) ||
2158                     !util_is_power_of_two_or_zero(storage_sample_count))
2159                         return false;
2160
2161                 /* MSAA support without framebuffer attachments. */
2162                 if (format == PIPE_FORMAT_NONE && sample_count <= 16)
2163                         return true;
2164
2165                 if (!sscreen->info.has_eqaa_surface_allocator ||
2166                     util_format_is_depth_or_stencil(format)) {
2167                         /* Color without EQAA or depth/stencil. */
2168                         if (sample_count > 8 ||
2169                             sample_count != storage_sample_count)
2170                                 return false;
2171                 } else {
2172                         /* Color with EQAA. */
2173                         if (sample_count > 16 ||
2174                             storage_sample_count > 8)
2175                                 return false;
2176                 }
2177         }
2178
2179         if (usage & (PIPE_BIND_SAMPLER_VIEW |
2180                      PIPE_BIND_SHADER_IMAGE)) {
2181                 if (target == PIPE_BUFFER) {
2182                         retval |= si_is_vertex_format_supported(
2183                                 screen, format, usage & (PIPE_BIND_SAMPLER_VIEW |
2184                                                          PIPE_BIND_SHADER_IMAGE));
2185                 } else {
2186                         if (si_is_sampler_format_supported(screen, format))
2187                                 retval |= usage & (PIPE_BIND_SAMPLER_VIEW |
2188                                                    PIPE_BIND_SHADER_IMAGE);
2189                 }
2190         }
2191
2192         if ((usage & (PIPE_BIND_RENDER_TARGET |
2193                       PIPE_BIND_DISPLAY_TARGET |
2194                       PIPE_BIND_SCANOUT |
2195                       PIPE_BIND_SHARED |
2196                       PIPE_BIND_BLENDABLE)) &&
2197             si_is_colorbuffer_format_supported(format)) {
2198                 retval |= usage &
2199                           (PIPE_BIND_RENDER_TARGET |
2200                            PIPE_BIND_DISPLAY_TARGET |
2201                            PIPE_BIND_SCANOUT |
2202                            PIPE_BIND_SHARED);
2203                 if (!util_format_is_pure_integer(format) &&
2204                     !util_format_is_depth_or_stencil(format))
2205                         retval |= usage & PIPE_BIND_BLENDABLE;
2206         }
2207
2208         if ((usage & PIPE_BIND_DEPTH_STENCIL) &&
2209             si_is_zs_format_supported(format)) {
2210                 retval |= PIPE_BIND_DEPTH_STENCIL;
2211         }
2212
2213         if (usage & PIPE_BIND_VERTEX_BUFFER) {
2214                 retval |= si_is_vertex_format_supported(screen, format,
2215                                                         PIPE_BIND_VERTEX_BUFFER);
2216         }
2217
2218         if ((usage & PIPE_BIND_LINEAR) &&
2219             !util_format_is_compressed(format) &&
2220             !(usage & PIPE_BIND_DEPTH_STENCIL))
2221                 retval |= PIPE_BIND_LINEAR;
2222
2223         return retval == usage;
2224 }
2225
2226 /*
2227  * framebuffer handling
2228  */
2229
2230 static void si_choose_spi_color_formats(struct si_surface *surf,
2231                                         unsigned format, unsigned swap,
2232                                         unsigned ntype, bool is_depth)
2233 {
2234         /* Alpha is needed for alpha-to-coverage.
2235          * Blending may be with or without alpha.
2236          */
2237         unsigned normal = 0; /* most optimal, may not support blending or export alpha */
2238         unsigned alpha = 0; /* exports alpha, but may not support blending */
2239         unsigned blend = 0; /* supports blending, but may not export alpha */
2240         unsigned blend_alpha = 0; /* least optimal, supports blending and exports alpha */
2241
2242         /* Choose the SPI color formats. These are required values for RB+.
2243          * Other chips have multiple choices, though they are not necessarily better.
2244          */
2245         switch (format) {
2246         case V_028C70_COLOR_5_6_5:
2247         case V_028C70_COLOR_1_5_5_5:
2248         case V_028C70_COLOR_5_5_5_1:
2249         case V_028C70_COLOR_4_4_4_4:
2250         case V_028C70_COLOR_10_11_11:
2251         case V_028C70_COLOR_11_11_10:
2252         case V_028C70_COLOR_8:
2253         case V_028C70_COLOR_8_8:
2254         case V_028C70_COLOR_8_8_8_8:
2255         case V_028C70_COLOR_10_10_10_2:
2256         case V_028C70_COLOR_2_10_10_10:
2257                 if (ntype == V_028C70_NUMBER_UINT)
2258                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_UINT16_ABGR;
2259                 else if (ntype == V_028C70_NUMBER_SINT)
2260                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_SINT16_ABGR;
2261                 else
2262                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_FP16_ABGR;
2263                 break;
2264
2265         case V_028C70_COLOR_16:
2266         case V_028C70_COLOR_16_16:
2267         case V_028C70_COLOR_16_16_16_16:
2268                 if (ntype == V_028C70_NUMBER_UNORM ||
2269                     ntype == V_028C70_NUMBER_SNORM) {
2270                         /* UNORM16 and SNORM16 don't support blending */
2271                         if (ntype == V_028C70_NUMBER_UNORM)
2272                                 normal = alpha = V_028714_SPI_SHADER_UNORM16_ABGR;
2273                         else
2274                                 normal = alpha = V_028714_SPI_SHADER_SNORM16_ABGR;
2275
2276                         /* Use 32 bits per channel for blending. */
2277                         if (format == V_028C70_COLOR_16) {
2278                                 if (swap == V_028C70_SWAP_STD) { /* R */
2279                                         blend = V_028714_SPI_SHADER_32_R;
2280                                         blend_alpha = V_028714_SPI_SHADER_32_AR;
2281                                 } else if (swap == V_028C70_SWAP_ALT_REV) /* A */
2282                                         blend = blend_alpha = V_028714_SPI_SHADER_32_AR;
2283                                 else
2284                                         assert(0);
2285                         } else if (format == V_028C70_COLOR_16_16) {
2286                                 if (swap == V_028C70_SWAP_STD) { /* RG */
2287                                         blend = V_028714_SPI_SHADER_32_GR;
2288                                         blend_alpha = V_028714_SPI_SHADER_32_ABGR;
2289                                 } else if (swap == V_028C70_SWAP_ALT) /* RA */
2290                                         blend = blend_alpha = V_028714_SPI_SHADER_32_AR;
2291                                 else
2292                                         assert(0);
2293                         } else /* 16_16_16_16 */
2294                                 blend = blend_alpha = V_028714_SPI_SHADER_32_ABGR;
2295                 } else if (ntype == V_028C70_NUMBER_UINT)
2296                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_UINT16_ABGR;
2297                 else if (ntype == V_028C70_NUMBER_SINT)
2298                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_SINT16_ABGR;
2299                 else if (ntype == V_028C70_NUMBER_FLOAT)
2300                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_FP16_ABGR;
2301                 else
2302                         assert(0);
2303                 break;
2304
2305         case V_028C70_COLOR_32:
2306                 if (swap == V_028C70_SWAP_STD) { /* R */
2307                         blend = normal = V_028714_SPI_SHADER_32_R;
2308                         alpha = blend_alpha = V_028714_SPI_SHADER_32_AR;
2309                 } else if (swap == V_028C70_SWAP_ALT_REV) /* A */
2310                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_AR;
2311                 else
2312                         assert(0);
2313                 break;
2314
2315         case V_028C70_COLOR_32_32:
2316                 if (swap == V_028C70_SWAP_STD) { /* RG */
2317                         blend = normal = V_028714_SPI_SHADER_32_GR;
2318                         alpha = blend_alpha = V_028714_SPI_SHADER_32_ABGR;
2319                 } else if (swap == V_028C70_SWAP_ALT) /* RA */
2320                         alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_AR;
2321                 else
2322                         assert(0);
2323                 break;
2324
2325         case V_028C70_COLOR_32_32_32_32:
2326         case V_028C70_COLOR_8_24:
2327         case V_028C70_COLOR_24_8:
2328         case V_028C70_COLOR_X24_8_32_FLOAT:
2329                 alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_ABGR;
2330                 break;
2331
2332         default:
2333                 assert(0);
2334                 return;
2335         }
2336
2337         /* The DB->CB copy needs 32_ABGR. */
2338         if (is_depth)
2339                 alpha = blend = blend_alpha = normal = V_028714_SPI_SHADER_32_ABGR;
2340
2341         surf->spi_shader_col_format = normal;
2342         surf->spi_shader_col_format_alpha = alpha;
2343         surf->spi_shader_col_format_blend = blend;
2344         surf->spi_shader_col_format_blend_alpha = blend_alpha;
2345 }
2346
2347 static void si_initialize_color_surface(struct si_context *sctx,
2348                                         struct si_surface *surf)
2349 {
2350         struct si_texture *tex = (struct si_texture*)surf->base.texture;
2351         unsigned color_info, color_attrib;
2352         unsigned format, swap, ntype, endian;
2353         const struct util_format_description *desc;
2354         int firstchan;
2355         unsigned blend_clamp = 0, blend_bypass = 0;
2356
2357         desc = util_format_description(surf->base.format);
2358         for (firstchan = 0; firstchan < 4; firstchan++) {
2359                 if (desc->channel[firstchan].type != UTIL_FORMAT_TYPE_VOID) {
2360                         break;
2361                 }
2362         }
2363         if (firstchan == 4 || desc->channel[firstchan].type == UTIL_FORMAT_TYPE_FLOAT) {
2364                 ntype = V_028C70_NUMBER_FLOAT;
2365         } else {
2366                 ntype = V_028C70_NUMBER_UNORM;
2367                 if (desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB)
2368                         ntype = V_028C70_NUMBER_SRGB;
2369                 else if (desc->channel[firstchan].type == UTIL_FORMAT_TYPE_SIGNED) {
2370                         if (desc->channel[firstchan].pure_integer) {
2371                                 ntype = V_028C70_NUMBER_SINT;
2372                         } else {
2373                                 assert(desc->channel[firstchan].normalized);
2374                                 ntype = V_028C70_NUMBER_SNORM;
2375                         }
2376                 } else if (desc->channel[firstchan].type == UTIL_FORMAT_TYPE_UNSIGNED) {
2377                         if (desc->channel[firstchan].pure_integer) {
2378                                 ntype = V_028C70_NUMBER_UINT;
2379                         } else {
2380                                 assert(desc->channel[firstchan].normalized);
2381                                 ntype = V_028C70_NUMBER_UNORM;
2382                         }
2383                 }
2384         }
2385
2386         format = si_translate_colorformat(surf->base.format);
2387         if (format == V_028C70_COLOR_INVALID) {
2388                 PRINT_ERR("Invalid CB format: %d, disabling CB.\n", surf->base.format);
2389         }
2390         assert(format != V_028C70_COLOR_INVALID);
2391         swap = si_translate_colorswap(surf->base.format, false);
2392         endian = si_colorformat_endian_swap(format);
2393
2394         /* blend clamp should be set for all NORM/SRGB types */
2395         if (ntype == V_028C70_NUMBER_UNORM ||
2396             ntype == V_028C70_NUMBER_SNORM ||
2397             ntype == V_028C70_NUMBER_SRGB)
2398                 blend_clamp = 1;
2399
2400         /* set blend bypass according to docs if SINT/UINT or
2401            8/24 COLOR variants */
2402         if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
2403             format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
2404             format == V_028C70_COLOR_X24_8_32_FLOAT) {
2405                 blend_clamp = 0;
2406                 blend_bypass = 1;
2407         }
2408
2409         if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) {
2410                 if (format == V_028C70_COLOR_8 ||
2411                     format == V_028C70_COLOR_8_8 ||
2412                     format == V_028C70_COLOR_8_8_8_8)
2413                         surf->color_is_int8 = true;
2414                 else if (format == V_028C70_COLOR_10_10_10_2 ||
2415                          format == V_028C70_COLOR_2_10_10_10)
2416                         surf->color_is_int10 = true;
2417         }
2418
2419         color_info = S_028C70_FORMAT(format) |
2420                 S_028C70_COMP_SWAP(swap) |
2421                 S_028C70_BLEND_CLAMP(blend_clamp) |
2422                 S_028C70_BLEND_BYPASS(blend_bypass) |
2423                 S_028C70_SIMPLE_FLOAT(1) |
2424                 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
2425                                     ntype != V_028C70_NUMBER_SNORM &&
2426                                     ntype != V_028C70_NUMBER_SRGB &&
2427                                     format != V_028C70_COLOR_8_24 &&
2428                                     format != V_028C70_COLOR_24_8) |
2429                 S_028C70_NUMBER_TYPE(ntype) |
2430                 S_028C70_ENDIAN(endian);
2431
2432         /* Intensity is implemented as Red, so treat it that way. */
2433         color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == PIPE_SWIZZLE_1 ||
2434                                                   util_format_is_intensity(surf->base.format));
2435
2436         if (tex->buffer.b.b.nr_samples > 1) {
2437                 unsigned log_samples = util_logbase2(tex->buffer.b.b.nr_samples);
2438                 unsigned log_fragments = util_logbase2(tex->buffer.b.b.nr_storage_samples);
2439
2440                 color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
2441                                 S_028C74_NUM_FRAGMENTS(log_fragments);
2442
2443                 if (tex->surface.fmask_size) {
2444                         color_info |= S_028C70_COMPRESSION(1);
2445                         unsigned fmask_bankh = util_logbase2(tex->surface.u.legacy.fmask.bankh);
2446
2447                         if (sctx->chip_class == SI) {
2448                                 /* due to a hw bug, FMASK_BANK_HEIGHT must be set on SI too */
2449                                 color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
2450                         }
2451                 }
2452         }
2453
2454         if (sctx->chip_class >= VI) {
2455                 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
2456                 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
2457
2458                 /* amdvlk: [min-compressed-block-size] should be set to 32 for dGPU and
2459                    64 for APU because all of our APUs to date use DIMMs which have
2460                    a request granularity size of 64B while all other chips have a
2461                    32B request size */
2462                 if (!sctx->screen->info.has_dedicated_vram)
2463                         min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
2464
2465                 if (tex->buffer.b.b.nr_storage_samples > 1) {
2466                         if (tex->surface.bpe == 1)
2467                                 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
2468                         else if (tex->surface.bpe == 2)
2469                                 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
2470                 }
2471
2472                 surf->cb_dcc_control = S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
2473                                        S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
2474                                        S_028C78_INDEPENDENT_64B_BLOCKS(1);
2475         }
2476
2477         /* This must be set for fast clear to work without FMASK. */
2478         if (!tex->surface.fmask_size && sctx->chip_class == SI) {
2479                 unsigned bankh = util_logbase2(tex->surface.u.legacy.bankh);
2480                 color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
2481         }
2482
2483         unsigned color_view = S_028C6C_SLICE_START(surf->base.u.tex.first_layer) |
2484                               S_028C6C_SLICE_MAX(surf->base.u.tex.last_layer);
2485
2486         if (sctx->chip_class >= GFX9) {
2487                 unsigned mip0_depth = util_max_layer(&tex->buffer.b.b, 0);
2488
2489                 color_view |= S_028C6C_MIP_LEVEL(surf->base.u.tex.level);
2490                 color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
2491                                 S_028C74_RESOURCE_TYPE(tex->surface.u.gfx9.resource_type);
2492                 surf->cb_color_attrib2 = S_028C68_MIP0_WIDTH(surf->width0 - 1) |
2493                                          S_028C68_MIP0_HEIGHT(surf->height0 - 1) |
2494                                          S_028C68_MAX_MIP(tex->buffer.b.b.last_level);
2495         }
2496
2497         surf->cb_color_view = color_view;
2498         surf->cb_color_info = color_info;
2499         surf->cb_color_attrib = color_attrib;
2500
2501         /* Determine pixel shader export format */
2502         si_choose_spi_color_formats(surf, format, swap, ntype, tex->is_depth);
2503
2504         surf->color_initialized = true;
2505 }
2506
2507 static void si_init_depth_surface(struct si_context *sctx,
2508                                   struct si_surface *surf)
2509 {
2510         struct si_texture *tex = (struct si_texture*)surf->base.texture;
2511         unsigned level = surf->base.u.tex.level;
2512         unsigned format, stencil_format;
2513         uint32_t z_info, s_info;
2514
2515         format = si_translate_dbformat(tex->db_render_format);
2516         stencil_format = tex->surface.has_stencil ?
2517                                  V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
2518
2519         assert(format != V_028040_Z_INVALID);
2520         if (format == V_028040_Z_INVALID)
2521                 PRINT_ERR("Invalid DB format: %d, disabling DB.\n", tex->buffer.b.b.format);
2522
2523         surf->db_depth_view = S_028008_SLICE_START(surf->base.u.tex.first_layer) |
2524                               S_028008_SLICE_MAX(surf->base.u.tex.last_layer);
2525         surf->db_htile_data_base = 0;
2526         surf->db_htile_surface = 0;
2527
2528         if (sctx->chip_class >= GFX9) {
2529                 assert(tex->surface.u.gfx9.surf_offset == 0);
2530                 surf->db_depth_base = tex->buffer.gpu_address >> 8;
2531                 surf->db_stencil_base = (tex->buffer.gpu_address +
2532                                          tex->surface.u.gfx9.stencil_offset) >> 8;
2533                 z_info = S_028038_FORMAT(format) |
2534                          S_028038_NUM_SAMPLES(util_logbase2(tex->buffer.b.b.nr_samples)) |
2535                          S_028038_SW_MODE(tex->surface.u.gfx9.surf.swizzle_mode) |
2536                          S_028038_MAXMIP(tex->buffer.b.b.last_level);
2537                 s_info = S_02803C_FORMAT(stencil_format) |
2538                          S_02803C_SW_MODE(tex->surface.u.gfx9.stencil.swizzle_mode);
2539                 surf->db_z_info2 = S_028068_EPITCH(tex->surface.u.gfx9.surf.epitch);
2540                 surf->db_stencil_info2 = S_02806C_EPITCH(tex->surface.u.gfx9.stencil.epitch);
2541                 surf->db_depth_view |= S_028008_MIPID(level);
2542                 surf->db_depth_size = S_02801C_X_MAX(tex->buffer.b.b.width0 - 1) |
2543                                       S_02801C_Y_MAX(tex->buffer.b.b.height0 - 1);
2544
2545                 if (si_htile_enabled(tex, level)) {
2546                         z_info |= S_028038_TILE_SURFACE_ENABLE(1) |
2547                                   S_028038_ALLOW_EXPCLEAR(1);
2548
2549                         if (tex->tc_compatible_htile) {
2550                                 unsigned max_zplanes = 4;
2551
2552                                 if (tex->db_render_format == PIPE_FORMAT_Z16_UNORM &&
2553                                     tex->buffer.b.b.nr_samples > 1)
2554                                         max_zplanes = 2;
2555
2556                                 z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes + 1) |
2557                                           S_028038_ITERATE_FLUSH(1);
2558                                 s_info |= S_02803C_ITERATE_FLUSH(1);
2559                         }
2560
2561                         if (tex->surface.has_stencil) {
2562                                 /* Stencil buffer workaround ported from the SI-CI-VI code.
2563                                  * See that for explanation.
2564                                  */
2565                                 s_info |= S_02803C_ALLOW_EXPCLEAR(tex->buffer.b.b.nr_samples <= 1);
2566                         } else {
2567                                 /* Use all HTILE for depth if there's no stencil. */
2568                                 s_info |= S_02803C_TILE_STENCIL_DISABLE(1);
2569                         }
2570
2571                         surf->db_htile_data_base = (tex->buffer.gpu_address +
2572                                                     tex->htile_offset) >> 8;
2573                         surf->db_htile_surface = S_028ABC_FULL_CACHE(1) |
2574                                                  S_028ABC_PIPE_ALIGNED(tex->surface.u.gfx9.htile.pipe_aligned) |
2575                                                  S_028ABC_RB_ALIGNED(tex->surface.u.gfx9.htile.rb_aligned);
2576                 }
2577         } else {
2578                 /* SI-CI-VI */
2579                 struct legacy_surf_level *levelinfo = &tex->surface.u.legacy.level[level];
2580
2581                 assert(levelinfo->nblk_x % 8 == 0 && levelinfo->nblk_y % 8 == 0);
2582
2583                 surf->db_depth_base = (tex->buffer.gpu_address +
2584                                        tex->surface.u.legacy.level[level].offset) >> 8;
2585                 surf->db_stencil_base = (tex->buffer.gpu_address +
2586                                          tex->surface.u.legacy.stencil_level[level].offset) >> 8;
2587
2588                 z_info = S_028040_FORMAT(format) |
2589                          S_028040_NUM_SAMPLES(util_logbase2(tex->buffer.b.b.nr_samples));
2590                 s_info = S_028044_FORMAT(stencil_format);
2591                 surf->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!tex->tc_compatible_htile);
2592
2593                 if (sctx->chip_class >= CIK) {
2594                         struct radeon_info *info = &sctx->screen->info;
2595                         unsigned index = tex->surface.u.legacy.tiling_index[level];
2596                         unsigned stencil_index = tex->surface.u.legacy.stencil_tiling_index[level];
2597                         unsigned macro_index = tex->surface.u.legacy.macro_tile_index;
2598                         unsigned tile_mode = info->si_tile_mode_array[index];
2599                         unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
2600                         unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
2601
2602                         surf->db_depth_info |=
2603                                 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
2604                                 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
2605                                 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
2606                                 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
2607                                 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
2608                                 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
2609                         z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
2610                         s_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
2611                 } else {
2612                         unsigned tile_mode_index = si_tile_mode_index(tex, level, false);
2613                         z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
2614                         tile_mode_index = si_tile_mode_index(tex, level, true);
2615                         s_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
2616                 }
2617
2618                 surf->db_depth_size = S_028058_PITCH_TILE_MAX((levelinfo->nblk_x / 8) - 1) |
2619                                       S_028058_HEIGHT_TILE_MAX((levelinfo->nblk_y / 8) - 1);
2620                 surf->db_depth_slice = S_02805C_SLICE_TILE_MAX((levelinfo->nblk_x *
2621                                                                 levelinfo->nblk_y) / 64 - 1);
2622
2623                 if (si_htile_enabled(tex, level)) {
2624                         z_info |= S_028040_TILE_SURFACE_ENABLE(1) |
2625                                   S_028040_ALLOW_EXPCLEAR(1);
2626
2627                         if (tex->surface.has_stencil) {
2628                                 /* Workaround: For a not yet understood reason, the
2629                                  * combination of MSAA, fast stencil clear and stencil
2630                                  * decompress messes with subsequent stencil buffer
2631                                  * uses. Problem was reproduced on Verde, Bonaire,
2632                                  * Tonga, and Carrizo.
2633                                  *
2634                                  * Disabling EXPCLEAR works around the problem.
2635                                  *
2636                                  * Check piglit's arb_texture_multisample-stencil-clear
2637                                  * test if you want to try changing this.
2638                                  */
2639                                 if (tex->buffer.b.b.nr_samples <= 1)
2640                                         s_info |= S_028044_ALLOW_EXPCLEAR(1);
2641                         } else if (!tex->tc_compatible_htile) {
2642                                 /* Use all of the htile_buffer for depth if there's no stencil.
2643                                  * This must not be set when TC-compatible HTILE is enabled
2644                                  * due to a hw bug.
2645                                  */
2646                                 s_info |= S_028044_TILE_STENCIL_DISABLE(1);
2647                         }
2648
2649                         surf->db_htile_data_base = (tex->buffer.gpu_address +
2650                                                     tex->htile_offset) >> 8;
2651                         surf->db_htile_surface = S_028ABC_FULL_CACHE(1);
2652
2653                         if (tex->tc_compatible_htile) {
2654                                 surf->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
2655
2656                                 /* 0 = full compression. N = only compress up to N-1 Z planes. */
2657                                 if (tex->buffer.b.b.nr_samples <= 1)
2658                                         z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(5);
2659                                 else if (tex->buffer.b.b.nr_samples <= 4)
2660                                         z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(3);
2661                                 else
2662                                         z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(2);
2663                         }
2664                 }
2665         }
2666
2667         surf->db_z_info = z_info;
2668         surf->db_stencil_info = s_info;
2669
2670         surf->depth_initialized = true;
2671 }
2672
2673 void si_update_fb_dirtiness_after_rendering(struct si_context *sctx)
2674 {
2675         if (sctx->decompression_enabled)
2676                 return;
2677
2678         if (sctx->framebuffer.state.zsbuf) {
2679                 struct pipe_surface *surf = sctx->framebuffer.state.zsbuf;
2680                 struct si_texture *tex = (struct si_texture *)surf->texture;
2681
2682                 tex->dirty_level_mask |= 1 << surf->u.tex.level;
2683
2684                 if (tex->surface.has_stencil)
2685                         tex->stencil_dirty_level_mask |= 1 << surf->u.tex.level;
2686         }
2687
2688         unsigned compressed_cb_mask = sctx->framebuffer.compressed_cb_mask;
2689         while (compressed_cb_mask) {
2690                 unsigned i = u_bit_scan(&compressed_cb_mask);
2691                 struct pipe_surface *surf = sctx->framebuffer.state.cbufs[i];
2692                 struct si_texture *tex = (struct si_texture*)surf->texture;
2693
2694                 if (tex->surface.fmask_size)
2695                         tex->dirty_level_mask |= 1 << surf->u.tex.level;
2696                 if (tex->dcc_gather_statistics)
2697                         tex->separate_dcc_dirty = true;
2698         }
2699 }
2700
2701 static void si_dec_framebuffer_counters(const struct pipe_framebuffer_state *state)
2702 {
2703         for (int i = 0; i < state->nr_cbufs; ++i) {
2704                 struct si_surface *surf = NULL;
2705                 struct si_texture *tex;
2706
2707                 if (!state->cbufs[i])
2708                         continue;
2709                 surf = (struct si_surface*)state->cbufs[i];
2710                 tex = (struct si_texture*)surf->base.texture;
2711
2712                 p_atomic_dec(&tex->framebuffers_bound);
2713         }
2714 }
2715
2716 static void si_set_framebuffer_state(struct pipe_context *ctx,
2717                                      const struct pipe_framebuffer_state *state)
2718 {
2719         struct si_context *sctx = (struct si_context *)ctx;
2720         struct pipe_constant_buffer constbuf = {0};
2721         struct si_surface *surf = NULL;
2722         struct si_texture *tex;
2723         bool old_any_dst_linear = sctx->framebuffer.any_dst_linear;
2724         unsigned old_nr_samples = sctx->framebuffer.nr_samples;
2725         unsigned old_colorbuf_enabled_4bit = sctx->framebuffer.colorbuf_enabled_4bit;
2726         bool old_has_zsbuf = !!sctx->framebuffer.state.zsbuf;
2727         bool old_has_stencil =
2728                 old_has_zsbuf &&
2729                 ((struct si_texture*)sctx->framebuffer.state.zsbuf->texture)->surface.has_stencil;
2730         bool unbound = false;
2731         int i;
2732
2733         si_update_fb_dirtiness_after_rendering(sctx);
2734
2735         for (i = 0; i < sctx->framebuffer.state.nr_cbufs; i++) {
2736                 if (!sctx->framebuffer.state.cbufs[i])
2737                         continue;
2738
2739                 tex = (struct si_texture*)sctx->framebuffer.state.cbufs[i]->texture;
2740                 if (tex->dcc_gather_statistics)
2741                         vi_separate_dcc_stop_query(sctx, tex);
2742         }
2743
2744         /* Disable DCC if the formats are incompatible. */
2745         for (i = 0; i < state->nr_cbufs; i++) {
2746                 if (!state->cbufs[i])
2747                         continue;
2748
2749                 surf = (struct si_surface*)state->cbufs[i];
2750                 tex = (struct si_texture*)surf->base.texture;
2751
2752                 if (!surf->dcc_incompatible)
2753                         continue;
2754
2755                 /* Since the DCC decompression calls back into set_framebuffer-
2756                  * _state, we need to unbind the framebuffer, so that
2757                  * vi_separate_dcc_stop_query isn't called twice with the same
2758                  * color buffer.
2759                  */
2760                 if (!unbound) {
2761                         util_copy_framebuffer_state(&sctx->framebuffer.state, NULL);
2762                         unbound = true;
2763                 }
2764
2765                 if (vi_dcc_enabled(tex, surf->base.u.tex.level))
2766                         if (!si_texture_disable_dcc(sctx, tex))
2767                                 si_decompress_dcc(sctx, tex);
2768
2769                 surf->dcc_incompatible = false;
2770         }
2771
2772         /* Only flush TC when changing the framebuffer state, because
2773          * the only client not using TC that can change textures is
2774          * the framebuffer.
2775          *
2776          * Wait for compute shaders because of possible transitions:
2777          * - FB write -> shader read
2778          * - shader write -> FB read
2779          *
2780          * DB caches are flushed on demand (using si_decompress_textures).
2781          *
2782          * When MSAA is enabled, CB and TC caches are flushed on demand
2783          * (after FMASK decompression). Shader write -> FB read transitions
2784          * cannot happen for MSAA textures, because MSAA shader images are
2785          * not supported.
2786          *
2787          * Only flush and wait for CB if there is actually a bound color buffer.
2788          */
2789         if (sctx->framebuffer.uncompressed_cb_mask)
2790                 si_make_CB_shader_coherent(sctx, sctx->framebuffer.nr_samples,
2791                                            sctx->framebuffer.CB_has_shader_readable_metadata);
2792
2793         sctx->flags |= SI_CONTEXT_CS_PARTIAL_FLUSH;
2794
2795         /* u_blitter doesn't invoke depth decompression when it does multiple
2796          * blits in a row, but the only case when it matters for DB is when
2797          * doing generate_mipmap. So here we flush DB manually between
2798          * individual generate_mipmap blits.
2799          * Note that lower mipmap levels aren't compressed.
2800          */
2801         if (sctx->generate_mipmap_for_depth) {
2802                 si_make_DB_shader_coherent(sctx, 1, false,
2803                                            sctx->framebuffer.DB_has_shader_readable_metadata);
2804         } else if (sctx->chip_class == GFX9) {
2805                 /* It appears that DB metadata "leaks" in a sequence of:
2806                  *  - depth clear
2807                  *  - DCC decompress for shader image writes (with DB disabled)
2808                  *  - render with DEPTH_BEFORE_SHADER=1
2809                  * Flushing DB metadata works around the problem.
2810                  */
2811                 sctx->flags |= SI_CONTEXT_FLUSH_AND_INV_DB_META;
2812         }
2813
2814         /* Take the maximum of the old and new count. If the new count is lower,
2815          * dirtying is needed to disable the unbound colorbuffers.
2816          */
2817         sctx->framebuffer.dirty_cbufs |=
2818                 (1 << MAX2(sctx->framebuffer.state.nr_cbufs, state->nr_cbufs)) - 1;
2819         sctx->framebuffer.dirty_zsbuf |= sctx->framebuffer.state.zsbuf != state->zsbuf;
2820
2821         si_dec_framebuffer_counters(&sctx->framebuffer.state);
2822         util_copy_framebuffer_state(&sctx->framebuffer.state, state);
2823
2824         sctx->framebuffer.colorbuf_enabled_4bit = 0;
2825         sctx->framebuffer.spi_shader_col_format = 0;
2826         sctx->framebuffer.spi_shader_col_format_alpha = 0;
2827         sctx->framebuffer.spi_shader_col_format_blend = 0;
2828         sctx->framebuffer.spi_shader_col_format_blend_alpha = 0;
2829         sctx->framebuffer.color_is_int8 = 0;
2830         sctx->framebuffer.color_is_int10 = 0;
2831
2832         sctx->framebuffer.compressed_cb_mask = 0;
2833         sctx->framebuffer.uncompressed_cb_mask = 0;
2834         sctx->framebuffer.nr_samples = util_framebuffer_get_num_samples(state);
2835         sctx->framebuffer.nr_color_samples = sctx->framebuffer.nr_samples;
2836         sctx->framebuffer.log_samples = util_logbase2(sctx->framebuffer.nr_samples);
2837         sctx->framebuffer.any_dst_linear = false;
2838         sctx->framebuffer.CB_has_shader_readable_metadata = false;
2839         sctx->framebuffer.DB_has_shader_readable_metadata = false;
2840
2841         for (i = 0; i < state->nr_cbufs; i++) {
2842                 if (!state->cbufs[i])
2843                         continue;
2844
2845                 surf = (struct si_surface*)state->cbufs[i];
2846                 tex = (struct si_texture*)surf->base.texture;
2847
2848                 if (!surf->color_initialized) {
2849                         si_initialize_color_surface(sctx, surf);
2850                 }
2851
2852                 sctx->framebuffer.colorbuf_enabled_4bit |= 0xf << (i * 4);
2853                 sctx->framebuffer.spi_shader_col_format |=
2854                         surf->spi_shader_col_format << (i * 4);
2855                 sctx->framebuffer.spi_shader_col_format_alpha |=
2856                         surf->spi_shader_col_format_alpha << (i * 4);
2857                 sctx->framebuffer.spi_shader_col_format_blend |=
2858                         surf->spi_shader_col_format_blend << (i * 4);
2859                 sctx->framebuffer.spi_shader_col_format_blend_alpha |=
2860                         surf->spi_shader_col_format_blend_alpha << (i * 4);
2861
2862                 if (surf->color_is_int8)
2863                         sctx->framebuffer.color_is_int8 |= 1 << i;
2864                 if (surf->color_is_int10)
2865                         sctx->framebuffer.color_is_int10 |= 1 << i;
2866
2867                 if (tex->surface.fmask_size)
2868                         sctx->framebuffer.compressed_cb_mask |= 1 << i;
2869                 else
2870                         sctx->framebuffer.uncompressed_cb_mask |= 1 << i;
2871
2872                 /* Don't update nr_color_samples for non-AA buffers.
2873                  * (e.g. destination of MSAA resolve)
2874                  */
2875                 if (tex->buffer.b.b.nr_samples >= 2 &&
2876                     tex->buffer.b.b.nr_storage_samples < tex->buffer.b.b.nr_samples) {
2877                         sctx->framebuffer.nr_color_samples =
2878                                 MIN2(sctx->framebuffer.nr_color_samples,
2879                                      tex->buffer.b.b.nr_storage_samples);
2880                         sctx->framebuffer.nr_color_samples =
2881                                 MAX2(1, sctx->framebuffer.nr_color_samples);
2882                 }
2883
2884                 if (tex->surface.is_linear)
2885                         sctx->framebuffer.any_dst_linear = true;
2886
2887                 if (vi_dcc_enabled(tex, surf->base.u.tex.level))
2888                         sctx->framebuffer.CB_has_shader_readable_metadata = true;
2889
2890                 si_context_add_resource_size(sctx, surf->base.texture);
2891
2892                 p_atomic_inc(&tex->framebuffers_bound);
2893
2894                 if (tex->dcc_gather_statistics) {
2895                         /* Dirty tracking must be enabled for DCC usage analysis. */
2896                         sctx->framebuffer.compressed_cb_mask |= 1 << i;
2897                         vi_separate_dcc_start_query(sctx, tex);
2898                 }
2899         }
2900
2901         struct si_texture *zstex = NULL;
2902
2903         if (state->zsbuf) {
2904                 surf = (struct si_surface*)state->zsbuf;
2905                 zstex = (struct si_texture*)surf->base.texture;
2906
2907                 if (!surf->depth_initialized) {
2908                         si_init_depth_surface(sctx, surf);
2909                 }
2910
2911                 if (vi_tc_compat_htile_enabled(zstex, surf->base.u.tex.level))
2912                         sctx->framebuffer.DB_has_shader_readable_metadata = true;
2913
2914                 si_context_add_resource_size(sctx, surf->base.texture);
2915         }
2916
2917         si_update_ps_colorbuf0_slot(sctx);
2918         si_update_poly_offset_state(sctx);
2919         si_mark_atom_dirty(sctx, &sctx->atoms.s.cb_render_state);
2920         si_mark_atom_dirty(sctx, &sctx->atoms.s.framebuffer);
2921
2922         if (sctx->screen->dpbb_allowed)
2923                 si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
2924
2925         if (sctx->framebuffer.any_dst_linear != old_any_dst_linear)
2926                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
2927
2928         if (sctx->screen->has_out_of_order_rast &&
2929             (sctx->framebuffer.colorbuf_enabled_4bit != old_colorbuf_enabled_4bit ||
2930              !!sctx->framebuffer.state.zsbuf != old_has_zsbuf ||
2931              (zstex && zstex->surface.has_stencil != old_has_stencil)))
2932                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
2933
2934         if (sctx->framebuffer.nr_samples != old_nr_samples) {
2935                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
2936                 si_mark_atom_dirty(sctx, &sctx->atoms.s.db_render_state);
2937
2938                 /* Set sample locations as fragment shader constants. */
2939                 switch (sctx->framebuffer.nr_samples) {
2940                 case 1:
2941                         constbuf.user_buffer = sctx->sample_locations_1x;
2942                         break;
2943                 case 2:
2944                         constbuf.user_buffer = sctx->sample_locations_2x;
2945                         break;
2946                 case 4:
2947                         constbuf.user_buffer = sctx->sample_locations_4x;
2948                         break;
2949                 case 8:
2950                         constbuf.user_buffer = sctx->sample_locations_8x;
2951                         break;
2952                 case 16:
2953                         constbuf.user_buffer = sctx->sample_locations_16x;
2954                         break;
2955                 default:
2956                         PRINT_ERR("Requested an invalid number of samples %i.\n",
2957                                  sctx->framebuffer.nr_samples);
2958                         assert(0);
2959                 }
2960                 constbuf.buffer_size = sctx->framebuffer.nr_samples * 2 * 4;
2961                 si_set_rw_buffer(sctx, SI_PS_CONST_SAMPLE_POSITIONS, &constbuf);
2962
2963                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_sample_locs);
2964         }
2965
2966         sctx->do_update_shaders = true;
2967
2968         if (!sctx->decompression_enabled) {
2969                 /* Prevent textures decompression when the framebuffer state
2970                  * changes come from the decompression passes themselves.
2971                  */
2972                 sctx->need_check_render_feedback = true;
2973         }
2974 }
2975
2976 static void si_emit_framebuffer_state(struct si_context *sctx)
2977 {
2978         struct radeon_cmdbuf *cs = sctx->gfx_cs;
2979         struct pipe_framebuffer_state *state = &sctx->framebuffer.state;
2980         unsigned i, nr_cbufs = state->nr_cbufs;
2981         struct si_texture *tex = NULL;
2982         struct si_surface *cb = NULL;
2983         unsigned cb_color_info = 0;
2984
2985         /* Colorbuffers. */
2986         for (i = 0; i < nr_cbufs; i++) {
2987                 uint64_t cb_color_base, cb_color_fmask, cb_color_cmask, cb_dcc_base;
2988                 unsigned cb_color_attrib;
2989
2990                 if (!(sctx->framebuffer.dirty_cbufs & (1 << i)))
2991                         continue;
2992
2993                 cb = (struct si_surface*)state->cbufs[i];
2994                 if (!cb) {
2995                         radeon_set_context_reg(cs, R_028C70_CB_COLOR0_INFO + i * 0x3C,
2996                                                S_028C70_FORMAT(V_028C70_COLOR_INVALID));
2997                         continue;
2998                 }
2999
3000                 tex = (struct si_texture *)cb->base.texture;
3001                 radeon_add_to_buffer_list(sctx, sctx->gfx_cs,
3002                                       &tex->buffer, RADEON_USAGE_READWRITE,
3003                                       tex->buffer.b.b.nr_samples > 1 ?
3004                                               RADEON_PRIO_COLOR_BUFFER_MSAA :
3005                                               RADEON_PRIO_COLOR_BUFFER);
3006
3007                 if (tex->cmask_buffer && tex->cmask_buffer != &tex->buffer) {
3008                         radeon_add_to_buffer_list(sctx, sctx->gfx_cs,
3009                                 tex->cmask_buffer, RADEON_USAGE_READWRITE,
3010                                 RADEON_PRIO_SEPARATE_META);
3011                 }
3012
3013                 if (tex->dcc_separate_buffer)
3014                         radeon_add_to_buffer_list(sctx, sctx->gfx_cs,
3015                                                   tex->dcc_separate_buffer,
3016                                                   RADEON_USAGE_READWRITE,
3017                                                   RADEON_PRIO_SEPARATE_META);
3018
3019                 /* Compute mutable surface parameters. */
3020                 cb_color_base = tex->buffer.gpu_address >> 8;
3021                 cb_color_fmask = 0;
3022                 cb_color_cmask = tex->cmask_base_address_reg;
3023                 cb_dcc_base = 0;
3024                 cb_color_info = cb->cb_color_info | tex->cb_color_info;
3025                 cb_color_attrib = cb->cb_color_attrib;
3026
3027                 if (cb->base.u.tex.level > 0)
3028                         cb_color_info &= C_028C70_FAST_CLEAR;
3029
3030                 if (tex->surface.fmask_size) {
3031                         cb_color_fmask = (tex->buffer.gpu_address + tex->fmask_offset) >> 8;
3032                         cb_color_fmask |= tex->surface.fmask_tile_swizzle;
3033                 }
3034
3035                 /* Set up DCC. */
3036                 if (vi_dcc_enabled(tex, cb->base.u.tex.level)) {
3037                         bool is_msaa_resolve_dst = state->cbufs[0] &&
3038                                                    state->cbufs[0]->texture->nr_samples > 1 &&
3039                                                    state->cbufs[1] == &cb->base &&
3040                                                    state->cbufs[1]->texture->nr_samples <= 1;
3041
3042                         if (!is_msaa_resolve_dst)
3043                                 cb_color_info |= S_028C70_DCC_ENABLE(1);
3044
3045                         cb_dcc_base = ((!tex->dcc_separate_buffer ? tex->buffer.gpu_address : 0) +
3046                                        tex->dcc_offset) >> 8;
3047                         cb_dcc_base |= tex->surface.tile_swizzle;
3048                 }
3049
3050                 if (sctx->chip_class >= GFX9) {
3051                         struct gfx9_surf_meta_flags meta;
3052
3053                         if (tex->dcc_offset)
3054                                 meta = tex->surface.u.gfx9.dcc;
3055                         else
3056                                 meta = tex->surface.u.gfx9.cmask;
3057
3058                         /* Set mutable surface parameters. */
3059                         cb_color_base += tex->surface.u.gfx9.surf_offset >> 8;
3060                         cb_color_base |= tex->surface.tile_swizzle;
3061                         if (!tex->surface.fmask_size)
3062                                 cb_color_fmask = cb_color_base;
3063                         if (cb->base.u.tex.level > 0)
3064                                 cb_color_cmask = cb_color_base;
3065                         cb_color_attrib |= S_028C74_COLOR_SW_MODE(tex->surface.u.gfx9.surf.swizzle_mode) |
3066                                            S_028C74_FMASK_SW_MODE(tex->surface.u.gfx9.fmask.swizzle_mode) |
3067                                            S_028C74_RB_ALIGNED(meta.rb_aligned) |
3068                                            S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
3069
3070                         radeon_set_context_reg_seq(cs, R_028C60_CB_COLOR0_BASE + i * 0x3C, 15);
3071                         radeon_emit(cs, cb_color_base);         /* CB_COLOR0_BASE */
3072                         radeon_emit(cs, S_028C64_BASE_256B(cb_color_base >> 32)); /* CB_COLOR0_BASE_EXT */
3073                         radeon_emit(cs, cb->cb_color_attrib2);  /* CB_COLOR0_ATTRIB2 */
3074                         radeon_emit(cs, cb->cb_color_view);     /* CB_COLOR0_VIEW */
3075                         radeon_emit(cs, cb_color_info);         /* CB_COLOR0_INFO */
3076                         radeon_emit(cs, cb_color_attrib);       /* CB_COLOR0_ATTRIB */
3077                         radeon_emit(cs, cb->cb_dcc_control);    /* CB_COLOR0_DCC_CONTROL */
3078                         radeon_emit(cs, cb_color_cmask);        /* CB_COLOR0_CMASK */
3079                         radeon_emit(cs, S_028C80_BASE_256B(cb_color_cmask >> 32)); /* CB_COLOR0_CMASK_BASE_EXT */
3080                         radeon_emit(cs, cb_color_fmask);        /* CB_COLOR0_FMASK */
3081                         radeon_emit(cs, S_028C88_BASE_256B(cb_color_fmask >> 32)); /* CB_COLOR0_FMASK_BASE_EXT */
3082                         radeon_emit(cs, tex->color_clear_value[0]); /* CB_COLOR0_CLEAR_WORD0 */
3083                         radeon_emit(cs, tex->color_clear_value[1]); /* CB_COLOR0_CLEAR_WORD1 */
3084                         radeon_emit(cs, cb_dcc_base);           /* CB_COLOR0_DCC_BASE */
3085                         radeon_emit(cs, S_028C98_BASE_256B(cb_dcc_base >> 32)); /* CB_COLOR0_DCC_BASE_EXT */
3086
3087                         radeon_set_context_reg(cs, R_0287A0_CB_MRT0_EPITCH + i * 4,
3088                                                S_0287A0_EPITCH(tex->surface.u.gfx9.surf.epitch));
3089                 } else {
3090                         /* Compute mutable surface parameters (SI-CI-VI). */
3091                         const struct legacy_surf_level *level_info =
3092                                 &tex->surface.u.legacy.level[cb->base.u.tex.level];
3093                         unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
3094                         unsigned cb_color_pitch, cb_color_slice, cb_color_fmask_slice;
3095
3096                         cb_color_base += level_info->offset >> 8;
3097                         /* Only macrotiled modes can set tile swizzle. */
3098                         if (level_info->mode == RADEON_SURF_MODE_2D)
3099                                 cb_color_base |= tex->surface.tile_swizzle;
3100
3101                         if (!tex->surface.fmask_size)
3102                                 cb_color_fmask = cb_color_base;
3103                         if (cb->base.u.tex.level > 0)
3104                                 cb_color_cmask = cb_color_base;
3105                         if (cb_dcc_base)
3106                                 cb_dcc_base += level_info->dcc_offset >> 8;
3107
3108                         pitch_tile_max = level_info->nblk_x / 8 - 1;
3109                         slice_tile_max = level_info->nblk_x *
3110                                          level_info->nblk_y / 64 - 1;
3111                         tile_mode_index = si_tile_mode_index(tex, cb->base.u.tex.level, false);
3112
3113                         cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
3114                         cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
3115                         cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
3116
3117                         if (tex->surface.fmask_size) {
3118                                 if (sctx->chip_class >= CIK)
3119                                         cb_color_pitch |= S_028C64_FMASK_TILE_MAX(tex->surface.u.legacy.fmask.pitch_in_pixels / 8 - 1);
3120                                 cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tex->surface.u.legacy.fmask.tiling_index);
3121                                 cb_color_fmask_slice = S_028C88_TILE_MAX(tex->surface.u.legacy.fmask.slice_tile_max);
3122                         } else {
3123                                 /* This must be set for fast clear to work without FMASK. */
3124                                 if (sctx->chip_class >= CIK)
3125                                         cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
3126                                 cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
3127                                 cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
3128                         }
3129
3130                         radeon_set_context_reg_seq(cs, R_028C60_CB_COLOR0_BASE + i * 0x3C,
3131                                                    sctx->chip_class >= VI ? 14 : 13);
3132                         radeon_emit(cs, cb_color_base);         /* CB_COLOR0_BASE */
3133                         radeon_emit(cs, cb_color_pitch);        /* CB_COLOR0_PITCH */
3134                         radeon_emit(cs, cb_color_slice);        /* CB_COLOR0_SLICE */
3135                         radeon_emit(cs, cb->cb_color_view);     /* CB_COLOR0_VIEW */
3136                         radeon_emit(cs, cb_color_info);         /* CB_COLOR0_INFO */
3137                         radeon_emit(cs, cb_color_attrib);       /* CB_COLOR0_ATTRIB */
3138                         radeon_emit(cs, cb->cb_dcc_control);    /* CB_COLOR0_DCC_CONTROL */
3139                         radeon_emit(cs, cb_color_cmask);        /* CB_COLOR0_CMASK */
3140                         radeon_emit(cs, tex->surface.u.legacy.cmask_slice_tile_max); /* CB_COLOR0_CMASK_SLICE */
3141                         radeon_emit(cs, cb_color_fmask);                /* CB_COLOR0_FMASK */
3142                         radeon_emit(cs, cb_color_fmask_slice);          /* CB_COLOR0_FMASK_SLICE */
3143                         radeon_emit(cs, tex->color_clear_value[0]);     /* CB_COLOR0_CLEAR_WORD0 */
3144                         radeon_emit(cs, tex->color_clear_value[1]);     /* CB_COLOR0_CLEAR_WORD1 */
3145
3146                         if (sctx->chip_class >= VI) /* R_028C94_CB_COLOR0_DCC_BASE */
3147                                 radeon_emit(cs, cb_dcc_base);
3148                 }
3149         }
3150         for (; i < 8 ; i++)
3151                 if (sctx->framebuffer.dirty_cbufs & (1 << i))
3152                         radeon_set_context_reg(cs, R_028C70_CB_COLOR0_INFO + i * 0x3C, 0);
3153
3154         /* ZS buffer. */
3155         if (state->zsbuf && sctx->framebuffer.dirty_zsbuf) {
3156                 struct si_surface *zb = (struct si_surface*)state->zsbuf;
3157                 struct si_texture *tex = (struct si_texture*)zb->base.texture;
3158
3159                 radeon_add_to_buffer_list(sctx, sctx->gfx_cs,
3160                                       &tex->buffer, RADEON_USAGE_READWRITE,
3161                                       zb->base.texture->nr_samples > 1 ?
3162                                               RADEON_PRIO_DEPTH_BUFFER_MSAA :
3163                                               RADEON_PRIO_DEPTH_BUFFER);
3164
3165                 if (sctx->chip_class >= GFX9) {
3166                         radeon_set_context_reg_seq(cs, R_028014_DB_HTILE_DATA_BASE, 3);
3167                         radeon_emit(cs, zb->db_htile_data_base);        /* DB_HTILE_DATA_BASE */
3168                         radeon_emit(cs, S_028018_BASE_HI(zb->db_htile_data_base >> 32)); /* DB_HTILE_DATA_BASE_HI */
3169                         radeon_emit(cs, zb->db_depth_size);             /* DB_DEPTH_SIZE */
3170
3171                         radeon_set_context_reg_seq(cs, R_028038_DB_Z_INFO, 10);
3172                         radeon_emit(cs, zb->db_z_info |                 /* DB_Z_INFO */
3173                                     S_028038_ZRANGE_PRECISION(tex->depth_clear_value != 0));
3174                         radeon_emit(cs, zb->db_stencil_info);           /* DB_STENCIL_INFO */
3175                         radeon_emit(cs, zb->db_depth_base);             /* DB_Z_READ_BASE */
3176                         radeon_emit(cs, S_028044_BASE_HI(zb->db_depth_base >> 32)); /* DB_Z_READ_BASE_HI */
3177                         radeon_emit(cs, zb->db_stencil_base);           /* DB_STENCIL_READ_BASE */
3178                         radeon_emit(cs, S_02804C_BASE_HI(zb->db_stencil_base >> 32)); /* DB_STENCIL_READ_BASE_HI */
3179                         radeon_emit(cs, zb->db_depth_base);             /* DB_Z_WRITE_BASE */
3180                         radeon_emit(cs, S_028054_BASE_HI(zb->db_depth_base >> 32)); /* DB_Z_WRITE_BASE_HI */
3181                         radeon_emit(cs, zb->db_stencil_base);           /* DB_STENCIL_WRITE_BASE */
3182                         radeon_emit(cs, S_02805C_BASE_HI(zb->db_stencil_base >> 32)); /* DB_STENCIL_WRITE_BASE_HI */
3183
3184                         radeon_set_context_reg_seq(cs, R_028068_DB_Z_INFO2, 2);
3185                         radeon_emit(cs, zb->db_z_info2);        /* DB_Z_INFO2 */
3186                         radeon_emit(cs, zb->db_stencil_info2);  /* DB_STENCIL_INFO2 */
3187                 } else {
3188                         radeon_set_context_reg(cs, R_028014_DB_HTILE_DATA_BASE, zb->db_htile_data_base);
3189
3190                         radeon_set_context_reg_seq(cs, R_02803C_DB_DEPTH_INFO, 9);
3191                         radeon_emit(cs, zb->db_depth_info);     /* DB_DEPTH_INFO */
3192                         radeon_emit(cs, zb->db_z_info |         /* DB_Z_INFO */
3193                                     S_028040_ZRANGE_PRECISION(tex->depth_clear_value != 0));
3194                         radeon_emit(cs, zb->db_stencil_info);   /* DB_STENCIL_INFO */
3195                         radeon_emit(cs, zb->db_depth_base);     /* DB_Z_READ_BASE */
3196                         radeon_emit(cs, zb->db_stencil_base);   /* DB_STENCIL_READ_BASE */
3197                         radeon_emit(cs, zb->db_depth_base);     /* DB_Z_WRITE_BASE */
3198                         radeon_emit(cs, zb->db_stencil_base);   /* DB_STENCIL_WRITE_BASE */
3199                         radeon_emit(cs, zb->db_depth_size);     /* DB_DEPTH_SIZE */
3200                         radeon_emit(cs, zb->db_depth_slice);    /* DB_DEPTH_SLICE */
3201                 }
3202
3203                 radeon_set_context_reg_seq(cs, R_028028_DB_STENCIL_CLEAR, 2);
3204                 radeon_emit(cs, tex->stencil_clear_value); /* R_028028_DB_STENCIL_CLEAR */
3205                 radeon_emit(cs, fui(tex->depth_clear_value)); /* R_02802C_DB_DEPTH_CLEAR */
3206
3207                 radeon_set_context_reg(cs, R_028008_DB_DEPTH_VIEW, zb->db_depth_view);
3208                 radeon_set_context_reg(cs, R_028ABC_DB_HTILE_SURFACE, zb->db_htile_surface);
3209         } else if (sctx->framebuffer.dirty_zsbuf) {
3210                 if (sctx->chip_class >= GFX9)
3211                         radeon_set_context_reg_seq(cs, R_028038_DB_Z_INFO, 2);
3212                 else
3213                         radeon_set_context_reg_seq(cs, R_028040_DB_Z_INFO, 2);
3214
3215                 radeon_emit(cs, S_028040_FORMAT(V_028040_Z_INVALID)); /* DB_Z_INFO */
3216                 radeon_emit(cs, S_028044_FORMAT(V_028044_STENCIL_INVALID)); /* DB_STENCIL_INFO */
3217         }
3218
3219         /* Framebuffer dimensions. */
3220         /* PA_SC_WINDOW_SCISSOR_TL is set in si_init_config() */
3221         radeon_set_context_reg(cs, R_028208_PA_SC_WINDOW_SCISSOR_BR,
3222                                S_028208_BR_X(state->width) | S_028208_BR_Y(state->height));
3223
3224         if (sctx->screen->dfsm_allowed) {
3225                 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3226                 radeon_emit(cs, EVENT_TYPE(V_028A90_BREAK_BATCH) | EVENT_INDEX(0));
3227         }
3228
3229         sctx->framebuffer.dirty_cbufs = 0;
3230         sctx->framebuffer.dirty_zsbuf = false;
3231 }
3232
3233 static void si_emit_msaa_sample_locs(struct si_context *sctx)
3234 {
3235         struct radeon_cmdbuf *cs = sctx->gfx_cs;
3236         unsigned nr_samples = sctx->framebuffer.nr_samples;
3237         bool has_msaa_sample_loc_bug = sctx->screen->has_msaa_sample_loc_bug;
3238
3239         /* Smoothing (only possible with nr_samples == 1) uses the same
3240          * sample locations as the MSAA it simulates.
3241          */
3242         if (nr_samples <= 1 && sctx->smoothing_enabled)
3243                 nr_samples = SI_NUM_SMOOTH_AA_SAMPLES;
3244
3245         /* On Polaris, the small primitive filter uses the sample locations
3246          * even when MSAA is off, so we need to make sure they're set to 0.
3247          */
3248         if (has_msaa_sample_loc_bug)
3249                 nr_samples = MAX2(nr_samples, 1);
3250
3251         if (nr_samples != sctx->sample_locs_num_samples) {
3252                 sctx->sample_locs_num_samples = nr_samples;
3253                 si_emit_sample_locations(cs, nr_samples);
3254         }
3255
3256         if (sctx->family >= CHIP_POLARIS10) {
3257                 struct si_state_rasterizer *rs = sctx->queued.named.rasterizer;
3258                 unsigned small_prim_filter_cntl =
3259                         S_028830_SMALL_PRIM_FILTER_ENABLE(1) |
3260                         /* line bug */
3261                         S_028830_LINE_FILTER_DISABLE(sctx->family <= CHIP_POLARIS12);
3262
3263                 /* The alternative of setting sample locations to 0 would
3264                  * require a DB flush to avoid Z errors, see
3265                  * https://bugs.freedesktop.org/show_bug.cgi?id=96908
3266                  */
3267                 if (has_msaa_sample_loc_bug &&
3268                     sctx->framebuffer.nr_samples > 1 &&
3269                     !rs->multisample_enable)
3270                         small_prim_filter_cntl &= C_028830_SMALL_PRIM_FILTER_ENABLE;
3271
3272                 radeon_opt_set_context_reg(sctx,
3273                                            R_028830_PA_SU_SMALL_PRIM_FILTER_CNTL,
3274                                            SI_TRACKED_PA_SU_SMALL_PRIM_FILTER_CNTL,
3275                                            small_prim_filter_cntl);
3276         }
3277 }
3278
3279 static bool si_out_of_order_rasterization(struct si_context *sctx)
3280 {
3281         struct si_state_blend *blend = sctx->queued.named.blend;
3282         struct si_state_dsa *dsa = sctx->queued.named.dsa;
3283
3284         if (!sctx->screen->has_out_of_order_rast)
3285                 return false;
3286
3287         unsigned colormask = sctx->framebuffer.colorbuf_enabled_4bit;
3288
3289         if (blend) {
3290                 colormask &= blend->cb_target_enabled_4bit;
3291         } else {
3292                 colormask = 0;
3293         }
3294
3295         /* Conservative: No logic op. */
3296         if (colormask && blend->logicop_enable)
3297                 return false;
3298
3299         struct si_dsa_order_invariance dsa_order_invariant = {
3300                 .zs = true, .pass_set = true, .pass_last = false
3301         };
3302
3303         if (sctx->framebuffer.state.zsbuf) {
3304                 struct si_texture *zstex =
3305                         (struct si_texture*)sctx->framebuffer.state.zsbuf->texture;
3306                 bool has_stencil = zstex->surface.has_stencil;
3307                 dsa_order_invariant = dsa->order_invariance[has_stencil];
3308                 if (!dsa_order_invariant.zs)
3309                         return false;
3310
3311                 /* The set of PS invocations is always order invariant,
3312                  * except when early Z/S tests are requested. */
3313                 if (sctx->ps_shader.cso &&
3314                     sctx->ps_shader.cso->info.writes_memory &&
3315                     sctx->ps_shader.cso->info.properties[TGSI_PROPERTY_FS_EARLY_DEPTH_STENCIL] &&
3316                     !dsa_order_invariant.pass_set)
3317                         return false;
3318
3319                 if (sctx->num_perfect_occlusion_queries != 0 &&
3320                     !dsa_order_invariant.pass_set)
3321                         return false;
3322         }
3323
3324         if (!colormask)
3325                 return true;
3326
3327         unsigned blendmask = colormask & blend->blend_enable_4bit;
3328
3329         if (blendmask) {
3330                 /* Only commutative blending. */
3331                 if (blendmask & ~blend->commutative_4bit)
3332                         return false;
3333
3334                 if (!dsa_order_invariant.pass_set)
3335                         return false;
3336         }
3337
3338         if (colormask & ~blendmask) {
3339                 if (!dsa_order_invariant.pass_last)
3340                         return false;
3341         }
3342
3343         return true;
3344 }
3345
3346 static void si_emit_msaa_config(struct si_context *sctx)
3347 {
3348         struct radeon_cmdbuf *cs = sctx->gfx_cs;
3349         unsigned num_tile_pipes = sctx->screen->info.num_tile_pipes;
3350         /* 33% faster rendering to linear color buffers */
3351         bool dst_is_linear = sctx->framebuffer.any_dst_linear;
3352         bool out_of_order_rast = si_out_of_order_rasterization(sctx);
3353         unsigned sc_mode_cntl_1 =
3354                 S_028A4C_WALK_SIZE(dst_is_linear) |
3355                 S_028A4C_WALK_FENCE_ENABLE(!dst_is_linear) |
3356                 S_028A4C_WALK_FENCE_SIZE(num_tile_pipes == 2 ? 2 : 3) |
3357                 S_028A4C_OUT_OF_ORDER_PRIMITIVE_ENABLE(out_of_order_rast) |
3358                 S_028A4C_OUT_OF_ORDER_WATER_MARK(0x7) |
3359                 /* always 1: */
3360                 S_028A4C_WALK_ALIGN8_PRIM_FITS_ST(1) |
3361                 S_028A4C_SUPERTILE_WALK_ORDER_ENABLE(1) |
3362                 S_028A4C_TILE_WALK_ORDER_ENABLE(1) |
3363                 S_028A4C_MULTI_SHADER_ENGINE_PRIM_DISCARD_ENABLE(1) |
3364                 S_028A4C_FORCE_EOV_CNTDWN_ENABLE(1) |
3365                 S_028A4C_FORCE_EOV_REZ_ENABLE(1);
3366         unsigned db_eqaa = S_028804_HIGH_QUALITY_INTERSECTIONS(1) |
3367                            S_028804_INCOHERENT_EQAA_READS(1) |
3368                            S_028804_INTERPOLATE_COMP_Z(1) |
3369                            S_028804_STATIC_ANCHOR_ASSOCIATIONS(1);
3370         unsigned coverage_samples, color_samples, z_samples;
3371
3372         /* S: Coverage samples (up to 16x):
3373          * - Scan conversion samples (PA_SC_AA_CONFIG.MSAA_NUM_SAMPLES)
3374          * - CB FMASK samples (CB_COLORi_ATTRIB.NUM_SAMPLES)
3375          *
3376          * Z: Z/S samples (up to 8x, must be <= coverage samples and >= color samples):
3377          * - Value seen by DB (DB_Z_INFO.NUM_SAMPLES)
3378          * - Value seen by CB, must be correct even if Z/S is unbound (DB_EQAA.MAX_ANCHOR_SAMPLES)
3379          * # Missing samples are derived from Z planes if Z is compressed (up to 16x quality), or
3380          * # from the closest defined sample if Z is uncompressed (same quality as the number of
3381          * # Z samples).
3382          *
3383          * F: Color samples (up to 8x, must be <= coverage samples):
3384          * - CB color samples (CB_COLORi_ATTRIB.NUM_FRAGMENTS)
3385          * - PS iter samples (DB_EQAA.PS_ITER_SAMPLES)
3386          *
3387          * Can be anything between coverage and color samples:
3388          * - SampleMaskIn samples (PA_SC_AA_CONFIG.MSAA_EXPOSED_SAMPLES)
3389          * - SampleMaskOut samples (DB_EQAA.MASK_EXPORT_NUM_SAMPLES)
3390          * - Alpha-to-coverage samples (DB_EQAA.ALPHA_TO_MASK_NUM_SAMPLES)
3391          * - Occlusion query samples (DB_COUNT_CONTROL.SAMPLE_RATE)
3392          * # All are currently set the same as coverage samples.
3393          *
3394          * If color samples < coverage samples, FMASK has a higher bpp to store an "unknown"
3395          * flag for undefined color samples. A shader-based resolve must handle unknowns
3396          * or mask them out with AND. Unknowns can also be guessed from neighbors via
3397          * an edge-detect shader-based resolve, which is required to make "color samples = 1"
3398          * useful. The CB resolve always drops unknowns.
3399          *
3400          * Sensible AA configurations:
3401          *   EQAA 16s 8z 8f - might look the same as 16x MSAA if Z is compressed
3402          *   EQAA 16s 8z 4f - might look the same as 16x MSAA if Z is compressed
3403          *   EQAA 16s 4z 4f - might look the same as 16x MSAA if Z is compressed
3404          *   EQAA  8s 8z 8f = 8x MSAA
3405          *   EQAA  8s 8z 4f - might look the same as 8x MSAA
3406          *   EQAA  8s 8z 2f - might look the same as 8x MSAA with low-density geometry
3407          *   EQAA  8s 4z 4f - might look the same as 8x MSAA if Z is compressed
3408          *   EQAA  8s 4z 2f - might look the same as 8x MSAA with low-density geometry if Z is compressed
3409          *   EQAA  4s 4z 4f = 4x MSAA
3410          *   EQAA  4s 4z 2f - might look the same as 4x MSAA with low-density geometry
3411          *   EQAA  2s 2z 2f = 2x MSAA
3412          */
3413         if (sctx->framebuffer.nr_samples > 1) {
3414                 coverage_samples = sctx->framebuffer.nr_samples;
3415                 color_samples = sctx->framebuffer.nr_color_samples;
3416
3417                 if (sctx->framebuffer.state.zsbuf) {
3418                         z_samples = sctx->framebuffer.state.zsbuf->texture->nr_samples;
3419                         z_samples = MAX2(1, z_samples);
3420                 } else {
3421                         z_samples = coverage_samples;
3422                 }
3423         } else if (sctx->smoothing_enabled) {
3424                 coverage_samples = color_samples = z_samples = SI_NUM_SMOOTH_AA_SAMPLES;
3425         } else {
3426                 coverage_samples = color_samples = z_samples = 1;
3427         }
3428
3429         /* Required by OpenGL line rasterization.
3430          *
3431          * TODO: We should also enable perpendicular endcaps for AA lines,
3432          *       but that requires implementing line stippling in the pixel
3433          *       shader. SC can only do line stippling with axis-aligned
3434          *       endcaps.
3435          */
3436         unsigned sc_line_cntl = S_028BDC_DX10_DIAMOND_TEST_ENA(1);
3437         unsigned sc_aa_config = 0;
3438
3439         if (coverage_samples > 1) {
3440                 /* distance from the pixel center, indexed by log2(nr_samples) */
3441                 static unsigned max_dist[] = {
3442                         0, /* unused */
3443                         4, /* 2x MSAA */
3444                         6, /* 4x MSAA */
3445                         7, /* 8x MSAA */
3446                         8, /* 16x MSAA */
3447                 };
3448                 unsigned log_samples = util_logbase2(coverage_samples);
3449                 unsigned log_z_samples = util_logbase2(z_samples);
3450                 unsigned ps_iter_samples = si_get_ps_iter_samples(sctx);
3451                 unsigned log_ps_iter_samples = util_logbase2(ps_iter_samples);
3452
3453                 sc_line_cntl |= S_028BDC_EXPAND_LINE_WIDTH(1);
3454                 sc_aa_config = S_028BE0_MSAA_NUM_SAMPLES(log_samples) |
3455                                S_028BE0_MAX_SAMPLE_DIST(max_dist[log_samples]) |
3456                                S_028BE0_MSAA_EXPOSED_SAMPLES(log_samples);
3457
3458                 if (sctx->framebuffer.nr_samples > 1) {
3459                         db_eqaa |= S_028804_MAX_ANCHOR_SAMPLES(log_z_samples) |
3460                                    S_028804_PS_ITER_SAMPLES(log_ps_iter_samples) |
3461                                    S_028804_MASK_EXPORT_NUM_SAMPLES(log_samples) |
3462                                    S_028804_ALPHA_TO_MASK_NUM_SAMPLES(log_samples);
3463                         sc_mode_cntl_1 |= S_028A4C_PS_ITER_SAMPLE(ps_iter_samples > 1);
3464                 } else if (sctx->smoothing_enabled) {
3465                         db_eqaa |= S_028804_OVERRASTERIZATION_AMOUNT(log_samples);
3466                 }
3467         }
3468
3469         /* R_028BDC_PA_SC_LINE_CNTL, R_028BE0_PA_SC_AA_CONFIG */
3470         radeon_opt_set_context_reg2(sctx, R_028BDC_PA_SC_LINE_CNTL,
3471                                     SI_TRACKED_PA_SC_LINE_CNTL, sc_line_cntl,
3472                                     sc_aa_config);
3473         /* R_028804_DB_EQAA */
3474         radeon_opt_set_context_reg(sctx, R_028804_DB_EQAA, SI_TRACKED_DB_EQAA,
3475                                    db_eqaa);
3476         /* R_028A4C_PA_SC_MODE_CNTL_1 */
3477         radeon_opt_set_context_reg(sctx, R_028A4C_PA_SC_MODE_CNTL_1,
3478                                    SI_TRACKED_PA_SC_MODE_CNTL_1, sc_mode_cntl_1);
3479
3480         /* GFX9: Flush DFSM when the AA mode changes. */
3481         if (sctx->screen->dfsm_allowed) {
3482                 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
3483                 radeon_emit(cs, EVENT_TYPE(V_028A90_FLUSH_DFSM) | EVENT_INDEX(0));
3484         }
3485 }
3486
3487 void si_update_ps_iter_samples(struct si_context *sctx)
3488 {
3489         if (sctx->framebuffer.nr_samples > 1)
3490                 si_mark_atom_dirty(sctx, &sctx->atoms.s.msaa_config);
3491         if (sctx->screen->dpbb_allowed)
3492                 si_mark_atom_dirty(sctx, &sctx->atoms.s.dpbb_state);
3493 }
3494
3495 static void si_set_min_samples(struct pipe_context *ctx, unsigned min_samples)
3496 {
3497         struct si_context *sctx = (struct si_context *)ctx;
3498
3499         /* The hardware can only do sample shading with 2^n samples. */
3500         min_samples = util_next_power_of_two(min_samples);
3501
3502         if (sctx->ps_iter_samples == min_samples)
3503                 return;
3504
3505         sctx->ps_iter_samples = min_samples;
3506         sctx->do_update_shaders = true;
3507
3508         si_update_ps_iter_samples(sctx);
3509 }
3510
3511 /*
3512  * Samplers
3513  */
3514
3515 /**
3516  * Build the sampler view descriptor for a buffer texture.
3517  * @param state 256-bit descriptor; only the high 128 bits are filled in
3518  */
3519 void
3520 si_make_buffer_descriptor(struct si_screen *screen, struct r600_resource *buf,
3521                           enum pipe_format format,
3522                           unsigned offset, unsigned size,
3523                           uint32_t *state)
3524 {
3525         const struct util_format_description *desc;
3526         int first_non_void;
3527         unsigned stride;
3528         unsigned num_records;
3529         unsigned num_format, data_format;
3530
3531         desc = util_format_description(format);
3532         first_non_void = util_format_get_first_non_void_channel(format);
3533         stride = desc->block.bits / 8;
3534         num_format = si_translate_buffer_numformat(&screen->b, desc, first_non_void);
3535         data_format = si_translate_buffer_dataformat(&screen->b, desc, first_non_void);
3536
3537         num_records = size / stride;
3538         num_records = MIN2(num_records, (buf->b.b.width0 - offset) / stride);
3539
3540         /* The NUM_RECORDS field has a different meaning depending on the chip,
3541          * instruction type, STRIDE, and SWIZZLE_ENABLE.
3542          *
3543          * SI-CIK:
3544          * - If STRIDE == 0, it's in byte units.
3545          * - If STRIDE != 0, it's in units of STRIDE, used with inst.IDXEN.
3546          *
3547          * VI:
3548          * - For SMEM and STRIDE == 0, it's in byte units.
3549          * - For SMEM and STRIDE != 0, it's in units of STRIDE.
3550          * - For VMEM and STRIDE == 0 or SWIZZLE_ENABLE == 0, it's in byte units.
3551          * - For VMEM and STRIDE != 0 and SWIZZLE_ENABLE == 1, it's in units of STRIDE.
3552          * NOTE: There is incompatibility between VMEM and SMEM opcodes due to SWIZZLE_-
3553          *       ENABLE. The workaround is to set STRIDE = 0 if SWIZZLE_ENABLE == 0 when
3554          *       using SMEM. This can be done in the shader by clearing STRIDE with s_and.
3555          *       That way the same descriptor can be used by both SMEM and VMEM.
3556          *
3557          * GFX9:
3558          * - For SMEM and STRIDE == 0, it's in byte units.
3559          * - For SMEM and STRIDE != 0, it's in units of STRIDE.
3560          * - For VMEM and inst.IDXEN == 0 or STRIDE == 0, it's in byte units.
3561          * - For VMEM and inst.IDXEN == 1 and STRIDE != 0, it's in units of STRIDE.
3562          */
3563         if (screen->info.chip_class >= GFX9)
3564                 /* When vindex == 0, LLVM sets IDXEN = 0, thus changing units
3565                  * from STRIDE to bytes. This works around it by setting
3566                  * NUM_RECORDS to at least the size of one element, so that
3567                  * the first element is readable when IDXEN == 0.
3568                  *
3569                  * TODO: Fix this in LLVM, but do we need a new intrinsic where
3570                  *       IDXEN is enforced?
3571                  */
3572                 num_records = num_records ? MAX2(num_records, stride) : 0;
3573         else if (screen->info.chip_class == VI)
3574                 num_records *= stride;
3575
3576         state[4] = 0;
3577         state[5] = S_008F04_STRIDE(stride);
3578         state[6] = num_records;
3579         state[7] = S_008F0C_DST_SEL_X(si_map_swizzle(desc->swizzle[0])) |
3580                    S_008F0C_DST_SEL_Y(si_map_swizzle(desc->swizzle[1])) |
3581                    S_008F0C_DST_SEL_Z(si_map_swizzle(desc->swizzle[2])) |
3582                    S_008F0C_DST_SEL_W(si_map_swizzle(desc->swizzle[3])) |
3583                    S_008F0C_NUM_FORMAT(num_format) |
3584                    S_008F0C_DATA_FORMAT(data_format);
3585 }
3586
3587 static unsigned gfx9_border_color_swizzle(const unsigned char swizzle[4])
3588 {
3589         unsigned bc_swizzle = V_008F20_BC_SWIZZLE_XYZW;
3590
3591         if (swizzle[3] == PIPE_SWIZZLE_X) {
3592                 /* For the pre-defined border color values (white, opaque
3593                  * black, transparent black), the only thing that matters is
3594                  * that the alpha channel winds up in the correct place
3595                  * (because the RGB channels are all the same) so either of
3596                  * these enumerations will work.
3597                  */
3598                 if (swizzle[2] == PIPE_SWIZZLE_Y)
3599                         bc_swizzle = V_008F20_BC_SWIZZLE_WZYX;
3600                 else
3601                         bc_swizzle = V_008F20_BC_SWIZZLE_WXYZ;
3602         } else if (swizzle[0] == PIPE_SWIZZLE_X) {
3603                 if (swizzle[1] == PIPE_SWIZZLE_Y)
3604                         bc_swizzle = V_008F20_BC_SWIZZLE_XYZW;
3605                 else
3606                         bc_swizzle = V_008F20_BC_SWIZZLE_XWYZ;
3607         } else if (swizzle[1] == PIPE_SWIZZLE_X) {
3608                 bc_swizzle = V_008F20_BC_SWIZZLE_YXWZ;
3609         } else if (swizzle[2] == PIPE_SWIZZLE_X) {
3610                 bc_swizzle = V_008F20_BC_SWIZZLE_ZYXW;
3611         }
3612
3613         return bc_swizzle;
3614 }
3615
3616 /**
3617  * Build the sampler view descriptor for a texture.
3618  */
3619 void
3620 si_make_texture_descriptor(struct si_screen *screen,
3621                            struct si_texture *tex,
3622                            bool sampler,
3623                            enum pipe_texture_target target,
3624                            enum pipe_format pipe_format,
3625                            const unsigned char state_swizzle[4],
3626                            unsigned first_level, unsigned last_level,
3627                            unsigned first_layer, unsigned last_layer,
3628                            unsigned width, unsigned height, unsigned depth,
3629                            uint32_t *state,
3630                            uint32_t *fmask_state)
3631 {
3632         struct pipe_resource *res = &tex->buffer.b.b;
3633         const struct util_format_description *desc;
3634         unsigned char swizzle[4];
3635         int first_non_void;
3636         unsigned num_format, data_format, type, num_samples;
3637         uint64_t va;
3638
3639         desc = util_format_description(pipe_format);
3640
3641         num_samples = desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS ?
3642                         MAX2(1, res->nr_samples) :
3643                         MAX2(1, res->nr_storage_samples);
3644
3645         if (desc->colorspace == UTIL_FORMAT_COLORSPACE_ZS) {
3646                 const unsigned char swizzle_xxxx[4] = {0, 0, 0, 0};
3647                 const unsigned char swizzle_yyyy[4] = {1, 1, 1, 1};
3648                 const unsigned char swizzle_wwww[4] = {3, 3, 3, 3};
3649
3650                 switch (pipe_format) {
3651                 case PIPE_FORMAT_S8_UINT_Z24_UNORM:
3652                 case PIPE_FORMAT_X32_S8X24_UINT:
3653                 case PIPE_FORMAT_X8Z24_UNORM:
3654                         util_format_compose_swizzles(swizzle_yyyy, state_swizzle, swizzle);
3655                         break;
3656                 case PIPE_FORMAT_X24S8_UINT:
3657                         /*
3658                          * X24S8 is implemented as an 8_8_8_8 data format, to
3659                          * fix texture gathers. This affects at least
3660                          * GL45-CTS.texture_cube_map_array.sampling on VI.
3661                          */
3662                         if (screen->info.chip_class <= VI)
3663                                 util_format_compose_swizzles(swizzle_wwww, state_swizzle, swizzle);
3664                         else
3665                                 util_format_compose_swizzles(swizzle_yyyy, state_swizzle, swizzle);
3666                         break;
3667                 default:
3668                         util_format_compose_swizzles(swizzle_xxxx, state_swizzle, swizzle);
3669                 }
3670         } else {
3671                 util_format_compose_swizzles(desc->swizzle, state_swizzle, swizzle);
3672         }
3673
3674         first_non_void = util_format_get_first_non_void_channel(pipe_format);
3675
3676         switch (pipe_format) {
3677         case PIPE_FORMAT_S8_UINT_Z24_UNORM:
3678                 num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
3679                 break;
3680         default:
3681                 if (first_non_void < 0) {
3682                         if (util_format_is_compressed(pipe_format)) {
3683                                 switch (pipe_format) {
3684                                 case PIPE_FORMAT_DXT1_SRGB:
3685                                 case PIPE_FORMAT_DXT1_SRGBA:
3686                                 case PIPE_FORMAT_DXT3_SRGBA:
3687                                 case PIPE_FORMAT_DXT5_SRGBA:
3688                                 case PIPE_FORMAT_BPTC_SRGBA:
3689                                 case PIPE_FORMAT_ETC2_SRGB8:
3690                                 case PIPE_FORMAT_ETC2_SRGB8A1:
3691                                 case PIPE_FORMAT_ETC2_SRGBA8:
3692                                         num_format = V_008F14_IMG_NUM_FORMAT_SRGB;
3693                                         break;
3694                                 case PIPE_FORMAT_RGTC1_SNORM:
3695                                 case PIPE_FORMAT_LATC1_SNORM:
3696                                 case PIPE_FORMAT_RGTC2_SNORM:
3697                                 case PIPE_FORMAT_LATC2_SNORM:
3698                                 case PIPE_FORMAT_ETC2_R11_SNORM:
3699                                 case PIPE_FORMAT_ETC2_RG11_SNORM:
3700                                 /* implies float, so use SNORM/UNORM to determine
3701                                    whether data is signed or not */
3702                                 case PIPE_FORMAT_BPTC_RGB_FLOAT:
3703                                         num_format = V_008F14_IMG_NUM_FORMAT_SNORM;
3704                                         break;
3705                                 default:
3706                                         num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
3707                                         break;
3708                                 }
3709                         } else if (desc->layout == UTIL_FORMAT_LAYOUT_SUBSAMPLED) {
3710                                 num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
3711                         } else {
3712                                 num_format = V_008F14_IMG_NUM_FORMAT_FLOAT;
3713                         }
3714                 } else if (desc->colorspace == UTIL_FORMAT_COLORSPACE_SRGB) {
3715                         num_format = V_008F14_IMG_NUM_FORMAT_SRGB;
3716                 } else {
3717                         num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
3718
3719                         switch (desc->channel[first_non_void].type) {
3720                         case UTIL_FORMAT_TYPE_FLOAT:
3721                                 num_format = V_008F14_IMG_NUM_FORMAT_FLOAT;
3722                                 break;
3723                         case UTIL_FORMAT_TYPE_SIGNED:
3724                                 if (desc->channel[first_non_void].normalized)
3725                                         num_format = V_008F14_IMG_NUM_FORMAT_SNORM;
3726                                 else if (desc->channel[first_non_void].pure_integer)
3727                                         num_format = V_008F14_IMG_NUM_FORMAT_SINT;
3728                                 else
3729                                         num_format = V_008F14_IMG_NUM_FORMAT_SSCALED;
3730                                 break;
3731                         case UTIL_FORMAT_TYPE_UNSIGNED:
3732                                 if (desc->channel[first_non_void].normalized)
3733                                         num_format = V_008F14_IMG_NUM_FORMAT_UNORM;
3734                                 else if (desc->channel[first_non_void].pure_integer)
3735                                         num_format = V_008F14_IMG_NUM_FORMAT_UINT;
3736                                 else
3737                                         num_format = V_008F14_IMG_NUM_FORMAT_USCALED;
3738                         }
3739                 }
3740         }
3741
3742         data_format = si_translate_texformat(&screen->b, pipe_format, desc, first_non_void);
3743         if (data_format == ~0) {
3744                 data_format = 0;
3745         }
3746
3747         /* S8 with Z32 HTILE needs a special format. */
3748         if (screen->info.chip_class >= GFX9 &&
3749             pipe_format == PIPE_FORMAT_S8_UINT &&
3750             tex->tc_compatible_htile)
3751                 data_format = V_008F14_IMG_DATA_FORMAT_S8_32;
3752
3753         if (!sampler &&
3754             (res->target == PIPE_TEXTURE_CUBE ||
3755              res->target == PIPE_TEXTURE_CUBE_ARRAY ||
3756              (screen->info.chip_class <= VI &&
3757               res->target == PIPE_TEXTURE_3D))) {
3758                 /* For the purpose of shader images, treat cube maps and 3D
3759                  * textures as 2D arrays. For 3D textures, the address
3760                  * calculations for mipmaps are different, so we rely on the
3761                  * caller to effectively disable mipmaps.
3762                  */
3763                 type = V_008F1C_SQ_RSRC_IMG_2D_ARRAY;
3764
3765                 assert(res->target != PIPE_TEXTURE_3D || (first_level == 0 && last_level == 0));
3766         } else {
3767                 type = si_tex_dim(screen, tex, target, num_samples);
3768         }
3769
3770         if (type == V_008F1C_SQ_RSRC_IMG_1D_ARRAY) {
3771                 height = 1;
3772                 depth = res->array_size;
3773         } else if (type == V_008F1C_SQ_RSRC_IMG_2D_ARRAY ||
3774                    type == V_008F1C_SQ_RSRC_IMG_2D_MSAA_ARRAY) {
3775                 if (sampler || res->target != PIPE_TEXTURE_3D)
3776                         depth = res->array_size;
3777         } else if (type == V_008F1C_SQ_RSRC_IMG_CUBE)
3778                 depth = res->array_size / 6;
3779
3780         state[0] = 0;
3781         state[1] = (S_008F14_DATA_FORMAT_GFX6(data_format) |
3782                     S_008F14_NUM_FORMAT_GFX6(num_format));
3783         state[2] = (S_008F18_WIDTH(width - 1) |
3784                     S_008F18_HEIGHT(height - 1) |
3785                     S_008F18_PERF_MOD(4));
3786         state[3] = (S_008F1C_DST_SEL_X(si_map_swizzle(swizzle[0])) |
3787                     S_008F1C_DST_SEL_Y(si_map_swizzle(swizzle[1])) |
3788                     S_008F1C_DST_SEL_Z(si_map_swizzle(swizzle[2])) |
3789                     S_008F1C_DST_SEL_W(si_map_swizzle(swizzle[3])) |
3790                     S_008F1C_BASE_LEVEL(num_samples > 1 ? 0 : first_level) |
3791                     S_008F1C_LAST_LEVEL(num_samples > 1 ?
3792                                         util_logbase2(num_samples) :
3793                                         last_level) |
3794                     S_008F1C_TYPE(type));
3795         state[4] = 0;
3796         state[5] = S_008F24_BASE_ARRAY(first_layer);
3797         state[6] = 0;
3798         state[7] = 0;
3799
3800         if (screen->info.chip_class >= GFX9) {
3801                 unsigned bc_swizzle = gfx9_border_color_swizzle(desc->swizzle);
3802
3803                 /* Depth is the the last accessible layer on Gfx9.
3804                  * The hw doesn't need to know the total number of layers.
3805                  */
3806                 if (type == V_008F1C_SQ_RSRC_IMG_3D)
3807                         state[4] |= S_008F20_DEPTH(depth - 1);
3808                 else
3809                         state[4] |= S_008F20_DEPTH(last_layer);
3810
3811                 state[4] |= S_008F20_BC_SWIZZLE(bc_swizzle);
3812                 state[5] |= S_008F24_MAX_MIP(num_samples > 1 ?
3813                                              util_logbase2(num_samples) :
3814                                              tex->buffer.b.b.last_level);
3815         } else {
3816                 state[3] |= S_008F1C_POW2_PAD(res->last_level > 0);
3817                 state[4] |= S_008F20_DEPTH(depth - 1);
3818                 state[5] |= S_008F24_LAST_ARRAY(last_layer);
3819         }
3820
3821         if (tex->dcc_offset) {
3822                 state[6] = S_008F28_ALPHA_IS_ON_MSB(vi_alpha_is_on_msb(pipe_format));
3823         } else {
3824                 /* The last dword is unused by hw. The shader uses it to clear
3825                  * bits in the first dword of sampler state.
3826                  */
3827                 if (screen->info.chip_class <= CIK && res->nr_samples <= 1) {
3828                         if (first_level == last_level)
3829                                 state[7] = C_008F30_MAX_ANISO_RATIO;
3830                         else
3831                                 state[7] = 0xffffffff;
3832                 }
3833         }
3834
3835         /* Initialize the sampler view for FMASK. */
3836         if (tex->surface.fmask_size) {
3837                 uint32_t data_format, num_format;
3838
3839                 va = tex->buffer.gpu_address + tex->fmask_offset;
3840
3841 #define FMASK(s,f) (((unsigned)(MAX2(1, s)) * 16) + (MAX2(1, f)))
3842                 if (screen->info.chip_class >= GFX9) {
3843                         data_format = V_008F14_IMG_DATA_FORMAT_FMASK;
3844                         switch (FMASK(res->nr_samples, res->nr_storage_samples)) {
3845                         case FMASK(2,1):
3846                                 num_format = V_008F14_IMG_FMASK_8_2_1;
3847                                 break;
3848                         case FMASK(2,2):
3849                                 num_format = V_008F14_IMG_FMASK_8_2_2;
3850                                 break;
3851                         case FMASK(4,1):
3852                                 num_format = V_008F14_IMG_FMASK_8_4_1;
3853                                 break;
3854                         case FMASK(4,2):
3855                                 num_format = V_008F14_IMG_FMASK_8_4_2;
3856                                 break;
3857                         case FMASK(4,4):
3858                                 num_format = V_008F14_IMG_FMASK_8_4_4;
3859                                 break;
3860                         case FMASK(8,1):
3861                                 num_format = V_008F14_IMG_FMASK_8_8_1;
3862                                 break;
3863                         case FMASK(8,2):
3864                                 num_format = V_008F14_IMG_FMASK_16_8_2;
3865                                 break;
3866                         case FMASK(8,4):
3867                                 num_format = V_008F14_IMG_FMASK_32_8_4;
3868                                 break;
3869                         case FMASK(8,8):
3870                                 num_format = V_008F14_IMG_FMASK_32_8_8;
3871                                 break;
3872                         case FMASK(16,1):
3873                                 num_format = V_008F14_IMG_FMASK_16_16_1;
3874                                 break;
3875                         case FMASK(16,2):
3876                                 num_format = V_008F14_IMG_FMASK_32_16_2;
3877                                 break;
3878                         case FMASK(16,4):
3879                                 num_format = V_008F14_IMG_FMASK_64_16_4;
3880                                 break;
3881                         case FMASK(16,8):
3882                                 num_format = V_008F14_IMG_FMASK_64_16_8;
3883                                 break;
3884                         default:
3885                                 unreachable("invalid nr_samples");
3886                         }
3887                 } else {
3888                         switch (FMASK(res->nr_samples, res->nr_storage_samples)) {
3889                         case FMASK(2,1):
3890                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S2_F1;
3891                                 break;
3892                         case FMASK(2,2):
3893                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S2_F2;
3894                                 break;
3895                         case FMASK(4,1):
3896                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S4_F1;
3897                                 break;
3898                         case FMASK(4,2):
3899                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S4_F2;
3900                                 break;
3901                         case FMASK(4,4):
3902                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S4_F4;
3903                                 break;
3904                         case FMASK(8,1):
3905                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK8_S8_F1;
3906                                 break;
3907                         case FMASK(8,2):
3908                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK16_S8_F2;
3909                                 break;
3910                         case FMASK(8,4):
3911                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK32_S8_F4;
3912                                 break;
3913                         case FMASK(8,8):
3914                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK32_S8_F8;
3915                                 break;
3916                         case FMASK(16,1):
3917                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK16_S16_F1;
3918                                 break;
3919                         case FMASK(16,2):
3920                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK32_S16_F2;
3921                                 break;
3922                         case FMASK(16,4):
3923                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK64_S16_F4;
3924                                 break;
3925                         case FMASK(16,8):
3926                                 data_format = V_008F14_IMG_DATA_FORMAT_FMASK64_S16_F8;
3927                                 break;
3928                         default:
3929                                 unreachable("invalid nr_samples");
3930                         }
3931                         num_format = V_008F14_IMG_NUM_FORMAT_UINT;
3932                 }
3933 #undef FMASK
3934
3935                 fmask_state[0] = (va >> 8) | tex->surface.fmask_tile_swizzle;
3936                 fmask_state[1] = S_008F14_BASE_ADDRESS_HI(va >> 40) |
3937                                  S_008F14_DATA_FORMAT_GFX6(data_format) |
3938                                  S_008F14_NUM_FORMAT_GFX6(num_format);
3939                 fmask_state[2] = S_008F18_WIDTH(width - 1) |
3940                                  S_008F18_HEIGHT(height - 1);
3941                 fmask_state[3] = S_008F1C_DST_SEL_X(V_008F1C_SQ_SEL_X) |
3942                                  S_008F1C_DST_SEL_Y(V_008F1C_SQ_SEL_X) |
3943                                  S_008F1C_DST_SEL_Z(V_008F1C_SQ_SEL_X) |
3944                                  S_008F1C_DST_SEL_W(V_008F1C_SQ_SEL_X) |
3945                                  S_008F1C_TYPE(si_tex_dim(screen, tex, target, 0));
3946                 fmask_state[4] = 0;
3947                 fmask_state[5] = S_008F24_BASE_ARRAY(first_layer);
3948                 fmask_state[6] = 0;
3949                 fmask_state[7] = 0;
3950
3951                 if (screen->info.chip_class >= GFX9) {
3952                         fmask_state[3] |= S_008F1C_SW_MODE(tex->surface.u.gfx9.fmask.swizzle_mode);
3953                         fmask_state[4] |= S_008F20_DEPTH(last_layer) |
3954                                           S_008F20_PITCH_GFX9(tex->surface.u.gfx9.fmask.epitch);
3955                         fmask_state[5] |= S_008F24_META_PIPE_ALIGNED(tex->surface.u.gfx9.cmask.pipe_aligned) |
3956                                           S_008F24_META_RB_ALIGNED(tex->surface.u.gfx9.cmask.rb_aligned);
3957                 } else {
3958                         fmask_state[3] |= S_008F1C_TILING_INDEX(tex->surface.u.legacy.fmask.tiling_index);
3959                         fmask_state[4] |= S_008F20_DEPTH(depth - 1) |
3960                                           S_008F20_PITCH_GFX6(tex->surface.u.legacy.fmask.pitch_in_pixels - 1);
3961                         fmask_state[5] |= S_008F24_LAST_ARRAY(last_layer);
3962                 }
3963         }
3964 }
3965
3966 /**
3967  * Create a sampler view.
3968  *
3969  * @param ctx           context
3970  * @param texture       texture
3971  * @param state         sampler view template
3972  * @param width0        width0 override (for compressed textures as int)
3973  * @param height0       height0 override (for compressed textures as int)
3974  * @param force_level   set the base address to the level (for compressed textures)
3975  */
3976 struct pipe_sampler_view *
3977 si_create_sampler_view_custom(struct pipe_context *ctx,
3978                               struct pipe_resource *texture,
3979                               const struct pipe_sampler_view *state,
3980                               unsigned width0, unsigned height0,
3981                               unsigned force_level)
3982 {
3983         struct si_context *sctx = (struct si_context*)ctx;
3984         struct si_sampler_view *view = CALLOC_STRUCT(si_sampler_view);
3985         struct si_texture *tex = (struct si_texture*)texture;
3986         unsigned base_level, first_level, last_level;
3987         unsigned char state_swizzle[4];
3988         unsigned height, depth, width;
3989         unsigned last_layer = state->u.tex.last_layer;
3990         enum pipe_format pipe_format;
3991         const struct legacy_surf_level *surflevel;
3992
3993         if (!view)
3994                 return NULL;
3995
3996         /* initialize base object */
3997         view->base = *state;
3998         view->base.texture = NULL;
3999         view->base.reference.count = 1;
4000         view->base.context = ctx;
4001
4002         assert(texture);
4003         pipe_resource_reference(&view->base.texture, texture);
4004
4005         if (state->format == PIPE_FORMAT_X24S8_UINT ||
4006             state->format == PIPE_FORMAT_S8X24_UINT ||
4007             state->format == PIPE_FORMAT_X32_S8X24_UINT ||
4008             state->format == PIPE_FORMAT_S8_UINT)
4009                 view->is_stencil_sampler = true;
4010
4011         /* Buffer resource. */
4012         if (texture->target == PIPE_BUFFER) {
4013                 si_make_buffer_descriptor(sctx->screen,
4014                                           r600_resource(texture),
4015                                           state->format,
4016                                           state->u.buf.offset,
4017                                           state->u.buf.size,
4018                                           view->state);
4019                 return &view->base;
4020         }
4021
4022         state_swizzle[0] = state->swizzle_r;
4023         state_swizzle[1] = state->swizzle_g;
4024         state_swizzle[2] = state->swizzle_b;
4025         state_swizzle[3] = state->swizzle_a;
4026
4027         base_level = 0;
4028         first_level = state->u.tex.first_level;
4029         last_level = state->u.tex.last_level;
4030         width = width0;
4031         height = height0;
4032         depth = texture->depth0;
4033
4034         if (sctx->chip_class <= VI && force_level) {
4035                 assert(force_level == first_level &&
4036                        force_level == last_level);
4037                 base_level = force_level;
4038                 first_level = 0;
4039                 last_level = 0;
4040                 width = u_minify(width, force_level);
4041                 height = u_minify(height, force_level);
4042                 depth = u_minify(depth, force_level);
4043         }
4044
4045         /* This is not needed if state trackers set last_layer correctly. */
4046         if (state->target == PIPE_TEXTURE_1D ||
4047             state->target == PIPE_TEXTURE_2D ||
4048             state->target == PIPE_TEXTURE_RECT ||
4049             state->target == PIPE_TEXTURE_CUBE)
4050                 last_layer = state->u.tex.first_layer;
4051
4052         /* Texturing with separate depth and stencil. */
4053         pipe_format = state->format;
4054
4055         /* Depth/stencil texturing sometimes needs separate texture. */
4056         if (tex->is_depth && !si_can_sample_zs(tex, view->is_stencil_sampler)) {
4057                 if (!tex->flushed_depth_texture &&
4058                     !si_init_flushed_depth_texture(ctx, texture, NULL)) {
4059                         pipe_resource_reference(&view->base.texture, NULL);
4060                         FREE(view);
4061                         return NULL;
4062                 }
4063
4064                 assert(tex->flushed_depth_texture);
4065
4066                 /* Override format for the case where the flushed texture
4067                  * contains only Z or only S.
4068                  */
4069                 if (tex->flushed_depth_texture->buffer.b.b.format != tex->buffer.b.b.format)
4070                         pipe_format = tex->flushed_depth_texture->buffer.b.b.format;
4071
4072                 tex = tex->flushed_depth_texture;
4073         }
4074
4075         surflevel = tex->surface.u.legacy.level;
4076
4077         if (tex->db_compatible) {
4078                 if (!view->is_stencil_sampler)
4079                         pipe_format = tex->db_render_format;
4080
4081                 switch (pipe_format) {
4082                 case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
4083                         pipe_format = PIPE_FORMAT_Z32_FLOAT;
4084                         break;
4085                 case PIPE_FORMAT_X8Z24_UNORM:
4086                 case PIPE_FORMAT_S8_UINT_Z24_UNORM:
4087                         /* Z24 is always stored like this for DB
4088                          * compatibility.
4089                          */
4090                         pipe_format = PIPE_FORMAT_Z24X8_UNORM;
4091                         break;
4092                 case PIPE_FORMAT_X24S8_UINT:
4093                 case PIPE_FORMAT_S8X24_UINT:
4094                 case PIPE_FORMAT_X32_S8X24_UINT:
4095                         pipe_format = PIPE_FORMAT_S8_UINT;
4096                         surflevel = tex->surface.u.legacy.stencil_level;
4097                         break;
4098                 default:;
4099                 }
4100         }
4101
4102         view->dcc_incompatible =
4103                 vi_dcc_formats_are_incompatible(texture,
4104                                                 state->u.tex.first_level,
4105                                                 state->format);
4106
4107         si_make_texture_descriptor(sctx->screen, tex, true,
4108                                    state->target, pipe_format, state_swizzle,
4109                                    first_level, last_level,
4110                                    state->u.tex.first_layer, last_layer,
4111                                    width, height, depth,
4112                                    view->state, view->fmask_state);
4113
4114         unsigned num_format = G_008F14_NUM_FORMAT_GFX6(view->state[1]);
4115         view->is_integer =
4116                 num_format == V_008F14_IMG_NUM_FORMAT_USCALED ||
4117                 num_format == V_008F14_IMG_NUM_FORMAT_SSCALED ||
4118                 num_format == V_008F14_IMG_NUM_FORMAT_UINT ||
4119                 num_format == V_008F14_IMG_NUM_FORMAT_SINT;
4120         view->base_level_info = &surflevel[base_level];
4121         view->base_level = base_level;
4122         view->block_width = util_format_get_blockwidth(pipe_format);
4123         return &view->base;
4124 }
4125
4126 static struct pipe_sampler_view *
4127 si_create_sampler_view(struct pipe_context *ctx,
4128                        struct pipe_resource *texture,
4129                        const struct pipe_sampler_view *state)
4130 {
4131         return si_create_sampler_view_custom(ctx, texture, state,
4132                                              texture ? texture->width0 : 0,
4133                                              texture ? texture->height0 : 0, 0);
4134 }
4135
4136 static void si_sampler_view_destroy(struct pipe_context *ctx,
4137                                     struct pipe_sampler_view *state)
4138 {
4139         struct si_sampler_view *view = (struct si_sampler_view *)state;
4140
4141         pipe_resource_reference(&state->texture, NULL);
4142         FREE(view);
4143 }
4144
4145 static bool wrap_mode_uses_border_color(unsigned wrap, bool linear_filter)
4146 {
4147         return wrap == PIPE_TEX_WRAP_CLAMP_TO_BORDER ||
4148                wrap == PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER ||
4149                (linear_filter &&
4150                 (wrap == PIPE_TEX_WRAP_CLAMP ||
4151                  wrap == PIPE_TEX_WRAP_MIRROR_CLAMP));
4152 }
4153
4154 static uint32_t si_translate_border_color(struct si_context *sctx,
4155                                           const struct pipe_sampler_state *state,
4156                                           const union pipe_color_union *color,
4157                                           bool is_integer)
4158 {
4159         bool linear_filter = state->min_img_filter != PIPE_TEX_FILTER_NEAREST ||
4160                              state->mag_img_filter != PIPE_TEX_FILTER_NEAREST;
4161
4162         if (!wrap_mode_uses_border_color(state->wrap_s, linear_filter) &&
4163             !wrap_mode_uses_border_color(state->wrap_t, linear_filter) &&
4164             !wrap_mode_uses_border_color(state->wrap_r, linear_filter))
4165                 return S_008F3C_BORDER_COLOR_TYPE(V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK);
4166
4167 #define simple_border_types(elt) \
4168 do { \
4169         if (color->elt[0] == 0 && color->elt[1] == 0 &&                         \
4170             color->elt[2] == 0 && color->elt[3] == 0)                           \
4171                 return S_008F3C_BORDER_COLOR_TYPE(V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK); \
4172         if (color->elt[0] == 0 && color->elt[1] == 0 &&                         \
4173             color->elt[2] == 0 && color->elt[3] == 1)                           \
4174                 return S_008F3C_BORDER_COLOR_TYPE(V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK); \
4175         if (color->elt[0] == 1 && color->elt[1] == 1 &&                         \
4176             color->elt[2] == 1 && color->elt[3] == 1)                           \
4177                 return S_008F3C_BORDER_COLOR_TYPE(V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE); \
4178 } while (false)
4179
4180         if (is_integer)
4181                 simple_border_types(ui);
4182         else
4183                 simple_border_types(f);
4184
4185 #undef simple_border_types
4186
4187         int i;
4188
4189         /* Check if the border has been uploaded already. */
4190         for (i = 0; i < sctx->border_color_count; i++)
4191                 if (memcmp(&sctx->border_color_table[i], color,
4192                            sizeof(*color)) == 0)
4193                         break;
4194
4195         if (i >= SI_MAX_BORDER_COLORS) {
4196                 /* Getting 4096 unique border colors is very unlikely. */
4197                 fprintf(stderr, "radeonsi: The border color table is full. "
4198                         "Any new border colors will be just black. "
4199                         "Please file a bug.\n");
4200                 return S_008F3C_BORDER_COLOR_TYPE(V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK);
4201         }
4202
4203         if (i == sctx->border_color_count) {
4204                 /* Upload a new border color. */
4205                 memcpy(&sctx->border_color_table[i], color,
4206                        sizeof(*color));
4207                 util_memcpy_cpu_to_le32(&sctx->border_color_map[i],
4208                                         color, sizeof(*color));
4209                 sctx->border_color_count++;
4210         }
4211
4212         return S_008F3C_BORDER_COLOR_PTR(i) |
4213                S_008F3C_BORDER_COLOR_TYPE(V_008F3C_SQ_TEX_BORDER_COLOR_REGISTER);
4214 }
4215
4216 static inline int S_FIXED(float value, unsigned frac_bits)
4217 {
4218         return value * (1 << frac_bits);
4219 }
4220
4221 static inline unsigned si_tex_filter(unsigned filter, unsigned max_aniso)
4222 {
4223         if (filter == PIPE_TEX_FILTER_LINEAR)
4224                 return max_aniso > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR
4225                                      : V_008F38_SQ_TEX_XY_FILTER_BILINEAR;
4226         else
4227                 return max_aniso > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT
4228                                      : V_008F38_SQ_TEX_XY_FILTER_POINT;
4229 }
4230
4231 static inline unsigned si_tex_aniso_filter(unsigned filter)
4232 {
4233         if (filter < 2)
4234                 return 0;
4235         if (filter < 4)
4236                 return 1;
4237         if (filter < 8)
4238                 return 2;
4239         if (filter < 16)
4240                 return 3;
4241         return 4;
4242 }
4243
4244 static void *si_create_sampler_state(struct pipe_context *ctx,
4245                                      const struct pipe_sampler_state *state)
4246 {
4247         struct si_context *sctx = (struct si_context *)ctx;
4248         struct si_screen *sscreen = sctx->screen;
4249         struct si_sampler_state *rstate = CALLOC_STRUCT(si_sampler_state);
4250         unsigned max_aniso = sscreen->force_aniso >= 0 ? sscreen->force_aniso
4251                                                        : state->max_anisotropy;
4252         unsigned max_aniso_ratio = si_tex_aniso_filter(max_aniso);
4253         union pipe_color_union clamped_border_color;
4254
4255         if (!rstate) {
4256                 return NULL;
4257         }
4258
4259 #ifdef DEBUG
4260         rstate->magic = SI_SAMPLER_STATE_MAGIC;
4261 #endif
4262         rstate->val[0] = (S_008F30_CLAMP_X(si_tex_wrap(state->wrap_s)) |
4263                           S_008F30_CLAMP_Y(si_tex_wrap(state->wrap_t)) |
4264                           S_008F30_CLAMP_Z(si_tex_wrap(state->wrap_r)) |
4265                           S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
4266                           S_008F30_DEPTH_COMPARE_FUNC(si_tex_compare(state->compare_func)) |
4267                           S_008F30_FORCE_UNNORMALIZED(!state->normalized_coords) |
4268                           S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
4269                           S_008F30_ANISO_BIAS(max_aniso_ratio) |
4270                           S_008F30_DISABLE_CUBE_WRAP(!state->seamless_cube_map) |
4271                           S_008F30_COMPAT_MODE(sctx->chip_class >= VI));
4272         rstate->val[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(state->min_lod, 0, 15), 8)) |
4273                           S_008F34_MAX_LOD(S_FIXED(CLAMP(state->max_lod, 0, 15), 8)) |
4274                           S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
4275         rstate->val[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(state->lod_bias, -16, 16), 8)) |
4276                           S_008F38_XY_MAG_FILTER(si_tex_filter(state->mag_img_filter, max_aniso)) |
4277                           S_008F38_XY_MIN_FILTER(si_tex_filter(state->min_img_filter, max_aniso)) |
4278                           S_008F38_MIP_FILTER(si_tex_mipfilter(state->min_mip_filter)) |
4279                           S_008F38_MIP_POINT_PRECLAMP(0) |
4280                           S_008F38_DISABLE_LSB_CEIL(sctx->chip_class <= VI) |
4281                           S_008F38_FILTER_PREC_FIX(1) |
4282                           S_008F38_ANISO_OVERRIDE(sctx->chip_class >= VI));
4283         rstate->val[3] = si_translate_border_color(sctx, state, &state->border_color, false);
4284
4285         /* Create sampler resource for integer textures. */
4286         memcpy(rstate->integer_val, rstate->val, sizeof(rstate->val));
4287         rstate->integer_val[3] = si_translate_border_color(sctx, state, &state->border_color, true);
4288
4289         /* Create sampler resource for upgraded depth textures. */
4290         memcpy(rstate->upgraded_depth_val, rstate->val, sizeof(rstate->val));
4291
4292         for (unsigned i = 0; i < 4; ++i) {
4293                 /* Use channel 0 on purpose, so that we can use OPAQUE_WHITE
4294                  * when the border color is 1.0. */
4295                 clamped_border_color.f[i] = CLAMP(state->border_color.f[0], 0, 1);
4296         }
4297
4298         if (memcmp(&state->border_color, &clamped_border_color, sizeof(clamped_border_color)) == 0)
4299                 rstate->upgraded_depth_val[3] |= S_008F3C_UPGRADED_DEPTH(1);
4300         else
4301                 rstate->upgraded_depth_val[3] =
4302                         si_translate_border_color(sctx, state, &clamped_border_color, false) |
4303                         S_008F3C_UPGRADED_DEPTH(1);
4304
4305         return rstate;
4306 }
4307
4308 static void si_set_sample_mask(struct pipe_context *ctx, unsigned sample_mask)
4309 {
4310         struct si_context *sctx = (struct si_context *)ctx;
4311
4312         if (sctx->sample_mask == (uint16_t)sample_mask)
4313                 return;
4314
4315         sctx->sample_mask = sample_mask;
4316         si_mark_atom_dirty(sctx, &sctx->atoms.s.sample_mask);
4317 }
4318
4319 static void si_emit_sample_mask(struct si_context *sctx)
4320 {
4321         struct radeon_cmdbuf *cs = sctx->gfx_cs;
4322         unsigned mask = sctx->sample_mask;
4323
4324         /* Needed for line and polygon smoothing as well as for the Polaris
4325          * small primitive filter. We expect the state tracker to take care of
4326          * this for us.
4327          */
4328         assert(mask == 0xffff || sctx->framebuffer.nr_samples > 1 ||
4329                (mask & 1 && sctx->blitter->running));
4330
4331         radeon_set_context_reg_seq(cs, R_028C38_PA_SC_AA_MASK_X0Y0_X1Y0, 2);
4332         radeon_emit(cs, mask | (mask << 16));
4333         radeon_emit(cs, mask | (mask << 16));
4334 }
4335
4336 static void si_delete_sampler_state(struct pipe_context *ctx, void *state)
4337 {
4338 #ifdef DEBUG
4339         struct si_sampler_state *s = state;
4340
4341         assert(s->magic == SI_SAMPLER_STATE_MAGIC);
4342         s->magic = 0;
4343 #endif
4344         free(state);
4345 }
4346
4347 /*
4348  * Vertex elements & buffers
4349  */
4350
4351 static void *si_create_vertex_elements(struct pipe_context *ctx,
4352                                        unsigned count,
4353                                        const struct pipe_vertex_element *elements)
4354 {
4355         struct si_screen *sscreen = (struct si_screen*)ctx->screen;
4356         struct si_vertex_elements *v = CALLOC_STRUCT(si_vertex_elements);
4357         bool used[SI_NUM_VERTEX_BUFFERS] = {};
4358         int i;
4359
4360         assert(count <= SI_MAX_ATTRIBS);
4361         if (!v)
4362                 return NULL;
4363
4364         v->count = count;
4365         v->desc_list_byte_size = align(count * 16, SI_CPDMA_ALIGNMENT);
4366
4367         for (i = 0; i < count; ++i) {
4368                 const struct util_format_description *desc;
4369                 const struct util_format_channel_description *channel;
4370                 unsigned data_format, num_format;
4371                 int first_non_void;
4372                 unsigned vbo_index = elements[i].vertex_buffer_index;
4373                 unsigned char swizzle[4];
4374
4375                 if (vbo_index >= SI_NUM_VERTEX_BUFFERS) {
4376                         FREE(v);
4377                         return NULL;
4378                 }
4379
4380                 if (elements[i].instance_divisor) {
4381                         v->uses_instance_divisors = true;
4382                         v->instance_divisors[i] = elements[i].instance_divisor;
4383
4384                         if (v->instance_divisors[i] == 1)
4385                                 v->instance_divisor_is_one |= 1u << i;
4386                         else
4387                                 v->instance_divisor_is_fetched |= 1u << i;
4388                 }
4389
4390                 if (!used[vbo_index]) {
4391                         v->first_vb_use_mask |= 1 << i;
4392                         used[vbo_index] = true;
4393                 }
4394
4395                 desc = util_format_description(elements[i].src_format);
4396                 first_non_void = util_format_get_first_non_void_channel(elements[i].src_format);
4397                 data_format = si_translate_buffer_dataformat(ctx->screen, desc, first_non_void);
4398                 num_format = si_translate_buffer_numformat(ctx->screen, desc, first_non_void);
4399                 channel = first_non_void >= 0 ? &desc->channel[first_non_void] : NULL;
4400                 memcpy(swizzle, desc->swizzle, sizeof(swizzle));
4401
4402                 v->format_size[i] = desc->block.bits / 8;
4403                 v->src_offset[i] = elements[i].src_offset;
4404                 v->vertex_buffer_index[i] = vbo_index;
4405
4406                 /* The hardware always treats the 2-bit alpha channel as
4407                  * unsigned, so a shader workaround is needed. The affected
4408                  * chips are VI and older except Stoney (GFX8.1).
4409                  */
4410                 if (data_format == V_008F0C_BUF_DATA_FORMAT_2_10_10_10 &&
4411                     sscreen->info.chip_class <= VI &&
4412                     sscreen->info.family != CHIP_STONEY) {
4413                         if (num_format == V_008F0C_BUF_NUM_FORMAT_SNORM) {
4414                                 v->fix_fetch[i] = SI_FIX_FETCH_A2_SNORM;
4415                         } else if (num_format == V_008F0C_BUF_NUM_FORMAT_SSCALED) {
4416                                 v->fix_fetch[i] = SI_FIX_FETCH_A2_SSCALED;
4417                         } else if (num_format == V_008F0C_BUF_NUM_FORMAT_SINT) {
4418                                 /* This isn't actually used in OpenGL. */
4419                                 v->fix_fetch[i] = SI_FIX_FETCH_A2_SINT;
4420                         }
4421                 } else if (channel && channel->type == UTIL_FORMAT_TYPE_FIXED) {
4422                         if (desc->swizzle[3] == PIPE_SWIZZLE_1)
4423                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBX_32_FIXED;
4424                         else
4425                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBA_32_FIXED;
4426                 } else if (channel && channel->size == 32 && !channel->pure_integer) {
4427                         if (channel->type == UTIL_FORMAT_TYPE_SIGNED) {
4428                                 if (channel->normalized) {
4429                                         if (desc->swizzle[3] == PIPE_SWIZZLE_1)
4430                                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBX_32_SNORM;
4431                                         else
4432                                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBA_32_SNORM;
4433                                 } else {
4434                                         v->fix_fetch[i] = SI_FIX_FETCH_RGBA_32_SSCALED;
4435                                 }
4436                         } else if (channel->type == UTIL_FORMAT_TYPE_UNSIGNED) {
4437                                 if (channel->normalized) {
4438                                         if (desc->swizzle[3] == PIPE_SWIZZLE_1)
4439                                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBX_32_UNORM;
4440                                         else
4441                                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBA_32_UNORM;
4442                                 } else {
4443                                         v->fix_fetch[i] = SI_FIX_FETCH_RGBA_32_USCALED;
4444                                 }
4445                         }
4446                 } else if (channel && channel->size == 64 &&
4447                            channel->type == UTIL_FORMAT_TYPE_FLOAT) {
4448                         switch (desc->nr_channels) {
4449                         case 1:
4450                         case 2:
4451                                 v->fix_fetch[i] = SI_FIX_FETCH_RG_64_FLOAT;
4452                                 swizzle[0] = PIPE_SWIZZLE_X;
4453                                 swizzle[1] = PIPE_SWIZZLE_Y;
4454                                 swizzle[2] = desc->nr_channels == 2 ? PIPE_SWIZZLE_Z : PIPE_SWIZZLE_0;
4455                                 swizzle[3] = desc->nr_channels == 2 ? PIPE_SWIZZLE_W : PIPE_SWIZZLE_0;
4456                                 break;
4457                         case 3:
4458                                 v->fix_fetch[i] = SI_FIX_FETCH_RGB_64_FLOAT;
4459                                 swizzle[0] = PIPE_SWIZZLE_X; /* 3 loads */
4460                                 swizzle[1] = PIPE_SWIZZLE_Y;
4461                                 swizzle[2] = PIPE_SWIZZLE_0;
4462                                 swizzle[3] = PIPE_SWIZZLE_0;
4463                                 break;
4464                         case 4:
4465                                 v->fix_fetch[i] = SI_FIX_FETCH_RGBA_64_FLOAT;
4466                                 swizzle[0] = PIPE_SWIZZLE_X; /* 2 loads */
4467                                 swizzle[1] = PIPE_SWIZZLE_Y;
4468                                 swizzle[2] = PIPE_SWIZZLE_Z;
4469                                 swizzle[3] = PIPE_SWIZZLE_W;
4470                                 break;
4471                         default:
4472                                 assert(0);
4473                         }
4474                 } else if (channel && desc->nr_channels == 3) {
4475                         assert(desc->swizzle[0] == PIPE_SWIZZLE_X);
4476
4477                         if (channel->size == 8) {
4478                                 if (channel->pure_integer)
4479                                         v->fix_fetch[i] = SI_FIX_FETCH_RGB_8_INT;
4480                                 else
4481                                         v->fix_fetch[i] = SI_FIX_FETCH_RGB_8;
4482                         } else if (channel->size == 16) {
4483                                 if (channel->pure_integer)
4484                                         v->fix_fetch[i] = SI_FIX_FETCH_RGB_16_INT;
4485                                 else
4486                                         v->fix_fetch[i] = SI_FIX_FETCH_RGB_16;
4487                         }
4488                 }
4489
4490                 v->rsrc_word3[i] = S_008F0C_DST_SEL_X(si_map_swizzle(swizzle[0])) |
4491                                    S_008F0C_DST_SEL_Y(si_map_swizzle(swizzle[1])) |
4492                                    S_008F0C_DST_SEL_Z(si_map_swizzle(swizzle[2])) |
4493                                    S_008F0C_DST_SEL_W(si_map_swizzle(swizzle[3])) |
4494                                    S_008F0C_NUM_FORMAT(num_format) |
4495                                    S_008F0C_DATA_FORMAT(data_format);
4496         }
4497         return v;
4498 }
4499
4500 static void si_bind_vertex_elements(struct pipe_context *ctx, void *state)
4501 {
4502         struct si_context *sctx = (struct si_context *)ctx;
4503         struct si_vertex_elements *old = sctx->vertex_elements;
4504         struct si_vertex_elements *v = (struct si_vertex_elements*)state;
4505
4506         sctx->vertex_elements = v;
4507         sctx->vertex_buffers_dirty = true;
4508
4509         if (v &&
4510             (!old ||
4511              old->count != v->count ||
4512              old->uses_instance_divisors != v->uses_instance_divisors ||
4513              v->uses_instance_divisors || /* we don't check which divisors changed */
4514              memcmp(old->fix_fetch, v->fix_fetch, sizeof(v->fix_fetch[0]) * v->count)))
4515                 sctx->do_update_shaders = true;
4516
4517         if (v && v->instance_divisor_is_fetched) {
4518                 struct pipe_constant_buffer cb;
4519
4520                 cb.buffer = NULL;
4521                 cb.user_buffer = v->instance_divisors;
4522                 cb.buffer_offset = 0;
4523                 cb.buffer_size = sizeof(uint32_t) * v->count;
4524                 si_set_rw_buffer(sctx, SI_VS_CONST_INSTANCE_DIVISORS, &cb);
4525         }
4526 }
4527
4528 static void si_delete_vertex_element(struct pipe_context *ctx, void *state)
4529 {
4530         struct si_context *sctx = (struct si_context *)ctx;
4531
4532         if (sctx->vertex_elements == state)
4533                 sctx->vertex_elements = NULL;
4534         FREE(state);
4535 }
4536
4537 static void si_set_vertex_buffers(struct pipe_context *ctx,
4538                                   unsigned start_slot, unsigned count,
4539                                   const struct pipe_vertex_buffer *buffers)
4540 {
4541         struct si_context *sctx = (struct si_context *)ctx;
4542         struct pipe_vertex_buffer *dst = sctx->vertex_buffer + start_slot;
4543         int i;
4544
4545         assert(start_slot + count <= ARRAY_SIZE(sctx->vertex_buffer));
4546
4547         if (buffers) {
4548                 for (i = 0; i < count; i++) {
4549                         const struct pipe_vertex_buffer *src = buffers + i;
4550                         struct pipe_vertex_buffer *dsti = dst + i;
4551                         struct pipe_resource *buf = src->buffer.resource;
4552
4553                         pipe_resource_reference(&dsti->buffer.resource, buf);
4554                         dsti->buffer_offset = src->buffer_offset;
4555                         dsti->stride = src->stride;
4556                         si_context_add_resource_size(sctx, buf);
4557                         if (buf)
4558                                 r600_resource(buf)->bind_history |= PIPE_BIND_VERTEX_BUFFER;
4559                 }
4560         } else {
4561                 for (i = 0; i < count; i++) {
4562                         pipe_resource_reference(&dst[i].buffer.resource, NULL);
4563                 }
4564         }
4565         sctx->vertex_buffers_dirty = true;
4566 }
4567
4568 /*
4569  * Misc
4570  */
4571
4572 static void si_set_tess_state(struct pipe_context *ctx,
4573                               const float default_outer_level[4],
4574                               const float default_inner_level[2])
4575 {
4576         struct si_context *sctx = (struct si_context *)ctx;
4577         struct pipe_constant_buffer cb;
4578         float array[8];
4579
4580         memcpy(array, default_outer_level, sizeof(float) * 4);
4581         memcpy(array+4, default_inner_level, sizeof(float) * 2);
4582
4583         cb.buffer = NULL;
4584         cb.user_buffer = NULL;
4585         cb.buffer_size = sizeof(array);
4586
4587         si_upload_const_buffer(sctx, (struct r600_resource**)&cb.buffer,
4588                                (void*)array, sizeof(array),
4589                                &cb.buffer_offset);
4590
4591         si_set_rw_buffer(sctx, SI_HS_CONST_DEFAULT_TESS_LEVELS, &cb);
4592         pipe_resource_reference(&cb.buffer, NULL);
4593 }
4594
4595 static void si_texture_barrier(struct pipe_context *ctx, unsigned flags)
4596 {
4597         struct si_context *sctx = (struct si_context *)ctx;
4598
4599         si_update_fb_dirtiness_after_rendering(sctx);
4600
4601         /* Multisample surfaces are flushed in si_decompress_textures. */
4602         if (sctx->framebuffer.uncompressed_cb_mask)
4603                 si_make_CB_shader_coherent(sctx, sctx->framebuffer.nr_samples,
4604                                            sctx->framebuffer.CB_has_shader_readable_metadata);
4605 }
4606
4607 /* This only ensures coherency for shader image/buffer stores. */
4608 static void si_memory_barrier(struct pipe_context *ctx, unsigned flags)
4609 {
4610         struct si_context *sctx = (struct si_context *)ctx;
4611
4612         /* Subsequent commands must wait for all shader invocations to
4613          * complete. */
4614         sctx->flags |= SI_CONTEXT_PS_PARTIAL_FLUSH |
4615                          SI_CONTEXT_CS_PARTIAL_FLUSH;
4616
4617         if (flags & PIPE_BARRIER_CONSTANT_BUFFER)
4618                 sctx->flags |= SI_CONTEXT_INV_SMEM_L1 |
4619                                  SI_CONTEXT_INV_VMEM_L1;
4620
4621         if (flags & (PIPE_BARRIER_VERTEX_BUFFER |
4622                      PIPE_BARRIER_SHADER_BUFFER |
4623                      PIPE_BARRIER_TEXTURE |
4624                      PIPE_BARRIER_IMAGE |
4625                      PIPE_BARRIER_STREAMOUT_BUFFER |
4626                      PIPE_BARRIER_GLOBAL_BUFFER)) {
4627                 /* As far as I can tell, L1 contents are written back to L2
4628                  * automatically at end of shader, but the contents of other
4629                  * L1 caches might still be stale. */
4630                 sctx->flags |= SI_CONTEXT_INV_VMEM_L1;
4631         }
4632
4633         if (flags & PIPE_BARRIER_INDEX_BUFFER) {
4634                 /* Indices are read through TC L2 since VI.
4635                  * L1 isn't used.
4636                  */
4637                 if (sctx->screen->info.chip_class <= CIK)
4638                         sctx->flags |= SI_CONTEXT_WRITEBACK_GLOBAL_L2;
4639         }
4640
4641         /* MSAA color, any depth and any stencil are flushed in
4642          * si_decompress_textures when needed.
4643          */
4644         if (flags & PIPE_BARRIER_FRAMEBUFFER &&
4645             sctx->framebuffer.uncompressed_cb_mask) {
4646                 sctx->flags |= SI_CONTEXT_FLUSH_AND_INV_CB;
4647
4648                 if (sctx->chip_class <= VI)
4649                         sctx->flags |= SI_CONTEXT_WRITEBACK_GLOBAL_L2;
4650         }
4651
4652         /* Indirect buffers use TC L2 on GFX9, but not older hw. */
4653         if (sctx->screen->info.chip_class <= VI &&
4654             flags & PIPE_BARRIER_INDIRECT_BUFFER)
4655                 sctx->flags |= SI_CONTEXT_WRITEBACK_GLOBAL_L2;
4656 }
4657
4658 static void *si_create_blend_custom(struct si_context *sctx, unsigned mode)
4659 {
4660         struct pipe_blend_state blend;
4661
4662         memset(&blend, 0, sizeof(blend));
4663         blend.independent_blend_enable = true;
4664         blend.rt[0].colormask = 0xf;
4665         return si_create_blend_state_mode(&sctx->b, &blend, mode);
4666 }
4667
4668 static void si_init_config(struct si_context *sctx);
4669
4670 void si_init_state_functions(struct si_context *sctx)
4671 {
4672         sctx->atoms.s.framebuffer.emit = si_emit_framebuffer_state;
4673         sctx->atoms.s.msaa_sample_locs.emit = si_emit_msaa_sample_locs;
4674         sctx->atoms.s.db_render_state.emit = si_emit_db_render_state;
4675         sctx->atoms.s.dpbb_state.emit = si_emit_dpbb_state;
4676         sctx->atoms.s.msaa_config.emit = si_emit_msaa_config;
4677         sctx->atoms.s.sample_mask.emit = si_emit_sample_mask;
4678         sctx->atoms.s.cb_render_state.emit = si_emit_cb_render_state;
4679         sctx->atoms.s.blend_color.emit = si_emit_blend_color;
4680         sctx->atoms.s.clip_regs.emit = si_emit_clip_regs;
4681         sctx->atoms.s.clip_state.emit = si_emit_clip_state;
4682         sctx->atoms.s.stencil_ref.emit = si_emit_stencil_ref;
4683
4684         sctx->b.create_blend_state = si_create_blend_state;
4685         sctx->b.bind_blend_state = si_bind_blend_state;
4686         sctx->b.delete_blend_state = si_delete_blend_state;
4687         sctx->b.set_blend_color = si_set_blend_color;
4688
4689         sctx->b.create_rasterizer_state = si_create_rs_state;
4690         sctx->b.bind_rasterizer_state = si_bind_rs_state;
4691         sctx->b.delete_rasterizer_state = si_delete_rs_state;
4692
4693         sctx->b.create_depth_stencil_alpha_state = si_create_dsa_state;
4694         sctx->b.bind_depth_stencil_alpha_state = si_bind_dsa_state;
4695         sctx->b.delete_depth_stencil_alpha_state = si_delete_dsa_state;
4696
4697         sctx->custom_dsa_flush = si_create_db_flush_dsa(sctx);
4698         sctx->custom_blend_resolve = si_create_blend_custom(sctx, V_028808_CB_RESOLVE);
4699         sctx->custom_blend_fmask_decompress = si_create_blend_custom(sctx, V_028808_CB_FMASK_DECOMPRESS);
4700         sctx->custom_blend_eliminate_fastclear = si_create_blend_custom(sctx, V_028808_CB_ELIMINATE_FAST_CLEAR);
4701         sctx->custom_blend_dcc_decompress = si_create_blend_custom(sctx, V_028808_CB_DCC_DECOMPRESS);
4702
4703         sctx->b.set_clip_state = si_set_clip_state;
4704         sctx->b.set_stencil_ref = si_set_stencil_ref;
4705
4706         sctx->b.set_framebuffer_state = si_set_framebuffer_state;
4707
4708         sctx->b.create_sampler_state = si_create_sampler_state;
4709         sctx->b.delete_sampler_state = si_delete_sampler_state;
4710
4711         sctx->b.create_sampler_view = si_create_sampler_view;
4712         sctx->b.sampler_view_destroy = si_sampler_view_destroy;
4713
4714         sctx->b.set_sample_mask = si_set_sample_mask;
4715
4716         sctx->b.create_vertex_elements_state = si_create_vertex_elements;
4717         sctx->b.bind_vertex_elements_state = si_bind_vertex_elements;
4718         sctx->b.delete_vertex_elements_state = si_delete_vertex_element;
4719         sctx->b.set_vertex_buffers = si_set_vertex_buffers;
4720
4721         sctx->b.texture_barrier = si_texture_barrier;
4722         sctx->b.memory_barrier = si_memory_barrier;
4723         sctx->b.set_min_samples = si_set_min_samples;
4724         sctx->b.set_tess_state = si_set_tess_state;
4725
4726         sctx->b.set_active_query_state = si_set_active_query_state;
4727
4728         sctx->b.draw_vbo = si_draw_vbo;
4729
4730         si_init_config(sctx);
4731 }
4732
4733 void si_init_screen_state_functions(struct si_screen *sscreen)
4734 {
4735         sscreen->b.is_format_supported = si_is_format_supported;
4736 }
4737
4738 static void si_set_grbm_gfx_index(struct si_context *sctx,
4739                                   struct si_pm4_state *pm4,  unsigned value)
4740 {
4741         unsigned reg = sctx->chip_class >= CIK ? R_030800_GRBM_GFX_INDEX :
4742                                                    R_00802C_GRBM_GFX_INDEX;
4743         si_pm4_set_reg(pm4, reg, value);
4744 }
4745
4746 static void si_set_grbm_gfx_index_se(struct si_context *sctx,
4747                                      struct si_pm4_state *pm4, unsigned se)
4748 {
4749         assert(se == ~0 || se < sctx->screen->info.max_se);
4750         si_set_grbm_gfx_index(sctx, pm4,
4751                               (se == ~0 ? S_030800_SE_BROADCAST_WRITES(1) :
4752                                           S_030800_SE_INDEX(se)) |
4753                               S_030800_SH_BROADCAST_WRITES(1) |
4754                               S_030800_INSTANCE_BROADCAST_WRITES(1));
4755 }
4756
4757 static void
4758 si_write_harvested_raster_configs(struct si_context *sctx,
4759                                   struct si_pm4_state *pm4,
4760                                   unsigned raster_config,
4761                                   unsigned raster_config_1)
4762 {
4763         unsigned num_se = MAX2(sctx->screen->info.max_se, 1);
4764         unsigned raster_config_se[4];
4765         unsigned se;
4766
4767         ac_get_harvested_configs(&sctx->screen->info,
4768                                  raster_config,
4769                                  &raster_config_1,
4770                                  raster_config_se);
4771
4772         for (se = 0; se < num_se; se++) {
4773                 si_set_grbm_gfx_index_se(sctx, pm4, se);
4774                 si_pm4_set_reg(pm4, R_028350_PA_SC_RASTER_CONFIG, raster_config_se[se]);
4775         }
4776         si_set_grbm_gfx_index(sctx, pm4, ~0);
4777
4778         if (sctx->chip_class >= CIK) {
4779                 si_pm4_set_reg(pm4, R_028354_PA_SC_RASTER_CONFIG_1, raster_config_1);
4780         }
4781 }
4782
4783 static void si_set_raster_config(struct si_context *sctx, struct si_pm4_state *pm4)
4784 {
4785         unsigned num_rb = MIN2(sctx->screen->info.num_render_backends, 16);
4786         unsigned rb_mask = sctx->screen->info.enabled_rb_mask;
4787         unsigned raster_config, raster_config_1;
4788
4789         ac_get_raster_config(&sctx->screen->info,
4790                              &raster_config,
4791                              &raster_config_1);
4792
4793         if (!rb_mask || util_bitcount(rb_mask) >= num_rb) {
4794                 /* Always use the default config when all backends are enabled
4795                  * (or when we failed to determine the enabled backends).
4796                  */
4797                 si_pm4_set_reg(pm4, R_028350_PA_SC_RASTER_CONFIG,
4798                                raster_config);
4799                 if (sctx->chip_class >= CIK)
4800                         si_pm4_set_reg(pm4, R_028354_PA_SC_RASTER_CONFIG_1,
4801                                        raster_config_1);
4802         } else {
4803                 si_write_harvested_raster_configs(sctx, pm4, raster_config, raster_config_1);
4804         }
4805 }
4806
4807 static void si_init_config(struct si_context *sctx)
4808 {
4809         struct si_screen *sscreen = sctx->screen;
4810         uint64_t border_color_va = sctx->border_color_buffer->gpu_address;
4811         bool has_clear_state = sscreen->has_clear_state;
4812         struct si_pm4_state *pm4 = CALLOC_STRUCT(si_pm4_state);
4813
4814         /* Only SI can disable CLEAR_STATE for now. */
4815         assert(has_clear_state || sscreen->info.chip_class == SI);
4816
4817         if (!pm4)
4818                 return;
4819
4820         si_pm4_cmd_begin(pm4, PKT3_CONTEXT_CONTROL);
4821         si_pm4_cmd_add(pm4, CONTEXT_CONTROL_LOAD_ENABLE(1));
4822         si_pm4_cmd_add(pm4, CONTEXT_CONTROL_SHADOW_ENABLE(1));
4823         si_pm4_cmd_end(pm4, false);
4824
4825         if (has_clear_state) {
4826                 si_pm4_cmd_begin(pm4, PKT3_CLEAR_STATE);
4827                 si_pm4_cmd_add(pm4, 0);
4828                 si_pm4_cmd_end(pm4, false);
4829         }
4830
4831         if (sctx->chip_class <= VI)
4832                 si_set_raster_config(sctx, pm4);
4833
4834         si_pm4_set_reg(pm4, R_028A18_VGT_HOS_MAX_TESS_LEVEL, fui(64));
4835         if (!has_clear_state)
4836                 si_pm4_set_reg(pm4, R_028A1C_VGT_HOS_MIN_TESS_LEVEL, fui(0));
4837
4838         /* FIXME calculate these values somehow ??? */
4839         if (sctx->chip_class <= VI) {
4840                 si_pm4_set_reg(pm4, R_028A54_VGT_GS_PER_ES, SI_GS_PER_ES);
4841                 si_pm4_set_reg(pm4, R_028A58_VGT_ES_PER_GS, 0x40);
4842         }
4843
4844         if (!has_clear_state) {
4845                 si_pm4_set_reg(pm4, R_028A5C_VGT_GS_PER_VS, 0x2);
4846                 si_pm4_set_reg(pm4, R_028A8C_VGT_PRIMITIVEID_RESET, 0x0);
4847                 si_pm4_set_reg(pm4, R_028B98_VGT_STRMOUT_BUFFER_CONFIG, 0x0);
4848         }
4849
4850         si_pm4_set_reg(pm4, R_028AA0_VGT_INSTANCE_STEP_RATE_0, 1);
4851         if (!has_clear_state)
4852                 si_pm4_set_reg(pm4, R_028AB8_VGT_VTX_CNT_EN, 0x0);
4853         if (sctx->chip_class < CIK)
4854                 si_pm4_set_reg(pm4, R_008A14_PA_CL_ENHANCE, S_008A14_NUM_CLIP_SEQ(3) |
4855                                S_008A14_CLIP_VTX_REORDER_ENA(1));
4856
4857         if (!has_clear_state)
4858                 si_pm4_set_reg(pm4, R_02882C_PA_SU_PRIM_FILTER_CNTL, 0);
4859
4860         /* CLEAR_STATE doesn't clear these correctly on certain generations.
4861          * I don't know why. Deduced by trial and error.
4862          */
4863         if (sctx->chip_class <= CIK) {
4864                 si_pm4_set_reg(pm4, R_028B28_VGT_STRMOUT_DRAW_OPAQUE_OFFSET, 0);
4865                 si_pm4_set_reg(pm4, R_028204_PA_SC_WINDOW_SCISSOR_TL, S_028204_WINDOW_OFFSET_DISABLE(1));
4866                 si_pm4_set_reg(pm4, R_028240_PA_SC_GENERIC_SCISSOR_TL, S_028240_WINDOW_OFFSET_DISABLE(1));
4867                 si_pm4_set_reg(pm4, R_028244_PA_SC_GENERIC_SCISSOR_BR,
4868                                S_028244_BR_X(16384) | S_028244_BR_Y(16384));
4869                 si_pm4_set_reg(pm4, R_028030_PA_SC_SCREEN_SCISSOR_TL, 0);
4870                 si_pm4_set_reg(pm4, R_028034_PA_SC_SCREEN_SCISSOR_BR,
4871                                S_028034_BR_X(16384) | S_028034_BR_Y(16384));
4872         }
4873
4874         if (!has_clear_state) {
4875                 si_pm4_set_reg(pm4, R_028230_PA_SC_EDGERULE,
4876                                S_028230_ER_TRI(0xA) |
4877                                S_028230_ER_POINT(0xA) |
4878                                S_028230_ER_RECT(0xA) |
4879                                /* Required by DX10_DIAMOND_TEST_ENA: */
4880                                S_028230_ER_LINE_LR(0x1A) |
4881                                S_028230_ER_LINE_RL(0x26) |
4882                                S_028230_ER_LINE_TB(0xA) |
4883                                S_028230_ER_LINE_BT(0xA));
4884                 /* PA_SU_HARDWARE_SCREEN_OFFSET must be 0 due to hw bug on SI */
4885                 si_pm4_set_reg(pm4, R_028234_PA_SU_HARDWARE_SCREEN_OFFSET, 0);
4886                 si_pm4_set_reg(pm4, R_028820_PA_CL_NANINF_CNTL, 0);
4887                 si_pm4_set_reg(pm4, R_028AC0_DB_SRESULTS_COMPARE_STATE0, 0x0);
4888                 si_pm4_set_reg(pm4, R_028AC4_DB_SRESULTS_COMPARE_STATE1, 0x0);
4889                 si_pm4_set_reg(pm4, R_028AC8_DB_PRELOAD_CONTROL, 0x0);
4890                 si_pm4_set_reg(pm4, R_02800C_DB_RENDER_OVERRIDE, 0);
4891         }
4892
4893         if (sctx->chip_class >= GFX9) {
4894                 si_pm4_set_reg(pm4, R_030920_VGT_MAX_VTX_INDX, ~0);
4895                 si_pm4_set_reg(pm4, R_030924_VGT_MIN_VTX_INDX, 0);
4896                 si_pm4_set_reg(pm4, R_030928_VGT_INDX_OFFSET, 0);
4897         } else {
4898                 /* These registers, when written, also overwrite the CLEAR_STATE
4899                  * context, so we can't rely on CLEAR_STATE setting them.
4900                  * It would be an issue if there was another UMD changing them.
4901                  */
4902                 si_pm4_set_reg(pm4, R_028400_VGT_MAX_VTX_INDX, ~0);
4903                 si_pm4_set_reg(pm4, R_028404_VGT_MIN_VTX_INDX, 0);
4904                 si_pm4_set_reg(pm4, R_028408_VGT_INDX_OFFSET, 0);
4905         }
4906
4907         if (sctx->chip_class >= CIK) {
4908                 if (sctx->chip_class >= GFX9) {
4909                         si_pm4_set_reg(pm4, R_00B41C_SPI_SHADER_PGM_RSRC3_HS,
4910                                        S_00B41C_CU_EN(0xffff) | S_00B41C_WAVE_LIMIT(0x3F));
4911                 } else {
4912                         si_pm4_set_reg(pm4, R_00B51C_SPI_SHADER_PGM_RSRC3_LS,
4913                                        S_00B51C_CU_EN(0xffff) | S_00B51C_WAVE_LIMIT(0x3F));
4914                         si_pm4_set_reg(pm4, R_00B41C_SPI_SHADER_PGM_RSRC3_HS,
4915                                        S_00B41C_WAVE_LIMIT(0x3F));
4916                         si_pm4_set_reg(pm4, R_00B31C_SPI_SHADER_PGM_RSRC3_ES,
4917                                        S_00B31C_CU_EN(0xffff) | S_00B31C_WAVE_LIMIT(0x3F));
4918
4919                         /* If this is 0, Bonaire can hang even if GS isn't being used.
4920                          * Other chips are unaffected. These are suboptimal values,
4921                          * but we don't use on-chip GS.
4922                          */
4923                         si_pm4_set_reg(pm4, R_028A44_VGT_GS_ONCHIP_CNTL,
4924                                        S_028A44_ES_VERTS_PER_SUBGRP(64) |
4925                                        S_028A44_GS_PRIMS_PER_SUBGRP(4));
4926                 }
4927                 si_pm4_set_reg(pm4, R_00B21C_SPI_SHADER_PGM_RSRC3_GS,
4928                                S_00B21C_CU_EN(0xffff) | S_00B21C_WAVE_LIMIT(0x3F));
4929
4930                 /* Compute LATE_ALLOC_VS.LIMIT. */
4931                 unsigned num_cu_per_sh = sscreen->info.num_good_compute_units /
4932                                          (sscreen->info.max_se *
4933                                           sscreen->info.max_sh_per_se);
4934                 unsigned late_alloc_limit; /* The limit is per SH. */
4935
4936                 if (sctx->family == CHIP_KABINI) {
4937                         late_alloc_limit = 0; /* Potential hang on Kabini. */
4938                 } else if (num_cu_per_sh <= 4) {
4939                         /* Too few available compute units per SH. Disallowing
4940                          * VS to run on one CU could hurt us more than late VS
4941                          * allocation would help.
4942                          *
4943                          * 2 is the highest safe number that allows us to keep
4944                          * all CUs enabled.
4945                          */
4946                         late_alloc_limit = 2;
4947                 } else {
4948                         /* This is a good initial value, allowing 1 late_alloc
4949                          * wave per SIMD on num_cu - 2.
4950                          */
4951                         late_alloc_limit = (num_cu_per_sh - 2) * 4;
4952
4953                         /* The limit is 0-based, so 0 means 1. */
4954                         assert(late_alloc_limit > 0 && late_alloc_limit <= 64);
4955                         late_alloc_limit -= 1;
4956                 }
4957
4958                 /* VS can't execute on one CU if the limit is > 2. */
4959                 si_pm4_set_reg(pm4, R_00B118_SPI_SHADER_PGM_RSRC3_VS,
4960                                S_00B118_CU_EN(late_alloc_limit > 2 ? 0xfffe : 0xffff) |
4961                                S_00B118_WAVE_LIMIT(0x3F));
4962                 si_pm4_set_reg(pm4, R_00B11C_SPI_SHADER_LATE_ALLOC_VS,
4963                                S_00B11C_LIMIT(late_alloc_limit));
4964                 si_pm4_set_reg(pm4, R_00B01C_SPI_SHADER_PGM_RSRC3_PS,
4965                                S_00B01C_CU_EN(0xffff) | S_00B01C_WAVE_LIMIT(0x3F));
4966         }
4967
4968         if (sctx->chip_class >= VI) {
4969                 unsigned vgt_tess_distribution;
4970
4971                 vgt_tess_distribution =
4972                         S_028B50_ACCUM_ISOLINE(32) |
4973                         S_028B50_ACCUM_TRI(11) |
4974                         S_028B50_ACCUM_QUAD(11) |
4975                         S_028B50_DONUT_SPLIT(16);
4976
4977                 /* Testing with Unigine Heaven extreme tesselation yielded best results
4978                  * with TRAP_SPLIT = 3.
4979                  */
4980                 if (sctx->family == CHIP_FIJI ||
4981                     sctx->family >= CHIP_POLARIS10)
4982                         vgt_tess_distribution |= S_028B50_TRAP_SPLIT(3);
4983
4984                 si_pm4_set_reg(pm4, R_028B50_VGT_TESS_DISTRIBUTION, vgt_tess_distribution);
4985         } else if (!has_clear_state) {
4986                 si_pm4_set_reg(pm4, R_028C58_VGT_VERTEX_REUSE_BLOCK_CNTL, 14);
4987                 si_pm4_set_reg(pm4, R_028C5C_VGT_OUT_DEALLOC_CNTL, 16);
4988         }
4989
4990         si_pm4_set_reg(pm4, R_028080_TA_BC_BASE_ADDR, border_color_va >> 8);
4991         if (sctx->chip_class >= CIK) {
4992                 si_pm4_set_reg(pm4, R_028084_TA_BC_BASE_ADDR_HI,
4993                                S_028084_ADDRESS(border_color_va >> 40));
4994         }
4995         si_pm4_add_bo(pm4, sctx->border_color_buffer, RADEON_USAGE_READ,
4996                       RADEON_PRIO_BORDER_COLORS);
4997
4998         if (sctx->chip_class >= GFX9) {
4999                 unsigned num_se = sscreen->info.max_se;
5000                 unsigned pc_lines = 0;
5001
5002                 switch (sctx->family) {
5003                 case CHIP_VEGA10:
5004                 case CHIP_VEGA12:
5005                 case CHIP_VEGA20:
5006                         pc_lines = 4096;
5007                         break;
5008                 case CHIP_RAVEN:
5009                         pc_lines = 1024;
5010                         break;
5011                 default:
5012                         assert(0);
5013                 }
5014
5015                 si_pm4_set_reg(pm4, R_028C48_PA_SC_BINNER_CNTL_1,
5016                                S_028C48_MAX_ALLOC_COUNT(MIN2(128, pc_lines / (4 * num_se))) |
5017                                S_028C48_MAX_PRIM_PER_BATCH(1023));
5018                 si_pm4_set_reg(pm4, R_028C4C_PA_SC_CONSERVATIVE_RASTERIZATION_CNTL,
5019                                S_028C4C_NULL_SQUAD_AA_MASK_ENABLE(1));
5020                 si_pm4_set_reg(pm4, R_030968_VGT_INSTANCE_BASE_ID, 0);
5021         }
5022
5023         si_pm4_upload_indirect_buffer(sctx, pm4);
5024         sctx->init_config = pm4;
5025 }