Merge tag 'powerpc-5.13-1' of git://git.kernel.org/pub/scm/linux/kernel/git/powerpc...
[linux-2.6-microblaze.git] / drivers / gpu / drm / bridge / ti-sn65dsi86.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2018, The Linux Foundation. All rights reserved.
4  * datasheet: https://www.ti.com/lit/ds/symlink/sn65dsi86.pdf
5  */
6
7 #include <linux/bits.h>
8 #include <linux/clk.h>
9 #include <linux/debugfs.h>
10 #include <linux/gpio/consumer.h>
11 #include <linux/gpio/driver.h>
12 #include <linux/i2c.h>
13 #include <linux/iopoll.h>
14 #include <linux/module.h>
15 #include <linux/of_graph.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/regmap.h>
18 #include <linux/regulator/consumer.h>
19
20 #include <asm/unaligned.h>
21
22 #include <drm/drm_atomic.h>
23 #include <drm/drm_atomic_helper.h>
24 #include <drm/drm_bridge.h>
25 #include <drm/drm_dp_helper.h>
26 #include <drm/drm_mipi_dsi.h>
27 #include <drm/drm_of.h>
28 #include <drm/drm_panel.h>
29 #include <drm/drm_print.h>
30 #include <drm/drm_probe_helper.h>
31
32 #define SN_DEVICE_REV_REG                       0x08
33 #define SN_DPPLL_SRC_REG                        0x0A
34 #define  DPPLL_CLK_SRC_DSICLK                   BIT(0)
35 #define  REFCLK_FREQ_MASK                       GENMASK(3, 1)
36 #define  REFCLK_FREQ(x)                         ((x) << 1)
37 #define  DPPLL_SRC_DP_PLL_LOCK                  BIT(7)
38 #define SN_PLL_ENABLE_REG                       0x0D
39 #define SN_DSI_LANES_REG                        0x10
40 #define  CHA_DSI_LANES_MASK                     GENMASK(4, 3)
41 #define  CHA_DSI_LANES(x)                       ((x) << 3)
42 #define SN_DSIA_CLK_FREQ_REG                    0x12
43 #define SN_CHA_ACTIVE_LINE_LENGTH_LOW_REG       0x20
44 #define SN_CHA_VERTICAL_DISPLAY_SIZE_LOW_REG    0x24
45 #define SN_CHA_HSYNC_PULSE_WIDTH_LOW_REG        0x2C
46 #define SN_CHA_HSYNC_PULSE_WIDTH_HIGH_REG       0x2D
47 #define  CHA_HSYNC_POLARITY                     BIT(7)
48 #define SN_CHA_VSYNC_PULSE_WIDTH_LOW_REG        0x30
49 #define SN_CHA_VSYNC_PULSE_WIDTH_HIGH_REG       0x31
50 #define  CHA_VSYNC_POLARITY                     BIT(7)
51 #define SN_CHA_HORIZONTAL_BACK_PORCH_REG        0x34
52 #define SN_CHA_VERTICAL_BACK_PORCH_REG          0x36
53 #define SN_CHA_HORIZONTAL_FRONT_PORCH_REG       0x38
54 #define SN_CHA_VERTICAL_FRONT_PORCH_REG         0x3A
55 #define SN_LN_ASSIGN_REG                        0x59
56 #define  LN_ASSIGN_WIDTH                        2
57 #define SN_ENH_FRAME_REG                        0x5A
58 #define  VSTREAM_ENABLE                         BIT(3)
59 #define  LN_POLRS_OFFSET                        4
60 #define  LN_POLRS_MASK                          0xf0
61 #define SN_DATA_FORMAT_REG                      0x5B
62 #define  BPP_18_RGB                             BIT(0)
63 #define SN_HPD_DISABLE_REG                      0x5C
64 #define  HPD_DISABLE                            BIT(0)
65 #define SN_GPIO_IO_REG                          0x5E
66 #define  SN_GPIO_INPUT_SHIFT                    4
67 #define  SN_GPIO_OUTPUT_SHIFT                   0
68 #define SN_GPIO_CTRL_REG                        0x5F
69 #define  SN_GPIO_MUX_INPUT                      0
70 #define  SN_GPIO_MUX_OUTPUT                     1
71 #define  SN_GPIO_MUX_SPECIAL                    2
72 #define  SN_GPIO_MUX_MASK                       0x3
73 #define SN_AUX_WDATA_REG(x)                     (0x64 + (x))
74 #define SN_AUX_ADDR_19_16_REG                   0x74
75 #define SN_AUX_ADDR_15_8_REG                    0x75
76 #define SN_AUX_ADDR_7_0_REG                     0x76
77 #define SN_AUX_ADDR_MASK                        GENMASK(19, 0)
78 #define SN_AUX_LENGTH_REG                       0x77
79 #define SN_AUX_CMD_REG                          0x78
80 #define  AUX_CMD_SEND                           BIT(0)
81 #define  AUX_CMD_REQ(x)                         ((x) << 4)
82 #define SN_AUX_RDATA_REG(x)                     (0x79 + (x))
83 #define SN_SSC_CONFIG_REG                       0x93
84 #define  DP_NUM_LANES_MASK                      GENMASK(5, 4)
85 #define  DP_NUM_LANES(x)                        ((x) << 4)
86 #define SN_DATARATE_CONFIG_REG                  0x94
87 #define  DP_DATARATE_MASK                       GENMASK(7, 5)
88 #define  DP_DATARATE(x)                         ((x) << 5)
89 #define SN_ML_TX_MODE_REG                       0x96
90 #define  ML_TX_MAIN_LINK_OFF                    0
91 #define  ML_TX_NORMAL_MODE                      BIT(0)
92 #define SN_AUX_CMD_STATUS_REG                   0xF4
93 #define  AUX_IRQ_STATUS_AUX_RPLY_TOUT           BIT(3)
94 #define  AUX_IRQ_STATUS_AUX_SHORT               BIT(5)
95 #define  AUX_IRQ_STATUS_NAT_I2C_FAIL            BIT(6)
96
97 #define MIN_DSI_CLK_FREQ_MHZ    40
98
99 /* fudge factor required to account for 8b/10b encoding */
100 #define DP_CLK_FUDGE_NUM        10
101 #define DP_CLK_FUDGE_DEN        8
102
103 /* Matches DP_AUX_MAX_PAYLOAD_BYTES (for now) */
104 #define SN_AUX_MAX_PAYLOAD_BYTES        16
105
106 #define SN_REGULATOR_SUPPLY_NUM         4
107
108 #define SN_MAX_DP_LANES                 4
109 #define SN_NUM_GPIOS                    4
110 #define SN_GPIO_PHYSICAL_OFFSET         1
111
112 #define SN_LINK_TRAINING_TRIES          10
113
114 /**
115  * struct ti_sn_bridge - Platform data for ti-sn65dsi86 driver.
116  * @dev:          Pointer to our device.
117  * @regmap:       Regmap for accessing i2c.
118  * @aux:          Our aux channel.
119  * @bridge:       Our bridge.
120  * @connector:    Our connector.
121  * @debugfs:      Used for managing our debugfs.
122  * @host_node:    Remote DSI node.
123  * @dsi:          Our MIPI DSI source.
124  * @edid:         Detected EDID of eDP panel.
125  * @refclk:       Our reference clock.
126  * @panel:        Our panel.
127  * @enable_gpio:  The GPIO we toggle to enable the bridge.
128  * @supplies:     Data for bulk enabling/disabling our regulators.
129  * @dp_lanes:     Count of dp_lanes we're using.
130  * @ln_assign:    Value to program to the LN_ASSIGN register.
131  * @ln_polrs:     Value for the 4-bit LN_POLRS field of SN_ENH_FRAME_REG.
132  *
133  * @gchip:        If we expose our GPIOs, this is used.
134  * @gchip_output: A cache of whether we've set GPIOs to output.  This
135  *                serves double-duty of keeping track of the direction and
136  *                also keeping track of whether we've incremented the
137  *                pm_runtime reference count for this pin, which we do
138  *                whenever a pin is configured as an output.  This is a
139  *                bitmap so we can do atomic ops on it without an extra
140  *                lock so concurrent users of our 4 GPIOs don't stomp on
141  *                each other's read-modify-write.
142  */
143 struct ti_sn_bridge {
144         struct device                   *dev;
145         struct regmap                   *regmap;
146         struct drm_dp_aux               aux;
147         struct drm_bridge               bridge;
148         struct drm_connector            connector;
149         struct dentry                   *debugfs;
150         struct edid                     *edid;
151         struct device_node              *host_node;
152         struct mipi_dsi_device          *dsi;
153         struct clk                      *refclk;
154         struct drm_panel                *panel;
155         struct gpio_desc                *enable_gpio;
156         struct regulator_bulk_data      supplies[SN_REGULATOR_SUPPLY_NUM];
157         int                             dp_lanes;
158         u8                              ln_assign;
159         u8                              ln_polrs;
160
161 #if defined(CONFIG_OF_GPIO)
162         struct gpio_chip                gchip;
163         DECLARE_BITMAP(gchip_output, SN_NUM_GPIOS);
164 #endif
165 };
166
167 static const struct regmap_range ti_sn_bridge_volatile_ranges[] = {
168         { .range_min = 0, .range_max = 0xFF },
169 };
170
171 static const struct regmap_access_table ti_sn_bridge_volatile_table = {
172         .yes_ranges = ti_sn_bridge_volatile_ranges,
173         .n_yes_ranges = ARRAY_SIZE(ti_sn_bridge_volatile_ranges),
174 };
175
176 static const struct regmap_config ti_sn_bridge_regmap_config = {
177         .reg_bits = 8,
178         .val_bits = 8,
179         .volatile_table = &ti_sn_bridge_volatile_table,
180         .cache_type = REGCACHE_NONE,
181 };
182
183 static void ti_sn_bridge_write_u16(struct ti_sn_bridge *pdata,
184                                    unsigned int reg, u16 val)
185 {
186         regmap_write(pdata->regmap, reg, val & 0xFF);
187         regmap_write(pdata->regmap, reg + 1, val >> 8);
188 }
189
190 static int __maybe_unused ti_sn_bridge_resume(struct device *dev)
191 {
192         struct ti_sn_bridge *pdata = dev_get_drvdata(dev);
193         int ret;
194
195         ret = regulator_bulk_enable(SN_REGULATOR_SUPPLY_NUM, pdata->supplies);
196         if (ret) {
197                 DRM_ERROR("failed to enable supplies %d\n", ret);
198                 return ret;
199         }
200
201         gpiod_set_value(pdata->enable_gpio, 1);
202
203         return ret;
204 }
205
206 static int __maybe_unused ti_sn_bridge_suspend(struct device *dev)
207 {
208         struct ti_sn_bridge *pdata = dev_get_drvdata(dev);
209         int ret;
210
211         gpiod_set_value(pdata->enable_gpio, 0);
212
213         ret = regulator_bulk_disable(SN_REGULATOR_SUPPLY_NUM, pdata->supplies);
214         if (ret)
215                 DRM_ERROR("failed to disable supplies %d\n", ret);
216
217         return ret;
218 }
219
220 static const struct dev_pm_ops ti_sn_bridge_pm_ops = {
221         SET_RUNTIME_PM_OPS(ti_sn_bridge_suspend, ti_sn_bridge_resume, NULL)
222         SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
223                                 pm_runtime_force_resume)
224 };
225
226 static int status_show(struct seq_file *s, void *data)
227 {
228         struct ti_sn_bridge *pdata = s->private;
229         unsigned int reg, val;
230
231         seq_puts(s, "STATUS REGISTERS:\n");
232
233         pm_runtime_get_sync(pdata->dev);
234
235         /* IRQ Status Registers, see Table 31 in datasheet */
236         for (reg = 0xf0; reg <= 0xf8; reg++) {
237                 regmap_read(pdata->regmap, reg, &val);
238                 seq_printf(s, "[0x%02x] = 0x%08x\n", reg, val);
239         }
240
241         pm_runtime_put(pdata->dev);
242
243         return 0;
244 }
245
246 DEFINE_SHOW_ATTRIBUTE(status);
247
248 static void ti_sn_debugfs_init(struct ti_sn_bridge *pdata)
249 {
250         pdata->debugfs = debugfs_create_dir(dev_name(pdata->dev), NULL);
251
252         debugfs_create_file("status", 0600, pdata->debugfs, pdata,
253                         &status_fops);
254 }
255
256 static void ti_sn_debugfs_remove(struct ti_sn_bridge *pdata)
257 {
258         debugfs_remove_recursive(pdata->debugfs);
259         pdata->debugfs = NULL;
260 }
261
262 /* Connector funcs */
263 static struct ti_sn_bridge *
264 connector_to_ti_sn_bridge(struct drm_connector *connector)
265 {
266         return container_of(connector, struct ti_sn_bridge, connector);
267 }
268
269 static int ti_sn_bridge_connector_get_modes(struct drm_connector *connector)
270 {
271         struct ti_sn_bridge *pdata = connector_to_ti_sn_bridge(connector);
272         struct edid *edid = pdata->edid;
273         int num, ret;
274
275         if (!edid) {
276                 pm_runtime_get_sync(pdata->dev);
277                 edid = pdata->edid = drm_get_edid(connector, &pdata->aux.ddc);
278                 pm_runtime_put(pdata->dev);
279         }
280
281         if (edid && drm_edid_is_valid(edid)) {
282                 ret = drm_connector_update_edid_property(connector, edid);
283                 if (!ret) {
284                         num = drm_add_edid_modes(connector, edid);
285                         if (num)
286                                 return num;
287                 }
288         }
289
290         return drm_panel_get_modes(pdata->panel, connector);
291 }
292
293 static enum drm_mode_status
294 ti_sn_bridge_connector_mode_valid(struct drm_connector *connector,
295                                   struct drm_display_mode *mode)
296 {
297         /* maximum supported resolution is 4K at 60 fps */
298         if (mode->clock > 594000)
299                 return MODE_CLOCK_HIGH;
300
301         return MODE_OK;
302 }
303
304 static struct drm_connector_helper_funcs ti_sn_bridge_connector_helper_funcs = {
305         .get_modes = ti_sn_bridge_connector_get_modes,
306         .mode_valid = ti_sn_bridge_connector_mode_valid,
307 };
308
309 static enum drm_connector_status
310 ti_sn_bridge_connector_detect(struct drm_connector *connector, bool force)
311 {
312         /**
313          * TODO: Currently if drm_panel is present, then always
314          * return the status as connected. Need to add support to detect
315          * device state for hot pluggable scenarios.
316          */
317         return connector_status_connected;
318 }
319
320 static const struct drm_connector_funcs ti_sn_bridge_connector_funcs = {
321         .fill_modes = drm_helper_probe_single_connector_modes,
322         .detect = ti_sn_bridge_connector_detect,
323         .destroy = drm_connector_cleanup,
324         .reset = drm_atomic_helper_connector_reset,
325         .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
326         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
327 };
328
329 static struct ti_sn_bridge *bridge_to_ti_sn_bridge(struct drm_bridge *bridge)
330 {
331         return container_of(bridge, struct ti_sn_bridge, bridge);
332 }
333
334 static int ti_sn_bridge_parse_regulators(struct ti_sn_bridge *pdata)
335 {
336         unsigned int i;
337         const char * const ti_sn_bridge_supply_names[] = {
338                 "vcca", "vcc", "vccio", "vpll",
339         };
340
341         for (i = 0; i < SN_REGULATOR_SUPPLY_NUM; i++)
342                 pdata->supplies[i].supply = ti_sn_bridge_supply_names[i];
343
344         return devm_regulator_bulk_get(pdata->dev, SN_REGULATOR_SUPPLY_NUM,
345                                        pdata->supplies);
346 }
347
348 static int ti_sn_bridge_attach(struct drm_bridge *bridge,
349                                enum drm_bridge_attach_flags flags)
350 {
351         int ret, val;
352         struct ti_sn_bridge *pdata = bridge_to_ti_sn_bridge(bridge);
353         struct mipi_dsi_host *host;
354         struct mipi_dsi_device *dsi;
355         const struct mipi_dsi_device_info info = { .type = "ti_sn_bridge",
356                                                    .channel = 0,
357                                                    .node = NULL,
358                                                  };
359
360         if (flags & DRM_BRIDGE_ATTACH_NO_CONNECTOR) {
361                 DRM_ERROR("Fix bridge driver to make connector optional!");
362                 return -EINVAL;
363         }
364
365         ret = drm_dp_aux_register(&pdata->aux);
366         if (ret < 0) {
367                 drm_err(bridge->dev, "Failed to register DP AUX channel: %d\n", ret);
368                 return ret;
369         }
370
371         ret = drm_connector_init(bridge->dev, &pdata->connector,
372                                  &ti_sn_bridge_connector_funcs,
373                                  DRM_MODE_CONNECTOR_eDP);
374         if (ret) {
375                 DRM_ERROR("Failed to initialize connector with drm\n");
376                 goto err_conn_init;
377         }
378
379         drm_connector_helper_add(&pdata->connector,
380                                  &ti_sn_bridge_connector_helper_funcs);
381         drm_connector_attach_encoder(&pdata->connector, bridge->encoder);
382
383         /*
384          * TODO: ideally finding host resource and dsi dev registration needs
385          * to be done in bridge probe. But some existing DSI host drivers will
386          * wait for any of the drm_bridge/drm_panel to get added to the global
387          * bridge/panel list, before completing their probe. So if we do the
388          * dsi dev registration part in bridge probe, before populating in
389          * the global bridge list, then it will cause deadlock as dsi host probe
390          * will never complete, neither our bridge probe. So keeping it here
391          * will satisfy most of the existing host drivers. Once the host driver
392          * is fixed we can move the below code to bridge probe safely.
393          */
394         host = of_find_mipi_dsi_host_by_node(pdata->host_node);
395         if (!host) {
396                 DRM_ERROR("failed to find dsi host\n");
397                 ret = -ENODEV;
398                 goto err_dsi_host;
399         }
400
401         dsi = mipi_dsi_device_register_full(host, &info);
402         if (IS_ERR(dsi)) {
403                 DRM_ERROR("failed to create dsi device\n");
404                 ret = PTR_ERR(dsi);
405                 goto err_dsi_host;
406         }
407
408         /* TODO: setting to 4 MIPI lanes always for now */
409         dsi->lanes = 4;
410         dsi->format = MIPI_DSI_FMT_RGB888;
411         dsi->mode_flags = MIPI_DSI_MODE_VIDEO;
412
413         /* check if continuous dsi clock is required or not */
414         pm_runtime_get_sync(pdata->dev);
415         regmap_read(pdata->regmap, SN_DPPLL_SRC_REG, &val);
416         pm_runtime_put(pdata->dev);
417         if (!(val & DPPLL_CLK_SRC_DSICLK))
418                 dsi->mode_flags |= MIPI_DSI_CLOCK_NON_CONTINUOUS;
419
420         ret = mipi_dsi_attach(dsi);
421         if (ret < 0) {
422                 DRM_ERROR("failed to attach dsi to host\n");
423                 goto err_dsi_attach;
424         }
425         pdata->dsi = dsi;
426
427         return 0;
428
429 err_dsi_attach:
430         mipi_dsi_device_unregister(dsi);
431 err_dsi_host:
432         drm_connector_cleanup(&pdata->connector);
433 err_conn_init:
434         drm_dp_aux_unregister(&pdata->aux);
435         return ret;
436 }
437
438 static void ti_sn_bridge_detach(struct drm_bridge *bridge)
439 {
440         drm_dp_aux_unregister(&bridge_to_ti_sn_bridge(bridge)->aux);
441 }
442
443 static void ti_sn_bridge_disable(struct drm_bridge *bridge)
444 {
445         struct ti_sn_bridge *pdata = bridge_to_ti_sn_bridge(bridge);
446
447         drm_panel_disable(pdata->panel);
448
449         /* disable video stream */
450         regmap_update_bits(pdata->regmap, SN_ENH_FRAME_REG, VSTREAM_ENABLE, 0);
451         /* semi auto link training mode OFF */
452         regmap_write(pdata->regmap, SN_ML_TX_MODE_REG, 0);
453         /* disable DP PLL */
454         regmap_write(pdata->regmap, SN_PLL_ENABLE_REG, 0);
455
456         drm_panel_unprepare(pdata->panel);
457 }
458
459 static u32 ti_sn_bridge_get_dsi_freq(struct ti_sn_bridge *pdata)
460 {
461         u32 bit_rate_khz, clk_freq_khz;
462         struct drm_display_mode *mode =
463                 &pdata->bridge.encoder->crtc->state->adjusted_mode;
464
465         bit_rate_khz = mode->clock *
466                         mipi_dsi_pixel_format_to_bpp(pdata->dsi->format);
467         clk_freq_khz = bit_rate_khz / (pdata->dsi->lanes * 2);
468
469         return clk_freq_khz;
470 }
471
472 /* clk frequencies supported by bridge in Hz in case derived from REFCLK pin */
473 static const u32 ti_sn_bridge_refclk_lut[] = {
474         12000000,
475         19200000,
476         26000000,
477         27000000,
478         38400000,
479 };
480
481 /* clk frequencies supported by bridge in Hz in case derived from DACP/N pin */
482 static const u32 ti_sn_bridge_dsiclk_lut[] = {
483         468000000,
484         384000000,
485         416000000,
486         486000000,
487         460800000,
488 };
489
490 static void ti_sn_bridge_set_refclk_freq(struct ti_sn_bridge *pdata)
491 {
492         int i;
493         u32 refclk_rate;
494         const u32 *refclk_lut;
495         size_t refclk_lut_size;
496
497         if (pdata->refclk) {
498                 refclk_rate = clk_get_rate(pdata->refclk);
499                 refclk_lut = ti_sn_bridge_refclk_lut;
500                 refclk_lut_size = ARRAY_SIZE(ti_sn_bridge_refclk_lut);
501                 clk_prepare_enable(pdata->refclk);
502         } else {
503                 refclk_rate = ti_sn_bridge_get_dsi_freq(pdata) * 1000;
504                 refclk_lut = ti_sn_bridge_dsiclk_lut;
505                 refclk_lut_size = ARRAY_SIZE(ti_sn_bridge_dsiclk_lut);
506         }
507
508         /* for i equals to refclk_lut_size means default frequency */
509         for (i = 0; i < refclk_lut_size; i++)
510                 if (refclk_lut[i] == refclk_rate)
511                         break;
512
513         regmap_update_bits(pdata->regmap, SN_DPPLL_SRC_REG, REFCLK_FREQ_MASK,
514                            REFCLK_FREQ(i));
515 }
516
517 static void ti_sn_bridge_set_dsi_rate(struct ti_sn_bridge *pdata)
518 {
519         unsigned int bit_rate_mhz, clk_freq_mhz;
520         unsigned int val;
521         struct drm_display_mode *mode =
522                 &pdata->bridge.encoder->crtc->state->adjusted_mode;
523
524         /* set DSIA clk frequency */
525         bit_rate_mhz = (mode->clock / 1000) *
526                         mipi_dsi_pixel_format_to_bpp(pdata->dsi->format);
527         clk_freq_mhz = bit_rate_mhz / (pdata->dsi->lanes * 2);
528
529         /* for each increment in val, frequency increases by 5MHz */
530         val = (MIN_DSI_CLK_FREQ_MHZ / 5) +
531                 (((clk_freq_mhz - MIN_DSI_CLK_FREQ_MHZ) / 5) & 0xFF);
532         regmap_write(pdata->regmap, SN_DSIA_CLK_FREQ_REG, val);
533 }
534
535 static unsigned int ti_sn_bridge_get_bpp(struct ti_sn_bridge *pdata)
536 {
537         if (pdata->connector.display_info.bpc <= 6)
538                 return 18;
539         else
540                 return 24;
541 }
542
543 /*
544  * LUT index corresponds to register value and
545  * LUT values corresponds to dp data rate supported
546  * by the bridge in Mbps unit.
547  */
548 static const unsigned int ti_sn_bridge_dp_rate_lut[] = {
549         0, 1620, 2160, 2430, 2700, 3240, 4320, 5400
550 };
551
552 static int ti_sn_bridge_calc_min_dp_rate_idx(struct ti_sn_bridge *pdata)
553 {
554         unsigned int bit_rate_khz, dp_rate_mhz;
555         unsigned int i;
556         struct drm_display_mode *mode =
557                 &pdata->bridge.encoder->crtc->state->adjusted_mode;
558
559         /* Calculate minimum bit rate based on our pixel clock. */
560         bit_rate_khz = mode->clock * ti_sn_bridge_get_bpp(pdata);
561
562         /* Calculate minimum DP data rate, taking 80% as per DP spec */
563         dp_rate_mhz = DIV_ROUND_UP(bit_rate_khz * DP_CLK_FUDGE_NUM,
564                                    1000 * pdata->dp_lanes * DP_CLK_FUDGE_DEN);
565
566         for (i = 1; i < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut) - 1; i++)
567                 if (ti_sn_bridge_dp_rate_lut[i] >= dp_rate_mhz)
568                         break;
569
570         return i;
571 }
572
573 static void ti_sn_bridge_read_valid_rates(struct ti_sn_bridge *pdata,
574                                           bool rate_valid[])
575 {
576         unsigned int rate_per_200khz;
577         unsigned int rate_mhz;
578         u8 dpcd_val;
579         int ret;
580         int i, j;
581
582         ret = drm_dp_dpcd_readb(&pdata->aux, DP_EDP_DPCD_REV, &dpcd_val);
583         if (ret != 1) {
584                 DRM_DEV_ERROR(pdata->dev,
585                               "Can't read eDP rev (%d), assuming 1.1\n", ret);
586                 dpcd_val = DP_EDP_11;
587         }
588
589         if (dpcd_val >= DP_EDP_14) {
590                 /* eDP 1.4 devices must provide a custom table */
591                 __le16 sink_rates[DP_MAX_SUPPORTED_RATES];
592
593                 ret = drm_dp_dpcd_read(&pdata->aux, DP_SUPPORTED_LINK_RATES,
594                                        sink_rates, sizeof(sink_rates));
595
596                 if (ret != sizeof(sink_rates)) {
597                         DRM_DEV_ERROR(pdata->dev,
598                                 "Can't read supported rate table (%d)\n", ret);
599
600                         /* By zeroing we'll fall back to DP_MAX_LINK_RATE. */
601                         memset(sink_rates, 0, sizeof(sink_rates));
602                 }
603
604                 for (i = 0; i < ARRAY_SIZE(sink_rates); i++) {
605                         rate_per_200khz = le16_to_cpu(sink_rates[i]);
606
607                         if (!rate_per_200khz)
608                                 break;
609
610                         rate_mhz = rate_per_200khz * 200 / 1000;
611                         for (j = 0;
612                              j < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut);
613                              j++) {
614                                 if (ti_sn_bridge_dp_rate_lut[j] == rate_mhz)
615                                         rate_valid[j] = true;
616                         }
617                 }
618
619                 for (i = 0; i < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut); i++) {
620                         if (rate_valid[i])
621                                 return;
622                 }
623                 DRM_DEV_ERROR(pdata->dev,
624                               "No matching eDP rates in table; falling back\n");
625         }
626
627         /* On older versions best we can do is use DP_MAX_LINK_RATE */
628         ret = drm_dp_dpcd_readb(&pdata->aux, DP_MAX_LINK_RATE, &dpcd_val);
629         if (ret != 1) {
630                 DRM_DEV_ERROR(pdata->dev,
631                               "Can't read max rate (%d); assuming 5.4 GHz\n",
632                               ret);
633                 dpcd_val = DP_LINK_BW_5_4;
634         }
635
636         switch (dpcd_val) {
637         default:
638                 DRM_DEV_ERROR(pdata->dev,
639                               "Unexpected max rate (%#x); assuming 5.4 GHz\n",
640                               (int)dpcd_val);
641                 fallthrough;
642         case DP_LINK_BW_5_4:
643                 rate_valid[7] = 1;
644                 fallthrough;
645         case DP_LINK_BW_2_7:
646                 rate_valid[4] = 1;
647                 fallthrough;
648         case DP_LINK_BW_1_62:
649                 rate_valid[1] = 1;
650                 break;
651         }
652 }
653
654 static void ti_sn_bridge_set_video_timings(struct ti_sn_bridge *pdata)
655 {
656         struct drm_display_mode *mode =
657                 &pdata->bridge.encoder->crtc->state->adjusted_mode;
658         u8 hsync_polarity = 0, vsync_polarity = 0;
659
660         if (mode->flags & DRM_MODE_FLAG_PHSYNC)
661                 hsync_polarity = CHA_HSYNC_POLARITY;
662         if (mode->flags & DRM_MODE_FLAG_PVSYNC)
663                 vsync_polarity = CHA_VSYNC_POLARITY;
664
665         ti_sn_bridge_write_u16(pdata, SN_CHA_ACTIVE_LINE_LENGTH_LOW_REG,
666                                mode->hdisplay);
667         ti_sn_bridge_write_u16(pdata, SN_CHA_VERTICAL_DISPLAY_SIZE_LOW_REG,
668                                mode->vdisplay);
669         regmap_write(pdata->regmap, SN_CHA_HSYNC_PULSE_WIDTH_LOW_REG,
670                      (mode->hsync_end - mode->hsync_start) & 0xFF);
671         regmap_write(pdata->regmap, SN_CHA_HSYNC_PULSE_WIDTH_HIGH_REG,
672                      (((mode->hsync_end - mode->hsync_start) >> 8) & 0x7F) |
673                      hsync_polarity);
674         regmap_write(pdata->regmap, SN_CHA_VSYNC_PULSE_WIDTH_LOW_REG,
675                      (mode->vsync_end - mode->vsync_start) & 0xFF);
676         regmap_write(pdata->regmap, SN_CHA_VSYNC_PULSE_WIDTH_HIGH_REG,
677                      (((mode->vsync_end - mode->vsync_start) >> 8) & 0x7F) |
678                      vsync_polarity);
679
680         regmap_write(pdata->regmap, SN_CHA_HORIZONTAL_BACK_PORCH_REG,
681                      (mode->htotal - mode->hsync_end) & 0xFF);
682         regmap_write(pdata->regmap, SN_CHA_VERTICAL_BACK_PORCH_REG,
683                      (mode->vtotal - mode->vsync_end) & 0xFF);
684
685         regmap_write(pdata->regmap, SN_CHA_HORIZONTAL_FRONT_PORCH_REG,
686                      (mode->hsync_start - mode->hdisplay) & 0xFF);
687         regmap_write(pdata->regmap, SN_CHA_VERTICAL_FRONT_PORCH_REG,
688                      (mode->vsync_start - mode->vdisplay) & 0xFF);
689
690         usleep_range(10000, 10500); /* 10ms delay recommended by spec */
691 }
692
693 static unsigned int ti_sn_get_max_lanes(struct ti_sn_bridge *pdata)
694 {
695         u8 data;
696         int ret;
697
698         ret = drm_dp_dpcd_readb(&pdata->aux, DP_MAX_LANE_COUNT, &data);
699         if (ret != 1) {
700                 DRM_DEV_ERROR(pdata->dev,
701                               "Can't read lane count (%d); assuming 4\n", ret);
702                 return 4;
703         }
704
705         return data & DP_LANE_COUNT_MASK;
706 }
707
708 static int ti_sn_link_training(struct ti_sn_bridge *pdata, int dp_rate_idx,
709                                const char **last_err_str)
710 {
711         unsigned int val;
712         int ret;
713         int i;
714
715         /* set dp clk frequency value */
716         regmap_update_bits(pdata->regmap, SN_DATARATE_CONFIG_REG,
717                            DP_DATARATE_MASK, DP_DATARATE(dp_rate_idx));
718
719         /* enable DP PLL */
720         regmap_write(pdata->regmap, SN_PLL_ENABLE_REG, 1);
721
722         ret = regmap_read_poll_timeout(pdata->regmap, SN_DPPLL_SRC_REG, val,
723                                        val & DPPLL_SRC_DP_PLL_LOCK, 1000,
724                                        50 * 1000);
725         if (ret) {
726                 *last_err_str = "DP_PLL_LOCK polling failed";
727                 goto exit;
728         }
729
730         /*
731          * We'll try to link train several times.  As part of link training
732          * the bridge chip will write DP_SET_POWER_D0 to DP_SET_POWER.  If
733          * the panel isn't ready quite it might respond NAK here which means
734          * we need to try again.
735          */
736         for (i = 0; i < SN_LINK_TRAINING_TRIES; i++) {
737                 /* Semi auto link training mode */
738                 regmap_write(pdata->regmap, SN_ML_TX_MODE_REG, 0x0A);
739                 ret = regmap_read_poll_timeout(pdata->regmap, SN_ML_TX_MODE_REG, val,
740                                                val == ML_TX_MAIN_LINK_OFF ||
741                                                val == ML_TX_NORMAL_MODE, 1000,
742                                                500 * 1000);
743                 if (ret) {
744                         *last_err_str = "Training complete polling failed";
745                 } else if (val == ML_TX_MAIN_LINK_OFF) {
746                         *last_err_str = "Link training failed, link is off";
747                         ret = -EIO;
748                         continue;
749                 }
750
751                 break;
752         }
753
754         /* If we saw quite a few retries, add a note about it */
755         if (!ret && i > SN_LINK_TRAINING_TRIES / 2)
756                 DRM_DEV_INFO(pdata->dev, "Link training needed %d retries\n", i);
757
758 exit:
759         /* Disable the PLL if we failed */
760         if (ret)
761                 regmap_write(pdata->regmap, SN_PLL_ENABLE_REG, 0);
762
763         return ret;
764 }
765
766 static void ti_sn_bridge_enable(struct drm_bridge *bridge)
767 {
768         struct ti_sn_bridge *pdata = bridge_to_ti_sn_bridge(bridge);
769         bool rate_valid[ARRAY_SIZE(ti_sn_bridge_dp_rate_lut)] = { };
770         const char *last_err_str = "No supported DP rate";
771         int dp_rate_idx;
772         unsigned int val;
773         int ret = -EINVAL;
774         int max_dp_lanes;
775
776         max_dp_lanes = ti_sn_get_max_lanes(pdata);
777         pdata->dp_lanes = min(pdata->dp_lanes, max_dp_lanes);
778
779         /* DSI_A lane config */
780         val = CHA_DSI_LANES(SN_MAX_DP_LANES - pdata->dsi->lanes);
781         regmap_update_bits(pdata->regmap, SN_DSI_LANES_REG,
782                            CHA_DSI_LANES_MASK, val);
783
784         regmap_write(pdata->regmap, SN_LN_ASSIGN_REG, pdata->ln_assign);
785         regmap_update_bits(pdata->regmap, SN_ENH_FRAME_REG, LN_POLRS_MASK,
786                            pdata->ln_polrs << LN_POLRS_OFFSET);
787
788         /* set dsi clk frequency value */
789         ti_sn_bridge_set_dsi_rate(pdata);
790
791         /**
792          * The SN65DSI86 only supports ASSR Display Authentication method and
793          * this method is enabled by default. An eDP panel must support this
794          * authentication method. We need to enable this method in the eDP panel
795          * at DisplayPort address 0x0010A prior to link training.
796          */
797         drm_dp_dpcd_writeb(&pdata->aux, DP_EDP_CONFIGURATION_SET,
798                            DP_ALTERNATE_SCRAMBLER_RESET_ENABLE);
799
800         /* Set the DP output format (18 bpp or 24 bpp) */
801         val = (ti_sn_bridge_get_bpp(pdata) == 18) ? BPP_18_RGB : 0;
802         regmap_update_bits(pdata->regmap, SN_DATA_FORMAT_REG, BPP_18_RGB, val);
803
804         /* DP lane config */
805         val = DP_NUM_LANES(min(pdata->dp_lanes, 3));
806         regmap_update_bits(pdata->regmap, SN_SSC_CONFIG_REG, DP_NUM_LANES_MASK,
807                            val);
808
809         ti_sn_bridge_read_valid_rates(pdata, rate_valid);
810
811         /* Train until we run out of rates */
812         for (dp_rate_idx = ti_sn_bridge_calc_min_dp_rate_idx(pdata);
813              dp_rate_idx < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut);
814              dp_rate_idx++) {
815                 if (!rate_valid[dp_rate_idx])
816                         continue;
817
818                 ret = ti_sn_link_training(pdata, dp_rate_idx, &last_err_str);
819                 if (!ret)
820                         break;
821         }
822         if (ret) {
823                 DRM_DEV_ERROR(pdata->dev, "%s (%d)\n", last_err_str, ret);
824                 return;
825         }
826
827         /* config video parameters */
828         ti_sn_bridge_set_video_timings(pdata);
829
830         /* enable video stream */
831         regmap_update_bits(pdata->regmap, SN_ENH_FRAME_REG, VSTREAM_ENABLE,
832                            VSTREAM_ENABLE);
833
834         drm_panel_enable(pdata->panel);
835 }
836
837 static void ti_sn_bridge_pre_enable(struct drm_bridge *bridge)
838 {
839         struct ti_sn_bridge *pdata = bridge_to_ti_sn_bridge(bridge);
840
841         pm_runtime_get_sync(pdata->dev);
842
843         /* configure bridge ref_clk */
844         ti_sn_bridge_set_refclk_freq(pdata);
845
846         /*
847          * HPD on this bridge chip is a bit useless.  This is an eDP bridge
848          * so the HPD is an internal signal that's only there to signal that
849          * the panel is done powering up.  ...but the bridge chip debounces
850          * this signal by between 100 ms and 400 ms (depending on process,
851          * voltage, and temperate--I measured it at about 200 ms).  One
852          * particular panel asserted HPD 84 ms after it was powered on meaning
853          * that we saw HPD 284 ms after power on.  ...but the same panel said
854          * that instead of looking at HPD you could just hardcode a delay of
855          * 200 ms.  We'll assume that the panel driver will have the hardcoded
856          * delay in its prepare and always disable HPD.
857          *
858          * If HPD somehow makes sense on some future panel we'll have to
859          * change this to be conditional on someone specifying that HPD should
860          * be used.
861          */
862         regmap_update_bits(pdata->regmap, SN_HPD_DISABLE_REG, HPD_DISABLE,
863                            HPD_DISABLE);
864
865         drm_panel_prepare(pdata->panel);
866 }
867
868 static void ti_sn_bridge_post_disable(struct drm_bridge *bridge)
869 {
870         struct ti_sn_bridge *pdata = bridge_to_ti_sn_bridge(bridge);
871
872         clk_disable_unprepare(pdata->refclk);
873
874         pm_runtime_put_sync(pdata->dev);
875 }
876
877 static const struct drm_bridge_funcs ti_sn_bridge_funcs = {
878         .attach = ti_sn_bridge_attach,
879         .detach = ti_sn_bridge_detach,
880         .pre_enable = ti_sn_bridge_pre_enable,
881         .enable = ti_sn_bridge_enable,
882         .disable = ti_sn_bridge_disable,
883         .post_disable = ti_sn_bridge_post_disable,
884 };
885
886 static struct ti_sn_bridge *aux_to_ti_sn_bridge(struct drm_dp_aux *aux)
887 {
888         return container_of(aux, struct ti_sn_bridge, aux);
889 }
890
891 static ssize_t ti_sn_aux_transfer(struct drm_dp_aux *aux,
892                                   struct drm_dp_aux_msg *msg)
893 {
894         struct ti_sn_bridge *pdata = aux_to_ti_sn_bridge(aux);
895         u32 request = msg->request & ~(DP_AUX_I2C_MOT | DP_AUX_I2C_WRITE_STATUS_UPDATE);
896         u32 request_val = AUX_CMD_REQ(msg->request);
897         u8 *buf = msg->buffer;
898         unsigned int len = msg->size;
899         unsigned int val;
900         int ret;
901         u8 addr_len[SN_AUX_LENGTH_REG + 1 - SN_AUX_ADDR_19_16_REG];
902
903         if (len > SN_AUX_MAX_PAYLOAD_BYTES)
904                 return -EINVAL;
905
906         switch (request) {
907         case DP_AUX_NATIVE_WRITE:
908         case DP_AUX_I2C_WRITE:
909         case DP_AUX_NATIVE_READ:
910         case DP_AUX_I2C_READ:
911                 regmap_write(pdata->regmap, SN_AUX_CMD_REG, request_val);
912                 /* Assume it's good */
913                 msg->reply = 0;
914                 break;
915         default:
916                 return -EINVAL;
917         }
918
919         BUILD_BUG_ON(sizeof(addr_len) != sizeof(__be32));
920         put_unaligned_be32((msg->address & SN_AUX_ADDR_MASK) << 8 | len,
921                            addr_len);
922         regmap_bulk_write(pdata->regmap, SN_AUX_ADDR_19_16_REG, addr_len,
923                           ARRAY_SIZE(addr_len));
924
925         if (request == DP_AUX_NATIVE_WRITE || request == DP_AUX_I2C_WRITE)
926                 regmap_bulk_write(pdata->regmap, SN_AUX_WDATA_REG(0), buf, len);
927
928         /* Clear old status bits before start so we don't get confused */
929         regmap_write(pdata->regmap, SN_AUX_CMD_STATUS_REG,
930                      AUX_IRQ_STATUS_NAT_I2C_FAIL |
931                      AUX_IRQ_STATUS_AUX_RPLY_TOUT |
932                      AUX_IRQ_STATUS_AUX_SHORT);
933
934         regmap_write(pdata->regmap, SN_AUX_CMD_REG, request_val | AUX_CMD_SEND);
935
936         /* Zero delay loop because i2c transactions are slow already */
937         ret = regmap_read_poll_timeout(pdata->regmap, SN_AUX_CMD_REG, val,
938                                        !(val & AUX_CMD_SEND), 0, 50 * 1000);
939         if (ret)
940                 return ret;
941
942         ret = regmap_read(pdata->regmap, SN_AUX_CMD_STATUS_REG, &val);
943         if (ret)
944                 return ret;
945
946         if (val & AUX_IRQ_STATUS_AUX_RPLY_TOUT) {
947                 /*
948                  * The hardware tried the message seven times per the DP spec
949                  * but it hit a timeout. We ignore defers here because they're
950                  * handled in hardware.
951                  */
952                 return -ETIMEDOUT;
953         }
954
955         if (val & AUX_IRQ_STATUS_AUX_SHORT) {
956                 ret = regmap_read(pdata->regmap, SN_AUX_LENGTH_REG, &len);
957                 if (ret)
958                         return ret;
959         } else if (val & AUX_IRQ_STATUS_NAT_I2C_FAIL) {
960                 switch (request) {
961                 case DP_AUX_I2C_WRITE:
962                 case DP_AUX_I2C_READ:
963                         msg->reply |= DP_AUX_I2C_REPLY_NACK;
964                         break;
965                 case DP_AUX_NATIVE_READ:
966                 case DP_AUX_NATIVE_WRITE:
967                         msg->reply |= DP_AUX_NATIVE_REPLY_NACK;
968                         break;
969                 }
970                 return 0;
971         }
972
973         if (request == DP_AUX_NATIVE_WRITE || request == DP_AUX_I2C_WRITE ||
974             len == 0)
975                 return len;
976
977         ret = regmap_bulk_read(pdata->regmap, SN_AUX_RDATA_REG(0), buf, len);
978         if (ret)
979                 return ret;
980
981         return len;
982 }
983
984 static int ti_sn_bridge_parse_dsi_host(struct ti_sn_bridge *pdata)
985 {
986         struct device_node *np = pdata->dev->of_node;
987
988         pdata->host_node = of_graph_get_remote_node(np, 0, 0);
989
990         if (!pdata->host_node) {
991                 DRM_ERROR("remote dsi host node not found\n");
992                 return -ENODEV;
993         }
994
995         return 0;
996 }
997
998 #if defined(CONFIG_OF_GPIO)
999
1000 static int tn_sn_bridge_of_xlate(struct gpio_chip *chip,
1001                                  const struct of_phandle_args *gpiospec,
1002                                  u32 *flags)
1003 {
1004         if (WARN_ON(gpiospec->args_count < chip->of_gpio_n_cells))
1005                 return -EINVAL;
1006
1007         if (gpiospec->args[0] > chip->ngpio || gpiospec->args[0] < 1)
1008                 return -EINVAL;
1009
1010         if (flags)
1011                 *flags = gpiospec->args[1];
1012
1013         return gpiospec->args[0] - SN_GPIO_PHYSICAL_OFFSET;
1014 }
1015
1016 static int ti_sn_bridge_gpio_get_direction(struct gpio_chip *chip,
1017                                            unsigned int offset)
1018 {
1019         struct ti_sn_bridge *pdata = gpiochip_get_data(chip);
1020
1021         /*
1022          * We already have to keep track of the direction because we use
1023          * that to figure out whether we've powered the device.  We can
1024          * just return that rather than (maybe) powering up the device
1025          * to ask its direction.
1026          */
1027         return test_bit(offset, pdata->gchip_output) ?
1028                 GPIO_LINE_DIRECTION_OUT : GPIO_LINE_DIRECTION_IN;
1029 }
1030
1031 static int ti_sn_bridge_gpio_get(struct gpio_chip *chip, unsigned int offset)
1032 {
1033         struct ti_sn_bridge *pdata = gpiochip_get_data(chip);
1034         unsigned int val;
1035         int ret;
1036
1037         /*
1038          * When the pin is an input we don't forcibly keep the bridge
1039          * powered--we just power it on to read the pin.  NOTE: part of
1040          * the reason this works is that the bridge defaults (when
1041          * powered back on) to all 4 GPIOs being configured as GPIO input.
1042          * Also note that if something else is keeping the chip powered the
1043          * pm_runtime functions are lightweight increments of a refcount.
1044          */
1045         pm_runtime_get_sync(pdata->dev);
1046         ret = regmap_read(pdata->regmap, SN_GPIO_IO_REG, &val);
1047         pm_runtime_put(pdata->dev);
1048
1049         if (ret)
1050                 return ret;
1051
1052         return !!(val & BIT(SN_GPIO_INPUT_SHIFT + offset));
1053 }
1054
1055 static void ti_sn_bridge_gpio_set(struct gpio_chip *chip, unsigned int offset,
1056                                   int val)
1057 {
1058         struct ti_sn_bridge *pdata = gpiochip_get_data(chip);
1059         int ret;
1060
1061         if (!test_bit(offset, pdata->gchip_output)) {
1062                 dev_err(pdata->dev, "Ignoring GPIO set while input\n");
1063                 return;
1064         }
1065
1066         val &= 1;
1067         ret = regmap_update_bits(pdata->regmap, SN_GPIO_IO_REG,
1068                                  BIT(SN_GPIO_OUTPUT_SHIFT + offset),
1069                                  val << (SN_GPIO_OUTPUT_SHIFT + offset));
1070         if (ret)
1071                 dev_warn(pdata->dev,
1072                          "Failed to set bridge GPIO %u: %d\n", offset, ret);
1073 }
1074
1075 static int ti_sn_bridge_gpio_direction_input(struct gpio_chip *chip,
1076                                              unsigned int offset)
1077 {
1078         struct ti_sn_bridge *pdata = gpiochip_get_data(chip);
1079         int shift = offset * 2;
1080         int ret;
1081
1082         if (!test_and_clear_bit(offset, pdata->gchip_output))
1083                 return 0;
1084
1085         ret = regmap_update_bits(pdata->regmap, SN_GPIO_CTRL_REG,
1086                                  SN_GPIO_MUX_MASK << shift,
1087                                  SN_GPIO_MUX_INPUT << shift);
1088         if (ret) {
1089                 set_bit(offset, pdata->gchip_output);
1090                 return ret;
1091         }
1092
1093         /*
1094          * NOTE: if nobody else is powering the device this may fully power
1095          * it off and when it comes back it will have lost all state, but
1096          * that's OK because the default is input and we're now an input.
1097          */
1098         pm_runtime_put(pdata->dev);
1099
1100         return 0;
1101 }
1102
1103 static int ti_sn_bridge_gpio_direction_output(struct gpio_chip *chip,
1104                                               unsigned int offset, int val)
1105 {
1106         struct ti_sn_bridge *pdata = gpiochip_get_data(chip);
1107         int shift = offset * 2;
1108         int ret;
1109
1110         if (test_and_set_bit(offset, pdata->gchip_output))
1111                 return 0;
1112
1113         pm_runtime_get_sync(pdata->dev);
1114
1115         /* Set value first to avoid glitching */
1116         ti_sn_bridge_gpio_set(chip, offset, val);
1117
1118         /* Set direction */
1119         ret = regmap_update_bits(pdata->regmap, SN_GPIO_CTRL_REG,
1120                                  SN_GPIO_MUX_MASK << shift,
1121                                  SN_GPIO_MUX_OUTPUT << shift);
1122         if (ret) {
1123                 clear_bit(offset, pdata->gchip_output);
1124                 pm_runtime_put(pdata->dev);
1125         }
1126
1127         return ret;
1128 }
1129
1130 static void ti_sn_bridge_gpio_free(struct gpio_chip *chip, unsigned int offset)
1131 {
1132         /* We won't keep pm_runtime if we're input, so switch there on free */
1133         ti_sn_bridge_gpio_direction_input(chip, offset);
1134 }
1135
1136 static const char * const ti_sn_bridge_gpio_names[SN_NUM_GPIOS] = {
1137         "GPIO1", "GPIO2", "GPIO3", "GPIO4"
1138 };
1139
1140 static int ti_sn_setup_gpio_controller(struct ti_sn_bridge *pdata)
1141 {
1142         int ret;
1143
1144         /* Only init if someone is going to use us as a GPIO controller */
1145         if (!of_property_read_bool(pdata->dev->of_node, "gpio-controller"))
1146                 return 0;
1147
1148         pdata->gchip.label = dev_name(pdata->dev);
1149         pdata->gchip.parent = pdata->dev;
1150         pdata->gchip.owner = THIS_MODULE;
1151         pdata->gchip.of_xlate = tn_sn_bridge_of_xlate;
1152         pdata->gchip.of_gpio_n_cells = 2;
1153         pdata->gchip.free = ti_sn_bridge_gpio_free;
1154         pdata->gchip.get_direction = ti_sn_bridge_gpio_get_direction;
1155         pdata->gchip.direction_input = ti_sn_bridge_gpio_direction_input;
1156         pdata->gchip.direction_output = ti_sn_bridge_gpio_direction_output;
1157         pdata->gchip.get = ti_sn_bridge_gpio_get;
1158         pdata->gchip.set = ti_sn_bridge_gpio_set;
1159         pdata->gchip.can_sleep = true;
1160         pdata->gchip.names = ti_sn_bridge_gpio_names;
1161         pdata->gchip.ngpio = SN_NUM_GPIOS;
1162         pdata->gchip.base = -1;
1163         ret = devm_gpiochip_add_data(pdata->dev, &pdata->gchip, pdata);
1164         if (ret)
1165                 dev_err(pdata->dev, "can't add gpio chip\n");
1166
1167         return ret;
1168 }
1169
1170 #else
1171
1172 static inline int ti_sn_setup_gpio_controller(struct ti_sn_bridge *pdata)
1173 {
1174         return 0;
1175 }
1176
1177 #endif
1178
1179 static void ti_sn_bridge_parse_lanes(struct ti_sn_bridge *pdata,
1180                                      struct device_node *np)
1181 {
1182         u32 lane_assignments[SN_MAX_DP_LANES] = { 0, 1, 2, 3 };
1183         u32 lane_polarities[SN_MAX_DP_LANES] = { };
1184         struct device_node *endpoint;
1185         u8 ln_assign = 0;
1186         u8 ln_polrs = 0;
1187         int dp_lanes;
1188         int i;
1189
1190         /*
1191          * Read config from the device tree about lane remapping and lane
1192          * polarities.  These are optional and we assume identity map and
1193          * normal polarity if nothing is specified.  It's OK to specify just
1194          * data-lanes but not lane-polarities but not vice versa.
1195          *
1196          * Error checking is light (we just make sure we don't crash or
1197          * buffer overrun) and we assume dts is well formed and specifying
1198          * mappings that the hardware supports.
1199          */
1200         endpoint = of_graph_get_endpoint_by_regs(np, 1, -1);
1201         dp_lanes = of_property_count_u32_elems(endpoint, "data-lanes");
1202         if (dp_lanes > 0 && dp_lanes <= SN_MAX_DP_LANES) {
1203                 of_property_read_u32_array(endpoint, "data-lanes",
1204                                            lane_assignments, dp_lanes);
1205                 of_property_read_u32_array(endpoint, "lane-polarities",
1206                                            lane_polarities, dp_lanes);
1207         } else {
1208                 dp_lanes = SN_MAX_DP_LANES;
1209         }
1210         of_node_put(endpoint);
1211
1212         /*
1213          * Convert into register format.  Loop over all lanes even if
1214          * data-lanes had fewer elements so that we nicely initialize
1215          * the LN_ASSIGN register.
1216          */
1217         for (i = SN_MAX_DP_LANES - 1; i >= 0; i--) {
1218                 ln_assign = ln_assign << LN_ASSIGN_WIDTH | lane_assignments[i];
1219                 ln_polrs = ln_polrs << 1 | lane_polarities[i];
1220         }
1221
1222         /* Stash in our struct for when we power on */
1223         pdata->dp_lanes = dp_lanes;
1224         pdata->ln_assign = ln_assign;
1225         pdata->ln_polrs = ln_polrs;
1226 }
1227
1228 static int ti_sn_bridge_probe(struct i2c_client *client,
1229                               const struct i2c_device_id *id)
1230 {
1231         struct ti_sn_bridge *pdata;
1232         int ret;
1233
1234         if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
1235                 DRM_ERROR("device doesn't support I2C\n");
1236                 return -ENODEV;
1237         }
1238
1239         pdata = devm_kzalloc(&client->dev, sizeof(struct ti_sn_bridge),
1240                              GFP_KERNEL);
1241         if (!pdata)
1242                 return -ENOMEM;
1243
1244         pdata->regmap = devm_regmap_init_i2c(client,
1245                                              &ti_sn_bridge_regmap_config);
1246         if (IS_ERR(pdata->regmap)) {
1247                 DRM_ERROR("regmap i2c init failed\n");
1248                 return PTR_ERR(pdata->regmap);
1249         }
1250
1251         pdata->dev = &client->dev;
1252
1253         ret = drm_of_find_panel_or_bridge(pdata->dev->of_node, 1, 0,
1254                                           &pdata->panel, NULL);
1255         if (ret) {
1256                 DRM_ERROR("could not find any panel node\n");
1257                 return ret;
1258         }
1259
1260         dev_set_drvdata(&client->dev, pdata);
1261
1262         pdata->enable_gpio = devm_gpiod_get(pdata->dev, "enable",
1263                                             GPIOD_OUT_LOW);
1264         if (IS_ERR(pdata->enable_gpio)) {
1265                 DRM_ERROR("failed to get enable gpio from DT\n");
1266                 ret = PTR_ERR(pdata->enable_gpio);
1267                 return ret;
1268         }
1269
1270         ti_sn_bridge_parse_lanes(pdata, client->dev.of_node);
1271
1272         ret = ti_sn_bridge_parse_regulators(pdata);
1273         if (ret) {
1274                 DRM_ERROR("failed to parse regulators\n");
1275                 return ret;
1276         }
1277
1278         pdata->refclk = devm_clk_get(pdata->dev, "refclk");
1279         if (IS_ERR(pdata->refclk)) {
1280                 ret = PTR_ERR(pdata->refclk);
1281                 if (ret == -EPROBE_DEFER)
1282                         return ret;
1283                 DRM_DEBUG_KMS("refclk not found\n");
1284                 pdata->refclk = NULL;
1285         }
1286
1287         ret = ti_sn_bridge_parse_dsi_host(pdata);
1288         if (ret)
1289                 return ret;
1290
1291         pm_runtime_enable(pdata->dev);
1292
1293         ret = ti_sn_setup_gpio_controller(pdata);
1294         if (ret) {
1295                 pm_runtime_disable(pdata->dev);
1296                 return ret;
1297         }
1298
1299         i2c_set_clientdata(client, pdata);
1300
1301         pdata->aux.name = "ti-sn65dsi86-aux";
1302         pdata->aux.dev = pdata->dev;
1303         pdata->aux.transfer = ti_sn_aux_transfer;
1304         drm_dp_aux_init(&pdata->aux);
1305
1306         pdata->bridge.funcs = &ti_sn_bridge_funcs;
1307         pdata->bridge.of_node = client->dev.of_node;
1308
1309         drm_bridge_add(&pdata->bridge);
1310
1311         ti_sn_debugfs_init(pdata);
1312
1313         return 0;
1314 }
1315
1316 static int ti_sn_bridge_remove(struct i2c_client *client)
1317 {
1318         struct ti_sn_bridge *pdata = i2c_get_clientdata(client);
1319
1320         if (!pdata)
1321                 return -EINVAL;
1322
1323         kfree(pdata->edid);
1324         ti_sn_debugfs_remove(pdata);
1325
1326         of_node_put(pdata->host_node);
1327
1328         pm_runtime_disable(pdata->dev);
1329
1330         if (pdata->dsi) {
1331                 mipi_dsi_detach(pdata->dsi);
1332                 mipi_dsi_device_unregister(pdata->dsi);
1333         }
1334
1335         drm_bridge_remove(&pdata->bridge);
1336
1337         return 0;
1338 }
1339
1340 static struct i2c_device_id ti_sn_bridge_id[] = {
1341         { "ti,sn65dsi86", 0},
1342         {},
1343 };
1344 MODULE_DEVICE_TABLE(i2c, ti_sn_bridge_id);
1345
1346 static const struct of_device_id ti_sn_bridge_match_table[] = {
1347         {.compatible = "ti,sn65dsi86"},
1348         {},
1349 };
1350 MODULE_DEVICE_TABLE(of, ti_sn_bridge_match_table);
1351
1352 static struct i2c_driver ti_sn_bridge_driver = {
1353         .driver = {
1354                 .name = "ti_sn65dsi86",
1355                 .of_match_table = ti_sn_bridge_match_table,
1356                 .pm = &ti_sn_bridge_pm_ops,
1357         },
1358         .probe = ti_sn_bridge_probe,
1359         .remove = ti_sn_bridge_remove,
1360         .id_table = ti_sn_bridge_id,
1361 };
1362 module_i2c_driver(ti_sn_bridge_driver);
1363
1364 MODULE_AUTHOR("Sandeep Panda <spanda@codeaurora.org>");
1365 MODULE_DESCRIPTION("sn65dsi86 DSI to eDP bridge driver");
1366 MODULE_LICENSE("GPL v2");