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