xref: /openbmc/linux/drivers/gpu/drm/bridge/tc358767.c (revision 0d4bb5e4)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * TC358767/TC358867/TC9595 DSI/DPI-to-DPI/(e)DP bridge driver
4  *
5  * The TC358767/TC358867/TC9595 can operate in multiple modes.
6  * All modes are supported -- DPI->(e)DP / DSI->DPI / DSI->(e)DP .
7  *
8  * Copyright (C) 2016 CogentEmbedded Inc
9  * Author: Andrey Gusakov <andrey.gusakov@cogentembedded.com>
10  *
11  * Copyright (C) 2016 Pengutronix, Philipp Zabel <p.zabel@pengutronix.de>
12  *
13  * Copyright (C) 2016 Zodiac Inflight Innovations
14  *
15  * Initially based on: drivers/gpu/drm/i2c/tda998x_drv.c
16  *
17  * Copyright (C) 2012 Texas Instruments
18  * Author: Rob Clark <robdclark@gmail.com>
19  */
20 
21 #include <linux/bitfield.h>
22 #include <linux/clk.h>
23 #include <linux/device.h>
24 #include <linux/gpio/consumer.h>
25 #include <linux/i2c.h>
26 #include <linux/kernel.h>
27 #include <linux/media-bus-format.h>
28 #include <linux/module.h>
29 #include <linux/regmap.h>
30 #include <linux/slab.h>
31 
32 #include <drm/display/drm_dp_helper.h>
33 #include <drm/drm_atomic_helper.h>
34 #include <drm/drm_bridge.h>
35 #include <drm/drm_edid.h>
36 #include <drm/drm_mipi_dsi.h>
37 #include <drm/drm_of.h>
38 #include <drm/drm_panel.h>
39 #include <drm/drm_print.h>
40 #include <drm/drm_probe_helper.h>
41 
42 /* Registers */
43 
44 /* PPI layer registers */
45 #define PPI_STARTPPI		0x0104 /* START control bit */
46 #define PPI_LPTXTIMECNT		0x0114 /* LPTX timing signal */
47 #define LPX_PERIOD			3
48 #define PPI_LANEENABLE		0x0134
49 #define PPI_TX_RX_TA		0x013c
50 #define TTA_GET				0x40000
51 #define TTA_SURE			6
52 #define PPI_D0S_ATMR		0x0144
53 #define PPI_D1S_ATMR		0x0148
54 #define PPI_D0S_CLRSIPOCOUNT	0x0164 /* Assertion timer for Lane 0 */
55 #define PPI_D1S_CLRSIPOCOUNT	0x0168 /* Assertion timer for Lane 1 */
56 #define PPI_D2S_CLRSIPOCOUNT	0x016c /* Assertion timer for Lane 2 */
57 #define PPI_D3S_CLRSIPOCOUNT	0x0170 /* Assertion timer for Lane 3 */
58 #define PPI_START_FUNCTION		BIT(0)
59 
60 /* DSI layer registers */
61 #define DSI_STARTDSI		0x0204 /* START control bit of DSI-TX */
62 #define DSI_LANEENABLE		0x0210 /* Enables each lane */
63 #define DSI_RX_START			BIT(0)
64 
65 /* Lane enable PPI and DSI register bits */
66 #define LANEENABLE_CLEN		BIT(0)
67 #define LANEENABLE_L0EN		BIT(1)
68 #define LANEENABLE_L1EN		BIT(2)
69 #define LANEENABLE_L2EN		BIT(1)
70 #define LANEENABLE_L3EN		BIT(2)
71 
72 /* Display Parallel Input Interface */
73 #define DPIPXLFMT		0x0440
74 #define VS_POL_ACTIVE_LOW		(1 << 10)
75 #define HS_POL_ACTIVE_LOW		(1 << 9)
76 #define DE_POL_ACTIVE_HIGH		(0 << 8)
77 #define SUB_CFG_TYPE_CONFIG1		(0 << 2) /* LSB aligned */
78 #define SUB_CFG_TYPE_CONFIG2		(1 << 2) /* Loosely Packed */
79 #define SUB_CFG_TYPE_CONFIG3		(2 << 2) /* LSB aligned 8-bit */
80 #define DPI_BPP_RGB888			(0 << 0)
81 #define DPI_BPP_RGB666			(1 << 0)
82 #define DPI_BPP_RGB565			(2 << 0)
83 
84 /* Display Parallel Output Interface */
85 #define POCTRL			0x0448
86 #define POCTRL_S2P			BIT(7)
87 #define POCTRL_PCLK_POL			BIT(3)
88 #define POCTRL_VS_POL			BIT(2)
89 #define POCTRL_HS_POL			BIT(1)
90 #define POCTRL_DE_POL			BIT(0)
91 
92 /* Video Path */
93 #define VPCTRL0			0x0450
94 #define VSDELAY			GENMASK(31, 20)
95 #define OPXLFMT_RGB666			(0 << 8)
96 #define OPXLFMT_RGB888			(1 << 8)
97 #define FRMSYNC_DISABLED		(0 << 4) /* Video Timing Gen Disabled */
98 #define FRMSYNC_ENABLED			(1 << 4) /* Video Timing Gen Enabled */
99 #define MSF_DISABLED			(0 << 0) /* Magic Square FRC disabled */
100 #define MSF_ENABLED			(1 << 0) /* Magic Square FRC enabled */
101 #define HTIM01			0x0454
102 #define HPW			GENMASK(8, 0)
103 #define HBPR			GENMASK(24, 16)
104 #define HTIM02			0x0458
105 #define HDISPR			GENMASK(10, 0)
106 #define HFPR			GENMASK(24, 16)
107 #define VTIM01			0x045c
108 #define VSPR			GENMASK(7, 0)
109 #define VBPR			GENMASK(23, 16)
110 #define VTIM02			0x0460
111 #define VFPR			GENMASK(23, 16)
112 #define VDISPR			GENMASK(10, 0)
113 #define VFUEN0			0x0464
114 #define VFUEN				BIT(0)   /* Video Frame Timing Upload */
115 
116 /* System */
117 #define TC_IDREG		0x0500
118 #define SYSSTAT			0x0508
119 #define SYSCTRL			0x0510
120 #define DP0_AUDSRC_NO_INPUT		(0 << 3)
121 #define DP0_AUDSRC_I2S_RX		(1 << 3)
122 #define DP0_VIDSRC_NO_INPUT		(0 << 0)
123 #define DP0_VIDSRC_DSI_RX		(1 << 0)
124 #define DP0_VIDSRC_DPI_RX		(2 << 0)
125 #define DP0_VIDSRC_COLOR_BAR		(3 << 0)
126 #define SYSRSTENB		0x050c
127 #define ENBI2C				(1 << 0)
128 #define ENBLCD0				(1 << 2)
129 #define ENBBM				(1 << 3)
130 #define ENBDSIRX			(1 << 4)
131 #define ENBREG				(1 << 5)
132 #define ENBHDCP				(1 << 8)
133 #define GPIOM			0x0540
134 #define GPIOC			0x0544
135 #define GPIOO			0x0548
136 #define GPIOI			0x054c
137 #define INTCTL_G		0x0560
138 #define INTSTS_G		0x0564
139 
140 #define INT_SYSERR		BIT(16)
141 #define INT_GPIO_H(x)		(1 << (x == 0 ? 2 : 10))
142 #define INT_GPIO_LC(x)		(1 << (x == 0 ? 3 : 11))
143 
144 #define INT_GP0_LCNT		0x0584
145 #define INT_GP1_LCNT		0x0588
146 
147 /* Control */
148 #define DP0CTL			0x0600
149 #define VID_MN_GEN			BIT(6)   /* Auto-generate M/N values */
150 #define EF_EN				BIT(5)   /* Enable Enhanced Framing */
151 #define VID_EN				BIT(1)   /* Video transmission enable */
152 #define DP_EN				BIT(0)   /* Enable DPTX function */
153 
154 /* Clocks */
155 #define DP0_VIDMNGEN0		0x0610
156 #define DP0_VIDMNGEN1		0x0614
157 #define DP0_VMNGENSTATUS	0x0618
158 
159 /* Main Channel */
160 #define DP0_SECSAMPLE		0x0640
161 #define DP0_VIDSYNCDELAY	0x0644
162 #define VID_SYNC_DLY		GENMASK(15, 0)
163 #define THRESH_DLY		GENMASK(31, 16)
164 
165 #define DP0_TOTALVAL		0x0648
166 #define H_TOTAL			GENMASK(15, 0)
167 #define V_TOTAL			GENMASK(31, 16)
168 #define DP0_STARTVAL		0x064c
169 #define H_START			GENMASK(15, 0)
170 #define V_START			GENMASK(31, 16)
171 #define DP0_ACTIVEVAL		0x0650
172 #define H_ACT			GENMASK(15, 0)
173 #define V_ACT			GENMASK(31, 16)
174 
175 #define DP0_SYNCVAL		0x0654
176 #define VS_WIDTH		GENMASK(30, 16)
177 #define HS_WIDTH		GENMASK(14, 0)
178 #define SYNCVAL_HS_POL_ACTIVE_LOW	(1 << 15)
179 #define SYNCVAL_VS_POL_ACTIVE_LOW	(1 << 31)
180 #define DP0_MISC		0x0658
181 #define TU_SIZE_RECOMMENDED		(63) /* LSCLK cycles per TU */
182 #define MAX_TU_SYMBOL		GENMASK(28, 23)
183 #define TU_SIZE			GENMASK(21, 16)
184 #define BPC_6				(0 << 5)
185 #define BPC_8				(1 << 5)
186 
187 /* AUX channel */
188 #define DP0_AUXCFG0		0x0660
189 #define DP0_AUXCFG0_BSIZE	GENMASK(11, 8)
190 #define DP0_AUXCFG0_ADDR_ONLY	BIT(4)
191 #define DP0_AUXCFG1		0x0664
192 #define AUX_RX_FILTER_EN		BIT(16)
193 
194 #define DP0_AUXADDR		0x0668
195 #define DP0_AUXWDATA(i)		(0x066c + (i) * 4)
196 #define DP0_AUXRDATA(i)		(0x067c + (i) * 4)
197 #define DP0_AUXSTATUS		0x068c
198 #define AUX_BYTES		GENMASK(15, 8)
199 #define AUX_STATUS		GENMASK(7, 4)
200 #define AUX_TIMEOUT		BIT(1)
201 #define AUX_BUSY		BIT(0)
202 #define DP0_AUXI2CADR		0x0698
203 
204 /* Link Training */
205 #define DP0_SRCCTRL		0x06a0
206 #define DP0_SRCCTRL_SCRMBLDIS		BIT(13)
207 #define DP0_SRCCTRL_EN810B		BIT(12)
208 #define DP0_SRCCTRL_NOTP		(0 << 8)
209 #define DP0_SRCCTRL_TP1			(1 << 8)
210 #define DP0_SRCCTRL_TP2			(2 << 8)
211 #define DP0_SRCCTRL_LANESKEW		BIT(7)
212 #define DP0_SRCCTRL_SSCG		BIT(3)
213 #define DP0_SRCCTRL_LANES_1		(0 << 2)
214 #define DP0_SRCCTRL_LANES_2		(1 << 2)
215 #define DP0_SRCCTRL_BW27		(1 << 1)
216 #define DP0_SRCCTRL_BW162		(0 << 1)
217 #define DP0_SRCCTRL_AUTOCORRECT		BIT(0)
218 #define DP0_LTSTAT		0x06d0
219 #define LT_LOOPDONE			BIT(13)
220 #define LT_STATUS_MASK			(0x1f << 8)
221 #define LT_CHANNEL1_EQ_BITS		(DP_CHANNEL_EQ_BITS << 4)
222 #define LT_INTERLANE_ALIGN_DONE		BIT(3)
223 #define LT_CHANNEL0_EQ_BITS		(DP_CHANNEL_EQ_BITS)
224 #define DP0_SNKLTCHGREQ		0x06d4
225 #define DP0_LTLOOPCTRL		0x06d8
226 #define DP0_SNKLTCTRL		0x06e4
227 
228 #define DP1_SRCCTRL		0x07a0
229 
230 /* PHY */
231 #define DP_PHY_CTRL		0x0800
232 #define DP_PHY_RST			BIT(28)  /* DP PHY Global Soft Reset */
233 #define BGREN				BIT(25)  /* AUX PHY BGR Enable */
234 #define PWR_SW_EN			BIT(24)  /* PHY Power Switch Enable */
235 #define PHY_M1_RST			BIT(12)  /* Reset PHY1 Main Channel */
236 #define PHY_RDY				BIT(16)  /* PHY Main Channels Ready */
237 #define PHY_M0_RST			BIT(8)   /* Reset PHY0 Main Channel */
238 #define PHY_2LANE			BIT(2)   /* PHY Enable 2 lanes */
239 #define PHY_A0_EN			BIT(1)   /* PHY Aux Channel0 Enable */
240 #define PHY_M0_EN			BIT(0)   /* PHY Main Channel0 Enable */
241 
242 /* PLL */
243 #define DP0_PLLCTRL		0x0900
244 #define DP1_PLLCTRL		0x0904	/* not defined in DS */
245 #define PXL_PLLCTRL		0x0908
246 #define PLLUPDATE			BIT(2)
247 #define PLLBYP				BIT(1)
248 #define PLLEN				BIT(0)
249 #define PXL_PLLPARAM		0x0914
250 #define IN_SEL_REFCLK			(0 << 14)
251 #define SYS_PLLPARAM		0x0918
252 #define REF_FREQ_38M4			(0 << 8) /* 38.4 MHz */
253 #define REF_FREQ_19M2			(1 << 8) /* 19.2 MHz */
254 #define REF_FREQ_26M			(2 << 8) /* 26 MHz */
255 #define REF_FREQ_13M			(3 << 8) /* 13 MHz */
256 #define SYSCLK_SEL_LSCLK		(0 << 4)
257 #define LSCLK_DIV_1			(0 << 0)
258 #define LSCLK_DIV_2			(1 << 0)
259 
260 /* Test & Debug */
261 #define TSTCTL			0x0a00
262 #define COLOR_R			GENMASK(31, 24)
263 #define COLOR_G			GENMASK(23, 16)
264 #define COLOR_B			GENMASK(15, 8)
265 #define ENI2CFILTER		BIT(4)
266 #define COLOR_BAR_MODE		GENMASK(1, 0)
267 #define COLOR_BAR_MODE_BARS	2
268 #define PLL_DBG			0x0a04
269 
270 static bool tc_test_pattern;
271 module_param_named(test, tc_test_pattern, bool, 0644);
272 
273 struct tc_edp_link {
274 	u8			dpcd[DP_RECEIVER_CAP_SIZE];
275 	unsigned int		rate;
276 	u8			num_lanes;
277 	u8			assr;
278 	bool			scrambler_dis;
279 	bool			spread;
280 };
281 
282 struct tc_data {
283 	struct device		*dev;
284 	struct regmap		*regmap;
285 	struct drm_dp_aux	aux;
286 
287 	struct drm_bridge	bridge;
288 	struct drm_bridge	*panel_bridge;
289 	struct drm_connector	connector;
290 
291 	struct mipi_dsi_device	*dsi;
292 
293 	/* link settings */
294 	struct tc_edp_link	link;
295 
296 	/* current mode */
297 	struct drm_display_mode	mode;
298 
299 	u32			rev;
300 	u8			assr;
301 
302 	struct gpio_desc	*sd_gpio;
303 	struct gpio_desc	*reset_gpio;
304 	struct clk		*refclk;
305 
306 	/* do we have IRQ */
307 	bool			have_irq;
308 
309 	/* Input connector type, DSI and not DPI. */
310 	bool			input_connector_dsi;
311 
312 	/* HPD pin number (0 or 1) or -ENODEV */
313 	int			hpd_pin;
314 };
315 
316 static inline struct tc_data *aux_to_tc(struct drm_dp_aux *a)
317 {
318 	return container_of(a, struct tc_data, aux);
319 }
320 
321 static inline struct tc_data *bridge_to_tc(struct drm_bridge *b)
322 {
323 	return container_of(b, struct tc_data, bridge);
324 }
325 
326 static inline struct tc_data *connector_to_tc(struct drm_connector *c)
327 {
328 	return container_of(c, struct tc_data, connector);
329 }
330 
331 static inline int tc_poll_timeout(struct tc_data *tc, unsigned int addr,
332 				  unsigned int cond_mask,
333 				  unsigned int cond_value,
334 				  unsigned long sleep_us, u64 timeout_us)
335 {
336 	unsigned int val;
337 
338 	return regmap_read_poll_timeout(tc->regmap, addr, val,
339 					(val & cond_mask) == cond_value,
340 					sleep_us, timeout_us);
341 }
342 
343 static int tc_aux_wait_busy(struct tc_data *tc)
344 {
345 	return tc_poll_timeout(tc, DP0_AUXSTATUS, AUX_BUSY, 0, 100, 100000);
346 }
347 
348 static int tc_aux_write_data(struct tc_data *tc, const void *data,
349 			     size_t size)
350 {
351 	u32 auxwdata[DP_AUX_MAX_PAYLOAD_BYTES / sizeof(u32)] = { 0 };
352 	int ret, count = ALIGN(size, sizeof(u32));
353 
354 	memcpy(auxwdata, data, size);
355 
356 	ret = regmap_raw_write(tc->regmap, DP0_AUXWDATA(0), auxwdata, count);
357 	if (ret)
358 		return ret;
359 
360 	return size;
361 }
362 
363 static int tc_aux_read_data(struct tc_data *tc, void *data, size_t size)
364 {
365 	u32 auxrdata[DP_AUX_MAX_PAYLOAD_BYTES / sizeof(u32)];
366 	int ret, count = ALIGN(size, sizeof(u32));
367 
368 	ret = regmap_raw_read(tc->regmap, DP0_AUXRDATA(0), auxrdata, count);
369 	if (ret)
370 		return ret;
371 
372 	memcpy(data, auxrdata, size);
373 
374 	return size;
375 }
376 
377 static u32 tc_auxcfg0(struct drm_dp_aux_msg *msg, size_t size)
378 {
379 	u32 auxcfg0 = msg->request;
380 
381 	if (size)
382 		auxcfg0 |= FIELD_PREP(DP0_AUXCFG0_BSIZE, size - 1);
383 	else
384 		auxcfg0 |= DP0_AUXCFG0_ADDR_ONLY;
385 
386 	return auxcfg0;
387 }
388 
389 static ssize_t tc_aux_transfer(struct drm_dp_aux *aux,
390 			       struct drm_dp_aux_msg *msg)
391 {
392 	struct tc_data *tc = aux_to_tc(aux);
393 	size_t size = min_t(size_t, DP_AUX_MAX_PAYLOAD_BYTES - 1, msg->size);
394 	u8 request = msg->request & ~DP_AUX_I2C_MOT;
395 	u32 auxstatus;
396 	int ret;
397 
398 	ret = tc_aux_wait_busy(tc);
399 	if (ret)
400 		return ret;
401 
402 	switch (request) {
403 	case DP_AUX_NATIVE_READ:
404 	case DP_AUX_I2C_READ:
405 		break;
406 	case DP_AUX_NATIVE_WRITE:
407 	case DP_AUX_I2C_WRITE:
408 		if (size) {
409 			ret = tc_aux_write_data(tc, msg->buffer, size);
410 			if (ret < 0)
411 				return ret;
412 		}
413 		break;
414 	default:
415 		return -EINVAL;
416 	}
417 
418 	/* Store address */
419 	ret = regmap_write(tc->regmap, DP0_AUXADDR, msg->address);
420 	if (ret)
421 		return ret;
422 	/* Start transfer */
423 	ret = regmap_write(tc->regmap, DP0_AUXCFG0, tc_auxcfg0(msg, size));
424 	if (ret)
425 		return ret;
426 
427 	ret = tc_aux_wait_busy(tc);
428 	if (ret)
429 		return ret;
430 
431 	ret = regmap_read(tc->regmap, DP0_AUXSTATUS, &auxstatus);
432 	if (ret)
433 		return ret;
434 
435 	if (auxstatus & AUX_TIMEOUT)
436 		return -ETIMEDOUT;
437 	/*
438 	 * For some reason address-only DP_AUX_I2C_WRITE (MOT), still
439 	 * reports 1 byte transferred in its status. To deal we that
440 	 * we ignore aux_bytes field if we know that this was an
441 	 * address-only transfer
442 	 */
443 	if (size)
444 		size = FIELD_GET(AUX_BYTES, auxstatus);
445 	msg->reply = FIELD_GET(AUX_STATUS, auxstatus);
446 
447 	switch (request) {
448 	case DP_AUX_NATIVE_READ:
449 	case DP_AUX_I2C_READ:
450 		if (size)
451 			return tc_aux_read_data(tc, msg->buffer, size);
452 		break;
453 	}
454 
455 	return size;
456 }
457 
458 static const char * const training_pattern1_errors[] = {
459 	"No errors",
460 	"Aux write error",
461 	"Aux read error",
462 	"Max voltage reached error",
463 	"Loop counter expired error",
464 	"res", "res", "res"
465 };
466 
467 static const char * const training_pattern2_errors[] = {
468 	"No errors",
469 	"Aux write error",
470 	"Aux read error",
471 	"Clock recovery failed error",
472 	"Loop counter expired error",
473 	"res", "res", "res"
474 };
475 
476 static u32 tc_srcctrl(struct tc_data *tc)
477 {
478 	/*
479 	 * No training pattern, skew lane 1 data by two LSCLK cycles with
480 	 * respect to lane 0 data, AutoCorrect Mode = 0
481 	 */
482 	u32 reg = DP0_SRCCTRL_NOTP | DP0_SRCCTRL_LANESKEW | DP0_SRCCTRL_EN810B;
483 
484 	if (tc->link.scrambler_dis)
485 		reg |= DP0_SRCCTRL_SCRMBLDIS;	/* Scrambler Disabled */
486 	if (tc->link.spread)
487 		reg |= DP0_SRCCTRL_SSCG;	/* Spread Spectrum Enable */
488 	if (tc->link.num_lanes == 2)
489 		reg |= DP0_SRCCTRL_LANES_2;	/* Two Main Channel Lanes */
490 	if (tc->link.rate != 162000)
491 		reg |= DP0_SRCCTRL_BW27;	/* 2.7 Gbps link */
492 	return reg;
493 }
494 
495 static int tc_pllupdate(struct tc_data *tc, unsigned int pllctrl)
496 {
497 	int ret;
498 
499 	ret = regmap_write(tc->regmap, pllctrl, PLLUPDATE | PLLEN);
500 	if (ret)
501 		return ret;
502 
503 	/* Wait for PLL to lock: up to 2.09 ms, depending on refclk */
504 	usleep_range(3000, 6000);
505 
506 	return 0;
507 }
508 
509 static int tc_pxl_pll_en(struct tc_data *tc, u32 refclk, u32 pixelclock)
510 {
511 	int ret;
512 	int i_pre, best_pre = 1;
513 	int i_post, best_post = 1;
514 	int div, best_div = 1;
515 	int mul, best_mul = 1;
516 	int delta, best_delta;
517 	int ext_div[] = {1, 2, 3, 5, 7};
518 	int clk_min, clk_max;
519 	int best_pixelclock = 0;
520 	int vco_hi = 0;
521 	u32 pxl_pllparam;
522 
523 	/*
524 	 * refclk * mul / (ext_pre_div * pre_div) should be in range:
525 	 * - DPI ..... 0 to 100 MHz
526 	 * - (e)DP ... 150 to 650 MHz
527 	 */
528 	if (tc->bridge.type == DRM_MODE_CONNECTOR_DPI) {
529 		clk_min = 0;
530 		clk_max = 100000000;
531 	} else {
532 		clk_min = 150000000;
533 		clk_max = 650000000;
534 	}
535 
536 	dev_dbg(tc->dev, "PLL: requested %d pixelclock, ref %d\n", pixelclock,
537 		refclk);
538 	best_delta = pixelclock;
539 	/* Loop over all possible ext_divs, skipping invalid configurations */
540 	for (i_pre = 0; i_pre < ARRAY_SIZE(ext_div); i_pre++) {
541 		/*
542 		 * refclk / ext_pre_div should be in the 1 to 200 MHz range.
543 		 * We don't allow any refclk > 200 MHz, only check lower bounds.
544 		 */
545 		if (refclk / ext_div[i_pre] < 1000000)
546 			continue;
547 		for (i_post = 0; i_post < ARRAY_SIZE(ext_div); i_post++) {
548 			for (div = 1; div <= 16; div++) {
549 				u32 clk;
550 				u64 tmp;
551 
552 				tmp = pixelclock * ext_div[i_pre] *
553 				      ext_div[i_post] * div;
554 				do_div(tmp, refclk);
555 				mul = tmp;
556 
557 				/* Check limits */
558 				if ((mul < 1) || (mul > 128))
559 					continue;
560 
561 				clk = (refclk / ext_div[i_pre] / div) * mul;
562 				if ((clk > clk_max) || (clk < clk_min))
563 					continue;
564 
565 				clk = clk / ext_div[i_post];
566 				delta = clk - pixelclock;
567 
568 				if (abs(delta) < abs(best_delta)) {
569 					best_pre = i_pre;
570 					best_post = i_post;
571 					best_div = div;
572 					best_mul = mul;
573 					best_delta = delta;
574 					best_pixelclock = clk;
575 				}
576 			}
577 		}
578 	}
579 	if (best_pixelclock == 0) {
580 		dev_err(tc->dev, "Failed to calc clock for %d pixelclock\n",
581 			pixelclock);
582 		return -EINVAL;
583 	}
584 
585 	dev_dbg(tc->dev, "PLL: got %d, delta %d\n", best_pixelclock,
586 		best_delta);
587 	dev_dbg(tc->dev, "PLL: %d / %d / %d * %d / %d\n", refclk,
588 		ext_div[best_pre], best_div, best_mul, ext_div[best_post]);
589 
590 	/* if VCO >= 300 MHz */
591 	if (refclk / ext_div[best_pre] / best_div * best_mul >= 300000000)
592 		vco_hi = 1;
593 	/* see DS */
594 	if (best_div == 16)
595 		best_div = 0;
596 	if (best_mul == 128)
597 		best_mul = 0;
598 
599 	/* Power up PLL and switch to bypass */
600 	ret = regmap_write(tc->regmap, PXL_PLLCTRL, PLLBYP | PLLEN);
601 	if (ret)
602 		return ret;
603 
604 	pxl_pllparam  = vco_hi << 24; /* For PLL VCO >= 300 MHz = 1 */
605 	pxl_pllparam |= ext_div[best_pre] << 20; /* External Pre-divider */
606 	pxl_pllparam |= ext_div[best_post] << 16; /* External Post-divider */
607 	pxl_pllparam |= IN_SEL_REFCLK; /* Use RefClk as PLL input */
608 	pxl_pllparam |= best_div << 8; /* Divider for PLL RefClk */
609 	pxl_pllparam |= best_mul; /* Multiplier for PLL */
610 
611 	ret = regmap_write(tc->regmap, PXL_PLLPARAM, pxl_pllparam);
612 	if (ret)
613 		return ret;
614 
615 	/* Force PLL parameter update and disable bypass */
616 	return tc_pllupdate(tc, PXL_PLLCTRL);
617 }
618 
619 static int tc_pxl_pll_dis(struct tc_data *tc)
620 {
621 	/* Enable PLL bypass, power down PLL */
622 	return regmap_write(tc->regmap, PXL_PLLCTRL, PLLBYP);
623 }
624 
625 static int tc_stream_clock_calc(struct tc_data *tc)
626 {
627 	/*
628 	 * If the Stream clock and Link Symbol clock are
629 	 * asynchronous with each other, the value of M changes over
630 	 * time. This way of generating link clock and stream
631 	 * clock is called Asynchronous Clock mode. The value M
632 	 * must change while the value N stays constant. The
633 	 * value of N in this Asynchronous Clock mode must be set
634 	 * to 2^15 or 32,768.
635 	 *
636 	 * LSCLK = 1/10 of high speed link clock
637 	 *
638 	 * f_STRMCLK = M/N * f_LSCLK
639 	 * M/N = f_STRMCLK / f_LSCLK
640 	 *
641 	 */
642 	return regmap_write(tc->regmap, DP0_VIDMNGEN1, 32768);
643 }
644 
645 static int tc_set_syspllparam(struct tc_data *tc)
646 {
647 	unsigned long rate;
648 	u32 pllparam = SYSCLK_SEL_LSCLK | LSCLK_DIV_2;
649 
650 	rate = clk_get_rate(tc->refclk);
651 	switch (rate) {
652 	case 38400000:
653 		pllparam |= REF_FREQ_38M4;
654 		break;
655 	case 26000000:
656 		pllparam |= REF_FREQ_26M;
657 		break;
658 	case 19200000:
659 		pllparam |= REF_FREQ_19M2;
660 		break;
661 	case 13000000:
662 		pllparam |= REF_FREQ_13M;
663 		break;
664 	default:
665 		dev_err(tc->dev, "Invalid refclk rate: %lu Hz\n", rate);
666 		return -EINVAL;
667 	}
668 
669 	return regmap_write(tc->regmap, SYS_PLLPARAM, pllparam);
670 }
671 
672 static int tc_aux_link_setup(struct tc_data *tc)
673 {
674 	int ret;
675 	u32 dp0_auxcfg1;
676 
677 	/* Setup DP-PHY / PLL */
678 	ret = tc_set_syspllparam(tc);
679 	if (ret)
680 		goto err;
681 
682 	ret = regmap_write(tc->regmap, DP_PHY_CTRL,
683 			   BGREN | PWR_SW_EN | PHY_A0_EN);
684 	if (ret)
685 		goto err;
686 	/*
687 	 * Initially PLLs are in bypass. Force PLL parameter update,
688 	 * disable PLL bypass, enable PLL
689 	 */
690 	ret = tc_pllupdate(tc, DP0_PLLCTRL);
691 	if (ret)
692 		goto err;
693 
694 	ret = tc_pllupdate(tc, DP1_PLLCTRL);
695 	if (ret)
696 		goto err;
697 
698 	ret = tc_poll_timeout(tc, DP_PHY_CTRL, PHY_RDY, PHY_RDY, 100, 100000);
699 	if (ret == -ETIMEDOUT) {
700 		dev_err(tc->dev, "Timeout waiting for PHY to become ready");
701 		return ret;
702 	} else if (ret) {
703 		goto err;
704 	}
705 
706 	/* Setup AUX link */
707 	dp0_auxcfg1  = AUX_RX_FILTER_EN;
708 	dp0_auxcfg1 |= 0x06 << 8; /* Aux Bit Period Calculator Threshold */
709 	dp0_auxcfg1 |= 0x3f << 0; /* Aux Response Timeout Timer */
710 
711 	ret = regmap_write(tc->regmap, DP0_AUXCFG1, dp0_auxcfg1);
712 	if (ret)
713 		goto err;
714 
715 	/* Register DP AUX channel */
716 	tc->aux.name = "TC358767 AUX i2c adapter";
717 	tc->aux.dev = tc->dev;
718 	tc->aux.transfer = tc_aux_transfer;
719 	drm_dp_aux_init(&tc->aux);
720 
721 	return 0;
722 err:
723 	dev_err(tc->dev, "tc_aux_link_setup failed: %d\n", ret);
724 	return ret;
725 }
726 
727 static int tc_get_display_props(struct tc_data *tc)
728 {
729 	u8 revision, num_lanes;
730 	unsigned int rate;
731 	int ret;
732 	u8 reg;
733 
734 	/* Read DP Rx Link Capability */
735 	ret = drm_dp_dpcd_read(&tc->aux, DP_DPCD_REV, tc->link.dpcd,
736 			       DP_RECEIVER_CAP_SIZE);
737 	if (ret < 0)
738 		goto err_dpcd_read;
739 
740 	revision = tc->link.dpcd[DP_DPCD_REV];
741 	rate = drm_dp_max_link_rate(tc->link.dpcd);
742 	num_lanes = drm_dp_max_lane_count(tc->link.dpcd);
743 
744 	if (rate != 162000 && rate != 270000) {
745 		dev_dbg(tc->dev, "Falling to 2.7 Gbps rate\n");
746 		rate = 270000;
747 	}
748 
749 	tc->link.rate = rate;
750 
751 	if (num_lanes > 2) {
752 		dev_dbg(tc->dev, "Falling to 2 lanes\n");
753 		num_lanes = 2;
754 	}
755 
756 	tc->link.num_lanes = num_lanes;
757 
758 	ret = drm_dp_dpcd_readb(&tc->aux, DP_MAX_DOWNSPREAD, &reg);
759 	if (ret < 0)
760 		goto err_dpcd_read;
761 	tc->link.spread = reg & DP_MAX_DOWNSPREAD_0_5;
762 
763 	ret = drm_dp_dpcd_readb(&tc->aux, DP_MAIN_LINK_CHANNEL_CODING, &reg);
764 	if (ret < 0)
765 		goto err_dpcd_read;
766 
767 	tc->link.scrambler_dis = false;
768 	/* read assr */
769 	ret = drm_dp_dpcd_readb(&tc->aux, DP_EDP_CONFIGURATION_SET, &reg);
770 	if (ret < 0)
771 		goto err_dpcd_read;
772 	tc->link.assr = reg & DP_ALTERNATE_SCRAMBLER_RESET_ENABLE;
773 
774 	dev_dbg(tc->dev, "DPCD rev: %d.%d, rate: %s, lanes: %d, framing: %s\n",
775 		revision >> 4, revision & 0x0f,
776 		(tc->link.rate == 162000) ? "1.62Gbps" : "2.7Gbps",
777 		tc->link.num_lanes,
778 		drm_dp_enhanced_frame_cap(tc->link.dpcd) ?
779 		"enhanced" : "default");
780 	dev_dbg(tc->dev, "Downspread: %s, scrambler: %s\n",
781 		tc->link.spread ? "0.5%" : "0.0%",
782 		tc->link.scrambler_dis ? "disabled" : "enabled");
783 	dev_dbg(tc->dev, "Display ASSR: %d, TC358767 ASSR: %d\n",
784 		tc->link.assr, tc->assr);
785 
786 	return 0;
787 
788 err_dpcd_read:
789 	dev_err(tc->dev, "failed to read DPCD: %d\n", ret);
790 	return ret;
791 }
792 
793 static int tc_set_common_video_mode(struct tc_data *tc,
794 				    const struct drm_display_mode *mode)
795 {
796 	int left_margin = mode->htotal - mode->hsync_end;
797 	int right_margin = mode->hsync_start - mode->hdisplay;
798 	int hsync_len = mode->hsync_end - mode->hsync_start;
799 	int upper_margin = mode->vtotal - mode->vsync_end;
800 	int lower_margin = mode->vsync_start - mode->vdisplay;
801 	int vsync_len = mode->vsync_end - mode->vsync_start;
802 	int ret;
803 
804 	dev_dbg(tc->dev, "set mode %dx%d\n",
805 		mode->hdisplay, mode->vdisplay);
806 	dev_dbg(tc->dev, "H margin %d,%d sync %d\n",
807 		left_margin, right_margin, hsync_len);
808 	dev_dbg(tc->dev, "V margin %d,%d sync %d\n",
809 		upper_margin, lower_margin, vsync_len);
810 	dev_dbg(tc->dev, "total: %dx%d\n", mode->htotal, mode->vtotal);
811 
812 
813 	/*
814 	 * LCD Ctl Frame Size
815 	 * datasheet is not clear of vsdelay in case of DPI
816 	 * assume we do not need any delay when DPI is a source of
817 	 * sync signals
818 	 */
819 	ret = regmap_write(tc->regmap, VPCTRL0,
820 			   FIELD_PREP(VSDELAY, 0) |
821 			   OPXLFMT_RGB888 | FRMSYNC_DISABLED | MSF_DISABLED);
822 	if (ret)
823 		return ret;
824 
825 	ret = regmap_write(tc->regmap, HTIM01,
826 			   FIELD_PREP(HBPR, ALIGN(left_margin, 2)) |
827 			   FIELD_PREP(HPW, ALIGN(hsync_len, 2)));
828 	if (ret)
829 		return ret;
830 
831 	ret = regmap_write(tc->regmap, HTIM02,
832 			   FIELD_PREP(HDISPR, ALIGN(mode->hdisplay, 2)) |
833 			   FIELD_PREP(HFPR, ALIGN(right_margin, 2)));
834 	if (ret)
835 		return ret;
836 
837 	ret = regmap_write(tc->regmap, VTIM01,
838 			   FIELD_PREP(VBPR, upper_margin) |
839 			   FIELD_PREP(VSPR, vsync_len));
840 	if (ret)
841 		return ret;
842 
843 	ret = regmap_write(tc->regmap, VTIM02,
844 			   FIELD_PREP(VFPR, lower_margin) |
845 			   FIELD_PREP(VDISPR, mode->vdisplay));
846 	if (ret)
847 		return ret;
848 
849 	ret = regmap_write(tc->regmap, VFUEN0, VFUEN); /* update settings */
850 	if (ret)
851 		return ret;
852 
853 	/* Test pattern settings */
854 	ret = regmap_write(tc->regmap, TSTCTL,
855 			   FIELD_PREP(COLOR_R, 120) |
856 			   FIELD_PREP(COLOR_G, 20) |
857 			   FIELD_PREP(COLOR_B, 99) |
858 			   ENI2CFILTER |
859 			   FIELD_PREP(COLOR_BAR_MODE, COLOR_BAR_MODE_BARS));
860 
861 	return ret;
862 }
863 
864 static int tc_set_dpi_video_mode(struct tc_data *tc,
865 				 const struct drm_display_mode *mode)
866 {
867 	u32 value = POCTRL_S2P;
868 
869 	if (tc->mode.flags & DRM_MODE_FLAG_NHSYNC)
870 		value |= POCTRL_HS_POL;
871 
872 	if (tc->mode.flags & DRM_MODE_FLAG_NVSYNC)
873 		value |= POCTRL_VS_POL;
874 
875 	return regmap_write(tc->regmap, POCTRL, value);
876 }
877 
878 static int tc_set_edp_video_mode(struct tc_data *tc,
879 				 const struct drm_display_mode *mode)
880 {
881 	int ret;
882 	int vid_sync_dly;
883 	int max_tu_symbol;
884 
885 	int left_margin = mode->htotal - mode->hsync_end;
886 	int hsync_len = mode->hsync_end - mode->hsync_start;
887 	int upper_margin = mode->vtotal - mode->vsync_end;
888 	int vsync_len = mode->vsync_end - mode->vsync_start;
889 	u32 dp0_syncval;
890 	u32 bits_per_pixel = 24;
891 	u32 in_bw, out_bw;
892 
893 	/*
894 	 * Recommended maximum number of symbols transferred in a transfer unit:
895 	 * DIV_ROUND_UP((input active video bandwidth in bytes) * tu_size,
896 	 *              (output active video bandwidth in bytes))
897 	 * Must be less than tu_size.
898 	 */
899 
900 	in_bw = mode->clock * bits_per_pixel / 8;
901 	out_bw = tc->link.num_lanes * tc->link.rate;
902 	max_tu_symbol = DIV_ROUND_UP(in_bw * TU_SIZE_RECOMMENDED, out_bw);
903 
904 	/* DP Main Stream Attributes */
905 	vid_sync_dly = hsync_len + left_margin + mode->hdisplay;
906 	ret = regmap_write(tc->regmap, DP0_VIDSYNCDELAY,
907 		 FIELD_PREP(THRESH_DLY, max_tu_symbol) |
908 		 FIELD_PREP(VID_SYNC_DLY, vid_sync_dly));
909 
910 	ret = regmap_write(tc->regmap, DP0_TOTALVAL,
911 			   FIELD_PREP(H_TOTAL, mode->htotal) |
912 			   FIELD_PREP(V_TOTAL, mode->vtotal));
913 	if (ret)
914 		return ret;
915 
916 	ret = regmap_write(tc->regmap, DP0_STARTVAL,
917 			   FIELD_PREP(H_START, left_margin + hsync_len) |
918 			   FIELD_PREP(V_START, upper_margin + vsync_len));
919 	if (ret)
920 		return ret;
921 
922 	ret = regmap_write(tc->regmap, DP0_ACTIVEVAL,
923 			   FIELD_PREP(V_ACT, mode->vdisplay) |
924 			   FIELD_PREP(H_ACT, mode->hdisplay));
925 	if (ret)
926 		return ret;
927 
928 	dp0_syncval = FIELD_PREP(VS_WIDTH, vsync_len) |
929 		      FIELD_PREP(HS_WIDTH, hsync_len);
930 
931 	if (mode->flags & DRM_MODE_FLAG_NVSYNC)
932 		dp0_syncval |= SYNCVAL_VS_POL_ACTIVE_LOW;
933 
934 	if (mode->flags & DRM_MODE_FLAG_NHSYNC)
935 		dp0_syncval |= SYNCVAL_HS_POL_ACTIVE_LOW;
936 
937 	ret = regmap_write(tc->regmap, DP0_SYNCVAL, dp0_syncval);
938 	if (ret)
939 		return ret;
940 
941 	ret = regmap_write(tc->regmap, DPIPXLFMT,
942 			   VS_POL_ACTIVE_LOW | HS_POL_ACTIVE_LOW |
943 			   DE_POL_ACTIVE_HIGH | SUB_CFG_TYPE_CONFIG1 |
944 			   DPI_BPP_RGB888);
945 	if (ret)
946 		return ret;
947 
948 	ret = regmap_write(tc->regmap, DP0_MISC,
949 			   FIELD_PREP(MAX_TU_SYMBOL, max_tu_symbol) |
950 			   FIELD_PREP(TU_SIZE, TU_SIZE_RECOMMENDED) |
951 			   BPC_8);
952 	return ret;
953 }
954 
955 static int tc_wait_link_training(struct tc_data *tc)
956 {
957 	u32 value;
958 	int ret;
959 
960 	ret = tc_poll_timeout(tc, DP0_LTSTAT, LT_LOOPDONE,
961 			      LT_LOOPDONE, 500, 100000);
962 	if (ret) {
963 		dev_err(tc->dev, "Link training timeout waiting for LT_LOOPDONE!\n");
964 		return ret;
965 	}
966 
967 	ret = regmap_read(tc->regmap, DP0_LTSTAT, &value);
968 	if (ret)
969 		return ret;
970 
971 	return (value >> 8) & 0x7;
972 }
973 
974 static int tc_main_link_enable(struct tc_data *tc)
975 {
976 	struct drm_dp_aux *aux = &tc->aux;
977 	struct device *dev = tc->dev;
978 	u32 dp_phy_ctrl;
979 	u32 value;
980 	int ret;
981 	u8 tmp[DP_LINK_STATUS_SIZE];
982 
983 	dev_dbg(tc->dev, "link enable\n");
984 
985 	ret = regmap_read(tc->regmap, DP0CTL, &value);
986 	if (ret)
987 		return ret;
988 
989 	if (WARN_ON(value & DP_EN)) {
990 		ret = regmap_write(tc->regmap, DP0CTL, 0);
991 		if (ret)
992 			return ret;
993 	}
994 
995 	ret = regmap_write(tc->regmap, DP0_SRCCTRL, tc_srcctrl(tc));
996 	if (ret)
997 		return ret;
998 	/* SSCG and BW27 on DP1 must be set to the same as on DP0 */
999 	ret = regmap_write(tc->regmap, DP1_SRCCTRL,
1000 		 (tc->link.spread ? DP0_SRCCTRL_SSCG : 0) |
1001 		 ((tc->link.rate != 162000) ? DP0_SRCCTRL_BW27 : 0));
1002 	if (ret)
1003 		return ret;
1004 
1005 	ret = tc_set_syspllparam(tc);
1006 	if (ret)
1007 		return ret;
1008 
1009 	/* Setup Main Link */
1010 	dp_phy_ctrl = BGREN | PWR_SW_EN | PHY_A0_EN | PHY_M0_EN;
1011 	if (tc->link.num_lanes == 2)
1012 		dp_phy_ctrl |= PHY_2LANE;
1013 
1014 	ret = regmap_write(tc->regmap, DP_PHY_CTRL, dp_phy_ctrl);
1015 	if (ret)
1016 		return ret;
1017 
1018 	/* PLL setup */
1019 	ret = tc_pllupdate(tc, DP0_PLLCTRL);
1020 	if (ret)
1021 		return ret;
1022 
1023 	ret = tc_pllupdate(tc, DP1_PLLCTRL);
1024 	if (ret)
1025 		return ret;
1026 
1027 	/* Reset/Enable Main Links */
1028 	dp_phy_ctrl |= DP_PHY_RST | PHY_M1_RST | PHY_M0_RST;
1029 	ret = regmap_write(tc->regmap, DP_PHY_CTRL, dp_phy_ctrl);
1030 	usleep_range(100, 200);
1031 	dp_phy_ctrl &= ~(DP_PHY_RST | PHY_M1_RST | PHY_M0_RST);
1032 	ret = regmap_write(tc->regmap, DP_PHY_CTRL, dp_phy_ctrl);
1033 
1034 	ret = tc_poll_timeout(tc, DP_PHY_CTRL, PHY_RDY, PHY_RDY, 500, 100000);
1035 	if (ret) {
1036 		dev_err(dev, "timeout waiting for phy become ready");
1037 		return ret;
1038 	}
1039 
1040 	/* Set misc: 8 bits per color */
1041 	ret = regmap_update_bits(tc->regmap, DP0_MISC, BPC_8, BPC_8);
1042 	if (ret)
1043 		return ret;
1044 
1045 	/*
1046 	 * ASSR mode
1047 	 * on TC358767 side ASSR configured through strap pin
1048 	 * seems there is no way to change this setting from SW
1049 	 *
1050 	 * check is tc configured for same mode
1051 	 */
1052 	if (tc->assr != tc->link.assr) {
1053 		dev_dbg(dev, "Trying to set display to ASSR: %d\n",
1054 			tc->assr);
1055 		/* try to set ASSR on display side */
1056 		tmp[0] = tc->assr;
1057 		ret = drm_dp_dpcd_writeb(aux, DP_EDP_CONFIGURATION_SET, tmp[0]);
1058 		if (ret < 0)
1059 			goto err_dpcd_read;
1060 		/* read back */
1061 		ret = drm_dp_dpcd_readb(aux, DP_EDP_CONFIGURATION_SET, tmp);
1062 		if (ret < 0)
1063 			goto err_dpcd_read;
1064 
1065 		if (tmp[0] != tc->assr) {
1066 			dev_dbg(dev, "Failed to switch display ASSR to %d, falling back to unscrambled mode\n",
1067 				tc->assr);
1068 			/* trying with disabled scrambler */
1069 			tc->link.scrambler_dis = true;
1070 		}
1071 	}
1072 
1073 	/* Setup Link & DPRx Config for Training */
1074 	tmp[0] = drm_dp_link_rate_to_bw_code(tc->link.rate);
1075 	tmp[1] = tc->link.num_lanes;
1076 
1077 	if (drm_dp_enhanced_frame_cap(tc->link.dpcd))
1078 		tmp[1] |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
1079 
1080 	ret = drm_dp_dpcd_write(aux, DP_LINK_BW_SET, tmp, 2);
1081 	if (ret < 0)
1082 		goto err_dpcd_write;
1083 
1084 	/* DOWNSPREAD_CTRL */
1085 	tmp[0] = tc->link.spread ? DP_SPREAD_AMP_0_5 : 0x00;
1086 	/* MAIN_LINK_CHANNEL_CODING_SET */
1087 	tmp[1] =  DP_SET_ANSI_8B10B;
1088 	ret = drm_dp_dpcd_write(aux, DP_DOWNSPREAD_CTRL, tmp, 2);
1089 	if (ret < 0)
1090 		goto err_dpcd_write;
1091 
1092 	/* Reset voltage-swing & pre-emphasis */
1093 	tmp[0] = tmp[1] = DP_TRAIN_VOLTAGE_SWING_LEVEL_0 |
1094 			  DP_TRAIN_PRE_EMPH_LEVEL_0;
1095 	ret = drm_dp_dpcd_write(aux, DP_TRAINING_LANE0_SET, tmp, 2);
1096 	if (ret < 0)
1097 		goto err_dpcd_write;
1098 
1099 	/* Clock-Recovery */
1100 
1101 	/* Set DPCD 0x102 for Training Pattern 1 */
1102 	ret = regmap_write(tc->regmap, DP0_SNKLTCTRL,
1103 			   DP_LINK_SCRAMBLING_DISABLE |
1104 			   DP_TRAINING_PATTERN_1);
1105 	if (ret)
1106 		return ret;
1107 
1108 	ret = regmap_write(tc->regmap, DP0_LTLOOPCTRL,
1109 			   (15 << 28) |	/* Defer Iteration Count */
1110 			   (15 << 24) |	/* Loop Iteration Count */
1111 			   (0xd << 0));	/* Loop Timer Delay */
1112 	if (ret)
1113 		return ret;
1114 
1115 	ret = regmap_write(tc->regmap, DP0_SRCCTRL,
1116 			   tc_srcctrl(tc) | DP0_SRCCTRL_SCRMBLDIS |
1117 			   DP0_SRCCTRL_AUTOCORRECT |
1118 			   DP0_SRCCTRL_TP1);
1119 	if (ret)
1120 		return ret;
1121 
1122 	/* Enable DP0 to start Link Training */
1123 	ret = regmap_write(tc->regmap, DP0CTL,
1124 			   (drm_dp_enhanced_frame_cap(tc->link.dpcd) ?
1125 				EF_EN : 0) | DP_EN);
1126 	if (ret)
1127 		return ret;
1128 
1129 	/* wait */
1130 
1131 	ret = tc_wait_link_training(tc);
1132 	if (ret < 0)
1133 		return ret;
1134 
1135 	if (ret) {
1136 		dev_err(tc->dev, "Link training phase 1 failed: %s\n",
1137 			training_pattern1_errors[ret]);
1138 		return -ENODEV;
1139 	}
1140 
1141 	/* Channel Equalization */
1142 
1143 	/* Set DPCD 0x102 for Training Pattern 2 */
1144 	ret = regmap_write(tc->regmap, DP0_SNKLTCTRL,
1145 			   DP_LINK_SCRAMBLING_DISABLE |
1146 			   DP_TRAINING_PATTERN_2);
1147 	if (ret)
1148 		return ret;
1149 
1150 	ret = regmap_write(tc->regmap, DP0_SRCCTRL,
1151 			   tc_srcctrl(tc) | DP0_SRCCTRL_SCRMBLDIS |
1152 			   DP0_SRCCTRL_AUTOCORRECT |
1153 			   DP0_SRCCTRL_TP2);
1154 	if (ret)
1155 		return ret;
1156 
1157 	/* wait */
1158 	ret = tc_wait_link_training(tc);
1159 	if (ret < 0)
1160 		return ret;
1161 
1162 	if (ret) {
1163 		dev_err(tc->dev, "Link training phase 2 failed: %s\n",
1164 			training_pattern2_errors[ret]);
1165 		return -ENODEV;
1166 	}
1167 
1168 	/*
1169 	 * Toshiba's documentation suggests to first clear DPCD 0x102, then
1170 	 * clear the training pattern bit in DP0_SRCCTRL. Testing shows
1171 	 * that the link sometimes drops if those steps are done in that order,
1172 	 * but if the steps are done in reverse order, the link stays up.
1173 	 *
1174 	 * So we do the steps differently than documented here.
1175 	 */
1176 
1177 	/* Clear Training Pattern, set AutoCorrect Mode = 1 */
1178 	ret = regmap_write(tc->regmap, DP0_SRCCTRL, tc_srcctrl(tc) |
1179 			   DP0_SRCCTRL_AUTOCORRECT);
1180 	if (ret)
1181 		return ret;
1182 
1183 	/* Clear DPCD 0x102 */
1184 	/* Note: Can Not use DP0_SNKLTCTRL (0x06E4) short cut */
1185 	tmp[0] = tc->link.scrambler_dis ? DP_LINK_SCRAMBLING_DISABLE : 0x00;
1186 	ret = drm_dp_dpcd_writeb(aux, DP_TRAINING_PATTERN_SET, tmp[0]);
1187 	if (ret < 0)
1188 		goto err_dpcd_write;
1189 
1190 	/* Check link status */
1191 	ret = drm_dp_dpcd_read_link_status(aux, tmp);
1192 	if (ret < 0)
1193 		goto err_dpcd_read;
1194 
1195 	ret = 0;
1196 
1197 	value = tmp[0] & DP_CHANNEL_EQ_BITS;
1198 
1199 	if (value != DP_CHANNEL_EQ_BITS) {
1200 		dev_err(tc->dev, "Lane 0 failed: %x\n", value);
1201 		ret = -ENODEV;
1202 	}
1203 
1204 	if (tc->link.num_lanes == 2) {
1205 		value = (tmp[0] >> 4) & DP_CHANNEL_EQ_BITS;
1206 
1207 		if (value != DP_CHANNEL_EQ_BITS) {
1208 			dev_err(tc->dev, "Lane 1 failed: %x\n", value);
1209 			ret = -ENODEV;
1210 		}
1211 
1212 		if (!(tmp[2] & DP_INTERLANE_ALIGN_DONE)) {
1213 			dev_err(tc->dev, "Interlane align failed\n");
1214 			ret = -ENODEV;
1215 		}
1216 	}
1217 
1218 	if (ret) {
1219 		dev_err(dev, "0x0202 LANE0_1_STATUS:            0x%02x\n", tmp[0]);
1220 		dev_err(dev, "0x0203 LANE2_3_STATUS             0x%02x\n", tmp[1]);
1221 		dev_err(dev, "0x0204 LANE_ALIGN_STATUS_UPDATED: 0x%02x\n", tmp[2]);
1222 		dev_err(dev, "0x0205 SINK_STATUS:               0x%02x\n", tmp[3]);
1223 		dev_err(dev, "0x0206 ADJUST_REQUEST_LANE0_1:    0x%02x\n", tmp[4]);
1224 		dev_err(dev, "0x0207 ADJUST_REQUEST_LANE2_3:    0x%02x\n", tmp[5]);
1225 		return ret;
1226 	}
1227 
1228 	return 0;
1229 err_dpcd_read:
1230 	dev_err(tc->dev, "Failed to read DPCD: %d\n", ret);
1231 	return ret;
1232 err_dpcd_write:
1233 	dev_err(tc->dev, "Failed to write DPCD: %d\n", ret);
1234 	return ret;
1235 }
1236 
1237 static int tc_main_link_disable(struct tc_data *tc)
1238 {
1239 	int ret;
1240 
1241 	dev_dbg(tc->dev, "link disable\n");
1242 
1243 	ret = regmap_write(tc->regmap, DP0_SRCCTRL, 0);
1244 	if (ret)
1245 		return ret;
1246 
1247 	return regmap_write(tc->regmap, DP0CTL, 0);
1248 }
1249 
1250 static int tc_dsi_rx_enable(struct tc_data *tc)
1251 {
1252 	u32 value;
1253 	int ret;
1254 
1255 	regmap_write(tc->regmap, PPI_D0S_CLRSIPOCOUNT, 3);
1256 	regmap_write(tc->regmap, PPI_D1S_CLRSIPOCOUNT, 3);
1257 	regmap_write(tc->regmap, PPI_D2S_CLRSIPOCOUNT, 3);
1258 	regmap_write(tc->regmap, PPI_D3S_CLRSIPOCOUNT, 3);
1259 	regmap_write(tc->regmap, PPI_D0S_ATMR, 0);
1260 	regmap_write(tc->regmap, PPI_D1S_ATMR, 0);
1261 	regmap_write(tc->regmap, PPI_TX_RX_TA, TTA_GET | TTA_SURE);
1262 	regmap_write(tc->regmap, PPI_LPTXTIMECNT, LPX_PERIOD);
1263 
1264 	value = ((LANEENABLE_L0EN << tc->dsi->lanes) - LANEENABLE_L0EN) |
1265 		LANEENABLE_CLEN;
1266 	regmap_write(tc->regmap, PPI_LANEENABLE, value);
1267 	regmap_write(tc->regmap, DSI_LANEENABLE, value);
1268 
1269 	/* Set input interface */
1270 	value = DP0_AUDSRC_NO_INPUT;
1271 	if (tc_test_pattern)
1272 		value |= DP0_VIDSRC_COLOR_BAR;
1273 	else
1274 		value |= DP0_VIDSRC_DSI_RX;
1275 	ret = regmap_write(tc->regmap, SYSCTRL, value);
1276 	if (ret)
1277 		return ret;
1278 
1279 	usleep_range(120, 150);
1280 
1281 	regmap_write(tc->regmap, PPI_STARTPPI, PPI_START_FUNCTION);
1282 	regmap_write(tc->regmap, DSI_STARTDSI, DSI_RX_START);
1283 
1284 	return 0;
1285 }
1286 
1287 static int tc_dpi_rx_enable(struct tc_data *tc)
1288 {
1289 	u32 value;
1290 
1291 	/* Set input interface */
1292 	value = DP0_AUDSRC_NO_INPUT;
1293 	if (tc_test_pattern)
1294 		value |= DP0_VIDSRC_COLOR_BAR;
1295 	else
1296 		value |= DP0_VIDSRC_DPI_RX;
1297 	return regmap_write(tc->regmap, SYSCTRL, value);
1298 }
1299 
1300 static int tc_dpi_stream_enable(struct tc_data *tc)
1301 {
1302 	int ret;
1303 
1304 	dev_dbg(tc->dev, "enable video stream\n");
1305 
1306 	/* Setup PLL */
1307 	ret = tc_set_syspllparam(tc);
1308 	if (ret)
1309 		return ret;
1310 
1311 	/*
1312 	 * Initially PLLs are in bypass. Force PLL parameter update,
1313 	 * disable PLL bypass, enable PLL
1314 	 */
1315 	ret = tc_pllupdate(tc, DP0_PLLCTRL);
1316 	if (ret)
1317 		return ret;
1318 
1319 	ret = tc_pllupdate(tc, DP1_PLLCTRL);
1320 	if (ret)
1321 		return ret;
1322 
1323 	/* Pixel PLL must always be enabled for DPI mode */
1324 	ret = tc_pxl_pll_en(tc, clk_get_rate(tc->refclk),
1325 			    1000 * tc->mode.clock);
1326 	if (ret)
1327 		return ret;
1328 
1329 	ret = tc_set_common_video_mode(tc, &tc->mode);
1330 	if (ret)
1331 		return ret;
1332 
1333 	ret = tc_set_dpi_video_mode(tc, &tc->mode);
1334 	if (ret)
1335 		return ret;
1336 
1337 	return tc_dsi_rx_enable(tc);
1338 }
1339 
1340 static int tc_dpi_stream_disable(struct tc_data *tc)
1341 {
1342 	dev_dbg(tc->dev, "disable video stream\n");
1343 
1344 	tc_pxl_pll_dis(tc);
1345 
1346 	return 0;
1347 }
1348 
1349 static int tc_edp_stream_enable(struct tc_data *tc)
1350 {
1351 	int ret;
1352 	u32 value;
1353 
1354 	dev_dbg(tc->dev, "enable video stream\n");
1355 
1356 	/*
1357 	 * Pixel PLL must be enabled for DSI input mode and test pattern.
1358 	 *
1359 	 * Per TC9595XBG datasheet Revision 0.1 2018-12-27 Figure 4.18
1360 	 * "Clock Mode Selection and Clock Sources", either Pixel PLL
1361 	 * or DPI_PCLK supplies StrmClk. DPI_PCLK is only available in
1362 	 * case valid Pixel Clock are supplied to the chip DPI input.
1363 	 * In case built-in test pattern is desired OR DSI input mode
1364 	 * is used, DPI_PCLK is not available and thus Pixel PLL must
1365 	 * be used instead.
1366 	 */
1367 	if (tc->input_connector_dsi || tc_test_pattern) {
1368 		ret = tc_pxl_pll_en(tc, clk_get_rate(tc->refclk),
1369 				    1000 * tc->mode.clock);
1370 		if (ret)
1371 			return ret;
1372 	}
1373 
1374 	ret = tc_set_common_video_mode(tc, &tc->mode);
1375 	if (ret)
1376 		return ret;
1377 
1378 	ret = tc_set_edp_video_mode(tc, &tc->mode);
1379 	if (ret)
1380 		return ret;
1381 
1382 	/* Set M/N */
1383 	ret = tc_stream_clock_calc(tc);
1384 	if (ret)
1385 		return ret;
1386 
1387 	value = VID_MN_GEN | DP_EN;
1388 	if (drm_dp_enhanced_frame_cap(tc->link.dpcd))
1389 		value |= EF_EN;
1390 	ret = regmap_write(tc->regmap, DP0CTL, value);
1391 	if (ret)
1392 		return ret;
1393 	/*
1394 	 * VID_EN assertion should be delayed by at least N * LSCLK
1395 	 * cycles from the time VID_MN_GEN is enabled in order to
1396 	 * generate stable values for VID_M. LSCLK is 270 MHz or
1397 	 * 162 MHz, VID_N is set to 32768 in  tc_stream_clock_calc(),
1398 	 * so a delay of at least 203 us should suffice.
1399 	 */
1400 	usleep_range(500, 1000);
1401 	value |= VID_EN;
1402 	ret = regmap_write(tc->regmap, DP0CTL, value);
1403 	if (ret)
1404 		return ret;
1405 
1406 	/* Set input interface */
1407 	if (tc->input_connector_dsi)
1408 		return tc_dsi_rx_enable(tc);
1409 	else
1410 		return tc_dpi_rx_enable(tc);
1411 }
1412 
1413 static int tc_edp_stream_disable(struct tc_data *tc)
1414 {
1415 	int ret;
1416 
1417 	dev_dbg(tc->dev, "disable video stream\n");
1418 
1419 	ret = regmap_update_bits(tc->regmap, DP0CTL, VID_EN, 0);
1420 	if (ret)
1421 		return ret;
1422 
1423 	tc_pxl_pll_dis(tc);
1424 
1425 	return 0;
1426 }
1427 
1428 static void
1429 tc_dpi_bridge_atomic_enable(struct drm_bridge *bridge,
1430 			    struct drm_bridge_state *old_bridge_state)
1431 
1432 {
1433 	struct tc_data *tc = bridge_to_tc(bridge);
1434 	int ret;
1435 
1436 	ret = tc_dpi_stream_enable(tc);
1437 	if (ret < 0) {
1438 		dev_err(tc->dev, "main link stream start error: %d\n", ret);
1439 		tc_main_link_disable(tc);
1440 		return;
1441 	}
1442 }
1443 
1444 static void
1445 tc_dpi_bridge_atomic_disable(struct drm_bridge *bridge,
1446 			     struct drm_bridge_state *old_bridge_state)
1447 {
1448 	struct tc_data *tc = bridge_to_tc(bridge);
1449 	int ret;
1450 
1451 	ret = tc_dpi_stream_disable(tc);
1452 	if (ret < 0)
1453 		dev_err(tc->dev, "main link stream stop error: %d\n", ret);
1454 }
1455 
1456 static void
1457 tc_edp_bridge_atomic_enable(struct drm_bridge *bridge,
1458 			    struct drm_bridge_state *old_bridge_state)
1459 {
1460 	struct tc_data *tc = bridge_to_tc(bridge);
1461 	int ret;
1462 
1463 	ret = tc_get_display_props(tc);
1464 	if (ret < 0) {
1465 		dev_err(tc->dev, "failed to read display props: %d\n", ret);
1466 		return;
1467 	}
1468 
1469 	ret = tc_main_link_enable(tc);
1470 	if (ret < 0) {
1471 		dev_err(tc->dev, "main link enable error: %d\n", ret);
1472 		return;
1473 	}
1474 
1475 	ret = tc_edp_stream_enable(tc);
1476 	if (ret < 0) {
1477 		dev_err(tc->dev, "main link stream start error: %d\n", ret);
1478 		tc_main_link_disable(tc);
1479 		return;
1480 	}
1481 }
1482 
1483 static void
1484 tc_edp_bridge_atomic_disable(struct drm_bridge *bridge,
1485 			     struct drm_bridge_state *old_bridge_state)
1486 {
1487 	struct tc_data *tc = bridge_to_tc(bridge);
1488 	int ret;
1489 
1490 	ret = tc_edp_stream_disable(tc);
1491 	if (ret < 0)
1492 		dev_err(tc->dev, "main link stream stop error: %d\n", ret);
1493 
1494 	ret = tc_main_link_disable(tc);
1495 	if (ret < 0)
1496 		dev_err(tc->dev, "main link disable error: %d\n", ret);
1497 }
1498 
1499 static bool tc_bridge_mode_fixup(struct drm_bridge *bridge,
1500 				 const struct drm_display_mode *mode,
1501 				 struct drm_display_mode *adj)
1502 {
1503 	/* Fixup sync polarities, both hsync and vsync are active low */
1504 	adj->flags = mode->flags;
1505 	adj->flags |= (DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_NVSYNC);
1506 	adj->flags &= ~(DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_PVSYNC);
1507 
1508 	return true;
1509 }
1510 
1511 static int tc_common_atomic_check(struct drm_bridge *bridge,
1512 				  struct drm_bridge_state *bridge_state,
1513 				  struct drm_crtc_state *crtc_state,
1514 				  struct drm_connector_state *conn_state,
1515 				  const unsigned int max_khz)
1516 {
1517 	tc_bridge_mode_fixup(bridge, &crtc_state->mode,
1518 			     &crtc_state->adjusted_mode);
1519 
1520 	if (crtc_state->adjusted_mode.clock > max_khz)
1521 		return -EINVAL;
1522 
1523 	return 0;
1524 }
1525 
1526 static int tc_dpi_atomic_check(struct drm_bridge *bridge,
1527 			       struct drm_bridge_state *bridge_state,
1528 			       struct drm_crtc_state *crtc_state,
1529 			       struct drm_connector_state *conn_state)
1530 {
1531 	/* DSI->DPI interface clock limitation: upto 100 MHz */
1532 	return tc_common_atomic_check(bridge, bridge_state, crtc_state,
1533 				      conn_state, 100000);
1534 }
1535 
1536 static int tc_edp_atomic_check(struct drm_bridge *bridge,
1537 			       struct drm_bridge_state *bridge_state,
1538 			       struct drm_crtc_state *crtc_state,
1539 			       struct drm_connector_state *conn_state)
1540 {
1541 	/* DPI->(e)DP interface clock limitation: upto 154 MHz */
1542 	return tc_common_atomic_check(bridge, bridge_state, crtc_state,
1543 				      conn_state, 154000);
1544 }
1545 
1546 static enum drm_mode_status
1547 tc_dpi_mode_valid(struct drm_bridge *bridge,
1548 		  const struct drm_display_info *info,
1549 		  const struct drm_display_mode *mode)
1550 {
1551 	/* DPI interface clock limitation: upto 100 MHz */
1552 	if (mode->clock > 100000)
1553 		return MODE_CLOCK_HIGH;
1554 
1555 	return MODE_OK;
1556 }
1557 
1558 static enum drm_mode_status
1559 tc_edp_mode_valid(struct drm_bridge *bridge,
1560 		  const struct drm_display_info *info,
1561 		  const struct drm_display_mode *mode)
1562 {
1563 	struct tc_data *tc = bridge_to_tc(bridge);
1564 	u32 req, avail;
1565 	u32 bits_per_pixel = 24;
1566 
1567 	/* DPI interface clock limitation: upto 154 MHz */
1568 	if (mode->clock > 154000)
1569 		return MODE_CLOCK_HIGH;
1570 
1571 	req = mode->clock * bits_per_pixel / 8;
1572 	avail = tc->link.num_lanes * tc->link.rate;
1573 
1574 	if (req > avail)
1575 		return MODE_BAD;
1576 
1577 	return MODE_OK;
1578 }
1579 
1580 static void tc_bridge_mode_set(struct drm_bridge *bridge,
1581 			       const struct drm_display_mode *mode,
1582 			       const struct drm_display_mode *adj)
1583 {
1584 	struct tc_data *tc = bridge_to_tc(bridge);
1585 
1586 	drm_mode_copy(&tc->mode, mode);
1587 }
1588 
1589 static struct edid *tc_get_edid(struct drm_bridge *bridge,
1590 				struct drm_connector *connector)
1591 {
1592 	struct tc_data *tc = bridge_to_tc(bridge);
1593 
1594 	return drm_get_edid(connector, &tc->aux.ddc);
1595 }
1596 
1597 static int tc_connector_get_modes(struct drm_connector *connector)
1598 {
1599 	struct tc_data *tc = connector_to_tc(connector);
1600 	int num_modes;
1601 	struct edid *edid;
1602 	int ret;
1603 
1604 	ret = tc_get_display_props(tc);
1605 	if (ret < 0) {
1606 		dev_err(tc->dev, "failed to read display props: %d\n", ret);
1607 		return 0;
1608 	}
1609 
1610 	if (tc->panel_bridge) {
1611 		num_modes = drm_bridge_get_modes(tc->panel_bridge, connector);
1612 		if (num_modes > 0)
1613 			return num_modes;
1614 	}
1615 
1616 	edid = tc_get_edid(&tc->bridge, connector);
1617 	num_modes = drm_add_edid_modes(connector, edid);
1618 	kfree(edid);
1619 
1620 	return num_modes;
1621 }
1622 
1623 static const struct drm_connector_helper_funcs tc_connector_helper_funcs = {
1624 	.get_modes = tc_connector_get_modes,
1625 };
1626 
1627 static enum drm_connector_status tc_bridge_detect(struct drm_bridge *bridge)
1628 {
1629 	struct tc_data *tc = bridge_to_tc(bridge);
1630 	bool conn;
1631 	u32 val;
1632 	int ret;
1633 
1634 	ret = regmap_read(tc->regmap, GPIOI, &val);
1635 	if (ret)
1636 		return connector_status_unknown;
1637 
1638 	conn = val & BIT(tc->hpd_pin);
1639 
1640 	if (conn)
1641 		return connector_status_connected;
1642 	else
1643 		return connector_status_disconnected;
1644 }
1645 
1646 static enum drm_connector_status
1647 tc_connector_detect(struct drm_connector *connector, bool force)
1648 {
1649 	struct tc_data *tc = connector_to_tc(connector);
1650 
1651 	if (tc->hpd_pin >= 0)
1652 		return tc_bridge_detect(&tc->bridge);
1653 
1654 	if (tc->panel_bridge)
1655 		return connector_status_connected;
1656 	else
1657 		return connector_status_unknown;
1658 }
1659 
1660 static const struct drm_connector_funcs tc_connector_funcs = {
1661 	.detect = tc_connector_detect,
1662 	.fill_modes = drm_helper_probe_single_connector_modes,
1663 	.destroy = drm_connector_cleanup,
1664 	.reset = drm_atomic_helper_connector_reset,
1665 	.atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state,
1666 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
1667 };
1668 
1669 static int tc_dpi_bridge_attach(struct drm_bridge *bridge,
1670 				enum drm_bridge_attach_flags flags)
1671 {
1672 	struct tc_data *tc = bridge_to_tc(bridge);
1673 
1674 	if (!tc->panel_bridge)
1675 		return 0;
1676 
1677 	return drm_bridge_attach(tc->bridge.encoder, tc->panel_bridge,
1678 				 &tc->bridge, flags);
1679 }
1680 
1681 static int tc_edp_bridge_attach(struct drm_bridge *bridge,
1682 				enum drm_bridge_attach_flags flags)
1683 {
1684 	u32 bus_format = MEDIA_BUS_FMT_RGB888_1X24;
1685 	struct tc_data *tc = bridge_to_tc(bridge);
1686 	struct drm_device *drm = bridge->dev;
1687 	int ret;
1688 
1689 	if (tc->panel_bridge) {
1690 		/* If a connector is required then this driver shall create it */
1691 		ret = drm_bridge_attach(tc->bridge.encoder, tc->panel_bridge,
1692 					&tc->bridge, flags | DRM_BRIDGE_ATTACH_NO_CONNECTOR);
1693 		if (ret)
1694 			return ret;
1695 	}
1696 
1697 	if (flags & DRM_BRIDGE_ATTACH_NO_CONNECTOR)
1698 		return 0;
1699 
1700 	tc->aux.drm_dev = drm;
1701 	ret = drm_dp_aux_register(&tc->aux);
1702 	if (ret < 0)
1703 		return ret;
1704 
1705 	/* Create DP/eDP connector */
1706 	drm_connector_helper_add(&tc->connector, &tc_connector_helper_funcs);
1707 	ret = drm_connector_init(drm, &tc->connector, &tc_connector_funcs, tc->bridge.type);
1708 	if (ret)
1709 		goto aux_unregister;
1710 
1711 	/* Don't poll if don't have HPD connected */
1712 	if (tc->hpd_pin >= 0) {
1713 		if (tc->have_irq)
1714 			tc->connector.polled = DRM_CONNECTOR_POLL_HPD;
1715 		else
1716 			tc->connector.polled = DRM_CONNECTOR_POLL_CONNECT |
1717 					       DRM_CONNECTOR_POLL_DISCONNECT;
1718 	}
1719 
1720 	drm_display_info_set_bus_formats(&tc->connector.display_info,
1721 					 &bus_format, 1);
1722 	tc->connector.display_info.bus_flags =
1723 		DRM_BUS_FLAG_DE_HIGH |
1724 		DRM_BUS_FLAG_PIXDATA_DRIVE_NEGEDGE |
1725 		DRM_BUS_FLAG_SYNC_DRIVE_NEGEDGE;
1726 	drm_connector_attach_encoder(&tc->connector, tc->bridge.encoder);
1727 
1728 	return 0;
1729 aux_unregister:
1730 	drm_dp_aux_unregister(&tc->aux);
1731 	return ret;
1732 }
1733 
1734 static void tc_edp_bridge_detach(struct drm_bridge *bridge)
1735 {
1736 	drm_dp_aux_unregister(&bridge_to_tc(bridge)->aux);
1737 }
1738 
1739 #define MAX_INPUT_SEL_FORMATS	1
1740 
1741 static u32 *
1742 tc_dpi_atomic_get_input_bus_fmts(struct drm_bridge *bridge,
1743 				 struct drm_bridge_state *bridge_state,
1744 				 struct drm_crtc_state *crtc_state,
1745 				 struct drm_connector_state *conn_state,
1746 				 u32 output_fmt,
1747 				 unsigned int *num_input_fmts)
1748 {
1749 	u32 *input_fmts;
1750 
1751 	*num_input_fmts = 0;
1752 
1753 	input_fmts = kcalloc(MAX_INPUT_SEL_FORMATS, sizeof(*input_fmts),
1754 			     GFP_KERNEL);
1755 	if (!input_fmts)
1756 		return NULL;
1757 
1758 	/* This is the DSI-end bus format */
1759 	input_fmts[0] = MEDIA_BUS_FMT_RGB888_1X24;
1760 	*num_input_fmts = 1;
1761 
1762 	return input_fmts;
1763 }
1764 
1765 static const struct drm_bridge_funcs tc_dpi_bridge_funcs = {
1766 	.attach = tc_dpi_bridge_attach,
1767 	.mode_valid = tc_dpi_mode_valid,
1768 	.mode_set = tc_bridge_mode_set,
1769 	.atomic_check = tc_dpi_atomic_check,
1770 	.atomic_enable = tc_dpi_bridge_atomic_enable,
1771 	.atomic_disable = tc_dpi_bridge_atomic_disable,
1772 	.atomic_duplicate_state = drm_atomic_helper_bridge_duplicate_state,
1773 	.atomic_destroy_state = drm_atomic_helper_bridge_destroy_state,
1774 	.atomic_reset = drm_atomic_helper_bridge_reset,
1775 	.atomic_get_input_bus_fmts = tc_dpi_atomic_get_input_bus_fmts,
1776 };
1777 
1778 static const struct drm_bridge_funcs tc_edp_bridge_funcs = {
1779 	.attach = tc_edp_bridge_attach,
1780 	.detach = tc_edp_bridge_detach,
1781 	.mode_valid = tc_edp_mode_valid,
1782 	.mode_set = tc_bridge_mode_set,
1783 	.atomic_check = tc_edp_atomic_check,
1784 	.atomic_enable = tc_edp_bridge_atomic_enable,
1785 	.atomic_disable = tc_edp_bridge_atomic_disable,
1786 	.mode_fixup = tc_bridge_mode_fixup,
1787 	.detect = tc_bridge_detect,
1788 	.get_edid = tc_get_edid,
1789 	.atomic_duplicate_state = drm_atomic_helper_bridge_duplicate_state,
1790 	.atomic_destroy_state = drm_atomic_helper_bridge_destroy_state,
1791 	.atomic_reset = drm_atomic_helper_bridge_reset,
1792 };
1793 
1794 static bool tc_readable_reg(struct device *dev, unsigned int reg)
1795 {
1796 	return reg != SYSCTRL;
1797 }
1798 
1799 static const struct regmap_range tc_volatile_ranges[] = {
1800 	regmap_reg_range(DP0_AUXWDATA(0), DP0_AUXSTATUS),
1801 	regmap_reg_range(DP0_LTSTAT, DP0_SNKLTCHGREQ),
1802 	regmap_reg_range(DP_PHY_CTRL, DP_PHY_CTRL),
1803 	regmap_reg_range(DP0_PLLCTRL, PXL_PLLCTRL),
1804 	regmap_reg_range(VFUEN0, VFUEN0),
1805 	regmap_reg_range(INTSTS_G, INTSTS_G),
1806 	regmap_reg_range(GPIOI, GPIOI),
1807 };
1808 
1809 static const struct regmap_access_table tc_volatile_table = {
1810 	.yes_ranges = tc_volatile_ranges,
1811 	.n_yes_ranges = ARRAY_SIZE(tc_volatile_ranges),
1812 };
1813 
1814 static bool tc_writeable_reg(struct device *dev, unsigned int reg)
1815 {
1816 	return (reg != TC_IDREG) &&
1817 	       (reg != DP0_LTSTAT) &&
1818 	       (reg != DP0_SNKLTCHGREQ);
1819 }
1820 
1821 static const struct regmap_config tc_regmap_config = {
1822 	.name = "tc358767",
1823 	.reg_bits = 16,
1824 	.val_bits = 32,
1825 	.reg_stride = 4,
1826 	.max_register = PLL_DBG,
1827 	.cache_type = REGCACHE_RBTREE,
1828 	.readable_reg = tc_readable_reg,
1829 	.volatile_table = &tc_volatile_table,
1830 	.writeable_reg = tc_writeable_reg,
1831 	.reg_format_endian = REGMAP_ENDIAN_BIG,
1832 	.val_format_endian = REGMAP_ENDIAN_LITTLE,
1833 };
1834 
1835 static irqreturn_t tc_irq_handler(int irq, void *arg)
1836 {
1837 	struct tc_data *tc = arg;
1838 	u32 val;
1839 	int r;
1840 
1841 	r = regmap_read(tc->regmap, INTSTS_G, &val);
1842 	if (r)
1843 		return IRQ_NONE;
1844 
1845 	if (!val)
1846 		return IRQ_NONE;
1847 
1848 	if (val & INT_SYSERR) {
1849 		u32 stat = 0;
1850 
1851 		regmap_read(tc->regmap, SYSSTAT, &stat);
1852 
1853 		dev_err(tc->dev, "syserr %x\n", stat);
1854 	}
1855 
1856 	if (tc->hpd_pin >= 0 && tc->bridge.dev) {
1857 		/*
1858 		 * H is triggered when the GPIO goes high.
1859 		 *
1860 		 * LC is triggered when the GPIO goes low and stays low for
1861 		 * the duration of LCNT
1862 		 */
1863 		bool h = val & INT_GPIO_H(tc->hpd_pin);
1864 		bool lc = val & INT_GPIO_LC(tc->hpd_pin);
1865 
1866 		dev_dbg(tc->dev, "GPIO%d: %s %s\n", tc->hpd_pin,
1867 			h ? "H" : "", lc ? "LC" : "");
1868 
1869 		if (h || lc)
1870 			drm_kms_helper_hotplug_event(tc->bridge.dev);
1871 	}
1872 
1873 	regmap_write(tc->regmap, INTSTS_G, val);
1874 
1875 	return IRQ_HANDLED;
1876 }
1877 
1878 static int tc_mipi_dsi_host_attach(struct tc_data *tc)
1879 {
1880 	struct device *dev = tc->dev;
1881 	struct device_node *host_node;
1882 	struct device_node *endpoint;
1883 	struct mipi_dsi_device *dsi;
1884 	struct mipi_dsi_host *host;
1885 	const struct mipi_dsi_device_info info = {
1886 		.type = "tc358767",
1887 		.channel = 0,
1888 		.node = NULL,
1889 	};
1890 	int dsi_lanes, ret;
1891 
1892 	endpoint = of_graph_get_endpoint_by_regs(dev->of_node, 0, -1);
1893 	dsi_lanes = drm_of_get_data_lanes_count(endpoint, 1, 4);
1894 	host_node = of_graph_get_remote_port_parent(endpoint);
1895 	host = of_find_mipi_dsi_host_by_node(host_node);
1896 	of_node_put(host_node);
1897 	of_node_put(endpoint);
1898 
1899 	if (!host)
1900 		return -EPROBE_DEFER;
1901 
1902 	if (dsi_lanes < 0)
1903 		return dsi_lanes;
1904 
1905 	dsi = mipi_dsi_device_register_full(host, &info);
1906 	if (IS_ERR(dsi))
1907 		return dev_err_probe(dev, PTR_ERR(dsi),
1908 				     "failed to create dsi device\n");
1909 
1910 	tc->dsi = dsi;
1911 
1912 	dsi->lanes = dsi_lanes;
1913 	dsi->format = MIPI_DSI_FMT_RGB888;
1914 	dsi->mode_flags = MIPI_DSI_MODE_VIDEO | MIPI_DSI_MODE_VIDEO_SYNC_PULSE;
1915 
1916 	ret = mipi_dsi_attach(dsi);
1917 	if (ret < 0) {
1918 		dev_err(dev, "failed to attach dsi to host: %d\n", ret);
1919 		return ret;
1920 	}
1921 
1922 	return 0;
1923 }
1924 
1925 static int tc_probe_dpi_bridge_endpoint(struct tc_data *tc)
1926 {
1927 	struct device *dev = tc->dev;
1928 	struct drm_panel *panel;
1929 	int ret;
1930 
1931 	/* port@1 is the DPI input/output port */
1932 	ret = drm_of_find_panel_or_bridge(dev->of_node, 1, 0, &panel, NULL);
1933 	if (ret && ret != -ENODEV)
1934 		return ret;
1935 
1936 	if (panel) {
1937 		struct drm_bridge *panel_bridge;
1938 
1939 		panel_bridge = devm_drm_panel_bridge_add(dev, panel);
1940 		if (IS_ERR(panel_bridge))
1941 			return PTR_ERR(panel_bridge);
1942 
1943 		tc->panel_bridge = panel_bridge;
1944 		tc->bridge.type = DRM_MODE_CONNECTOR_DPI;
1945 		tc->bridge.funcs = &tc_dpi_bridge_funcs;
1946 
1947 		return 0;
1948 	}
1949 
1950 	return ret;
1951 }
1952 
1953 static int tc_probe_edp_bridge_endpoint(struct tc_data *tc)
1954 {
1955 	struct device *dev = tc->dev;
1956 	struct drm_panel *panel;
1957 	int ret;
1958 
1959 	/* port@2 is the output port */
1960 	ret = drm_of_find_panel_or_bridge(dev->of_node, 2, 0, &panel, NULL);
1961 	if (ret && ret != -ENODEV)
1962 		return ret;
1963 
1964 	if (panel) {
1965 		struct drm_bridge *panel_bridge;
1966 
1967 		panel_bridge = devm_drm_panel_bridge_add(dev, panel);
1968 		if (IS_ERR(panel_bridge))
1969 			return PTR_ERR(panel_bridge);
1970 
1971 		tc->panel_bridge = panel_bridge;
1972 		tc->bridge.type = DRM_MODE_CONNECTOR_eDP;
1973 	} else {
1974 		tc->bridge.type = DRM_MODE_CONNECTOR_DisplayPort;
1975 	}
1976 
1977 	tc->bridge.funcs = &tc_edp_bridge_funcs;
1978 	if (tc->hpd_pin >= 0)
1979 		tc->bridge.ops |= DRM_BRIDGE_OP_DETECT;
1980 	tc->bridge.ops |= DRM_BRIDGE_OP_EDID;
1981 
1982 	return 0;
1983 }
1984 
1985 static int tc_probe_bridge_endpoint(struct tc_data *tc)
1986 {
1987 	struct device *dev = tc->dev;
1988 	struct of_endpoint endpoint;
1989 	struct device_node *node = NULL;
1990 	const u8 mode_dpi_to_edp = BIT(1) | BIT(2);
1991 	const u8 mode_dpi_to_dp = BIT(1);
1992 	const u8 mode_dsi_to_edp = BIT(0) | BIT(2);
1993 	const u8 mode_dsi_to_dp = BIT(0);
1994 	const u8 mode_dsi_to_dpi = BIT(0) | BIT(1);
1995 	u8 mode = 0;
1996 
1997 	/*
1998 	 * Determine bridge configuration.
1999 	 *
2000 	 * Port allocation:
2001 	 * port@0 - DSI input
2002 	 * port@1 - DPI input/output
2003 	 * port@2 - eDP output
2004 	 *
2005 	 * Possible connections:
2006 	 * DPI -> port@1 -> port@2 -> eDP :: [port@0 is not connected]
2007 	 * DSI -> port@0 -> port@2 -> eDP :: [port@1 is not connected]
2008 	 * DSI -> port@0 -> port@1 -> DPI :: [port@2 is not connected]
2009 	 */
2010 
2011 	for_each_endpoint_of_node(dev->of_node, node) {
2012 		of_graph_parse_endpoint(node, &endpoint);
2013 		if (endpoint.port > 2)
2014 			return -EINVAL;
2015 
2016 		mode |= BIT(endpoint.port);
2017 	}
2018 
2019 	if (mode == mode_dpi_to_edp || mode == mode_dpi_to_dp) {
2020 		tc->input_connector_dsi = false;
2021 		return tc_probe_edp_bridge_endpoint(tc);
2022 	} else if (mode == mode_dsi_to_dpi) {
2023 		tc->input_connector_dsi = true;
2024 		return tc_probe_dpi_bridge_endpoint(tc);
2025 	} else if (mode == mode_dsi_to_edp || mode == mode_dsi_to_dp) {
2026 		tc->input_connector_dsi = true;
2027 		return tc_probe_edp_bridge_endpoint(tc);
2028 	}
2029 
2030 	dev_warn(dev, "Invalid mode (0x%x) is not supported!\n", mode);
2031 
2032 	return -EINVAL;
2033 }
2034 
2035 static void tc_clk_disable(void *data)
2036 {
2037 	struct clk *refclk = data;
2038 
2039 	clk_disable_unprepare(refclk);
2040 }
2041 
2042 static int tc_probe(struct i2c_client *client, const struct i2c_device_id *id)
2043 {
2044 	struct device *dev = &client->dev;
2045 	struct tc_data *tc;
2046 	int ret;
2047 
2048 	tc = devm_kzalloc(dev, sizeof(*tc), GFP_KERNEL);
2049 	if (!tc)
2050 		return -ENOMEM;
2051 
2052 	tc->dev = dev;
2053 
2054 	ret = tc_probe_bridge_endpoint(tc);
2055 	if (ret)
2056 		return ret;
2057 
2058 	tc->refclk = devm_clk_get(dev, "ref");
2059 	if (IS_ERR(tc->refclk)) {
2060 		ret = PTR_ERR(tc->refclk);
2061 		dev_err(dev, "Failed to get refclk: %d\n", ret);
2062 		return ret;
2063 	}
2064 
2065 	ret = clk_prepare_enable(tc->refclk);
2066 	if (ret)
2067 		return ret;
2068 
2069 	ret = devm_add_action_or_reset(dev, tc_clk_disable, tc->refclk);
2070 	if (ret)
2071 		return ret;
2072 
2073 	/* tRSTW = 100 cycles , at 13 MHz that is ~7.69 us */
2074 	usleep_range(10, 15);
2075 
2076 	/* Shut down GPIO is optional */
2077 	tc->sd_gpio = devm_gpiod_get_optional(dev, "shutdown", GPIOD_OUT_HIGH);
2078 	if (IS_ERR(tc->sd_gpio))
2079 		return PTR_ERR(tc->sd_gpio);
2080 
2081 	if (tc->sd_gpio) {
2082 		gpiod_set_value_cansleep(tc->sd_gpio, 0);
2083 		usleep_range(5000, 10000);
2084 	}
2085 
2086 	/* Reset GPIO is optional */
2087 	tc->reset_gpio = devm_gpiod_get_optional(dev, "reset", GPIOD_OUT_LOW);
2088 	if (IS_ERR(tc->reset_gpio))
2089 		return PTR_ERR(tc->reset_gpio);
2090 
2091 	if (tc->reset_gpio) {
2092 		gpiod_set_value_cansleep(tc->reset_gpio, 1);
2093 		usleep_range(5000, 10000);
2094 	}
2095 
2096 	tc->regmap = devm_regmap_init_i2c(client, &tc_regmap_config);
2097 	if (IS_ERR(tc->regmap)) {
2098 		ret = PTR_ERR(tc->regmap);
2099 		dev_err(dev, "Failed to initialize regmap: %d\n", ret);
2100 		return ret;
2101 	}
2102 
2103 	ret = of_property_read_u32(dev->of_node, "toshiba,hpd-pin",
2104 				   &tc->hpd_pin);
2105 	if (ret) {
2106 		tc->hpd_pin = -ENODEV;
2107 	} else {
2108 		if (tc->hpd_pin < 0 || tc->hpd_pin > 1) {
2109 			dev_err(dev, "failed to parse HPD number\n");
2110 			return ret;
2111 		}
2112 	}
2113 
2114 	if (client->irq > 0) {
2115 		/* enable SysErr */
2116 		regmap_write(tc->regmap, INTCTL_G, INT_SYSERR);
2117 
2118 		ret = devm_request_threaded_irq(dev, client->irq,
2119 						NULL, tc_irq_handler,
2120 						IRQF_ONESHOT,
2121 						"tc358767-irq", tc);
2122 		if (ret) {
2123 			dev_err(dev, "failed to register dp interrupt\n");
2124 			return ret;
2125 		}
2126 
2127 		tc->have_irq = true;
2128 	}
2129 
2130 	ret = regmap_read(tc->regmap, TC_IDREG, &tc->rev);
2131 	if (ret) {
2132 		dev_err(tc->dev, "can not read device ID: %d\n", ret);
2133 		return ret;
2134 	}
2135 
2136 	if ((tc->rev != 0x6601) && (tc->rev != 0x6603)) {
2137 		dev_err(tc->dev, "invalid device ID: 0x%08x\n", tc->rev);
2138 		return -EINVAL;
2139 	}
2140 
2141 	tc->assr = (tc->rev == 0x6601); /* Enable ASSR for eDP panels */
2142 
2143 	if (!tc->reset_gpio) {
2144 		/*
2145 		 * If the reset pin isn't present, do a software reset. It isn't
2146 		 * as thorough as the hardware reset, as we can't reset the I2C
2147 		 * communication block for obvious reasons, but it's getting the
2148 		 * chip into a defined state.
2149 		 */
2150 		regmap_update_bits(tc->regmap, SYSRSTENB,
2151 				ENBLCD0 | ENBBM | ENBDSIRX | ENBREG | ENBHDCP,
2152 				0);
2153 		regmap_update_bits(tc->regmap, SYSRSTENB,
2154 				ENBLCD0 | ENBBM | ENBDSIRX | ENBREG | ENBHDCP,
2155 				ENBLCD0 | ENBBM | ENBDSIRX | ENBREG | ENBHDCP);
2156 		usleep_range(5000, 10000);
2157 	}
2158 
2159 	if (tc->hpd_pin >= 0) {
2160 		u32 lcnt_reg = tc->hpd_pin == 0 ? INT_GP0_LCNT : INT_GP1_LCNT;
2161 		u32 h_lc = INT_GPIO_H(tc->hpd_pin) | INT_GPIO_LC(tc->hpd_pin);
2162 
2163 		/* Set LCNT to 2ms */
2164 		regmap_write(tc->regmap, lcnt_reg,
2165 			     clk_get_rate(tc->refclk) * 2 / 1000);
2166 		/* We need the "alternate" mode for HPD */
2167 		regmap_write(tc->regmap, GPIOM, BIT(tc->hpd_pin));
2168 
2169 		if (tc->have_irq) {
2170 			/* enable H & LC */
2171 			regmap_update_bits(tc->regmap, INTCTL_G, h_lc, h_lc);
2172 		}
2173 	}
2174 
2175 	if (tc->bridge.type != DRM_MODE_CONNECTOR_DPI) { /* (e)DP output */
2176 		ret = tc_aux_link_setup(tc);
2177 		if (ret)
2178 			return ret;
2179 	}
2180 
2181 	tc->bridge.of_node = dev->of_node;
2182 	drm_bridge_add(&tc->bridge);
2183 
2184 	i2c_set_clientdata(client, tc);
2185 
2186 	if (tc->input_connector_dsi) {			/* DSI input */
2187 		ret = tc_mipi_dsi_host_attach(tc);
2188 		if (ret) {
2189 			drm_bridge_remove(&tc->bridge);
2190 			return ret;
2191 		}
2192 	}
2193 
2194 	return 0;
2195 }
2196 
2197 static int tc_remove(struct i2c_client *client)
2198 {
2199 	struct tc_data *tc = i2c_get_clientdata(client);
2200 
2201 	drm_bridge_remove(&tc->bridge);
2202 
2203 	return 0;
2204 }
2205 
2206 static const struct i2c_device_id tc358767_i2c_ids[] = {
2207 	{ "tc358767", 0 },
2208 	{ }
2209 };
2210 MODULE_DEVICE_TABLE(i2c, tc358767_i2c_ids);
2211 
2212 static const struct of_device_id tc358767_of_ids[] = {
2213 	{ .compatible = "toshiba,tc358767", },
2214 	{ }
2215 };
2216 MODULE_DEVICE_TABLE(of, tc358767_of_ids);
2217 
2218 static struct i2c_driver tc358767_driver = {
2219 	.driver = {
2220 		.name = "tc358767",
2221 		.of_match_table = tc358767_of_ids,
2222 	},
2223 	.id_table = tc358767_i2c_ids,
2224 	.probe = tc_probe,
2225 	.remove	= tc_remove,
2226 };
2227 module_i2c_driver(tc358767_driver);
2228 
2229 MODULE_AUTHOR("Andrey Gusakov <andrey.gusakov@cogentembedded.com>");
2230 MODULE_DESCRIPTION("tc358767 eDP encoder driver");
2231 MODULE_LICENSE("GPL");
2232