6335b181be4bfd81233daaf85764c10ff7135236
[linux-2.6-microblaze.git] / drivers / gpu / drm / i915 / display / intel_dp.c
1 /*
2  * Copyright © 2008 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *    Keith Packard <keithp@keithp.com>
25  *
26  */
27
28 #include <linux/export.h>
29 #include <linux/i2c.h>
30 #include <linux/notifier.h>
31 #include <linux/reboot.h>
32 #include <linux/slab.h>
33 #include <linux/types.h>
34
35 #include <asm/byteorder.h>
36
37 #include <drm/drm_atomic_helper.h>
38 #include <drm/drm_crtc.h>
39 #include <drm/drm_dp_helper.h>
40 #include <drm/drm_edid.h>
41 #include <drm/drm_hdcp.h>
42 #include <drm/drm_probe_helper.h>
43
44 #include "i915_debugfs.h"
45 #include "i915_drv.h"
46 #include "i915_trace.h"
47 #include "intel_atomic.h"
48 #include "intel_audio.h"
49 #include "intel_connector.h"
50 #include "intel_ddi.h"
51 #include "intel_display_types.h"
52 #include "intel_dp.h"
53 #include "intel_dp_link_training.h"
54 #include "intel_dp_mst.h"
55 #include "intel_dpio_phy.h"
56 #include "intel_fifo_underrun.h"
57 #include "intel_hdcp.h"
58 #include "intel_hdmi.h"
59 #include "intel_hotplug.h"
60 #include "intel_lspcon.h"
61 #include "intel_lvds.h"
62 #include "intel_panel.h"
63 #include "intel_psr.h"
64 #include "intel_sideband.h"
65 #include "intel_tc.h"
66 #include "intel_vdsc.h"
67
68 #define DP_DPRX_ESI_LEN 14
69
70 /* DP DSC throughput values used for slice count calculations KPixels/s */
71 #define DP_DSC_PEAK_PIXEL_RATE                  2720000
72 #define DP_DSC_MAX_ENC_THROUGHPUT_0             340000
73 #define DP_DSC_MAX_ENC_THROUGHPUT_1             400000
74
75 /* DP DSC FEC Overhead factor = 1/(0.972261) */
76 #define DP_DSC_FEC_OVERHEAD_FACTOR              972261
77
78 /* Compliance test status bits  */
79 #define INTEL_DP_RESOLUTION_SHIFT_MASK  0
80 #define INTEL_DP_RESOLUTION_PREFERRED   (1 << INTEL_DP_RESOLUTION_SHIFT_MASK)
81 #define INTEL_DP_RESOLUTION_STANDARD    (2 << INTEL_DP_RESOLUTION_SHIFT_MASK)
82 #define INTEL_DP_RESOLUTION_FAILSAFE    (3 << INTEL_DP_RESOLUTION_SHIFT_MASK)
83
84 struct dp_link_dpll {
85         int clock;
86         struct dpll dpll;
87 };
88
89 static const struct dp_link_dpll g4x_dpll[] = {
90         { 162000,
91                 { .p1 = 2, .p2 = 10, .n = 2, .m1 = 23, .m2 = 8 } },
92         { 270000,
93                 { .p1 = 1, .p2 = 10, .n = 1, .m1 = 14, .m2 = 2 } }
94 };
95
96 static const struct dp_link_dpll pch_dpll[] = {
97         { 162000,
98                 { .p1 = 2, .p2 = 10, .n = 1, .m1 = 12, .m2 = 9 } },
99         { 270000,
100                 { .p1 = 1, .p2 = 10, .n = 2, .m1 = 14, .m2 = 8 } }
101 };
102
103 static const struct dp_link_dpll vlv_dpll[] = {
104         { 162000,
105                 { .p1 = 3, .p2 = 2, .n = 5, .m1 = 3, .m2 = 81 } },
106         { 270000,
107                 { .p1 = 2, .p2 = 2, .n = 1, .m1 = 2, .m2 = 27 } }
108 };
109
110 /*
111  * CHV supports eDP 1.4 that have  more link rates.
112  * Below only provides the fixed rate but exclude variable rate.
113  */
114 static const struct dp_link_dpll chv_dpll[] = {
115         /*
116          * CHV requires to program fractional division for m2.
117          * m2 is stored in fixed point format using formula below
118          * (m2_int << 22) | m2_fraction
119          */
120         { 162000,       /* m2_int = 32, m2_fraction = 1677722 */
121                 { .p1 = 4, .p2 = 2, .n = 1, .m1 = 2, .m2 = 0x819999a } },
122         { 270000,       /* m2_int = 27, m2_fraction = 0 */
123                 { .p1 = 4, .p2 = 1, .n = 1, .m1 = 2, .m2 = 0x6c00000 } },
124 };
125
126 /* Constants for DP DSC configurations */
127 static const u8 valid_dsc_bpp[] = {6, 8, 10, 12, 15};
128
129 /* With Single pipe configuration, HW is capable of supporting maximum
130  * of 4 slices per line.
131  */
132 static const u8 valid_dsc_slicecount[] = {1, 2, 4};
133
134 /**
135  * intel_dp_is_edp - is the given port attached to an eDP panel (either CPU or PCH)
136  * @intel_dp: DP struct
137  *
138  * If a CPU or PCH DP output is attached to an eDP panel, this function
139  * will return true, and false otherwise.
140  */
141 bool intel_dp_is_edp(struct intel_dp *intel_dp)
142 {
143         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
144
145         return intel_dig_port->base.type == INTEL_OUTPUT_EDP;
146 }
147
148 static void intel_dp_link_down(struct intel_encoder *encoder,
149                                const struct intel_crtc_state *old_crtc_state);
150 static bool edp_panel_vdd_on(struct intel_dp *intel_dp);
151 static void edp_panel_vdd_off(struct intel_dp *intel_dp, bool sync);
152 static void vlv_init_panel_power_sequencer(struct intel_encoder *encoder,
153                                            const struct intel_crtc_state *crtc_state);
154 static void vlv_steal_power_sequencer(struct drm_i915_private *dev_priv,
155                                       enum pipe pipe);
156 static void intel_dp_unset_edid(struct intel_dp *intel_dp);
157
158 /* update sink rates from dpcd */
159 static void intel_dp_set_sink_rates(struct intel_dp *intel_dp)
160 {
161         static const int dp_rates[] = {
162                 162000, 270000, 540000, 810000
163         };
164         int i, max_rate;
165
166         if (drm_dp_has_quirk(&intel_dp->desc, 0,
167                              DP_DPCD_QUIRK_CAN_DO_MAX_LINK_RATE_3_24_GBPS)) {
168                 /* Needed, e.g., for Apple MBP 2017, 15 inch eDP Retina panel */
169                 static const int quirk_rates[] = { 162000, 270000, 324000 };
170
171                 memcpy(intel_dp->sink_rates, quirk_rates, sizeof(quirk_rates));
172                 intel_dp->num_sink_rates = ARRAY_SIZE(quirk_rates);
173
174                 return;
175         }
176
177         max_rate = drm_dp_bw_code_to_link_rate(intel_dp->dpcd[DP_MAX_LINK_RATE]);
178
179         for (i = 0; i < ARRAY_SIZE(dp_rates); i++) {
180                 if (dp_rates[i] > max_rate)
181                         break;
182                 intel_dp->sink_rates[i] = dp_rates[i];
183         }
184
185         intel_dp->num_sink_rates = i;
186 }
187
188 /* Get length of rates array potentially limited by max_rate. */
189 static int intel_dp_rate_limit_len(const int *rates, int len, int max_rate)
190 {
191         int i;
192
193         /* Limit results by potentially reduced max rate */
194         for (i = 0; i < len; i++) {
195                 if (rates[len - i - 1] <= max_rate)
196                         return len - i;
197         }
198
199         return 0;
200 }
201
202 /* Get length of common rates array potentially limited by max_rate. */
203 static int intel_dp_common_len_rate_limit(const struct intel_dp *intel_dp,
204                                           int max_rate)
205 {
206         return intel_dp_rate_limit_len(intel_dp->common_rates,
207                                        intel_dp->num_common_rates, max_rate);
208 }
209
210 /* Theoretical max between source and sink */
211 static int intel_dp_max_common_rate(struct intel_dp *intel_dp)
212 {
213         return intel_dp->common_rates[intel_dp->num_common_rates - 1];
214 }
215
216 /* Theoretical max between source and sink */
217 static int intel_dp_max_common_lane_count(struct intel_dp *intel_dp)
218 {
219         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
220         int source_max = intel_dig_port->max_lanes;
221         int sink_max = drm_dp_max_lane_count(intel_dp->dpcd);
222         int fia_max = intel_tc_port_fia_max_lane_count(intel_dig_port);
223
224         return min3(source_max, sink_max, fia_max);
225 }
226
227 int intel_dp_max_lane_count(struct intel_dp *intel_dp)
228 {
229         return intel_dp->max_link_lane_count;
230 }
231
232 int
233 intel_dp_link_required(int pixel_clock, int bpp)
234 {
235         /* pixel_clock is in kHz, divide bpp by 8 for bit to Byte conversion */
236         return DIV_ROUND_UP(pixel_clock * bpp, 8);
237 }
238
239 int
240 intel_dp_max_data_rate(int max_link_clock, int max_lanes)
241 {
242         /* max_link_clock is the link symbol clock (LS_Clk) in kHz and not the
243          * link rate that is generally expressed in Gbps. Since, 8 bits of data
244          * is transmitted every LS_Clk per lane, there is no need to account for
245          * the channel encoding that is done in the PHY layer here.
246          */
247
248         return max_link_clock * max_lanes;
249 }
250
251 static int
252 intel_dp_downstream_max_dotclock(struct intel_dp *intel_dp)
253 {
254         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
255         struct intel_encoder *encoder = &intel_dig_port->base;
256         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
257         int max_dotclk = dev_priv->max_dotclk_freq;
258         int ds_max_dotclk;
259
260         int type = intel_dp->downstream_ports[0] & DP_DS_PORT_TYPE_MASK;
261
262         if (type != DP_DS_PORT_TYPE_VGA)
263                 return max_dotclk;
264
265         ds_max_dotclk = drm_dp_downstream_max_clock(intel_dp->dpcd,
266                                                     intel_dp->downstream_ports);
267
268         if (ds_max_dotclk != 0)
269                 max_dotclk = min(max_dotclk, ds_max_dotclk);
270
271         return max_dotclk;
272 }
273
274 static int cnl_max_source_rate(struct intel_dp *intel_dp)
275 {
276         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
277         struct drm_i915_private *dev_priv = to_i915(dig_port->base.base.dev);
278         enum port port = dig_port->base.port;
279
280         u32 voltage = intel_de_read(dev_priv, CNL_PORT_COMP_DW3) & VOLTAGE_INFO_MASK;
281
282         /* Low voltage SKUs are limited to max of 5.4G */
283         if (voltage == VOLTAGE_INFO_0_85V)
284                 return 540000;
285
286         /* For this SKU 8.1G is supported in all ports */
287         if (IS_CNL_WITH_PORT_F(dev_priv))
288                 return 810000;
289
290         /* For other SKUs, max rate on ports A and D is 5.4G */
291         if (port == PORT_A || port == PORT_D)
292                 return 540000;
293
294         return 810000;
295 }
296
297 static int icl_max_source_rate(struct intel_dp *intel_dp)
298 {
299         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
300         struct drm_i915_private *dev_priv = to_i915(dig_port->base.base.dev);
301         enum phy phy = intel_port_to_phy(dev_priv, dig_port->base.port);
302
303         if (intel_phy_is_combo(dev_priv, phy) &&
304             !IS_ELKHARTLAKE(dev_priv) &&
305             !intel_dp_is_edp(intel_dp))
306                 return 540000;
307
308         return 810000;
309 }
310
311 static void
312 intel_dp_set_source_rates(struct intel_dp *intel_dp)
313 {
314         /* The values must be in increasing order */
315         static const int cnl_rates[] = {
316                 162000, 216000, 270000, 324000, 432000, 540000, 648000, 810000
317         };
318         static const int bxt_rates[] = {
319                 162000, 216000, 243000, 270000, 324000, 432000, 540000
320         };
321         static const int skl_rates[] = {
322                 162000, 216000, 270000, 324000, 432000, 540000
323         };
324         static const int hsw_rates[] = {
325                 162000, 270000, 540000
326         };
327         static const int g4x_rates[] = {
328                 162000, 270000
329         };
330         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
331         struct intel_encoder *encoder = &dig_port->base;
332         struct drm_i915_private *dev_priv = to_i915(dig_port->base.base.dev);
333         const int *source_rates;
334         int size, max_rate = 0, vbt_max_rate;
335
336         /* This should only be done once */
337         drm_WARN_ON(&dev_priv->drm,
338                     intel_dp->source_rates || intel_dp->num_source_rates);
339
340         if (INTEL_GEN(dev_priv) >= 10) {
341                 source_rates = cnl_rates;
342                 size = ARRAY_SIZE(cnl_rates);
343                 if (IS_GEN(dev_priv, 10))
344                         max_rate = cnl_max_source_rate(intel_dp);
345                 else
346                         max_rate = icl_max_source_rate(intel_dp);
347         } else if (IS_GEN9_LP(dev_priv)) {
348                 source_rates = bxt_rates;
349                 size = ARRAY_SIZE(bxt_rates);
350         } else if (IS_GEN9_BC(dev_priv)) {
351                 source_rates = skl_rates;
352                 size = ARRAY_SIZE(skl_rates);
353         } else if ((IS_HASWELL(dev_priv) && !IS_HSW_ULX(dev_priv)) ||
354                    IS_BROADWELL(dev_priv)) {
355                 source_rates = hsw_rates;
356                 size = ARRAY_SIZE(hsw_rates);
357         } else {
358                 source_rates = g4x_rates;
359                 size = ARRAY_SIZE(g4x_rates);
360         }
361
362         vbt_max_rate = intel_bios_dp_max_link_rate(encoder);
363         if (max_rate && vbt_max_rate)
364                 max_rate = min(max_rate, vbt_max_rate);
365         else if (vbt_max_rate)
366                 max_rate = vbt_max_rate;
367
368         if (max_rate)
369                 size = intel_dp_rate_limit_len(source_rates, size, max_rate);
370
371         intel_dp->source_rates = source_rates;
372         intel_dp->num_source_rates = size;
373 }
374
375 static int intersect_rates(const int *source_rates, int source_len,
376                            const int *sink_rates, int sink_len,
377                            int *common_rates)
378 {
379         int i = 0, j = 0, k = 0;
380
381         while (i < source_len && j < sink_len) {
382                 if (source_rates[i] == sink_rates[j]) {
383                         if (WARN_ON(k >= DP_MAX_SUPPORTED_RATES))
384                                 return k;
385                         common_rates[k] = source_rates[i];
386                         ++k;
387                         ++i;
388                         ++j;
389                 } else if (source_rates[i] < sink_rates[j]) {
390                         ++i;
391                 } else {
392                         ++j;
393                 }
394         }
395         return k;
396 }
397
398 /* return index of rate in rates array, or -1 if not found */
399 static int intel_dp_rate_index(const int *rates, int len, int rate)
400 {
401         int i;
402
403         for (i = 0; i < len; i++)
404                 if (rate == rates[i])
405                         return i;
406
407         return -1;
408 }
409
410 static void intel_dp_set_common_rates(struct intel_dp *intel_dp)
411 {
412         WARN_ON(!intel_dp->num_source_rates || !intel_dp->num_sink_rates);
413
414         intel_dp->num_common_rates = intersect_rates(intel_dp->source_rates,
415                                                      intel_dp->num_source_rates,
416                                                      intel_dp->sink_rates,
417                                                      intel_dp->num_sink_rates,
418                                                      intel_dp->common_rates);
419
420         /* Paranoia, there should always be something in common. */
421         if (WARN_ON(intel_dp->num_common_rates == 0)) {
422                 intel_dp->common_rates[0] = 162000;
423                 intel_dp->num_common_rates = 1;
424         }
425 }
426
427 static bool intel_dp_link_params_valid(struct intel_dp *intel_dp, int link_rate,
428                                        u8 lane_count)
429 {
430         /*
431          * FIXME: we need to synchronize the current link parameters with
432          * hardware readout. Currently fast link training doesn't work on
433          * boot-up.
434          */
435         if (link_rate == 0 ||
436             link_rate > intel_dp->max_link_rate)
437                 return false;
438
439         if (lane_count == 0 ||
440             lane_count > intel_dp_max_lane_count(intel_dp))
441                 return false;
442
443         return true;
444 }
445
446 static bool intel_dp_can_link_train_fallback_for_edp(struct intel_dp *intel_dp,
447                                                      int link_rate,
448                                                      u8 lane_count)
449 {
450         const struct drm_display_mode *fixed_mode =
451                 intel_dp->attached_connector->panel.fixed_mode;
452         int mode_rate, max_rate;
453
454         mode_rate = intel_dp_link_required(fixed_mode->clock, 18);
455         max_rate = intel_dp_max_data_rate(link_rate, lane_count);
456         if (mode_rate > max_rate)
457                 return false;
458
459         return true;
460 }
461
462 int intel_dp_get_link_train_fallback_values(struct intel_dp *intel_dp,
463                                             int link_rate, u8 lane_count)
464 {
465         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
466         int index;
467
468         index = intel_dp_rate_index(intel_dp->common_rates,
469                                     intel_dp->num_common_rates,
470                                     link_rate);
471         if (index > 0) {
472                 if (intel_dp_is_edp(intel_dp) &&
473                     !intel_dp_can_link_train_fallback_for_edp(intel_dp,
474                                                               intel_dp->common_rates[index - 1],
475                                                               lane_count)) {
476                         drm_dbg_kms(&i915->drm,
477                                     "Retrying Link training for eDP with same parameters\n");
478                         return 0;
479                 }
480                 intel_dp->max_link_rate = intel_dp->common_rates[index - 1];
481                 intel_dp->max_link_lane_count = lane_count;
482         } else if (lane_count > 1) {
483                 if (intel_dp_is_edp(intel_dp) &&
484                     !intel_dp_can_link_train_fallback_for_edp(intel_dp,
485                                                               intel_dp_max_common_rate(intel_dp),
486                                                               lane_count >> 1)) {
487                         drm_dbg_kms(&i915->drm,
488                                     "Retrying Link training for eDP with same parameters\n");
489                         return 0;
490                 }
491                 intel_dp->max_link_rate = intel_dp_max_common_rate(intel_dp);
492                 intel_dp->max_link_lane_count = lane_count >> 1;
493         } else {
494                 drm_err(&i915->drm, "Link Training Unsuccessful\n");
495                 return -1;
496         }
497
498         return 0;
499 }
500
501 u32 intel_dp_mode_to_fec_clock(u32 mode_clock)
502 {
503         return div_u64(mul_u32_u32(mode_clock, 1000000U),
504                        DP_DSC_FEC_OVERHEAD_FACTOR);
505 }
506
507 static int
508 small_joiner_ram_size_bits(struct drm_i915_private *i915)
509 {
510         if (INTEL_GEN(i915) >= 11)
511                 return 7680 * 8;
512         else
513                 return 6144 * 8;
514 }
515
516 static u16 intel_dp_dsc_get_output_bpp(struct drm_i915_private *i915,
517                                        u32 link_clock, u32 lane_count,
518                                        u32 mode_clock, u32 mode_hdisplay)
519 {
520         u32 bits_per_pixel, max_bpp_small_joiner_ram;
521         int i;
522
523         /*
524          * Available Link Bandwidth(Kbits/sec) = (NumberOfLanes)*
525          * (LinkSymbolClock)* 8 * (TimeSlotsPerMTP)
526          * for SST -> TimeSlotsPerMTP is 1,
527          * for MST -> TimeSlotsPerMTP has to be calculated
528          */
529         bits_per_pixel = (link_clock * lane_count * 8) /
530                          intel_dp_mode_to_fec_clock(mode_clock);
531         drm_dbg_kms(&i915->drm, "Max link bpp: %u\n", bits_per_pixel);
532
533         /* Small Joiner Check: output bpp <= joiner RAM (bits) / Horiz. width */
534         max_bpp_small_joiner_ram = small_joiner_ram_size_bits(i915) /
535                 mode_hdisplay;
536         drm_dbg_kms(&i915->drm, "Max small joiner bpp: %u\n",
537                     max_bpp_small_joiner_ram);
538
539         /*
540          * Greatest allowed DSC BPP = MIN (output BPP from available Link BW
541          * check, output bpp from small joiner RAM check)
542          */
543         bits_per_pixel = min(bits_per_pixel, max_bpp_small_joiner_ram);
544
545         /* Error out if the max bpp is less than smallest allowed valid bpp */
546         if (bits_per_pixel < valid_dsc_bpp[0]) {
547                 drm_dbg_kms(&i915->drm, "Unsupported BPP %u, min %u\n",
548                             bits_per_pixel, valid_dsc_bpp[0]);
549                 return 0;
550         }
551
552         /* Find the nearest match in the array of known BPPs from VESA */
553         for (i = 0; i < ARRAY_SIZE(valid_dsc_bpp) - 1; i++) {
554                 if (bits_per_pixel < valid_dsc_bpp[i + 1])
555                         break;
556         }
557         bits_per_pixel = valid_dsc_bpp[i];
558
559         /*
560          * Compressed BPP in U6.4 format so multiply by 16, for Gen 11,
561          * fractional part is 0
562          */
563         return bits_per_pixel << 4;
564 }
565
566 static u8 intel_dp_dsc_get_slice_count(struct intel_dp *intel_dp,
567                                        int mode_clock, int mode_hdisplay)
568 {
569         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
570         u8 min_slice_count, i;
571         int max_slice_width;
572
573         if (mode_clock <= DP_DSC_PEAK_PIXEL_RATE)
574                 min_slice_count = DIV_ROUND_UP(mode_clock,
575                                                DP_DSC_MAX_ENC_THROUGHPUT_0);
576         else
577                 min_slice_count = DIV_ROUND_UP(mode_clock,
578                                                DP_DSC_MAX_ENC_THROUGHPUT_1);
579
580         max_slice_width = drm_dp_dsc_sink_max_slice_width(intel_dp->dsc_dpcd);
581         if (max_slice_width < DP_DSC_MIN_SLICE_WIDTH_VALUE) {
582                 drm_dbg_kms(&i915->drm,
583                             "Unsupported slice width %d by DP DSC Sink device\n",
584                             max_slice_width);
585                 return 0;
586         }
587         /* Also take into account max slice width */
588         min_slice_count = min_t(u8, min_slice_count,
589                                 DIV_ROUND_UP(mode_hdisplay,
590                                              max_slice_width));
591
592         /* Find the closest match to the valid slice count values */
593         for (i = 0; i < ARRAY_SIZE(valid_dsc_slicecount); i++) {
594                 if (valid_dsc_slicecount[i] >
595                     drm_dp_dsc_sink_max_slice_count(intel_dp->dsc_dpcd,
596                                                     false))
597                         break;
598                 if (min_slice_count  <= valid_dsc_slicecount[i])
599                         return valid_dsc_slicecount[i];
600         }
601
602         drm_dbg_kms(&i915->drm, "Unsupported Slice Count %d\n",
603                     min_slice_count);
604         return 0;
605 }
606
607 static bool intel_dp_hdisplay_bad(struct drm_i915_private *dev_priv,
608                                   int hdisplay)
609 {
610         /*
611          * Older platforms don't like hdisplay==4096 with DP.
612          *
613          * On ILK/SNB/IVB the pipe seems to be somewhat running (scanline
614          * and frame counter increment), but we don't get vblank interrupts,
615          * and the pipe underruns immediately. The link also doesn't seem
616          * to get trained properly.
617          *
618          * On CHV the vblank interrupts don't seem to disappear but
619          * otherwise the symptoms are similar.
620          *
621          * TODO: confirm the behaviour on HSW+
622          */
623         return hdisplay == 4096 && !HAS_DDI(dev_priv);
624 }
625
626 static enum drm_mode_status
627 intel_dp_mode_valid(struct drm_connector *connector,
628                     struct drm_display_mode *mode)
629 {
630         struct intel_dp *intel_dp = intel_attached_dp(to_intel_connector(connector));
631         struct intel_connector *intel_connector = to_intel_connector(connector);
632         struct drm_display_mode *fixed_mode = intel_connector->panel.fixed_mode;
633         struct drm_i915_private *dev_priv = to_i915(connector->dev);
634         int target_clock = mode->clock;
635         int max_rate, mode_rate, max_lanes, max_link_clock;
636         int max_dotclk;
637         u16 dsc_max_output_bpp = 0;
638         u8 dsc_slice_count = 0;
639
640         if (mode->flags & DRM_MODE_FLAG_DBLSCAN)
641                 return MODE_NO_DBLESCAN;
642
643         max_dotclk = intel_dp_downstream_max_dotclock(intel_dp);
644
645         if (intel_dp_is_edp(intel_dp) && fixed_mode) {
646                 if (mode->hdisplay > fixed_mode->hdisplay)
647                         return MODE_PANEL;
648
649                 if (mode->vdisplay > fixed_mode->vdisplay)
650                         return MODE_PANEL;
651
652                 target_clock = fixed_mode->clock;
653         }
654
655         max_link_clock = intel_dp_max_link_rate(intel_dp);
656         max_lanes = intel_dp_max_lane_count(intel_dp);
657
658         max_rate = intel_dp_max_data_rate(max_link_clock, max_lanes);
659         mode_rate = intel_dp_link_required(target_clock, 18);
660
661         if (intel_dp_hdisplay_bad(dev_priv, mode->hdisplay))
662                 return MODE_H_ILLEGAL;
663
664         /*
665          * Output bpp is stored in 6.4 format so right shift by 4 to get the
666          * integer value since we support only integer values of bpp.
667          */
668         if ((INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv)) &&
669             drm_dp_sink_supports_dsc(intel_dp->dsc_dpcd)) {
670                 if (intel_dp_is_edp(intel_dp)) {
671                         dsc_max_output_bpp =
672                                 drm_edp_dsc_sink_output_bpp(intel_dp->dsc_dpcd) >> 4;
673                         dsc_slice_count =
674                                 drm_dp_dsc_sink_max_slice_count(intel_dp->dsc_dpcd,
675                                                                 true);
676                 } else if (drm_dp_sink_supports_fec(intel_dp->fec_capable)) {
677                         dsc_max_output_bpp =
678                                 intel_dp_dsc_get_output_bpp(dev_priv,
679                                                             max_link_clock,
680                                                             max_lanes,
681                                                             target_clock,
682                                                             mode->hdisplay) >> 4;
683                         dsc_slice_count =
684                                 intel_dp_dsc_get_slice_count(intel_dp,
685                                                              target_clock,
686                                                              mode->hdisplay);
687                 }
688         }
689
690         if ((mode_rate > max_rate && !(dsc_max_output_bpp && dsc_slice_count)) ||
691             target_clock > max_dotclk)
692                 return MODE_CLOCK_HIGH;
693
694         if (mode->clock < 10000)
695                 return MODE_CLOCK_LOW;
696
697         if (mode->flags & DRM_MODE_FLAG_DBLCLK)
698                 return MODE_H_ILLEGAL;
699
700         return intel_mode_valid_max_plane_size(dev_priv, mode);
701 }
702
703 u32 intel_dp_pack_aux(const u8 *src, int src_bytes)
704 {
705         int i;
706         u32 v = 0;
707
708         if (src_bytes > 4)
709                 src_bytes = 4;
710         for (i = 0; i < src_bytes; i++)
711                 v |= ((u32)src[i]) << ((3 - i) * 8);
712         return v;
713 }
714
715 static void intel_dp_unpack_aux(u32 src, u8 *dst, int dst_bytes)
716 {
717         int i;
718         if (dst_bytes > 4)
719                 dst_bytes = 4;
720         for (i = 0; i < dst_bytes; i++)
721                 dst[i] = src >> ((3-i) * 8);
722 }
723
724 static void
725 intel_dp_init_panel_power_sequencer(struct intel_dp *intel_dp);
726 static void
727 intel_dp_init_panel_power_sequencer_registers(struct intel_dp *intel_dp,
728                                               bool force_disable_vdd);
729 static void
730 intel_dp_pps_init(struct intel_dp *intel_dp);
731
732 static intel_wakeref_t
733 pps_lock(struct intel_dp *intel_dp)
734 {
735         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
736         intel_wakeref_t wakeref;
737
738         /*
739          * See intel_power_sequencer_reset() why we need
740          * a power domain reference here.
741          */
742         wakeref = intel_display_power_get(dev_priv,
743                                           intel_aux_power_domain(dp_to_dig_port(intel_dp)));
744
745         mutex_lock(&dev_priv->pps_mutex);
746
747         return wakeref;
748 }
749
750 static intel_wakeref_t
751 pps_unlock(struct intel_dp *intel_dp, intel_wakeref_t wakeref)
752 {
753         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
754
755         mutex_unlock(&dev_priv->pps_mutex);
756         intel_display_power_put(dev_priv,
757                                 intel_aux_power_domain(dp_to_dig_port(intel_dp)),
758                                 wakeref);
759         return 0;
760 }
761
762 #define with_pps_lock(dp, wf) \
763         for ((wf) = pps_lock(dp); (wf); (wf) = pps_unlock((dp), (wf)))
764
765 static void
766 vlv_power_sequencer_kick(struct intel_dp *intel_dp)
767 {
768         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
769         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
770         enum pipe pipe = intel_dp->pps_pipe;
771         bool pll_enabled, release_cl_override = false;
772         enum dpio_phy phy = DPIO_PHY(pipe);
773         enum dpio_channel ch = vlv_pipe_to_channel(pipe);
774         u32 DP;
775
776         if (drm_WARN(&dev_priv->drm,
777                      intel_de_read(dev_priv, intel_dp->output_reg) & DP_PORT_EN,
778                      "skipping pipe %c power sequencer kick due to [ENCODER:%d:%s] being active\n",
779                      pipe_name(pipe), intel_dig_port->base.base.base.id,
780                      intel_dig_port->base.base.name))
781                 return;
782
783         drm_dbg_kms(&dev_priv->drm,
784                     "kicking pipe %c power sequencer for [ENCODER:%d:%s]\n",
785                     pipe_name(pipe), intel_dig_port->base.base.base.id,
786                     intel_dig_port->base.base.name);
787
788         /* Preserve the BIOS-computed detected bit. This is
789          * supposed to be read-only.
790          */
791         DP = intel_de_read(dev_priv, intel_dp->output_reg) & DP_DETECTED;
792         DP |= DP_VOLTAGE_0_4 | DP_PRE_EMPHASIS_0;
793         DP |= DP_PORT_WIDTH(1);
794         DP |= DP_LINK_TRAIN_PAT_1;
795
796         if (IS_CHERRYVIEW(dev_priv))
797                 DP |= DP_PIPE_SEL_CHV(pipe);
798         else
799                 DP |= DP_PIPE_SEL(pipe);
800
801         pll_enabled = intel_de_read(dev_priv, DPLL(pipe)) & DPLL_VCO_ENABLE;
802
803         /*
804          * The DPLL for the pipe must be enabled for this to work.
805          * So enable temporarily it if it's not already enabled.
806          */
807         if (!pll_enabled) {
808                 release_cl_override = IS_CHERRYVIEW(dev_priv) &&
809                         !chv_phy_powergate_ch(dev_priv, phy, ch, true);
810
811                 if (vlv_force_pll_on(dev_priv, pipe, IS_CHERRYVIEW(dev_priv) ?
812                                      &chv_dpll[0].dpll : &vlv_dpll[0].dpll)) {
813                         drm_err(&dev_priv->drm,
814                                 "Failed to force on pll for pipe %c!\n",
815                                 pipe_name(pipe));
816                         return;
817                 }
818         }
819
820         /*
821          * Similar magic as in intel_dp_enable_port().
822          * We _must_ do this port enable + disable trick
823          * to make this power sequencer lock onto the port.
824          * Otherwise even VDD force bit won't work.
825          */
826         intel_de_write(dev_priv, intel_dp->output_reg, DP);
827         intel_de_posting_read(dev_priv, intel_dp->output_reg);
828
829         intel_de_write(dev_priv, intel_dp->output_reg, DP | DP_PORT_EN);
830         intel_de_posting_read(dev_priv, intel_dp->output_reg);
831
832         intel_de_write(dev_priv, intel_dp->output_reg, DP & ~DP_PORT_EN);
833         intel_de_posting_read(dev_priv, intel_dp->output_reg);
834
835         if (!pll_enabled) {
836                 vlv_force_pll_off(dev_priv, pipe);
837
838                 if (release_cl_override)
839                         chv_phy_powergate_ch(dev_priv, phy, ch, false);
840         }
841 }
842
843 static enum pipe vlv_find_free_pps(struct drm_i915_private *dev_priv)
844 {
845         struct intel_encoder *encoder;
846         unsigned int pipes = (1 << PIPE_A) | (1 << PIPE_B);
847
848         /*
849          * We don't have power sequencer currently.
850          * Pick one that's not used by other ports.
851          */
852         for_each_intel_dp(&dev_priv->drm, encoder) {
853                 struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
854
855                 if (encoder->type == INTEL_OUTPUT_EDP) {
856                         drm_WARN_ON(&dev_priv->drm,
857                                     intel_dp->active_pipe != INVALID_PIPE &&
858                                     intel_dp->active_pipe !=
859                                     intel_dp->pps_pipe);
860
861                         if (intel_dp->pps_pipe != INVALID_PIPE)
862                                 pipes &= ~(1 << intel_dp->pps_pipe);
863                 } else {
864                         drm_WARN_ON(&dev_priv->drm,
865                                     intel_dp->pps_pipe != INVALID_PIPE);
866
867                         if (intel_dp->active_pipe != INVALID_PIPE)
868                                 pipes &= ~(1 << intel_dp->active_pipe);
869                 }
870         }
871
872         if (pipes == 0)
873                 return INVALID_PIPE;
874
875         return ffs(pipes) - 1;
876 }
877
878 static enum pipe
879 vlv_power_sequencer_pipe(struct intel_dp *intel_dp)
880 {
881         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
882         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
883         enum pipe pipe;
884
885         lockdep_assert_held(&dev_priv->pps_mutex);
886
887         /* We should never land here with regular DP ports */
888         drm_WARN_ON(&dev_priv->drm, !intel_dp_is_edp(intel_dp));
889
890         drm_WARN_ON(&dev_priv->drm, intel_dp->active_pipe != INVALID_PIPE &&
891                     intel_dp->active_pipe != intel_dp->pps_pipe);
892
893         if (intel_dp->pps_pipe != INVALID_PIPE)
894                 return intel_dp->pps_pipe;
895
896         pipe = vlv_find_free_pps(dev_priv);
897
898         /*
899          * Didn't find one. This should not happen since there
900          * are two power sequencers and up to two eDP ports.
901          */
902         if (drm_WARN_ON(&dev_priv->drm, pipe == INVALID_PIPE))
903                 pipe = PIPE_A;
904
905         vlv_steal_power_sequencer(dev_priv, pipe);
906         intel_dp->pps_pipe = pipe;
907
908         drm_dbg_kms(&dev_priv->drm,
909                     "picked pipe %c power sequencer for [ENCODER:%d:%s]\n",
910                     pipe_name(intel_dp->pps_pipe),
911                     intel_dig_port->base.base.base.id,
912                     intel_dig_port->base.base.name);
913
914         /* init power sequencer on this pipe and port */
915         intel_dp_init_panel_power_sequencer(intel_dp);
916         intel_dp_init_panel_power_sequencer_registers(intel_dp, true);
917
918         /*
919          * Even vdd force doesn't work until we've made
920          * the power sequencer lock in on the port.
921          */
922         vlv_power_sequencer_kick(intel_dp);
923
924         return intel_dp->pps_pipe;
925 }
926
927 static int
928 bxt_power_sequencer_idx(struct intel_dp *intel_dp)
929 {
930         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
931         int backlight_controller = dev_priv->vbt.backlight.controller;
932
933         lockdep_assert_held(&dev_priv->pps_mutex);
934
935         /* We should never land here with regular DP ports */
936         drm_WARN_ON(&dev_priv->drm, !intel_dp_is_edp(intel_dp));
937
938         if (!intel_dp->pps_reset)
939                 return backlight_controller;
940
941         intel_dp->pps_reset = false;
942
943         /*
944          * Only the HW needs to be reprogrammed, the SW state is fixed and
945          * has been setup during connector init.
946          */
947         intel_dp_init_panel_power_sequencer_registers(intel_dp, false);
948
949         return backlight_controller;
950 }
951
952 typedef bool (*vlv_pipe_check)(struct drm_i915_private *dev_priv,
953                                enum pipe pipe);
954
955 static bool vlv_pipe_has_pp_on(struct drm_i915_private *dev_priv,
956                                enum pipe pipe)
957 {
958         return intel_de_read(dev_priv, PP_STATUS(pipe)) & PP_ON;
959 }
960
961 static bool vlv_pipe_has_vdd_on(struct drm_i915_private *dev_priv,
962                                 enum pipe pipe)
963 {
964         return intel_de_read(dev_priv, PP_CONTROL(pipe)) & EDP_FORCE_VDD;
965 }
966
967 static bool vlv_pipe_any(struct drm_i915_private *dev_priv,
968                          enum pipe pipe)
969 {
970         return true;
971 }
972
973 static enum pipe
974 vlv_initial_pps_pipe(struct drm_i915_private *dev_priv,
975                      enum port port,
976                      vlv_pipe_check pipe_check)
977 {
978         enum pipe pipe;
979
980         for (pipe = PIPE_A; pipe <= PIPE_B; pipe++) {
981                 u32 port_sel = intel_de_read(dev_priv, PP_ON_DELAYS(pipe)) &
982                         PANEL_PORT_SELECT_MASK;
983
984                 if (port_sel != PANEL_PORT_SELECT_VLV(port))
985                         continue;
986
987                 if (!pipe_check(dev_priv, pipe))
988                         continue;
989
990                 return pipe;
991         }
992
993         return INVALID_PIPE;
994 }
995
996 static void
997 vlv_initial_power_sequencer_setup(struct intel_dp *intel_dp)
998 {
999         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1000         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
1001         enum port port = intel_dig_port->base.port;
1002
1003         lockdep_assert_held(&dev_priv->pps_mutex);
1004
1005         /* try to find a pipe with this port selected */
1006         /* first pick one where the panel is on */
1007         intel_dp->pps_pipe = vlv_initial_pps_pipe(dev_priv, port,
1008                                                   vlv_pipe_has_pp_on);
1009         /* didn't find one? pick one where vdd is on */
1010         if (intel_dp->pps_pipe == INVALID_PIPE)
1011                 intel_dp->pps_pipe = vlv_initial_pps_pipe(dev_priv, port,
1012                                                           vlv_pipe_has_vdd_on);
1013         /* didn't find one? pick one with just the correct port */
1014         if (intel_dp->pps_pipe == INVALID_PIPE)
1015                 intel_dp->pps_pipe = vlv_initial_pps_pipe(dev_priv, port,
1016                                                           vlv_pipe_any);
1017
1018         /* didn't find one? just let vlv_power_sequencer_pipe() pick one when needed */
1019         if (intel_dp->pps_pipe == INVALID_PIPE) {
1020                 drm_dbg_kms(&dev_priv->drm,
1021                             "no initial power sequencer for [ENCODER:%d:%s]\n",
1022                             intel_dig_port->base.base.base.id,
1023                             intel_dig_port->base.base.name);
1024                 return;
1025         }
1026
1027         drm_dbg_kms(&dev_priv->drm,
1028                     "initial power sequencer for [ENCODER:%d:%s]: pipe %c\n",
1029                     intel_dig_port->base.base.base.id,
1030                     intel_dig_port->base.base.name,
1031                     pipe_name(intel_dp->pps_pipe));
1032
1033         intel_dp_init_panel_power_sequencer(intel_dp);
1034         intel_dp_init_panel_power_sequencer_registers(intel_dp, false);
1035 }
1036
1037 void intel_power_sequencer_reset(struct drm_i915_private *dev_priv)
1038 {
1039         struct intel_encoder *encoder;
1040
1041         if (drm_WARN_ON(&dev_priv->drm,
1042                         !(IS_VALLEYVIEW(dev_priv) ||
1043                           IS_CHERRYVIEW(dev_priv) ||
1044                           IS_GEN9_LP(dev_priv))))
1045                 return;
1046
1047         /*
1048          * We can't grab pps_mutex here due to deadlock with power_domain
1049          * mutex when power_domain functions are called while holding pps_mutex.
1050          * That also means that in order to use pps_pipe the code needs to
1051          * hold both a power domain reference and pps_mutex, and the power domain
1052          * reference get/put must be done while _not_ holding pps_mutex.
1053          * pps_{lock,unlock}() do these steps in the correct order, so one
1054          * should use them always.
1055          */
1056
1057         for_each_intel_dp(&dev_priv->drm, encoder) {
1058                 struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
1059
1060                 drm_WARN_ON(&dev_priv->drm,
1061                             intel_dp->active_pipe != INVALID_PIPE);
1062
1063                 if (encoder->type != INTEL_OUTPUT_EDP)
1064                         continue;
1065
1066                 if (IS_GEN9_LP(dev_priv))
1067                         intel_dp->pps_reset = true;
1068                 else
1069                         intel_dp->pps_pipe = INVALID_PIPE;
1070         }
1071 }
1072
1073 struct pps_registers {
1074         i915_reg_t pp_ctrl;
1075         i915_reg_t pp_stat;
1076         i915_reg_t pp_on;
1077         i915_reg_t pp_off;
1078         i915_reg_t pp_div;
1079 };
1080
1081 static void intel_pps_get_registers(struct intel_dp *intel_dp,
1082                                     struct pps_registers *regs)
1083 {
1084         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1085         int pps_idx = 0;
1086
1087         memset(regs, 0, sizeof(*regs));
1088
1089         if (IS_GEN9_LP(dev_priv))
1090                 pps_idx = bxt_power_sequencer_idx(intel_dp);
1091         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
1092                 pps_idx = vlv_power_sequencer_pipe(intel_dp);
1093
1094         regs->pp_ctrl = PP_CONTROL(pps_idx);
1095         regs->pp_stat = PP_STATUS(pps_idx);
1096         regs->pp_on = PP_ON_DELAYS(pps_idx);
1097         regs->pp_off = PP_OFF_DELAYS(pps_idx);
1098
1099         /* Cycle delay moved from PP_DIVISOR to PP_CONTROL */
1100         if (IS_GEN9_LP(dev_priv) || INTEL_PCH_TYPE(dev_priv) >= PCH_CNP)
1101                 regs->pp_div = INVALID_MMIO_REG;
1102         else
1103                 regs->pp_div = PP_DIVISOR(pps_idx);
1104 }
1105
1106 static i915_reg_t
1107 _pp_ctrl_reg(struct intel_dp *intel_dp)
1108 {
1109         struct pps_registers regs;
1110
1111         intel_pps_get_registers(intel_dp, &regs);
1112
1113         return regs.pp_ctrl;
1114 }
1115
1116 static i915_reg_t
1117 _pp_stat_reg(struct intel_dp *intel_dp)
1118 {
1119         struct pps_registers regs;
1120
1121         intel_pps_get_registers(intel_dp, &regs);
1122
1123         return regs.pp_stat;
1124 }
1125
1126 /* Reboot notifier handler to shutdown panel power to guarantee T12 timing
1127    This function only applicable when panel PM state is not to be tracked */
1128 static int edp_notify_handler(struct notifier_block *this, unsigned long code,
1129                               void *unused)
1130 {
1131         struct intel_dp *intel_dp = container_of(this, typeof(* intel_dp),
1132                                                  edp_notifier);
1133         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1134         intel_wakeref_t wakeref;
1135
1136         if (!intel_dp_is_edp(intel_dp) || code != SYS_RESTART)
1137                 return 0;
1138
1139         with_pps_lock(intel_dp, wakeref) {
1140                 if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
1141                         enum pipe pipe = vlv_power_sequencer_pipe(intel_dp);
1142                         i915_reg_t pp_ctrl_reg, pp_div_reg;
1143                         u32 pp_div;
1144
1145                         pp_ctrl_reg = PP_CONTROL(pipe);
1146                         pp_div_reg  = PP_DIVISOR(pipe);
1147                         pp_div = intel_de_read(dev_priv, pp_div_reg);
1148                         pp_div &= PP_REFERENCE_DIVIDER_MASK;
1149
1150                         /* 0x1F write to PP_DIV_REG sets max cycle delay */
1151                         intel_de_write(dev_priv, pp_div_reg, pp_div | 0x1F);
1152                         intel_de_write(dev_priv, pp_ctrl_reg,
1153                                        PANEL_UNLOCK_REGS);
1154                         msleep(intel_dp->panel_power_cycle_delay);
1155                 }
1156         }
1157
1158         return 0;
1159 }
1160
1161 static bool edp_have_panel_power(struct intel_dp *intel_dp)
1162 {
1163         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1164
1165         lockdep_assert_held(&dev_priv->pps_mutex);
1166
1167         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
1168             intel_dp->pps_pipe == INVALID_PIPE)
1169                 return false;
1170
1171         return (intel_de_read(dev_priv, _pp_stat_reg(intel_dp)) & PP_ON) != 0;
1172 }
1173
1174 static bool edp_have_panel_vdd(struct intel_dp *intel_dp)
1175 {
1176         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1177
1178         lockdep_assert_held(&dev_priv->pps_mutex);
1179
1180         if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
1181             intel_dp->pps_pipe == INVALID_PIPE)
1182                 return false;
1183
1184         return intel_de_read(dev_priv, _pp_ctrl_reg(intel_dp)) & EDP_FORCE_VDD;
1185 }
1186
1187 static void
1188 intel_dp_check_edp(struct intel_dp *intel_dp)
1189 {
1190         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1191
1192         if (!intel_dp_is_edp(intel_dp))
1193                 return;
1194
1195         if (!edp_have_panel_power(intel_dp) && !edp_have_panel_vdd(intel_dp)) {
1196                 drm_WARN(&dev_priv->drm, 1,
1197                          "eDP powered off while attempting aux channel communication.\n");
1198                 drm_dbg_kms(&dev_priv->drm, "Status 0x%08x Control 0x%08x\n",
1199                             intel_de_read(dev_priv, _pp_stat_reg(intel_dp)),
1200                             intel_de_read(dev_priv, _pp_ctrl_reg(intel_dp)));
1201         }
1202 }
1203
1204 static u32
1205 intel_dp_aux_wait_done(struct intel_dp *intel_dp)
1206 {
1207         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
1208         i915_reg_t ch_ctl = intel_dp->aux_ch_ctl_reg(intel_dp);
1209         const unsigned int timeout_ms = 10;
1210         u32 status;
1211         bool done;
1212
1213 #define C (((status = intel_uncore_read_notrace(&i915->uncore, ch_ctl)) & DP_AUX_CH_CTL_SEND_BUSY) == 0)
1214         done = wait_event_timeout(i915->gmbus_wait_queue, C,
1215                                   msecs_to_jiffies_timeout(timeout_ms));
1216
1217         /* just trace the final value */
1218         trace_i915_reg_rw(false, ch_ctl, status, sizeof(status), true);
1219
1220         if (!done)
1221                 drm_err(&i915->drm,
1222                         "%s: did not complete or timeout within %ums (status 0x%08x)\n",
1223                         intel_dp->aux.name, timeout_ms, status);
1224 #undef C
1225
1226         return status;
1227 }
1228
1229 static u32 g4x_get_aux_clock_divider(struct intel_dp *intel_dp, int index)
1230 {
1231         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1232
1233         if (index)
1234                 return 0;
1235
1236         /*
1237          * The clock divider is based off the hrawclk, and would like to run at
1238          * 2MHz.  So, take the hrawclk value and divide by 2000 and use that
1239          */
1240         return DIV_ROUND_CLOSEST(RUNTIME_INFO(dev_priv)->rawclk_freq, 2000);
1241 }
1242
1243 static u32 ilk_get_aux_clock_divider(struct intel_dp *intel_dp, int index)
1244 {
1245         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1246         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1247         u32 freq;
1248
1249         if (index)
1250                 return 0;
1251
1252         /*
1253          * The clock divider is based off the cdclk or PCH rawclk, and would
1254          * like to run at 2MHz.  So, take the cdclk or PCH rawclk value and
1255          * divide by 2000 and use that
1256          */
1257         if (dig_port->aux_ch == AUX_CH_A)
1258                 freq = dev_priv->cdclk.hw.cdclk;
1259         else
1260                 freq = RUNTIME_INFO(dev_priv)->rawclk_freq;
1261         return DIV_ROUND_CLOSEST(freq, 2000);
1262 }
1263
1264 static u32 hsw_get_aux_clock_divider(struct intel_dp *intel_dp, int index)
1265 {
1266         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1267         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1268
1269         if (dig_port->aux_ch != AUX_CH_A && HAS_PCH_LPT_H(dev_priv)) {
1270                 /* Workaround for non-ULT HSW */
1271                 switch (index) {
1272                 case 0: return 63;
1273                 case 1: return 72;
1274                 default: return 0;
1275                 }
1276         }
1277
1278         return ilk_get_aux_clock_divider(intel_dp, index);
1279 }
1280
1281 static u32 skl_get_aux_clock_divider(struct intel_dp *intel_dp, int index)
1282 {
1283         /*
1284          * SKL doesn't need us to program the AUX clock divider (Hardware will
1285          * derive the clock from CDCLK automatically). We still implement the
1286          * get_aux_clock_divider vfunc to plug-in into the existing code.
1287          */
1288         return index ? 0 : 1;
1289 }
1290
1291 static u32 g4x_get_aux_send_ctl(struct intel_dp *intel_dp,
1292                                 int send_bytes,
1293                                 u32 aux_clock_divider)
1294 {
1295         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
1296         struct drm_i915_private *dev_priv =
1297                         to_i915(intel_dig_port->base.base.dev);
1298         u32 precharge, timeout;
1299
1300         if (IS_GEN(dev_priv, 6))
1301                 precharge = 3;
1302         else
1303                 precharge = 5;
1304
1305         if (IS_BROADWELL(dev_priv))
1306                 timeout = DP_AUX_CH_CTL_TIME_OUT_600us;
1307         else
1308                 timeout = DP_AUX_CH_CTL_TIME_OUT_400us;
1309
1310         return DP_AUX_CH_CTL_SEND_BUSY |
1311                DP_AUX_CH_CTL_DONE |
1312                DP_AUX_CH_CTL_INTERRUPT |
1313                DP_AUX_CH_CTL_TIME_OUT_ERROR |
1314                timeout |
1315                DP_AUX_CH_CTL_RECEIVE_ERROR |
1316                (send_bytes << DP_AUX_CH_CTL_MESSAGE_SIZE_SHIFT) |
1317                (precharge << DP_AUX_CH_CTL_PRECHARGE_2US_SHIFT) |
1318                (aux_clock_divider << DP_AUX_CH_CTL_BIT_CLOCK_2X_SHIFT);
1319 }
1320
1321 static u32 skl_get_aux_send_ctl(struct intel_dp *intel_dp,
1322                                 int send_bytes,
1323                                 u32 unused)
1324 {
1325         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
1326         struct drm_i915_private *i915 =
1327                         to_i915(intel_dig_port->base.base.dev);
1328         enum phy phy = intel_port_to_phy(i915, intel_dig_port->base.port);
1329         u32 ret;
1330
1331         ret = DP_AUX_CH_CTL_SEND_BUSY |
1332               DP_AUX_CH_CTL_DONE |
1333               DP_AUX_CH_CTL_INTERRUPT |
1334               DP_AUX_CH_CTL_TIME_OUT_ERROR |
1335               DP_AUX_CH_CTL_TIME_OUT_MAX |
1336               DP_AUX_CH_CTL_RECEIVE_ERROR |
1337               (send_bytes << DP_AUX_CH_CTL_MESSAGE_SIZE_SHIFT) |
1338               DP_AUX_CH_CTL_FW_SYNC_PULSE_SKL(32) |
1339               DP_AUX_CH_CTL_SYNC_PULSE_SKL(32);
1340
1341         if (intel_phy_is_tc(i915, phy) &&
1342             intel_dig_port->tc_mode == TC_PORT_TBT_ALT)
1343                 ret |= DP_AUX_CH_CTL_TBT_IO;
1344
1345         return ret;
1346 }
1347
1348 static int
1349 intel_dp_aux_xfer(struct intel_dp *intel_dp,
1350                   const u8 *send, int send_bytes,
1351                   u8 *recv, int recv_size,
1352                   u32 aux_send_ctl_flags)
1353 {
1354         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
1355         struct drm_i915_private *i915 =
1356                         to_i915(intel_dig_port->base.base.dev);
1357         struct intel_uncore *uncore = &i915->uncore;
1358         enum phy phy = intel_port_to_phy(i915, intel_dig_port->base.port);
1359         bool is_tc_port = intel_phy_is_tc(i915, phy);
1360         i915_reg_t ch_ctl, ch_data[5];
1361         u32 aux_clock_divider;
1362         enum intel_display_power_domain aux_domain =
1363                 intel_aux_power_domain(intel_dig_port);
1364         intel_wakeref_t aux_wakeref;
1365         intel_wakeref_t pps_wakeref;
1366         int i, ret, recv_bytes;
1367         int try, clock = 0;
1368         u32 status;
1369         bool vdd;
1370
1371         ch_ctl = intel_dp->aux_ch_ctl_reg(intel_dp);
1372         for (i = 0; i < ARRAY_SIZE(ch_data); i++)
1373                 ch_data[i] = intel_dp->aux_ch_data_reg(intel_dp, i);
1374
1375         if (is_tc_port)
1376                 intel_tc_port_lock(intel_dig_port);
1377
1378         aux_wakeref = intel_display_power_get(i915, aux_domain);
1379         pps_wakeref = pps_lock(intel_dp);
1380
1381         /*
1382          * We will be called with VDD already enabled for dpcd/edid/oui reads.
1383          * In such cases we want to leave VDD enabled and it's up to upper layers
1384          * to turn it off. But for eg. i2c-dev access we need to turn it on/off
1385          * ourselves.
1386          */
1387         vdd = edp_panel_vdd_on(intel_dp);
1388
1389         /* dp aux is extremely sensitive to irq latency, hence request the
1390          * lowest possible wakeup latency and so prevent the cpu from going into
1391          * deep sleep states.
1392          */
1393         cpu_latency_qos_update_request(&i915->pm_qos, 0);
1394
1395         intel_dp_check_edp(intel_dp);
1396
1397         /* Try to wait for any previous AUX channel activity */
1398         for (try = 0; try < 3; try++) {
1399                 status = intel_uncore_read_notrace(uncore, ch_ctl);
1400                 if ((status & DP_AUX_CH_CTL_SEND_BUSY) == 0)
1401                         break;
1402                 msleep(1);
1403         }
1404         /* just trace the final value */
1405         trace_i915_reg_rw(false, ch_ctl, status, sizeof(status), true);
1406
1407         if (try == 3) {
1408                 const u32 status = intel_uncore_read(uncore, ch_ctl);
1409
1410                 if (status != intel_dp->aux_busy_last_status) {
1411                         drm_WARN(&i915->drm, 1,
1412                                  "%s: not started (status 0x%08x)\n",
1413                                  intel_dp->aux.name, status);
1414                         intel_dp->aux_busy_last_status = status;
1415                 }
1416
1417                 ret = -EBUSY;
1418                 goto out;
1419         }
1420
1421         /* Only 5 data registers! */
1422         if (drm_WARN_ON(&i915->drm, send_bytes > 20 || recv_size > 20)) {
1423                 ret = -E2BIG;
1424                 goto out;
1425         }
1426
1427         while ((aux_clock_divider = intel_dp->get_aux_clock_divider(intel_dp, clock++))) {
1428                 u32 send_ctl = intel_dp->get_aux_send_ctl(intel_dp,
1429                                                           send_bytes,
1430                                                           aux_clock_divider);
1431
1432                 send_ctl |= aux_send_ctl_flags;
1433
1434                 /* Must try at least 3 times according to DP spec */
1435                 for (try = 0; try < 5; try++) {
1436                         /* Load the send data into the aux channel data registers */
1437                         for (i = 0; i < send_bytes; i += 4)
1438                                 intel_uncore_write(uncore,
1439                                                    ch_data[i >> 2],
1440                                                    intel_dp_pack_aux(send + i,
1441                                                                      send_bytes - i));
1442
1443                         /* Send the command and wait for it to complete */
1444                         intel_uncore_write(uncore, ch_ctl, send_ctl);
1445
1446                         status = intel_dp_aux_wait_done(intel_dp);
1447
1448                         /* Clear done status and any errors */
1449                         intel_uncore_write(uncore,
1450                                            ch_ctl,
1451                                            status |
1452                                            DP_AUX_CH_CTL_DONE |
1453                                            DP_AUX_CH_CTL_TIME_OUT_ERROR |
1454                                            DP_AUX_CH_CTL_RECEIVE_ERROR);
1455
1456                         /* DP CTS 1.2 Core Rev 1.1, 4.2.1.1 & 4.2.1.2
1457                          *   400us delay required for errors and timeouts
1458                          *   Timeout errors from the HW already meet this
1459                          *   requirement so skip to next iteration
1460                          */
1461                         if (status & DP_AUX_CH_CTL_TIME_OUT_ERROR)
1462                                 continue;
1463
1464                         if (status & DP_AUX_CH_CTL_RECEIVE_ERROR) {
1465                                 usleep_range(400, 500);
1466                                 continue;
1467                         }
1468                         if (status & DP_AUX_CH_CTL_DONE)
1469                                 goto done;
1470                 }
1471         }
1472
1473         if ((status & DP_AUX_CH_CTL_DONE) == 0) {
1474                 drm_err(&i915->drm, "%s: not done (status 0x%08x)\n",
1475                         intel_dp->aux.name, status);
1476                 ret = -EBUSY;
1477                 goto out;
1478         }
1479
1480 done:
1481         /* Check for timeout or receive error.
1482          * Timeouts occur when the sink is not connected
1483          */
1484         if (status & DP_AUX_CH_CTL_RECEIVE_ERROR) {
1485                 drm_err(&i915->drm, "%s: receive error (status 0x%08x)\n",
1486                         intel_dp->aux.name, status);
1487                 ret = -EIO;
1488                 goto out;
1489         }
1490
1491         /* Timeouts occur when the device isn't connected, so they're
1492          * "normal" -- don't fill the kernel log with these */
1493         if (status & DP_AUX_CH_CTL_TIME_OUT_ERROR) {
1494                 drm_dbg_kms(&i915->drm, "%s: timeout (status 0x%08x)\n",
1495                             intel_dp->aux.name, status);
1496                 ret = -ETIMEDOUT;
1497                 goto out;
1498         }
1499
1500         /* Unload any bytes sent back from the other side */
1501         recv_bytes = ((status & DP_AUX_CH_CTL_MESSAGE_SIZE_MASK) >>
1502                       DP_AUX_CH_CTL_MESSAGE_SIZE_SHIFT);
1503
1504         /*
1505          * By BSpec: "Message sizes of 0 or >20 are not allowed."
1506          * We have no idea of what happened so we return -EBUSY so
1507          * drm layer takes care for the necessary retries.
1508          */
1509         if (recv_bytes == 0 || recv_bytes > 20) {
1510                 drm_dbg_kms(&i915->drm,
1511                             "%s: Forbidden recv_bytes = %d on aux transaction\n",
1512                             intel_dp->aux.name, recv_bytes);
1513                 ret = -EBUSY;
1514                 goto out;
1515         }
1516
1517         if (recv_bytes > recv_size)
1518                 recv_bytes = recv_size;
1519
1520         for (i = 0; i < recv_bytes; i += 4)
1521                 intel_dp_unpack_aux(intel_uncore_read(uncore, ch_data[i >> 2]),
1522                                     recv + i, recv_bytes - i);
1523
1524         ret = recv_bytes;
1525 out:
1526         cpu_latency_qos_update_request(&i915->pm_qos, PM_QOS_DEFAULT_VALUE);
1527
1528         if (vdd)
1529                 edp_panel_vdd_off(intel_dp, false);
1530
1531         pps_unlock(intel_dp, pps_wakeref);
1532         intel_display_power_put_async(i915, aux_domain, aux_wakeref);
1533
1534         if (is_tc_port)
1535                 intel_tc_port_unlock(intel_dig_port);
1536
1537         return ret;
1538 }
1539
1540 #define BARE_ADDRESS_SIZE       3
1541 #define HEADER_SIZE             (BARE_ADDRESS_SIZE + 1)
1542
1543 static void
1544 intel_dp_aux_header(u8 txbuf[HEADER_SIZE],
1545                     const struct drm_dp_aux_msg *msg)
1546 {
1547         txbuf[0] = (msg->request << 4) | ((msg->address >> 16) & 0xf);
1548         txbuf[1] = (msg->address >> 8) & 0xff;
1549         txbuf[2] = msg->address & 0xff;
1550         txbuf[3] = msg->size - 1;
1551 }
1552
1553 static ssize_t
1554 intel_dp_aux_transfer(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
1555 {
1556         struct intel_dp *intel_dp = container_of(aux, struct intel_dp, aux);
1557         u8 txbuf[20], rxbuf[20];
1558         size_t txsize, rxsize;
1559         int ret;
1560
1561         intel_dp_aux_header(txbuf, msg);
1562
1563         switch (msg->request & ~DP_AUX_I2C_MOT) {
1564         case DP_AUX_NATIVE_WRITE:
1565         case DP_AUX_I2C_WRITE:
1566         case DP_AUX_I2C_WRITE_STATUS_UPDATE:
1567                 txsize = msg->size ? HEADER_SIZE + msg->size : BARE_ADDRESS_SIZE;
1568                 rxsize = 2; /* 0 or 1 data bytes */
1569
1570                 if (WARN_ON(txsize > 20))
1571                         return -E2BIG;
1572
1573                 WARN_ON(!msg->buffer != !msg->size);
1574
1575                 if (msg->buffer)
1576                         memcpy(txbuf + HEADER_SIZE, msg->buffer, msg->size);
1577
1578                 ret = intel_dp_aux_xfer(intel_dp, txbuf, txsize,
1579                                         rxbuf, rxsize, 0);
1580                 if (ret > 0) {
1581                         msg->reply = rxbuf[0] >> 4;
1582
1583                         if (ret > 1) {
1584                                 /* Number of bytes written in a short write. */
1585                                 ret = clamp_t(int, rxbuf[1], 0, msg->size);
1586                         } else {
1587                                 /* Return payload size. */
1588                                 ret = msg->size;
1589                         }
1590                 }
1591                 break;
1592
1593         case DP_AUX_NATIVE_READ:
1594         case DP_AUX_I2C_READ:
1595                 txsize = msg->size ? HEADER_SIZE : BARE_ADDRESS_SIZE;
1596                 rxsize = msg->size + 1;
1597
1598                 if (WARN_ON(rxsize > 20))
1599                         return -E2BIG;
1600
1601                 ret = intel_dp_aux_xfer(intel_dp, txbuf, txsize,
1602                                         rxbuf, rxsize, 0);
1603                 if (ret > 0) {
1604                         msg->reply = rxbuf[0] >> 4;
1605                         /*
1606                          * Assume happy day, and copy the data. The caller is
1607                          * expected to check msg->reply before touching it.
1608                          *
1609                          * Return payload size.
1610                          */
1611                         ret--;
1612                         memcpy(msg->buffer, rxbuf + 1, ret);
1613                 }
1614                 break;
1615
1616         default:
1617                 ret = -EINVAL;
1618                 break;
1619         }
1620
1621         return ret;
1622 }
1623
1624
1625 static i915_reg_t g4x_aux_ctl_reg(struct intel_dp *intel_dp)
1626 {
1627         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1628         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1629         enum aux_ch aux_ch = dig_port->aux_ch;
1630
1631         switch (aux_ch) {
1632         case AUX_CH_B:
1633         case AUX_CH_C:
1634         case AUX_CH_D:
1635                 return DP_AUX_CH_CTL(aux_ch);
1636         default:
1637                 MISSING_CASE(aux_ch);
1638                 return DP_AUX_CH_CTL(AUX_CH_B);
1639         }
1640 }
1641
1642 static i915_reg_t g4x_aux_data_reg(struct intel_dp *intel_dp, int index)
1643 {
1644         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1645         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1646         enum aux_ch aux_ch = dig_port->aux_ch;
1647
1648         switch (aux_ch) {
1649         case AUX_CH_B:
1650         case AUX_CH_C:
1651         case AUX_CH_D:
1652                 return DP_AUX_CH_DATA(aux_ch, index);
1653         default:
1654                 MISSING_CASE(aux_ch);
1655                 return DP_AUX_CH_DATA(AUX_CH_B, index);
1656         }
1657 }
1658
1659 static i915_reg_t ilk_aux_ctl_reg(struct intel_dp *intel_dp)
1660 {
1661         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1662         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1663         enum aux_ch aux_ch = dig_port->aux_ch;
1664
1665         switch (aux_ch) {
1666         case AUX_CH_A:
1667                 return DP_AUX_CH_CTL(aux_ch);
1668         case AUX_CH_B:
1669         case AUX_CH_C:
1670         case AUX_CH_D:
1671                 return PCH_DP_AUX_CH_CTL(aux_ch);
1672         default:
1673                 MISSING_CASE(aux_ch);
1674                 return DP_AUX_CH_CTL(AUX_CH_A);
1675         }
1676 }
1677
1678 static i915_reg_t ilk_aux_data_reg(struct intel_dp *intel_dp, int index)
1679 {
1680         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1681         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1682         enum aux_ch aux_ch = dig_port->aux_ch;
1683
1684         switch (aux_ch) {
1685         case AUX_CH_A:
1686                 return DP_AUX_CH_DATA(aux_ch, index);
1687         case AUX_CH_B:
1688         case AUX_CH_C:
1689         case AUX_CH_D:
1690                 return PCH_DP_AUX_CH_DATA(aux_ch, index);
1691         default:
1692                 MISSING_CASE(aux_ch);
1693                 return DP_AUX_CH_DATA(AUX_CH_A, index);
1694         }
1695 }
1696
1697 static i915_reg_t skl_aux_ctl_reg(struct intel_dp *intel_dp)
1698 {
1699         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1700         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1701         enum aux_ch aux_ch = dig_port->aux_ch;
1702
1703         switch (aux_ch) {
1704         case AUX_CH_A:
1705         case AUX_CH_B:
1706         case AUX_CH_C:
1707         case AUX_CH_D:
1708         case AUX_CH_E:
1709         case AUX_CH_F:
1710         case AUX_CH_G:
1711                 return DP_AUX_CH_CTL(aux_ch);
1712         default:
1713                 MISSING_CASE(aux_ch);
1714                 return DP_AUX_CH_CTL(AUX_CH_A);
1715         }
1716 }
1717
1718 static i915_reg_t skl_aux_data_reg(struct intel_dp *intel_dp, int index)
1719 {
1720         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1721         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1722         enum aux_ch aux_ch = dig_port->aux_ch;
1723
1724         switch (aux_ch) {
1725         case AUX_CH_A:
1726         case AUX_CH_B:
1727         case AUX_CH_C:
1728         case AUX_CH_D:
1729         case AUX_CH_E:
1730         case AUX_CH_F:
1731         case AUX_CH_G:
1732                 return DP_AUX_CH_DATA(aux_ch, index);
1733         default:
1734                 MISSING_CASE(aux_ch);
1735                 return DP_AUX_CH_DATA(AUX_CH_A, index);
1736         }
1737 }
1738
1739 static void
1740 intel_dp_aux_fini(struct intel_dp *intel_dp)
1741 {
1742         kfree(intel_dp->aux.name);
1743 }
1744
1745 static void
1746 intel_dp_aux_init(struct intel_dp *intel_dp)
1747 {
1748         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1749         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
1750         struct intel_encoder *encoder = &dig_port->base;
1751
1752         if (INTEL_GEN(dev_priv) >= 9) {
1753                 intel_dp->aux_ch_ctl_reg = skl_aux_ctl_reg;
1754                 intel_dp->aux_ch_data_reg = skl_aux_data_reg;
1755         } else if (HAS_PCH_SPLIT(dev_priv)) {
1756                 intel_dp->aux_ch_ctl_reg = ilk_aux_ctl_reg;
1757                 intel_dp->aux_ch_data_reg = ilk_aux_data_reg;
1758         } else {
1759                 intel_dp->aux_ch_ctl_reg = g4x_aux_ctl_reg;
1760                 intel_dp->aux_ch_data_reg = g4x_aux_data_reg;
1761         }
1762
1763         if (INTEL_GEN(dev_priv) >= 9)
1764                 intel_dp->get_aux_clock_divider = skl_get_aux_clock_divider;
1765         else if (IS_BROADWELL(dev_priv) || IS_HASWELL(dev_priv))
1766                 intel_dp->get_aux_clock_divider = hsw_get_aux_clock_divider;
1767         else if (HAS_PCH_SPLIT(dev_priv))
1768                 intel_dp->get_aux_clock_divider = ilk_get_aux_clock_divider;
1769         else
1770                 intel_dp->get_aux_clock_divider = g4x_get_aux_clock_divider;
1771
1772         if (INTEL_GEN(dev_priv) >= 9)
1773                 intel_dp->get_aux_send_ctl = skl_get_aux_send_ctl;
1774         else
1775                 intel_dp->get_aux_send_ctl = g4x_get_aux_send_ctl;
1776
1777         drm_dp_aux_init(&intel_dp->aux);
1778
1779         /* Failure to allocate our preferred name is not critical */
1780         intel_dp->aux.name = kasprintf(GFP_KERNEL, "AUX %c/port %c",
1781                                        aux_ch_name(dig_port->aux_ch),
1782                                        port_name(encoder->port));
1783         intel_dp->aux.transfer = intel_dp_aux_transfer;
1784 }
1785
1786 bool intel_dp_source_supports_hbr2(struct intel_dp *intel_dp)
1787 {
1788         int max_rate = intel_dp->source_rates[intel_dp->num_source_rates - 1];
1789
1790         return max_rate >= 540000;
1791 }
1792
1793 bool intel_dp_source_supports_hbr3(struct intel_dp *intel_dp)
1794 {
1795         int max_rate = intel_dp->source_rates[intel_dp->num_source_rates - 1];
1796
1797         return max_rate >= 810000;
1798 }
1799
1800 static void
1801 intel_dp_set_clock(struct intel_encoder *encoder,
1802                    struct intel_crtc_state *pipe_config)
1803 {
1804         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
1805         const struct dp_link_dpll *divisor = NULL;
1806         int i, count = 0;
1807
1808         if (IS_G4X(dev_priv)) {
1809                 divisor = g4x_dpll;
1810                 count = ARRAY_SIZE(g4x_dpll);
1811         } else if (HAS_PCH_SPLIT(dev_priv)) {
1812                 divisor = pch_dpll;
1813                 count = ARRAY_SIZE(pch_dpll);
1814         } else if (IS_CHERRYVIEW(dev_priv)) {
1815                 divisor = chv_dpll;
1816                 count = ARRAY_SIZE(chv_dpll);
1817         } else if (IS_VALLEYVIEW(dev_priv)) {
1818                 divisor = vlv_dpll;
1819                 count = ARRAY_SIZE(vlv_dpll);
1820         }
1821
1822         if (divisor && count) {
1823                 for (i = 0; i < count; i++) {
1824                         if (pipe_config->port_clock == divisor[i].clock) {
1825                                 pipe_config->dpll = divisor[i].dpll;
1826                                 pipe_config->clock_set = true;
1827                                 break;
1828                         }
1829                 }
1830         }
1831 }
1832
1833 static void snprintf_int_array(char *str, size_t len,
1834                                const int *array, int nelem)
1835 {
1836         int i;
1837
1838         str[0] = '\0';
1839
1840         for (i = 0; i < nelem; i++) {
1841                 int r = snprintf(str, len, "%s%d", i ? ", " : "", array[i]);
1842                 if (r >= len)
1843                         return;
1844                 str += r;
1845                 len -= r;
1846         }
1847 }
1848
1849 static void intel_dp_print_rates(struct intel_dp *intel_dp)
1850 {
1851         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
1852         char str[128]; /* FIXME: too big for stack? */
1853
1854         if (!drm_debug_enabled(DRM_UT_KMS))
1855                 return;
1856
1857         snprintf_int_array(str, sizeof(str),
1858                            intel_dp->source_rates, intel_dp->num_source_rates);
1859         drm_dbg_kms(&i915->drm, "source rates: %s\n", str);
1860
1861         snprintf_int_array(str, sizeof(str),
1862                            intel_dp->sink_rates, intel_dp->num_sink_rates);
1863         drm_dbg_kms(&i915->drm, "sink rates: %s\n", str);
1864
1865         snprintf_int_array(str, sizeof(str),
1866                            intel_dp->common_rates, intel_dp->num_common_rates);
1867         drm_dbg_kms(&i915->drm, "common rates: %s\n", str);
1868 }
1869
1870 int
1871 intel_dp_max_link_rate(struct intel_dp *intel_dp)
1872 {
1873         int len;
1874
1875         len = intel_dp_common_len_rate_limit(intel_dp, intel_dp->max_link_rate);
1876         if (WARN_ON(len <= 0))
1877                 return 162000;
1878
1879         return intel_dp->common_rates[len - 1];
1880 }
1881
1882 int intel_dp_rate_select(struct intel_dp *intel_dp, int rate)
1883 {
1884         int i = intel_dp_rate_index(intel_dp->sink_rates,
1885                                     intel_dp->num_sink_rates, rate);
1886
1887         if (WARN_ON(i < 0))
1888                 i = 0;
1889
1890         return i;
1891 }
1892
1893 void intel_dp_compute_rate(struct intel_dp *intel_dp, int port_clock,
1894                            u8 *link_bw, u8 *rate_select)
1895 {
1896         /* eDP 1.4 rate select method. */
1897         if (intel_dp->use_rate_select) {
1898                 *link_bw = 0;
1899                 *rate_select =
1900                         intel_dp_rate_select(intel_dp, port_clock);
1901         } else {
1902                 *link_bw = drm_dp_link_rate_to_bw_code(port_clock);
1903                 *rate_select = 0;
1904         }
1905 }
1906
1907 static bool intel_dp_source_supports_fec(struct intel_dp *intel_dp,
1908                                          const struct intel_crtc_state *pipe_config)
1909 {
1910         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1911
1912         /* On TGL, FEC is supported on all Pipes */
1913         if (INTEL_GEN(dev_priv) >= 12)
1914                 return true;
1915
1916         if (IS_GEN(dev_priv, 11) && pipe_config->cpu_transcoder != TRANSCODER_A)
1917                 return true;
1918
1919         return false;
1920 }
1921
1922 static bool intel_dp_supports_fec(struct intel_dp *intel_dp,
1923                                   const struct intel_crtc_state *pipe_config)
1924 {
1925         return intel_dp_source_supports_fec(intel_dp, pipe_config) &&
1926                 drm_dp_sink_supports_fec(intel_dp->fec_capable);
1927 }
1928
1929 static bool intel_dp_supports_dsc(struct intel_dp *intel_dp,
1930                                   const struct intel_crtc_state *crtc_state)
1931 {
1932         struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
1933
1934         if (!intel_dp_is_edp(intel_dp) && !crtc_state->fec_enable)
1935                 return false;
1936
1937         return intel_dsc_source_support(encoder, crtc_state) &&
1938                 drm_dp_sink_supports_dsc(intel_dp->dsc_dpcd);
1939 }
1940
1941 static int intel_dp_compute_bpp(struct intel_dp *intel_dp,
1942                                 struct intel_crtc_state *pipe_config)
1943 {
1944         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
1945         struct intel_connector *intel_connector = intel_dp->attached_connector;
1946         int bpp, bpc;
1947
1948         bpp = pipe_config->pipe_bpp;
1949         bpc = drm_dp_downstream_max_bpc(intel_dp->dpcd, intel_dp->downstream_ports);
1950
1951         if (bpc > 0)
1952                 bpp = min(bpp, 3*bpc);
1953
1954         if (intel_dp_is_edp(intel_dp)) {
1955                 /* Get bpp from vbt only for panels that dont have bpp in edid */
1956                 if (intel_connector->base.display_info.bpc == 0 &&
1957                     dev_priv->vbt.edp.bpp && dev_priv->vbt.edp.bpp < bpp) {
1958                         drm_dbg_kms(&dev_priv->drm,
1959                                     "clamping bpp for eDP panel to BIOS-provided %i\n",
1960                                     dev_priv->vbt.edp.bpp);
1961                         bpp = dev_priv->vbt.edp.bpp;
1962                 }
1963         }
1964
1965         return bpp;
1966 }
1967
1968 /* Adjust link config limits based on compliance test requests. */
1969 void
1970 intel_dp_adjust_compliance_config(struct intel_dp *intel_dp,
1971                                   struct intel_crtc_state *pipe_config,
1972                                   struct link_config_limits *limits)
1973 {
1974         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
1975
1976         /* For DP Compliance we override the computed bpp for the pipe */
1977         if (intel_dp->compliance.test_data.bpc != 0) {
1978                 int bpp = 3 * intel_dp->compliance.test_data.bpc;
1979
1980                 limits->min_bpp = limits->max_bpp = bpp;
1981                 pipe_config->dither_force_disable = bpp == 6 * 3;
1982
1983                 drm_dbg_kms(&i915->drm, "Setting pipe_bpp to %d\n", bpp);
1984         }
1985
1986         /* Use values requested by Compliance Test Request */
1987         if (intel_dp->compliance.test_type == DP_TEST_LINK_TRAINING) {
1988                 int index;
1989
1990                 /* Validate the compliance test data since max values
1991                  * might have changed due to link train fallback.
1992                  */
1993                 if (intel_dp_link_params_valid(intel_dp, intel_dp->compliance.test_link_rate,
1994                                                intel_dp->compliance.test_lane_count)) {
1995                         index = intel_dp_rate_index(intel_dp->common_rates,
1996                                                     intel_dp->num_common_rates,
1997                                                     intel_dp->compliance.test_link_rate);
1998                         if (index >= 0)
1999                                 limits->min_clock = limits->max_clock = index;
2000                         limits->min_lane_count = limits->max_lane_count =
2001                                 intel_dp->compliance.test_lane_count;
2002                 }
2003         }
2004 }
2005
2006 static int intel_dp_output_bpp(const struct intel_crtc_state *crtc_state, int bpp)
2007 {
2008         /*
2009          * bpp value was assumed to RGB format. And YCbCr 4:2:0 output
2010          * format of the number of bytes per pixel will be half the number
2011          * of bytes of RGB pixel.
2012          */
2013         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
2014                 bpp /= 2;
2015
2016         return bpp;
2017 }
2018
2019 /* Optimize link config in order: max bpp, min clock, min lanes */
2020 static int
2021 intel_dp_compute_link_config_wide(struct intel_dp *intel_dp,
2022                                   struct intel_crtc_state *pipe_config,
2023                                   const struct link_config_limits *limits)
2024 {
2025         struct drm_display_mode *adjusted_mode = &pipe_config->hw.adjusted_mode;
2026         int bpp, clock, lane_count;
2027         int mode_rate, link_clock, link_avail;
2028
2029         for (bpp = limits->max_bpp; bpp >= limits->min_bpp; bpp -= 2 * 3) {
2030                 int output_bpp = intel_dp_output_bpp(pipe_config, bpp);
2031
2032                 mode_rate = intel_dp_link_required(adjusted_mode->crtc_clock,
2033                                                    output_bpp);
2034
2035                 for (clock = limits->min_clock; clock <= limits->max_clock; clock++) {
2036                         for (lane_count = limits->min_lane_count;
2037                              lane_count <= limits->max_lane_count;
2038                              lane_count <<= 1) {
2039                                 link_clock = intel_dp->common_rates[clock];
2040                                 link_avail = intel_dp_max_data_rate(link_clock,
2041                                                                     lane_count);
2042
2043                                 if (mode_rate <= link_avail) {
2044                                         pipe_config->lane_count = lane_count;
2045                                         pipe_config->pipe_bpp = bpp;
2046                                         pipe_config->port_clock = link_clock;
2047
2048                                         return 0;
2049                                 }
2050                         }
2051                 }
2052         }
2053
2054         return -EINVAL;
2055 }
2056
2057 static int intel_dp_dsc_compute_bpp(struct intel_dp *intel_dp, u8 dsc_max_bpc)
2058 {
2059         int i, num_bpc;
2060         u8 dsc_bpc[3] = {0};
2061
2062         num_bpc = drm_dp_dsc_sink_supported_input_bpcs(intel_dp->dsc_dpcd,
2063                                                        dsc_bpc);
2064         for (i = 0; i < num_bpc; i++) {
2065                 if (dsc_max_bpc >= dsc_bpc[i])
2066                         return dsc_bpc[i] * 3;
2067         }
2068
2069         return 0;
2070 }
2071
2072 #define DSC_SUPPORTED_VERSION_MIN               1
2073
2074 static int intel_dp_dsc_compute_params(struct intel_encoder *encoder,
2075                                        struct intel_crtc_state *crtc_state)
2076 {
2077         struct drm_i915_private *i915 = to_i915(encoder->base.dev);
2078         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
2079         struct drm_dsc_config *vdsc_cfg = &crtc_state->dsc.config;
2080         u8 line_buf_depth;
2081         int ret;
2082
2083         ret = intel_dsc_compute_params(encoder, crtc_state);
2084         if (ret)
2085                 return ret;
2086
2087         /*
2088          * Slice Height of 8 works for all currently available panels. So start
2089          * with that if pic_height is an integral multiple of 8. Eventually add
2090          * logic to try multiple slice heights.
2091          */
2092         if (vdsc_cfg->pic_height % 8 == 0)
2093                 vdsc_cfg->slice_height = 8;
2094         else if (vdsc_cfg->pic_height % 4 == 0)
2095                 vdsc_cfg->slice_height = 4;
2096         else
2097                 vdsc_cfg->slice_height = 2;
2098
2099         vdsc_cfg->dsc_version_major =
2100                 (intel_dp->dsc_dpcd[DP_DSC_REV - DP_DSC_SUPPORT] &
2101                  DP_DSC_MAJOR_MASK) >> DP_DSC_MAJOR_SHIFT;
2102         vdsc_cfg->dsc_version_minor =
2103                 min(DSC_SUPPORTED_VERSION_MIN,
2104                     (intel_dp->dsc_dpcd[DP_DSC_REV - DP_DSC_SUPPORT] &
2105                      DP_DSC_MINOR_MASK) >> DP_DSC_MINOR_SHIFT);
2106
2107         vdsc_cfg->convert_rgb = intel_dp->dsc_dpcd[DP_DSC_DEC_COLOR_FORMAT_CAP - DP_DSC_SUPPORT] &
2108                 DP_DSC_RGB;
2109
2110         line_buf_depth = drm_dp_dsc_sink_line_buf_depth(intel_dp->dsc_dpcd);
2111         if (!line_buf_depth) {
2112                 drm_dbg_kms(&i915->drm,
2113                             "DSC Sink Line Buffer Depth invalid\n");
2114                 return -EINVAL;
2115         }
2116
2117         if (vdsc_cfg->dsc_version_minor == 2)
2118                 vdsc_cfg->line_buf_depth = (line_buf_depth == DSC_1_2_MAX_LINEBUF_DEPTH_BITS) ?
2119                         DSC_1_2_MAX_LINEBUF_DEPTH_VAL : line_buf_depth;
2120         else
2121                 vdsc_cfg->line_buf_depth = (line_buf_depth > DSC_1_1_MAX_LINEBUF_DEPTH_BITS) ?
2122                         DSC_1_1_MAX_LINEBUF_DEPTH_BITS : line_buf_depth;
2123
2124         vdsc_cfg->block_pred_enable =
2125                 intel_dp->dsc_dpcd[DP_DSC_BLK_PREDICTION_SUPPORT - DP_DSC_SUPPORT] &
2126                 DP_DSC_BLK_PREDICTION_IS_SUPPORTED;
2127
2128         return drm_dsc_compute_rc_parameters(vdsc_cfg);
2129 }
2130
2131 static int intel_dp_dsc_compute_config(struct intel_dp *intel_dp,
2132                                        struct intel_crtc_state *pipe_config,
2133                                        struct drm_connector_state *conn_state,
2134                                        struct link_config_limits *limits)
2135 {
2136         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
2137         struct drm_i915_private *dev_priv = to_i915(dig_port->base.base.dev);
2138         const struct drm_display_mode *adjusted_mode =
2139                 &pipe_config->hw.adjusted_mode;
2140         u8 dsc_max_bpc;
2141         int pipe_bpp;
2142         int ret;
2143
2144         pipe_config->fec_enable = !intel_dp_is_edp(intel_dp) &&
2145                 intel_dp_supports_fec(intel_dp, pipe_config);
2146
2147         if (!intel_dp_supports_dsc(intel_dp, pipe_config))
2148                 return -EINVAL;
2149
2150         /* Max DSC Input BPC for ICL is 10 and for TGL+ is 12 */
2151         if (INTEL_GEN(dev_priv) >= 12)
2152                 dsc_max_bpc = min_t(u8, 12, conn_state->max_requested_bpc);
2153         else
2154                 dsc_max_bpc = min_t(u8, 10,
2155                                     conn_state->max_requested_bpc);
2156
2157         pipe_bpp = intel_dp_dsc_compute_bpp(intel_dp, dsc_max_bpc);
2158
2159         /* Min Input BPC for ICL+ is 8 */
2160         if (pipe_bpp < 8 * 3) {
2161                 drm_dbg_kms(&dev_priv->drm,
2162                             "No DSC support for less than 8bpc\n");
2163                 return -EINVAL;
2164         }
2165
2166         /*
2167          * For now enable DSC for max bpp, max link rate, max lane count.
2168          * Optimize this later for the minimum possible link rate/lane count
2169          * with DSC enabled for the requested mode.
2170          */
2171         pipe_config->pipe_bpp = pipe_bpp;
2172         pipe_config->port_clock = intel_dp->common_rates[limits->max_clock];
2173         pipe_config->lane_count = limits->max_lane_count;
2174
2175         if (intel_dp_is_edp(intel_dp)) {
2176                 pipe_config->dsc.compressed_bpp =
2177                         min_t(u16, drm_edp_dsc_sink_output_bpp(intel_dp->dsc_dpcd) >> 4,
2178                               pipe_config->pipe_bpp);
2179                 pipe_config->dsc.slice_count =
2180                         drm_dp_dsc_sink_max_slice_count(intel_dp->dsc_dpcd,
2181                                                         true);
2182         } else {
2183                 u16 dsc_max_output_bpp;
2184                 u8 dsc_dp_slice_count;
2185
2186                 dsc_max_output_bpp =
2187                         intel_dp_dsc_get_output_bpp(dev_priv,
2188                                                     pipe_config->port_clock,
2189                                                     pipe_config->lane_count,
2190                                                     adjusted_mode->crtc_clock,
2191                                                     adjusted_mode->crtc_hdisplay);
2192                 dsc_dp_slice_count =
2193                         intel_dp_dsc_get_slice_count(intel_dp,
2194                                                      adjusted_mode->crtc_clock,
2195                                                      adjusted_mode->crtc_hdisplay);
2196                 if (!dsc_max_output_bpp || !dsc_dp_slice_count) {
2197                         drm_dbg_kms(&dev_priv->drm,
2198                                     "Compressed BPP/Slice Count not supported\n");
2199                         return -EINVAL;
2200                 }
2201                 pipe_config->dsc.compressed_bpp = min_t(u16,
2202                                                                dsc_max_output_bpp >> 4,
2203                                                                pipe_config->pipe_bpp);
2204                 pipe_config->dsc.slice_count = dsc_dp_slice_count;
2205         }
2206         /*
2207          * VDSC engine operates at 1 Pixel per clock, so if peak pixel rate
2208          * is greater than the maximum Cdclock and if slice count is even
2209          * then we need to use 2 VDSC instances.
2210          */
2211         if (adjusted_mode->crtc_clock > dev_priv->max_cdclk_freq) {
2212                 if (pipe_config->dsc.slice_count > 1) {
2213                         pipe_config->dsc.dsc_split = true;
2214                 } else {
2215                         drm_dbg_kms(&dev_priv->drm,
2216                                     "Cannot split stream to use 2 VDSC instances\n");
2217                         return -EINVAL;
2218                 }
2219         }
2220
2221         ret = intel_dp_dsc_compute_params(&dig_port->base, pipe_config);
2222         if (ret < 0) {
2223                 drm_dbg_kms(&dev_priv->drm,
2224                             "Cannot compute valid DSC parameters for Input Bpp = %d "
2225                             "Compressed BPP = %d\n",
2226                             pipe_config->pipe_bpp,
2227                             pipe_config->dsc.compressed_bpp);
2228                 return ret;
2229         }
2230
2231         pipe_config->dsc.compression_enable = true;
2232         drm_dbg_kms(&dev_priv->drm, "DP DSC computed with Input Bpp = %d "
2233                     "Compressed Bpp = %d Slice Count = %d\n",
2234                     pipe_config->pipe_bpp,
2235                     pipe_config->dsc.compressed_bpp,
2236                     pipe_config->dsc.slice_count);
2237
2238         return 0;
2239 }
2240
2241 int intel_dp_min_bpp(const struct intel_crtc_state *crtc_state)
2242 {
2243         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_RGB)
2244                 return 6 * 3;
2245         else
2246                 return 8 * 3;
2247 }
2248
2249 static int
2250 intel_dp_compute_link_config(struct intel_encoder *encoder,
2251                              struct intel_crtc_state *pipe_config,
2252                              struct drm_connector_state *conn_state)
2253 {
2254         struct drm_i915_private *i915 = to_i915(encoder->base.dev);
2255         const struct drm_display_mode *adjusted_mode =
2256                 &pipe_config->hw.adjusted_mode;
2257         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
2258         struct link_config_limits limits;
2259         int common_len;
2260         int ret;
2261
2262         common_len = intel_dp_common_len_rate_limit(intel_dp,
2263                                                     intel_dp->max_link_rate);
2264
2265         /* No common link rates between source and sink */
2266         drm_WARN_ON(encoder->base.dev, common_len <= 0);
2267
2268         limits.min_clock = 0;
2269         limits.max_clock = common_len - 1;
2270
2271         limits.min_lane_count = 1;
2272         limits.max_lane_count = intel_dp_max_lane_count(intel_dp);
2273
2274         limits.min_bpp = intel_dp_min_bpp(pipe_config);
2275         limits.max_bpp = intel_dp_compute_bpp(intel_dp, pipe_config);
2276
2277         if (intel_dp_is_edp(intel_dp)) {
2278                 /*
2279                  * Use the maximum clock and number of lanes the eDP panel
2280                  * advertizes being capable of. The panels are generally
2281                  * designed to support only a single clock and lane
2282                  * configuration, and typically these values correspond to the
2283                  * native resolution of the panel.
2284                  */
2285                 limits.min_lane_count = limits.max_lane_count;
2286                 limits.min_clock = limits.max_clock;
2287         }
2288
2289         intel_dp_adjust_compliance_config(intel_dp, pipe_config, &limits);
2290
2291         drm_dbg_kms(&i915->drm, "DP link computation with max lane count %i "
2292                     "max rate %d max bpp %d pixel clock %iKHz\n",
2293                     limits.max_lane_count,
2294                     intel_dp->common_rates[limits.max_clock],
2295                     limits.max_bpp, adjusted_mode->crtc_clock);
2296
2297         /*
2298          * Optimize for slow and wide. This is the place to add alternative
2299          * optimization policy.
2300          */
2301         ret = intel_dp_compute_link_config_wide(intel_dp, pipe_config, &limits);
2302
2303         /* enable compression if the mode doesn't fit available BW */
2304         drm_dbg_kms(&i915->drm, "Force DSC en = %d\n", intel_dp->force_dsc_en);
2305         if (ret || intel_dp->force_dsc_en) {
2306                 ret = intel_dp_dsc_compute_config(intel_dp, pipe_config,
2307                                                   conn_state, &limits);
2308                 if (ret < 0)
2309                         return ret;
2310         }
2311
2312         if (pipe_config->dsc.compression_enable) {
2313                 drm_dbg_kms(&i915->drm,
2314                             "DP lane count %d clock %d Input bpp %d Compressed bpp %d\n",
2315                             pipe_config->lane_count, pipe_config->port_clock,
2316                             pipe_config->pipe_bpp,
2317                             pipe_config->dsc.compressed_bpp);
2318
2319                 drm_dbg_kms(&i915->drm,
2320                             "DP link rate required %i available %i\n",
2321                             intel_dp_link_required(adjusted_mode->crtc_clock,
2322                                                    pipe_config->dsc.compressed_bpp),
2323                             intel_dp_max_data_rate(pipe_config->port_clock,
2324                                                    pipe_config->lane_count));
2325         } else {
2326                 drm_dbg_kms(&i915->drm, "DP lane count %d clock %d bpp %d\n",
2327                             pipe_config->lane_count, pipe_config->port_clock,
2328                             pipe_config->pipe_bpp);
2329
2330                 drm_dbg_kms(&i915->drm,
2331                             "DP link rate required %i available %i\n",
2332                             intel_dp_link_required(adjusted_mode->crtc_clock,
2333                                                    pipe_config->pipe_bpp),
2334                             intel_dp_max_data_rate(pipe_config->port_clock,
2335                                                    pipe_config->lane_count));
2336         }
2337         return 0;
2338 }
2339
2340 static int
2341 intel_dp_ycbcr420_config(struct intel_dp *intel_dp,
2342                          struct intel_crtc_state *crtc_state,
2343                          const struct drm_connector_state *conn_state)
2344 {
2345         struct drm_connector *connector = conn_state->connector;
2346         const struct drm_display_info *info = &connector->display_info;
2347         const struct drm_display_mode *adjusted_mode =
2348                 &crtc_state->hw.adjusted_mode;
2349
2350         if (!drm_mode_is_420_only(info, adjusted_mode) ||
2351             !intel_dp_get_colorimetry_status(intel_dp) ||
2352             !connector->ycbcr_420_allowed)
2353                 return 0;
2354
2355         crtc_state->output_format = INTEL_OUTPUT_FORMAT_YCBCR420;
2356
2357         return intel_pch_panel_fitting(crtc_state, conn_state);
2358 }
2359
2360 bool intel_dp_limited_color_range(const struct intel_crtc_state *crtc_state,
2361                                   const struct drm_connector_state *conn_state)
2362 {
2363         const struct intel_digital_connector_state *intel_conn_state =
2364                 to_intel_digital_connector_state(conn_state);
2365         const struct drm_display_mode *adjusted_mode =
2366                 &crtc_state->hw.adjusted_mode;
2367
2368         /*
2369          * Our YCbCr output is always limited range.
2370          * crtc_state->limited_color_range only applies to RGB,
2371          * and it must never be set for YCbCr or we risk setting
2372          * some conflicting bits in PIPECONF which will mess up
2373          * the colors on the monitor.
2374          */
2375         if (crtc_state->output_format != INTEL_OUTPUT_FORMAT_RGB)
2376                 return false;
2377
2378         if (intel_conn_state->broadcast_rgb == INTEL_BROADCAST_RGB_AUTO) {
2379                 /*
2380                  * See:
2381                  * CEA-861-E - 5.1 Default Encoding Parameters
2382                  * VESA DisplayPort Ver.1.2a - 5.1.1.1 Video Colorimetry
2383                  */
2384                 return crtc_state->pipe_bpp != 18 &&
2385                         drm_default_rgb_quant_range(adjusted_mode) ==
2386                         HDMI_QUANTIZATION_RANGE_LIMITED;
2387         } else {
2388                 return intel_conn_state->broadcast_rgb ==
2389                         INTEL_BROADCAST_RGB_LIMITED;
2390         }
2391 }
2392
2393 static bool intel_dp_port_has_audio(struct drm_i915_private *dev_priv,
2394                                     enum port port)
2395 {
2396         if (IS_G4X(dev_priv))
2397                 return false;
2398         if (INTEL_GEN(dev_priv) < 12 && port == PORT_A)
2399                 return false;
2400
2401         return true;
2402 }
2403
2404 static void intel_dp_compute_vsc_colorimetry(const struct intel_crtc_state *crtc_state,
2405                                              const struct drm_connector_state *conn_state,
2406                                              struct drm_dp_vsc_sdp *vsc)
2407 {
2408         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
2409         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
2410
2411         /*
2412          * Prepare VSC Header for SU as per DP 1.4 spec, Table 2-118
2413          * VSC SDP supporting 3D stereo, PSR2, and Pixel Encoding/
2414          * Colorimetry Format indication.
2415          */
2416         vsc->revision = 0x5;
2417         vsc->length = 0x13;
2418
2419         /* DP 1.4a spec, Table 2-120 */
2420         switch (crtc_state->output_format) {
2421         case INTEL_OUTPUT_FORMAT_YCBCR444:
2422                 vsc->pixelformat = DP_PIXELFORMAT_YUV444;
2423                 break;
2424         case INTEL_OUTPUT_FORMAT_YCBCR420:
2425                 vsc->pixelformat = DP_PIXELFORMAT_YUV420;
2426                 break;
2427         case INTEL_OUTPUT_FORMAT_RGB:
2428         default:
2429                 vsc->pixelformat = DP_PIXELFORMAT_RGB;
2430         }
2431
2432         switch (conn_state->colorspace) {
2433         case DRM_MODE_COLORIMETRY_BT709_YCC:
2434                 vsc->colorimetry = DP_COLORIMETRY_BT709_YCC;
2435                 break;
2436         case DRM_MODE_COLORIMETRY_XVYCC_601:
2437                 vsc->colorimetry = DP_COLORIMETRY_XVYCC_601;
2438                 break;
2439         case DRM_MODE_COLORIMETRY_XVYCC_709:
2440                 vsc->colorimetry = DP_COLORIMETRY_XVYCC_709;
2441                 break;
2442         case DRM_MODE_COLORIMETRY_SYCC_601:
2443                 vsc->colorimetry = DP_COLORIMETRY_SYCC_601;
2444                 break;
2445         case DRM_MODE_COLORIMETRY_OPYCC_601:
2446                 vsc->colorimetry = DP_COLORIMETRY_OPYCC_601;
2447                 break;
2448         case DRM_MODE_COLORIMETRY_BT2020_CYCC:
2449                 vsc->colorimetry = DP_COLORIMETRY_BT2020_CYCC;
2450                 break;
2451         case DRM_MODE_COLORIMETRY_BT2020_RGB:
2452                 vsc->colorimetry = DP_COLORIMETRY_BT2020_RGB;
2453                 break;
2454         case DRM_MODE_COLORIMETRY_BT2020_YCC:
2455                 vsc->colorimetry = DP_COLORIMETRY_BT2020_YCC;
2456                 break;
2457         case DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65:
2458         case DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER:
2459                 vsc->colorimetry = DP_COLORIMETRY_DCI_P3_RGB;
2460                 break;
2461         default:
2462                 /*
2463                  * RGB->YCBCR color conversion uses the BT.709
2464                  * color space.
2465                  */
2466                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
2467                         vsc->colorimetry = DP_COLORIMETRY_BT709_YCC;
2468                 else
2469                         vsc->colorimetry = DP_COLORIMETRY_DEFAULT;
2470                 break;
2471         }
2472
2473         vsc->bpc = crtc_state->pipe_bpp / 3;
2474
2475         /* only RGB pixelformat supports 6 bpc */
2476         drm_WARN_ON(&dev_priv->drm,
2477                     vsc->bpc == 6 && vsc->pixelformat != DP_PIXELFORMAT_RGB);
2478
2479         /* all YCbCr are always limited range */
2480         vsc->dynamic_range = DP_DYNAMIC_RANGE_CTA;
2481         vsc->content_type = DP_CONTENT_TYPE_NOT_DEFINED;
2482 }
2483
2484 static void intel_dp_compute_vsc_sdp(struct intel_dp *intel_dp,
2485                                      struct intel_crtc_state *crtc_state,
2486                                      const struct drm_connector_state *conn_state)
2487 {
2488         struct drm_dp_vsc_sdp *vsc = &crtc_state->infoframes.vsc;
2489
2490         /* When PSR is enabled, VSC SDP is handled by PSR routine */
2491         if (intel_psr_enabled(intel_dp))
2492                 return;
2493
2494         if (!intel_dp_needs_vsc_sdp(crtc_state, conn_state))
2495                 return;
2496
2497         crtc_state->infoframes.enable |= intel_hdmi_infoframe_enable(DP_SDP_VSC);
2498         vsc->sdp_type = DP_SDP_VSC;
2499         intel_dp_compute_vsc_colorimetry(crtc_state, conn_state,
2500                                          &crtc_state->infoframes.vsc);
2501 }
2502
2503 static void
2504 intel_dp_compute_hdr_metadata_infoframe_sdp(struct intel_dp *intel_dp,
2505                                             struct intel_crtc_state *crtc_state,
2506                                             const struct drm_connector_state *conn_state)
2507 {
2508         int ret;
2509         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
2510         struct hdmi_drm_infoframe *drm_infoframe = &crtc_state->infoframes.drm.drm;
2511
2512         if (!conn_state->hdr_output_metadata)
2513                 return;
2514
2515         ret = drm_hdmi_infoframe_set_hdr_metadata(drm_infoframe, conn_state);
2516
2517         if (ret) {
2518                 drm_dbg_kms(&dev_priv->drm, "couldn't set HDR metadata in infoframe\n");
2519                 return;
2520         }
2521
2522         crtc_state->infoframes.enable |=
2523                 intel_hdmi_infoframe_enable(HDMI_PACKET_TYPE_GAMUT_METADATA);
2524 }
2525
2526 int
2527 intel_dp_compute_config(struct intel_encoder *encoder,
2528                         struct intel_crtc_state *pipe_config,
2529                         struct drm_connector_state *conn_state)
2530 {
2531         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
2532         struct drm_display_mode *adjusted_mode = &pipe_config->hw.adjusted_mode;
2533         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
2534         struct intel_lspcon *lspcon = enc_to_intel_lspcon(encoder);
2535         enum port port = encoder->port;
2536         struct intel_connector *intel_connector = intel_dp->attached_connector;
2537         struct intel_digital_connector_state *intel_conn_state =
2538                 to_intel_digital_connector_state(conn_state);
2539         bool constant_n = drm_dp_has_quirk(&intel_dp->desc, 0,
2540                                            DP_DPCD_QUIRK_CONSTANT_N);
2541         int ret = 0, output_bpp;
2542
2543         if (HAS_PCH_SPLIT(dev_priv) && !HAS_DDI(dev_priv) && port != PORT_A)
2544                 pipe_config->has_pch_encoder = true;
2545
2546         pipe_config->output_format = INTEL_OUTPUT_FORMAT_RGB;
2547
2548         if (lspcon->active)
2549                 lspcon_ycbcr420_config(&intel_connector->base, pipe_config);
2550         else
2551                 ret = intel_dp_ycbcr420_config(intel_dp, pipe_config,
2552                                                conn_state);
2553         if (ret)
2554                 return ret;
2555
2556         pipe_config->has_drrs = false;
2557         if (!intel_dp_port_has_audio(dev_priv, port))
2558                 pipe_config->has_audio = false;
2559         else if (intel_conn_state->force_audio == HDMI_AUDIO_AUTO)
2560                 pipe_config->has_audio = intel_dp->has_audio;
2561         else
2562                 pipe_config->has_audio = intel_conn_state->force_audio == HDMI_AUDIO_ON;
2563
2564         if (intel_dp_is_edp(intel_dp) && intel_connector->panel.fixed_mode) {
2565                 intel_fixed_panel_mode(intel_connector->panel.fixed_mode,
2566                                        adjusted_mode);
2567
2568                 if (HAS_GMCH(dev_priv))
2569                         ret = intel_gmch_panel_fitting(pipe_config, conn_state);
2570                 else
2571                         ret = intel_pch_panel_fitting(pipe_config, conn_state);
2572                 if (ret)
2573                         return ret;
2574         }
2575
2576         if (adjusted_mode->flags & DRM_MODE_FLAG_DBLSCAN)
2577                 return -EINVAL;
2578
2579         if (HAS_GMCH(dev_priv) &&
2580             adjusted_mode->flags & DRM_MODE_FLAG_INTERLACE)
2581                 return -EINVAL;
2582
2583         if (adjusted_mode->flags & DRM_MODE_FLAG_DBLCLK)
2584                 return -EINVAL;
2585
2586         if (intel_dp_hdisplay_bad(dev_priv, adjusted_mode->crtc_hdisplay))
2587                 return -EINVAL;
2588
2589         ret = intel_dp_compute_link_config(encoder, pipe_config, conn_state);
2590         if (ret < 0)
2591                 return ret;
2592
2593         pipe_config->limited_color_range =
2594                 intel_dp_limited_color_range(pipe_config, conn_state);
2595
2596         if (pipe_config->dsc.compression_enable)
2597                 output_bpp = pipe_config->dsc.compressed_bpp;
2598         else
2599                 output_bpp = intel_dp_output_bpp(pipe_config, pipe_config->pipe_bpp);
2600
2601         intel_link_compute_m_n(output_bpp,
2602                                pipe_config->lane_count,
2603                                adjusted_mode->crtc_clock,
2604                                pipe_config->port_clock,
2605                                &pipe_config->dp_m_n,
2606                                constant_n, pipe_config->fec_enable);
2607
2608         if (intel_connector->panel.downclock_mode != NULL &&
2609                 dev_priv->drrs.type == SEAMLESS_DRRS_SUPPORT) {
2610                         pipe_config->has_drrs = true;
2611                         intel_link_compute_m_n(output_bpp,
2612                                                pipe_config->lane_count,
2613                                                intel_connector->panel.downclock_mode->clock,
2614                                                pipe_config->port_clock,
2615                                                &pipe_config->dp_m2_n2,
2616                                                constant_n, pipe_config->fec_enable);
2617         }
2618
2619         if (!HAS_DDI(dev_priv))
2620                 intel_dp_set_clock(encoder, pipe_config);
2621
2622         intel_psr_compute_config(intel_dp, pipe_config);
2623         intel_dp_compute_vsc_sdp(intel_dp, pipe_config, conn_state);
2624         intel_dp_compute_hdr_metadata_infoframe_sdp(intel_dp, pipe_config, conn_state);
2625
2626         return 0;
2627 }
2628
2629 void intel_dp_set_link_params(struct intel_dp *intel_dp,
2630                               int link_rate, u8 lane_count,
2631                               bool link_mst)
2632 {
2633         intel_dp->link_trained = false;
2634         intel_dp->link_rate = link_rate;
2635         intel_dp->lane_count = lane_count;
2636         intel_dp->link_mst = link_mst;
2637 }
2638
2639 static void intel_dp_prepare(struct intel_encoder *encoder,
2640                              const struct intel_crtc_state *pipe_config)
2641 {
2642         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
2643         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
2644         enum port port = encoder->port;
2645         struct intel_crtc *crtc = to_intel_crtc(pipe_config->uapi.crtc);
2646         const struct drm_display_mode *adjusted_mode = &pipe_config->hw.adjusted_mode;
2647
2648         intel_dp_set_link_params(intel_dp, pipe_config->port_clock,
2649                                  pipe_config->lane_count,
2650                                  intel_crtc_has_type(pipe_config,
2651                                                      INTEL_OUTPUT_DP_MST));
2652
2653         /*
2654          * There are four kinds of DP registers:
2655          *
2656          *      IBX PCH
2657          *      SNB CPU
2658          *      IVB CPU
2659          *      CPT PCH
2660          *
2661          * IBX PCH and CPU are the same for almost everything,
2662          * except that the CPU DP PLL is configured in this
2663          * register
2664          *
2665          * CPT PCH is quite different, having many bits moved
2666          * to the TRANS_DP_CTL register instead. That
2667          * configuration happens (oddly) in ilk_pch_enable
2668          */
2669
2670         /* Preserve the BIOS-computed detected bit. This is
2671          * supposed to be read-only.
2672          */
2673         intel_dp->DP = intel_de_read(dev_priv, intel_dp->output_reg) & DP_DETECTED;
2674
2675         /* Handle DP bits in common between all three register formats */
2676         intel_dp->DP |= DP_VOLTAGE_0_4 | DP_PRE_EMPHASIS_0;
2677         intel_dp->DP |= DP_PORT_WIDTH(pipe_config->lane_count);
2678
2679         /* Split out the IBX/CPU vs CPT settings */
2680
2681         if (IS_IVYBRIDGE(dev_priv) && port == PORT_A) {
2682                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
2683                         intel_dp->DP |= DP_SYNC_HS_HIGH;
2684                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
2685                         intel_dp->DP |= DP_SYNC_VS_HIGH;
2686                 intel_dp->DP |= DP_LINK_TRAIN_OFF_CPT;
2687
2688                 if (drm_dp_enhanced_frame_cap(intel_dp->dpcd))
2689                         intel_dp->DP |= DP_ENHANCED_FRAMING;
2690
2691                 intel_dp->DP |= DP_PIPE_SEL_IVB(crtc->pipe);
2692         } else if (HAS_PCH_CPT(dev_priv) && port != PORT_A) {
2693                 u32 trans_dp;
2694
2695                 intel_dp->DP |= DP_LINK_TRAIN_OFF_CPT;
2696
2697                 trans_dp = intel_de_read(dev_priv, TRANS_DP_CTL(crtc->pipe));
2698                 if (drm_dp_enhanced_frame_cap(intel_dp->dpcd))
2699                         trans_dp |= TRANS_DP_ENH_FRAMING;
2700                 else
2701                         trans_dp &= ~TRANS_DP_ENH_FRAMING;
2702                 intel_de_write(dev_priv, TRANS_DP_CTL(crtc->pipe), trans_dp);
2703         } else {
2704                 if (IS_G4X(dev_priv) && pipe_config->limited_color_range)
2705                         intel_dp->DP |= DP_COLOR_RANGE_16_235;
2706
2707                 if (adjusted_mode->flags & DRM_MODE_FLAG_PHSYNC)
2708                         intel_dp->DP |= DP_SYNC_HS_HIGH;
2709                 if (adjusted_mode->flags & DRM_MODE_FLAG_PVSYNC)
2710                         intel_dp->DP |= DP_SYNC_VS_HIGH;
2711                 intel_dp->DP |= DP_LINK_TRAIN_OFF;
2712
2713                 if (drm_dp_enhanced_frame_cap(intel_dp->dpcd))
2714                         intel_dp->DP |= DP_ENHANCED_FRAMING;
2715
2716                 if (IS_CHERRYVIEW(dev_priv))
2717                         intel_dp->DP |= DP_PIPE_SEL_CHV(crtc->pipe);
2718                 else
2719                         intel_dp->DP |= DP_PIPE_SEL(crtc->pipe);
2720         }
2721 }
2722
2723 #define IDLE_ON_MASK            (PP_ON | PP_SEQUENCE_MASK | 0                     | PP_SEQUENCE_STATE_MASK)
2724 #define IDLE_ON_VALUE           (PP_ON | PP_SEQUENCE_NONE | 0                     | PP_SEQUENCE_STATE_ON_IDLE)
2725
2726 #define IDLE_OFF_MASK           (PP_ON | PP_SEQUENCE_MASK | 0                     | 0)
2727 #define IDLE_OFF_VALUE          (0     | PP_SEQUENCE_NONE | 0                     | 0)
2728
2729 #define IDLE_CYCLE_MASK         (PP_ON | PP_SEQUENCE_MASK | PP_CYCLE_DELAY_ACTIVE | PP_SEQUENCE_STATE_MASK)
2730 #define IDLE_CYCLE_VALUE        (0     | PP_SEQUENCE_NONE | 0                     | PP_SEQUENCE_STATE_OFF_IDLE)
2731
2732 static void intel_pps_verify_state(struct intel_dp *intel_dp);
2733
2734 static void wait_panel_status(struct intel_dp *intel_dp,
2735                                        u32 mask,
2736                                        u32 value)
2737 {
2738         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
2739         i915_reg_t pp_stat_reg, pp_ctrl_reg;
2740
2741         lockdep_assert_held(&dev_priv->pps_mutex);
2742
2743         intel_pps_verify_state(intel_dp);
2744
2745         pp_stat_reg = _pp_stat_reg(intel_dp);
2746         pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
2747
2748         drm_dbg_kms(&dev_priv->drm,
2749                     "mask %08x value %08x status %08x control %08x\n",
2750                     mask, value,
2751                     intel_de_read(dev_priv, pp_stat_reg),
2752                     intel_de_read(dev_priv, pp_ctrl_reg));
2753
2754         if (intel_de_wait_for_register(dev_priv, pp_stat_reg,
2755                                        mask, value, 5000))
2756                 drm_err(&dev_priv->drm,
2757                         "Panel status timeout: status %08x control %08x\n",
2758                         intel_de_read(dev_priv, pp_stat_reg),
2759                         intel_de_read(dev_priv, pp_ctrl_reg));
2760
2761         drm_dbg_kms(&dev_priv->drm, "Wait complete\n");
2762 }
2763
2764 static void wait_panel_on(struct intel_dp *intel_dp)
2765 {
2766         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
2767
2768         drm_dbg_kms(&i915->drm, "Wait for panel power on\n");
2769         wait_panel_status(intel_dp, IDLE_ON_MASK, IDLE_ON_VALUE);
2770 }
2771
2772 static void wait_panel_off(struct intel_dp *intel_dp)
2773 {
2774         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
2775
2776         drm_dbg_kms(&i915->drm, "Wait for panel power off time\n");
2777         wait_panel_status(intel_dp, IDLE_OFF_MASK, IDLE_OFF_VALUE);
2778 }
2779
2780 static void wait_panel_power_cycle(struct intel_dp *intel_dp)
2781 {
2782         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
2783         ktime_t panel_power_on_time;
2784         s64 panel_power_off_duration;
2785
2786         drm_dbg_kms(&i915->drm, "Wait for panel power cycle\n");
2787
2788         /* take the difference of currrent time and panel power off time
2789          * and then make panel wait for t11_t12 if needed. */
2790         panel_power_on_time = ktime_get_boottime();
2791         panel_power_off_duration = ktime_ms_delta(panel_power_on_time, intel_dp->panel_power_off_time);
2792
2793         /* When we disable the VDD override bit last we have to do the manual
2794          * wait. */
2795         if (panel_power_off_duration < (s64)intel_dp->panel_power_cycle_delay)
2796                 wait_remaining_ms_from_jiffies(jiffies,
2797                                        intel_dp->panel_power_cycle_delay - panel_power_off_duration);
2798
2799         wait_panel_status(intel_dp, IDLE_CYCLE_MASK, IDLE_CYCLE_VALUE);
2800 }
2801
2802 static void wait_backlight_on(struct intel_dp *intel_dp)
2803 {
2804         wait_remaining_ms_from_jiffies(intel_dp->last_power_on,
2805                                        intel_dp->backlight_on_delay);
2806 }
2807
2808 static void edp_wait_backlight_off(struct intel_dp *intel_dp)
2809 {
2810         wait_remaining_ms_from_jiffies(intel_dp->last_backlight_off,
2811                                        intel_dp->backlight_off_delay);
2812 }
2813
2814 /* Read the current pp_control value, unlocking the register if it
2815  * is locked
2816  */
2817
2818 static  u32 ilk_get_pp_control(struct intel_dp *intel_dp)
2819 {
2820         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
2821         u32 control;
2822
2823         lockdep_assert_held(&dev_priv->pps_mutex);
2824
2825         control = intel_de_read(dev_priv, _pp_ctrl_reg(intel_dp));
2826         if (drm_WARN_ON(&dev_priv->drm, !HAS_DDI(dev_priv) &&
2827                         (control & PANEL_UNLOCK_MASK) != PANEL_UNLOCK_REGS)) {
2828                 control &= ~PANEL_UNLOCK_MASK;
2829                 control |= PANEL_UNLOCK_REGS;
2830         }
2831         return control;
2832 }
2833
2834 /*
2835  * Must be paired with edp_panel_vdd_off().
2836  * Must hold pps_mutex around the whole on/off sequence.
2837  * Can be nested with intel_edp_panel_vdd_{on,off}() calls.
2838  */
2839 static bool edp_panel_vdd_on(struct intel_dp *intel_dp)
2840 {
2841         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
2842         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
2843         u32 pp;
2844         i915_reg_t pp_stat_reg, pp_ctrl_reg;
2845         bool need_to_disable = !intel_dp->want_panel_vdd;
2846
2847         lockdep_assert_held(&dev_priv->pps_mutex);
2848
2849         if (!intel_dp_is_edp(intel_dp))
2850                 return false;
2851
2852         cancel_delayed_work(&intel_dp->panel_vdd_work);
2853         intel_dp->want_panel_vdd = true;
2854
2855         if (edp_have_panel_vdd(intel_dp))
2856                 return need_to_disable;
2857
2858         intel_display_power_get(dev_priv,
2859                                 intel_aux_power_domain(intel_dig_port));
2860
2861         drm_dbg_kms(&dev_priv->drm, "Turning [ENCODER:%d:%s] VDD on\n",
2862                     intel_dig_port->base.base.base.id,
2863                     intel_dig_port->base.base.name);
2864
2865         if (!edp_have_panel_power(intel_dp))
2866                 wait_panel_power_cycle(intel_dp);
2867
2868         pp = ilk_get_pp_control(intel_dp);
2869         pp |= EDP_FORCE_VDD;
2870
2871         pp_stat_reg = _pp_stat_reg(intel_dp);
2872         pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
2873
2874         intel_de_write(dev_priv, pp_ctrl_reg, pp);
2875         intel_de_posting_read(dev_priv, pp_ctrl_reg);
2876         drm_dbg_kms(&dev_priv->drm, "PP_STATUS: 0x%08x PP_CONTROL: 0x%08x\n",
2877                     intel_de_read(dev_priv, pp_stat_reg),
2878                     intel_de_read(dev_priv, pp_ctrl_reg));
2879         /*
2880          * If the panel wasn't on, delay before accessing aux channel
2881          */
2882         if (!edp_have_panel_power(intel_dp)) {
2883                 drm_dbg_kms(&dev_priv->drm,
2884                             "[ENCODER:%d:%s] panel power wasn't enabled\n",
2885                             intel_dig_port->base.base.base.id,
2886                             intel_dig_port->base.base.name);
2887                 msleep(intel_dp->panel_power_up_delay);
2888         }
2889
2890         return need_to_disable;
2891 }
2892
2893 /*
2894  * Must be paired with intel_edp_panel_vdd_off() or
2895  * intel_edp_panel_off().
2896  * Nested calls to these functions are not allowed since
2897  * we drop the lock. Caller must use some higher level
2898  * locking to prevent nested calls from other threads.
2899  */
2900 void intel_edp_panel_vdd_on(struct intel_dp *intel_dp)
2901 {
2902         intel_wakeref_t wakeref;
2903         bool vdd;
2904
2905         if (!intel_dp_is_edp(intel_dp))
2906                 return;
2907
2908         vdd = false;
2909         with_pps_lock(intel_dp, wakeref)
2910                 vdd = edp_panel_vdd_on(intel_dp);
2911         I915_STATE_WARN(!vdd, "[ENCODER:%d:%s] VDD already requested on\n",
2912                         dp_to_dig_port(intel_dp)->base.base.base.id,
2913                         dp_to_dig_port(intel_dp)->base.base.name);
2914 }
2915
2916 static void edp_panel_vdd_off_sync(struct intel_dp *intel_dp)
2917 {
2918         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
2919         struct intel_digital_port *intel_dig_port =
2920                 dp_to_dig_port(intel_dp);
2921         u32 pp;
2922         i915_reg_t pp_stat_reg, pp_ctrl_reg;
2923
2924         lockdep_assert_held(&dev_priv->pps_mutex);
2925
2926         drm_WARN_ON(&dev_priv->drm, intel_dp->want_panel_vdd);
2927
2928         if (!edp_have_panel_vdd(intel_dp))
2929                 return;
2930
2931         drm_dbg_kms(&dev_priv->drm, "Turning [ENCODER:%d:%s] VDD off\n",
2932                     intel_dig_port->base.base.base.id,
2933                     intel_dig_port->base.base.name);
2934
2935         pp = ilk_get_pp_control(intel_dp);
2936         pp &= ~EDP_FORCE_VDD;
2937
2938         pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
2939         pp_stat_reg = _pp_stat_reg(intel_dp);
2940
2941         intel_de_write(dev_priv, pp_ctrl_reg, pp);
2942         intel_de_posting_read(dev_priv, pp_ctrl_reg);
2943
2944         /* Make sure sequencer is idle before allowing subsequent activity */
2945         drm_dbg_kms(&dev_priv->drm, "PP_STATUS: 0x%08x PP_CONTROL: 0x%08x\n",
2946                     intel_de_read(dev_priv, pp_stat_reg),
2947                     intel_de_read(dev_priv, pp_ctrl_reg));
2948
2949         if ((pp & PANEL_POWER_ON) == 0)
2950                 intel_dp->panel_power_off_time = ktime_get_boottime();
2951
2952         intel_display_power_put_unchecked(dev_priv,
2953                                           intel_aux_power_domain(intel_dig_port));
2954 }
2955
2956 static void edp_panel_vdd_work(struct work_struct *__work)
2957 {
2958         struct intel_dp *intel_dp =
2959                 container_of(to_delayed_work(__work),
2960                              struct intel_dp, panel_vdd_work);
2961         intel_wakeref_t wakeref;
2962
2963         with_pps_lock(intel_dp, wakeref) {
2964                 if (!intel_dp->want_panel_vdd)
2965                         edp_panel_vdd_off_sync(intel_dp);
2966         }
2967 }
2968
2969 static void edp_panel_vdd_schedule_off(struct intel_dp *intel_dp)
2970 {
2971         unsigned long delay;
2972
2973         /*
2974          * Queue the timer to fire a long time from now (relative to the power
2975          * down delay) to keep the panel power up across a sequence of
2976          * operations.
2977          */
2978         delay = msecs_to_jiffies(intel_dp->panel_power_cycle_delay * 5);
2979         schedule_delayed_work(&intel_dp->panel_vdd_work, delay);
2980 }
2981
2982 /*
2983  * Must be paired with edp_panel_vdd_on().
2984  * Must hold pps_mutex around the whole on/off sequence.
2985  * Can be nested with intel_edp_panel_vdd_{on,off}() calls.
2986  */
2987 static void edp_panel_vdd_off(struct intel_dp *intel_dp, bool sync)
2988 {
2989         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
2990
2991         lockdep_assert_held(&dev_priv->pps_mutex);
2992
2993         if (!intel_dp_is_edp(intel_dp))
2994                 return;
2995
2996         I915_STATE_WARN(!intel_dp->want_panel_vdd, "[ENCODER:%d:%s] VDD not forced on",
2997                         dp_to_dig_port(intel_dp)->base.base.base.id,
2998                         dp_to_dig_port(intel_dp)->base.base.name);
2999
3000         intel_dp->want_panel_vdd = false;
3001
3002         if (sync)
3003                 edp_panel_vdd_off_sync(intel_dp);
3004         else
3005                 edp_panel_vdd_schedule_off(intel_dp);
3006 }
3007
3008 static void edp_panel_on(struct intel_dp *intel_dp)
3009 {
3010         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3011         u32 pp;
3012         i915_reg_t pp_ctrl_reg;
3013
3014         lockdep_assert_held(&dev_priv->pps_mutex);
3015
3016         if (!intel_dp_is_edp(intel_dp))
3017                 return;
3018
3019         drm_dbg_kms(&dev_priv->drm, "Turn [ENCODER:%d:%s] panel power on\n",
3020                     dp_to_dig_port(intel_dp)->base.base.base.id,
3021                     dp_to_dig_port(intel_dp)->base.base.name);
3022
3023         if (drm_WARN(&dev_priv->drm, edp_have_panel_power(intel_dp),
3024                      "[ENCODER:%d:%s] panel power already on\n",
3025                      dp_to_dig_port(intel_dp)->base.base.base.id,
3026                      dp_to_dig_port(intel_dp)->base.base.name))
3027                 return;
3028
3029         wait_panel_power_cycle(intel_dp);
3030
3031         pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
3032         pp = ilk_get_pp_control(intel_dp);
3033         if (IS_GEN(dev_priv, 5)) {
3034                 /* ILK workaround: disable reset around power sequence */
3035                 pp &= ~PANEL_POWER_RESET;
3036                 intel_de_write(dev_priv, pp_ctrl_reg, pp);
3037                 intel_de_posting_read(dev_priv, pp_ctrl_reg);
3038         }
3039
3040         pp |= PANEL_POWER_ON;
3041         if (!IS_GEN(dev_priv, 5))
3042                 pp |= PANEL_POWER_RESET;
3043
3044         intel_de_write(dev_priv, pp_ctrl_reg, pp);
3045         intel_de_posting_read(dev_priv, pp_ctrl_reg);
3046
3047         wait_panel_on(intel_dp);
3048         intel_dp->last_power_on = jiffies;
3049
3050         if (IS_GEN(dev_priv, 5)) {
3051                 pp |= PANEL_POWER_RESET; /* restore panel reset bit */
3052                 intel_de_write(dev_priv, pp_ctrl_reg, pp);
3053                 intel_de_posting_read(dev_priv, pp_ctrl_reg);
3054         }
3055 }
3056
3057 void intel_edp_panel_on(struct intel_dp *intel_dp)
3058 {
3059         intel_wakeref_t wakeref;
3060
3061         if (!intel_dp_is_edp(intel_dp))
3062                 return;
3063
3064         with_pps_lock(intel_dp, wakeref)
3065                 edp_panel_on(intel_dp);
3066 }
3067
3068
3069 static void edp_panel_off(struct intel_dp *intel_dp)
3070 {
3071         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3072         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
3073         u32 pp;
3074         i915_reg_t pp_ctrl_reg;
3075
3076         lockdep_assert_held(&dev_priv->pps_mutex);
3077
3078         if (!intel_dp_is_edp(intel_dp))
3079                 return;
3080
3081         drm_dbg_kms(&dev_priv->drm, "Turn [ENCODER:%d:%s] panel power off\n",
3082                     dig_port->base.base.base.id, dig_port->base.base.name);
3083
3084         drm_WARN(&dev_priv->drm, !intel_dp->want_panel_vdd,
3085                  "Need [ENCODER:%d:%s] VDD to turn off panel\n",
3086                  dig_port->base.base.base.id, dig_port->base.base.name);
3087
3088         pp = ilk_get_pp_control(intel_dp);
3089         /* We need to switch off panel power _and_ force vdd, for otherwise some
3090          * panels get very unhappy and cease to work. */
3091         pp &= ~(PANEL_POWER_ON | PANEL_POWER_RESET | EDP_FORCE_VDD |
3092                 EDP_BLC_ENABLE);
3093
3094         pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
3095
3096         intel_dp->want_panel_vdd = false;
3097
3098         intel_de_write(dev_priv, pp_ctrl_reg, pp);
3099         intel_de_posting_read(dev_priv, pp_ctrl_reg);
3100
3101         wait_panel_off(intel_dp);
3102         intel_dp->panel_power_off_time = ktime_get_boottime();
3103
3104         /* We got a reference when we enabled the VDD. */
3105         intel_display_power_put_unchecked(dev_priv, intel_aux_power_domain(dig_port));
3106 }
3107
3108 void intel_edp_panel_off(struct intel_dp *intel_dp)
3109 {
3110         intel_wakeref_t wakeref;
3111
3112         if (!intel_dp_is_edp(intel_dp))
3113                 return;
3114
3115         with_pps_lock(intel_dp, wakeref)
3116                 edp_panel_off(intel_dp);
3117 }
3118
3119 /* Enable backlight in the panel power control. */
3120 static void _intel_edp_backlight_on(struct intel_dp *intel_dp)
3121 {
3122         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3123         intel_wakeref_t wakeref;
3124
3125         /*
3126          * If we enable the backlight right away following a panel power
3127          * on, we may see slight flicker as the panel syncs with the eDP
3128          * link.  So delay a bit to make sure the image is solid before
3129          * allowing it to appear.
3130          */
3131         wait_backlight_on(intel_dp);
3132
3133         with_pps_lock(intel_dp, wakeref) {
3134                 i915_reg_t pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
3135                 u32 pp;
3136
3137                 pp = ilk_get_pp_control(intel_dp);
3138                 pp |= EDP_BLC_ENABLE;
3139
3140                 intel_de_write(dev_priv, pp_ctrl_reg, pp);
3141                 intel_de_posting_read(dev_priv, pp_ctrl_reg);
3142         }
3143 }
3144
3145 /* Enable backlight PWM and backlight PP control. */
3146 void intel_edp_backlight_on(const struct intel_crtc_state *crtc_state,
3147                             const struct drm_connector_state *conn_state)
3148 {
3149         struct intel_dp *intel_dp = enc_to_intel_dp(to_intel_encoder(conn_state->best_encoder));
3150         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
3151
3152         if (!intel_dp_is_edp(intel_dp))
3153                 return;
3154
3155         drm_dbg_kms(&i915->drm, "\n");
3156
3157         intel_panel_enable_backlight(crtc_state, conn_state);
3158         _intel_edp_backlight_on(intel_dp);
3159 }
3160
3161 /* Disable backlight in the panel power control. */
3162 static void _intel_edp_backlight_off(struct intel_dp *intel_dp)
3163 {
3164         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3165         intel_wakeref_t wakeref;
3166
3167         if (!intel_dp_is_edp(intel_dp))
3168                 return;
3169
3170         with_pps_lock(intel_dp, wakeref) {
3171                 i915_reg_t pp_ctrl_reg = _pp_ctrl_reg(intel_dp);
3172                 u32 pp;
3173
3174                 pp = ilk_get_pp_control(intel_dp);
3175                 pp &= ~EDP_BLC_ENABLE;
3176
3177                 intel_de_write(dev_priv, pp_ctrl_reg, pp);
3178                 intel_de_posting_read(dev_priv, pp_ctrl_reg);
3179         }
3180
3181         intel_dp->last_backlight_off = jiffies;
3182         edp_wait_backlight_off(intel_dp);
3183 }
3184
3185 /* Disable backlight PP control and backlight PWM. */
3186 void intel_edp_backlight_off(const struct drm_connector_state *old_conn_state)
3187 {
3188         struct intel_dp *intel_dp = enc_to_intel_dp(to_intel_encoder(old_conn_state->best_encoder));
3189         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
3190
3191         if (!intel_dp_is_edp(intel_dp))
3192                 return;
3193
3194         drm_dbg_kms(&i915->drm, "\n");
3195
3196         _intel_edp_backlight_off(intel_dp);
3197         intel_panel_disable_backlight(old_conn_state);
3198 }
3199
3200 /*
3201  * Hook for controlling the panel power control backlight through the bl_power
3202  * sysfs attribute. Take care to handle multiple calls.
3203  */
3204 static void intel_edp_backlight_power(struct intel_connector *connector,
3205                                       bool enable)
3206 {
3207         struct drm_i915_private *i915 = to_i915(connector->base.dev);
3208         struct intel_dp *intel_dp = intel_attached_dp(connector);
3209         intel_wakeref_t wakeref;
3210         bool is_enabled;
3211
3212         is_enabled = false;
3213         with_pps_lock(intel_dp, wakeref)
3214                 is_enabled = ilk_get_pp_control(intel_dp) & EDP_BLC_ENABLE;
3215         if (is_enabled == enable)
3216                 return;
3217
3218         drm_dbg_kms(&i915->drm, "panel power control backlight %s\n",
3219                     enable ? "enable" : "disable");
3220
3221         if (enable)
3222                 _intel_edp_backlight_on(intel_dp);
3223         else
3224                 _intel_edp_backlight_off(intel_dp);
3225 }
3226
3227 static void assert_dp_port(struct intel_dp *intel_dp, bool state)
3228 {
3229         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
3230         struct drm_i915_private *dev_priv = to_i915(dig_port->base.base.dev);
3231         bool cur_state = intel_de_read(dev_priv, intel_dp->output_reg) & DP_PORT_EN;
3232
3233         I915_STATE_WARN(cur_state != state,
3234                         "[ENCODER:%d:%s] state assertion failure (expected %s, current %s)\n",
3235                         dig_port->base.base.base.id, dig_port->base.base.name,
3236                         onoff(state), onoff(cur_state));
3237 }
3238 #define assert_dp_port_disabled(d) assert_dp_port((d), false)
3239
3240 static void assert_edp_pll(struct drm_i915_private *dev_priv, bool state)
3241 {
3242         bool cur_state = intel_de_read(dev_priv, DP_A) & DP_PLL_ENABLE;
3243
3244         I915_STATE_WARN(cur_state != state,
3245                         "eDP PLL state assertion failure (expected %s, current %s)\n",
3246                         onoff(state), onoff(cur_state));
3247 }
3248 #define assert_edp_pll_enabled(d) assert_edp_pll((d), true)
3249 #define assert_edp_pll_disabled(d) assert_edp_pll((d), false)
3250
3251 static void ilk_edp_pll_on(struct intel_dp *intel_dp,
3252                            const struct intel_crtc_state *pipe_config)
3253 {
3254         struct intel_crtc *crtc = to_intel_crtc(pipe_config->uapi.crtc);
3255         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3256
3257         assert_pipe_disabled(dev_priv, pipe_config->cpu_transcoder);
3258         assert_dp_port_disabled(intel_dp);
3259         assert_edp_pll_disabled(dev_priv);
3260
3261         drm_dbg_kms(&dev_priv->drm, "enabling eDP PLL for clock %d\n",
3262                     pipe_config->port_clock);
3263
3264         intel_dp->DP &= ~DP_PLL_FREQ_MASK;
3265
3266         if (pipe_config->port_clock == 162000)
3267                 intel_dp->DP |= DP_PLL_FREQ_162MHZ;
3268         else
3269                 intel_dp->DP |= DP_PLL_FREQ_270MHZ;
3270
3271         intel_de_write(dev_priv, DP_A, intel_dp->DP);
3272         intel_de_posting_read(dev_priv, DP_A);
3273         udelay(500);
3274
3275         /*
3276          * [DevILK] Work around required when enabling DP PLL
3277          * while a pipe is enabled going to FDI:
3278          * 1. Wait for the start of vertical blank on the enabled pipe going to FDI
3279          * 2. Program DP PLL enable
3280          */
3281         if (IS_GEN(dev_priv, 5))
3282                 intel_wait_for_vblank_if_active(dev_priv, !crtc->pipe);
3283
3284         intel_dp->DP |= DP_PLL_ENABLE;
3285
3286         intel_de_write(dev_priv, DP_A, intel_dp->DP);
3287         intel_de_posting_read(dev_priv, DP_A);
3288         udelay(200);
3289 }
3290
3291 static void ilk_edp_pll_off(struct intel_dp *intel_dp,
3292                             const struct intel_crtc_state *old_crtc_state)
3293 {
3294         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->uapi.crtc);
3295         struct drm_i915_private *dev_priv = to_i915(crtc->base.dev);
3296
3297         assert_pipe_disabled(dev_priv, old_crtc_state->cpu_transcoder);
3298         assert_dp_port_disabled(intel_dp);
3299         assert_edp_pll_enabled(dev_priv);
3300
3301         drm_dbg_kms(&dev_priv->drm, "disabling eDP PLL\n");
3302
3303         intel_dp->DP &= ~DP_PLL_ENABLE;
3304
3305         intel_de_write(dev_priv, DP_A, intel_dp->DP);
3306         intel_de_posting_read(dev_priv, DP_A);
3307         udelay(200);
3308 }
3309
3310 static bool downstream_hpd_needs_d0(struct intel_dp *intel_dp)
3311 {
3312         /*
3313          * DPCD 1.2+ should support BRANCH_DEVICE_CTRL, and thus
3314          * be capable of signalling downstream hpd with a long pulse.
3315          * Whether or not that means D3 is safe to use is not clear,
3316          * but let's assume so until proven otherwise.
3317          *
3318          * FIXME should really check all downstream ports...
3319          */
3320         return intel_dp->dpcd[DP_DPCD_REV] == 0x11 &&
3321                 drm_dp_is_branch(intel_dp->dpcd) &&
3322                 intel_dp->downstream_ports[0] & DP_DS_PORT_HPD;
3323 }
3324
3325 void intel_dp_sink_set_decompression_state(struct intel_dp *intel_dp,
3326                                            const struct intel_crtc_state *crtc_state,
3327                                            bool enable)
3328 {
3329         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
3330         int ret;
3331
3332         if (!crtc_state->dsc.compression_enable)
3333                 return;
3334
3335         ret = drm_dp_dpcd_writeb(&intel_dp->aux, DP_DSC_ENABLE,
3336                                  enable ? DP_DECOMPRESSION_EN : 0);
3337         if (ret < 0)
3338                 drm_dbg_kms(&i915->drm,
3339                             "Failed to %s sink decompression state\n",
3340                             enable ? "enable" : "disable");
3341 }
3342
3343 /* If the sink supports it, try to set the power state appropriately */
3344 void intel_dp_sink_dpms(struct intel_dp *intel_dp, int mode)
3345 {
3346         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
3347         int ret, i;
3348
3349         /* Should have a valid DPCD by this point */
3350         if (intel_dp->dpcd[DP_DPCD_REV] < 0x11)
3351                 return;
3352
3353         if (mode != DRM_MODE_DPMS_ON) {
3354                 if (downstream_hpd_needs_d0(intel_dp))
3355                         return;
3356
3357                 ret = drm_dp_dpcd_writeb(&intel_dp->aux, DP_SET_POWER,
3358                                          DP_SET_POWER_D3);
3359         } else {
3360                 struct intel_lspcon *lspcon = dp_to_lspcon(intel_dp);
3361
3362                 /*
3363                  * When turning on, we need to retry for 1ms to give the sink
3364                  * time to wake up.
3365                  */
3366                 for (i = 0; i < 3; i++) {
3367                         ret = drm_dp_dpcd_writeb(&intel_dp->aux, DP_SET_POWER,
3368                                                  DP_SET_POWER_D0);
3369                         if (ret == 1)
3370                                 break;
3371                         msleep(1);
3372                 }
3373
3374                 if (ret == 1 && lspcon->active)
3375                         lspcon_wait_pcon_mode(lspcon);
3376         }
3377
3378         if (ret != 1)
3379                 drm_dbg_kms(&i915->drm, "failed to %s sink power state\n",
3380                             mode == DRM_MODE_DPMS_ON ? "enable" : "disable");
3381 }
3382
3383 static bool cpt_dp_port_selected(struct drm_i915_private *dev_priv,
3384                                  enum port port, enum pipe *pipe)
3385 {
3386         enum pipe p;
3387
3388         for_each_pipe(dev_priv, p) {
3389                 u32 val = intel_de_read(dev_priv, TRANS_DP_CTL(p));
3390
3391                 if ((val & TRANS_DP_PORT_SEL_MASK) == TRANS_DP_PORT_SEL(port)) {
3392                         *pipe = p;
3393                         return true;
3394                 }
3395         }
3396
3397         drm_dbg_kms(&dev_priv->drm, "No pipe for DP port %c found\n",
3398                     port_name(port));
3399
3400         /* must initialize pipe to something for the asserts */
3401         *pipe = PIPE_A;
3402
3403         return false;
3404 }
3405
3406 bool intel_dp_port_enabled(struct drm_i915_private *dev_priv,
3407                            i915_reg_t dp_reg, enum port port,
3408                            enum pipe *pipe)
3409 {
3410         bool ret;
3411         u32 val;
3412
3413         val = intel_de_read(dev_priv, dp_reg);
3414
3415         ret = val & DP_PORT_EN;
3416
3417         /* asserts want to know the pipe even if the port is disabled */
3418         if (IS_IVYBRIDGE(dev_priv) && port == PORT_A)
3419                 *pipe = (val & DP_PIPE_SEL_MASK_IVB) >> DP_PIPE_SEL_SHIFT_IVB;
3420         else if (HAS_PCH_CPT(dev_priv) && port != PORT_A)
3421                 ret &= cpt_dp_port_selected(dev_priv, port, pipe);
3422         else if (IS_CHERRYVIEW(dev_priv))
3423                 *pipe = (val & DP_PIPE_SEL_MASK_CHV) >> DP_PIPE_SEL_SHIFT_CHV;
3424         else
3425                 *pipe = (val & DP_PIPE_SEL_MASK) >> DP_PIPE_SEL_SHIFT;
3426
3427         return ret;
3428 }
3429
3430 static bool intel_dp_get_hw_state(struct intel_encoder *encoder,
3431                                   enum pipe *pipe)
3432 {
3433         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
3434         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3435         intel_wakeref_t wakeref;
3436         bool ret;
3437
3438         wakeref = intel_display_power_get_if_enabled(dev_priv,
3439                                                      encoder->power_domain);
3440         if (!wakeref)
3441                 return false;
3442
3443         ret = intel_dp_port_enabled(dev_priv, intel_dp->output_reg,
3444                                     encoder->port, pipe);
3445
3446         intel_display_power_put(dev_priv, encoder->power_domain, wakeref);
3447
3448         return ret;
3449 }
3450
3451 static void intel_dp_get_config(struct intel_encoder *encoder,
3452                                 struct intel_crtc_state *pipe_config)
3453 {
3454         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
3455         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3456         u32 tmp, flags = 0;
3457         enum port port = encoder->port;
3458         struct intel_crtc *crtc = to_intel_crtc(pipe_config->uapi.crtc);
3459
3460         if (encoder->type == INTEL_OUTPUT_EDP)
3461                 pipe_config->output_types |= BIT(INTEL_OUTPUT_EDP);
3462         else
3463                 pipe_config->output_types |= BIT(INTEL_OUTPUT_DP);
3464
3465         tmp = intel_de_read(dev_priv, intel_dp->output_reg);
3466
3467         pipe_config->has_audio = tmp & DP_AUDIO_OUTPUT_ENABLE && port != PORT_A;
3468
3469         if (HAS_PCH_CPT(dev_priv) && port != PORT_A) {
3470                 u32 trans_dp = intel_de_read(dev_priv,
3471                                              TRANS_DP_CTL(crtc->pipe));
3472
3473                 if (trans_dp & TRANS_DP_HSYNC_ACTIVE_HIGH)
3474                         flags |= DRM_MODE_FLAG_PHSYNC;
3475                 else
3476                         flags |= DRM_MODE_FLAG_NHSYNC;
3477
3478                 if (trans_dp & TRANS_DP_VSYNC_ACTIVE_HIGH)
3479                         flags |= DRM_MODE_FLAG_PVSYNC;
3480                 else
3481                         flags |= DRM_MODE_FLAG_NVSYNC;
3482         } else {
3483                 if (tmp & DP_SYNC_HS_HIGH)
3484                         flags |= DRM_MODE_FLAG_PHSYNC;
3485                 else
3486                         flags |= DRM_MODE_FLAG_NHSYNC;
3487
3488                 if (tmp & DP_SYNC_VS_HIGH)
3489                         flags |= DRM_MODE_FLAG_PVSYNC;
3490                 else
3491                         flags |= DRM_MODE_FLAG_NVSYNC;
3492         }
3493
3494         pipe_config->hw.adjusted_mode.flags |= flags;
3495
3496         if (IS_G4X(dev_priv) && tmp & DP_COLOR_RANGE_16_235)
3497                 pipe_config->limited_color_range = true;
3498
3499         pipe_config->lane_count =
3500                 ((tmp & DP_PORT_WIDTH_MASK) >> DP_PORT_WIDTH_SHIFT) + 1;
3501
3502         intel_dp_get_m_n(crtc, pipe_config);
3503
3504         if (port == PORT_A) {
3505                 if ((intel_de_read(dev_priv, DP_A) & DP_PLL_FREQ_MASK) == DP_PLL_FREQ_162MHZ)
3506                         pipe_config->port_clock = 162000;
3507                 else
3508                         pipe_config->port_clock = 270000;
3509         }
3510
3511         pipe_config->hw.adjusted_mode.crtc_clock =
3512                 intel_dotclock_calculate(pipe_config->port_clock,
3513                                          &pipe_config->dp_m_n);
3514
3515         if (intel_dp_is_edp(intel_dp) && dev_priv->vbt.edp.bpp &&
3516             pipe_config->pipe_bpp > dev_priv->vbt.edp.bpp) {
3517                 /*
3518                  * This is a big fat ugly hack.
3519                  *
3520                  * Some machines in UEFI boot mode provide us a VBT that has 18
3521                  * bpp and 1.62 GHz link bandwidth for eDP, which for reasons
3522                  * unknown we fail to light up. Yet the same BIOS boots up with
3523                  * 24 bpp and 2.7 GHz link. Use the same bpp as the BIOS uses as
3524                  * max, not what it tells us to use.
3525                  *
3526                  * Note: This will still be broken if the eDP panel is not lit
3527                  * up by the BIOS, and thus we can't get the mode at module
3528                  * load.
3529                  */
3530                 drm_dbg_kms(&dev_priv->drm,
3531                             "pipe has %d bpp for eDP panel, overriding BIOS-provided max %d bpp\n",
3532                             pipe_config->pipe_bpp, dev_priv->vbt.edp.bpp);
3533                 dev_priv->vbt.edp.bpp = pipe_config->pipe_bpp;
3534         }
3535 }
3536
3537 static void intel_disable_dp(struct intel_atomic_state *state,
3538                              struct intel_encoder *encoder,
3539                              const struct intel_crtc_state *old_crtc_state,
3540                              const struct drm_connector_state *old_conn_state)
3541 {
3542         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3543
3544         intel_dp->link_trained = false;
3545
3546         if (old_crtc_state->has_audio)
3547                 intel_audio_codec_disable(encoder,
3548                                           old_crtc_state, old_conn_state);
3549
3550         /* Make sure the panel is off before trying to change the mode. But also
3551          * ensure that we have vdd while we switch off the panel. */
3552         intel_edp_panel_vdd_on(intel_dp);
3553         intel_edp_backlight_off(old_conn_state);
3554         intel_dp_sink_dpms(intel_dp, DRM_MODE_DPMS_OFF);
3555         intel_edp_panel_off(intel_dp);
3556 }
3557
3558 static void g4x_disable_dp(struct intel_atomic_state *state,
3559                            struct intel_encoder *encoder,
3560                            const struct intel_crtc_state *old_crtc_state,
3561                            const struct drm_connector_state *old_conn_state)
3562 {
3563         intel_disable_dp(state, encoder, old_crtc_state, old_conn_state);
3564 }
3565
3566 static void vlv_disable_dp(struct intel_atomic_state *state,
3567                            struct intel_encoder *encoder,
3568                            const struct intel_crtc_state *old_crtc_state,
3569                            const struct drm_connector_state *old_conn_state)
3570 {
3571         intel_disable_dp(state, encoder, old_crtc_state, old_conn_state);
3572 }
3573
3574 static void g4x_post_disable_dp(struct intel_atomic_state *state,
3575                                 struct intel_encoder *encoder,
3576                                 const struct intel_crtc_state *old_crtc_state,
3577                                 const struct drm_connector_state *old_conn_state)
3578 {
3579         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3580         enum port port = encoder->port;
3581
3582         /*
3583          * Bspec does not list a specific disable sequence for g4x DP.
3584          * Follow the ilk+ sequence (disable pipe before the port) for
3585          * g4x DP as it does not suffer from underruns like the normal
3586          * g4x modeset sequence (disable pipe after the port).
3587          */
3588         intel_dp_link_down(encoder, old_crtc_state);
3589
3590         /* Only ilk+ has port A */
3591         if (port == PORT_A)
3592                 ilk_edp_pll_off(intel_dp, old_crtc_state);
3593 }
3594
3595 static void vlv_post_disable_dp(struct intel_atomic_state *state,
3596                                 struct intel_encoder *encoder,
3597                                 const struct intel_crtc_state *old_crtc_state,
3598                                 const struct drm_connector_state *old_conn_state)
3599 {
3600         intel_dp_link_down(encoder, old_crtc_state);
3601 }
3602
3603 static void chv_post_disable_dp(struct intel_atomic_state *state,
3604                                 struct intel_encoder *encoder,
3605                                 const struct intel_crtc_state *old_crtc_state,
3606                                 const struct drm_connector_state *old_conn_state)
3607 {
3608         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
3609
3610         intel_dp_link_down(encoder, old_crtc_state);
3611
3612         vlv_dpio_get(dev_priv);
3613
3614         /* Assert data lane reset */
3615         chv_data_lane_soft_reset(encoder, old_crtc_state, true);
3616
3617         vlv_dpio_put(dev_priv);
3618 }
3619
3620 static void
3621 cpt_set_link_train(struct intel_dp *intel_dp,
3622                    u8 dp_train_pat)
3623 {
3624         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3625         u32 *DP = &intel_dp->DP;
3626
3627         *DP &= ~DP_LINK_TRAIN_MASK_CPT;
3628
3629         switch (dp_train_pat & DP_TRAINING_PATTERN_MASK) {
3630         case DP_TRAINING_PATTERN_DISABLE:
3631                 *DP |= DP_LINK_TRAIN_OFF_CPT;
3632                 break;
3633         case DP_TRAINING_PATTERN_1:
3634                 *DP |= DP_LINK_TRAIN_PAT_1_CPT;
3635                 break;
3636         case DP_TRAINING_PATTERN_2:
3637                 *DP |= DP_LINK_TRAIN_PAT_2_CPT;
3638                 break;
3639         case DP_TRAINING_PATTERN_3:
3640                 drm_dbg_kms(&dev_priv->drm,
3641                             "TPS3 not supported, using TPS2 instead\n");
3642                 *DP |= DP_LINK_TRAIN_PAT_2_CPT;
3643                 break;
3644         }
3645
3646         intel_de_write(dev_priv, intel_dp->output_reg, intel_dp->DP);
3647         intel_de_posting_read(dev_priv, intel_dp->output_reg);
3648 }
3649
3650 static void
3651 g4x_set_link_train(struct intel_dp *intel_dp,
3652                    u8 dp_train_pat)
3653 {
3654         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3655         u32 *DP = &intel_dp->DP;
3656
3657         *DP &= ~DP_LINK_TRAIN_MASK;
3658
3659         switch (dp_train_pat & DP_TRAINING_PATTERN_MASK) {
3660         case DP_TRAINING_PATTERN_DISABLE:
3661                 *DP |= DP_LINK_TRAIN_OFF;
3662                 break;
3663         case DP_TRAINING_PATTERN_1:
3664                 *DP |= DP_LINK_TRAIN_PAT_1;
3665                 break;
3666         case DP_TRAINING_PATTERN_2:
3667                 *DP |= DP_LINK_TRAIN_PAT_2;
3668                 break;
3669         case DP_TRAINING_PATTERN_3:
3670                 drm_dbg_kms(&dev_priv->drm,
3671                             "TPS3 not supported, using TPS2 instead\n");
3672                 *DP |= DP_LINK_TRAIN_PAT_2;
3673                 break;
3674         }
3675
3676         intel_de_write(dev_priv, intel_dp->output_reg, intel_dp->DP);
3677         intel_de_posting_read(dev_priv, intel_dp->output_reg);
3678 }
3679
3680 static void intel_dp_enable_port(struct intel_dp *intel_dp,
3681                                  const struct intel_crtc_state *old_crtc_state)
3682 {
3683         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3684
3685         /* enable with pattern 1 (as per spec) */
3686
3687         intel_dp_program_link_training_pattern(intel_dp, DP_TRAINING_PATTERN_1);
3688
3689         /*
3690          * Magic for VLV/CHV. We _must_ first set up the register
3691          * without actually enabling the port, and then do another
3692          * write to enable the port. Otherwise link training will
3693          * fail when the power sequencer is freshly used for this port.
3694          */
3695         intel_dp->DP |= DP_PORT_EN;
3696         if (old_crtc_state->has_audio)
3697                 intel_dp->DP |= DP_AUDIO_OUTPUT_ENABLE;
3698
3699         intel_de_write(dev_priv, intel_dp->output_reg, intel_dp->DP);
3700         intel_de_posting_read(dev_priv, intel_dp->output_reg);
3701 }
3702
3703 static void intel_enable_dp(struct intel_atomic_state *state,
3704                             struct intel_encoder *encoder,
3705                             const struct intel_crtc_state *pipe_config,
3706                             const struct drm_connector_state *conn_state)
3707 {
3708         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
3709         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3710         struct intel_crtc *crtc = to_intel_crtc(pipe_config->uapi.crtc);
3711         u32 dp_reg = intel_de_read(dev_priv, intel_dp->output_reg);
3712         enum pipe pipe = crtc->pipe;
3713         intel_wakeref_t wakeref;
3714
3715         if (drm_WARN_ON(&dev_priv->drm, dp_reg & DP_PORT_EN))
3716                 return;
3717
3718         with_pps_lock(intel_dp, wakeref) {
3719                 if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
3720                         vlv_init_panel_power_sequencer(encoder, pipe_config);
3721
3722                 intel_dp_enable_port(intel_dp, pipe_config);
3723
3724                 edp_panel_vdd_on(intel_dp);
3725                 edp_panel_on(intel_dp);
3726                 edp_panel_vdd_off(intel_dp, true);
3727         }
3728
3729         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
3730                 unsigned int lane_mask = 0x0;
3731
3732                 if (IS_CHERRYVIEW(dev_priv))
3733                         lane_mask = intel_dp_unused_lane_mask(pipe_config->lane_count);
3734
3735                 vlv_wait_port_ready(dev_priv, dp_to_dig_port(intel_dp),
3736                                     lane_mask);
3737         }
3738
3739         intel_dp_sink_dpms(intel_dp, DRM_MODE_DPMS_ON);
3740         intel_dp_start_link_train(intel_dp);
3741         intel_dp_stop_link_train(intel_dp);
3742
3743         if (pipe_config->has_audio) {
3744                 drm_dbg(&dev_priv->drm, "Enabling DP audio on pipe %c\n",
3745                         pipe_name(pipe));
3746                 intel_audio_codec_enable(encoder, pipe_config, conn_state);
3747         }
3748 }
3749
3750 static void g4x_enable_dp(struct intel_atomic_state *state,
3751                           struct intel_encoder *encoder,
3752                           const struct intel_crtc_state *pipe_config,
3753                           const struct drm_connector_state *conn_state)
3754 {
3755         intel_enable_dp(state, encoder, pipe_config, conn_state);
3756         intel_edp_backlight_on(pipe_config, conn_state);
3757 }
3758
3759 static void vlv_enable_dp(struct intel_atomic_state *state,
3760                           struct intel_encoder *encoder,
3761                           const struct intel_crtc_state *pipe_config,
3762                           const struct drm_connector_state *conn_state)
3763 {
3764         intel_edp_backlight_on(pipe_config, conn_state);
3765 }
3766
3767 static void g4x_pre_enable_dp(struct intel_atomic_state *state,
3768                               struct intel_encoder *encoder,
3769                               const struct intel_crtc_state *pipe_config,
3770                               const struct drm_connector_state *conn_state)
3771 {
3772         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3773         enum port port = encoder->port;
3774
3775         intel_dp_prepare(encoder, pipe_config);
3776
3777         /* Only ilk+ has port A */
3778         if (port == PORT_A)
3779                 ilk_edp_pll_on(intel_dp, pipe_config);
3780 }
3781
3782 static void vlv_detach_power_sequencer(struct intel_dp *intel_dp)
3783 {
3784         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
3785         struct drm_i915_private *dev_priv = to_i915(intel_dig_port->base.base.dev);
3786         enum pipe pipe = intel_dp->pps_pipe;
3787         i915_reg_t pp_on_reg = PP_ON_DELAYS(pipe);
3788
3789         drm_WARN_ON(&dev_priv->drm, intel_dp->active_pipe != INVALID_PIPE);
3790
3791         if (drm_WARN_ON(&dev_priv->drm, pipe != PIPE_A && pipe != PIPE_B))
3792                 return;
3793
3794         edp_panel_vdd_off_sync(intel_dp);
3795
3796         /*
3797          * VLV seems to get confused when multiple power sequencers
3798          * have the same port selected (even if only one has power/vdd
3799          * enabled). The failure manifests as vlv_wait_port_ready() failing
3800          * CHV on the other hand doesn't seem to mind having the same port
3801          * selected in multiple power sequencers, but let's clear the
3802          * port select always when logically disconnecting a power sequencer
3803          * from a port.
3804          */
3805         drm_dbg_kms(&dev_priv->drm,
3806                     "detaching pipe %c power sequencer from [ENCODER:%d:%s]\n",
3807                     pipe_name(pipe), intel_dig_port->base.base.base.id,
3808                     intel_dig_port->base.base.name);
3809         intel_de_write(dev_priv, pp_on_reg, 0);
3810         intel_de_posting_read(dev_priv, pp_on_reg);
3811
3812         intel_dp->pps_pipe = INVALID_PIPE;
3813 }
3814
3815 static void vlv_steal_power_sequencer(struct drm_i915_private *dev_priv,
3816                                       enum pipe pipe)
3817 {
3818         struct intel_encoder *encoder;
3819
3820         lockdep_assert_held(&dev_priv->pps_mutex);
3821
3822         for_each_intel_dp(&dev_priv->drm, encoder) {
3823                 struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3824
3825                 drm_WARN(&dev_priv->drm, intel_dp->active_pipe == pipe,
3826                          "stealing pipe %c power sequencer from active [ENCODER:%d:%s]\n",
3827                          pipe_name(pipe), encoder->base.base.id,
3828                          encoder->base.name);
3829
3830                 if (intel_dp->pps_pipe != pipe)
3831                         continue;
3832
3833                 drm_dbg_kms(&dev_priv->drm,
3834                             "stealing pipe %c power sequencer from [ENCODER:%d:%s]\n",
3835                             pipe_name(pipe), encoder->base.base.id,
3836                             encoder->base.name);
3837
3838                 /* make sure vdd is off before we steal it */
3839                 vlv_detach_power_sequencer(intel_dp);
3840         }
3841 }
3842
3843 static void vlv_init_panel_power_sequencer(struct intel_encoder *encoder,
3844                                            const struct intel_crtc_state *crtc_state)
3845 {
3846         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
3847         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
3848         struct intel_crtc *crtc = to_intel_crtc(crtc_state->uapi.crtc);
3849
3850         lockdep_assert_held(&dev_priv->pps_mutex);
3851
3852         drm_WARN_ON(&dev_priv->drm, intel_dp->active_pipe != INVALID_PIPE);
3853
3854         if (intel_dp->pps_pipe != INVALID_PIPE &&
3855             intel_dp->pps_pipe != crtc->pipe) {
3856                 /*
3857                  * If another power sequencer was being used on this
3858                  * port previously make sure to turn off vdd there while
3859                  * we still have control of it.
3860                  */
3861                 vlv_detach_power_sequencer(intel_dp);
3862         }
3863
3864         /*
3865          * We may be stealing the power
3866          * sequencer from another port.
3867          */
3868         vlv_steal_power_sequencer(dev_priv, crtc->pipe);
3869
3870         intel_dp->active_pipe = crtc->pipe;
3871
3872         if (!intel_dp_is_edp(intel_dp))
3873                 return;
3874
3875         /* now it's all ours */
3876         intel_dp->pps_pipe = crtc->pipe;
3877
3878         drm_dbg_kms(&dev_priv->drm,
3879                     "initializing pipe %c power sequencer for [ENCODER:%d:%s]\n",
3880                     pipe_name(intel_dp->pps_pipe), encoder->base.base.id,
3881                     encoder->base.name);
3882
3883         /* init power sequencer on this pipe and port */
3884         intel_dp_init_panel_power_sequencer(intel_dp);
3885         intel_dp_init_panel_power_sequencer_registers(intel_dp, true);
3886 }
3887
3888 static void vlv_pre_enable_dp(struct intel_atomic_state *state,
3889                               struct intel_encoder *encoder,
3890                               const struct intel_crtc_state *pipe_config,
3891                               const struct drm_connector_state *conn_state)
3892 {
3893         vlv_phy_pre_encoder_enable(encoder, pipe_config);
3894
3895         intel_enable_dp(state, encoder, pipe_config, conn_state);
3896 }
3897
3898 static void vlv_dp_pre_pll_enable(struct intel_atomic_state *state,
3899                                   struct intel_encoder *encoder,
3900                                   const struct intel_crtc_state *pipe_config,
3901                                   const struct drm_connector_state *conn_state)
3902 {
3903         intel_dp_prepare(encoder, pipe_config);
3904
3905         vlv_phy_pre_pll_enable(encoder, pipe_config);
3906 }
3907
3908 static void chv_pre_enable_dp(struct intel_atomic_state *state,
3909                               struct intel_encoder *encoder,
3910                               const struct intel_crtc_state *pipe_config,
3911                               const struct drm_connector_state *conn_state)
3912 {
3913         chv_phy_pre_encoder_enable(encoder, pipe_config);
3914
3915         intel_enable_dp(state, encoder, pipe_config, conn_state);
3916
3917         /* Second common lane will stay alive on its own now */
3918         chv_phy_release_cl2_override(encoder);
3919 }
3920
3921 static void chv_dp_pre_pll_enable(struct intel_atomic_state *state,
3922                                   struct intel_encoder *encoder,
3923                                   const struct intel_crtc_state *pipe_config,
3924                                   const struct drm_connector_state *conn_state)
3925 {
3926         intel_dp_prepare(encoder, pipe_config);
3927
3928         chv_phy_pre_pll_enable(encoder, pipe_config);
3929 }
3930
3931 static void chv_dp_post_pll_disable(struct intel_atomic_state *state,
3932                                     struct intel_encoder *encoder,
3933                                     const struct intel_crtc_state *old_crtc_state,
3934                                     const struct drm_connector_state *old_conn_state)
3935 {
3936         chv_phy_post_pll_disable(encoder, old_crtc_state);
3937 }
3938
3939 /*
3940  * Fetch AUX CH registers 0x202 - 0x207 which contain
3941  * link status information
3942  */
3943 bool
3944 intel_dp_get_link_status(struct intel_dp *intel_dp, u8 link_status[DP_LINK_STATUS_SIZE])
3945 {
3946         return drm_dp_dpcd_read(&intel_dp->aux, DP_LANE0_1_STATUS, link_status,
3947                                 DP_LINK_STATUS_SIZE) == DP_LINK_STATUS_SIZE;
3948 }
3949
3950 /* These are source-specific values. */
3951 u8
3952 intel_dp_voltage_max(struct intel_dp *intel_dp)
3953 {
3954         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3955         struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
3956         enum port port = encoder->port;
3957
3958         if (HAS_DDI(dev_priv))
3959                 return intel_ddi_dp_voltage_max(encoder);
3960         else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
3961                 return DP_TRAIN_VOLTAGE_SWING_LEVEL_3;
3962         else if (IS_IVYBRIDGE(dev_priv) && port == PORT_A)
3963                 return DP_TRAIN_VOLTAGE_SWING_LEVEL_2;
3964         else if (HAS_PCH_CPT(dev_priv) && port != PORT_A)
3965                 return DP_TRAIN_VOLTAGE_SWING_LEVEL_3;
3966         else
3967                 return DP_TRAIN_VOLTAGE_SWING_LEVEL_2;
3968 }
3969
3970 u8
3971 intel_dp_pre_emphasis_max(struct intel_dp *intel_dp, u8 voltage_swing)
3972 {
3973         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
3974         struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
3975         enum port port = encoder->port;
3976
3977         if (HAS_DDI(dev_priv)) {
3978                 return intel_ddi_dp_pre_emphasis_max(encoder, voltage_swing);
3979         } else if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
3980                 switch (voltage_swing & DP_TRAIN_VOLTAGE_SWING_MASK) {
3981                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
3982                         return DP_TRAIN_PRE_EMPH_LEVEL_3;
3983                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
3984                         return DP_TRAIN_PRE_EMPH_LEVEL_2;
3985                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
3986                         return DP_TRAIN_PRE_EMPH_LEVEL_1;
3987                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_3:
3988                 default:
3989                         return DP_TRAIN_PRE_EMPH_LEVEL_0;
3990                 }
3991         } else if (IS_IVYBRIDGE(dev_priv) && port == PORT_A) {
3992                 switch (voltage_swing & DP_TRAIN_VOLTAGE_SWING_MASK) {
3993                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
3994                         return DP_TRAIN_PRE_EMPH_LEVEL_2;
3995                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
3996                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
3997                         return DP_TRAIN_PRE_EMPH_LEVEL_1;
3998                 default:
3999                         return DP_TRAIN_PRE_EMPH_LEVEL_0;
4000                 }
4001         } else {
4002                 switch (voltage_swing & DP_TRAIN_VOLTAGE_SWING_MASK) {
4003                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4004                         return DP_TRAIN_PRE_EMPH_LEVEL_2;
4005                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4006                         return DP_TRAIN_PRE_EMPH_LEVEL_2;
4007                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
4008                         return DP_TRAIN_PRE_EMPH_LEVEL_1;
4009                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_3:
4010                 default:
4011                         return DP_TRAIN_PRE_EMPH_LEVEL_0;
4012                 }
4013         }
4014 }
4015
4016 static void vlv_set_signal_levels(struct intel_dp *intel_dp)
4017 {
4018         struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
4019         unsigned long demph_reg_value, preemph_reg_value,
4020                 uniqtranscale_reg_value;
4021         u8 train_set = intel_dp->train_set[0];
4022
4023         switch (train_set & DP_TRAIN_PRE_EMPHASIS_MASK) {
4024         case DP_TRAIN_PRE_EMPH_LEVEL_0:
4025                 preemph_reg_value = 0x0004000;
4026                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4027                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4028                         demph_reg_value = 0x2B405555;
4029                         uniqtranscale_reg_value = 0x552AB83A;
4030                         break;
4031                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4032                         demph_reg_value = 0x2B404040;
4033                         uniqtranscale_reg_value = 0x5548B83A;
4034                         break;
4035                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
4036                         demph_reg_value = 0x2B245555;
4037                         uniqtranscale_reg_value = 0x5560B83A;
4038                         break;
4039                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_3:
4040                         demph_reg_value = 0x2B405555;
4041                         uniqtranscale_reg_value = 0x5598DA3A;
4042                         break;
4043                 default:
4044                         return;
4045                 }
4046                 break;
4047         case DP_TRAIN_PRE_EMPH_LEVEL_1:
4048                 preemph_reg_value = 0x0002000;
4049                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4050                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4051                         demph_reg_value = 0x2B404040;
4052                         uniqtranscale_reg_value = 0x5552B83A;
4053                         break;
4054                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4055                         demph_reg_value = 0x2B404848;
4056                         uniqtranscale_reg_value = 0x5580B83A;
4057                         break;
4058                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
4059                         demph_reg_value = 0x2B404040;
4060                         uniqtranscale_reg_value = 0x55ADDA3A;
4061                         break;
4062                 default:
4063                         return;
4064                 }
4065                 break;
4066         case DP_TRAIN_PRE_EMPH_LEVEL_2:
4067                 preemph_reg_value = 0x0000000;
4068                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4069                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4070                         demph_reg_value = 0x2B305555;
4071                         uniqtranscale_reg_value = 0x5570B83A;
4072                         break;
4073                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4074                         demph_reg_value = 0x2B2B4040;
4075                         uniqtranscale_reg_value = 0x55ADDA3A;
4076                         break;
4077                 default:
4078                         return;
4079                 }
4080                 break;
4081         case DP_TRAIN_PRE_EMPH_LEVEL_3:
4082                 preemph_reg_value = 0x0006000;
4083                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4084                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4085                         demph_reg_value = 0x1B405555;
4086                         uniqtranscale_reg_value = 0x55ADDA3A;
4087                         break;
4088                 default:
4089                         return;
4090                 }
4091                 break;
4092         default:
4093                 return;
4094         }
4095
4096         vlv_set_phy_signal_level(encoder, demph_reg_value, preemph_reg_value,
4097                                  uniqtranscale_reg_value, 0);
4098 }
4099
4100 static void chv_set_signal_levels(struct intel_dp *intel_dp)
4101 {
4102         struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
4103         u32 deemph_reg_value, margin_reg_value;
4104         bool uniq_trans_scale = false;
4105         u8 train_set = intel_dp->train_set[0];
4106
4107         switch (train_set & DP_TRAIN_PRE_EMPHASIS_MASK) {
4108         case DP_TRAIN_PRE_EMPH_LEVEL_0:
4109                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4110                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4111                         deemph_reg_value = 128;
4112                         margin_reg_value = 52;
4113                         break;
4114                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4115                         deemph_reg_value = 128;
4116                         margin_reg_value = 77;
4117                         break;
4118                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
4119                         deemph_reg_value = 128;
4120                         margin_reg_value = 102;
4121                         break;
4122                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_3:
4123                         deemph_reg_value = 128;
4124                         margin_reg_value = 154;
4125                         uniq_trans_scale = true;
4126                         break;
4127                 default:
4128                         return;
4129                 }
4130                 break;
4131         case DP_TRAIN_PRE_EMPH_LEVEL_1:
4132                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4133                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4134                         deemph_reg_value = 85;
4135                         margin_reg_value = 78;
4136                         break;
4137                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4138                         deemph_reg_value = 85;
4139                         margin_reg_value = 116;
4140                         break;
4141                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
4142                         deemph_reg_value = 85;
4143                         margin_reg_value = 154;
4144                         break;
4145                 default:
4146                         return;
4147                 }
4148                 break;
4149         case DP_TRAIN_PRE_EMPH_LEVEL_2:
4150                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4151                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4152                         deemph_reg_value = 64;
4153                         margin_reg_value = 104;
4154                         break;
4155                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4156                         deemph_reg_value = 64;
4157                         margin_reg_value = 154;
4158                         break;
4159                 default:
4160                         return;
4161                 }
4162                 break;
4163         case DP_TRAIN_PRE_EMPH_LEVEL_3:
4164                 switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4165                 case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4166                         deemph_reg_value = 43;
4167                         margin_reg_value = 154;
4168                         break;
4169                 default:
4170                         return;
4171                 }
4172                 break;
4173         default:
4174                 return;
4175         }
4176
4177         chv_set_phy_signal_level(encoder, deemph_reg_value,
4178                                  margin_reg_value, uniq_trans_scale);
4179 }
4180
4181 static u32 g4x_signal_levels(u8 train_set)
4182 {
4183         u32 signal_levels = 0;
4184
4185         switch (train_set & DP_TRAIN_VOLTAGE_SWING_MASK) {
4186         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0:
4187         default:
4188                 signal_levels |= DP_VOLTAGE_0_4;
4189                 break;
4190         case DP_TRAIN_VOLTAGE_SWING_LEVEL_1:
4191                 signal_levels |= DP_VOLTAGE_0_6;
4192                 break;
4193         case DP_TRAIN_VOLTAGE_SWING_LEVEL_2:
4194                 signal_levels |= DP_VOLTAGE_0_8;
4195                 break;
4196         case DP_TRAIN_VOLTAGE_SWING_LEVEL_3:
4197                 signal_levels |= DP_VOLTAGE_1_2;
4198                 break;
4199         }
4200         switch (train_set & DP_TRAIN_PRE_EMPHASIS_MASK) {
4201         case DP_TRAIN_PRE_EMPH_LEVEL_0:
4202         default:
4203                 signal_levels |= DP_PRE_EMPHASIS_0;
4204                 break;
4205         case DP_TRAIN_PRE_EMPH_LEVEL_1:
4206                 signal_levels |= DP_PRE_EMPHASIS_3_5;
4207                 break;
4208         case DP_TRAIN_PRE_EMPH_LEVEL_2:
4209                 signal_levels |= DP_PRE_EMPHASIS_6;
4210                 break;
4211         case DP_TRAIN_PRE_EMPH_LEVEL_3:
4212                 signal_levels |= DP_PRE_EMPHASIS_9_5;
4213                 break;
4214         }
4215         return signal_levels;
4216 }
4217
4218 static void
4219 g4x_set_signal_levels(struct intel_dp *intel_dp)
4220 {
4221         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
4222         u8 train_set = intel_dp->train_set[0];
4223         u32 signal_levels;
4224
4225         signal_levels = g4x_signal_levels(train_set);
4226
4227         drm_dbg_kms(&dev_priv->drm, "Using signal levels %08x\n",
4228                     signal_levels);
4229
4230         intel_dp->DP &= ~(DP_VOLTAGE_MASK | DP_PRE_EMPHASIS_MASK);
4231         intel_dp->DP |= signal_levels;
4232
4233         intel_de_write(dev_priv, intel_dp->output_reg, intel_dp->DP);
4234         intel_de_posting_read(dev_priv, intel_dp->output_reg);
4235 }
4236
4237 /* SNB CPU eDP voltage swing and pre-emphasis control */
4238 static u32 snb_cpu_edp_signal_levels(u8 train_set)
4239 {
4240         u8 signal_levels = train_set & (DP_TRAIN_VOLTAGE_SWING_MASK |
4241                                         DP_TRAIN_PRE_EMPHASIS_MASK);
4242
4243         switch (signal_levels) {
4244         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4245         case DP_TRAIN_VOLTAGE_SWING_LEVEL_1 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4246                 return EDP_LINK_TRAIN_400_600MV_0DB_SNB_B;
4247         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0 | DP_TRAIN_PRE_EMPH_LEVEL_1:
4248                 return EDP_LINK_TRAIN_400MV_3_5DB_SNB_B;
4249         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0 | DP_TRAIN_PRE_EMPH_LEVEL_2:
4250         case DP_TRAIN_VOLTAGE_SWING_LEVEL_1 | DP_TRAIN_PRE_EMPH_LEVEL_2:
4251                 return EDP_LINK_TRAIN_400_600MV_6DB_SNB_B;
4252         case DP_TRAIN_VOLTAGE_SWING_LEVEL_1 | DP_TRAIN_PRE_EMPH_LEVEL_1:
4253         case DP_TRAIN_VOLTAGE_SWING_LEVEL_2 | DP_TRAIN_PRE_EMPH_LEVEL_1:
4254                 return EDP_LINK_TRAIN_600_800MV_3_5DB_SNB_B;
4255         case DP_TRAIN_VOLTAGE_SWING_LEVEL_2 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4256         case DP_TRAIN_VOLTAGE_SWING_LEVEL_3 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4257                 return EDP_LINK_TRAIN_800_1200MV_0DB_SNB_B;
4258         default:
4259                 DRM_DEBUG_KMS("Unsupported voltage swing/pre-emphasis level:"
4260                               "0x%x\n", signal_levels);
4261                 return EDP_LINK_TRAIN_400_600MV_0DB_SNB_B;
4262         }
4263 }
4264
4265 static void
4266 snb_cpu_edp_set_signal_levels(struct intel_dp *intel_dp)
4267 {
4268         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
4269         u8 train_set = intel_dp->train_set[0];
4270         u32 signal_levels;
4271
4272         signal_levels = snb_cpu_edp_signal_levels(train_set);
4273
4274         drm_dbg_kms(&dev_priv->drm, "Using signal levels %08x\n",
4275                     signal_levels);
4276
4277         intel_dp->DP &= ~EDP_LINK_TRAIN_VOL_EMP_MASK_SNB;
4278         intel_dp->DP |= signal_levels;
4279
4280         intel_de_write(dev_priv, intel_dp->output_reg, intel_dp->DP);
4281         intel_de_posting_read(dev_priv, intel_dp->output_reg);
4282 }
4283
4284 /* IVB CPU eDP voltage swing and pre-emphasis control */
4285 static u32 ivb_cpu_edp_signal_levels(u8 train_set)
4286 {
4287         u8 signal_levels = train_set & (DP_TRAIN_VOLTAGE_SWING_MASK |
4288                                         DP_TRAIN_PRE_EMPHASIS_MASK);
4289
4290         switch (signal_levels) {
4291         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4292                 return EDP_LINK_TRAIN_400MV_0DB_IVB;
4293         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0 | DP_TRAIN_PRE_EMPH_LEVEL_1:
4294                 return EDP_LINK_TRAIN_400MV_3_5DB_IVB;
4295         case DP_TRAIN_VOLTAGE_SWING_LEVEL_0 | DP_TRAIN_PRE_EMPH_LEVEL_2:
4296                 return EDP_LINK_TRAIN_400MV_6DB_IVB;
4297
4298         case DP_TRAIN_VOLTAGE_SWING_LEVEL_1 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4299                 return EDP_LINK_TRAIN_600MV_0DB_IVB;
4300         case DP_TRAIN_VOLTAGE_SWING_LEVEL_1 | DP_TRAIN_PRE_EMPH_LEVEL_1:
4301                 return EDP_LINK_TRAIN_600MV_3_5DB_IVB;
4302
4303         case DP_TRAIN_VOLTAGE_SWING_LEVEL_2 | DP_TRAIN_PRE_EMPH_LEVEL_0:
4304                 return EDP_LINK_TRAIN_800MV_0DB_IVB;
4305         case DP_TRAIN_VOLTAGE_SWING_LEVEL_2 | DP_TRAIN_PRE_EMPH_LEVEL_1:
4306                 return EDP_LINK_TRAIN_800MV_3_5DB_IVB;
4307
4308         default:
4309                 DRM_DEBUG_KMS("Unsupported voltage swing/pre-emphasis level:"
4310                               "0x%x\n", signal_levels);
4311                 return EDP_LINK_TRAIN_500MV_0DB_IVB;
4312         }
4313 }
4314
4315 static void
4316 ivb_cpu_edp_set_signal_levels(struct intel_dp *intel_dp)
4317 {
4318         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
4319         u8 train_set = intel_dp->train_set[0];
4320         u32 signal_levels;
4321
4322         signal_levels = ivb_cpu_edp_signal_levels(train_set);
4323
4324         drm_dbg_kms(&dev_priv->drm, "Using signal levels %08x\n",
4325                     signal_levels);
4326
4327         intel_dp->DP &= ~EDP_LINK_TRAIN_VOL_EMP_MASK_IVB;
4328         intel_dp->DP |= signal_levels;
4329
4330         intel_de_write(dev_priv, intel_dp->output_reg, intel_dp->DP);
4331         intel_de_posting_read(dev_priv, intel_dp->output_reg);
4332 }
4333
4334 void intel_dp_set_signal_levels(struct intel_dp *intel_dp)
4335 {
4336         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
4337         u8 train_set = intel_dp->train_set[0];
4338
4339         drm_dbg_kms(&dev_priv->drm, "Using vswing level %d%s\n",
4340                     train_set & DP_TRAIN_VOLTAGE_SWING_MASK,
4341                     train_set & DP_TRAIN_MAX_SWING_REACHED ? " (max)" : "");
4342         drm_dbg_kms(&dev_priv->drm, "Using pre-emphasis level %d%s\n",
4343                     (train_set & DP_TRAIN_PRE_EMPHASIS_MASK) >>
4344                     DP_TRAIN_PRE_EMPHASIS_SHIFT,
4345                     train_set & DP_TRAIN_MAX_PRE_EMPHASIS_REACHED ?
4346                     " (max)" : "");
4347
4348         intel_dp->set_signal_levels(intel_dp);
4349 }
4350
4351 void
4352 intel_dp_program_link_training_pattern(struct intel_dp *intel_dp,
4353                                        u8 dp_train_pat)
4354 {
4355         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
4356         u8 train_pat_mask = drm_dp_training_pattern_mask(intel_dp->dpcd);
4357
4358         if (dp_train_pat & train_pat_mask)
4359                 drm_dbg_kms(&dev_priv->drm,
4360                             "Using DP training pattern TPS%d\n",
4361                             dp_train_pat & train_pat_mask);
4362
4363         intel_dp->set_link_train(intel_dp, dp_train_pat);
4364 }
4365
4366 void intel_dp_set_idle_link_train(struct intel_dp *intel_dp)
4367 {
4368         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
4369         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
4370         enum port port = intel_dig_port->base.port;
4371         u32 val;
4372
4373         if (!HAS_DDI(dev_priv))
4374                 return;
4375
4376         val = intel_de_read(dev_priv, intel_dp->regs.dp_tp_ctl);
4377         val &= ~DP_TP_CTL_LINK_TRAIN_MASK;
4378         val |= DP_TP_CTL_LINK_TRAIN_IDLE;
4379         intel_de_write(dev_priv, intel_dp->regs.dp_tp_ctl, val);
4380
4381         /*
4382          * Until TGL on PORT_A we can have only eDP in SST mode. There the only
4383          * reason we need to set idle transmission mode is to work around a HW
4384          * issue where we enable the pipe while not in idle link-training mode.
4385          * In this case there is requirement to wait for a minimum number of
4386          * idle patterns to be sent.
4387          */
4388         if (port == PORT_A && INTEL_GEN(dev_priv) < 12)
4389                 return;
4390
4391         if (intel_de_wait_for_set(dev_priv, intel_dp->regs.dp_tp_status,
4392                                   DP_TP_STATUS_IDLE_DONE, 1))
4393                 drm_err(&dev_priv->drm,
4394                         "Timed out waiting for DP idle patterns\n");
4395 }
4396
4397 static void
4398 intel_dp_link_down(struct intel_encoder *encoder,
4399                    const struct intel_crtc_state *old_crtc_state)
4400 {
4401         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
4402         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
4403         struct intel_crtc *crtc = to_intel_crtc(old_crtc_state->uapi.crtc);
4404         enum port port = encoder->port;
4405         u32 DP = intel_dp->DP;
4406
4407         if (drm_WARN_ON(&dev_priv->drm,
4408                         (intel_de_read(dev_priv, intel_dp->output_reg) &
4409                          DP_PORT_EN) == 0))
4410                 return;
4411
4412         drm_dbg_kms(&dev_priv->drm, "\n");
4413
4414         if ((IS_IVYBRIDGE(dev_priv) && port == PORT_A) ||
4415             (HAS_PCH_CPT(dev_priv) && port != PORT_A)) {
4416                 DP &= ~DP_LINK_TRAIN_MASK_CPT;
4417                 DP |= DP_LINK_TRAIN_PAT_IDLE_CPT;
4418         } else {
4419                 DP &= ~DP_LINK_TRAIN_MASK;
4420                 DP |= DP_LINK_TRAIN_PAT_IDLE;
4421         }
4422         intel_de_write(dev_priv, intel_dp->output_reg, DP);
4423         intel_de_posting_read(dev_priv, intel_dp->output_reg);
4424
4425         DP &= ~(DP_PORT_EN | DP_AUDIO_OUTPUT_ENABLE);
4426         intel_de_write(dev_priv, intel_dp->output_reg, DP);
4427         intel_de_posting_read(dev_priv, intel_dp->output_reg);
4428
4429         /*
4430          * HW workaround for IBX, we need to move the port
4431          * to transcoder A after disabling it to allow the
4432          * matching HDMI port to be enabled on transcoder A.
4433          */
4434         if (HAS_PCH_IBX(dev_priv) && crtc->pipe == PIPE_B && port != PORT_A) {
4435                 /*
4436                  * We get CPU/PCH FIFO underruns on the other pipe when
4437                  * doing the workaround. Sweep them under the rug.
4438                  */
4439                 intel_set_cpu_fifo_underrun_reporting(dev_priv, PIPE_A, false);
4440                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A, false);
4441
4442                 /* always enable with pattern 1 (as per spec) */
4443                 DP &= ~(DP_PIPE_SEL_MASK | DP_LINK_TRAIN_MASK);
4444                 DP |= DP_PORT_EN | DP_PIPE_SEL(PIPE_A) |
4445                         DP_LINK_TRAIN_PAT_1;
4446                 intel_de_write(dev_priv, intel_dp->output_reg, DP);
4447                 intel_de_posting_read(dev_priv, intel_dp->output_reg);
4448
4449                 DP &= ~DP_PORT_EN;
4450                 intel_de_write(dev_priv, intel_dp->output_reg, DP);
4451                 intel_de_posting_read(dev_priv, intel_dp->output_reg);
4452
4453                 intel_wait_for_vblank_if_active(dev_priv, PIPE_A);
4454                 intel_set_cpu_fifo_underrun_reporting(dev_priv, PIPE_A, true);
4455                 intel_set_pch_fifo_underrun_reporting(dev_priv, PIPE_A, true);
4456         }
4457
4458         msleep(intel_dp->panel_power_down_delay);
4459
4460         intel_dp->DP = DP;
4461
4462         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
4463                 intel_wakeref_t wakeref;
4464
4465                 with_pps_lock(intel_dp, wakeref)
4466                         intel_dp->active_pipe = INVALID_PIPE;
4467         }
4468 }
4469
4470 static void
4471 intel_dp_extended_receiver_capabilities(struct intel_dp *intel_dp)
4472 {
4473         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
4474         u8 dpcd_ext[6];
4475
4476         /*
4477          * Prior to DP1.3 the bit represented by
4478          * DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT was reserved.
4479          * if it is set DP_DPCD_REV at 0000h could be at a value less than
4480          * the true capability of the panel. The only way to check is to
4481          * then compare 0000h and 2200h.
4482          */
4483         if (!(intel_dp->dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
4484               DP_EXTENDED_RECEIVER_CAP_FIELD_PRESENT))
4485                 return;
4486
4487         if (drm_dp_dpcd_read(&intel_dp->aux, DP_DP13_DPCD_REV,
4488                              &dpcd_ext, sizeof(dpcd_ext)) != sizeof(dpcd_ext)) {
4489                 drm_err(&i915->drm,
4490                         "DPCD failed read at extended capabilities\n");
4491                 return;
4492         }
4493
4494         if (intel_dp->dpcd[DP_DPCD_REV] > dpcd_ext[DP_DPCD_REV]) {
4495                 drm_dbg_kms(&i915->drm,
4496                             "DPCD extended DPCD rev less than base DPCD rev\n");
4497                 return;
4498         }
4499
4500         if (!memcmp(intel_dp->dpcd, dpcd_ext, sizeof(dpcd_ext)))
4501                 return;
4502
4503         drm_dbg_kms(&i915->drm, "Base DPCD: %*ph\n",
4504                     (int)sizeof(intel_dp->dpcd), intel_dp->dpcd);
4505
4506         memcpy(intel_dp->dpcd, dpcd_ext, sizeof(dpcd_ext));
4507 }
4508
4509 bool
4510 intel_dp_read_dpcd(struct intel_dp *intel_dp)
4511 {
4512         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
4513
4514         if (drm_dp_dpcd_read(&intel_dp->aux, 0x000, intel_dp->dpcd,
4515                              sizeof(intel_dp->dpcd)) < 0)
4516                 return false; /* aux transfer failed */
4517
4518         intel_dp_extended_receiver_capabilities(intel_dp);
4519
4520         drm_dbg_kms(&i915->drm, "DPCD: %*ph\n", (int)sizeof(intel_dp->dpcd),
4521                     intel_dp->dpcd);
4522
4523         return intel_dp->dpcd[DP_DPCD_REV] != 0;
4524 }
4525
4526 bool intel_dp_get_colorimetry_status(struct intel_dp *intel_dp)
4527 {
4528         u8 dprx = 0;
4529
4530         if (drm_dp_dpcd_readb(&intel_dp->aux, DP_DPRX_FEATURE_ENUMERATION_LIST,
4531                               &dprx) != 1)
4532                 return false;
4533         return dprx & DP_VSC_SDP_EXT_FOR_COLORIMETRY_SUPPORTED;
4534 }
4535
4536 static void intel_dp_get_dsc_sink_cap(struct intel_dp *intel_dp)
4537 {
4538         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
4539
4540         /*
4541          * Clear the cached register set to avoid using stale values
4542          * for the sinks that do not support DSC.
4543          */
4544         memset(intel_dp->dsc_dpcd, 0, sizeof(intel_dp->dsc_dpcd));
4545
4546         /* Clear fec_capable to avoid using stale values */
4547         intel_dp->fec_capable = 0;
4548
4549         /* Cache the DSC DPCD if eDP or DP rev >= 1.4 */
4550         if (intel_dp->dpcd[DP_DPCD_REV] >= 0x14 ||
4551             intel_dp->edp_dpcd[0] >= DP_EDP_14) {
4552                 if (drm_dp_dpcd_read(&intel_dp->aux, DP_DSC_SUPPORT,
4553                                      intel_dp->dsc_dpcd,
4554                                      sizeof(intel_dp->dsc_dpcd)) < 0)
4555                         drm_err(&i915->drm,
4556                                 "Failed to read DPCD register 0x%x\n",
4557                                 DP_DSC_SUPPORT);
4558
4559                 drm_dbg_kms(&i915->drm, "DSC DPCD: %*ph\n",
4560                             (int)sizeof(intel_dp->dsc_dpcd),
4561                             intel_dp->dsc_dpcd);
4562
4563                 /* FEC is supported only on DP 1.4 */
4564                 if (!intel_dp_is_edp(intel_dp) &&
4565                     drm_dp_dpcd_readb(&intel_dp->aux, DP_FEC_CAPABILITY,
4566                                       &intel_dp->fec_capable) < 0)
4567                         drm_err(&i915->drm,
4568                                 "Failed to read FEC DPCD register\n");
4569
4570                 drm_dbg_kms(&i915->drm, "FEC CAPABILITY: %x\n",
4571                             intel_dp->fec_capable);
4572         }
4573 }
4574
4575 static bool
4576 intel_edp_init_dpcd(struct intel_dp *intel_dp)
4577 {
4578         struct drm_i915_private *dev_priv =
4579                 to_i915(dp_to_dig_port(intel_dp)->base.base.dev);
4580
4581         /* this function is meant to be called only once */
4582         drm_WARN_ON(&dev_priv->drm, intel_dp->dpcd[DP_DPCD_REV] != 0);
4583
4584         if (!intel_dp_read_dpcd(intel_dp))
4585                 return false;
4586
4587         drm_dp_read_desc(&intel_dp->aux, &intel_dp->desc,
4588                          drm_dp_is_branch(intel_dp->dpcd));
4589
4590         /*
4591          * Read the eDP display control registers.
4592          *
4593          * Do this independent of DP_DPCD_DISPLAY_CONTROL_CAPABLE bit in
4594          * DP_EDP_CONFIGURATION_CAP, because some buggy displays do not have it
4595          * set, but require eDP 1.4+ detection (e.g. for supported link rates
4596          * method). The display control registers should read zero if they're
4597          * not supported anyway.
4598          */
4599         if (drm_dp_dpcd_read(&intel_dp->aux, DP_EDP_DPCD_REV,
4600                              intel_dp->edp_dpcd, sizeof(intel_dp->edp_dpcd)) ==
4601                              sizeof(intel_dp->edp_dpcd))
4602                 drm_dbg_kms(&dev_priv->drm, "eDP DPCD: %*ph\n",
4603                             (int)sizeof(intel_dp->edp_dpcd),
4604                             intel_dp->edp_dpcd);
4605
4606         /*
4607          * This has to be called after intel_dp->edp_dpcd is filled, PSR checks
4608          * for SET_POWER_CAPABLE bit in intel_dp->edp_dpcd[1]
4609          */
4610         intel_psr_init_dpcd(intel_dp);
4611
4612         /* Read the eDP 1.4+ supported link rates. */
4613         if (intel_dp->edp_dpcd[0] >= DP_EDP_14) {
4614                 __le16 sink_rates[DP_MAX_SUPPORTED_RATES];
4615                 int i;
4616
4617                 drm_dp_dpcd_read(&intel_dp->aux, DP_SUPPORTED_LINK_RATES,
4618                                 sink_rates, sizeof(sink_rates));
4619
4620                 for (i = 0; i < ARRAY_SIZE(sink_rates); i++) {
4621                         int val = le16_to_cpu(sink_rates[i]);
4622
4623                         if (val == 0)
4624                                 break;
4625
4626                         /* Value read multiplied by 200kHz gives the per-lane
4627                          * link rate in kHz. The source rates are, however,
4628                          * stored in terms of LS_Clk kHz. The full conversion
4629                          * back to symbols is
4630                          * (val * 200kHz)*(8/10 ch. encoding)*(1/8 bit to Byte)
4631                          */
4632                         intel_dp->sink_rates[i] = (val * 200) / 10;
4633                 }
4634                 intel_dp->num_sink_rates = i;
4635         }
4636
4637         /*
4638          * Use DP_LINK_RATE_SET if DP_SUPPORTED_LINK_RATES are available,
4639          * default to DP_MAX_LINK_RATE and DP_LINK_BW_SET otherwise.
4640          */
4641         if (intel_dp->num_sink_rates)
4642                 intel_dp->use_rate_select = true;
4643         else
4644                 intel_dp_set_sink_rates(intel_dp);
4645
4646         intel_dp_set_common_rates(intel_dp);
4647
4648         /* Read the eDP DSC DPCD registers */
4649         if (INTEL_GEN(dev_priv) >= 10 || IS_GEMINILAKE(dev_priv))
4650                 intel_dp_get_dsc_sink_cap(intel_dp);
4651
4652         return true;
4653 }
4654
4655
4656 static bool
4657 intel_dp_get_dpcd(struct intel_dp *intel_dp)
4658 {
4659         if (!intel_dp_read_dpcd(intel_dp))
4660                 return false;
4661
4662         /*
4663          * Don't clobber cached eDP rates. Also skip re-reading
4664          * the OUI/ID since we know it won't change.
4665          */
4666         if (!intel_dp_is_edp(intel_dp)) {
4667                 drm_dp_read_desc(&intel_dp->aux, &intel_dp->desc,
4668                                  drm_dp_is_branch(intel_dp->dpcd));
4669
4670                 intel_dp_set_sink_rates(intel_dp);
4671                 intel_dp_set_common_rates(intel_dp);
4672         }
4673
4674         /*
4675          * Some eDP panels do not set a valid value for sink count, that is why
4676          * it don't care about read it here and in intel_edp_init_dpcd().
4677          */
4678         if (!intel_dp_is_edp(intel_dp) &&
4679             !drm_dp_has_quirk(&intel_dp->desc, 0,
4680                               DP_DPCD_QUIRK_NO_SINK_COUNT)) {
4681                 u8 count;
4682                 ssize_t r;
4683
4684                 r = drm_dp_dpcd_readb(&intel_dp->aux, DP_SINK_COUNT, &count);
4685                 if (r < 1)
4686                         return false;
4687
4688                 /*
4689                  * Sink count can change between short pulse hpd hence
4690                  * a member variable in intel_dp will track any changes
4691                  * between short pulse interrupts.
4692                  */
4693                 intel_dp->sink_count = DP_GET_SINK_COUNT(count);
4694
4695                 /*
4696                  * SINK_COUNT == 0 and DOWNSTREAM_PORT_PRESENT == 1 implies that
4697                  * a dongle is present but no display. Unless we require to know
4698                  * if a dongle is present or not, we don't need to update
4699                  * downstream port information. So, an early return here saves
4700                  * time from performing other operations which are not required.
4701                  */
4702                 if (!intel_dp->sink_count)
4703                         return false;
4704         }
4705
4706         if (!drm_dp_is_branch(intel_dp->dpcd))
4707                 return true; /* native DP sink */
4708
4709         if (intel_dp->dpcd[DP_DPCD_REV] == 0x10)
4710                 return true; /* no per-port downstream info */
4711
4712         if (drm_dp_dpcd_read(&intel_dp->aux, DP_DOWNSTREAM_PORT_0,
4713                              intel_dp->downstream_ports,
4714                              DP_MAX_DOWNSTREAM_PORTS) < 0)
4715                 return false; /* downstream port status fetch failed */
4716
4717         return true;
4718 }
4719
4720 static bool
4721 intel_dp_sink_can_mst(struct intel_dp *intel_dp)
4722 {
4723         u8 mstm_cap;
4724
4725         if (intel_dp->dpcd[DP_DPCD_REV] < 0x12)
4726                 return false;
4727
4728         if (drm_dp_dpcd_readb(&intel_dp->aux, DP_MSTM_CAP, &mstm_cap) != 1)
4729                 return false;
4730
4731         return mstm_cap & DP_MST_CAP;
4732 }
4733
4734 static bool
4735 intel_dp_can_mst(struct intel_dp *intel_dp)
4736 {
4737         return i915_modparams.enable_dp_mst &&
4738                 intel_dp->can_mst &&
4739                 intel_dp_sink_can_mst(intel_dp);
4740 }
4741
4742 static void
4743 intel_dp_configure_mst(struct intel_dp *intel_dp)
4744 {
4745         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
4746         struct intel_encoder *encoder =
4747                 &dp_to_dig_port(intel_dp)->base;
4748         bool sink_can_mst = intel_dp_sink_can_mst(intel_dp);
4749
4750         drm_dbg_kms(&i915->drm,
4751                     "[ENCODER:%d:%s] MST support: port: %s, sink: %s, modparam: %s\n",
4752                     encoder->base.base.id, encoder->base.name,
4753                     yesno(intel_dp->can_mst), yesno(sink_can_mst),
4754                     yesno(i915_modparams.enable_dp_mst));
4755
4756         if (!intel_dp->can_mst)
4757                 return;
4758
4759         intel_dp->is_mst = sink_can_mst &&
4760                 i915_modparams.enable_dp_mst;
4761
4762         drm_dp_mst_topology_mgr_set_mst(&intel_dp->mst_mgr,
4763                                         intel_dp->is_mst);
4764 }
4765
4766 static bool
4767 intel_dp_get_sink_irq_esi(struct intel_dp *intel_dp, u8 *sink_irq_vector)
4768 {
4769         return drm_dp_dpcd_read(&intel_dp->aux, DP_SINK_COUNT_ESI,
4770                                 sink_irq_vector, DP_DPRX_ESI_LEN) ==
4771                 DP_DPRX_ESI_LEN;
4772 }
4773
4774 bool
4775 intel_dp_needs_vsc_sdp(const struct intel_crtc_state *crtc_state,
4776                        const struct drm_connector_state *conn_state)
4777 {
4778         /*
4779          * As per DP 1.4a spec section 2.2.4.3 [MSA Field for Indication
4780          * of Color Encoding Format and Content Color Gamut], in order to
4781          * sending YCBCR 420 or HDR BT.2020 signals we should use DP VSC SDP.
4782          */
4783         if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
4784                 return true;
4785
4786         switch (conn_state->colorspace) {
4787         case DRM_MODE_COLORIMETRY_SYCC_601:
4788         case DRM_MODE_COLORIMETRY_OPYCC_601:
4789         case DRM_MODE_COLORIMETRY_BT2020_YCC:
4790         case DRM_MODE_COLORIMETRY_BT2020_RGB:
4791         case DRM_MODE_COLORIMETRY_BT2020_CYCC:
4792                 return true;
4793         default:
4794                 break;
4795         }
4796
4797         return false;
4798 }
4799
4800 static ssize_t intel_dp_vsc_sdp_pack(const struct drm_dp_vsc_sdp *vsc,
4801                                      struct dp_sdp *sdp, size_t size)
4802 {
4803         size_t length = sizeof(struct dp_sdp);
4804
4805         if (size < length)
4806                 return -ENOSPC;
4807
4808         memset(sdp, 0, size);
4809
4810         /*
4811          * Prepare VSC Header for SU as per DP 1.4a spec, Table 2-119
4812          * VSC SDP Header Bytes
4813          */
4814         sdp->sdp_header.HB0 = 0; /* Secondary-Data Packet ID = 0 */
4815         sdp->sdp_header.HB1 = vsc->sdp_type; /* Secondary-data Packet Type */
4816         sdp->sdp_header.HB2 = vsc->revision; /* Revision Number */
4817         sdp->sdp_header.HB3 = vsc->length; /* Number of Valid Data Bytes */
4818
4819         /* VSC SDP Payload for DB16 through DB18 */
4820         /* Pixel Encoding and Colorimetry Formats  */
4821         sdp->db[16] = (vsc->pixelformat & 0xf) << 4; /* DB16[7:4] */
4822         sdp->db[16] |= vsc->colorimetry & 0xf; /* DB16[3:0] */
4823
4824         switch (vsc->bpc) {
4825         case 6:
4826                 /* 6bpc: 0x0 */
4827                 break;
4828         case 8:
4829                 sdp->db[17] = 0x1; /* DB17[3:0] */
4830                 break;
4831         case 10:
4832                 sdp->db[17] = 0x2;
4833                 break;
4834         case 12:
4835                 sdp->db[17] = 0x3;
4836                 break;
4837         case 16:
4838                 sdp->db[17] = 0x4;
4839                 break;
4840         default:
4841                 MISSING_CASE(vsc->bpc);
4842                 break;
4843         }
4844         /* Dynamic Range and Component Bit Depth */
4845         if (vsc->dynamic_range == DP_DYNAMIC_RANGE_CTA)
4846                 sdp->db[17] |= 0x80;  /* DB17[7] */
4847
4848         /* Content Type */
4849         sdp->db[18] = vsc->content_type & 0x7;
4850
4851         return length;
4852 }
4853
4854 static ssize_t
4855 intel_dp_hdr_metadata_infoframe_sdp_pack(const struct hdmi_drm_infoframe *drm_infoframe,
4856                                          struct dp_sdp *sdp,
4857                                          size_t size)
4858 {
4859         size_t length = sizeof(struct dp_sdp);
4860         const int infoframe_size = HDMI_INFOFRAME_HEADER_SIZE + HDMI_DRM_INFOFRAME_SIZE;
4861         unsigned char buf[HDMI_INFOFRAME_HEADER_SIZE + HDMI_DRM_INFOFRAME_SIZE];
4862         ssize_t len;
4863
4864         if (size < length)
4865                 return -ENOSPC;
4866
4867         memset(sdp, 0, size);
4868
4869         len = hdmi_drm_infoframe_pack_only(drm_infoframe, buf, sizeof(buf));
4870         if (len < 0) {
4871                 DRM_DEBUG_KMS("buffer size is smaller than hdr metadata infoframe\n");
4872                 return -ENOSPC;
4873         }
4874
4875         if (len != infoframe_size) {
4876                 DRM_DEBUG_KMS("wrong static hdr metadata size\n");
4877                 return -ENOSPC;
4878         }
4879
4880         /*
4881          * Set up the infoframe sdp packet for HDR static metadata.
4882          * Prepare VSC Header for SU as per DP 1.4a spec,
4883          * Table 2-100 and Table 2-101
4884          */
4885
4886         /* Secondary-Data Packet ID, 00h for non-Audio INFOFRAME */
4887         sdp->sdp_header.HB0 = 0;
4888         /*
4889          * Packet Type 80h + Non-audio INFOFRAME Type value
4890          * HDMI_INFOFRAME_TYPE_DRM: 0x87
4891          * - 80h + Non-audio INFOFRAME Type value
4892          * - InfoFrame Type: 0x07
4893          *    [CTA-861-G Table-42 Dynamic Range and Mastering InfoFrame]
4894          */
4895         sdp->sdp_header.HB1 = drm_infoframe->type;
4896         /*
4897          * Least Significant Eight Bits of (Data Byte Count – 1)
4898          * infoframe_size - 1
4899          */
4900         sdp->sdp_header.HB2 = 0x1D;
4901         /* INFOFRAME SDP Version Number */
4902         sdp->sdp_header.HB3 = (0x13 << 2);
4903         /* CTA Header Byte 2 (INFOFRAME Version Number) */
4904         sdp->db[0] = drm_infoframe->version;
4905         /* CTA Header Byte 3 (Length of INFOFRAME): HDMI_DRM_INFOFRAME_SIZE */
4906         sdp->db[1] = drm_infoframe->length;
4907         /*
4908          * Copy HDMI_DRM_INFOFRAME_SIZE size from a buffer after
4909          * HDMI_INFOFRAME_HEADER_SIZE
4910          */
4911         BUILD_BUG_ON(sizeof(sdp->db) < HDMI_DRM_INFOFRAME_SIZE + 2);
4912         memcpy(&sdp->db[2], &buf[HDMI_INFOFRAME_HEADER_SIZE],
4913                HDMI_DRM_INFOFRAME_SIZE);
4914
4915         /*
4916          * Size of DP infoframe sdp packet for HDR static metadata consists of
4917          * - DP SDP Header(struct dp_sdp_header): 4 bytes
4918          * - Two Data Blocks: 2 bytes
4919          *    CTA Header Byte2 (INFOFRAME Version Number)
4920          *    CTA Header Byte3 (Length of INFOFRAME)
4921          * - HDMI_DRM_INFOFRAME_SIZE: 26 bytes
4922          *
4923          * Prior to GEN11's GMP register size is identical to DP HDR static metadata
4924          * infoframe size. But GEN11+ has larger than that size, write_infoframe
4925          * will pad rest of the size.
4926          */
4927         return sizeof(struct dp_sdp_header) + 2 + HDMI_DRM_INFOFRAME_SIZE;
4928 }
4929
4930 static void intel_write_dp_sdp(struct intel_encoder *encoder,
4931                                const struct intel_crtc_state *crtc_state,
4932                                unsigned int type)
4933 {
4934         struct intel_digital_port *intel_dig_port = enc_to_dig_port(encoder);
4935         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
4936         struct dp_sdp sdp = {};
4937         ssize_t len;
4938
4939         if ((crtc_state->infoframes.enable &
4940              intel_hdmi_infoframe_enable(type)) == 0)
4941                 return;
4942
4943         switch (type) {
4944         case DP_SDP_VSC:
4945                 len = intel_dp_vsc_sdp_pack(&crtc_state->infoframes.vsc, &sdp,
4946                                             sizeof(sdp));
4947                 break;
4948         case HDMI_PACKET_TYPE_GAMUT_METADATA:
4949                 len = intel_dp_hdr_metadata_infoframe_sdp_pack(&crtc_state->infoframes.drm.drm,
4950                                                                &sdp, sizeof(sdp));
4951                 break;
4952         default:
4953                 MISSING_CASE(type);
4954                 return;
4955         }
4956
4957         if (drm_WARN_ON(&dev_priv->drm, len < 0))
4958                 return;
4959
4960         intel_dig_port->write_infoframe(encoder, crtc_state, type, &sdp, len);
4961 }
4962
4963 void intel_dp_set_infoframes(struct intel_encoder *encoder,
4964                              bool enable,
4965                              const struct intel_crtc_state *crtc_state,
4966                              const struct drm_connector_state *conn_state)
4967 {
4968         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
4969         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
4970         i915_reg_t reg = HSW_TVIDEO_DIP_CTL(crtc_state->cpu_transcoder);
4971         u32 dip_enable = VIDEO_DIP_ENABLE_AVI_HSW | VIDEO_DIP_ENABLE_GCP_HSW |
4972                          VIDEO_DIP_ENABLE_VS_HSW | VIDEO_DIP_ENABLE_GMP_HSW |
4973                          VIDEO_DIP_ENABLE_SPD_HSW | VIDEO_DIP_ENABLE_DRM_GLK;
4974         u32 val = intel_de_read(dev_priv, reg);
4975
4976         /* TODO: Add DSC case (DIP_ENABLE_PPS) */
4977         /* When PSR is enabled, this routine doesn't disable VSC DIP */
4978         if (intel_psr_enabled(intel_dp))
4979                 val &= ~dip_enable;
4980         else
4981                 val &= ~(dip_enable | VIDEO_DIP_ENABLE_VSC_HSW);
4982
4983         if (!enable) {
4984                 intel_de_write(dev_priv, reg, val);
4985                 intel_de_posting_read(dev_priv, reg);
4986                 return;
4987         }
4988
4989         intel_de_write(dev_priv, reg, val);
4990         intel_de_posting_read(dev_priv, reg);
4991
4992         /* When PSR is enabled, VSC SDP is handled by PSR routine */
4993         if (!intel_psr_enabled(intel_dp))
4994                 intel_write_dp_sdp(encoder, crtc_state, DP_SDP_VSC);
4995
4996         intel_write_dp_sdp(encoder, crtc_state, HDMI_PACKET_TYPE_GAMUT_METADATA);
4997 }
4998
4999 static void
5000 intel_dp_setup_vsc_sdp(struct intel_dp *intel_dp,
5001                        const struct intel_crtc_state *crtc_state,
5002                        const struct drm_connector_state *conn_state)
5003 {
5004         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
5005         struct dp_sdp vsc_sdp = {};
5006
5007         /* Prepare VSC Header for SU as per DP 1.4a spec, Table 2-119 */
5008         vsc_sdp.sdp_header.HB0 = 0;
5009         vsc_sdp.sdp_header.HB1 = 0x7;
5010
5011         /*
5012          * VSC SDP supporting 3D stereo, PSR2, and Pixel Encoding/
5013          * Colorimetry Format indication.
5014          */
5015         vsc_sdp.sdp_header.HB2 = 0x5;
5016
5017         /*
5018          * VSC SDP supporting 3D stereo, + PSR2, + Pixel Encoding/
5019          * Colorimetry Format indication (HB2 = 05h).
5020          */
5021         vsc_sdp.sdp_header.HB3 = 0x13;
5022
5023         /* DP 1.4a spec, Table 2-120 */
5024         switch (crtc_state->output_format) {
5025         case INTEL_OUTPUT_FORMAT_YCBCR444:
5026                 vsc_sdp.db[16] = 0x1 << 4; /* YCbCr 444 : DB16[7:4] = 1h */
5027                 break;
5028         case INTEL_OUTPUT_FORMAT_YCBCR420:
5029                 vsc_sdp.db[16] = 0x3 << 4; /* YCbCr 420 : DB16[7:4] = 3h */
5030                 break;
5031         case INTEL_OUTPUT_FORMAT_RGB:
5032         default:
5033                 /* RGB: DB16[7:4] = 0h */
5034                 break;
5035         }
5036
5037         switch (conn_state->colorspace) {
5038         case DRM_MODE_COLORIMETRY_BT709_YCC:
5039                 vsc_sdp.db[16] |= 0x1;
5040                 break;
5041         case DRM_MODE_COLORIMETRY_XVYCC_601:
5042                 vsc_sdp.db[16] |= 0x2;
5043                 break;
5044         case DRM_MODE_COLORIMETRY_XVYCC_709:
5045                 vsc_sdp.db[16] |= 0x3;
5046                 break;
5047         case DRM_MODE_COLORIMETRY_SYCC_601:
5048                 vsc_sdp.db[16] |= 0x4;
5049                 break;
5050         case DRM_MODE_COLORIMETRY_OPYCC_601:
5051                 vsc_sdp.db[16] |= 0x5;
5052                 break;
5053         case DRM_MODE_COLORIMETRY_BT2020_CYCC:
5054         case DRM_MODE_COLORIMETRY_BT2020_RGB:
5055                 vsc_sdp.db[16] |= 0x6;
5056                 break;
5057         case DRM_MODE_COLORIMETRY_BT2020_YCC:
5058                 vsc_sdp.db[16] |= 0x7;
5059                 break;
5060         case DRM_MODE_COLORIMETRY_DCI_P3_RGB_D65:
5061         case DRM_MODE_COLORIMETRY_DCI_P3_RGB_THEATER:
5062                 vsc_sdp.db[16] |= 0x4; /* DCI-P3 (SMPTE RP 431-2) */
5063                 break;
5064         default:
5065                 /* sRGB (IEC 61966-2-1) / ITU-R BT.601: DB16[0:3] = 0h */
5066
5067                 /* RGB->YCBCR color conversion uses the BT.709 color space. */
5068                 if (crtc_state->output_format == INTEL_OUTPUT_FORMAT_YCBCR420)
5069                         vsc_sdp.db[16] |= 0x1; /* 0x1, ITU-R BT.709 */
5070                 break;
5071         }
5072
5073         /*
5074          * For pixel encoding formats YCbCr444, YCbCr422, YCbCr420, and Y Only,
5075          * the following Component Bit Depth values are defined:
5076          * 001b = 8bpc.
5077          * 010b = 10bpc.
5078          * 011b = 12bpc.
5079          * 100b = 16bpc.
5080          */
5081         switch (crtc_state->pipe_bpp) {
5082         case 24: /* 8bpc */
5083                 vsc_sdp.db[17] = 0x1;
5084                 break;
5085         case 30: /* 10bpc */
5086                 vsc_sdp.db[17] = 0x2;
5087                 break;
5088         case 36: /* 12bpc */
5089                 vsc_sdp.db[17] = 0x3;
5090                 break;
5091         case 48: /* 16bpc */
5092                 vsc_sdp.db[17] = 0x4;
5093                 break;
5094         default:
5095                 MISSING_CASE(crtc_state->pipe_bpp);
5096                 break;
5097         }
5098
5099         /*
5100          * Dynamic Range (Bit 7)
5101          * 0 = VESA range, 1 = CTA range.
5102          * all YCbCr are always limited range
5103          */
5104         vsc_sdp.db[17] |= 0x80;
5105
5106         /*
5107          * Content Type (Bits 2:0)
5108          * 000b = Not defined.
5109          * 001b = Graphics.
5110          * 010b = Photo.
5111          * 011b = Video.
5112          * 100b = Game
5113          * All other values are RESERVED.
5114          * Note: See CTA-861-G for the definition and expected
5115          * processing by a stream sink for the above contect types.
5116          */
5117         vsc_sdp.db[18] = 0;
5118
5119         intel_dig_port->write_infoframe(&intel_dig_port->base,
5120                         crtc_state, DP_SDP_VSC, &vsc_sdp, sizeof(vsc_sdp));
5121 }
5122
5123 static void
5124 intel_dp_setup_hdr_metadata_infoframe_sdp(struct intel_dp *intel_dp,
5125                                           const struct intel_crtc_state *crtc_state,
5126                                           const struct drm_connector_state *conn_state)
5127 {
5128         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5129         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
5130         struct dp_sdp infoframe_sdp = {};
5131         struct hdmi_drm_infoframe drm_infoframe = {};
5132         const int infoframe_size = HDMI_INFOFRAME_HEADER_SIZE + HDMI_DRM_INFOFRAME_SIZE;
5133         unsigned char buf[HDMI_INFOFRAME_HEADER_SIZE + HDMI_DRM_INFOFRAME_SIZE];
5134         ssize_t len;
5135         int ret;
5136
5137         ret = drm_hdmi_infoframe_set_hdr_metadata(&drm_infoframe, conn_state);
5138         if (ret) {
5139                 drm_dbg_kms(&i915->drm,
5140                             "couldn't set HDR metadata in infoframe\n");
5141                 return;
5142         }
5143
5144         len = hdmi_drm_infoframe_pack_only(&drm_infoframe, buf, sizeof(buf));
5145         if (len < 0) {
5146                 drm_dbg_kms(&i915->drm,
5147                             "buffer size is smaller than hdr metadata infoframe\n");
5148                 return;
5149         }
5150
5151         if (len != infoframe_size) {
5152                 drm_dbg_kms(&i915->drm, "wrong static hdr metadata size\n");
5153                 return;
5154         }
5155
5156         /*
5157          * Set up the infoframe sdp packet for HDR static metadata.
5158          * Prepare VSC Header for SU as per DP 1.4a spec,
5159          * Table 2-100 and Table 2-101
5160          */
5161
5162         /* Packet ID, 00h for non-Audio INFOFRAME */
5163         infoframe_sdp.sdp_header.HB0 = 0;
5164         /*
5165          * Packet Type 80h + Non-audio INFOFRAME Type value
5166          * HDMI_INFOFRAME_TYPE_DRM: 0x87,
5167          */
5168         infoframe_sdp.sdp_header.HB1 = drm_infoframe.type;
5169         /*
5170          * Least Significant Eight Bits of (Data Byte Count – 1)
5171          * infoframe_size - 1,
5172          */
5173         infoframe_sdp.sdp_header.HB2 = 0x1D;
5174         /* INFOFRAME SDP Version Number */
5175         infoframe_sdp.sdp_header.HB3 = (0x13 << 2);
5176         /* CTA Header Byte 2 (INFOFRAME Version Number) */
5177         infoframe_sdp.db[0] = drm_infoframe.version;
5178         /* CTA Header Byte 3 (Length of INFOFRAME): HDMI_DRM_INFOFRAME_SIZE */
5179         infoframe_sdp.db[1] = drm_infoframe.length;
5180         /*
5181          * Copy HDMI_DRM_INFOFRAME_SIZE size from a buffer after
5182          * HDMI_INFOFRAME_HEADER_SIZE
5183          */
5184         BUILD_BUG_ON(sizeof(infoframe_sdp.db) < HDMI_DRM_INFOFRAME_SIZE + 2);
5185         memcpy(&infoframe_sdp.db[2], &buf[HDMI_INFOFRAME_HEADER_SIZE],
5186                HDMI_DRM_INFOFRAME_SIZE);
5187
5188         /*
5189          * Size of DP infoframe sdp packet for HDR static metadata is consist of
5190          * - DP SDP Header(struct dp_sdp_header): 4 bytes
5191          * - Two Data Blocks: 2 bytes
5192          *    CTA Header Byte2 (INFOFRAME Version Number)
5193          *    CTA Header Byte3 (Length of INFOFRAME)
5194          * - HDMI_DRM_INFOFRAME_SIZE: 26 bytes
5195          *
5196          * Prior to GEN11's GMP register size is identical to DP HDR static metadata
5197          * infoframe size. But GEN11+ has larger than that size, write_infoframe
5198          * will pad rest of the size.
5199          */
5200         intel_dig_port->write_infoframe(&intel_dig_port->base, crtc_state,
5201                                         HDMI_PACKET_TYPE_GAMUT_METADATA,
5202                                         &infoframe_sdp,
5203                                         sizeof(struct dp_sdp_header) + 2 + HDMI_DRM_INFOFRAME_SIZE);
5204 }
5205
5206 void intel_dp_vsc_enable(struct intel_dp *intel_dp,
5207                          const struct intel_crtc_state *crtc_state,
5208                          const struct drm_connector_state *conn_state)
5209 {
5210         if (!intel_dp_needs_vsc_sdp(crtc_state, conn_state))
5211                 return;
5212
5213         intel_dp_setup_vsc_sdp(intel_dp, crtc_state, conn_state);
5214 }
5215
5216 void intel_dp_hdr_metadata_enable(struct intel_dp *intel_dp,
5217                                   const struct intel_crtc_state *crtc_state,
5218                                   const struct drm_connector_state *conn_state)
5219 {
5220         if (!conn_state->hdr_output_metadata)
5221                 return;
5222
5223         intel_dp_setup_hdr_metadata_infoframe_sdp(intel_dp,
5224                                                   crtc_state,
5225                                                   conn_state);
5226 }
5227
5228 static u8 intel_dp_autotest_link_training(struct intel_dp *intel_dp)
5229 {
5230         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5231         int status = 0;
5232         int test_link_rate;
5233         u8 test_lane_count, test_link_bw;
5234         /* (DP CTS 1.2)
5235          * 4.3.1.11
5236          */
5237         /* Read the TEST_LANE_COUNT and TEST_LINK_RTAE fields (DP CTS 3.1.4) */
5238         status = drm_dp_dpcd_readb(&intel_dp->aux, DP_TEST_LANE_COUNT,
5239                                    &test_lane_count);
5240
5241         if (status <= 0) {
5242                 drm_dbg_kms(&i915->drm, "Lane count read failed\n");
5243                 return DP_TEST_NAK;
5244         }
5245         test_lane_count &= DP_MAX_LANE_COUNT_MASK;
5246
5247         status = drm_dp_dpcd_readb(&intel_dp->aux, DP_TEST_LINK_RATE,
5248                                    &test_link_bw);
5249         if (status <= 0) {
5250                 drm_dbg_kms(&i915->drm, "Link Rate read failed\n");
5251                 return DP_TEST_NAK;
5252         }
5253         test_link_rate = drm_dp_bw_code_to_link_rate(test_link_bw);
5254
5255         /* Validate the requested link rate and lane count */
5256         if (!intel_dp_link_params_valid(intel_dp, test_link_rate,
5257                                         test_lane_count))
5258                 return DP_TEST_NAK;
5259
5260         intel_dp->compliance.test_lane_count = test_lane_count;
5261         intel_dp->compliance.test_link_rate = test_link_rate;
5262
5263         return DP_TEST_ACK;
5264 }
5265
5266 static u8 intel_dp_autotest_video_pattern(struct intel_dp *intel_dp)
5267 {
5268         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5269         u8 test_pattern;
5270         u8 test_misc;
5271         __be16 h_width, v_height;
5272         int status = 0;
5273
5274         /* Read the TEST_PATTERN (DP CTS 3.1.5) */
5275         status = drm_dp_dpcd_readb(&intel_dp->aux, DP_TEST_PATTERN,
5276                                    &test_pattern);
5277         if (status <= 0) {
5278                 drm_dbg_kms(&i915->drm, "Test pattern read failed\n");
5279                 return DP_TEST_NAK;
5280         }
5281         if (test_pattern != DP_COLOR_RAMP)
5282                 return DP_TEST_NAK;
5283
5284         status = drm_dp_dpcd_read(&intel_dp->aux, DP_TEST_H_WIDTH_HI,
5285                                   &h_width, 2);
5286         if (status <= 0) {
5287                 drm_dbg_kms(&i915->drm, "H Width read failed\n");
5288                 return DP_TEST_NAK;
5289         }
5290
5291         status = drm_dp_dpcd_read(&intel_dp->aux, DP_TEST_V_HEIGHT_HI,
5292                                   &v_height, 2);
5293         if (status <= 0) {
5294                 drm_dbg_kms(&i915->drm, "V Height read failed\n");
5295                 return DP_TEST_NAK;
5296         }
5297
5298         status = drm_dp_dpcd_readb(&intel_dp->aux, DP_TEST_MISC0,
5299                                    &test_misc);
5300         if (status <= 0) {
5301                 drm_dbg_kms(&i915->drm, "TEST MISC read failed\n");
5302                 return DP_TEST_NAK;
5303         }
5304         if ((test_misc & DP_TEST_COLOR_FORMAT_MASK) != DP_COLOR_FORMAT_RGB)
5305                 return DP_TEST_NAK;
5306         if (test_misc & DP_TEST_DYNAMIC_RANGE_CEA)
5307                 return DP_TEST_NAK;
5308         switch (test_misc & DP_TEST_BIT_DEPTH_MASK) {
5309         case DP_TEST_BIT_DEPTH_6:
5310                 intel_dp->compliance.test_data.bpc = 6;
5311                 break;
5312         case DP_TEST_BIT_DEPTH_8:
5313                 intel_dp->compliance.test_data.bpc = 8;
5314                 break;
5315         default:
5316                 return DP_TEST_NAK;
5317         }
5318
5319         intel_dp->compliance.test_data.video_pattern = test_pattern;
5320         intel_dp->compliance.test_data.hdisplay = be16_to_cpu(h_width);
5321         intel_dp->compliance.test_data.vdisplay = be16_to_cpu(v_height);
5322         /* Set test active flag here so userspace doesn't interrupt things */
5323         intel_dp->compliance.test_active = true;
5324
5325         return DP_TEST_ACK;
5326 }
5327
5328 static u8 intel_dp_autotest_edid(struct intel_dp *intel_dp)
5329 {
5330         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5331         u8 test_result = DP_TEST_ACK;
5332         struct intel_connector *intel_connector = intel_dp->attached_connector;
5333         struct drm_connector *connector = &intel_connector->base;
5334
5335         if (intel_connector->detect_edid == NULL ||
5336             connector->edid_corrupt ||
5337             intel_dp->aux.i2c_defer_count > 6) {
5338                 /* Check EDID read for NACKs, DEFERs and corruption
5339                  * (DP CTS 1.2 Core r1.1)
5340                  *    4.2.2.4 : Failed EDID read, I2C_NAK
5341                  *    4.2.2.5 : Failed EDID read, I2C_DEFER
5342                  *    4.2.2.6 : EDID corruption detected
5343                  * Use failsafe mode for all cases
5344                  */
5345                 if (intel_dp->aux.i2c_nack_count > 0 ||
5346                         intel_dp->aux.i2c_defer_count > 0)
5347                         drm_dbg_kms(&i915->drm,
5348                                     "EDID read had %d NACKs, %d DEFERs\n",
5349                                     intel_dp->aux.i2c_nack_count,
5350                                     intel_dp->aux.i2c_defer_count);
5351                 intel_dp->compliance.test_data.edid = INTEL_DP_RESOLUTION_FAILSAFE;
5352         } else {
5353                 struct edid *block = intel_connector->detect_edid;
5354
5355                 /* We have to write the checksum
5356                  * of the last block read
5357                  */
5358                 block += intel_connector->detect_edid->extensions;
5359
5360                 if (drm_dp_dpcd_writeb(&intel_dp->aux, DP_TEST_EDID_CHECKSUM,
5361                                        block->checksum) <= 0)
5362                         drm_dbg_kms(&i915->drm,
5363                                     "Failed to write EDID checksum\n");
5364
5365                 test_result = DP_TEST_ACK | DP_TEST_EDID_CHECKSUM_WRITE;
5366                 intel_dp->compliance.test_data.edid = INTEL_DP_RESOLUTION_PREFERRED;
5367         }
5368
5369         /* Set test active flag here so userspace doesn't interrupt things */
5370         intel_dp->compliance.test_active = true;
5371
5372         return test_result;
5373 }
5374
5375 static u8 intel_dp_prepare_phytest(struct intel_dp *intel_dp)
5376 {
5377         struct drm_dp_phy_test_params *data =
5378                 &intel_dp->compliance.test_data.phytest;
5379
5380         if (drm_dp_get_phy_test_pattern(&intel_dp->aux, data)) {
5381                 DRM_DEBUG_KMS("DP Phy Test pattern AUX read failure\n");
5382                 return DP_TEST_NAK;
5383         }
5384
5385         /*
5386          * link_mst is set to false to avoid executing mst related code
5387          * during compliance testing.
5388          */
5389         intel_dp->link_mst = false;
5390
5391         return DP_TEST_ACK;
5392 }
5393
5394 static void intel_dp_phy_pattern_update(struct intel_dp *intel_dp)
5395 {
5396         struct drm_i915_private *dev_priv =
5397                         to_i915(dp_to_dig_port(intel_dp)->base.base.dev);
5398         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
5399         struct drm_dp_phy_test_params *data =
5400                         &intel_dp->compliance.test_data.phytest;
5401         struct intel_crtc *crtc = to_intel_crtc(intel_dig_port->base.base.crtc);
5402         enum pipe pipe = crtc->pipe;
5403         u32 pattern_val;
5404
5405         switch (data->phy_pattern) {
5406         case DP_PHY_TEST_PATTERN_NONE:
5407                 DRM_DEBUG_KMS("Disable Phy Test Pattern\n");
5408                 intel_de_write(dev_priv, DDI_DP_COMP_CTL(pipe), 0x0);
5409                 break;
5410         case DP_PHY_TEST_PATTERN_D10_2:
5411                 DRM_DEBUG_KMS("Set D10.2 Phy Test Pattern\n");
5412                 intel_de_write(dev_priv, DDI_DP_COMP_CTL(pipe),
5413                                DDI_DP_COMP_CTL_ENABLE | DDI_DP_COMP_CTL_D10_2);
5414                 break;
5415         case DP_PHY_TEST_PATTERN_ERROR_COUNT:
5416                 DRM_DEBUG_KMS("Set Error Count Phy Test Pattern\n");
5417                 intel_de_write(dev_priv, DDI_DP_COMP_CTL(pipe),
5418                                DDI_DP_COMP_CTL_ENABLE |
5419                                DDI_DP_COMP_CTL_SCRAMBLED_0);
5420                 break;
5421         case DP_PHY_TEST_PATTERN_PRBS7:
5422                 DRM_DEBUG_KMS("Set PRBS7 Phy Test Pattern\n");
5423                 intel_de_write(dev_priv, DDI_DP_COMP_CTL(pipe),
5424                                DDI_DP_COMP_CTL_ENABLE | DDI_DP_COMP_CTL_PRBS7);
5425                 break;
5426         case DP_PHY_TEST_PATTERN_80BIT_CUSTOM:
5427                 /*
5428                  * FIXME: Ideally pattern should come from DPCD 0x250. As
5429                  * current firmware of DPR-100 could not set it, so hardcoding
5430                  * now for complaince test.
5431                  */
5432                 DRM_DEBUG_KMS("Set 80Bit Custom Phy Test Pattern 0x3e0f83e0 0x0f83e0f8 0x0000f83e\n");
5433                 pattern_val = 0x3e0f83e0;
5434                 intel_de_write(dev_priv, DDI_DP_COMP_PAT(pipe, 0), pattern_val);
5435                 pattern_val = 0x0f83e0f8;
5436                 intel_de_write(dev_priv, DDI_DP_COMP_PAT(pipe, 1), pattern_val);
5437                 pattern_val = 0x0000f83e;
5438                 intel_de_write(dev_priv, DDI_DP_COMP_PAT(pipe, 2), pattern_val);
5439                 intel_de_write(dev_priv, DDI_DP_COMP_CTL(pipe),
5440                                DDI_DP_COMP_CTL_ENABLE |
5441                                DDI_DP_COMP_CTL_CUSTOM80);
5442                 break;
5443         case DP_PHY_TEST_PATTERN_CP2520:
5444                 /*
5445                  * FIXME: Ideally pattern should come from DPCD 0x24A. As
5446                  * current firmware of DPR-100 could not set it, so hardcoding
5447                  * now for complaince test.
5448                  */
5449                 DRM_DEBUG_KMS("Set HBR2 compliance Phy Test Pattern\n");
5450                 pattern_val = 0xFB;
5451                 intel_de_write(dev_priv, DDI_DP_COMP_CTL(pipe),
5452                                DDI_DP_COMP_CTL_ENABLE | DDI_DP_COMP_CTL_HBR2 |
5453                                pattern_val);
5454                 break;
5455         default:
5456                 WARN(1, "Invalid Phy Test Pattern\n");
5457         }
5458 }
5459
5460 static void
5461 intel_dp_autotest_phy_ddi_disable(struct intel_dp *intel_dp)
5462 {
5463         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
5464         struct drm_device *dev = intel_dig_port->base.base.dev;
5465         struct drm_i915_private *dev_priv = to_i915(dev);
5466         struct intel_crtc *crtc = to_intel_crtc(intel_dig_port->base.base.crtc);
5467         enum pipe pipe = crtc->pipe;
5468         u32 trans_ddi_func_ctl_value, trans_conf_value, dp_tp_ctl_value;
5469
5470         trans_ddi_func_ctl_value = intel_de_read(dev_priv,
5471                                                  TRANS_DDI_FUNC_CTL(pipe));
5472         trans_conf_value = intel_de_read(dev_priv, PIPECONF(pipe));
5473         dp_tp_ctl_value = intel_de_read(dev_priv, TGL_DP_TP_CTL(pipe));
5474
5475         trans_ddi_func_ctl_value &= ~(TRANS_DDI_FUNC_ENABLE |
5476                                       TGL_TRANS_DDI_PORT_MASK);
5477         trans_conf_value &= ~PIPECONF_ENABLE;
5478         dp_tp_ctl_value &= ~DP_TP_CTL_ENABLE;
5479
5480         intel_de_write(dev_priv, PIPECONF(pipe), trans_conf_value);
5481         intel_de_write(dev_priv, TRANS_DDI_FUNC_CTL(pipe),
5482                        trans_ddi_func_ctl_value);
5483         intel_de_write(dev_priv, TGL_DP_TP_CTL(pipe), dp_tp_ctl_value);
5484 }
5485
5486 static void
5487 intel_dp_autotest_phy_ddi_enable(struct intel_dp *intel_dp, uint8_t lane_cnt)
5488 {
5489         struct intel_digital_port *intel_dig_port = dp_to_dig_port(intel_dp);
5490         struct drm_device *dev = intel_dig_port->base.base.dev;
5491         struct drm_i915_private *dev_priv = to_i915(dev);
5492         enum port port = intel_dig_port->base.port;
5493         struct intel_crtc *crtc = to_intel_crtc(intel_dig_port->base.base.crtc);
5494         enum pipe pipe = crtc->pipe;
5495         u32 trans_ddi_func_ctl_value, trans_conf_value, dp_tp_ctl_value;
5496
5497         trans_ddi_func_ctl_value = intel_de_read(dev_priv,
5498                                                  TRANS_DDI_FUNC_CTL(pipe));
5499         trans_conf_value = intel_de_read(dev_priv, PIPECONF(pipe));
5500         dp_tp_ctl_value = intel_de_read(dev_priv, TGL_DP_TP_CTL(pipe));
5501
5502         trans_ddi_func_ctl_value |= TRANS_DDI_FUNC_ENABLE |
5503                                     TGL_TRANS_DDI_SELECT_PORT(port);
5504         trans_conf_value |= PIPECONF_ENABLE;
5505         dp_tp_ctl_value |= DP_TP_CTL_ENABLE;
5506
5507         intel_de_write(dev_priv, PIPECONF(pipe), trans_conf_value);
5508         intel_de_write(dev_priv, TGL_DP_TP_CTL(pipe), dp_tp_ctl_value);
5509         intel_de_write(dev_priv, TRANS_DDI_FUNC_CTL(pipe),
5510                        trans_ddi_func_ctl_value);
5511 }
5512
5513 void intel_dp_process_phy_request(struct intel_dp *intel_dp)
5514 {
5515         struct drm_dp_phy_test_params *data =
5516                 &intel_dp->compliance.test_data.phytest;
5517         u8 link_status[DP_LINK_STATUS_SIZE];
5518
5519         if (!intel_dp_get_link_status(intel_dp, link_status)) {
5520                 DRM_DEBUG_KMS("failed to get link status\n");
5521                 return;
5522         }
5523
5524         /* retrieve vswing & pre-emphasis setting */
5525         intel_dp_get_adjust_train(intel_dp, link_status);
5526
5527         intel_dp_autotest_phy_ddi_disable(intel_dp);
5528
5529         intel_dp_set_signal_levels(intel_dp);
5530
5531         intel_dp_phy_pattern_update(intel_dp);
5532
5533         intel_dp_autotest_phy_ddi_enable(intel_dp, data->num_lanes);
5534
5535         drm_dp_set_phy_test_pattern(&intel_dp->aux, data,
5536                                     link_status[DP_DPCD_REV]);
5537 }
5538
5539 static u8 intel_dp_autotest_phy_pattern(struct intel_dp *intel_dp)
5540 {
5541         u8 test_result;
5542
5543         test_result = intel_dp_prepare_phytest(intel_dp);
5544         if (test_result != DP_TEST_ACK)
5545                 DRM_ERROR("Phy test preparation failed\n");
5546
5547         intel_dp_process_phy_request(intel_dp);
5548
5549         return test_result;
5550 }
5551
5552 static void intel_dp_handle_test_request(struct intel_dp *intel_dp)
5553 {
5554         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5555         u8 response = DP_TEST_NAK;
5556         u8 request = 0;
5557         int status;
5558
5559         status = drm_dp_dpcd_readb(&intel_dp->aux, DP_TEST_REQUEST, &request);
5560         if (status <= 0) {
5561                 drm_dbg_kms(&i915->drm,
5562                             "Could not read test request from sink\n");
5563                 goto update_status;
5564         }
5565
5566         switch (request) {
5567         case DP_TEST_LINK_TRAINING:
5568                 drm_dbg_kms(&i915->drm, "LINK_TRAINING test requested\n");
5569                 response = intel_dp_autotest_link_training(intel_dp);
5570                 break;
5571         case DP_TEST_LINK_VIDEO_PATTERN:
5572                 drm_dbg_kms(&i915->drm, "TEST_PATTERN test requested\n");
5573                 response = intel_dp_autotest_video_pattern(intel_dp);
5574                 break;
5575         case DP_TEST_LINK_EDID_READ:
5576                 drm_dbg_kms(&i915->drm, "EDID test requested\n");
5577                 response = intel_dp_autotest_edid(intel_dp);
5578                 break;
5579         case DP_TEST_LINK_PHY_TEST_PATTERN:
5580                 drm_dbg_kms(&i915->drm, "PHY_PATTERN test requested\n");
5581                 response = intel_dp_autotest_phy_pattern(intel_dp);
5582                 break;
5583         default:
5584                 drm_dbg_kms(&i915->drm, "Invalid test request '%02x'\n",
5585                             request);
5586                 break;
5587         }
5588
5589         if (response & DP_TEST_ACK)
5590                 intel_dp->compliance.test_type = request;
5591
5592 update_status:
5593         status = drm_dp_dpcd_writeb(&intel_dp->aux, DP_TEST_RESPONSE, response);
5594         if (status <= 0)
5595                 drm_dbg_kms(&i915->drm,
5596                             "Could not write test response to sink\n");
5597 }
5598
5599 static int
5600 intel_dp_check_mst_status(struct intel_dp *intel_dp)
5601 {
5602         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5603         bool need_retrain = false;
5604
5605         if (!intel_dp->is_mst)
5606                 return -EINVAL;
5607
5608         WARN_ON_ONCE(intel_dp->active_mst_links < 0);
5609
5610         for (;;) {
5611                 u8 esi[DP_DPRX_ESI_LEN] = {};
5612                 bool bret, handled;
5613                 int retry;
5614
5615                 bret = intel_dp_get_sink_irq_esi(intel_dp, esi);
5616                 if (!bret) {
5617                         drm_dbg_kms(&i915->drm,
5618                                     "failed to get ESI - device may have failed\n");
5619                         return -EINVAL;
5620                 }
5621
5622                 /* check link status - esi[10] = 0x200c */
5623                 if (intel_dp->active_mst_links > 0 && !need_retrain &&
5624                     !drm_dp_channel_eq_ok(&esi[10], intel_dp->lane_count)) {
5625                         drm_dbg_kms(&i915->drm,
5626                                     "channel EQ not ok, retraining\n");
5627                         need_retrain = true;
5628                 }
5629
5630                 drm_dbg_kms(&i915->drm, "got esi %3ph\n", esi);
5631
5632                 drm_dp_mst_hpd_irq(&intel_dp->mst_mgr, esi, &handled);
5633                 if (!handled)
5634                         break;
5635
5636                 for (retry = 0; retry < 3; retry++) {
5637                         int wret;
5638
5639                         wret = drm_dp_dpcd_write(&intel_dp->aux,
5640                                                  DP_SINK_COUNT_ESI+1,
5641                                                  &esi[1], 3);
5642                         if (wret == 3)
5643                                 break;
5644                 }
5645         }
5646
5647         return need_retrain;
5648 }
5649
5650 static bool
5651 intel_dp_needs_link_retrain(struct intel_dp *intel_dp)
5652 {
5653         u8 link_status[DP_LINK_STATUS_SIZE];
5654
5655         if (!intel_dp->link_trained)
5656                 return false;
5657
5658         /*
5659          * While PSR source HW is enabled, it will control main-link sending
5660          * frames, enabling and disabling it so trying to do a retrain will fail
5661          * as the link would or not be on or it could mix training patterns
5662          * and frame data at the same time causing retrain to fail.
5663          * Also when exiting PSR, HW will retrain the link anyways fixing
5664          * any link status error.
5665          */
5666         if (intel_psr_enabled(intel_dp))
5667                 return false;
5668
5669         if (!intel_dp_get_link_status(intel_dp, link_status))
5670                 return false;
5671
5672         /*
5673          * Validate the cached values of intel_dp->link_rate and
5674          * intel_dp->lane_count before attempting to retrain.
5675          */
5676         if (!intel_dp_link_params_valid(intel_dp, intel_dp->link_rate,
5677                                         intel_dp->lane_count))
5678                 return false;
5679
5680         /* Retrain if Channel EQ or CR not ok */
5681         return !drm_dp_channel_eq_ok(link_status, intel_dp->lane_count);
5682 }
5683
5684 static bool intel_dp_has_connector(struct intel_dp *intel_dp,
5685                                    const struct drm_connector_state *conn_state)
5686 {
5687         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5688         struct intel_encoder *encoder;
5689         enum pipe pipe;
5690
5691         if (!conn_state->best_encoder)
5692                 return false;
5693
5694         /* SST */
5695         encoder = &dp_to_dig_port(intel_dp)->base;
5696         if (conn_state->best_encoder == &encoder->base)
5697                 return true;
5698
5699         /* MST */
5700         for_each_pipe(i915, pipe) {
5701                 encoder = &intel_dp->mst_encoders[pipe]->base;
5702                 if (conn_state->best_encoder == &encoder->base)
5703                         return true;
5704         }
5705
5706         return false;
5707 }
5708
5709 static int intel_dp_prep_link_retrain(struct intel_dp *intel_dp,
5710                                       struct drm_modeset_acquire_ctx *ctx,
5711                                       u32 *crtc_mask)
5712 {
5713         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5714         struct drm_connector_list_iter conn_iter;
5715         struct intel_connector *connector;
5716         int ret = 0;
5717
5718         *crtc_mask = 0;
5719
5720         if (!intel_dp_needs_link_retrain(intel_dp))
5721                 return 0;
5722
5723         drm_connector_list_iter_begin(&i915->drm, &conn_iter);
5724         for_each_intel_connector_iter(connector, &conn_iter) {
5725                 struct drm_connector_state *conn_state =
5726                         connector->base.state;
5727                 struct intel_crtc_state *crtc_state;
5728                 struct intel_crtc *crtc;
5729
5730                 if (!intel_dp_has_connector(intel_dp, conn_state))
5731                         continue;
5732
5733                 crtc = to_intel_crtc(conn_state->crtc);
5734                 if (!crtc)
5735                         continue;
5736
5737                 ret = drm_modeset_lock(&crtc->base.mutex, ctx);
5738                 if (ret)
5739                         break;
5740
5741                 crtc_state = to_intel_crtc_state(crtc->base.state);
5742
5743                 drm_WARN_ON(&i915->drm, !intel_crtc_has_dp_encoder(crtc_state));
5744
5745                 if (!crtc_state->hw.active)
5746                         continue;
5747
5748                 if (conn_state->commit &&
5749                     !try_wait_for_completion(&conn_state->commit->hw_done))
5750                         continue;
5751
5752                 *crtc_mask |= drm_crtc_mask(&crtc->base);
5753         }
5754         drm_connector_list_iter_end(&conn_iter);
5755
5756         if (!intel_dp_needs_link_retrain(intel_dp))
5757                 *crtc_mask = 0;
5758
5759         return ret;
5760 }
5761
5762 static bool intel_dp_is_connected(struct intel_dp *intel_dp)
5763 {
5764         struct intel_connector *connector = intel_dp->attached_connector;
5765
5766         return connector->base.status == connector_status_connected ||
5767                 intel_dp->is_mst;
5768 }
5769
5770 int intel_dp_retrain_link(struct intel_encoder *encoder,
5771                           struct drm_modeset_acquire_ctx *ctx)
5772 {
5773         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
5774         struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
5775         struct intel_crtc *crtc;
5776         u32 crtc_mask;
5777         int ret;
5778
5779         if (!intel_dp_is_connected(intel_dp))
5780                 return 0;
5781
5782         ret = drm_modeset_lock(&dev_priv->drm.mode_config.connection_mutex,
5783                                ctx);
5784         if (ret)
5785                 return ret;
5786
5787         ret = intel_dp_prep_link_retrain(intel_dp, ctx, &crtc_mask);
5788         if (ret)
5789                 return ret;
5790
5791         if (crtc_mask == 0)
5792                 return 0;
5793
5794         drm_dbg_kms(&dev_priv->drm, "[ENCODER:%d:%s] retraining link\n",
5795                     encoder->base.base.id, encoder->base.name);
5796
5797         for_each_intel_crtc_mask(&dev_priv->drm, crtc, crtc_mask) {
5798                 const struct intel_crtc_state *crtc_state =
5799                         to_intel_crtc_state(crtc->base.state);
5800
5801                 /* Suppress underruns caused by re-training */
5802                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, false);
5803                 if (crtc_state->has_pch_encoder)
5804                         intel_set_pch_fifo_underrun_reporting(dev_priv,
5805                                                               intel_crtc_pch_transcoder(crtc), false);
5806         }
5807
5808         intel_dp_start_link_train(intel_dp);
5809         intel_dp_stop_link_train(intel_dp);
5810
5811         for_each_intel_crtc_mask(&dev_priv->drm, crtc, crtc_mask) {
5812                 const struct intel_crtc_state *crtc_state =
5813                         to_intel_crtc_state(crtc->base.state);
5814
5815                 /* Keep underrun reporting disabled until things are stable */
5816                 intel_wait_for_vblank(dev_priv, crtc->pipe);
5817
5818                 intel_set_cpu_fifo_underrun_reporting(dev_priv, crtc->pipe, true);
5819                 if (crtc_state->has_pch_encoder)
5820                         intel_set_pch_fifo_underrun_reporting(dev_priv,
5821                                                               intel_crtc_pch_transcoder(crtc), true);
5822         }
5823
5824         return 0;
5825 }
5826
5827 /*
5828  * If display is now connected check links status,
5829  * there has been known issues of link loss triggering
5830  * long pulse.
5831  *
5832  * Some sinks (eg. ASUS PB287Q) seem to perform some
5833  * weird HPD ping pong during modesets. So we can apparently
5834  * end up with HPD going low during a modeset, and then
5835  * going back up soon after. And once that happens we must
5836  * retrain the link to get a picture. That's in case no
5837  * userspace component reacted to intermittent HPD dip.
5838  */
5839 static enum intel_hotplug_state
5840 intel_dp_hotplug(struct intel_encoder *encoder,
5841                  struct intel_connector *connector)
5842 {
5843         struct drm_modeset_acquire_ctx ctx;
5844         enum intel_hotplug_state state;
5845         int ret;
5846
5847         state = intel_encoder_hotplug(encoder, connector);
5848
5849         drm_modeset_acquire_init(&ctx, 0);
5850
5851         for (;;) {
5852                 ret = intel_dp_retrain_link(encoder, &ctx);
5853
5854                 if (ret == -EDEADLK) {
5855                         drm_modeset_backoff(&ctx);
5856                         continue;
5857                 }
5858
5859                 break;
5860         }
5861
5862         drm_modeset_drop_locks(&ctx);
5863         drm_modeset_acquire_fini(&ctx);
5864         drm_WARN(encoder->base.dev, ret,
5865                  "Acquiring modeset locks failed with %i\n", ret);
5866
5867         /*
5868          * Keeping it consistent with intel_ddi_hotplug() and
5869          * intel_hdmi_hotplug().
5870          */
5871         if (state == INTEL_HOTPLUG_UNCHANGED && !connector->hotplug_retries)
5872                 state = INTEL_HOTPLUG_RETRY;
5873
5874         return state;
5875 }
5876
5877 static void intel_dp_check_service_irq(struct intel_dp *intel_dp)
5878 {
5879         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5880         u8 val;
5881
5882         if (intel_dp->dpcd[DP_DPCD_REV] < 0x11)
5883                 return;
5884
5885         if (drm_dp_dpcd_readb(&intel_dp->aux,
5886                               DP_DEVICE_SERVICE_IRQ_VECTOR, &val) != 1 || !val)
5887                 return;
5888
5889         drm_dp_dpcd_writeb(&intel_dp->aux, DP_DEVICE_SERVICE_IRQ_VECTOR, val);
5890
5891         if (val & DP_AUTOMATED_TEST_REQUEST)
5892                 intel_dp_handle_test_request(intel_dp);
5893
5894         if (val & DP_CP_IRQ)
5895                 intel_hdcp_handle_cp_irq(intel_dp->attached_connector);
5896
5897         if (val & DP_SINK_SPECIFIC_IRQ)
5898                 drm_dbg_kms(&i915->drm, "Sink specific irq unhandled\n");
5899 }
5900
5901 /*
5902  * According to DP spec
5903  * 5.1.2:
5904  *  1. Read DPCD
5905  *  2. Configure link according to Receiver Capabilities
5906  *  3. Use Link Training from 2.5.3.3 and 3.5.1.3
5907  *  4. Check link status on receipt of hot-plug interrupt
5908  *
5909  * intel_dp_short_pulse -  handles short pulse interrupts
5910  * when full detection is not required.
5911  * Returns %true if short pulse is handled and full detection
5912  * is NOT required and %false otherwise.
5913  */
5914 static bool
5915 intel_dp_short_pulse(struct intel_dp *intel_dp)
5916 {
5917         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
5918         u8 old_sink_count = intel_dp->sink_count;
5919         bool ret;
5920
5921         /*
5922          * Clearing compliance test variables to allow capturing
5923          * of values for next automated test request.
5924          */
5925         memset(&intel_dp->compliance, 0, sizeof(intel_dp->compliance));
5926
5927         /*
5928          * Now read the DPCD to see if it's actually running
5929          * If the current value of sink count doesn't match with
5930          * the value that was stored earlier or dpcd read failed
5931          * we need to do full detection
5932          */
5933         ret = intel_dp_get_dpcd(intel_dp);
5934
5935         if ((old_sink_count != intel_dp->sink_count) || !ret) {
5936                 /* No need to proceed if we are going to do full detect */
5937                 return false;
5938         }
5939
5940         intel_dp_check_service_irq(intel_dp);
5941
5942         /* Handle CEC interrupts, if any */
5943         drm_dp_cec_irq(&intel_dp->aux);
5944
5945         /* defer to the hotplug work for link retraining if needed */
5946         if (intel_dp_needs_link_retrain(intel_dp))
5947                 return false;
5948
5949         intel_psr_short_pulse(intel_dp);
5950
5951         if (intel_dp->compliance.test_type == DP_TEST_LINK_TRAINING) {
5952                 drm_dbg_kms(&dev_priv->drm,
5953                             "Link Training Compliance Test requested\n");
5954                 /* Send a Hotplug Uevent to userspace to start modeset */
5955                 drm_kms_helper_hotplug_event(&dev_priv->drm);
5956         }
5957
5958         return true;
5959 }
5960
5961 /* XXX this is probably wrong for multiple downstream ports */
5962 static enum drm_connector_status
5963 intel_dp_detect_dpcd(struct intel_dp *intel_dp)
5964 {
5965         struct drm_i915_private *i915 = dp_to_i915(intel_dp);
5966         struct intel_lspcon *lspcon = dp_to_lspcon(intel_dp);
5967         u8 *dpcd = intel_dp->dpcd;
5968         u8 type;
5969
5970         if (WARN_ON(intel_dp_is_edp(intel_dp)))
5971                 return connector_status_connected;
5972
5973         if (lspcon->active)
5974                 lspcon_resume(lspcon);
5975
5976         if (!intel_dp_get_dpcd(intel_dp))
5977                 return connector_status_disconnected;
5978
5979         /* if there's no downstream port, we're done */
5980         if (!drm_dp_is_branch(dpcd))
5981                 return connector_status_connected;
5982
5983         /* If we're HPD-aware, SINK_COUNT changes dynamically */
5984         if (intel_dp->dpcd[DP_DPCD_REV] >= 0x11 &&
5985             intel_dp->downstream_ports[0] & DP_DS_PORT_HPD) {
5986
5987                 return intel_dp->sink_count ?
5988                 connector_status_connected : connector_status_disconnected;
5989         }
5990
5991         if (intel_dp_can_mst(intel_dp))
5992                 return connector_status_connected;
5993
5994         /* If no HPD, poke DDC gently */
5995         if (drm_probe_ddc(&intel_dp->aux.ddc))
5996                 return connector_status_connected;
5997
5998         /* Well we tried, say unknown for unreliable port types */
5999         if (intel_dp->dpcd[DP_DPCD_REV] >= 0x11) {
6000                 type = intel_dp->downstream_ports[0] & DP_DS_PORT_TYPE_MASK;
6001                 if (type == DP_DS_PORT_TYPE_VGA ||
6002                     type == DP_DS_PORT_TYPE_NON_EDID)
6003                         return connector_status_unknown;
6004         } else {
6005                 type = intel_dp->dpcd[DP_DOWNSTREAMPORT_PRESENT] &
6006                         DP_DWN_STRM_PORT_TYPE_MASK;
6007                 if (type == DP_DWN_STRM_PORT_TYPE_ANALOG ||
6008                     type == DP_DWN_STRM_PORT_TYPE_OTHER)
6009                         return connector_status_unknown;
6010         }
6011
6012         /* Anything else is out of spec, warn and ignore */
6013         drm_dbg_kms(&i915->drm, "Broken DP branch device, ignoring\n");
6014         return connector_status_disconnected;
6015 }
6016
6017 static enum drm_connector_status
6018 edp_detect(struct intel_dp *intel_dp)
6019 {
6020         return connector_status_connected;
6021 }
6022
6023 static bool ibx_digital_port_connected(struct intel_encoder *encoder)
6024 {
6025         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6026         u32 bit;
6027
6028         switch (encoder->hpd_pin) {
6029         case HPD_PORT_B:
6030                 bit = SDE_PORTB_HOTPLUG;
6031                 break;
6032         case HPD_PORT_C:
6033                 bit = SDE_PORTC_HOTPLUG;
6034                 break;
6035         case HPD_PORT_D:
6036                 bit = SDE_PORTD_HOTPLUG;
6037                 break;
6038         default:
6039                 MISSING_CASE(encoder->hpd_pin);
6040                 return false;
6041         }
6042
6043         return intel_de_read(dev_priv, SDEISR) & bit;
6044 }
6045
6046 static bool cpt_digital_port_connected(struct intel_encoder *encoder)
6047 {
6048         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6049         u32 bit;
6050
6051         switch (encoder->hpd_pin) {
6052         case HPD_PORT_B:
6053                 bit = SDE_PORTB_HOTPLUG_CPT;
6054                 break;
6055         case HPD_PORT_C:
6056                 bit = SDE_PORTC_HOTPLUG_CPT;
6057                 break;
6058         case HPD_PORT_D:
6059                 bit = SDE_PORTD_HOTPLUG_CPT;
6060                 break;
6061         default:
6062                 MISSING_CASE(encoder->hpd_pin);
6063                 return false;
6064         }
6065
6066         return intel_de_read(dev_priv, SDEISR) & bit;
6067 }
6068
6069 static bool spt_digital_port_connected(struct intel_encoder *encoder)
6070 {
6071         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6072         u32 bit;
6073
6074         switch (encoder->hpd_pin) {
6075         case HPD_PORT_A:
6076                 bit = SDE_PORTA_HOTPLUG_SPT;
6077                 break;
6078         case HPD_PORT_E:
6079                 bit = SDE_PORTE_HOTPLUG_SPT;
6080                 break;
6081         default:
6082                 return cpt_digital_port_connected(encoder);
6083         }
6084
6085         return intel_de_read(dev_priv, SDEISR) & bit;
6086 }
6087
6088 static bool g4x_digital_port_connected(struct intel_encoder *encoder)
6089 {
6090         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6091         u32 bit;
6092
6093         switch (encoder->hpd_pin) {
6094         case HPD_PORT_B:
6095                 bit = PORTB_HOTPLUG_LIVE_STATUS_G4X;
6096                 break;
6097         case HPD_PORT_C:
6098                 bit = PORTC_HOTPLUG_LIVE_STATUS_G4X;
6099                 break;
6100         case HPD_PORT_D:
6101                 bit = PORTD_HOTPLUG_LIVE_STATUS_G4X;
6102                 break;
6103         default:
6104                 MISSING_CASE(encoder->hpd_pin);
6105                 return false;
6106         }
6107
6108         return intel_de_read(dev_priv, PORT_HOTPLUG_STAT) & bit;
6109 }
6110
6111 static bool gm45_digital_port_connected(struct intel_encoder *encoder)
6112 {
6113         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6114         u32 bit;
6115
6116         switch (encoder->hpd_pin) {
6117         case HPD_PORT_B:
6118                 bit = PORTB_HOTPLUG_LIVE_STATUS_GM45;
6119                 break;
6120         case HPD_PORT_C:
6121                 bit = PORTC_HOTPLUG_LIVE_STATUS_GM45;
6122                 break;
6123         case HPD_PORT_D:
6124                 bit = PORTD_HOTPLUG_LIVE_STATUS_GM45;
6125                 break;
6126         default:
6127                 MISSING_CASE(encoder->hpd_pin);
6128                 return false;
6129         }
6130
6131         return intel_de_read(dev_priv, PORT_HOTPLUG_STAT) & bit;
6132 }
6133
6134 static bool ilk_digital_port_connected(struct intel_encoder *encoder)
6135 {
6136         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6137
6138         if (encoder->hpd_pin == HPD_PORT_A)
6139                 return intel_de_read(dev_priv, DEISR) & DE_DP_A_HOTPLUG;
6140         else
6141                 return ibx_digital_port_connected(encoder);
6142 }
6143
6144 static bool snb_digital_port_connected(struct intel_encoder *encoder)
6145 {
6146         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6147
6148         if (encoder->hpd_pin == HPD_PORT_A)
6149                 return intel_de_read(dev_priv, DEISR) & DE_DP_A_HOTPLUG;
6150         else
6151                 return cpt_digital_port_connected(encoder);
6152 }
6153
6154 static bool ivb_digital_port_connected(struct intel_encoder *encoder)
6155 {
6156         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6157
6158         if (encoder->hpd_pin == HPD_PORT_A)
6159                 return intel_de_read(dev_priv, DEISR) & DE_DP_A_HOTPLUG_IVB;
6160         else
6161                 return cpt_digital_port_connected(encoder);
6162 }
6163
6164 static bool bdw_digital_port_connected(struct intel_encoder *encoder)
6165 {
6166         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6167
6168         if (encoder->hpd_pin == HPD_PORT_A)
6169                 return intel_de_read(dev_priv, GEN8_DE_PORT_ISR) & GEN8_PORT_DP_A_HOTPLUG;
6170         else
6171                 return cpt_digital_port_connected(encoder);
6172 }
6173
6174 static bool bxt_digital_port_connected(struct intel_encoder *encoder)
6175 {
6176         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6177         u32 bit;
6178
6179         switch (encoder->hpd_pin) {
6180         case HPD_PORT_A:
6181                 bit = BXT_DE_PORT_HP_DDIA;
6182                 break;
6183         case HPD_PORT_B:
6184                 bit = BXT_DE_PORT_HP_DDIB;
6185                 break;
6186         case HPD_PORT_C:
6187                 bit = BXT_DE_PORT_HP_DDIC;
6188                 break;
6189         default:
6190                 MISSING_CASE(encoder->hpd_pin);
6191                 return false;
6192         }
6193
6194         return intel_de_read(dev_priv, GEN8_DE_PORT_ISR) & bit;
6195 }
6196
6197 static bool intel_combo_phy_connected(struct drm_i915_private *dev_priv,
6198                                       enum phy phy)
6199 {
6200         if (HAS_PCH_MCC(dev_priv) && phy == PHY_C)
6201                 return intel_de_read(dev_priv, SDEISR) & SDE_TC_HOTPLUG_ICP(PORT_TC1);
6202
6203         return intel_de_read(dev_priv, SDEISR) & SDE_DDI_HOTPLUG_ICP(phy);
6204 }
6205
6206 static bool icp_digital_port_connected(struct intel_encoder *encoder)
6207 {
6208         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6209         struct intel_digital_port *dig_port = enc_to_dig_port(encoder);
6210         enum phy phy = intel_port_to_phy(dev_priv, encoder->port);
6211
6212         if (intel_phy_is_combo(dev_priv, phy))
6213                 return intel_combo_phy_connected(dev_priv, phy);
6214         else if (intel_phy_is_tc(dev_priv, phy))
6215                 return intel_tc_port_connected(dig_port);
6216         else
6217                 MISSING_CASE(encoder->hpd_pin);
6218
6219         return false;
6220 }
6221
6222 /*
6223  * intel_digital_port_connected - is the specified port connected?
6224  * @encoder: intel_encoder
6225  *
6226  * In cases where there's a connector physically connected but it can't be used
6227  * by our hardware we also return false, since the rest of the driver should
6228  * pretty much treat the port as disconnected. This is relevant for type-C
6229  * (starting on ICL) where there's ownership involved.
6230  *
6231  * Return %true if port is connected, %false otherwise.
6232  */
6233 static bool __intel_digital_port_connected(struct intel_encoder *encoder)
6234 {
6235         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6236
6237         if (HAS_GMCH(dev_priv)) {
6238                 if (IS_GM45(dev_priv))
6239                         return gm45_digital_port_connected(encoder);
6240                 else
6241                         return g4x_digital_port_connected(encoder);
6242         }
6243
6244         if (INTEL_PCH_TYPE(dev_priv) >= PCH_ICP)
6245                 return icp_digital_port_connected(encoder);
6246         else if (INTEL_PCH_TYPE(dev_priv) >= PCH_SPT)
6247                 return spt_digital_port_connected(encoder);
6248         else if (IS_GEN9_LP(dev_priv))
6249                 return bxt_digital_port_connected(encoder);
6250         else if (IS_GEN(dev_priv, 8))
6251                 return bdw_digital_port_connected(encoder);
6252         else if (IS_GEN(dev_priv, 7))
6253                 return ivb_digital_port_connected(encoder);
6254         else if (IS_GEN(dev_priv, 6))
6255                 return snb_digital_port_connected(encoder);
6256         else if (IS_GEN(dev_priv, 5))
6257                 return ilk_digital_port_connected(encoder);
6258
6259         MISSING_CASE(INTEL_GEN(dev_priv));
6260         return false;
6261 }
6262
6263 bool intel_digital_port_connected(struct intel_encoder *encoder)
6264 {
6265         struct drm_i915_private *dev_priv = to_i915(encoder->base.dev);
6266         bool is_connected = false;
6267         intel_wakeref_t wakeref;
6268
6269         with_intel_display_power(dev_priv, POWER_DOMAIN_DISPLAY_CORE, wakeref)
6270                 is_connected = __intel_digital_port_connected(encoder);
6271
6272         return is_connected;
6273 }
6274
6275 static struct edid *
6276 intel_dp_get_edid(struct intel_dp *intel_dp)
6277 {
6278         struct intel_connector *intel_connector = intel_dp->attached_connector;
6279
6280         /* use cached edid if we have one */
6281         if (intel_connector->edid) {
6282                 /* invalid edid */
6283                 if (IS_ERR(intel_connector->edid))
6284                         return NULL;
6285
6286                 return drm_edid_duplicate(intel_connector->edid);
6287         } else
6288                 return drm_get_edid(&intel_connector->base,
6289                                     &intel_dp->aux.ddc);
6290 }
6291
6292 static void
6293 intel_dp_set_edid(struct intel_dp *intel_dp)
6294 {
6295         struct intel_connector *intel_connector = intel_dp->attached_connector;
6296         struct edid *edid;
6297
6298         intel_dp_unset_edid(intel_dp);
6299         edid = intel_dp_get_edid(intel_dp);
6300         intel_connector->detect_edid = edid;
6301
6302         intel_dp->has_audio = drm_detect_monitor_audio(edid);
6303         drm_dp_cec_set_edid(&intel_dp->aux, edid);
6304         intel_dp->edid_quirks = drm_dp_get_edid_quirks(edid);
6305 }
6306
6307 static void
6308 intel_dp_unset_edid(struct intel_dp *intel_dp)
6309 {
6310         struct intel_connector *intel_connector = intel_dp->attached_connector;
6311
6312         drm_dp_cec_unset_edid(&intel_dp->aux);
6313         kfree(intel_connector->detect_edid);
6314         intel_connector->detect_edid = NULL;
6315
6316         intel_dp->has_audio = false;
6317         intel_dp->edid_quirks = 0;
6318 }
6319
6320 static int
6321 intel_dp_detect(struct drm_connector *connector,
6322                 struct drm_modeset_acquire_ctx *ctx,
6323                 bool force)
6324 {
6325         struct drm_i915_private *dev_priv = to_i915(connector->dev);
6326         struct intel_dp *intel_dp = intel_attached_dp(to_intel_connector(connector));
6327         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
6328         struct intel_encoder *encoder = &dig_port->base;
6329         enum drm_connector_status status;
6330
6331         drm_dbg_kms(&dev_priv->drm, "[CONNECTOR:%d:%s]\n",
6332                     connector->base.id, connector->name);
6333         drm_WARN_ON(&dev_priv->drm,
6334                     !drm_modeset_is_locked(&dev_priv->drm.mode_config.connection_mutex));
6335
6336         /* Can't disconnect eDP */
6337         if (intel_dp_is_edp(intel_dp))
6338                 status = edp_detect(intel_dp);
6339         else if (intel_digital_port_connected(encoder))
6340                 status = intel_dp_detect_dpcd(intel_dp);
6341         else
6342                 status = connector_status_disconnected;
6343
6344         if (status == connector_status_disconnected) {
6345                 memset(&intel_dp->compliance, 0, sizeof(intel_dp->compliance));
6346                 memset(intel_dp->dsc_dpcd, 0, sizeof(intel_dp->dsc_dpcd));
6347
6348                 if (intel_dp->is_mst) {
6349                         drm_dbg_kms(&dev_priv->drm,
6350                                     "MST device may have disappeared %d vs %d\n",
6351                                     intel_dp->is_mst,
6352                                     intel_dp->mst_mgr.mst_state);
6353                         intel_dp->is_mst = false;
6354                         drm_dp_mst_topology_mgr_set_mst(&intel_dp->mst_mgr,
6355                                                         intel_dp->is_mst);
6356                 }
6357
6358                 goto out;
6359         }
6360
6361         if (intel_dp->reset_link_params) {
6362                 /* Initial max link lane count */
6363                 intel_dp->max_link_lane_count = intel_dp_max_common_lane_count(intel_dp);
6364
6365                 /* Initial max link rate */
6366                 intel_dp->max_link_rate = intel_dp_max_common_rate(intel_dp);
6367
6368                 intel_dp->reset_link_params = false;
6369         }
6370
6371         intel_dp_print_rates(intel_dp);
6372
6373         /* Read DP Sink DSC Cap DPCD regs for DP v1.4 */
6374         if (INTEL_GEN(dev_priv) >= 11)
6375                 intel_dp_get_dsc_sink_cap(intel_dp);
6376
6377         intel_dp_configure_mst(intel_dp);
6378
6379         if (intel_dp->is_mst) {
6380                 /*
6381                  * If we are in MST mode then this connector
6382                  * won't appear connected or have anything
6383                  * with EDID on it
6384                  */
6385                 status = connector_status_disconnected;
6386                 goto out;
6387         }
6388
6389         /*
6390          * Some external monitors do not signal loss of link synchronization
6391          * with an IRQ_HPD, so force a link status check.
6392          */
6393         if (!intel_dp_is_edp(intel_dp)) {
6394                 int ret;
6395
6396                 ret = intel_dp_retrain_link(encoder, ctx);
6397                 if (ret)
6398                         return ret;
6399         }
6400
6401         /*
6402          * Clearing NACK and defer counts to get their exact values
6403          * while reading EDID which are required by Compliance tests
6404          * 4.2.2.4 and 4.2.2.5
6405          */
6406         intel_dp->aux.i2c_nack_count = 0;
6407         intel_dp->aux.i2c_defer_count = 0;
6408
6409         intel_dp_set_edid(intel_dp);
6410         if (intel_dp_is_edp(intel_dp) ||
6411             to_intel_connector(connector)->detect_edid)
6412                 status = connector_status_connected;
6413
6414         intel_dp_check_service_irq(intel_dp);
6415
6416 out:
6417         if (status != connector_status_connected && !intel_dp->is_mst)
6418                 intel_dp_unset_edid(intel_dp);
6419
6420         /*
6421          * Make sure the refs for power wells enabled during detect are
6422          * dropped to avoid a new detect cycle triggered by HPD polling.
6423          */
6424         intel_display_power_flush_work(dev_priv);
6425
6426         return status;
6427 }
6428
6429 static void
6430 intel_dp_force(struct drm_connector *connector)
6431 {
6432         struct intel_dp *intel_dp = intel_attached_dp(to_intel_connector(connector));
6433         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
6434         struct intel_encoder *intel_encoder = &dig_port->base;
6435         struct drm_i915_private *dev_priv = to_i915(intel_encoder->base.dev);
6436         enum intel_display_power_domain aux_domain =
6437                 intel_aux_power_domain(dig_port);
6438         intel_wakeref_t wakeref;
6439
6440         drm_dbg_kms(&dev_priv->drm, "[CONNECTOR:%d:%s]\n",
6441                     connector->base.id, connector->name);
6442         intel_dp_unset_edid(intel_dp);
6443
6444         if (connector->status != connector_status_connected)
6445                 return;
6446
6447         wakeref = intel_display_power_get(dev_priv, aux_domain);
6448
6449         intel_dp_set_edid(intel_dp);
6450
6451         intel_display_power_put(dev_priv, aux_domain, wakeref);
6452 }
6453
6454 static int intel_dp_get_modes(struct drm_connector *connector)
6455 {
6456         struct intel_connector *intel_connector = to_intel_connector(connector);
6457         struct edid *edid;
6458
6459         edid = intel_connector->detect_edid;
6460         if (edid) {
6461                 int ret = intel_connector_update_modes(connector, edid);
6462                 if (ret)
6463                         return ret;
6464         }
6465
6466         /* if eDP has no EDID, fall back to fixed mode */
6467         if (intel_dp_is_edp(intel_attached_dp(to_intel_connector(connector))) &&
6468             intel_connector->panel.fixed_mode) {
6469                 struct drm_display_mode *mode;
6470
6471                 mode = drm_mode_duplicate(connector->dev,
6472                                           intel_connector->panel.fixed_mode);
6473                 if (mode) {
6474                         drm_mode_probed_add(connector, mode);
6475                         return 1;
6476                 }
6477         }
6478
6479         return 0;
6480 }
6481
6482 static int
6483 intel_dp_connector_register(struct drm_connector *connector)
6484 {
6485         struct drm_i915_private *i915 = to_i915(connector->dev);
6486         struct intel_dp *intel_dp = intel_attached_dp(to_intel_connector(connector));
6487         int ret;
6488
6489         ret = intel_connector_register(connector);
6490         if (ret)
6491                 return ret;
6492
6493         drm_dbg_kms(&i915->drm, "registering %s bus for %s\n",
6494                     intel_dp->aux.name, connector->kdev->kobj.name);
6495
6496         intel_dp->aux.dev = connector->kdev;
6497         ret = drm_dp_aux_register(&intel_dp->aux);
6498         if (!ret)
6499                 drm_dp_cec_register_connector(&intel_dp->aux, connector);
6500         return ret;
6501 }
6502
6503 static void
6504 intel_dp_connector_unregister(struct drm_connector *connector)
6505 {
6506         struct intel_dp *intel_dp = intel_attached_dp(to_intel_connector(connector));
6507
6508         drm_dp_cec_unregister_connector(&intel_dp->aux);
6509         drm_dp_aux_unregister(&intel_dp->aux);
6510         intel_connector_unregister(connector);
6511 }
6512
6513 void intel_dp_encoder_flush_work(struct drm_encoder *encoder)
6514 {
6515         struct intel_digital_port *intel_dig_port = enc_to_dig_port(to_intel_encoder(encoder));
6516         struct intel_dp *intel_dp = &intel_dig_port->dp;
6517
6518         intel_dp_mst_encoder_cleanup(intel_dig_port);
6519         if (intel_dp_is_edp(intel_dp)) {
6520                 intel_wakeref_t wakeref;
6521
6522                 cancel_delayed_work_sync(&intel_dp->panel_vdd_work);
6523                 /*
6524                  * vdd might still be enabled do to the delayed vdd off.
6525                  * Make sure vdd is actually turned off here.
6526                  */
6527                 with_pps_lock(intel_dp, wakeref)
6528                         edp_panel_vdd_off_sync(intel_dp);
6529
6530                 if (intel_dp->edp_notifier.notifier_call) {
6531                         unregister_reboot_notifier(&intel_dp->edp_notifier);
6532                         intel_dp->edp_notifier.notifier_call = NULL;
6533                 }
6534         }
6535
6536         intel_dp_aux_fini(intel_dp);
6537 }
6538
6539 static void intel_dp_encoder_destroy(struct drm_encoder *encoder)
6540 {
6541         intel_dp_encoder_flush_work(encoder);
6542
6543         drm_encoder_cleanup(encoder);
6544         kfree(enc_to_dig_port(to_intel_encoder(encoder)));
6545 }
6546
6547 void intel_dp_encoder_suspend(struct intel_encoder *intel_encoder)
6548 {
6549         struct intel_dp *intel_dp = enc_to_intel_dp(intel_encoder);
6550         intel_wakeref_t wakeref;
6551
6552         if (!intel_dp_is_edp(intel_dp))
6553                 return;
6554
6555         /*
6556          * vdd might still be enabled do to the delayed vdd off.
6557          * Make sure vdd is actually turned off here.
6558          */
6559         cancel_delayed_work_sync(&intel_dp->panel_vdd_work);
6560         with_pps_lock(intel_dp, wakeref)
6561                 edp_panel_vdd_off_sync(intel_dp);
6562 }
6563
6564 static void intel_dp_hdcp_wait_for_cp_irq(struct intel_hdcp *hdcp, int timeout)
6565 {
6566         long ret;
6567
6568 #define C (hdcp->cp_irq_count_cached != atomic_read(&hdcp->cp_irq_count))
6569         ret = wait_event_interruptible_timeout(hdcp->cp_irq_queue, C,
6570                                                msecs_to_jiffies(timeout));
6571
6572         if (!ret)
6573                 DRM_DEBUG_KMS("Timedout at waiting for CP_IRQ\n");
6574 }
6575
6576 static
6577 int intel_dp_hdcp_write_an_aksv(struct intel_digital_port *intel_dig_port,
6578                                 u8 *an)
6579 {
6580         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6581         struct intel_dp *intel_dp = enc_to_intel_dp(to_intel_encoder(&intel_dig_port->base.base));
6582         static const struct drm_dp_aux_msg msg = {
6583                 .request = DP_AUX_NATIVE_WRITE,
6584                 .address = DP_AUX_HDCP_AKSV,
6585                 .size = DRM_HDCP_KSV_LEN,
6586         };
6587         u8 txbuf[HEADER_SIZE + DRM_HDCP_KSV_LEN] = {}, rxbuf[2], reply = 0;
6588         ssize_t dpcd_ret;
6589         int ret;
6590
6591         /* Output An first, that's easy */
6592         dpcd_ret = drm_dp_dpcd_write(&intel_dig_port->dp.aux, DP_AUX_HDCP_AN,
6593                                      an, DRM_HDCP_AN_LEN);
6594         if (dpcd_ret != DRM_HDCP_AN_LEN) {
6595                 drm_dbg_kms(&i915->drm,
6596                             "Failed to write An over DP/AUX (%zd)\n",
6597                             dpcd_ret);
6598                 return dpcd_ret >= 0 ? -EIO : dpcd_ret;
6599         }
6600
6601         /*
6602          * Since Aksv is Oh-So-Secret, we can't access it in software. So in
6603          * order to get it on the wire, we need to create the AUX header as if
6604          * we were writing the data, and then tickle the hardware to output the
6605          * data once the header is sent out.
6606          */
6607         intel_dp_aux_header(txbuf, &msg);
6608
6609         ret = intel_dp_aux_xfer(intel_dp, txbuf, HEADER_SIZE + msg.size,
6610                                 rxbuf, sizeof(rxbuf),
6611                                 DP_AUX_CH_CTL_AUX_AKSV_SELECT);
6612         if (ret < 0) {
6613                 drm_dbg_kms(&i915->drm,
6614                             "Write Aksv over DP/AUX failed (%d)\n", ret);
6615                 return ret;
6616         } else if (ret == 0) {
6617                 drm_dbg_kms(&i915->drm, "Aksv write over DP/AUX was empty\n");
6618                 return -EIO;
6619         }
6620
6621         reply = (rxbuf[0] >> 4) & DP_AUX_NATIVE_REPLY_MASK;
6622         if (reply != DP_AUX_NATIVE_REPLY_ACK) {
6623                 drm_dbg_kms(&i915->drm,
6624                             "Aksv write: no DP_AUX_NATIVE_REPLY_ACK %x\n",
6625                             reply);
6626                 return -EIO;
6627         }
6628         return 0;
6629 }
6630
6631 static int intel_dp_hdcp_read_bksv(struct intel_digital_port *intel_dig_port,
6632                                    u8 *bksv)
6633 {
6634         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6635         ssize_t ret;
6636
6637         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, DP_AUX_HDCP_BKSV, bksv,
6638                                DRM_HDCP_KSV_LEN);
6639         if (ret != DRM_HDCP_KSV_LEN) {
6640                 drm_dbg_kms(&i915->drm,
6641                             "Read Bksv from DP/AUX failed (%zd)\n", ret);
6642                 return ret >= 0 ? -EIO : ret;
6643         }
6644         return 0;
6645 }
6646
6647 static int intel_dp_hdcp_read_bstatus(struct intel_digital_port *intel_dig_port,
6648                                       u8 *bstatus)
6649 {
6650         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6651         ssize_t ret;
6652
6653         /*
6654          * For some reason the HDMI and DP HDCP specs call this register
6655          * definition by different names. In the HDMI spec, it's called BSTATUS,
6656          * but in DP it's called BINFO.
6657          */
6658         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, DP_AUX_HDCP_BINFO,
6659                                bstatus, DRM_HDCP_BSTATUS_LEN);
6660         if (ret != DRM_HDCP_BSTATUS_LEN) {
6661                 drm_dbg_kms(&i915->drm,
6662                             "Read bstatus from DP/AUX failed (%zd)\n", ret);
6663                 return ret >= 0 ? -EIO : ret;
6664         }
6665         return 0;
6666 }
6667
6668 static
6669 int intel_dp_hdcp_read_bcaps(struct intel_digital_port *intel_dig_port,
6670                              u8 *bcaps)
6671 {
6672         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6673         ssize_t ret;
6674
6675         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, DP_AUX_HDCP_BCAPS,
6676                                bcaps, 1);
6677         if (ret != 1) {
6678                 drm_dbg_kms(&i915->drm,
6679                             "Read bcaps from DP/AUX failed (%zd)\n", ret);
6680                 return ret >= 0 ? -EIO : ret;
6681         }
6682
6683         return 0;
6684 }
6685
6686 static
6687 int intel_dp_hdcp_repeater_present(struct intel_digital_port *intel_dig_port,
6688                                    bool *repeater_present)
6689 {
6690         ssize_t ret;
6691         u8 bcaps;
6692
6693         ret = intel_dp_hdcp_read_bcaps(intel_dig_port, &bcaps);
6694         if (ret)
6695                 return ret;
6696
6697         *repeater_present = bcaps & DP_BCAPS_REPEATER_PRESENT;
6698         return 0;
6699 }
6700
6701 static
6702 int intel_dp_hdcp_read_ri_prime(struct intel_digital_port *intel_dig_port,
6703                                 u8 *ri_prime)
6704 {
6705         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6706         ssize_t ret;
6707
6708         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, DP_AUX_HDCP_RI_PRIME,
6709                                ri_prime, DRM_HDCP_RI_LEN);
6710         if (ret != DRM_HDCP_RI_LEN) {
6711                 drm_dbg_kms(&i915->drm, "Read Ri' from DP/AUX failed (%zd)\n",
6712                             ret);
6713                 return ret >= 0 ? -EIO : ret;
6714         }
6715         return 0;
6716 }
6717
6718 static
6719 int intel_dp_hdcp_read_ksv_ready(struct intel_digital_port *intel_dig_port,
6720                                  bool *ksv_ready)
6721 {
6722         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6723         ssize_t ret;
6724         u8 bstatus;
6725
6726         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, DP_AUX_HDCP_BSTATUS,
6727                                &bstatus, 1);
6728         if (ret != 1) {
6729                 drm_dbg_kms(&i915->drm,
6730                             "Read bstatus from DP/AUX failed (%zd)\n", ret);
6731                 return ret >= 0 ? -EIO : ret;
6732         }
6733         *ksv_ready = bstatus & DP_BSTATUS_READY;
6734         return 0;
6735 }
6736
6737 static
6738 int intel_dp_hdcp_read_ksv_fifo(struct intel_digital_port *intel_dig_port,
6739                                 int num_downstream, u8 *ksv_fifo)
6740 {
6741         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6742         ssize_t ret;
6743         int i;
6744
6745         /* KSV list is read via 15 byte window (3 entries @ 5 bytes each) */
6746         for (i = 0; i < num_downstream; i += 3) {
6747                 size_t len = min(num_downstream - i, 3) * DRM_HDCP_KSV_LEN;
6748                 ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux,
6749                                        DP_AUX_HDCP_KSV_FIFO,
6750                                        ksv_fifo + i * DRM_HDCP_KSV_LEN,
6751                                        len);
6752                 if (ret != len) {
6753                         drm_dbg_kms(&i915->drm,
6754                                     "Read ksv[%d] from DP/AUX failed (%zd)\n",
6755                                     i, ret);
6756                         return ret >= 0 ? -EIO : ret;
6757                 }
6758         }
6759         return 0;
6760 }
6761
6762 static
6763 int intel_dp_hdcp_read_v_prime_part(struct intel_digital_port *intel_dig_port,
6764                                     int i, u32 *part)
6765 {
6766         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6767         ssize_t ret;
6768
6769         if (i >= DRM_HDCP_V_PRIME_NUM_PARTS)
6770                 return -EINVAL;
6771
6772         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux,
6773                                DP_AUX_HDCP_V_PRIME(i), part,
6774                                DRM_HDCP_V_PRIME_PART_LEN);
6775         if (ret != DRM_HDCP_V_PRIME_PART_LEN) {
6776                 drm_dbg_kms(&i915->drm,
6777                             "Read v'[%d] from DP/AUX failed (%zd)\n", i, ret);
6778                 return ret >= 0 ? -EIO : ret;
6779         }
6780         return 0;
6781 }
6782
6783 static
6784 int intel_dp_hdcp_toggle_signalling(struct intel_digital_port *intel_dig_port,
6785                                     bool enable)
6786 {
6787         /* Not used for single stream DisplayPort setups */
6788         return 0;
6789 }
6790
6791 static
6792 bool intel_dp_hdcp_check_link(struct intel_digital_port *intel_dig_port)
6793 {
6794         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6795         ssize_t ret;
6796         u8 bstatus;
6797
6798         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, DP_AUX_HDCP_BSTATUS,
6799                                &bstatus, 1);
6800         if (ret != 1) {
6801                 drm_dbg_kms(&i915->drm,
6802                             "Read bstatus from DP/AUX failed (%zd)\n", ret);
6803                 return false;
6804         }
6805
6806         return !(bstatus & (DP_BSTATUS_LINK_FAILURE | DP_BSTATUS_REAUTH_REQ));
6807 }
6808
6809 static
6810 int intel_dp_hdcp_capable(struct intel_digital_port *intel_dig_port,
6811                           bool *hdcp_capable)
6812 {
6813         ssize_t ret;
6814         u8 bcaps;
6815
6816         ret = intel_dp_hdcp_read_bcaps(intel_dig_port, &bcaps);
6817         if (ret)
6818                 return ret;
6819
6820         *hdcp_capable = bcaps & DP_BCAPS_HDCP_CAPABLE;
6821         return 0;
6822 }
6823
6824 struct hdcp2_dp_errata_stream_type {
6825         u8      msg_id;
6826         u8      stream_type;
6827 } __packed;
6828
6829 struct hdcp2_dp_msg_data {
6830         u8 msg_id;
6831         u32 offset;
6832         bool msg_detectable;
6833         u32 timeout;
6834         u32 timeout2; /* Added for non_paired situation */
6835 };
6836
6837 static const struct hdcp2_dp_msg_data hdcp2_dp_msg_data[] = {
6838         { HDCP_2_2_AKE_INIT, DP_HDCP_2_2_AKE_INIT_OFFSET, false, 0, 0 },
6839         { HDCP_2_2_AKE_SEND_CERT, DP_HDCP_2_2_AKE_SEND_CERT_OFFSET,
6840           false, HDCP_2_2_CERT_TIMEOUT_MS, 0 },
6841         { HDCP_2_2_AKE_NO_STORED_KM, DP_HDCP_2_2_AKE_NO_STORED_KM_OFFSET,
6842           false, 0, 0 },
6843         { HDCP_2_2_AKE_STORED_KM, DP_HDCP_2_2_AKE_STORED_KM_OFFSET,
6844           false, 0, 0 },
6845         { HDCP_2_2_AKE_SEND_HPRIME, DP_HDCP_2_2_AKE_SEND_HPRIME_OFFSET,
6846           true, HDCP_2_2_HPRIME_PAIRED_TIMEOUT_MS,
6847           HDCP_2_2_HPRIME_NO_PAIRED_TIMEOUT_MS },
6848         { HDCP_2_2_AKE_SEND_PAIRING_INFO,
6849           DP_HDCP_2_2_AKE_SEND_PAIRING_INFO_OFFSET, true,
6850           HDCP_2_2_PAIRING_TIMEOUT_MS, 0 },
6851         { HDCP_2_2_LC_INIT, DP_HDCP_2_2_LC_INIT_OFFSET, false, 0, 0 },
6852         { HDCP_2_2_LC_SEND_LPRIME, DP_HDCP_2_2_LC_SEND_LPRIME_OFFSET,
6853           false, HDCP_2_2_DP_LPRIME_TIMEOUT_MS, 0 },
6854         { HDCP_2_2_SKE_SEND_EKS, DP_HDCP_2_2_SKE_SEND_EKS_OFFSET, false,
6855           0, 0 },
6856         { HDCP_2_2_REP_SEND_RECVID_LIST,
6857           DP_HDCP_2_2_REP_SEND_RECVID_LIST_OFFSET, true,
6858           HDCP_2_2_RECVID_LIST_TIMEOUT_MS, 0 },
6859         { HDCP_2_2_REP_SEND_ACK, DP_HDCP_2_2_REP_SEND_ACK_OFFSET, false,
6860           0, 0 },
6861         { HDCP_2_2_REP_STREAM_MANAGE,
6862           DP_HDCP_2_2_REP_STREAM_MANAGE_OFFSET, false,
6863           0, 0 },
6864         { HDCP_2_2_REP_STREAM_READY, DP_HDCP_2_2_REP_STREAM_READY_OFFSET,
6865           false, HDCP_2_2_STREAM_READY_TIMEOUT_MS, 0 },
6866 /* local define to shovel this through the write_2_2 interface */
6867 #define HDCP_2_2_ERRATA_DP_STREAM_TYPE  50
6868         { HDCP_2_2_ERRATA_DP_STREAM_TYPE,
6869           DP_HDCP_2_2_REG_STREAM_TYPE_OFFSET, false,
6870           0, 0 },
6871 };
6872
6873 static int
6874 intel_dp_hdcp2_read_rx_status(struct intel_digital_port *intel_dig_port,
6875                               u8 *rx_status)
6876 {
6877         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6878         ssize_t ret;
6879
6880         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux,
6881                                DP_HDCP_2_2_REG_RXSTATUS_OFFSET, rx_status,
6882                                HDCP_2_2_DP_RXSTATUS_LEN);
6883         if (ret != HDCP_2_2_DP_RXSTATUS_LEN) {
6884                 drm_dbg_kms(&i915->drm,
6885                             "Read bstatus from DP/AUX failed (%zd)\n", ret);
6886                 return ret >= 0 ? -EIO : ret;
6887         }
6888
6889         return 0;
6890 }
6891
6892 static
6893 int hdcp2_detect_msg_availability(struct intel_digital_port *intel_dig_port,
6894                                   u8 msg_id, bool *msg_ready)
6895 {
6896         u8 rx_status;
6897         int ret;
6898
6899         *msg_ready = false;
6900         ret = intel_dp_hdcp2_read_rx_status(intel_dig_port, &rx_status);
6901         if (ret < 0)
6902                 return ret;
6903
6904         switch (msg_id) {
6905         case HDCP_2_2_AKE_SEND_HPRIME:
6906                 if (HDCP_2_2_DP_RXSTATUS_H_PRIME(rx_status))
6907                         *msg_ready = true;
6908                 break;
6909         case HDCP_2_2_AKE_SEND_PAIRING_INFO:
6910                 if (HDCP_2_2_DP_RXSTATUS_PAIRING(rx_status))
6911                         *msg_ready = true;
6912                 break;
6913         case HDCP_2_2_REP_SEND_RECVID_LIST:
6914                 if (HDCP_2_2_DP_RXSTATUS_READY(rx_status))
6915                         *msg_ready = true;
6916                 break;
6917         default:
6918                 DRM_ERROR("Unidentified msg_id: %d\n", msg_id);
6919                 return -EINVAL;
6920         }
6921
6922         return 0;
6923 }
6924
6925 static ssize_t
6926 intel_dp_hdcp2_wait_for_msg(struct intel_digital_port *intel_dig_port,
6927                             const struct hdcp2_dp_msg_data *hdcp2_msg_data)
6928 {
6929         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
6930         struct intel_dp *dp = &intel_dig_port->dp;
6931         struct intel_hdcp *hdcp = &dp->attached_connector->hdcp;
6932         u8 msg_id = hdcp2_msg_data->msg_id;
6933         int ret, timeout;
6934         bool msg_ready = false;
6935
6936         if (msg_id == HDCP_2_2_AKE_SEND_HPRIME && !hdcp->is_paired)
6937                 timeout = hdcp2_msg_data->timeout2;
6938         else
6939                 timeout = hdcp2_msg_data->timeout;
6940
6941         /*
6942          * There is no way to detect the CERT, LPRIME and STREAM_READY
6943          * availability. So Wait for timeout and read the msg.
6944          */
6945         if (!hdcp2_msg_data->msg_detectable) {
6946                 mdelay(timeout);
6947                 ret = 0;
6948         } else {
6949                 /*
6950                  * As we want to check the msg availability at timeout, Ignoring
6951                  * the timeout at wait for CP_IRQ.
6952                  */
6953                 intel_dp_hdcp_wait_for_cp_irq(hdcp, timeout);
6954                 ret = hdcp2_detect_msg_availability(intel_dig_port,
6955                                                     msg_id, &msg_ready);
6956                 if (!msg_ready)
6957                         ret = -ETIMEDOUT;
6958         }
6959
6960         if (ret)
6961                 drm_dbg_kms(&i915->drm,
6962                             "msg_id %d, ret %d, timeout(mSec): %d\n",
6963                             hdcp2_msg_data->msg_id, ret, timeout);
6964
6965         return ret;
6966 }
6967
6968 static const struct hdcp2_dp_msg_data *get_hdcp2_dp_msg_data(u8 msg_id)
6969 {
6970         int i;
6971
6972         for (i = 0; i < ARRAY_SIZE(hdcp2_dp_msg_data); i++)
6973                 if (hdcp2_dp_msg_data[i].msg_id == msg_id)
6974                         return &hdcp2_dp_msg_data[i];
6975
6976         return NULL;
6977 }
6978
6979 static
6980 int intel_dp_hdcp2_write_msg(struct intel_digital_port *intel_dig_port,
6981                              void *buf, size_t size)
6982 {
6983         struct intel_dp *dp = &intel_dig_port->dp;
6984         struct intel_hdcp *hdcp = &dp->attached_connector->hdcp;
6985         unsigned int offset;
6986         u8 *byte = buf;
6987         ssize_t ret, bytes_to_write, len;
6988         const struct hdcp2_dp_msg_data *hdcp2_msg_data;
6989
6990         hdcp2_msg_data = get_hdcp2_dp_msg_data(*byte);
6991         if (!hdcp2_msg_data)
6992                 return -EINVAL;
6993
6994         offset = hdcp2_msg_data->offset;
6995
6996         /* No msg_id in DP HDCP2.2 msgs */
6997         bytes_to_write = size - 1;
6998         byte++;
6999
7000         hdcp->cp_irq_count_cached = atomic_read(&hdcp->cp_irq_count);
7001
7002         while (bytes_to_write) {
7003                 len = bytes_to_write > DP_AUX_MAX_PAYLOAD_BYTES ?
7004                                 DP_AUX_MAX_PAYLOAD_BYTES : bytes_to_write;
7005
7006                 ret = drm_dp_dpcd_write(&intel_dig_port->dp.aux,
7007                                         offset, (void *)byte, len);
7008                 if (ret < 0)
7009                         return ret;
7010
7011                 bytes_to_write -= ret;
7012                 byte += ret;
7013                 offset += ret;
7014         }
7015
7016         return size;
7017 }
7018
7019 static
7020 ssize_t get_receiver_id_list_size(struct intel_digital_port *intel_dig_port)
7021 {
7022         u8 rx_info[HDCP_2_2_RXINFO_LEN];
7023         u32 dev_cnt;
7024         ssize_t ret;
7025
7026         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux,
7027                                DP_HDCP_2_2_REG_RXINFO_OFFSET,
7028                                (void *)rx_info, HDCP_2_2_RXINFO_LEN);
7029         if (ret != HDCP_2_2_RXINFO_LEN)
7030                 return ret >= 0 ? -EIO : ret;
7031
7032         dev_cnt = (HDCP_2_2_DEV_COUNT_HI(rx_info[0]) << 4 |
7033                    HDCP_2_2_DEV_COUNT_LO(rx_info[1]));
7034
7035         if (dev_cnt > HDCP_2_2_MAX_DEVICE_COUNT)
7036                 dev_cnt = HDCP_2_2_MAX_DEVICE_COUNT;
7037
7038         ret = sizeof(struct hdcp2_rep_send_receiverid_list) -
7039                 HDCP_2_2_RECEIVER_IDS_MAX_LEN +
7040                 (dev_cnt * HDCP_2_2_RECEIVER_ID_LEN);
7041
7042         return ret;
7043 }
7044
7045 static
7046 int intel_dp_hdcp2_read_msg(struct intel_digital_port *intel_dig_port,
7047                             u8 msg_id, void *buf, size_t size)
7048 {
7049         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
7050         unsigned int offset;
7051         u8 *byte = buf;
7052         ssize_t ret, bytes_to_recv, len;
7053         const struct hdcp2_dp_msg_data *hdcp2_msg_data;
7054
7055         hdcp2_msg_data = get_hdcp2_dp_msg_data(msg_id);
7056         if (!hdcp2_msg_data)
7057                 return -EINVAL;
7058         offset = hdcp2_msg_data->offset;
7059
7060         ret = intel_dp_hdcp2_wait_for_msg(intel_dig_port, hdcp2_msg_data);
7061         if (ret < 0)
7062                 return ret;
7063
7064         if (msg_id == HDCP_2_2_REP_SEND_RECVID_LIST) {
7065                 ret = get_receiver_id_list_size(intel_dig_port);
7066                 if (ret < 0)
7067                         return ret;
7068
7069                 size = ret;
7070         }
7071         bytes_to_recv = size - 1;
7072
7073         /* DP adaptation msgs has no msg_id */
7074         byte++;
7075
7076         while (bytes_to_recv) {
7077                 len = bytes_to_recv > DP_AUX_MAX_PAYLOAD_BYTES ?
7078                       DP_AUX_MAX_PAYLOAD_BYTES : bytes_to_recv;
7079
7080                 ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux, offset,
7081                                        (void *)byte, len);
7082                 if (ret < 0) {
7083                         drm_dbg_kms(&i915->drm, "msg_id %d, ret %zd\n",
7084                                     msg_id, ret);
7085                         return ret;
7086                 }
7087
7088                 bytes_to_recv -= ret;
7089                 byte += ret;
7090                 offset += ret;
7091         }
7092         byte = buf;
7093         *byte = msg_id;
7094
7095         return size;
7096 }
7097
7098 static
7099 int intel_dp_hdcp2_config_stream_type(struct intel_digital_port *intel_dig_port,
7100                                       bool is_repeater, u8 content_type)
7101 {
7102         int ret;
7103         struct hdcp2_dp_errata_stream_type stream_type_msg;
7104
7105         if (is_repeater)
7106                 return 0;
7107
7108         /*
7109          * Errata for DP: As Stream type is used for encryption, Receiver
7110          * should be communicated with stream type for the decryption of the
7111          * content.
7112          * Repeater will be communicated with stream type as a part of it's
7113          * auth later in time.
7114          */
7115         stream_type_msg.msg_id = HDCP_2_2_ERRATA_DP_STREAM_TYPE;
7116         stream_type_msg.stream_type = content_type;
7117
7118         ret =  intel_dp_hdcp2_write_msg(intel_dig_port, &stream_type_msg,
7119                                         sizeof(stream_type_msg));
7120
7121         return ret < 0 ? ret : 0;
7122
7123 }
7124
7125 static
7126 int intel_dp_hdcp2_check_link(struct intel_digital_port *intel_dig_port)
7127 {
7128         u8 rx_status;
7129         int ret;
7130
7131         ret = intel_dp_hdcp2_read_rx_status(intel_dig_port, &rx_status);
7132         if (ret)
7133                 return ret;
7134
7135         if (HDCP_2_2_DP_RXSTATUS_REAUTH_REQ(rx_status))
7136                 ret = HDCP_REAUTH_REQUEST;
7137         else if (HDCP_2_2_DP_RXSTATUS_LINK_FAILED(rx_status))
7138                 ret = HDCP_LINK_INTEGRITY_FAILURE;
7139         else if (HDCP_2_2_DP_RXSTATUS_READY(rx_status))
7140                 ret = HDCP_TOPOLOGY_CHANGE;
7141
7142         return ret;
7143 }
7144
7145 static
7146 int intel_dp_hdcp2_capable(struct intel_digital_port *intel_dig_port,
7147                            bool *capable)
7148 {
7149         u8 rx_caps[3];
7150         int ret;
7151
7152         *capable = false;
7153         ret = drm_dp_dpcd_read(&intel_dig_port->dp.aux,
7154                                DP_HDCP_2_2_REG_RX_CAPS_OFFSET,
7155                                rx_caps, HDCP_2_2_RXCAPS_LEN);
7156         if (ret != HDCP_2_2_RXCAPS_LEN)
7157                 return ret >= 0 ? -EIO : ret;
7158
7159         if (rx_caps[0] == HDCP_2_2_RX_CAPS_VERSION_VAL &&
7160             HDCP_2_2_DP_HDCP_CAPABLE(rx_caps[2]))
7161                 *capable = true;
7162
7163         return 0;
7164 }
7165
7166 static const struct intel_hdcp_shim intel_dp_hdcp_shim = {
7167         .write_an_aksv = intel_dp_hdcp_write_an_aksv,
7168         .read_bksv = intel_dp_hdcp_read_bksv,
7169         .read_bstatus = intel_dp_hdcp_read_bstatus,
7170         .repeater_present = intel_dp_hdcp_repeater_present,
7171         .read_ri_prime = intel_dp_hdcp_read_ri_prime,
7172         .read_ksv_ready = intel_dp_hdcp_read_ksv_ready,
7173         .read_ksv_fifo = intel_dp_hdcp_read_ksv_fifo,
7174         .read_v_prime_part = intel_dp_hdcp_read_v_prime_part,
7175         .toggle_signalling = intel_dp_hdcp_toggle_signalling,
7176         .check_link = intel_dp_hdcp_check_link,
7177         .hdcp_capable = intel_dp_hdcp_capable,
7178         .write_2_2_msg = intel_dp_hdcp2_write_msg,
7179         .read_2_2_msg = intel_dp_hdcp2_read_msg,
7180         .config_stream_type = intel_dp_hdcp2_config_stream_type,
7181         .check_2_2_link = intel_dp_hdcp2_check_link,
7182         .hdcp_2_2_capable = intel_dp_hdcp2_capable,
7183         .protocol = HDCP_PROTOCOL_DP,
7184 };
7185
7186 static void intel_edp_panel_vdd_sanitize(struct intel_dp *intel_dp)
7187 {
7188         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7189         struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
7190
7191         lockdep_assert_held(&dev_priv->pps_mutex);
7192
7193         if (!edp_have_panel_vdd(intel_dp))
7194                 return;
7195
7196         /*
7197          * The VDD bit needs a power domain reference, so if the bit is
7198          * already enabled when we boot or resume, grab this reference and
7199          * schedule a vdd off, so we don't hold on to the reference
7200          * indefinitely.
7201          */
7202         drm_dbg_kms(&dev_priv->drm,
7203                     "VDD left on by BIOS, adjusting state tracking\n");
7204         intel_display_power_get(dev_priv, intel_aux_power_domain(dig_port));
7205
7206         edp_panel_vdd_schedule_off(intel_dp);
7207 }
7208
7209 static enum pipe vlv_active_pipe(struct intel_dp *intel_dp)
7210 {
7211         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7212         struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
7213         enum pipe pipe;
7214
7215         if (intel_dp_port_enabled(dev_priv, intel_dp->output_reg,
7216                                   encoder->port, &pipe))
7217                 return pipe;
7218
7219         return INVALID_PIPE;
7220 }
7221
7222 void intel_dp_encoder_reset(struct drm_encoder *encoder)
7223 {
7224         struct drm_i915_private *dev_priv = to_i915(encoder->dev);
7225         struct intel_dp *intel_dp = enc_to_intel_dp(to_intel_encoder(encoder));
7226         struct intel_lspcon *lspcon = dp_to_lspcon(intel_dp);
7227         intel_wakeref_t wakeref;
7228
7229         if (!HAS_DDI(dev_priv))
7230                 intel_dp->DP = intel_de_read(dev_priv, intel_dp->output_reg);
7231
7232         if (lspcon->active)
7233                 lspcon_resume(lspcon);
7234
7235         intel_dp->reset_link_params = true;
7236
7237         if (!IS_VALLEYVIEW(dev_priv) && !IS_CHERRYVIEW(dev_priv) &&
7238             !intel_dp_is_edp(intel_dp))
7239                 return;
7240
7241         with_pps_lock(intel_dp, wakeref) {
7242                 if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
7243                         intel_dp->active_pipe = vlv_active_pipe(intel_dp);
7244
7245                 if (intel_dp_is_edp(intel_dp)) {
7246                         /*
7247                          * Reinit the power sequencer, in case BIOS did
7248                          * something nasty with it.
7249                          */
7250                         intel_dp_pps_init(intel_dp);
7251                         intel_edp_panel_vdd_sanitize(intel_dp);
7252                 }
7253         }
7254 }
7255
7256 static int intel_modeset_tile_group(struct intel_atomic_state *state,
7257                                     int tile_group_id)
7258 {
7259         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
7260         struct drm_connector_list_iter conn_iter;
7261         struct drm_connector *connector;
7262         int ret = 0;
7263
7264         drm_connector_list_iter_begin(&dev_priv->drm, &conn_iter);
7265         drm_for_each_connector_iter(connector, &conn_iter) {
7266                 struct drm_connector_state *conn_state;
7267                 struct intel_crtc_state *crtc_state;
7268                 struct intel_crtc *crtc;
7269
7270                 if (!connector->has_tile ||
7271                     connector->tile_group->id != tile_group_id)
7272                         continue;
7273
7274                 conn_state = drm_atomic_get_connector_state(&state->base,
7275                                                             connector);
7276                 if (IS_ERR(conn_state)) {
7277                         ret = PTR_ERR(conn_state);
7278                         break;
7279                 }
7280
7281                 crtc = to_intel_crtc(conn_state->crtc);
7282
7283                 if (!crtc)
7284                         continue;
7285
7286                 crtc_state = intel_atomic_get_new_crtc_state(state, crtc);
7287                 crtc_state->uapi.mode_changed = true;
7288
7289                 ret = drm_atomic_add_affected_planes(&state->base, &crtc->base);
7290                 if (ret)
7291                         break;
7292         }
7293         drm_connector_list_iter_end(&conn_iter);
7294
7295         return ret;
7296 }
7297
7298 static int intel_modeset_affected_transcoders(struct intel_atomic_state *state, u8 transcoders)
7299 {
7300         struct drm_i915_private *dev_priv = to_i915(state->base.dev);
7301         struct intel_crtc *crtc;
7302
7303         if (transcoders == 0)
7304                 return 0;
7305
7306         for_each_intel_crtc(&dev_priv->drm, crtc) {
7307                 struct intel_crtc_state *crtc_state;
7308                 int ret;
7309
7310                 crtc_state = intel_atomic_get_crtc_state(&state->base, crtc);
7311                 if (IS_ERR(crtc_state))
7312                         return PTR_ERR(crtc_state);
7313
7314                 if (!crtc_state->hw.enable)
7315                         continue;
7316
7317                 if (!(transcoders & BIT(crtc_state->cpu_transcoder)))
7318                         continue;
7319
7320                 crtc_state->uapi.mode_changed = true;
7321
7322                 ret = drm_atomic_add_affected_connectors(&state->base, &crtc->base);
7323                 if (ret)
7324                         return ret;
7325
7326                 ret = drm_atomic_add_affected_planes(&state->base, &crtc->base);
7327                 if (ret)
7328                         return ret;
7329
7330                 transcoders &= ~BIT(crtc_state->cpu_transcoder);
7331         }
7332
7333         drm_WARN_ON(&dev_priv->drm, transcoders != 0);
7334
7335         return 0;
7336 }
7337
7338 static int intel_modeset_synced_crtcs(struct intel_atomic_state *state,
7339                                       struct drm_connector *connector)
7340 {
7341         const struct drm_connector_state *old_conn_state =
7342                 drm_atomic_get_old_connector_state(&state->base, connector);
7343         const struct intel_crtc_state *old_crtc_state;
7344         struct intel_crtc *crtc;
7345         u8 transcoders;
7346
7347         crtc = to_intel_crtc(old_conn_state->crtc);
7348         if (!crtc)
7349                 return 0;
7350
7351         old_crtc_state = intel_atomic_get_old_crtc_state(state, crtc);
7352
7353         if (!old_crtc_state->hw.active)
7354                 return 0;
7355
7356         transcoders = old_crtc_state->sync_mode_slaves_mask;
7357         if (old_crtc_state->master_transcoder != INVALID_TRANSCODER)
7358                 transcoders |= BIT(old_crtc_state->master_transcoder);
7359
7360         return intel_modeset_affected_transcoders(state,
7361                                                   transcoders);
7362 }
7363
7364 static int intel_dp_connector_atomic_check(struct drm_connector *conn,
7365                                            struct drm_atomic_state *_state)
7366 {
7367         struct drm_i915_private *dev_priv = to_i915(conn->dev);
7368         struct intel_atomic_state *state = to_intel_atomic_state(_state);
7369         int ret;
7370
7371         ret = intel_digital_connector_atomic_check(conn, &state->base);
7372         if (ret)
7373                 return ret;
7374
7375         /*
7376          * We don't enable port sync on BDW due to missing w/as and
7377          * due to not having adjusted the modeset sequence appropriately.
7378          */
7379         if (INTEL_GEN(dev_priv) < 9)
7380                 return 0;
7381
7382         if (!intel_connector_needs_modeset(state, conn))
7383                 return 0;
7384
7385         if (conn->has_tile) {
7386                 ret = intel_modeset_tile_group(state, conn->tile_group->id);
7387                 if (ret)
7388                         return ret;
7389         }
7390
7391         return intel_modeset_synced_crtcs(state, conn);
7392 }
7393
7394 static const struct drm_connector_funcs intel_dp_connector_funcs = {
7395         .force = intel_dp_force,
7396         .fill_modes = drm_helper_probe_single_connector_modes,
7397         .atomic_get_property = intel_digital_connector_atomic_get_property,
7398         .atomic_set_property = intel_digital_connector_atomic_set_property,
7399         .late_register = intel_dp_connector_register,
7400         .early_unregister = intel_dp_connector_unregister,
7401         .destroy = intel_connector_destroy,
7402         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
7403         .atomic_duplicate_state = intel_digital_connector_duplicate_state,
7404 };
7405
7406 static const struct drm_connector_helper_funcs intel_dp_connector_helper_funcs = {
7407         .detect_ctx = intel_dp_detect,
7408         .get_modes = intel_dp_get_modes,
7409         .mode_valid = intel_dp_mode_valid,
7410         .atomic_check = intel_dp_connector_atomic_check,
7411 };
7412
7413 static const struct drm_encoder_funcs intel_dp_enc_funcs = {
7414         .reset = intel_dp_encoder_reset,
7415         .destroy = intel_dp_encoder_destroy,
7416 };
7417
7418 static bool intel_edp_have_power(struct intel_dp *intel_dp)
7419 {
7420         intel_wakeref_t wakeref;
7421         bool have_power = false;
7422
7423         with_pps_lock(intel_dp, wakeref) {
7424                 have_power = edp_have_panel_power(intel_dp) &&
7425                                                   edp_have_panel_vdd(intel_dp);
7426         }
7427
7428         return have_power;
7429 }
7430
7431 enum irqreturn
7432 intel_dp_hpd_pulse(struct intel_digital_port *intel_dig_port, bool long_hpd)
7433 {
7434         struct drm_i915_private *i915 = to_i915(intel_dig_port->base.base.dev);
7435         struct intel_dp *intel_dp = &intel_dig_port->dp;
7436
7437         if (intel_dig_port->base.type == INTEL_OUTPUT_EDP &&
7438             (long_hpd || !intel_edp_have_power(intel_dp))) {
7439                 /*
7440                  * vdd off can generate a long/short pulse on eDP which
7441                  * would require vdd on to handle it, and thus we
7442                  * would end up in an endless cycle of
7443                  * "vdd off -> long/short hpd -> vdd on -> detect -> vdd off -> ..."
7444                  */
7445                 drm_dbg_kms(&i915->drm,
7446                             "ignoring %s hpd on eDP [ENCODER:%d:%s]\n",
7447                             long_hpd ? "long" : "short",
7448                             intel_dig_port->base.base.base.id,
7449                             intel_dig_port->base.base.name);
7450                 return IRQ_HANDLED;
7451         }
7452
7453         drm_dbg_kms(&i915->drm, "got hpd irq on [ENCODER:%d:%s] - %s\n",
7454                     intel_dig_port->base.base.base.id,
7455                     intel_dig_port->base.base.name,
7456                     long_hpd ? "long" : "short");
7457
7458         if (long_hpd) {
7459                 intel_dp->reset_link_params = true;
7460                 return IRQ_NONE;
7461         }
7462
7463         if (intel_dp->is_mst) {
7464                 switch (intel_dp_check_mst_status(intel_dp)) {
7465                 case -EINVAL:
7466                         /*
7467                          * If we were in MST mode, and device is not
7468                          * there, get out of MST mode
7469                          */
7470                         drm_dbg_kms(&i915->drm,
7471                                     "MST device may have disappeared %d vs %d\n",
7472                                     intel_dp->is_mst,
7473                                     intel_dp->mst_mgr.mst_state);
7474                         intel_dp->is_mst = false;
7475                         drm_dp_mst_topology_mgr_set_mst(&intel_dp->mst_mgr,
7476                                                         intel_dp->is_mst);
7477
7478                         return IRQ_NONE;
7479                 case 1:
7480                         return IRQ_NONE;
7481                 default:
7482                         break;
7483                 }
7484         }
7485
7486         if (!intel_dp->is_mst) {
7487                 bool handled;
7488
7489                 handled = intel_dp_short_pulse(intel_dp);
7490
7491                 if (!handled)
7492                         return IRQ_NONE;
7493         }
7494
7495         return IRQ_HANDLED;
7496 }
7497
7498 /* check the VBT to see whether the eDP is on another port */
7499 bool intel_dp_is_port_edp(struct drm_i915_private *dev_priv, enum port port)
7500 {
7501         /*
7502          * eDP not supported on g4x. so bail out early just
7503          * for a bit extra safety in case the VBT is bonkers.
7504          */
7505         if (INTEL_GEN(dev_priv) < 5)
7506                 return false;
7507
7508         if (INTEL_GEN(dev_priv) < 9 && port == PORT_A)
7509                 return true;
7510
7511         return intel_bios_is_port_edp(dev_priv, port);
7512 }
7513
7514 static void
7515 intel_dp_add_properties(struct intel_dp *intel_dp, struct drm_connector *connector)
7516 {
7517         struct drm_i915_private *dev_priv = to_i915(connector->dev);
7518         enum port port = dp_to_dig_port(intel_dp)->base.port;
7519
7520         if (!IS_G4X(dev_priv) && port != PORT_A)
7521                 intel_attach_force_audio_property(connector);
7522
7523         intel_attach_broadcast_rgb_property(connector);
7524         if (HAS_GMCH(dev_priv))
7525                 drm_connector_attach_max_bpc_property(connector, 6, 10);
7526         else if (INTEL_GEN(dev_priv) >= 5)
7527                 drm_connector_attach_max_bpc_property(connector, 6, 12);
7528
7529         intel_attach_colorspace_property(connector);
7530
7531         if (IS_GEMINILAKE(dev_priv) || INTEL_GEN(dev_priv) >= 11)
7532                 drm_object_attach_property(&connector->base,
7533                                            connector->dev->mode_config.hdr_output_metadata_property,
7534                                            0);
7535
7536         if (intel_dp_is_edp(intel_dp)) {
7537                 u32 allowed_scalers;
7538
7539                 allowed_scalers = BIT(DRM_MODE_SCALE_ASPECT) | BIT(DRM_MODE_SCALE_FULLSCREEN);
7540                 if (!HAS_GMCH(dev_priv))
7541                         allowed_scalers |= BIT(DRM_MODE_SCALE_CENTER);
7542
7543                 drm_connector_attach_scaling_mode_property(connector, allowed_scalers);
7544
7545                 connector->state->scaling_mode = DRM_MODE_SCALE_ASPECT;
7546
7547         }
7548 }
7549
7550 static void intel_dp_init_panel_power_timestamps(struct intel_dp *intel_dp)
7551 {
7552         intel_dp->panel_power_off_time = ktime_get_boottime();
7553         intel_dp->last_power_on = jiffies;
7554         intel_dp->last_backlight_off = jiffies;
7555 }
7556
7557 static void
7558 intel_pps_readout_hw_state(struct intel_dp *intel_dp, struct edp_power_seq *seq)
7559 {
7560         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7561         u32 pp_on, pp_off, pp_ctl;
7562         struct pps_registers regs;
7563
7564         intel_pps_get_registers(intel_dp, &regs);
7565
7566         pp_ctl = ilk_get_pp_control(intel_dp);
7567
7568         /* Ensure PPS is unlocked */
7569         if (!HAS_DDI(dev_priv))
7570                 intel_de_write(dev_priv, regs.pp_ctrl, pp_ctl);
7571
7572         pp_on = intel_de_read(dev_priv, regs.pp_on);
7573         pp_off = intel_de_read(dev_priv, regs.pp_off);
7574
7575         /* Pull timing values out of registers */
7576         seq->t1_t3 = REG_FIELD_GET(PANEL_POWER_UP_DELAY_MASK, pp_on);
7577         seq->t8 = REG_FIELD_GET(PANEL_LIGHT_ON_DELAY_MASK, pp_on);
7578         seq->t9 = REG_FIELD_GET(PANEL_LIGHT_OFF_DELAY_MASK, pp_off);
7579         seq->t10 = REG_FIELD_GET(PANEL_POWER_DOWN_DELAY_MASK, pp_off);
7580
7581         if (i915_mmio_reg_valid(regs.pp_div)) {
7582                 u32 pp_div;
7583
7584                 pp_div = intel_de_read(dev_priv, regs.pp_div);
7585
7586                 seq->t11_t12 = REG_FIELD_GET(PANEL_POWER_CYCLE_DELAY_MASK, pp_div) * 1000;
7587         } else {
7588                 seq->t11_t12 = REG_FIELD_GET(BXT_POWER_CYCLE_DELAY_MASK, pp_ctl) * 1000;
7589         }
7590 }
7591
7592 static void
7593 intel_pps_dump_state(const char *state_name, const struct edp_power_seq *seq)
7594 {
7595         DRM_DEBUG_KMS("%s t1_t3 %d t8 %d t9 %d t10 %d t11_t12 %d\n",
7596                       state_name,
7597                       seq->t1_t3, seq->t8, seq->t9, seq->t10, seq->t11_t12);
7598 }
7599
7600 static void
7601 intel_pps_verify_state(struct intel_dp *intel_dp)
7602 {
7603         struct edp_power_seq hw;
7604         struct edp_power_seq *sw = &intel_dp->pps_delays;
7605
7606         intel_pps_readout_hw_state(intel_dp, &hw);
7607
7608         if (hw.t1_t3 != sw->t1_t3 || hw.t8 != sw->t8 || hw.t9 != sw->t9 ||
7609             hw.t10 != sw->t10 || hw.t11_t12 != sw->t11_t12) {
7610                 DRM_ERROR("PPS state mismatch\n");
7611                 intel_pps_dump_state("sw", sw);
7612                 intel_pps_dump_state("hw", &hw);
7613         }
7614 }
7615
7616 static void
7617 intel_dp_init_panel_power_sequencer(struct intel_dp *intel_dp)
7618 {
7619         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7620         struct edp_power_seq cur, vbt, spec,
7621                 *final = &intel_dp->pps_delays;
7622
7623         lockdep_assert_held(&dev_priv->pps_mutex);
7624
7625         /* already initialized? */
7626         if (final->t11_t12 != 0)
7627                 return;
7628
7629         intel_pps_readout_hw_state(intel_dp, &cur);
7630
7631         intel_pps_dump_state("cur", &cur);
7632
7633         vbt = dev_priv->vbt.edp.pps;
7634         /* On Toshiba Satellite P50-C-18C system the VBT T12 delay
7635          * of 500ms appears to be too short. Ocassionally the panel
7636          * just fails to power back on. Increasing the delay to 800ms
7637          * seems sufficient to avoid this problem.
7638          */
7639         if (dev_priv->quirks & QUIRK_INCREASE_T12_DELAY) {
7640                 vbt.t11_t12 = max_t(u16, vbt.t11_t12, 1300 * 10);
7641                 drm_dbg_kms(&dev_priv->drm,
7642                             "Increasing T12 panel delay as per the quirk to %d\n",
7643                             vbt.t11_t12);
7644         }
7645         /* T11_T12 delay is special and actually in units of 100ms, but zero
7646          * based in the hw (so we need to add 100 ms). But the sw vbt
7647          * table multiplies it with 1000 to make it in units of 100usec,
7648          * too. */
7649         vbt.t11_t12 += 100 * 10;
7650
7651         /* Upper limits from eDP 1.3 spec. Note that we use the clunky units of
7652          * our hw here, which are all in 100usec. */
7653         spec.t1_t3 = 210 * 10;
7654         spec.t8 = 50 * 10; /* no limit for t8, use t7 instead */
7655         spec.t9 = 50 * 10; /* no limit for t9, make it symmetric with t8 */
7656         spec.t10 = 500 * 10;
7657         /* This one is special and actually in units of 100ms, but zero
7658          * based in the hw (so we need to add 100 ms). But the sw vbt
7659          * table multiplies it with 1000 to make it in units of 100usec,
7660          * too. */
7661         spec.t11_t12 = (510 + 100) * 10;
7662
7663         intel_pps_dump_state("vbt", &vbt);
7664
7665         /* Use the max of the register settings and vbt. If both are
7666          * unset, fall back to the spec limits. */
7667 #define assign_final(field)     final->field = (max(cur.field, vbt.field) == 0 ? \
7668                                        spec.field : \
7669                                        max(cur.field, vbt.field))
7670         assign_final(t1_t3);
7671         assign_final(t8);
7672         assign_final(t9);
7673         assign_final(t10);
7674         assign_final(t11_t12);
7675 #undef assign_final
7676
7677 #define get_delay(field)        (DIV_ROUND_UP(final->field, 10))
7678         intel_dp->panel_power_up_delay = get_delay(t1_t3);
7679         intel_dp->backlight_on_delay = get_delay(t8);
7680         intel_dp->backlight_off_delay = get_delay(t9);
7681         intel_dp->panel_power_down_delay = get_delay(t10);
7682         intel_dp->panel_power_cycle_delay = get_delay(t11_t12);
7683 #undef get_delay
7684
7685         drm_dbg_kms(&dev_priv->drm,
7686                     "panel power up delay %d, power down delay %d, power cycle delay %d\n",
7687                     intel_dp->panel_power_up_delay,
7688                     intel_dp->panel_power_down_delay,
7689                     intel_dp->panel_power_cycle_delay);
7690
7691         drm_dbg_kms(&dev_priv->drm, "backlight on delay %d, off delay %d\n",
7692                     intel_dp->backlight_on_delay,
7693                     intel_dp->backlight_off_delay);
7694
7695         /*
7696          * We override the HW backlight delays to 1 because we do manual waits
7697          * on them. For T8, even BSpec recommends doing it. For T9, if we
7698          * don't do this, we'll end up waiting for the backlight off delay
7699          * twice: once when we do the manual sleep, and once when we disable
7700          * the panel and wait for the PP_STATUS bit to become zero.
7701          */
7702         final->t8 = 1;
7703         final->t9 = 1;
7704
7705         /*
7706          * HW has only a 100msec granularity for t11_t12 so round it up
7707          * accordingly.
7708          */
7709         final->t11_t12 = roundup(final->t11_t12, 100 * 10);
7710 }
7711
7712 static void
7713 intel_dp_init_panel_power_sequencer_registers(struct intel_dp *intel_dp,
7714                                               bool force_disable_vdd)
7715 {
7716         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7717         u32 pp_on, pp_off, port_sel = 0;
7718         int div = RUNTIME_INFO(dev_priv)->rawclk_freq / 1000;
7719         struct pps_registers regs;
7720         enum port port = dp_to_dig_port(intel_dp)->base.port;
7721         const struct edp_power_seq *seq = &intel_dp->pps_delays;
7722
7723         lockdep_assert_held(&dev_priv->pps_mutex);
7724
7725         intel_pps_get_registers(intel_dp, &regs);
7726
7727         /*
7728          * On some VLV machines the BIOS can leave the VDD
7729          * enabled even on power sequencers which aren't
7730          * hooked up to any port. This would mess up the
7731          * power domain tracking the first time we pick
7732          * one of these power sequencers for use since
7733          * edp_panel_vdd_on() would notice that the VDD was
7734          * already on and therefore wouldn't grab the power
7735          * domain reference. Disable VDD first to avoid this.
7736          * This also avoids spuriously turning the VDD on as
7737          * soon as the new power sequencer gets initialized.
7738          */
7739         if (force_disable_vdd) {
7740                 u32 pp = ilk_get_pp_control(intel_dp);
7741
7742                 drm_WARN(&dev_priv->drm, pp & PANEL_POWER_ON,
7743                          "Panel power already on\n");
7744
7745                 if (pp & EDP_FORCE_VDD)
7746                         drm_dbg_kms(&dev_priv->drm,
7747                                     "VDD already on, disabling first\n");
7748
7749                 pp &= ~EDP_FORCE_VDD;
7750
7751                 intel_de_write(dev_priv, regs.pp_ctrl, pp);
7752         }
7753
7754         pp_on = REG_FIELD_PREP(PANEL_POWER_UP_DELAY_MASK, seq->t1_t3) |
7755                 REG_FIELD_PREP(PANEL_LIGHT_ON_DELAY_MASK, seq->t8);
7756         pp_off = REG_FIELD_PREP(PANEL_LIGHT_OFF_DELAY_MASK, seq->t9) |
7757                 REG_FIELD_PREP(PANEL_POWER_DOWN_DELAY_MASK, seq->t10);
7758
7759         /* Haswell doesn't have any port selection bits for the panel
7760          * power sequencer any more. */
7761         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
7762                 port_sel = PANEL_PORT_SELECT_VLV(port);
7763         } else if (HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)) {
7764                 switch (port) {
7765                 case PORT_A:
7766                         port_sel = PANEL_PORT_SELECT_DPA;
7767                         break;
7768                 case PORT_C:
7769                         port_sel = PANEL_PORT_SELECT_DPC;
7770                         break;
7771                 case PORT_D:
7772                         port_sel = PANEL_PORT_SELECT_DPD;
7773                         break;
7774                 default:
7775                         MISSING_CASE(port);
7776                         break;
7777                 }
7778         }
7779
7780         pp_on |= port_sel;
7781
7782         intel_de_write(dev_priv, regs.pp_on, pp_on);
7783         intel_de_write(dev_priv, regs.pp_off, pp_off);
7784
7785         /*
7786          * Compute the divisor for the pp clock, simply match the Bspec formula.
7787          */
7788         if (i915_mmio_reg_valid(regs.pp_div)) {
7789                 intel_de_write(dev_priv, regs.pp_div,
7790                                REG_FIELD_PREP(PP_REFERENCE_DIVIDER_MASK, (100 * div) / 2 - 1) | REG_FIELD_PREP(PANEL_POWER_CYCLE_DELAY_MASK, DIV_ROUND_UP(seq->t11_t12, 1000)));
7791         } else {
7792                 u32 pp_ctl;
7793
7794                 pp_ctl = intel_de_read(dev_priv, regs.pp_ctrl);
7795                 pp_ctl &= ~BXT_POWER_CYCLE_DELAY_MASK;
7796                 pp_ctl |= REG_FIELD_PREP(BXT_POWER_CYCLE_DELAY_MASK, DIV_ROUND_UP(seq->t11_t12, 1000));
7797                 intel_de_write(dev_priv, regs.pp_ctrl, pp_ctl);
7798         }
7799
7800         drm_dbg_kms(&dev_priv->drm,
7801                     "panel power sequencer register settings: PP_ON %#x, PP_OFF %#x, PP_DIV %#x\n",
7802                     intel_de_read(dev_priv, regs.pp_on),
7803                     intel_de_read(dev_priv, regs.pp_off),
7804                     i915_mmio_reg_valid(regs.pp_div) ?
7805                     intel_de_read(dev_priv, regs.pp_div) :
7806                     (intel_de_read(dev_priv, regs.pp_ctrl) & BXT_POWER_CYCLE_DELAY_MASK));
7807 }
7808
7809 static void intel_dp_pps_init(struct intel_dp *intel_dp)
7810 {
7811         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7812
7813         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
7814                 vlv_initial_power_sequencer_setup(intel_dp);
7815         } else {
7816                 intel_dp_init_panel_power_sequencer(intel_dp);
7817                 intel_dp_init_panel_power_sequencer_registers(intel_dp, false);
7818         }
7819 }
7820
7821 /**
7822  * intel_dp_set_drrs_state - program registers for RR switch to take effect
7823  * @dev_priv: i915 device
7824  * @crtc_state: a pointer to the active intel_crtc_state
7825  * @refresh_rate: RR to be programmed
7826  *
7827  * This function gets called when refresh rate (RR) has to be changed from
7828  * one frequency to another. Switches can be between high and low RR
7829  * supported by the panel or to any other RR based on media playback (in
7830  * this case, RR value needs to be passed from user space).
7831  *
7832  * The caller of this function needs to take a lock on dev_priv->drrs.
7833  */
7834 static void intel_dp_set_drrs_state(struct drm_i915_private *dev_priv,
7835                                     const struct intel_crtc_state *crtc_state,
7836                                     int refresh_rate)
7837 {
7838         struct intel_dp *intel_dp = dev_priv->drrs.dp;
7839         struct intel_crtc *intel_crtc = to_intel_crtc(crtc_state->uapi.crtc);
7840         enum drrs_refresh_rate_type index = DRRS_HIGH_RR;
7841
7842         if (refresh_rate <= 0) {
7843                 drm_dbg_kms(&dev_priv->drm,
7844                             "Refresh rate should be positive non-zero.\n");
7845                 return;
7846         }
7847
7848         if (intel_dp == NULL) {
7849                 drm_dbg_kms(&dev_priv->drm, "DRRS not supported.\n");
7850                 return;
7851         }
7852
7853         if (!intel_crtc) {
7854                 drm_dbg_kms(&dev_priv->drm,
7855                             "DRRS: intel_crtc not initialized\n");
7856                 return;
7857         }
7858
7859         if (dev_priv->drrs.type < SEAMLESS_DRRS_SUPPORT) {
7860                 drm_dbg_kms(&dev_priv->drm, "Only Seamless DRRS supported.\n");
7861                 return;
7862         }
7863
7864         if (intel_dp->attached_connector->panel.downclock_mode->vrefresh ==
7865                         refresh_rate)
7866                 index = DRRS_LOW_RR;
7867
7868         if (index == dev_priv->drrs.refresh_rate_type) {
7869                 drm_dbg_kms(&dev_priv->drm,
7870                             "DRRS requested for previously set RR...ignoring\n");
7871                 return;
7872         }
7873
7874         if (!crtc_state->hw.active) {
7875                 drm_dbg_kms(&dev_priv->drm,
7876                             "eDP encoder disabled. CRTC not Active\n");
7877                 return;
7878         }
7879
7880         if (INTEL_GEN(dev_priv) >= 8 && !IS_CHERRYVIEW(dev_priv)) {
7881                 switch (index) {
7882                 case DRRS_HIGH_RR:
7883                         intel_dp_set_m_n(crtc_state, M1_N1);
7884                         break;
7885                 case DRRS_LOW_RR:
7886                         intel_dp_set_m_n(crtc_state, M2_N2);
7887                         break;
7888                 case DRRS_MAX_RR:
7889                 default:
7890                         drm_err(&dev_priv->drm,
7891                                 "Unsupported refreshrate type\n");
7892                 }
7893         } else if (INTEL_GEN(dev_priv) > 6) {
7894                 i915_reg_t reg = PIPECONF(crtc_state->cpu_transcoder);
7895                 u32 val;
7896
7897                 val = intel_de_read(dev_priv, reg);
7898                 if (index > DRRS_HIGH_RR) {
7899                         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
7900                                 val |= PIPECONF_EDP_RR_MODE_SWITCH_VLV;
7901                         else
7902                                 val |= PIPECONF_EDP_RR_MODE_SWITCH;
7903                 } else {
7904                         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
7905                                 val &= ~PIPECONF_EDP_RR_MODE_SWITCH_VLV;
7906                         else
7907                                 val &= ~PIPECONF_EDP_RR_MODE_SWITCH;
7908                 }
7909                 intel_de_write(dev_priv, reg, val);
7910         }
7911
7912         dev_priv->drrs.refresh_rate_type = index;
7913
7914         drm_dbg_kms(&dev_priv->drm, "eDP Refresh Rate set to : %dHz\n",
7915                     refresh_rate);
7916 }
7917
7918 /**
7919  * intel_edp_drrs_enable - init drrs struct if supported
7920  * @intel_dp: DP struct
7921  * @crtc_state: A pointer to the active crtc state.
7922  *
7923  * Initializes frontbuffer_bits and drrs.dp
7924  */
7925 void intel_edp_drrs_enable(struct intel_dp *intel_dp,
7926                            const struct intel_crtc_state *crtc_state)
7927 {
7928         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7929
7930         if (!crtc_state->has_drrs) {
7931                 drm_dbg_kms(&dev_priv->drm, "Panel doesn't support DRRS\n");
7932                 return;
7933         }
7934
7935         if (dev_priv->psr.enabled) {
7936                 drm_dbg_kms(&dev_priv->drm,
7937                             "PSR enabled. Not enabling DRRS.\n");
7938                 return;
7939         }
7940
7941         mutex_lock(&dev_priv->drrs.mutex);
7942         if (dev_priv->drrs.dp) {
7943                 drm_dbg_kms(&dev_priv->drm, "DRRS already enabled\n");
7944                 goto unlock;
7945         }
7946
7947         dev_priv->drrs.busy_frontbuffer_bits = 0;
7948
7949         dev_priv->drrs.dp = intel_dp;
7950
7951 unlock:
7952         mutex_unlock(&dev_priv->drrs.mutex);
7953 }
7954
7955 /**
7956  * intel_edp_drrs_disable - Disable DRRS
7957  * @intel_dp: DP struct
7958  * @old_crtc_state: Pointer to old crtc_state.
7959  *
7960  */
7961 void intel_edp_drrs_disable(struct intel_dp *intel_dp,
7962                             const struct intel_crtc_state *old_crtc_state)
7963 {
7964         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
7965
7966         if (!old_crtc_state->has_drrs)
7967                 return;
7968
7969         mutex_lock(&dev_priv->drrs.mutex);
7970         if (!dev_priv->drrs.dp) {
7971                 mutex_unlock(&dev_priv->drrs.mutex);
7972                 return;
7973         }
7974
7975         if (dev_priv->drrs.refresh_rate_type == DRRS_LOW_RR)
7976                 intel_dp_set_drrs_state(dev_priv, old_crtc_state,
7977                         intel_dp->attached_connector->panel.fixed_mode->vrefresh);
7978
7979         dev_priv->drrs.dp = NULL;
7980         mutex_unlock(&dev_priv->drrs.mutex);
7981
7982         cancel_delayed_work_sync(&dev_priv->drrs.work);
7983 }
7984
7985 static void intel_edp_drrs_downclock_work(struct work_struct *work)
7986 {
7987         struct drm_i915_private *dev_priv =
7988                 container_of(work, typeof(*dev_priv), drrs.work.work);
7989         struct intel_dp *intel_dp;
7990
7991         mutex_lock(&dev_priv->drrs.mutex);
7992
7993         intel_dp = dev_priv->drrs.dp;
7994
7995         if (!intel_dp)
7996                 goto unlock;
7997
7998         /*
7999          * The delayed work can race with an invalidate hence we need to
8000          * recheck.
8001          */
8002
8003         if (dev_priv->drrs.busy_frontbuffer_bits)
8004                 goto unlock;
8005
8006         if (dev_priv->drrs.refresh_rate_type != DRRS_LOW_RR) {
8007                 struct drm_crtc *crtc = dp_to_dig_port(intel_dp)->base.base.crtc;
8008
8009                 intel_dp_set_drrs_state(dev_priv, to_intel_crtc(crtc)->config,
8010                         intel_dp->attached_connector->panel.downclock_mode->vrefresh);
8011         }
8012
8013 unlock:
8014         mutex_unlock(&dev_priv->drrs.mutex);
8015 }
8016
8017 /**
8018  * intel_edp_drrs_invalidate - Disable Idleness DRRS
8019  * @dev_priv: i915 device
8020  * @frontbuffer_bits: frontbuffer plane tracking bits
8021  *
8022  * This function gets called everytime rendering on the given planes start.
8023  * Hence DRRS needs to be Upclocked, i.e. (LOW_RR -> HIGH_RR).
8024  *
8025  * Dirty frontbuffers relevant to DRRS are tracked in busy_frontbuffer_bits.
8026  */
8027 void intel_edp_drrs_invalidate(struct drm_i915_private *dev_priv,
8028                                unsigned int frontbuffer_bits)
8029 {
8030         struct drm_crtc *crtc;
8031         enum pipe pipe;
8032
8033         if (dev_priv->drrs.type == DRRS_NOT_SUPPORTED)
8034                 return;
8035
8036         cancel_delayed_work(&dev_priv->drrs.work);
8037
8038         mutex_lock(&dev_priv->drrs.mutex);
8039         if (!dev_priv->drrs.dp) {
8040                 mutex_unlock(&dev_priv->drrs.mutex);
8041                 return;
8042         }
8043
8044         crtc = dp_to_dig_port(dev_priv->drrs.dp)->base.base.crtc;
8045         pipe = to_intel_crtc(crtc)->pipe;
8046
8047         frontbuffer_bits &= INTEL_FRONTBUFFER_ALL_MASK(pipe);
8048         dev_priv->drrs.busy_frontbuffer_bits |= frontbuffer_bits;
8049
8050         /* invalidate means busy screen hence upclock */
8051         if (frontbuffer_bits && dev_priv->drrs.refresh_rate_type == DRRS_LOW_RR)
8052                 intel_dp_set_drrs_state(dev_priv, to_intel_crtc(crtc)->config,
8053                         dev_priv->drrs.dp->attached_connector->panel.fixed_mode->vrefresh);
8054
8055         mutex_unlock(&dev_priv->drrs.mutex);
8056 }
8057
8058 /**
8059  * intel_edp_drrs_flush - Restart Idleness DRRS
8060  * @dev_priv: i915 device
8061  * @frontbuffer_bits: frontbuffer plane tracking bits
8062  *
8063  * This function gets called every time rendering on the given planes has
8064  * completed or flip on a crtc is completed. So DRRS should be upclocked
8065  * (LOW_RR -> HIGH_RR). And also Idleness detection should be started again,
8066  * if no other planes are dirty.
8067  *
8068  * Dirty frontbuffers relevant to DRRS are tracked in busy_frontbuffer_bits.
8069  */
8070 void intel_edp_drrs_flush(struct drm_i915_private *dev_priv,
8071                           unsigned int frontbuffer_bits)
8072 {
8073         struct drm_crtc *crtc;
8074         enum pipe pipe;
8075
8076         if (dev_priv->drrs.type == DRRS_NOT_SUPPORTED)
8077                 return;
8078
8079         cancel_delayed_work(&dev_priv->drrs.work);
8080
8081         mutex_lock(&dev_priv->drrs.mutex);
8082         if (!dev_priv->drrs.dp) {
8083                 mutex_unlock(&dev_priv->drrs.mutex);
8084                 return;
8085         }
8086
8087         crtc = dp_to_dig_port(dev_priv->drrs.dp)->base.base.crtc;
8088         pipe = to_intel_crtc(crtc)->pipe;
8089
8090         frontbuffer_bits &= INTEL_FRONTBUFFER_ALL_MASK(pipe);
8091         dev_priv->drrs.busy_frontbuffer_bits &= ~frontbuffer_bits;
8092
8093         /* flush means busy screen hence upclock */
8094         if (frontbuffer_bits && dev_priv->drrs.refresh_rate_type == DRRS_LOW_RR)
8095                 intel_dp_set_drrs_state(dev_priv, to_intel_crtc(crtc)->config,
8096                                 dev_priv->drrs.dp->attached_connector->panel.fixed_mode->vrefresh);
8097
8098         /*
8099          * flush also means no more activity hence schedule downclock, if all
8100          * other fbs are quiescent too
8101          */
8102         if (!dev_priv->drrs.busy_frontbuffer_bits)
8103                 schedule_delayed_work(&dev_priv->drrs.work,
8104                                 msecs_to_jiffies(1000));
8105         mutex_unlock(&dev_priv->drrs.mutex);
8106 }
8107
8108 /**
8109  * DOC: Display Refresh Rate Switching (DRRS)
8110  *
8111  * Display Refresh Rate Switching (DRRS) is a power conservation feature
8112  * which enables swtching between low and high refresh rates,
8113  * dynamically, based on the usage scenario. This feature is applicable
8114  * for internal panels.
8115  *
8116  * Indication that the panel supports DRRS is given by the panel EDID, which
8117  * would list multiple refresh rates for one resolution.
8118  *
8119  * DRRS is of 2 types - static and seamless.
8120  * Static DRRS involves changing refresh rate (RR) by doing a full modeset
8121  * (may appear as a blink on screen) and is used in dock-undock scenario.
8122  * Seamless DRRS involves changing RR without any visual effect to the user
8123  * and can be used during normal system usage. This is done by programming
8124  * certain registers.
8125  *
8126  * Support for static/seamless DRRS may be indicated in the VBT based on
8127  * inputs from the panel spec.
8128  *
8129  * DRRS saves power by switching to low RR based on usage scenarios.
8130  *
8131  * The implementation is based on frontbuffer tracking implementation.  When
8132  * there is a disturbance on the screen triggered by user activity or a periodic
8133  * system activity, DRRS is disabled (RR is changed to high RR).  When there is
8134  * no movement on screen, after a timeout of 1 second, a switch to low RR is
8135  * made.
8136  *
8137  * For integration with frontbuffer tracking code, intel_edp_drrs_invalidate()
8138  * and intel_edp_drrs_flush() are called.
8139  *
8140  * DRRS can be further extended to support other internal panels and also
8141  * the scenario of video playback wherein RR is set based on the rate
8142  * requested by userspace.
8143  */
8144
8145 /**
8146  * intel_dp_drrs_init - Init basic DRRS work and mutex.
8147  * @connector: eDP connector
8148  * @fixed_mode: preferred mode of panel
8149  *
8150  * This function is  called only once at driver load to initialize basic
8151  * DRRS stuff.
8152  *
8153  * Returns:
8154  * Downclock mode if panel supports it, else return NULL.
8155  * DRRS support is determined by the presence of downclock mode (apart
8156  * from VBT setting).
8157  */
8158 static struct drm_display_mode *
8159 intel_dp_drrs_init(struct intel_connector *connector,
8160                    struct drm_display_mode *fixed_mode)
8161 {
8162         struct drm_i915_private *dev_priv = to_i915(connector->base.dev);
8163         struct drm_display_mode *downclock_mode = NULL;
8164
8165         INIT_DELAYED_WORK(&dev_priv->drrs.work, intel_edp_drrs_downclock_work);
8166         mutex_init(&dev_priv->drrs.mutex);
8167
8168         if (INTEL_GEN(dev_priv) <= 6) {
8169                 drm_dbg_kms(&dev_priv->drm,
8170                             "DRRS supported for Gen7 and above\n");
8171                 return NULL;
8172         }
8173
8174         if (dev_priv->vbt.drrs_type != SEAMLESS_DRRS_SUPPORT) {
8175                 drm_dbg_kms(&dev_priv->drm, "VBT doesn't support DRRS\n");
8176                 return NULL;
8177         }
8178
8179         downclock_mode = intel_panel_edid_downclock_mode(connector, fixed_mode);
8180         if (!downclock_mode) {
8181                 drm_dbg_kms(&dev_priv->drm,
8182                             "Downclock mode is not found. DRRS not supported\n");
8183                 return NULL;
8184         }
8185
8186         dev_priv->drrs.type = dev_priv->vbt.drrs_type;
8187
8188         dev_priv->drrs.refresh_rate_type = DRRS_HIGH_RR;
8189         drm_dbg_kms(&dev_priv->drm,
8190                     "seamless DRRS supported for eDP panel.\n");
8191         return downclock_mode;
8192 }
8193
8194 static bool intel_edp_init_connector(struct intel_dp *intel_dp,
8195                                      struct intel_connector *intel_connector)
8196 {
8197         struct drm_i915_private *dev_priv = dp_to_i915(intel_dp);
8198         struct drm_device *dev = &dev_priv->drm;
8199         struct drm_connector *connector = &intel_connector->base;
8200         struct drm_display_mode *fixed_mode = NULL;
8201         struct drm_display_mode *downclock_mode = NULL;
8202         bool has_dpcd;
8203         enum pipe pipe = INVALID_PIPE;
8204         intel_wakeref_t wakeref;
8205         struct edid *edid;
8206
8207         if (!intel_dp_is_edp(intel_dp))
8208                 return true;
8209
8210         INIT_DELAYED_WORK(&intel_dp->panel_vdd_work, edp_panel_vdd_work);
8211
8212         /*
8213          * On IBX/CPT we may get here with LVDS already registered. Since the
8214          * driver uses the only internal power sequencer available for both
8215          * eDP and LVDS bail out early in this case to prevent interfering
8216          * with an already powered-on LVDS power sequencer.
8217          */
8218         if (intel_get_lvds_encoder(dev_priv)) {
8219                 drm_WARN_ON(dev,
8220                             !(HAS_PCH_IBX(dev_priv) || HAS_PCH_CPT(dev_priv)));
8221                 drm_info(&dev_priv->drm,
8222                          "LVDS was detected, not registering eDP\n");
8223
8224                 return false;
8225         }
8226
8227         with_pps_lock(intel_dp, wakeref) {
8228                 intel_dp_init_panel_power_timestamps(intel_dp);
8229                 intel_dp_pps_init(intel_dp);
8230                 intel_edp_panel_vdd_sanitize(intel_dp);
8231         }
8232
8233         /* Cache DPCD and EDID for edp. */
8234         has_dpcd = intel_edp_init_dpcd(intel_dp);
8235
8236         if (!has_dpcd) {
8237                 /* if this fails, presume the device is a ghost */
8238                 drm_info(&dev_priv->drm,
8239                          "failed to retrieve link info, disabling eDP\n");
8240                 goto out_vdd_off;
8241         }
8242
8243         mutex_lock(&dev->mode_config.mutex);
8244         edid = drm_get_edid(connector, &intel_dp->aux.ddc);
8245         if (edid) {
8246                 if (drm_add_edid_modes(connector, edid)) {
8247                         drm_connector_update_edid_property(connector, edid);
8248                         intel_dp->edid_quirks = drm_dp_get_edid_quirks(edid);
8249                 } else {
8250                         kfree(edid);
8251                         edid = ERR_PTR(-EINVAL);
8252                 }
8253         } else {
8254                 edid = ERR_PTR(-ENOENT);
8255         }
8256         intel_connector->edid = edid;
8257
8258         fixed_mode = intel_panel_edid_fixed_mode(intel_connector);
8259         if (fixed_mode)
8260                 downclock_mode = intel_dp_drrs_init(intel_connector, fixed_mode);
8261
8262         /* fallback to VBT if available for eDP */
8263         if (!fixed_mode)
8264                 fixed_mode = intel_panel_vbt_fixed_mode(intel_connector);
8265         mutex_unlock(&dev->mode_config.mutex);
8266
8267         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) {
8268                 intel_dp->edp_notifier.notifier_call = edp_notify_handler;
8269                 register_reboot_notifier(&intel_dp->edp_notifier);
8270
8271                 /*
8272                  * Figure out the current pipe for the initial backlight setup.
8273                  * If the current pipe isn't valid, try the PPS pipe, and if that
8274                  * fails just assume pipe A.
8275                  */
8276                 pipe = vlv_active_pipe(intel_dp);
8277
8278                 if (pipe != PIPE_A && pipe != PIPE_B)
8279                         pipe = intel_dp->pps_pipe;
8280
8281                 if (pipe != PIPE_A && pipe != PIPE_B)
8282                         pipe = PIPE_A;
8283
8284                 drm_dbg_kms(&dev_priv->drm,
8285                             "using pipe %c for initial backlight setup\n",
8286                             pipe_name(pipe));
8287         }
8288
8289         intel_panel_init(&intel_connector->panel, fixed_mode, downclock_mode);
8290         intel_connector->panel.backlight.power = intel_edp_backlight_power;
8291         intel_panel_setup_backlight(connector, pipe);
8292
8293         if (fixed_mode) {
8294                 drm_connector_set_panel_orientation_with_quirk(connector,
8295                                 dev_priv->vbt.orientation,
8296                                 fixed_mode->hdisplay, fixed_mode->vdisplay);
8297         }
8298
8299         return true;
8300
8301 out_vdd_off:
8302         cancel_delayed_work_sync(&intel_dp->panel_vdd_work);
8303         /*
8304          * vdd might still be enabled do to the delayed vdd off.
8305          * Make sure vdd is actually turned off here.
8306          */
8307         with_pps_lock(intel_dp, wakeref)
8308                 edp_panel_vdd_off_sync(intel_dp);
8309
8310         return false;
8311 }
8312
8313 static void intel_dp_modeset_retry_work_fn(struct work_struct *work)
8314 {
8315         struct intel_connector *intel_connector;
8316         struct drm_connector *connector;
8317
8318         intel_connector = container_of(work, typeof(*intel_connector),
8319                                        modeset_retry_work);
8320         connector = &intel_connector->base;
8321         DRM_DEBUG_KMS("[CONNECTOR:%d:%s]\n", connector->base.id,
8322                       connector->name);
8323
8324         /* Grab the locks before changing connector property*/
8325         mutex_lock(&connector->dev->mode_config.mutex);
8326         /* Set connector link status to BAD and send a Uevent to notify
8327          * userspace to do a modeset.
8328          */
8329         drm_connector_set_link_status_property(connector,
8330                                                DRM_MODE_LINK_STATUS_BAD);
8331         mutex_unlock(&connector->dev->mode_config.mutex);
8332         /* Send Hotplug uevent so userspace can reprobe */
8333         drm_kms_helper_hotplug_event(connector->dev);
8334 }
8335
8336 bool
8337 intel_dp_init_connector(struct intel_digital_port *intel_dig_port,
8338                         struct intel_connector *intel_connector)
8339 {
8340         struct drm_connector *connector = &intel_connector->base;
8341         struct intel_dp *intel_dp = &intel_dig_port->dp;
8342         struct intel_encoder *intel_encoder = &intel_dig_port->base;
8343         struct drm_device *dev = intel_encoder->base.dev;
8344         struct drm_i915_private *dev_priv = to_i915(dev);
8345         enum port port = intel_encoder->port;
8346         enum phy phy = intel_port_to_phy(dev_priv, port);
8347         int type;
8348
8349         /* Initialize the work for modeset in case of link train failure */
8350         INIT_WORK(&intel_connector->modeset_retry_work,
8351                   intel_dp_modeset_retry_work_fn);
8352
8353         if (drm_WARN(dev, intel_dig_port->max_lanes < 1,
8354                      "Not enough lanes (%d) for DP on [ENCODER:%d:%s]\n",
8355                      intel_dig_port->max_lanes, intel_encoder->base.base.id,
8356                      intel_encoder->base.name))
8357                 return false;
8358
8359         intel_dp_set_source_rates(intel_dp);
8360
8361         intel_dp->reset_link_params = true;
8362         intel_dp->pps_pipe = INVALID_PIPE;
8363         intel_dp->active_pipe = INVALID_PIPE;
8364
8365         /* Preserve the current hw state. */
8366         intel_dp->DP = intel_de_read(dev_priv, intel_dp->output_reg);
8367         intel_dp->attached_connector = intel_connector;
8368
8369         if (intel_dp_is_port_edp(dev_priv, port)) {
8370                 /*
8371                  * Currently we don't support eDP on TypeC ports, although in
8372                  * theory it could work on TypeC legacy ports.
8373                  */
8374                 drm_WARN_ON(dev, intel_phy_is_tc(dev_priv, phy));
8375                 type = DRM_MODE_CONNECTOR_eDP;
8376         } else {
8377                 type = DRM_MODE_CONNECTOR_DisplayPort;
8378         }
8379
8380         if (IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv))
8381                 intel_dp->active_pipe = vlv_active_pipe(intel_dp);
8382
8383         /*
8384          * For eDP we always set the encoder type to INTEL_OUTPUT_EDP, but
8385          * for DP the encoder type can be set by the caller to
8386          * INTEL_OUTPUT_UNKNOWN for DDI, so don't rewrite it.
8387          */
8388         if (type == DRM_MODE_CONNECTOR_eDP)
8389                 intel_encoder->type = INTEL_OUTPUT_EDP;
8390
8391         /* eDP only on port B and/or C on vlv/chv */
8392         if (drm_WARN_ON(dev, (IS_VALLEYVIEW(dev_priv) ||
8393                               IS_CHERRYVIEW(dev_priv)) &&
8394                         intel_dp_is_edp(intel_dp) &&
8395                         port != PORT_B && port != PORT_C))
8396                 return false;
8397
8398         drm_dbg_kms(&dev_priv->drm,
8399                     "Adding %s connector on [ENCODER:%d:%s]\n",
8400                     type == DRM_MODE_CONNECTOR_eDP ? "eDP" : "DP",
8401                     intel_encoder->base.base.id, intel_encoder->base.name);
8402
8403         drm_connector_init(dev, connector, &intel_dp_connector_funcs, type);
8404         drm_connector_helper_add(connector, &intel_dp_connector_helper_funcs);
8405
8406         if (!HAS_GMCH(dev_priv))
8407                 connector->interlace_allowed = true;
8408         connector->doublescan_allowed = 0;
8409
8410         if (INTEL_GEN(dev_priv) >= 11)
8411                 connector->ycbcr_420_allowed = true;
8412
8413         intel_encoder->hpd_pin = intel_hpd_pin_default(dev_priv, port);
8414         intel_connector->polled = DRM_CONNECTOR_POLL_HPD;
8415
8416         intel_dp_aux_init(intel_dp);
8417
8418         intel_connector_attach_encoder(intel_connector, intel_encoder);
8419
8420         if (HAS_DDI(dev_priv))
8421                 intel_connector->get_hw_state = intel_ddi_connector_get_hw_state;
8422         else
8423                 intel_connector->get_hw_state = intel_connector_get_hw_state;
8424
8425         /* init MST on ports that can support it */
8426         intel_dp_mst_encoder_init(intel_dig_port,
8427                                   intel_connector->base.base.id);
8428
8429         if (!intel_edp_init_connector(intel_dp, intel_connector)) {
8430                 intel_dp_aux_fini(intel_dp);
8431                 intel_dp_mst_encoder_cleanup(intel_dig_port);
8432                 goto fail;
8433         }
8434
8435         intel_dp_add_properties(intel_dp, connector);
8436
8437         if (is_hdcp_supported(dev_priv, port) && !intel_dp_is_edp(intel_dp)) {
8438                 int ret = intel_hdcp_init(intel_connector, &intel_dp_hdcp_shim);
8439                 if (ret)
8440                         drm_dbg_kms(&dev_priv->drm,
8441                                     "HDCP init failed, skipping.\n");
8442         }
8443
8444         /* For G4X desktop chip, PEG_BAND_GAP_DATA 3:0 must first be written
8445          * 0xd.  Failure to do so will result in spurious interrupts being
8446          * generated on the port when a cable is not attached.
8447          */
8448         if (IS_G45(dev_priv)) {
8449                 u32 temp = intel_de_read(dev_priv, PEG_BAND_GAP_DATA);
8450                 intel_de_write(dev_priv, PEG_BAND_GAP_DATA,
8451                                (temp & ~0xf) | 0xd);
8452         }
8453
8454         return true;
8455
8456 fail:
8457         drm_connector_cleanup(connector);
8458
8459         return false;
8460 }
8461
8462 bool intel_dp_init(struct drm_i915_private *dev_priv,
8463                    i915_reg_t output_reg,
8464                    enum port port)
8465 {
8466         struct intel_digital_port *intel_dig_port;
8467         struct intel_encoder *intel_encoder;
8468         struct drm_encoder *encoder;
8469         struct intel_connector *intel_connector;
8470
8471         intel_dig_port = kzalloc(sizeof(*intel_dig_port), GFP_KERNEL);
8472         if (!intel_dig_port)
8473                 return false;
8474
8475         intel_connector = intel_connector_alloc();
8476         if (!intel_connector)
8477                 goto err_connector_alloc;
8478
8479         intel_encoder = &intel_dig_port->base;
8480         encoder = &intel_encoder->base;
8481
8482         if (drm_encoder_init(&dev_priv->drm, &intel_encoder->base,
8483                              &intel_dp_enc_funcs, DRM_MODE_ENCODER_TMDS,
8484                              "DP %c", port_name(port)))
8485                 goto err_encoder_init;
8486
8487         intel_encoder->hotplug = intel_dp_hotplug;
8488         intel_encoder->compute_config = intel_dp_compute_config;
8489         intel_encoder->get_hw_state = intel_dp_get_hw_state;
8490         intel_encoder->get_config = intel_dp_get_config;
8491         intel_encoder->update_pipe = intel_panel_update_backlight;
8492         intel_encoder->suspend = intel_dp_encoder_suspend;
8493         if (IS_CHERRYVIEW(dev_priv)) {
8494                 intel_encoder->pre_pll_enable = chv_dp_pre_pll_enable;
8495                 intel_encoder->pre_enable = chv_pre_enable_dp;
8496                 intel_encoder->enable = vlv_enable_dp;
8497                 intel_encoder->disable = vlv_disable_dp;
8498                 intel_encoder->post_disable = chv_post_disable_dp;
8499                 intel_encoder->post_pll_disable = chv_dp_post_pll_disable;
8500         } else if (IS_VALLEYVIEW(dev_priv)) {
8501                 intel_encoder->pre_pll_enable = vlv_dp_pre_pll_enable;
8502                 intel_encoder->pre_enable = vlv_pre_enable_dp;
8503                 intel_encoder->enable = vlv_enable_dp;
8504                 intel_encoder->disable = vlv_disable_dp;
8505                 intel_encoder->post_disable = vlv_post_disable_dp;
8506         } else {
8507                 intel_encoder->pre_enable = g4x_pre_enable_dp;
8508                 intel_encoder->enable = g4x_enable_dp;
8509                 intel_encoder->disable = g4x_disable_dp;
8510                 intel_encoder->post_disable = g4x_post_disable_dp;
8511         }
8512
8513         if ((IS_IVYBRIDGE(dev_priv) && port == PORT_A) ||
8514             (HAS_PCH_CPT(dev_priv) && port != PORT_A))
8515                 intel_dig_port->dp.set_link_train = cpt_set_link_train;
8516         else
8517                 intel_dig_port->dp.set_link_train = g4x_set_link_train;
8518
8519         if (IS_CHERRYVIEW(dev_priv))
8520                 intel_dig_port->dp.set_signal_levels = chv_set_signal_levels;
8521         else if (IS_VALLEYVIEW(dev_priv))
8522                 intel_dig_port->dp.set_signal_levels = vlv_set_signal_levels;
8523         else if (IS_IVYBRIDGE(dev_priv) && port == PORT_A)
8524                 intel_dig_port->dp.set_signal_levels = ivb_cpu_edp_set_signal_levels;
8525         else if (IS_GEN(dev_priv, 6) && port == PORT_A)
8526                 intel_dig_port->dp.set_signal_levels = snb_cpu_edp_set_signal_levels;
8527         else
8528                 intel_dig_port->dp.set_signal_levels = g4x_set_signal_levels;
8529
8530         intel_dig_port->dp.output_reg = output_reg;
8531         intel_dig_port->max_lanes = 4;
8532         intel_dig_port->dp.regs.dp_tp_ctl = DP_TP_CTL(port);
8533         intel_dig_port->dp.regs.dp_tp_status = DP_TP_STATUS(port);
8534
8535         intel_encoder->type = INTEL_OUTPUT_DP;
8536         intel_encoder->power_domain = intel_port_to_power_domain(port);
8537         if (IS_CHERRYVIEW(dev_priv)) {
8538                 if (port == PORT_D)
8539                         intel_encoder->pipe_mask = BIT(PIPE_C);
8540                 else
8541                         intel_encoder->pipe_mask = BIT(PIPE_A) | BIT(PIPE_B);
8542         } else {
8543                 intel_encoder->pipe_mask = ~0;
8544         }
8545         intel_encoder->cloneable = 0;
8546         intel_encoder->port = port;
8547
8548         intel_dig_port->hpd_pulse = intel_dp_hpd_pulse;
8549
8550         if (port != PORT_A)
8551                 intel_infoframe_init(intel_dig_port);
8552
8553         intel_dig_port->aux_ch = intel_bios_port_aux_ch(dev_priv, port);
8554         if (!intel_dp_init_connector(intel_dig_port, intel_connector))
8555                 goto err_init_connector;
8556
8557         return true;
8558
8559 err_init_connector:
8560         drm_encoder_cleanup(encoder);
8561 err_encoder_init:
8562         kfree(intel_connector);
8563 err_connector_alloc:
8564         kfree(intel_dig_port);
8565         return false;
8566 }
8567
8568 void intel_dp_mst_suspend(struct drm_i915_private *dev_priv)
8569 {
8570         struct intel_encoder *encoder;
8571
8572         for_each_intel_encoder(&dev_priv->drm, encoder) {
8573                 struct intel_dp *intel_dp;
8574
8575                 if (encoder->type != INTEL_OUTPUT_DDI)
8576                         continue;
8577
8578                 intel_dp = enc_to_intel_dp(encoder);
8579
8580                 if (!intel_dp->can_mst)
8581                         continue;
8582
8583                 if (intel_dp->is_mst)
8584                         drm_dp_mst_topology_mgr_suspend(&intel_dp->mst_mgr);
8585         }
8586 }
8587
8588 void intel_dp_mst_resume(struct drm_i915_private *dev_priv)
8589 {
8590         struct intel_encoder *encoder;
8591
8592         for_each_intel_encoder(&dev_priv->drm, encoder) {
8593                 struct intel_dp *intel_dp;
8594                 int ret;
8595
8596                 if (encoder->type != INTEL_OUTPUT_DDI)
8597                         continue;
8598
8599                 intel_dp = enc_to_intel_dp(encoder);
8600
8601                 if (!intel_dp->can_mst)
8602                         continue;
8603
8604                 ret = drm_dp_mst_topology_mgr_resume(&intel_dp->mst_mgr,
8605                                                      true);
8606                 if (ret) {
8607                         intel_dp->is_mst = false;
8608                         drm_dp_mst_topology_mgr_set_mst(&intel_dp->mst_mgr,
8609                                                         false);
8610                 }
8611         }
8612 }