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