xref: /linux/drivers/gpu/drm/bridge/ti-sn65dsi86.c (revision ed531feda7852de0aa702fbe3d23a0f743ccc77b)
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/atomic.h>
8 #include <linux/auxiliary_bus.h>
9 #include <linux/bitfield.h>
10 #include <linux/bits.h>
11 #include <linux/clk.h>
12 #include <linux/debugfs.h>
13 #include <linux/gpio/consumer.h>
14 #include <linux/gpio/driver.h>
15 #include <linux/i2c.h>
16 #include <linux/iopoll.h>
17 #include <linux/module.h>
18 #include <linux/of_graph.h>
19 #include <linux/pm_runtime.h>
20 #include <linux/pwm.h>
21 #include <linux/regmap.h>
22 #include <linux/regulator/consumer.h>
23 
24 #include <linux/unaligned.h>
25 
26 #include <drm/display/drm_dp_aux_bus.h>
27 #include <drm/display/drm_dp_helper.h>
28 #include <drm/drm_atomic.h>
29 #include <drm/drm_atomic_helper.h>
30 #include <drm/drm_bridge.h>
31 #include <drm/drm_bridge_connector.h>
32 #include <drm/drm_edid.h>
33 #include <drm/drm_mipi_dsi.h>
34 #include <drm/drm_of.h>
35 #include <drm/drm_print.h>
36 #include <drm/drm_probe_helper.h>
37 
38 #define SN_DEVICE_REV_REG			0x08
39 #define SN_DPPLL_SRC_REG			0x0A
40 #define  DPPLL_CLK_SRC_DSICLK			BIT(0)
41 #define  REFCLK_FREQ_MASK			GENMASK(3, 1)
42 #define  REFCLK_FREQ(x)				((x) << 1)
43 #define  DPPLL_SRC_DP_PLL_LOCK			BIT(7)
44 #define SN_PLL_ENABLE_REG			0x0D
45 #define SN_DSI_LANES_REG			0x10
46 #define  CHA_DSI_LANES_MASK			GENMASK(4, 3)
47 #define  CHA_DSI_LANES(x)			((x) << 3)
48 #define SN_DSIA_CLK_FREQ_REG			0x12
49 #define SN_CHA_ACTIVE_LINE_LENGTH_LOW_REG	0x20
50 #define SN_CHA_VERTICAL_DISPLAY_SIZE_LOW_REG	0x24
51 #define SN_CHA_HSYNC_PULSE_WIDTH_LOW_REG	0x2C
52 #define SN_CHA_HSYNC_PULSE_WIDTH_HIGH_REG	0x2D
53 #define  CHA_HSYNC_POLARITY			BIT(7)
54 #define SN_CHA_VSYNC_PULSE_WIDTH_LOW_REG	0x30
55 #define SN_CHA_VSYNC_PULSE_WIDTH_HIGH_REG	0x31
56 #define  CHA_VSYNC_POLARITY			BIT(7)
57 #define SN_CHA_HORIZONTAL_BACK_PORCH_REG	0x34
58 #define SN_CHA_VERTICAL_BACK_PORCH_REG		0x36
59 #define SN_CHA_HORIZONTAL_FRONT_PORCH_REG	0x38
60 #define SN_CHA_VERTICAL_FRONT_PORCH_REG		0x3A
61 #define SN_LN_ASSIGN_REG			0x59
62 #define  LN_ASSIGN_WIDTH			2
63 #define SN_ENH_FRAME_REG			0x5A
64 #define  VSTREAM_ENABLE				BIT(3)
65 #define  LN_POLRS_OFFSET			4
66 #define  LN_POLRS_MASK				0xf0
67 #define SN_DATA_FORMAT_REG			0x5B
68 #define  BPP_18_RGB				BIT(0)
69 #define SN_HPD_DISABLE_REG			0x5C
70 #define  HPD_DISABLE				BIT(0)
71 #define  HPD_DEBOUNCED_STATE			BIT(4)
72 #define SN_GPIO_IO_REG				0x5E
73 #define  SN_GPIO_INPUT_SHIFT			4
74 #define  SN_GPIO_OUTPUT_SHIFT			0
75 #define SN_GPIO_CTRL_REG			0x5F
76 #define  SN_GPIO_MUX_INPUT			0
77 #define  SN_GPIO_MUX_OUTPUT			1
78 #define  SN_GPIO_MUX_SPECIAL			2
79 #define  SN_GPIO_MUX_MASK			0x3
80 #define SN_AUX_WDATA_REG(x)			(0x64 + (x))
81 #define SN_AUX_ADDR_19_16_REG			0x74
82 #define SN_AUX_ADDR_15_8_REG			0x75
83 #define SN_AUX_ADDR_7_0_REG			0x76
84 #define SN_AUX_ADDR_MASK			GENMASK(19, 0)
85 #define SN_AUX_LENGTH_REG			0x77
86 #define SN_AUX_CMD_REG				0x78
87 #define  AUX_CMD_SEND				BIT(0)
88 #define  AUX_CMD_REQ(x)				((x) << 4)
89 #define SN_AUX_RDATA_REG(x)			(0x79 + (x))
90 #define SN_SSC_CONFIG_REG			0x93
91 #define  DP_NUM_LANES_MASK			GENMASK(5, 4)
92 #define  DP_NUM_LANES(x)			((x) << 4)
93 #define SN_DATARATE_CONFIG_REG			0x94
94 #define  DP_DATARATE_MASK			GENMASK(7, 5)
95 #define  DP_DATARATE(x)				((x) << 5)
96 #define SN_TRAINING_SETTING_REG			0x95
97 #define  SCRAMBLE_DISABLE			BIT(4)
98 #define SN_ML_TX_MODE_REG			0x96
99 #define  ML_TX_MAIN_LINK_OFF			0
100 #define  ML_TX_NORMAL_MODE			BIT(0)
101 #define SN_PWM_PRE_DIV_REG			0xA0
102 #define SN_BACKLIGHT_SCALE_REG			0xA1
103 #define  BACKLIGHT_SCALE_MAX			0xFFFF
104 #define SN_BACKLIGHT_REG			0xA3
105 #define SN_PWM_EN_INV_REG			0xA5
106 #define  SN_PWM_INV_MASK			BIT(0)
107 #define  SN_PWM_EN_MASK				BIT(1)
108 #define SN_AUX_CMD_STATUS_REG			0xF4
109 #define  AUX_IRQ_STATUS_AUX_RPLY_TOUT		BIT(3)
110 #define  AUX_IRQ_STATUS_AUX_SHORT		BIT(5)
111 #define  AUX_IRQ_STATUS_NAT_I2C_FAIL		BIT(6)
112 
113 #define MIN_DSI_CLK_FREQ_MHZ	40
114 
115 /* fudge factor required to account for 8b/10b encoding */
116 #define DP_CLK_FUDGE_NUM	10
117 #define DP_CLK_FUDGE_DEN	8
118 
119 /* Matches DP_AUX_MAX_PAYLOAD_BYTES (for now) */
120 #define SN_AUX_MAX_PAYLOAD_BYTES	16
121 
122 #define SN_REGULATOR_SUPPLY_NUM		4
123 
124 #define SN_MAX_DP_LANES			4
125 #define SN_NUM_GPIOS			4
126 #define SN_GPIO_PHYSICAL_OFFSET		1
127 
128 #define SN_LINK_TRAINING_TRIES		10
129 
130 #define SN_PWM_GPIO_IDX			3 /* 4th GPIO */
131 
132 /**
133  * struct ti_sn65dsi86 - Platform data for ti-sn65dsi86 driver.
134  * @bridge_aux:   AUX-bus sub device for MIPI-to-eDP bridge functionality.
135  * @gpio_aux:     AUX-bus sub device for GPIO controller functionality.
136  * @aux_aux:      AUX-bus sub device for eDP AUX channel functionality.
137  * @pwm_aux:      AUX-bus sub device for PWM controller functionality.
138  *
139  * @dev:          Pointer to the top level (i2c) device.
140  * @regmap:       Regmap for accessing i2c.
141  * @aux:          Our aux channel.
142  * @bridge:       Our bridge.
143  * @connector:    Our connector.
144  * @host_node:    Remote DSI node.
145  * @dsi:          Our MIPI DSI source.
146  * @refclk:       Our reference clock.
147  * @next_bridge:  The bridge on the eDP side.
148  * @enable_gpio:  The GPIO we toggle to enable the bridge.
149  * @supplies:     Data for bulk enabling/disabling our regulators.
150  * @dp_lanes:     Count of dp_lanes we're using.
151  * @ln_assign:    Value to program to the LN_ASSIGN register.
152  * @ln_polrs:     Value for the 4-bit LN_POLRS field of SN_ENH_FRAME_REG.
153  * @comms_enabled: If true then communication over the aux channel is enabled.
154  * @comms_mutex:   Protects modification of comms_enabled.
155  *
156  * @gchip:        If we expose our GPIOs, this is used.
157  * @gchip_output: A cache of whether we've set GPIOs to output.  This
158  *                serves double-duty of keeping track of the direction and
159  *                also keeping track of whether we've incremented the
160  *                pm_runtime reference count for this pin, which we do
161  *                whenever a pin is configured as an output.  This is a
162  *                bitmap so we can do atomic ops on it without an extra
163  *                lock so concurrent users of our 4 GPIOs don't stomp on
164  *                each other's read-modify-write.
165  *
166  * @pchip:        pwm_chip if the PWM is exposed.
167  * @pwm_enabled:  Used to track if the PWM signal is currently enabled.
168  * @pwm_pin_busy: Track if GPIO4 is currently requested for GPIO or PWM.
169  * @pwm_refclk_freq: Cache for the reference clock input to the PWM.
170  */
171 struct ti_sn65dsi86 {
172 	struct auxiliary_device		*bridge_aux;
173 	struct auxiliary_device		*gpio_aux;
174 	struct auxiliary_device		*aux_aux;
175 	struct auxiliary_device		*pwm_aux;
176 
177 	struct device			*dev;
178 	struct regmap			*regmap;
179 	struct drm_dp_aux		aux;
180 	struct drm_bridge		bridge;
181 	struct drm_connector		*connector;
182 	struct device_node		*host_node;
183 	struct mipi_dsi_device		*dsi;
184 	struct clk			*refclk;
185 	struct drm_bridge		*next_bridge;
186 	struct gpio_desc		*enable_gpio;
187 	struct regulator_bulk_data	supplies[SN_REGULATOR_SUPPLY_NUM];
188 	int				dp_lanes;
189 	u8				ln_assign;
190 	u8				ln_polrs;
191 	bool				comms_enabled;
192 	struct mutex			comms_mutex;
193 
194 #if defined(CONFIG_OF_GPIO)
195 	struct gpio_chip		gchip;
196 	DECLARE_BITMAP(gchip_output, SN_NUM_GPIOS);
197 #endif
198 #if IS_REACHABLE(CONFIG_PWM)
199 	struct pwm_chip			*pchip;
200 	bool				pwm_enabled;
201 	atomic_t			pwm_pin_busy;
202 #endif
203 	unsigned int			pwm_refclk_freq;
204 };
205 
206 static const struct regmap_range ti_sn65dsi86_volatile_ranges[] = {
207 	{ .range_min = 0, .range_max = 0xFF },
208 };
209 
210 static const struct regmap_access_table ti_sn_bridge_volatile_table = {
211 	.yes_ranges = ti_sn65dsi86_volatile_ranges,
212 	.n_yes_ranges = ARRAY_SIZE(ti_sn65dsi86_volatile_ranges),
213 };
214 
215 static const struct regmap_config ti_sn65dsi86_regmap_config = {
216 	.reg_bits = 8,
217 	.val_bits = 8,
218 	.volatile_table = &ti_sn_bridge_volatile_table,
219 	.cache_type = REGCACHE_NONE,
220 	.max_register = 0xFF,
221 };
222 
223 static int __maybe_unused ti_sn65dsi86_read_u16(struct ti_sn65dsi86 *pdata,
224 						unsigned int reg, u16 *val)
225 {
226 	u8 buf[2];
227 	int ret;
228 
229 	ret = regmap_bulk_read(pdata->regmap, reg, buf, ARRAY_SIZE(buf));
230 	if (ret)
231 		return ret;
232 
233 	*val = buf[0] | (buf[1] << 8);
234 
235 	return 0;
236 }
237 
238 static void ti_sn65dsi86_write_u16(struct ti_sn65dsi86 *pdata,
239 				   unsigned int reg, u16 val)
240 {
241 	u8 buf[2] = { val & 0xff, val >> 8 };
242 
243 	regmap_bulk_write(pdata->regmap, reg, buf, ARRAY_SIZE(buf));
244 }
245 
246 static u32 ti_sn_bridge_get_dsi_freq(struct ti_sn65dsi86 *pdata)
247 {
248 	u32 bit_rate_khz, clk_freq_khz;
249 	struct drm_display_mode *mode =
250 		&pdata->bridge.encoder->crtc->state->adjusted_mode;
251 
252 	bit_rate_khz = mode->clock *
253 			mipi_dsi_pixel_format_to_bpp(pdata->dsi->format);
254 	clk_freq_khz = bit_rate_khz / (pdata->dsi->lanes * 2);
255 
256 	return clk_freq_khz;
257 }
258 
259 /* clk frequencies supported by bridge in Hz in case derived from REFCLK pin */
260 static const u32 ti_sn_bridge_refclk_lut[] = {
261 	12000000,
262 	19200000,
263 	26000000,
264 	27000000,
265 	38400000,
266 };
267 
268 /* clk frequencies supported by bridge in Hz in case derived from DACP/N pin */
269 static const u32 ti_sn_bridge_dsiclk_lut[] = {
270 	468000000,
271 	384000000,
272 	416000000,
273 	486000000,
274 	460800000,
275 };
276 
277 static void ti_sn_bridge_set_refclk_freq(struct ti_sn65dsi86 *pdata)
278 {
279 	int i;
280 	u32 refclk_rate;
281 	const u32 *refclk_lut;
282 	size_t refclk_lut_size;
283 
284 	if (pdata->refclk) {
285 		refclk_rate = clk_get_rate(pdata->refclk);
286 		refclk_lut = ti_sn_bridge_refclk_lut;
287 		refclk_lut_size = ARRAY_SIZE(ti_sn_bridge_refclk_lut);
288 		clk_prepare_enable(pdata->refclk);
289 	} else {
290 		refclk_rate = ti_sn_bridge_get_dsi_freq(pdata) * 1000;
291 		refclk_lut = ti_sn_bridge_dsiclk_lut;
292 		refclk_lut_size = ARRAY_SIZE(ti_sn_bridge_dsiclk_lut);
293 	}
294 
295 	/* for i equals to refclk_lut_size means default frequency */
296 	for (i = 0; i < refclk_lut_size; i++)
297 		if (refclk_lut[i] == refclk_rate)
298 			break;
299 
300 	/* avoid buffer overflow and "1" is the default rate in the datasheet. */
301 	if (i >= refclk_lut_size)
302 		i = 1;
303 
304 	regmap_update_bits(pdata->regmap, SN_DPPLL_SRC_REG, REFCLK_FREQ_MASK,
305 			   REFCLK_FREQ(i));
306 
307 	/*
308 	 * The PWM refclk is based on the value written to SN_DPPLL_SRC_REG,
309 	 * regardless of its actual sourcing.
310 	 */
311 	pdata->pwm_refclk_freq = ti_sn_bridge_refclk_lut[i];
312 }
313 
314 static void ti_sn65dsi86_enable_comms(struct ti_sn65dsi86 *pdata)
315 {
316 	mutex_lock(&pdata->comms_mutex);
317 
318 	/* configure bridge ref_clk */
319 	ti_sn_bridge_set_refclk_freq(pdata);
320 
321 	/*
322 	 * HPD on this bridge chip is a bit useless.  This is an eDP bridge
323 	 * so the HPD is an internal signal that's only there to signal that
324 	 * the panel is done powering up.  ...but the bridge chip debounces
325 	 * this signal by between 100 ms and 400 ms (depending on process,
326 	 * voltage, and temperate--I measured it at about 200 ms).  One
327 	 * particular panel asserted HPD 84 ms after it was powered on meaning
328 	 * that we saw HPD 284 ms after power on.  ...but the same panel said
329 	 * that instead of looking at HPD you could just hardcode a delay of
330 	 * 200 ms.  We'll assume that the panel driver will have the hardcoded
331 	 * delay in its prepare and always disable HPD.
332 	 *
333 	 * If HPD somehow makes sense on some future panel we'll have to
334 	 * change this to be conditional on someone specifying that HPD should
335 	 * be used.
336 	 */
337 	regmap_update_bits(pdata->regmap, SN_HPD_DISABLE_REG, HPD_DISABLE,
338 			   HPD_DISABLE);
339 
340 	pdata->comms_enabled = true;
341 
342 	mutex_unlock(&pdata->comms_mutex);
343 }
344 
345 static void ti_sn65dsi86_disable_comms(struct ti_sn65dsi86 *pdata)
346 {
347 	mutex_lock(&pdata->comms_mutex);
348 
349 	pdata->comms_enabled = false;
350 	clk_disable_unprepare(pdata->refclk);
351 
352 	mutex_unlock(&pdata->comms_mutex);
353 }
354 
355 static int __maybe_unused ti_sn65dsi86_resume(struct device *dev)
356 {
357 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(dev);
358 	int ret;
359 
360 	ret = regulator_bulk_enable(SN_REGULATOR_SUPPLY_NUM, pdata->supplies);
361 	if (ret) {
362 		DRM_ERROR("failed to enable supplies %d\n", ret);
363 		return ret;
364 	}
365 
366 	/* td2: min 100 us after regulators before enabling the GPIO */
367 	usleep_range(100, 110);
368 
369 	gpiod_set_value_cansleep(pdata->enable_gpio, 1);
370 
371 	/*
372 	 * If we have a reference clock we can enable communication w/ the
373 	 * panel (including the aux channel) w/out any need for an input clock
374 	 * so we can do it in resume which lets us read the EDID before
375 	 * pre_enable(). Without a reference clock we need the MIPI reference
376 	 * clock so reading early doesn't work.
377 	 */
378 	if (pdata->refclk)
379 		ti_sn65dsi86_enable_comms(pdata);
380 
381 	return ret;
382 }
383 
384 static int __maybe_unused ti_sn65dsi86_suspend(struct device *dev)
385 {
386 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(dev);
387 	int ret;
388 
389 	if (pdata->refclk)
390 		ti_sn65dsi86_disable_comms(pdata);
391 
392 	gpiod_set_value_cansleep(pdata->enable_gpio, 0);
393 
394 	ret = regulator_bulk_disable(SN_REGULATOR_SUPPLY_NUM, pdata->supplies);
395 	if (ret)
396 		DRM_ERROR("failed to disable supplies %d\n", ret);
397 
398 	return ret;
399 }
400 
401 static const struct dev_pm_ops ti_sn65dsi86_pm_ops = {
402 	SET_RUNTIME_PM_OPS(ti_sn65dsi86_suspend, ti_sn65dsi86_resume, NULL)
403 	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
404 				pm_runtime_force_resume)
405 };
406 
407 static int status_show(struct seq_file *s, void *data)
408 {
409 	struct ti_sn65dsi86 *pdata = s->private;
410 	unsigned int reg, val;
411 
412 	seq_puts(s, "STATUS REGISTERS:\n");
413 
414 	pm_runtime_get_sync(pdata->dev);
415 
416 	/* IRQ Status Registers, see Table 31 in datasheet */
417 	for (reg = 0xf0; reg <= 0xf8; reg++) {
418 		regmap_read(pdata->regmap, reg, &val);
419 		seq_printf(s, "[0x%02x] = 0x%08x\n", reg, val);
420 	}
421 
422 	pm_runtime_put_autosuspend(pdata->dev);
423 
424 	return 0;
425 }
426 
427 DEFINE_SHOW_ATTRIBUTE(status);
428 
429 static void ti_sn65dsi86_debugfs_remove(void *data)
430 {
431 	debugfs_remove_recursive(data);
432 }
433 
434 static void ti_sn65dsi86_debugfs_init(struct ti_sn65dsi86 *pdata)
435 {
436 	struct device *dev = pdata->dev;
437 	struct dentry *debugfs;
438 	int ret;
439 
440 	debugfs = debugfs_create_dir(dev_name(dev), NULL);
441 
442 	/*
443 	 * We might get an error back if debugfs wasn't enabled in the kernel
444 	 * so let's just silently return upon failure.
445 	 */
446 	if (IS_ERR_OR_NULL(debugfs))
447 		return;
448 
449 	ret = devm_add_action_or_reset(dev, ti_sn65dsi86_debugfs_remove, debugfs);
450 	if (ret)
451 		return;
452 
453 	debugfs_create_file("status", 0600, debugfs, pdata, &status_fops);
454 }
455 
456 /* -----------------------------------------------------------------------------
457  * Auxiliary Devices (*not* AUX)
458  */
459 
460 static void ti_sn65dsi86_uninit_aux(void *data)
461 {
462 	auxiliary_device_uninit(data);
463 }
464 
465 static void ti_sn65dsi86_delete_aux(void *data)
466 {
467 	auxiliary_device_delete(data);
468 }
469 
470 static void ti_sn65dsi86_aux_device_release(struct device *dev)
471 {
472 	struct auxiliary_device *aux = container_of(dev, struct auxiliary_device, dev);
473 
474 	kfree(aux);
475 }
476 
477 static int ti_sn65dsi86_add_aux_device(struct ti_sn65dsi86 *pdata,
478 				       struct auxiliary_device **aux_out,
479 				       const char *name)
480 {
481 	struct device *dev = pdata->dev;
482 	const struct i2c_client *client = to_i2c_client(dev);
483 	struct auxiliary_device *aux;
484 	int ret;
485 
486 	aux = kzalloc(sizeof(*aux), GFP_KERNEL);
487 	if (!aux)
488 		return -ENOMEM;
489 
490 	aux->name = name;
491 	aux->id = (client->adapter->nr << 10) | client->addr;
492 	aux->dev.parent = dev;
493 	aux->dev.release = ti_sn65dsi86_aux_device_release;
494 	device_set_of_node_from_dev(&aux->dev, dev);
495 	ret = auxiliary_device_init(aux);
496 	if (ret) {
497 		kfree(aux);
498 		return ret;
499 	}
500 	ret = devm_add_action_or_reset(dev, ti_sn65dsi86_uninit_aux, aux);
501 	if (ret)
502 		return ret;
503 
504 	ret = auxiliary_device_add(aux);
505 	if (ret)
506 		return ret;
507 	ret = devm_add_action_or_reset(dev, ti_sn65dsi86_delete_aux, aux);
508 	if (!ret)
509 		*aux_out = aux;
510 
511 	return ret;
512 }
513 
514 /* -----------------------------------------------------------------------------
515  * AUX Adapter
516  */
517 
518 static struct ti_sn65dsi86 *aux_to_ti_sn65dsi86(struct drm_dp_aux *aux)
519 {
520 	return container_of(aux, struct ti_sn65dsi86, aux);
521 }
522 
523 static ssize_t ti_sn_aux_transfer(struct drm_dp_aux *aux,
524 				  struct drm_dp_aux_msg *msg)
525 {
526 	struct ti_sn65dsi86 *pdata = aux_to_ti_sn65dsi86(aux);
527 	u32 request = msg->request & ~(DP_AUX_I2C_MOT | DP_AUX_I2C_WRITE_STATUS_UPDATE);
528 	u32 request_val = AUX_CMD_REQ(msg->request);
529 	u8 *buf = msg->buffer;
530 	unsigned int len = msg->size;
531 	unsigned int short_len;
532 	unsigned int val;
533 	int ret;
534 	u8 addr_len[SN_AUX_LENGTH_REG + 1 - SN_AUX_ADDR_19_16_REG];
535 
536 	if (len > SN_AUX_MAX_PAYLOAD_BYTES)
537 		return -EINVAL;
538 
539 	pm_runtime_get_sync(pdata->dev);
540 	mutex_lock(&pdata->comms_mutex);
541 
542 	/*
543 	 * If someone tries to do a DDC over AUX transaction before pre_enable()
544 	 * on a device without a dedicated reference clock then we just can't
545 	 * do it. Fail right away. This prevents non-refclk users from reading
546 	 * the EDID before enabling the panel but such is life.
547 	 */
548 	if (!pdata->comms_enabled) {
549 		ret = -EIO;
550 		goto exit;
551 	}
552 
553 	switch (request) {
554 	case DP_AUX_NATIVE_WRITE:
555 	case DP_AUX_I2C_WRITE:
556 	case DP_AUX_NATIVE_READ:
557 	case DP_AUX_I2C_READ:
558 		regmap_write(pdata->regmap, SN_AUX_CMD_REG, request_val);
559 		/* Assume it's good */
560 		msg->reply = 0;
561 		break;
562 	default:
563 		ret = -EINVAL;
564 		goto exit;
565 	}
566 
567 	BUILD_BUG_ON(sizeof(addr_len) != sizeof(__be32));
568 	put_unaligned_be32((msg->address & SN_AUX_ADDR_MASK) << 8 | len,
569 			   addr_len);
570 	regmap_bulk_write(pdata->regmap, SN_AUX_ADDR_19_16_REG, addr_len,
571 			  ARRAY_SIZE(addr_len));
572 
573 	if (request == DP_AUX_NATIVE_WRITE || request == DP_AUX_I2C_WRITE)
574 		regmap_bulk_write(pdata->regmap, SN_AUX_WDATA_REG(0), buf, len);
575 
576 	/* Clear old status bits before start so we don't get confused */
577 	regmap_write(pdata->regmap, SN_AUX_CMD_STATUS_REG,
578 		     AUX_IRQ_STATUS_NAT_I2C_FAIL |
579 		     AUX_IRQ_STATUS_AUX_RPLY_TOUT |
580 		     AUX_IRQ_STATUS_AUX_SHORT);
581 
582 	regmap_write(pdata->regmap, SN_AUX_CMD_REG, request_val | AUX_CMD_SEND);
583 
584 	/* Zero delay loop because i2c transactions are slow already */
585 	ret = regmap_read_poll_timeout(pdata->regmap, SN_AUX_CMD_REG, val,
586 				       !(val & AUX_CMD_SEND), 0, 50 * 1000);
587 	if (ret)
588 		goto exit;
589 
590 	ret = regmap_read(pdata->regmap, SN_AUX_CMD_STATUS_REG, &val);
591 	if (ret)
592 		goto exit;
593 
594 	if (val & AUX_IRQ_STATUS_AUX_RPLY_TOUT) {
595 		/*
596 		 * The hardware tried the message seven times per the DP spec
597 		 * but it hit a timeout. We ignore defers here because they're
598 		 * handled in hardware.
599 		 */
600 		ret = -ETIMEDOUT;
601 		goto exit;
602 	}
603 
604 	if (val & AUX_IRQ_STATUS_AUX_SHORT) {
605 		ret = regmap_read(pdata->regmap, SN_AUX_LENGTH_REG, &short_len);
606 		len = min(len, short_len);
607 		if (ret)
608 			goto exit;
609 	} else if (val & AUX_IRQ_STATUS_NAT_I2C_FAIL) {
610 		switch (request) {
611 		case DP_AUX_I2C_WRITE:
612 		case DP_AUX_I2C_READ:
613 			msg->reply |= DP_AUX_I2C_REPLY_NACK;
614 			break;
615 		case DP_AUX_NATIVE_READ:
616 		case DP_AUX_NATIVE_WRITE:
617 			msg->reply |= DP_AUX_NATIVE_REPLY_NACK;
618 			break;
619 		}
620 		len = 0;
621 		goto exit;
622 	}
623 
624 	if (request != DP_AUX_NATIVE_WRITE && request != DP_AUX_I2C_WRITE && len != 0)
625 		ret = regmap_bulk_read(pdata->regmap, SN_AUX_RDATA_REG(0), buf, len);
626 
627 exit:
628 	mutex_unlock(&pdata->comms_mutex);
629 	pm_runtime_mark_last_busy(pdata->dev);
630 	pm_runtime_put_autosuspend(pdata->dev);
631 
632 	if (ret)
633 		return ret;
634 	return len;
635 }
636 
637 static int ti_sn_aux_wait_hpd_asserted(struct drm_dp_aux *aux, unsigned long wait_us)
638 {
639 	/*
640 	 * The HPD in this chip is a bit useless (See comment in
641 	 * ti_sn65dsi86_enable_comms) so if our driver is expected to wait
642 	 * for HPD, we just assume it's asserted after the wait_us delay.
643 	 *
644 	 * In case we are asked to wait forever (wait_us=0) take conservative
645 	 * 500ms delay.
646 	 */
647 	if (wait_us == 0)
648 		wait_us = 500000;
649 
650 	usleep_range(wait_us, wait_us + 1000);
651 
652 	return 0;
653 }
654 
655 static int ti_sn_aux_probe(struct auxiliary_device *adev,
656 			   const struct auxiliary_device_id *id)
657 {
658 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(adev->dev.parent);
659 	int ret;
660 
661 	pdata->aux.name = "ti-sn65dsi86-aux";
662 	pdata->aux.dev = &adev->dev;
663 	pdata->aux.transfer = ti_sn_aux_transfer;
664 	pdata->aux.wait_hpd_asserted = ti_sn_aux_wait_hpd_asserted;
665 	drm_dp_aux_init(&pdata->aux);
666 
667 	ret = devm_of_dp_aux_populate_ep_devices(&pdata->aux);
668 	if (ret)
669 		return ret;
670 
671 	/*
672 	 * The eDP to MIPI bridge parts don't work until the AUX channel is
673 	 * setup so we don't add it in the main driver probe, we add it now.
674 	 */
675 	return ti_sn65dsi86_add_aux_device(pdata, &pdata->bridge_aux, "bridge");
676 }
677 
678 static const struct auxiliary_device_id ti_sn_aux_id_table[] = {
679 	{ .name = "ti_sn65dsi86.aux", },
680 	{},
681 };
682 
683 static struct auxiliary_driver ti_sn_aux_driver = {
684 	.name = "aux",
685 	.probe = ti_sn_aux_probe,
686 	.id_table = ti_sn_aux_id_table,
687 };
688 
689 /*------------------------------------------------------------------------------
690  * DRM Bridge
691  */
692 
693 static struct ti_sn65dsi86 *bridge_to_ti_sn65dsi86(struct drm_bridge *bridge)
694 {
695 	return container_of(bridge, struct ti_sn65dsi86, bridge);
696 }
697 
698 static int ti_sn_attach_host(struct auxiliary_device *adev, struct ti_sn65dsi86 *pdata)
699 {
700 	int val;
701 	struct mipi_dsi_host *host;
702 	struct mipi_dsi_device *dsi;
703 	struct device *dev = pdata->dev;
704 	const struct mipi_dsi_device_info info = { .type = "ti_sn_bridge",
705 						   .channel = 0,
706 						   .node = NULL,
707 	};
708 
709 	host = of_find_mipi_dsi_host_by_node(pdata->host_node);
710 	if (!host)
711 		return -EPROBE_DEFER;
712 
713 	dsi = devm_mipi_dsi_device_register_full(&adev->dev, host, &info);
714 	if (IS_ERR(dsi))
715 		return PTR_ERR(dsi);
716 
717 	/* TODO: setting to 4 MIPI lanes always for now */
718 	dsi->lanes = 4;
719 	dsi->format = MIPI_DSI_FMT_RGB888;
720 	dsi->mode_flags = MIPI_DSI_MODE_VIDEO;
721 
722 	/* check if continuous dsi clock is required or not */
723 	pm_runtime_get_sync(dev);
724 	regmap_read(pdata->regmap, SN_DPPLL_SRC_REG, &val);
725 	pm_runtime_put_autosuspend(dev);
726 	if (!(val & DPPLL_CLK_SRC_DSICLK))
727 		dsi->mode_flags |= MIPI_DSI_CLOCK_NON_CONTINUOUS;
728 
729 	pdata->dsi = dsi;
730 
731 	return devm_mipi_dsi_attach(&adev->dev, dsi);
732 }
733 
734 static int ti_sn_bridge_attach(struct drm_bridge *bridge,
735 			       enum drm_bridge_attach_flags flags)
736 {
737 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
738 	int ret;
739 
740 	pdata->aux.drm_dev = bridge->dev;
741 	ret = drm_dp_aux_register(&pdata->aux);
742 	if (ret < 0) {
743 		drm_err(bridge->dev, "Failed to register DP AUX channel: %d\n", ret);
744 		return ret;
745 	}
746 
747 	/*
748 	 * Attach the next bridge.
749 	 * We never want the next bridge to *also* create a connector.
750 	 */
751 	ret = drm_bridge_attach(bridge->encoder, pdata->next_bridge,
752 				&pdata->bridge, flags | DRM_BRIDGE_ATTACH_NO_CONNECTOR);
753 	if (ret < 0)
754 		goto err_initted_aux;
755 
756 	if (flags & DRM_BRIDGE_ATTACH_NO_CONNECTOR)
757 		return 0;
758 
759 	pdata->connector = drm_bridge_connector_init(pdata->bridge.dev,
760 						     pdata->bridge.encoder);
761 	if (IS_ERR(pdata->connector)) {
762 		ret = PTR_ERR(pdata->connector);
763 		goto err_initted_aux;
764 	}
765 
766 	drm_connector_attach_encoder(pdata->connector, pdata->bridge.encoder);
767 
768 	return 0;
769 
770 err_initted_aux:
771 	drm_dp_aux_unregister(&pdata->aux);
772 	return ret;
773 }
774 
775 static void ti_sn_bridge_detach(struct drm_bridge *bridge)
776 {
777 	drm_dp_aux_unregister(&bridge_to_ti_sn65dsi86(bridge)->aux);
778 }
779 
780 static enum drm_mode_status
781 ti_sn_bridge_mode_valid(struct drm_bridge *bridge,
782 			const struct drm_display_info *info,
783 			const struct drm_display_mode *mode)
784 {
785 	/* maximum supported resolution is 4K at 60 fps */
786 	if (mode->clock > 594000)
787 		return MODE_CLOCK_HIGH;
788 
789 	/*
790 	 * The front and back porch registers are 8 bits, and pulse width
791 	 * registers are 15 bits, so reject any modes with larger periods.
792 	 */
793 
794 	if ((mode->hsync_start - mode->hdisplay) > 0xff)
795 		return MODE_HBLANK_WIDE;
796 
797 	if ((mode->vsync_start - mode->vdisplay) > 0xff)
798 		return MODE_VBLANK_WIDE;
799 
800 	if ((mode->hsync_end - mode->hsync_start) > 0x7fff)
801 		return MODE_HSYNC_WIDE;
802 
803 	if ((mode->vsync_end - mode->vsync_start) > 0x7fff)
804 		return MODE_VSYNC_WIDE;
805 
806 	if ((mode->htotal - mode->hsync_end) > 0xff)
807 		return MODE_HBLANK_WIDE;
808 
809 	if ((mode->vtotal - mode->vsync_end) > 0xff)
810 		return MODE_VBLANK_WIDE;
811 
812 	return MODE_OK;
813 }
814 
815 static void ti_sn_bridge_atomic_disable(struct drm_bridge *bridge,
816 					struct drm_atomic_state *state)
817 {
818 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
819 
820 	/* disable video stream */
821 	regmap_update_bits(pdata->regmap, SN_ENH_FRAME_REG, VSTREAM_ENABLE, 0);
822 }
823 
824 static void ti_sn_bridge_set_dsi_rate(struct ti_sn65dsi86 *pdata)
825 {
826 	unsigned int bit_rate_mhz, clk_freq_mhz;
827 	unsigned int val;
828 	struct drm_display_mode *mode =
829 		&pdata->bridge.encoder->crtc->state->adjusted_mode;
830 
831 	/* set DSIA clk frequency */
832 	bit_rate_mhz = (mode->clock / 1000) *
833 			mipi_dsi_pixel_format_to_bpp(pdata->dsi->format);
834 	clk_freq_mhz = bit_rate_mhz / (pdata->dsi->lanes * 2);
835 
836 	/* for each increment in val, frequency increases by 5MHz */
837 	val = (MIN_DSI_CLK_FREQ_MHZ / 5) +
838 		(((clk_freq_mhz - MIN_DSI_CLK_FREQ_MHZ) / 5) & 0xFF);
839 	regmap_write(pdata->regmap, SN_DSIA_CLK_FREQ_REG, val);
840 }
841 
842 static unsigned int ti_sn_bridge_get_bpp(struct drm_connector *connector)
843 {
844 	if (connector->display_info.bpc <= 6)
845 		return 18;
846 	else
847 		return 24;
848 }
849 
850 /*
851  * LUT index corresponds to register value and
852  * LUT values corresponds to dp data rate supported
853  * by the bridge in Mbps unit.
854  */
855 static const unsigned int ti_sn_bridge_dp_rate_lut[] = {
856 	0, 1620, 2160, 2430, 2700, 3240, 4320, 5400
857 };
858 
859 static int ti_sn_bridge_calc_min_dp_rate_idx(struct ti_sn65dsi86 *pdata, unsigned int bpp)
860 {
861 	unsigned int bit_rate_khz, dp_rate_mhz;
862 	unsigned int i;
863 	struct drm_display_mode *mode =
864 		&pdata->bridge.encoder->crtc->state->adjusted_mode;
865 
866 	/* Calculate minimum bit rate based on our pixel clock. */
867 	bit_rate_khz = mode->clock * bpp;
868 
869 	/* Calculate minimum DP data rate, taking 80% as per DP spec */
870 	dp_rate_mhz = DIV_ROUND_UP(bit_rate_khz * DP_CLK_FUDGE_NUM,
871 				   1000 * pdata->dp_lanes * DP_CLK_FUDGE_DEN);
872 
873 	for (i = 1; i < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut) - 1; i++)
874 		if (ti_sn_bridge_dp_rate_lut[i] >= dp_rate_mhz)
875 			break;
876 
877 	return i;
878 }
879 
880 static unsigned int ti_sn_bridge_read_valid_rates(struct ti_sn65dsi86 *pdata)
881 {
882 	unsigned int valid_rates = 0;
883 	unsigned int rate_per_200khz;
884 	unsigned int rate_mhz;
885 	u8 dpcd_val;
886 	int ret;
887 	int i, j;
888 
889 	ret = drm_dp_dpcd_readb(&pdata->aux, DP_EDP_DPCD_REV, &dpcd_val);
890 	if (ret != 1) {
891 		DRM_DEV_ERROR(pdata->dev,
892 			      "Can't read eDP rev (%d), assuming 1.1\n", ret);
893 		dpcd_val = DP_EDP_11;
894 	}
895 
896 	if (dpcd_val >= DP_EDP_14) {
897 		/* eDP 1.4 devices must provide a custom table */
898 		__le16 sink_rates[DP_MAX_SUPPORTED_RATES];
899 
900 		ret = drm_dp_dpcd_read(&pdata->aux, DP_SUPPORTED_LINK_RATES,
901 				       sink_rates, sizeof(sink_rates));
902 
903 		if (ret != sizeof(sink_rates)) {
904 			DRM_DEV_ERROR(pdata->dev,
905 				"Can't read supported rate table (%d)\n", ret);
906 
907 			/* By zeroing we'll fall back to DP_MAX_LINK_RATE. */
908 			memset(sink_rates, 0, sizeof(sink_rates));
909 		}
910 
911 		for (i = 0; i < ARRAY_SIZE(sink_rates); i++) {
912 			rate_per_200khz = le16_to_cpu(sink_rates[i]);
913 
914 			if (!rate_per_200khz)
915 				break;
916 
917 			rate_mhz = rate_per_200khz * 200 / 1000;
918 			for (j = 0;
919 			     j < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut);
920 			     j++) {
921 				if (ti_sn_bridge_dp_rate_lut[j] == rate_mhz)
922 					valid_rates |= BIT(j);
923 			}
924 		}
925 
926 		for (i = 0; i < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut); i++) {
927 			if (valid_rates & BIT(i))
928 				return valid_rates;
929 		}
930 		DRM_DEV_ERROR(pdata->dev,
931 			      "No matching eDP rates in table; falling back\n");
932 	}
933 
934 	/* On older versions best we can do is use DP_MAX_LINK_RATE */
935 	ret = drm_dp_dpcd_readb(&pdata->aux, DP_MAX_LINK_RATE, &dpcd_val);
936 	if (ret != 1) {
937 		DRM_DEV_ERROR(pdata->dev,
938 			      "Can't read max rate (%d); assuming 5.4 GHz\n",
939 			      ret);
940 		dpcd_val = DP_LINK_BW_5_4;
941 	}
942 
943 	switch (dpcd_val) {
944 	default:
945 		DRM_DEV_ERROR(pdata->dev,
946 			      "Unexpected max rate (%#x); assuming 5.4 GHz\n",
947 			      (int)dpcd_val);
948 		fallthrough;
949 	case DP_LINK_BW_5_4:
950 		valid_rates |= BIT(7);
951 		fallthrough;
952 	case DP_LINK_BW_2_7:
953 		valid_rates |= BIT(4);
954 		fallthrough;
955 	case DP_LINK_BW_1_62:
956 		valid_rates |= BIT(1);
957 		break;
958 	}
959 
960 	return valid_rates;
961 }
962 
963 static void ti_sn_bridge_set_video_timings(struct ti_sn65dsi86 *pdata)
964 {
965 	struct drm_display_mode *mode =
966 		&pdata->bridge.encoder->crtc->state->adjusted_mode;
967 	u8 hsync_polarity = 0, vsync_polarity = 0;
968 
969 	if (mode->flags & DRM_MODE_FLAG_NHSYNC)
970 		hsync_polarity = CHA_HSYNC_POLARITY;
971 	if (mode->flags & DRM_MODE_FLAG_NVSYNC)
972 		vsync_polarity = CHA_VSYNC_POLARITY;
973 
974 	ti_sn65dsi86_write_u16(pdata, SN_CHA_ACTIVE_LINE_LENGTH_LOW_REG,
975 			       mode->hdisplay);
976 	ti_sn65dsi86_write_u16(pdata, SN_CHA_VERTICAL_DISPLAY_SIZE_LOW_REG,
977 			       mode->vdisplay);
978 	regmap_write(pdata->regmap, SN_CHA_HSYNC_PULSE_WIDTH_LOW_REG,
979 		     (mode->hsync_end - mode->hsync_start) & 0xFF);
980 	regmap_write(pdata->regmap, SN_CHA_HSYNC_PULSE_WIDTH_HIGH_REG,
981 		     (((mode->hsync_end - mode->hsync_start) >> 8) & 0x7F) |
982 		     hsync_polarity);
983 	regmap_write(pdata->regmap, SN_CHA_VSYNC_PULSE_WIDTH_LOW_REG,
984 		     (mode->vsync_end - mode->vsync_start) & 0xFF);
985 	regmap_write(pdata->regmap, SN_CHA_VSYNC_PULSE_WIDTH_HIGH_REG,
986 		     (((mode->vsync_end - mode->vsync_start) >> 8) & 0x7F) |
987 		     vsync_polarity);
988 
989 	regmap_write(pdata->regmap, SN_CHA_HORIZONTAL_BACK_PORCH_REG,
990 		     (mode->htotal - mode->hsync_end) & 0xFF);
991 	regmap_write(pdata->regmap, SN_CHA_VERTICAL_BACK_PORCH_REG,
992 		     (mode->vtotal - mode->vsync_end) & 0xFF);
993 
994 	regmap_write(pdata->regmap, SN_CHA_HORIZONTAL_FRONT_PORCH_REG,
995 		     (mode->hsync_start - mode->hdisplay) & 0xFF);
996 	regmap_write(pdata->regmap, SN_CHA_VERTICAL_FRONT_PORCH_REG,
997 		     (mode->vsync_start - mode->vdisplay) & 0xFF);
998 
999 	usleep_range(10000, 10500); /* 10ms delay recommended by spec */
1000 }
1001 
1002 static unsigned int ti_sn_get_max_lanes(struct ti_sn65dsi86 *pdata)
1003 {
1004 	u8 data;
1005 	int ret;
1006 
1007 	ret = drm_dp_dpcd_readb(&pdata->aux, DP_MAX_LANE_COUNT, &data);
1008 	if (ret != 1) {
1009 		DRM_DEV_ERROR(pdata->dev,
1010 			      "Can't read lane count (%d); assuming 4\n", ret);
1011 		return 4;
1012 	}
1013 
1014 	return data & DP_LANE_COUNT_MASK;
1015 }
1016 
1017 static int ti_sn_link_training(struct ti_sn65dsi86 *pdata, int dp_rate_idx,
1018 			       const char **last_err_str)
1019 {
1020 	unsigned int val;
1021 	int ret;
1022 	int i;
1023 
1024 	/* set dp clk frequency value */
1025 	regmap_update_bits(pdata->regmap, SN_DATARATE_CONFIG_REG,
1026 			   DP_DATARATE_MASK, DP_DATARATE(dp_rate_idx));
1027 
1028 	/* enable DP PLL */
1029 	regmap_write(pdata->regmap, SN_PLL_ENABLE_REG, 1);
1030 
1031 	ret = regmap_read_poll_timeout(pdata->regmap, SN_DPPLL_SRC_REG, val,
1032 				       val & DPPLL_SRC_DP_PLL_LOCK, 1000,
1033 				       50 * 1000);
1034 	if (ret) {
1035 		*last_err_str = "DP_PLL_LOCK polling failed";
1036 		goto exit;
1037 	}
1038 
1039 	/*
1040 	 * We'll try to link train several times.  As part of link training
1041 	 * the bridge chip will write DP_SET_POWER_D0 to DP_SET_POWER.  If
1042 	 * the panel isn't ready quite it might respond NAK here which means
1043 	 * we need to try again.
1044 	 */
1045 	for (i = 0; i < SN_LINK_TRAINING_TRIES; i++) {
1046 		/* Semi auto link training mode */
1047 		regmap_write(pdata->regmap, SN_ML_TX_MODE_REG, 0x0A);
1048 		ret = regmap_read_poll_timeout(pdata->regmap, SN_ML_TX_MODE_REG, val,
1049 					       val == ML_TX_MAIN_LINK_OFF ||
1050 					       val == ML_TX_NORMAL_MODE, 1000,
1051 					       500 * 1000);
1052 		if (ret) {
1053 			*last_err_str = "Training complete polling failed";
1054 		} else if (val == ML_TX_MAIN_LINK_OFF) {
1055 			*last_err_str = "Link training failed, link is off";
1056 			ret = -EIO;
1057 			continue;
1058 		}
1059 
1060 		break;
1061 	}
1062 
1063 	/* If we saw quite a few retries, add a note about it */
1064 	if (!ret && i > SN_LINK_TRAINING_TRIES / 2)
1065 		DRM_DEV_INFO(pdata->dev, "Link training needed %d retries\n", i);
1066 
1067 exit:
1068 	/* Disable the PLL if we failed */
1069 	if (ret)
1070 		regmap_write(pdata->regmap, SN_PLL_ENABLE_REG, 0);
1071 
1072 	return ret;
1073 }
1074 
1075 static void ti_sn_bridge_atomic_enable(struct drm_bridge *bridge,
1076 				       struct drm_atomic_state *state)
1077 {
1078 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
1079 	struct drm_connector *connector;
1080 	const char *last_err_str = "No supported DP rate";
1081 	unsigned int valid_rates;
1082 	int dp_rate_idx;
1083 	unsigned int val;
1084 	int ret = -EINVAL;
1085 	int max_dp_lanes;
1086 	unsigned int bpp;
1087 
1088 	connector = drm_atomic_get_new_connector_for_encoder(state,
1089 							     bridge->encoder);
1090 	if (!connector) {
1091 		dev_err_ratelimited(pdata->dev, "Could not get the connector\n");
1092 		return;
1093 	}
1094 
1095 	max_dp_lanes = ti_sn_get_max_lanes(pdata);
1096 	pdata->dp_lanes = min(pdata->dp_lanes, max_dp_lanes);
1097 
1098 	/* DSI_A lane config */
1099 	val = CHA_DSI_LANES(SN_MAX_DP_LANES - pdata->dsi->lanes);
1100 	regmap_update_bits(pdata->regmap, SN_DSI_LANES_REG,
1101 			   CHA_DSI_LANES_MASK, val);
1102 
1103 	regmap_write(pdata->regmap, SN_LN_ASSIGN_REG, pdata->ln_assign);
1104 	regmap_update_bits(pdata->regmap, SN_ENH_FRAME_REG, LN_POLRS_MASK,
1105 			   pdata->ln_polrs << LN_POLRS_OFFSET);
1106 
1107 	/* set dsi clk frequency value */
1108 	ti_sn_bridge_set_dsi_rate(pdata);
1109 
1110 	/*
1111 	 * The SN65DSI86 only supports ASSR Display Authentication method and
1112 	 * this method is enabled for eDP panels. An eDP panel must support this
1113 	 * authentication method. We need to enable this method in the eDP panel
1114 	 * at DisplayPort address 0x0010A prior to link training.
1115 	 *
1116 	 * As only ASSR is supported by SN65DSI86, for full DisplayPort displays
1117 	 * we need to disable the scrambler.
1118 	 */
1119 	if (pdata->bridge.type == DRM_MODE_CONNECTOR_eDP) {
1120 		drm_dp_dpcd_writeb(&pdata->aux, DP_EDP_CONFIGURATION_SET,
1121 				   DP_ALTERNATE_SCRAMBLER_RESET_ENABLE);
1122 
1123 		regmap_update_bits(pdata->regmap, SN_TRAINING_SETTING_REG,
1124 				   SCRAMBLE_DISABLE, 0);
1125 	} else {
1126 		regmap_update_bits(pdata->regmap, SN_TRAINING_SETTING_REG,
1127 				   SCRAMBLE_DISABLE, SCRAMBLE_DISABLE);
1128 	}
1129 
1130 	bpp = ti_sn_bridge_get_bpp(connector);
1131 	/* Set the DP output format (18 bpp or 24 bpp) */
1132 	val = bpp == 18 ? BPP_18_RGB : 0;
1133 	regmap_update_bits(pdata->regmap, SN_DATA_FORMAT_REG, BPP_18_RGB, val);
1134 
1135 	/* DP lane config */
1136 	val = DP_NUM_LANES(min(pdata->dp_lanes, 3));
1137 	regmap_update_bits(pdata->regmap, SN_SSC_CONFIG_REG, DP_NUM_LANES_MASK,
1138 			   val);
1139 
1140 	valid_rates = ti_sn_bridge_read_valid_rates(pdata);
1141 
1142 	/* Train until we run out of rates */
1143 	for (dp_rate_idx = ti_sn_bridge_calc_min_dp_rate_idx(pdata, bpp);
1144 	     dp_rate_idx < ARRAY_SIZE(ti_sn_bridge_dp_rate_lut);
1145 	     dp_rate_idx++) {
1146 		if (!(valid_rates & BIT(dp_rate_idx)))
1147 			continue;
1148 
1149 		ret = ti_sn_link_training(pdata, dp_rate_idx, &last_err_str);
1150 		if (!ret)
1151 			break;
1152 	}
1153 	if (ret) {
1154 		DRM_DEV_ERROR(pdata->dev, "%s (%d)\n", last_err_str, ret);
1155 		return;
1156 	}
1157 
1158 	/* config video parameters */
1159 	ti_sn_bridge_set_video_timings(pdata);
1160 
1161 	/* enable video stream */
1162 	regmap_update_bits(pdata->regmap, SN_ENH_FRAME_REG, VSTREAM_ENABLE,
1163 			   VSTREAM_ENABLE);
1164 }
1165 
1166 static void ti_sn_bridge_atomic_pre_enable(struct drm_bridge *bridge,
1167 					   struct drm_atomic_state *state)
1168 {
1169 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
1170 
1171 	pm_runtime_get_sync(pdata->dev);
1172 
1173 	if (!pdata->refclk)
1174 		ti_sn65dsi86_enable_comms(pdata);
1175 
1176 	/* td7: min 100 us after enable before DSI data */
1177 	usleep_range(100, 110);
1178 }
1179 
1180 static void ti_sn_bridge_atomic_post_disable(struct drm_bridge *bridge,
1181 					     struct drm_atomic_state *state)
1182 {
1183 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
1184 
1185 	/* semi auto link training mode OFF */
1186 	regmap_write(pdata->regmap, SN_ML_TX_MODE_REG, 0);
1187 	/* Num lanes to 0 as per power sequencing in data sheet */
1188 	regmap_update_bits(pdata->regmap, SN_SSC_CONFIG_REG, DP_NUM_LANES_MASK, 0);
1189 	/* disable DP PLL */
1190 	regmap_write(pdata->regmap, SN_PLL_ENABLE_REG, 0);
1191 
1192 	if (!pdata->refclk)
1193 		ti_sn65dsi86_disable_comms(pdata);
1194 
1195 	pm_runtime_put_sync(pdata->dev);
1196 }
1197 
1198 static enum drm_connector_status ti_sn_bridge_detect(struct drm_bridge *bridge)
1199 {
1200 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
1201 	int val = 0;
1202 
1203 	pm_runtime_get_sync(pdata->dev);
1204 	regmap_read(pdata->regmap, SN_HPD_DISABLE_REG, &val);
1205 	pm_runtime_put_autosuspend(pdata->dev);
1206 
1207 	return val & HPD_DEBOUNCED_STATE ? connector_status_connected
1208 					 : connector_status_disconnected;
1209 }
1210 
1211 static const struct drm_edid *ti_sn_bridge_edid_read(struct drm_bridge *bridge,
1212 						     struct drm_connector *connector)
1213 {
1214 	struct ti_sn65dsi86 *pdata = bridge_to_ti_sn65dsi86(bridge);
1215 
1216 	return drm_edid_read_ddc(connector, &pdata->aux.ddc);
1217 }
1218 
1219 static const struct drm_bridge_funcs ti_sn_bridge_funcs = {
1220 	.attach = ti_sn_bridge_attach,
1221 	.detach = ti_sn_bridge_detach,
1222 	.mode_valid = ti_sn_bridge_mode_valid,
1223 	.edid_read = ti_sn_bridge_edid_read,
1224 	.detect = ti_sn_bridge_detect,
1225 	.atomic_pre_enable = ti_sn_bridge_atomic_pre_enable,
1226 	.atomic_enable = ti_sn_bridge_atomic_enable,
1227 	.atomic_disable = ti_sn_bridge_atomic_disable,
1228 	.atomic_post_disable = ti_sn_bridge_atomic_post_disable,
1229 	.atomic_reset = drm_atomic_helper_bridge_reset,
1230 	.atomic_duplicate_state = drm_atomic_helper_bridge_duplicate_state,
1231 	.atomic_destroy_state = drm_atomic_helper_bridge_destroy_state,
1232 };
1233 
1234 static void ti_sn_bridge_parse_lanes(struct ti_sn65dsi86 *pdata,
1235 				     struct device_node *np)
1236 {
1237 	u32 lane_assignments[SN_MAX_DP_LANES] = { 0, 1, 2, 3 };
1238 	u32 lane_polarities[SN_MAX_DP_LANES] = { };
1239 	struct device_node *endpoint;
1240 	u8 ln_assign = 0;
1241 	u8 ln_polrs = 0;
1242 	int dp_lanes;
1243 	int i;
1244 
1245 	/*
1246 	 * Read config from the device tree about lane remapping and lane
1247 	 * polarities.  These are optional and we assume identity map and
1248 	 * normal polarity if nothing is specified.  It's OK to specify just
1249 	 * data-lanes but not lane-polarities but not vice versa.
1250 	 *
1251 	 * Error checking is light (we just make sure we don't crash or
1252 	 * buffer overrun) and we assume dts is well formed and specifying
1253 	 * mappings that the hardware supports.
1254 	 */
1255 	endpoint = of_graph_get_endpoint_by_regs(np, 1, -1);
1256 	dp_lanes = drm_of_get_data_lanes_count(endpoint, 1, SN_MAX_DP_LANES);
1257 	if (dp_lanes > 0) {
1258 		of_property_read_u32_array(endpoint, "data-lanes",
1259 					   lane_assignments, dp_lanes);
1260 		of_property_read_u32_array(endpoint, "lane-polarities",
1261 					   lane_polarities, dp_lanes);
1262 	} else {
1263 		dp_lanes = SN_MAX_DP_LANES;
1264 	}
1265 	of_node_put(endpoint);
1266 
1267 	/*
1268 	 * Convert into register format.  Loop over all lanes even if
1269 	 * data-lanes had fewer elements so that we nicely initialize
1270 	 * the LN_ASSIGN register.
1271 	 */
1272 	for (i = SN_MAX_DP_LANES - 1; i >= 0; i--) {
1273 		ln_assign = ln_assign << LN_ASSIGN_WIDTH | lane_assignments[i];
1274 		ln_polrs = ln_polrs << 1 | lane_polarities[i];
1275 	}
1276 
1277 	/* Stash in our struct for when we power on */
1278 	pdata->dp_lanes = dp_lanes;
1279 	pdata->ln_assign = ln_assign;
1280 	pdata->ln_polrs = ln_polrs;
1281 }
1282 
1283 static int ti_sn_bridge_parse_dsi_host(struct ti_sn65dsi86 *pdata)
1284 {
1285 	struct device_node *np = pdata->dev->of_node;
1286 
1287 	pdata->host_node = of_graph_get_remote_node(np, 0, 0);
1288 
1289 	if (!pdata->host_node) {
1290 		DRM_ERROR("remote dsi host node not found\n");
1291 		return -ENODEV;
1292 	}
1293 
1294 	return 0;
1295 }
1296 
1297 static int ti_sn_bridge_probe(struct auxiliary_device *adev,
1298 			      const struct auxiliary_device_id *id)
1299 {
1300 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(adev->dev.parent);
1301 	struct device_node *np = pdata->dev->of_node;
1302 	int ret;
1303 
1304 	pdata->next_bridge = devm_drm_of_get_bridge(&adev->dev, np, 1, 0);
1305 	if (IS_ERR(pdata->next_bridge))
1306 		return dev_err_probe(&adev->dev, PTR_ERR(pdata->next_bridge),
1307 				     "failed to create panel bridge\n");
1308 
1309 	ti_sn_bridge_parse_lanes(pdata, np);
1310 
1311 	ret = ti_sn_bridge_parse_dsi_host(pdata);
1312 	if (ret)
1313 		return ret;
1314 
1315 	pdata->bridge.funcs = &ti_sn_bridge_funcs;
1316 	pdata->bridge.of_node = np;
1317 	pdata->bridge.type = pdata->next_bridge->type == DRM_MODE_CONNECTOR_DisplayPort
1318 			   ? DRM_MODE_CONNECTOR_DisplayPort : DRM_MODE_CONNECTOR_eDP;
1319 
1320 	if (pdata->bridge.type == DRM_MODE_CONNECTOR_DisplayPort)
1321 		pdata->bridge.ops = DRM_BRIDGE_OP_EDID | DRM_BRIDGE_OP_DETECT;
1322 
1323 	drm_bridge_add(&pdata->bridge);
1324 
1325 	ret = ti_sn_attach_host(adev, pdata);
1326 	if (ret) {
1327 		dev_err_probe(&adev->dev, ret, "failed to attach dsi host\n");
1328 		goto err_remove_bridge;
1329 	}
1330 
1331 	return 0;
1332 
1333 err_remove_bridge:
1334 	drm_bridge_remove(&pdata->bridge);
1335 	return ret;
1336 }
1337 
1338 static void ti_sn_bridge_remove(struct auxiliary_device *adev)
1339 {
1340 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(adev->dev.parent);
1341 
1342 	if (!pdata)
1343 		return;
1344 
1345 	drm_bridge_remove(&pdata->bridge);
1346 
1347 	of_node_put(pdata->host_node);
1348 }
1349 
1350 static const struct auxiliary_device_id ti_sn_bridge_id_table[] = {
1351 	{ .name = "ti_sn65dsi86.bridge", },
1352 	{},
1353 };
1354 
1355 static struct auxiliary_driver ti_sn_bridge_driver = {
1356 	.name = "bridge",
1357 	.probe = ti_sn_bridge_probe,
1358 	.remove = ti_sn_bridge_remove,
1359 	.id_table = ti_sn_bridge_id_table,
1360 };
1361 
1362 /* -----------------------------------------------------------------------------
1363  * PWM Controller
1364  */
1365 #if IS_REACHABLE(CONFIG_PWM)
1366 static int ti_sn_pwm_pin_request(struct ti_sn65dsi86 *pdata)
1367 {
1368 	return atomic_xchg(&pdata->pwm_pin_busy, 1) ? -EBUSY : 0;
1369 }
1370 
1371 static void ti_sn_pwm_pin_release(struct ti_sn65dsi86 *pdata)
1372 {
1373 	atomic_set(&pdata->pwm_pin_busy, 0);
1374 }
1375 
1376 static struct ti_sn65dsi86 *pwm_chip_to_ti_sn_bridge(struct pwm_chip *chip)
1377 {
1378 	return pwmchip_get_drvdata(chip);
1379 }
1380 
1381 static int ti_sn_pwm_request(struct pwm_chip *chip, struct pwm_device *pwm)
1382 {
1383 	struct ti_sn65dsi86 *pdata = pwm_chip_to_ti_sn_bridge(chip);
1384 
1385 	return ti_sn_pwm_pin_request(pdata);
1386 }
1387 
1388 static void ti_sn_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm)
1389 {
1390 	struct ti_sn65dsi86 *pdata = pwm_chip_to_ti_sn_bridge(chip);
1391 
1392 	ti_sn_pwm_pin_release(pdata);
1393 }
1394 
1395 /*
1396  * Limitations:
1397  * - The PWM signal is not driven when the chip is powered down, or in its
1398  *   reset state and the driver does not implement the "suspend state"
1399  *   described in the documentation. In order to save power, state->enabled is
1400  *   interpreted as denoting if the signal is expected to be valid, and is used
1401  *   to determine if the chip needs to be kept powered.
1402  * - Changing both period and duty_cycle is not done atomically, neither is the
1403  *   multi-byte register updates, so the output might briefly be undefined
1404  *   during update.
1405  */
1406 static int ti_sn_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm,
1407 			   const struct pwm_state *state)
1408 {
1409 	struct ti_sn65dsi86 *pdata = pwm_chip_to_ti_sn_bridge(chip);
1410 	unsigned int pwm_en_inv;
1411 	unsigned int backlight;
1412 	unsigned int pre_div;
1413 	unsigned int scale;
1414 	u64 period_max;
1415 	u64 period;
1416 	int ret;
1417 
1418 	if (!pdata->pwm_enabled) {
1419 		ret = pm_runtime_resume_and_get(pwmchip_parent(chip));
1420 		if (ret < 0)
1421 			return ret;
1422 	}
1423 
1424 	if (state->enabled) {
1425 		if (!pdata->pwm_enabled) {
1426 			/*
1427 			 * The chip might have been powered down while we
1428 			 * didn't hold a PM runtime reference, so mux in the
1429 			 * PWM function on the GPIO pin again.
1430 			 */
1431 			ret = regmap_update_bits(pdata->regmap, SN_GPIO_CTRL_REG,
1432 						 SN_GPIO_MUX_MASK << (2 * SN_PWM_GPIO_IDX),
1433 						 SN_GPIO_MUX_SPECIAL << (2 * SN_PWM_GPIO_IDX));
1434 			if (ret) {
1435 				dev_err(pwmchip_parent(chip), "failed to mux in PWM function\n");
1436 				goto out;
1437 			}
1438 		}
1439 
1440 		/*
1441 		 * Per the datasheet the PWM frequency is given by:
1442 		 *
1443 		 *                          REFCLK_FREQ
1444 		 *   PWM_FREQ = -----------------------------------
1445 		 *               PWM_PRE_DIV * BACKLIGHT_SCALE + 1
1446 		 *
1447 		 * However, after careful review the author is convinced that
1448 		 * the documentation has lost some parenthesis around
1449 		 * "BACKLIGHT_SCALE + 1".
1450 		 *
1451 		 * With the period T_pwm = 1/PWM_FREQ this can be written:
1452 		 *
1453 		 *   T_pwm * REFCLK_FREQ = PWM_PRE_DIV * (BACKLIGHT_SCALE + 1)
1454 		 *
1455 		 * In order to keep BACKLIGHT_SCALE within its 16 bits,
1456 		 * PWM_PRE_DIV must be:
1457 		 *
1458 		 *                     T_pwm * REFCLK_FREQ
1459 		 *   PWM_PRE_DIV >= -------------------------
1460 		 *                   BACKLIGHT_SCALE_MAX + 1
1461 		 *
1462 		 * To simplify the search and to favour higher resolution of
1463 		 * the duty cycle over accuracy of the period, the lowest
1464 		 * possible PWM_PRE_DIV is used. Finally the scale is
1465 		 * calculated as:
1466 		 *
1467 		 *                      T_pwm * REFCLK_FREQ
1468 		 *   BACKLIGHT_SCALE = ---------------------- - 1
1469 		 *                          PWM_PRE_DIV
1470 		 *
1471 		 * Here T_pwm is represented in seconds, so appropriate scaling
1472 		 * to nanoseconds is necessary.
1473 		 */
1474 
1475 		/* Minimum T_pwm is 1 / REFCLK_FREQ */
1476 		if (state->period <= NSEC_PER_SEC / pdata->pwm_refclk_freq) {
1477 			ret = -EINVAL;
1478 			goto out;
1479 		}
1480 
1481 		/*
1482 		 * Maximum T_pwm is 255 * (65535 + 1) / REFCLK_FREQ
1483 		 * Limit period to this to avoid overflows
1484 		 */
1485 		period_max = div_u64((u64)NSEC_PER_SEC * 255 * (65535 + 1),
1486 				     pdata->pwm_refclk_freq);
1487 		period = min(state->period, period_max);
1488 
1489 		pre_div = DIV64_U64_ROUND_UP(period * pdata->pwm_refclk_freq,
1490 					     (u64)NSEC_PER_SEC * (BACKLIGHT_SCALE_MAX + 1));
1491 		scale = div64_u64(period * pdata->pwm_refclk_freq, (u64)NSEC_PER_SEC * pre_div) - 1;
1492 
1493 		/*
1494 		 * The documentation has the duty ratio given as:
1495 		 *
1496 		 *     duty          BACKLIGHT
1497 		 *   ------- = ---------------------
1498 		 *    period    BACKLIGHT_SCALE + 1
1499 		 *
1500 		 * Solve for BACKLIGHT, substituting BACKLIGHT_SCALE according
1501 		 * to definition above and adjusting for nanosecond
1502 		 * representation of duty cycle gives us:
1503 		 */
1504 		backlight = div64_u64(state->duty_cycle * pdata->pwm_refclk_freq,
1505 				      (u64)NSEC_PER_SEC * pre_div);
1506 		if (backlight > scale)
1507 			backlight = scale;
1508 
1509 		ret = regmap_write(pdata->regmap, SN_PWM_PRE_DIV_REG, pre_div);
1510 		if (ret) {
1511 			dev_err(pwmchip_parent(chip), "failed to update PWM_PRE_DIV\n");
1512 			goto out;
1513 		}
1514 
1515 		ti_sn65dsi86_write_u16(pdata, SN_BACKLIGHT_SCALE_REG, scale);
1516 		ti_sn65dsi86_write_u16(pdata, SN_BACKLIGHT_REG, backlight);
1517 	}
1518 
1519 	pwm_en_inv = FIELD_PREP(SN_PWM_EN_MASK, state->enabled) |
1520 		     FIELD_PREP(SN_PWM_INV_MASK, state->polarity == PWM_POLARITY_INVERSED);
1521 	ret = regmap_write(pdata->regmap, SN_PWM_EN_INV_REG, pwm_en_inv);
1522 	if (ret) {
1523 		dev_err(pwmchip_parent(chip), "failed to update PWM_EN/PWM_INV\n");
1524 		goto out;
1525 	}
1526 
1527 	pdata->pwm_enabled = state->enabled;
1528 out:
1529 
1530 	if (!pdata->pwm_enabled)
1531 		pm_runtime_put_sync(pwmchip_parent(chip));
1532 
1533 	return ret;
1534 }
1535 
1536 static int ti_sn_pwm_get_state(struct pwm_chip *chip, struct pwm_device *pwm,
1537 			       struct pwm_state *state)
1538 {
1539 	struct ti_sn65dsi86 *pdata = pwm_chip_to_ti_sn_bridge(chip);
1540 	unsigned int pwm_en_inv;
1541 	unsigned int pre_div;
1542 	u16 backlight;
1543 	u16 scale;
1544 	int ret;
1545 
1546 	ret = regmap_read(pdata->regmap, SN_PWM_EN_INV_REG, &pwm_en_inv);
1547 	if (ret)
1548 		return ret;
1549 
1550 	ret = ti_sn65dsi86_read_u16(pdata, SN_BACKLIGHT_SCALE_REG, &scale);
1551 	if (ret)
1552 		return ret;
1553 
1554 	ret = ti_sn65dsi86_read_u16(pdata, SN_BACKLIGHT_REG, &backlight);
1555 	if (ret)
1556 		return ret;
1557 
1558 	ret = regmap_read(pdata->regmap, SN_PWM_PRE_DIV_REG, &pre_div);
1559 	if (ret)
1560 		return ret;
1561 
1562 	state->enabled = FIELD_GET(SN_PWM_EN_MASK, pwm_en_inv);
1563 	if (FIELD_GET(SN_PWM_INV_MASK, pwm_en_inv))
1564 		state->polarity = PWM_POLARITY_INVERSED;
1565 	else
1566 		state->polarity = PWM_POLARITY_NORMAL;
1567 
1568 	state->period = DIV_ROUND_UP_ULL((u64)NSEC_PER_SEC * pre_div * (scale + 1),
1569 					 pdata->pwm_refclk_freq);
1570 	state->duty_cycle = DIV_ROUND_UP_ULL((u64)NSEC_PER_SEC * pre_div * backlight,
1571 					     pdata->pwm_refclk_freq);
1572 
1573 	if (state->duty_cycle > state->period)
1574 		state->duty_cycle = state->period;
1575 
1576 	return 0;
1577 }
1578 
1579 static const struct pwm_ops ti_sn_pwm_ops = {
1580 	.request = ti_sn_pwm_request,
1581 	.free = ti_sn_pwm_free,
1582 	.apply = ti_sn_pwm_apply,
1583 	.get_state = ti_sn_pwm_get_state,
1584 };
1585 
1586 static int ti_sn_pwm_probe(struct auxiliary_device *adev,
1587 			   const struct auxiliary_device_id *id)
1588 {
1589 	struct pwm_chip *chip;
1590 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(adev->dev.parent);
1591 
1592 	pdata->pchip = chip = devm_pwmchip_alloc(&adev->dev, 1, 0);
1593 	if (IS_ERR(chip))
1594 		return PTR_ERR(chip);
1595 
1596 	pwmchip_set_drvdata(chip, pdata);
1597 
1598 	chip->ops = &ti_sn_pwm_ops;
1599 	chip->of_xlate = of_pwm_single_xlate;
1600 
1601 	devm_pm_runtime_enable(&adev->dev);
1602 
1603 	return pwmchip_add(chip);
1604 }
1605 
1606 static void ti_sn_pwm_remove(struct auxiliary_device *adev)
1607 {
1608 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(adev->dev.parent);
1609 
1610 	pwmchip_remove(pdata->pchip);
1611 
1612 	if (pdata->pwm_enabled)
1613 		pm_runtime_put_sync(&adev->dev);
1614 }
1615 
1616 static const struct auxiliary_device_id ti_sn_pwm_id_table[] = {
1617 	{ .name = "ti_sn65dsi86.pwm", },
1618 	{},
1619 };
1620 
1621 static struct auxiliary_driver ti_sn_pwm_driver = {
1622 	.name = "pwm",
1623 	.probe = ti_sn_pwm_probe,
1624 	.remove = ti_sn_pwm_remove,
1625 	.id_table = ti_sn_pwm_id_table,
1626 };
1627 
1628 static int __init ti_sn_pwm_register(void)
1629 {
1630 	return auxiliary_driver_register(&ti_sn_pwm_driver);
1631 }
1632 
1633 static void ti_sn_pwm_unregister(void)
1634 {
1635 	auxiliary_driver_unregister(&ti_sn_pwm_driver);
1636 }
1637 
1638 #else
1639 static inline int __maybe_unused ti_sn_pwm_pin_request(struct ti_sn65dsi86 *pdata) { return 0; }
1640 static inline void __maybe_unused ti_sn_pwm_pin_release(struct ti_sn65dsi86 *pdata) {}
1641 
1642 static inline int ti_sn_pwm_register(void) { return 0; }
1643 static inline void ti_sn_pwm_unregister(void) {}
1644 #endif
1645 
1646 /* -----------------------------------------------------------------------------
1647  * GPIO Controller
1648  */
1649 #if defined(CONFIG_OF_GPIO)
1650 
1651 static int tn_sn_bridge_of_xlate(struct gpio_chip *chip,
1652 				 const struct of_phandle_args *gpiospec,
1653 				 u32 *flags)
1654 {
1655 	if (WARN_ON(gpiospec->args_count < chip->of_gpio_n_cells))
1656 		return -EINVAL;
1657 
1658 	if (gpiospec->args[0] > chip->ngpio || gpiospec->args[0] < 1)
1659 		return -EINVAL;
1660 
1661 	if (flags)
1662 		*flags = gpiospec->args[1];
1663 
1664 	return gpiospec->args[0] - SN_GPIO_PHYSICAL_OFFSET;
1665 }
1666 
1667 static int ti_sn_bridge_gpio_get_direction(struct gpio_chip *chip,
1668 					   unsigned int offset)
1669 {
1670 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1671 
1672 	/*
1673 	 * We already have to keep track of the direction because we use
1674 	 * that to figure out whether we've powered the device.  We can
1675 	 * just return that rather than (maybe) powering up the device
1676 	 * to ask its direction.
1677 	 */
1678 	return test_bit(offset, pdata->gchip_output) ?
1679 		GPIO_LINE_DIRECTION_OUT : GPIO_LINE_DIRECTION_IN;
1680 }
1681 
1682 static int ti_sn_bridge_gpio_get(struct gpio_chip *chip, unsigned int offset)
1683 {
1684 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1685 	unsigned int val;
1686 	int ret;
1687 
1688 	/*
1689 	 * When the pin is an input we don't forcibly keep the bridge
1690 	 * powered--we just power it on to read the pin.  NOTE: part of
1691 	 * the reason this works is that the bridge defaults (when
1692 	 * powered back on) to all 4 GPIOs being configured as GPIO input.
1693 	 * Also note that if something else is keeping the chip powered the
1694 	 * pm_runtime functions are lightweight increments of a refcount.
1695 	 */
1696 	pm_runtime_get_sync(pdata->dev);
1697 	ret = regmap_read(pdata->regmap, SN_GPIO_IO_REG, &val);
1698 	pm_runtime_put_autosuspend(pdata->dev);
1699 
1700 	if (ret)
1701 		return ret;
1702 
1703 	return !!(val & BIT(SN_GPIO_INPUT_SHIFT + offset));
1704 }
1705 
1706 static void ti_sn_bridge_gpio_set(struct gpio_chip *chip, unsigned int offset,
1707 				  int val)
1708 {
1709 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1710 	int ret;
1711 
1712 	if (!test_bit(offset, pdata->gchip_output)) {
1713 		dev_err(pdata->dev, "Ignoring GPIO set while input\n");
1714 		return;
1715 	}
1716 
1717 	val &= 1;
1718 	ret = regmap_update_bits(pdata->regmap, SN_GPIO_IO_REG,
1719 				 BIT(SN_GPIO_OUTPUT_SHIFT + offset),
1720 				 val << (SN_GPIO_OUTPUT_SHIFT + offset));
1721 	if (ret)
1722 		dev_warn(pdata->dev,
1723 			 "Failed to set bridge GPIO %u: %d\n", offset, ret);
1724 }
1725 
1726 static int ti_sn_bridge_gpio_direction_input(struct gpio_chip *chip,
1727 					     unsigned int offset)
1728 {
1729 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1730 	int shift = offset * 2;
1731 	int ret;
1732 
1733 	if (!test_and_clear_bit(offset, pdata->gchip_output))
1734 		return 0;
1735 
1736 	ret = regmap_update_bits(pdata->regmap, SN_GPIO_CTRL_REG,
1737 				 SN_GPIO_MUX_MASK << shift,
1738 				 SN_GPIO_MUX_INPUT << shift);
1739 	if (ret) {
1740 		set_bit(offset, pdata->gchip_output);
1741 		return ret;
1742 	}
1743 
1744 	/*
1745 	 * NOTE: if nobody else is powering the device this may fully power
1746 	 * it off and when it comes back it will have lost all state, but
1747 	 * that's OK because the default is input and we're now an input.
1748 	 */
1749 	pm_runtime_put_autosuspend(pdata->dev);
1750 
1751 	return 0;
1752 }
1753 
1754 static int ti_sn_bridge_gpio_direction_output(struct gpio_chip *chip,
1755 					      unsigned int offset, int val)
1756 {
1757 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1758 	int shift = offset * 2;
1759 	int ret;
1760 
1761 	if (test_and_set_bit(offset, pdata->gchip_output))
1762 		return 0;
1763 
1764 	pm_runtime_get_sync(pdata->dev);
1765 
1766 	/* Set value first to avoid glitching */
1767 	ti_sn_bridge_gpio_set(chip, offset, val);
1768 
1769 	/* Set direction */
1770 	ret = regmap_update_bits(pdata->regmap, SN_GPIO_CTRL_REG,
1771 				 SN_GPIO_MUX_MASK << shift,
1772 				 SN_GPIO_MUX_OUTPUT << shift);
1773 	if (ret) {
1774 		clear_bit(offset, pdata->gchip_output);
1775 		pm_runtime_put_autosuspend(pdata->dev);
1776 	}
1777 
1778 	return ret;
1779 }
1780 
1781 static int ti_sn_bridge_gpio_request(struct gpio_chip *chip, unsigned int offset)
1782 {
1783 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1784 
1785 	if (offset == SN_PWM_GPIO_IDX)
1786 		return ti_sn_pwm_pin_request(pdata);
1787 
1788 	return 0;
1789 }
1790 
1791 static void ti_sn_bridge_gpio_free(struct gpio_chip *chip, unsigned int offset)
1792 {
1793 	struct ti_sn65dsi86 *pdata = gpiochip_get_data(chip);
1794 
1795 	/* We won't keep pm_runtime if we're input, so switch there on free */
1796 	ti_sn_bridge_gpio_direction_input(chip, offset);
1797 
1798 	if (offset == SN_PWM_GPIO_IDX)
1799 		ti_sn_pwm_pin_release(pdata);
1800 }
1801 
1802 static const char * const ti_sn_bridge_gpio_names[SN_NUM_GPIOS] = {
1803 	"GPIO1", "GPIO2", "GPIO3", "GPIO4"
1804 };
1805 
1806 static int ti_sn_gpio_probe(struct auxiliary_device *adev,
1807 			    const struct auxiliary_device_id *id)
1808 {
1809 	struct ti_sn65dsi86 *pdata = dev_get_drvdata(adev->dev.parent);
1810 	int ret;
1811 
1812 	/* Only init if someone is going to use us as a GPIO controller */
1813 	if (!of_property_read_bool(pdata->dev->of_node, "gpio-controller"))
1814 		return 0;
1815 
1816 	pdata->gchip.label = dev_name(pdata->dev);
1817 	pdata->gchip.parent = pdata->dev;
1818 	pdata->gchip.owner = THIS_MODULE;
1819 	pdata->gchip.of_xlate = tn_sn_bridge_of_xlate;
1820 	pdata->gchip.of_gpio_n_cells = 2;
1821 	pdata->gchip.request = ti_sn_bridge_gpio_request;
1822 	pdata->gchip.free = ti_sn_bridge_gpio_free;
1823 	pdata->gchip.get_direction = ti_sn_bridge_gpio_get_direction;
1824 	pdata->gchip.direction_input = ti_sn_bridge_gpio_direction_input;
1825 	pdata->gchip.direction_output = ti_sn_bridge_gpio_direction_output;
1826 	pdata->gchip.get = ti_sn_bridge_gpio_get;
1827 	pdata->gchip.set = ti_sn_bridge_gpio_set;
1828 	pdata->gchip.can_sleep = true;
1829 	pdata->gchip.names = ti_sn_bridge_gpio_names;
1830 	pdata->gchip.ngpio = SN_NUM_GPIOS;
1831 	pdata->gchip.base = -1;
1832 	ret = devm_gpiochip_add_data(&adev->dev, &pdata->gchip, pdata);
1833 	if (ret)
1834 		dev_err(pdata->dev, "can't add gpio chip\n");
1835 
1836 	return ret;
1837 }
1838 
1839 static const struct auxiliary_device_id ti_sn_gpio_id_table[] = {
1840 	{ .name = "ti_sn65dsi86.gpio", },
1841 	{},
1842 };
1843 
1844 MODULE_DEVICE_TABLE(auxiliary, ti_sn_gpio_id_table);
1845 
1846 static struct auxiliary_driver ti_sn_gpio_driver = {
1847 	.name = "gpio",
1848 	.probe = ti_sn_gpio_probe,
1849 	.id_table = ti_sn_gpio_id_table,
1850 };
1851 
1852 static int __init ti_sn_gpio_register(void)
1853 {
1854 	return auxiliary_driver_register(&ti_sn_gpio_driver);
1855 }
1856 
1857 static void ti_sn_gpio_unregister(void)
1858 {
1859 	auxiliary_driver_unregister(&ti_sn_gpio_driver);
1860 }
1861 
1862 #else
1863 
1864 static inline int ti_sn_gpio_register(void) { return 0; }
1865 static inline void ti_sn_gpio_unregister(void) {}
1866 
1867 #endif
1868 
1869 /* -----------------------------------------------------------------------------
1870  * Probe & Remove
1871  */
1872 
1873 static void ti_sn65dsi86_runtime_disable(void *data)
1874 {
1875 	pm_runtime_dont_use_autosuspend(data);
1876 	pm_runtime_disable(data);
1877 }
1878 
1879 static int ti_sn65dsi86_parse_regulators(struct ti_sn65dsi86 *pdata)
1880 {
1881 	unsigned int i;
1882 	const char * const ti_sn_bridge_supply_names[] = {
1883 		"vcca", "vcc", "vccio", "vpll",
1884 	};
1885 
1886 	for (i = 0; i < SN_REGULATOR_SUPPLY_NUM; i++)
1887 		pdata->supplies[i].supply = ti_sn_bridge_supply_names[i];
1888 
1889 	return devm_regulator_bulk_get(pdata->dev, SN_REGULATOR_SUPPLY_NUM,
1890 				       pdata->supplies);
1891 }
1892 
1893 static int ti_sn65dsi86_probe(struct i2c_client *client)
1894 {
1895 	struct device *dev = &client->dev;
1896 	struct ti_sn65dsi86 *pdata;
1897 	int ret;
1898 
1899 	if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
1900 		DRM_ERROR("device doesn't support I2C\n");
1901 		return -ENODEV;
1902 	}
1903 
1904 	pdata = devm_kzalloc(dev, sizeof(struct ti_sn65dsi86), GFP_KERNEL);
1905 	if (!pdata)
1906 		return -ENOMEM;
1907 	dev_set_drvdata(dev, pdata);
1908 	pdata->dev = dev;
1909 
1910 	mutex_init(&pdata->comms_mutex);
1911 
1912 	pdata->regmap = devm_regmap_init_i2c(client,
1913 					     &ti_sn65dsi86_regmap_config);
1914 	if (IS_ERR(pdata->regmap))
1915 		return dev_err_probe(dev, PTR_ERR(pdata->regmap),
1916 				     "regmap i2c init failed\n");
1917 
1918 	pdata->enable_gpio = devm_gpiod_get_optional(dev, "enable",
1919 						     GPIOD_OUT_LOW);
1920 	if (IS_ERR(pdata->enable_gpio))
1921 		return dev_err_probe(dev, PTR_ERR(pdata->enable_gpio),
1922 				     "failed to get enable gpio from DT\n");
1923 
1924 	ret = ti_sn65dsi86_parse_regulators(pdata);
1925 	if (ret)
1926 		return dev_err_probe(dev, ret, "failed to parse regulators\n");
1927 
1928 	pdata->refclk = devm_clk_get_optional(dev, "refclk");
1929 	if (IS_ERR(pdata->refclk))
1930 		return dev_err_probe(dev, PTR_ERR(pdata->refclk),
1931 				     "failed to get reference clock\n");
1932 
1933 	pm_runtime_enable(dev);
1934 	pm_runtime_set_autosuspend_delay(pdata->dev, 500);
1935 	pm_runtime_use_autosuspend(pdata->dev);
1936 	ret = devm_add_action_or_reset(dev, ti_sn65dsi86_runtime_disable, dev);
1937 	if (ret)
1938 		return ret;
1939 
1940 	ti_sn65dsi86_debugfs_init(pdata);
1941 
1942 	/*
1943 	 * Break ourselves up into a collection of aux devices. The only real
1944 	 * motiviation here is to solve the chicken-and-egg problem of probe
1945 	 * ordering. The bridge wants the panel to be there when it probes.
1946 	 * The panel wants its HPD GPIO (provided by sn65dsi86 on some boards)
1947 	 * when it probes. The panel and maybe backlight might want the DDC
1948 	 * bus or the pwm_chip. Having sub-devices allows the some sub devices
1949 	 * to finish probing even if others return -EPROBE_DEFER and gets us
1950 	 * around the problems.
1951 	 */
1952 
1953 	if (IS_ENABLED(CONFIG_OF_GPIO)) {
1954 		ret = ti_sn65dsi86_add_aux_device(pdata, &pdata->gpio_aux, "gpio");
1955 		if (ret)
1956 			return ret;
1957 	}
1958 
1959 	if (IS_REACHABLE(CONFIG_PWM)) {
1960 		ret = ti_sn65dsi86_add_aux_device(pdata, &pdata->pwm_aux, "pwm");
1961 		if (ret)
1962 			return ret;
1963 	}
1964 
1965 	/*
1966 	 * NOTE: At the end of the AUX channel probe we'll add the aux device
1967 	 * for the bridge. This is because the bridge can't be used until the
1968 	 * AUX channel is there and this is a very simple solution to the
1969 	 * dependency problem.
1970 	 */
1971 	return ti_sn65dsi86_add_aux_device(pdata, &pdata->aux_aux, "aux");
1972 }
1973 
1974 static const struct i2c_device_id ti_sn65dsi86_id[] = {
1975 	{ "ti,sn65dsi86" },
1976 	{}
1977 };
1978 MODULE_DEVICE_TABLE(i2c, ti_sn65dsi86_id);
1979 
1980 static const struct of_device_id ti_sn65dsi86_match_table[] = {
1981 	{.compatible = "ti,sn65dsi86"},
1982 	{},
1983 };
1984 MODULE_DEVICE_TABLE(of, ti_sn65dsi86_match_table);
1985 
1986 static struct i2c_driver ti_sn65dsi86_driver = {
1987 	.driver = {
1988 		.name = "ti_sn65dsi86",
1989 		.of_match_table = ti_sn65dsi86_match_table,
1990 		.pm = &ti_sn65dsi86_pm_ops,
1991 	},
1992 	.probe = ti_sn65dsi86_probe,
1993 	.id_table = ti_sn65dsi86_id,
1994 };
1995 
1996 static int __init ti_sn65dsi86_init(void)
1997 {
1998 	int ret;
1999 
2000 	ret = i2c_add_driver(&ti_sn65dsi86_driver);
2001 	if (ret)
2002 		return ret;
2003 
2004 	ret = ti_sn_gpio_register();
2005 	if (ret)
2006 		goto err_main_was_registered;
2007 
2008 	ret = ti_sn_pwm_register();
2009 	if (ret)
2010 		goto err_gpio_was_registered;
2011 
2012 	ret = auxiliary_driver_register(&ti_sn_aux_driver);
2013 	if (ret)
2014 		goto err_pwm_was_registered;
2015 
2016 	ret = auxiliary_driver_register(&ti_sn_bridge_driver);
2017 	if (ret)
2018 		goto err_aux_was_registered;
2019 
2020 	return 0;
2021 
2022 err_aux_was_registered:
2023 	auxiliary_driver_unregister(&ti_sn_aux_driver);
2024 err_pwm_was_registered:
2025 	ti_sn_pwm_unregister();
2026 err_gpio_was_registered:
2027 	ti_sn_gpio_unregister();
2028 err_main_was_registered:
2029 	i2c_del_driver(&ti_sn65dsi86_driver);
2030 
2031 	return ret;
2032 }
2033 module_init(ti_sn65dsi86_init);
2034 
2035 static void __exit ti_sn65dsi86_exit(void)
2036 {
2037 	auxiliary_driver_unregister(&ti_sn_bridge_driver);
2038 	auxiliary_driver_unregister(&ti_sn_aux_driver);
2039 	ti_sn_pwm_unregister();
2040 	ti_sn_gpio_unregister();
2041 	i2c_del_driver(&ti_sn65dsi86_driver);
2042 }
2043 module_exit(ti_sn65dsi86_exit);
2044 
2045 MODULE_AUTHOR("Sandeep Panda <spanda@codeaurora.org>");
2046 MODULE_DESCRIPTION("sn65dsi86 DSI to eDP bridge driver");
2047 MODULE_LICENSE("GPL v2");
2048