1// SPDX-License-Identifier: GPL-2.0-or-later
2/* linux/drivers/i2c/busses/i2c-s3c2410.c
3 *
4 * Copyright (C) 2004,2005,2009 Simtec Electronics
5 *	Ben Dooks <ben@simtec.co.uk>
6 *
7 * S3C2410 I2C Controller
8*/
9
10#include <linux/kernel.h>
11#include <linux/module.h>
12
13#include <linux/i2c.h>
14#include <linux/init.h>
15#include <linux/time.h>
16#include <linux/interrupt.h>
17#include <linux/delay.h>
18#include <linux/errno.h>
19#include <linux/err.h>
20#include <linux/platform_device.h>
21#include <linux/pm_runtime.h>
22#include <linux/clk.h>
23#include <linux/cpufreq.h>
24#include <linux/slab.h>
25#include <linux/io.h>
26#include <linux/of.h>
27#include <linux/gpio/consumer.h>
28#include <linux/pinctrl/consumer.h>
29#include <linux/mfd/syscon.h>
30#include <linux/regmap.h>
31
32#include <asm/irq.h>
33
34#include <linux/platform_data/i2c-s3c2410.h>
35
36/* see s3c2410x user guide, v1.1, section 9 (p447) for more info */
37
38#define S3C2410_IICCON			0x00
39#define S3C2410_IICSTAT			0x04
40#define S3C2410_IICADD			0x08
41#define S3C2410_IICDS			0x0C
42#define S3C2440_IICLC			0x10
43
44#define S3C2410_IICCON_ACKEN		(1 << 7)
45#define S3C2410_IICCON_TXDIV_16		(0 << 6)
46#define S3C2410_IICCON_TXDIV_512	(1 << 6)
47#define S3C2410_IICCON_IRQEN		(1 << 5)
48#define S3C2410_IICCON_IRQPEND		(1 << 4)
49#define S3C2410_IICCON_SCALE(x)		((x) & 0xf)
50#define S3C2410_IICCON_SCALEMASK	(0xf)
51
52#define S3C2410_IICSTAT_MASTER_RX	(2 << 6)
53#define S3C2410_IICSTAT_MASTER_TX	(3 << 6)
54#define S3C2410_IICSTAT_SLAVE_RX	(0 << 6)
55#define S3C2410_IICSTAT_SLAVE_TX	(1 << 6)
56#define S3C2410_IICSTAT_MODEMASK	(3 << 6)
57
58#define S3C2410_IICSTAT_START		(1 << 5)
59#define S3C2410_IICSTAT_BUSBUSY		(1 << 5)
60#define S3C2410_IICSTAT_TXRXEN		(1 << 4)
61#define S3C2410_IICSTAT_ARBITR		(1 << 3)
62#define S3C2410_IICSTAT_ASSLAVE		(1 << 2)
63#define S3C2410_IICSTAT_ADDR0		(1 << 1)
64#define S3C2410_IICSTAT_LASTBIT		(1 << 0)
65
66#define S3C2410_IICLC_SDA_DELAY0	(0 << 0)
67#define S3C2410_IICLC_SDA_DELAY5	(1 << 0)
68#define S3C2410_IICLC_SDA_DELAY10	(2 << 0)
69#define S3C2410_IICLC_SDA_DELAY15	(3 << 0)
70#define S3C2410_IICLC_SDA_DELAY_MASK	(3 << 0)
71
72#define S3C2410_IICLC_FILTER_ON		(1 << 2)
73
74/* Treat S3C2410 as baseline hardware, anything else is supported via quirks */
75#define QUIRK_S3C2440		(1 << 0)
76#define QUIRK_HDMIPHY		(1 << 1)
77#define QUIRK_NO_GPIO		(1 << 2)
78#define QUIRK_POLL		(1 << 3)
79
80/* Max time to wait for bus to become idle after a xfer (in us) */
81#define S3C2410_IDLE_TIMEOUT	5000
82
83/* Exynos5 Sysreg offset */
84#define EXYNOS5_SYS_I2C_CFG	0x0234
85
86/* i2c controller state */
87enum s3c24xx_i2c_state {
88	STATE_IDLE,
89	STATE_START,
90	STATE_READ,
91	STATE_WRITE,
92	STATE_STOP
93};
94
95struct s3c24xx_i2c {
96	wait_queue_head_t	wait;
97	kernel_ulong_t		quirks;
98
99	struct i2c_msg		*msg;
100	unsigned int		msg_num;
101	unsigned int		msg_idx;
102	unsigned int		msg_ptr;
103
104	unsigned int		tx_setup;
105	unsigned int		irq;
106
107	enum s3c24xx_i2c_state	state;
108	unsigned long		clkrate;
109
110	void __iomem		*regs;
111	struct clk		*clk;
112	struct device		*dev;
113	struct i2c_adapter	adap;
114
115	struct s3c2410_platform_i2c	*pdata;
116	struct gpio_desc	*gpios[2];
117	struct pinctrl          *pctrl;
118#if defined(CONFIG_ARM_S3C24XX_CPUFREQ)
119	struct notifier_block	freq_transition;
120#endif
121	struct regmap		*sysreg;
122	unsigned int		sys_i2c_cfg;
123};
124
125static const struct platform_device_id s3c24xx_driver_ids[] = {
126	{
127		.name		= "s3c2410-i2c",
128		.driver_data	= 0,
129	}, {
130		.name		= "s3c2440-i2c",
131		.driver_data	= QUIRK_S3C2440,
132	}, {
133		.name		= "s3c2440-hdmiphy-i2c",
134		.driver_data	= QUIRK_S3C2440 | QUIRK_HDMIPHY | QUIRK_NO_GPIO,
135	}, { },
136};
137MODULE_DEVICE_TABLE(platform, s3c24xx_driver_ids);
138
139static int i2c_s3c_irq_nextbyte(struct s3c24xx_i2c *i2c, unsigned long iicstat);
140
141#ifdef CONFIG_OF
142static const struct of_device_id s3c24xx_i2c_match[] = {
143	{ .compatible = "samsung,s3c2410-i2c", .data = (void *)0 },
144	{ .compatible = "samsung,s3c2440-i2c", .data = (void *)QUIRK_S3C2440 },
145	{ .compatible = "samsung,s3c2440-hdmiphy-i2c",
146	  .data = (void *)(QUIRK_S3C2440 | QUIRK_HDMIPHY | QUIRK_NO_GPIO) },
147	{ .compatible = "samsung,exynos5-sata-phy-i2c",
148	  .data = (void *)(QUIRK_S3C2440 | QUIRK_POLL | QUIRK_NO_GPIO) },
149	{},
150};
151MODULE_DEVICE_TABLE(of, s3c24xx_i2c_match);
152#endif
153
154/*
155 * Get controller type either from device tree or platform device variant.
156 */
157static inline kernel_ulong_t s3c24xx_get_device_quirks(struct platform_device *pdev)
158{
159	if (pdev->dev.of_node) {
160		const struct of_device_id *match;
161
162		match = of_match_node(s3c24xx_i2c_match, pdev->dev.of_node);
163		return (kernel_ulong_t)match->data;
164	}
165
166	return platform_get_device_id(pdev)->driver_data;
167}
168
169/*
170 * Complete the message and wake up the caller, using the given return code,
171 * or zero to mean ok.
172 */
173static inline void s3c24xx_i2c_master_complete(struct s3c24xx_i2c *i2c, int ret)
174{
175	dev_dbg(i2c->dev, "master_complete %d\n", ret);
176
177	i2c->msg_ptr = 0;
178	i2c->msg = NULL;
179	i2c->msg_idx++;
180	i2c->msg_num = 0;
181	if (ret)
182		i2c->msg_idx = ret;
183
184	if (!(i2c->quirks & QUIRK_POLL))
185		wake_up(&i2c->wait);
186}
187
188static inline void s3c24xx_i2c_disable_ack(struct s3c24xx_i2c *i2c)
189{
190	unsigned long tmp;
191
192	tmp = readl(i2c->regs + S3C2410_IICCON);
193	writel(tmp & ~S3C2410_IICCON_ACKEN, i2c->regs + S3C2410_IICCON);
194}
195
196static inline void s3c24xx_i2c_enable_ack(struct s3c24xx_i2c *i2c)
197{
198	unsigned long tmp;
199
200	tmp = readl(i2c->regs + S3C2410_IICCON);
201	writel(tmp | S3C2410_IICCON_ACKEN, i2c->regs + S3C2410_IICCON);
202}
203
204/* irq enable/disable functions */
205static inline void s3c24xx_i2c_disable_irq(struct s3c24xx_i2c *i2c)
206{
207	unsigned long tmp;
208
209	tmp = readl(i2c->regs + S3C2410_IICCON);
210	writel(tmp & ~S3C2410_IICCON_IRQEN, i2c->regs + S3C2410_IICCON);
211}
212
213static inline void s3c24xx_i2c_enable_irq(struct s3c24xx_i2c *i2c)
214{
215	unsigned long tmp;
216
217	tmp = readl(i2c->regs + S3C2410_IICCON);
218	writel(tmp | S3C2410_IICCON_IRQEN, i2c->regs + S3C2410_IICCON);
219}
220
221static bool is_ack(struct s3c24xx_i2c *i2c)
222{
223	int tries;
224
225	for (tries = 50; tries; --tries) {
226		unsigned long tmp = readl(i2c->regs + S3C2410_IICCON);
227
228		if (!(tmp & S3C2410_IICCON_ACKEN)) {
229			/*
230			 * Wait a bit for the bus to stabilize,
231			 * delay estimated experimentally.
232			 */
233			usleep_range(100, 200);
234			return true;
235		}
236		if (tmp & S3C2410_IICCON_IRQPEND) {
237			if (!(readl(i2c->regs + S3C2410_IICSTAT)
238				& S3C2410_IICSTAT_LASTBIT))
239				return true;
240		}
241		usleep_range(1000, 2000);
242	}
243	dev_err(i2c->dev, "ack was not received\n");
244	return false;
245}
246
247/*
248 * put the start of a message onto the bus
249 */
250static void s3c24xx_i2c_message_start(struct s3c24xx_i2c *i2c,
251				      struct i2c_msg *msg)
252{
253	unsigned int addr = (msg->addr & 0x7f) << 1;
254	unsigned long stat;
255	unsigned long iiccon;
256
257	stat = 0;
258	stat |=  S3C2410_IICSTAT_TXRXEN;
259
260	if (msg->flags & I2C_M_RD) {
261		stat |= S3C2410_IICSTAT_MASTER_RX;
262		addr |= 1;
263	} else
264		stat |= S3C2410_IICSTAT_MASTER_TX;
265
266	if (msg->flags & I2C_M_REV_DIR_ADDR)
267		addr ^= 1;
268
269	/* todo - check for whether ack wanted or not */
270	s3c24xx_i2c_enable_ack(i2c);
271
272	iiccon = readl(i2c->regs + S3C2410_IICCON);
273	writel(stat, i2c->regs + S3C2410_IICSTAT);
274
275	dev_dbg(i2c->dev, "START: %08lx to IICSTAT, %02x to DS\n", stat, addr);
276	writeb(addr, i2c->regs + S3C2410_IICDS);
277
278	/*
279	 * delay here to ensure the data byte has gotten onto the bus
280	 * before the transaction is started
281	 */
282	ndelay(i2c->tx_setup);
283
284	dev_dbg(i2c->dev, "iiccon, %08lx\n", iiccon);
285	writel(iiccon, i2c->regs + S3C2410_IICCON);
286
287	stat |= S3C2410_IICSTAT_START;
288	writel(stat, i2c->regs + S3C2410_IICSTAT);
289}
290
291static inline void s3c24xx_i2c_stop(struct s3c24xx_i2c *i2c, int ret)
292{
293	unsigned long iicstat = readl(i2c->regs + S3C2410_IICSTAT);
294
295	dev_dbg(i2c->dev, "STOP\n");
296
297	/*
298	 * The datasheet says that the STOP sequence should be:
299	 *  1) I2CSTAT.5 = 0	- Clear BUSY (or 'generate STOP')
300	 *  2) I2CCON.4 = 0	- Clear IRQPEND
301	 *  3) Wait until the stop condition takes effect.
302	 *  4*) I2CSTAT.4 = 0	- Clear TXRXEN
303	 *
304	 * Where, step "4*" is only for buses with the "HDMIPHY" quirk.
305	 *
306	 * However, after much experimentation, it appears that:
307	 * a) normal buses automatically clear BUSY and transition from
308	 *    Master->Slave when they complete generating a STOP condition.
309	 *    Therefore, step (3) can be done in doxfer() by polling I2CCON.4
310	 *    after starting the STOP generation here.
311	 * b) HDMIPHY bus does neither, so there is no way to do step 3.
312	 *    There is no indication when this bus has finished generating
313	 *    STOP.
314	 *
315	 * In fact, we have found that as soon as the IRQPEND bit is cleared in
316	 * step 2, the HDMIPHY bus generates the STOP condition, and then
317	 * immediately starts transferring another data byte, even though the
318	 * bus is supposedly stopped.  This is presumably because the bus is
319	 * still in "Master" mode, and its BUSY bit is still set.
320	 *
321	 * To avoid these extra post-STOP transactions on HDMI phy devices, we
322	 * just disable Serial Output on the bus (I2CSTAT.4 = 0) directly,
323	 * instead of first generating a proper STOP condition.  This should
324	 * float SDA & SCK terminating the transfer.  Subsequent transfers
325	 *  start with a proper START condition, and proceed normally.
326	 *
327	 * The HDMIPHY bus is an internal bus that always has exactly two
328	 * devices, the host as Master and the HDMIPHY device as the slave.
329	 * Skipping the STOP condition has been tested on this bus and works.
330	 */
331	if (i2c->quirks & QUIRK_HDMIPHY) {
332		/* Stop driving the I2C pins */
333		iicstat &= ~S3C2410_IICSTAT_TXRXEN;
334	} else {
335		/* stop the transfer */
336		iicstat &= ~S3C2410_IICSTAT_START;
337	}
338	writel(iicstat, i2c->regs + S3C2410_IICSTAT);
339
340	i2c->state = STATE_STOP;
341
342	s3c24xx_i2c_master_complete(i2c, ret);
343	s3c24xx_i2c_disable_irq(i2c);
344}
345
346/*
347 * helper functions to determine the current state in the set of
348 * messages we are sending
349 */
350
351/*
352 * returns TRUE if the current message is the last in the set
353 */
354static inline int is_lastmsg(struct s3c24xx_i2c *i2c)
355{
356	return i2c->msg_idx >= (i2c->msg_num - 1);
357}
358
359/*
360 * returns TRUE if we this is the last byte in the current message
361 */
362static inline int is_msglast(struct s3c24xx_i2c *i2c)
363{
364	/*
365	 * msg->len is always 1 for the first byte of smbus block read.
366	 * Actual length will be read from slave. More bytes will be
367	 * read according to the length then.
368	 */
369	if (i2c->msg->flags & I2C_M_RECV_LEN && i2c->msg->len == 1)
370		return 0;
371
372	return i2c->msg_ptr == i2c->msg->len-1;
373}
374
375/*
376 * returns TRUE if we reached the end of the current message
377 */
378static inline int is_msgend(struct s3c24xx_i2c *i2c)
379{
380	return i2c->msg_ptr >= i2c->msg->len;
381}
382
383/*
384 * process an interrupt and work out what to do
385 */
386static int i2c_s3c_irq_nextbyte(struct s3c24xx_i2c *i2c, unsigned long iicstat)
387{
388	unsigned long tmp;
389	unsigned char byte;
390	int ret = 0;
391
392	switch (i2c->state) {
393
394	case STATE_IDLE:
395		dev_err(i2c->dev, "%s: called in STATE_IDLE\n", __func__);
396		goto out;
397
398	case STATE_STOP:
399		dev_err(i2c->dev, "%s: called in STATE_STOP\n", __func__);
400		s3c24xx_i2c_disable_irq(i2c);
401		goto out_ack;
402
403	case STATE_START:
404		/*
405		 * last thing we did was send a start condition on the
406		 * bus, or started a new i2c message
407		 */
408		if (iicstat & S3C2410_IICSTAT_LASTBIT &&
409		    !(i2c->msg->flags & I2C_M_IGNORE_NAK)) {
410			/* ack was not received... */
411			dev_dbg(i2c->dev, "ack was not received\n");
412			s3c24xx_i2c_stop(i2c, -ENXIO);
413			goto out_ack;
414		}
415
416		if (i2c->msg->flags & I2C_M_RD)
417			i2c->state = STATE_READ;
418		else
419			i2c->state = STATE_WRITE;
420
421		/*
422		 * Terminate the transfer if there is nothing to do
423		 * as this is used by the i2c probe to find devices.
424		 */
425		if (is_lastmsg(i2c) && i2c->msg->len == 0) {
426			s3c24xx_i2c_stop(i2c, 0);
427			goto out_ack;
428		}
429
430		if (i2c->state == STATE_READ)
431			goto prepare_read;
432
433		/*
434		 * fall through to the write state, as we will need to
435		 * send a byte as well
436		 */
437		fallthrough;
438	case STATE_WRITE:
439		/*
440		 * we are writing data to the device... check for the
441		 * end of the message, and if so, work out what to do
442		 */
443		if (!(i2c->msg->flags & I2C_M_IGNORE_NAK)) {
444			if (iicstat & S3C2410_IICSTAT_LASTBIT) {
445				dev_dbg(i2c->dev, "WRITE: No Ack\n");
446
447				s3c24xx_i2c_stop(i2c, -ECONNREFUSED);
448				goto out_ack;
449			}
450		}
451
452 retry_write:
453
454		if (!is_msgend(i2c)) {
455			byte = i2c->msg->buf[i2c->msg_ptr++];
456			writeb(byte, i2c->regs + S3C2410_IICDS);
457
458			/*
459			 * delay after writing the byte to allow the
460			 * data setup time on the bus, as writing the
461			 * data to the register causes the first bit
462			 * to appear on SDA, and SCL will change as
463			 * soon as the interrupt is acknowledged
464			 */
465			ndelay(i2c->tx_setup);
466
467		} else if (!is_lastmsg(i2c)) {
468			/* we need to go to the next i2c message */
469
470			dev_dbg(i2c->dev, "WRITE: Next Message\n");
471
472			i2c->msg_ptr = 0;
473			i2c->msg_idx++;
474			i2c->msg++;
475
476			/* check to see if we need to do another message */
477			if (i2c->msg->flags & I2C_M_NOSTART) {
478
479				if (i2c->msg->flags & I2C_M_RD) {
480					/*
481					 * cannot do this, the controller
482					 * forces us to send a new START
483					 * when we change direction
484					 */
485					dev_dbg(i2c->dev,
486						"missing START before write->read\n");
487					s3c24xx_i2c_stop(i2c, -EINVAL);
488					break;
489				}
490
491				goto retry_write;
492			} else {
493				/* send the new start */
494				s3c24xx_i2c_message_start(i2c, i2c->msg);
495				i2c->state = STATE_START;
496			}
497
498		} else {
499			/* send stop */
500			s3c24xx_i2c_stop(i2c, 0);
501		}
502		break;
503
504	case STATE_READ:
505		/*
506		 * we have a byte of data in the data register, do
507		 * something with it, and then work out whether we are
508		 * going to do any more read/write
509		 */
510		byte = readb(i2c->regs + S3C2410_IICDS);
511		i2c->msg->buf[i2c->msg_ptr++] = byte;
512
513		/* Add actual length to read for smbus block read */
514		if (i2c->msg->flags & I2C_M_RECV_LEN && i2c->msg->len == 1)
515			i2c->msg->len += byte;
516 prepare_read:
517		if (is_msglast(i2c)) {
518			/* last byte of buffer */
519
520			if (is_lastmsg(i2c))
521				s3c24xx_i2c_disable_ack(i2c);
522
523		} else if (is_msgend(i2c)) {
524			/*
525			 * ok, we've read the entire buffer, see if there
526			 * is anything else we need to do
527			 */
528			if (is_lastmsg(i2c)) {
529				/* last message, send stop and complete */
530				dev_dbg(i2c->dev, "READ: Send Stop\n");
531
532				s3c24xx_i2c_stop(i2c, 0);
533			} else {
534				/* go to the next transfer */
535				dev_dbg(i2c->dev, "READ: Next Transfer\n");
536
537				i2c->msg_ptr = 0;
538				i2c->msg_idx++;
539				i2c->msg++;
540			}
541		}
542
543		break;
544	}
545
546	/* acknowlegde the IRQ and get back on with the work */
547
548 out_ack:
549	tmp = readl(i2c->regs + S3C2410_IICCON);
550	tmp &= ~S3C2410_IICCON_IRQPEND;
551	writel(tmp, i2c->regs + S3C2410_IICCON);
552 out:
553	return ret;
554}
555
556/*
557 * top level IRQ servicing routine
558 */
559static irqreturn_t s3c24xx_i2c_irq(int irqno, void *dev_id)
560{
561	struct s3c24xx_i2c *i2c = dev_id;
562	unsigned long status;
563	unsigned long tmp;
564
565	status = readl(i2c->regs + S3C2410_IICSTAT);
566
567	if (status & S3C2410_IICSTAT_ARBITR) {
568		/* deal with arbitration loss */
569		dev_err(i2c->dev, "deal with arbitration loss\n");
570	}
571
572	if (i2c->state == STATE_IDLE) {
573		dev_dbg(i2c->dev, "IRQ: error i2c->state == IDLE\n");
574
575		tmp = readl(i2c->regs + S3C2410_IICCON);
576		tmp &= ~S3C2410_IICCON_IRQPEND;
577		writel(tmp, i2c->regs +  S3C2410_IICCON);
578		goto out;
579	}
580
581	/*
582	 * pretty much this leaves us with the fact that we've
583	 * transmitted or received whatever byte we last sent
584	 */
585	i2c_s3c_irq_nextbyte(i2c, status);
586
587 out:
588	return IRQ_HANDLED;
589}
590
591/*
592 * Disable the bus so that we won't get any interrupts from now on, or try
593 * to drive any lines. This is the default state when we don't have
594 * anything to send/receive.
595 *
596 * If there is an event on the bus, or we have a pre-existing event at
597 * kernel boot time, we may not notice the event and the I2C controller
598 * will lock the bus with the I2C clock line low indefinitely.
599 */
600static inline void s3c24xx_i2c_disable_bus(struct s3c24xx_i2c *i2c)
601{
602	unsigned long tmp;
603
604	/* Stop driving the I2C pins */
605	tmp = readl(i2c->regs + S3C2410_IICSTAT);
606	tmp &= ~S3C2410_IICSTAT_TXRXEN;
607	writel(tmp, i2c->regs + S3C2410_IICSTAT);
608
609	/* We don't expect any interrupts now, and don't want send acks */
610	tmp = readl(i2c->regs + S3C2410_IICCON);
611	tmp &= ~(S3C2410_IICCON_IRQEN | S3C2410_IICCON_IRQPEND |
612		S3C2410_IICCON_ACKEN);
613	writel(tmp, i2c->regs + S3C2410_IICCON);
614}
615
616
617/*
618 * get the i2c bus for a master transaction
619 */
620static int s3c24xx_i2c_set_master(struct s3c24xx_i2c *i2c)
621{
622	unsigned long iicstat;
623	int timeout = 400;
624
625	while (timeout-- > 0) {
626		iicstat = readl(i2c->regs + S3C2410_IICSTAT);
627
628		if (!(iicstat & S3C2410_IICSTAT_BUSBUSY))
629			return 0;
630
631		msleep(1);
632	}
633
634	return -ETIMEDOUT;
635}
636
637/*
638 * wait for the i2c bus to become idle.
639 */
640static void s3c24xx_i2c_wait_idle(struct s3c24xx_i2c *i2c)
641{
642	unsigned long iicstat;
643	ktime_t start, now;
644	unsigned long delay;
645	int spins;
646
647	/* ensure the stop has been through the bus */
648
649	dev_dbg(i2c->dev, "waiting for bus idle\n");
650
651	start = now = ktime_get();
652
653	/*
654	 * Most of the time, the bus is already idle within a few usec of the
655	 * end of a transaction.  However, really slow i2c devices can stretch
656	 * the clock, delaying STOP generation.
657	 *
658	 * On slower SoCs this typically happens within a very small number of
659	 * instructions so busy wait briefly to avoid scheduling overhead.
660	 */
661	spins = 3;
662	iicstat = readl(i2c->regs + S3C2410_IICSTAT);
663	while ((iicstat & S3C2410_IICSTAT_START) && --spins) {
664		cpu_relax();
665		iicstat = readl(i2c->regs + S3C2410_IICSTAT);
666	}
667
668	/*
669	 * If we do get an appreciable delay as a compromise between idle
670	 * detection latency for the normal, fast case, and system load in the
671	 * slow device case, use an exponential back off in the polling loop,
672	 * up to 1/10th of the total timeout, then continue to poll at a
673	 * constant rate up to the timeout.
674	 */
675	delay = 1;
676	while ((iicstat & S3C2410_IICSTAT_START) &&
677	       ktime_us_delta(now, start) < S3C2410_IDLE_TIMEOUT) {
678		usleep_range(delay, 2 * delay);
679		if (delay < S3C2410_IDLE_TIMEOUT / 10)
680			delay <<= 1;
681		now = ktime_get();
682		iicstat = readl(i2c->regs + S3C2410_IICSTAT);
683	}
684
685	if (iicstat & S3C2410_IICSTAT_START)
686		dev_warn(i2c->dev, "timeout waiting for bus idle\n");
687}
688
689/*
690 * this starts an i2c transfer
691 */
692static int s3c24xx_i2c_doxfer(struct s3c24xx_i2c *i2c,
693			      struct i2c_msg *msgs, int num)
694{
695	unsigned long timeout = 0;
696	int ret;
697
698	ret = s3c24xx_i2c_set_master(i2c);
699	if (ret != 0) {
700		dev_err(i2c->dev, "cannot get bus (error %d)\n", ret);
701		ret = -EAGAIN;
702		goto out;
703	}
704
705	i2c->msg     = msgs;
706	i2c->msg_num = num;
707	i2c->msg_ptr = 0;
708	i2c->msg_idx = 0;
709	i2c->state   = STATE_START;
710
711	s3c24xx_i2c_enable_irq(i2c);
712	s3c24xx_i2c_message_start(i2c, msgs);
713
714	if (i2c->quirks & QUIRK_POLL) {
715		while ((i2c->msg_num != 0) && is_ack(i2c)) {
716			unsigned long stat = readl(i2c->regs + S3C2410_IICSTAT);
717
718			i2c_s3c_irq_nextbyte(i2c, stat);
719
720			stat = readl(i2c->regs + S3C2410_IICSTAT);
721			if (stat & S3C2410_IICSTAT_ARBITR)
722				dev_err(i2c->dev, "deal with arbitration loss\n");
723		}
724	} else {
725		timeout = wait_event_timeout(i2c->wait, i2c->msg_num == 0, HZ * 5);
726	}
727
728	ret = i2c->msg_idx;
729
730	/*
731	 * Having these next two as dev_err() makes life very
732	 * noisy when doing an i2cdetect
733	 */
734	if (timeout == 0)
735		dev_dbg(i2c->dev, "timeout\n");
736	else if (ret != num)
737		dev_dbg(i2c->dev, "incomplete xfer (%d)\n", ret);
738
739	/* For QUIRK_HDMIPHY, bus is already disabled */
740	if (i2c->quirks & QUIRK_HDMIPHY)
741		goto out;
742
743	s3c24xx_i2c_wait_idle(i2c);
744
745	s3c24xx_i2c_disable_bus(i2c);
746
747 out:
748	i2c->state = STATE_IDLE;
749
750	return ret;
751}
752
753/*
754 * first port of call from the i2c bus code when an message needs
755 * transferring across the i2c bus.
756 */
757static int s3c24xx_i2c_xfer(struct i2c_adapter *adap,
758			struct i2c_msg *msgs, int num)
759{
760	struct s3c24xx_i2c *i2c = (struct s3c24xx_i2c *)adap->algo_data;
761	int retry;
762	int ret;
763
764	ret = clk_enable(i2c->clk);
765	if (ret)
766		return ret;
767
768	for (retry = 0; retry < adap->retries; retry++) {
769
770		ret = s3c24xx_i2c_doxfer(i2c, msgs, num);
771
772		if (ret != -EAGAIN) {
773			clk_disable(i2c->clk);
774			return ret;
775		}
776
777		dev_dbg(i2c->dev, "Retrying transmission (%d)\n", retry);
778
779		udelay(100);
780	}
781
782	clk_disable(i2c->clk);
783	return -EREMOTEIO;
784}
785
786/* declare our i2c functionality */
787static u32 s3c24xx_i2c_func(struct i2c_adapter *adap)
788{
789	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL | I2C_FUNC_NOSTART |
790		I2C_FUNC_PROTOCOL_MANGLING;
791}
792
793/* i2c bus registration info */
794static const struct i2c_algorithm s3c24xx_i2c_algorithm = {
795	.master_xfer		= s3c24xx_i2c_xfer,
796	.functionality		= s3c24xx_i2c_func,
797};
798
799/*
800 * return the divisor settings for a given frequency
801 */
802static int s3c24xx_i2c_calcdivisor(unsigned long clkin, unsigned int wanted,
803				   unsigned int *div1, unsigned int *divs)
804{
805	unsigned int calc_divs = clkin / wanted;
806	unsigned int calc_div1;
807
808	if (calc_divs > (16*16))
809		calc_div1 = 512;
810	else
811		calc_div1 = 16;
812
813	calc_divs += calc_div1-1;
814	calc_divs /= calc_div1;
815
816	if (calc_divs == 0)
817		calc_divs = 1;
818	if (calc_divs > 17)
819		calc_divs = 17;
820
821	*divs = calc_divs;
822	*div1 = calc_div1;
823
824	return clkin / (calc_divs * calc_div1);
825}
826
827/*
828 * work out a divisor for the user requested frequency setting,
829 * either by the requested frequency, or scanning the acceptable
830 * range of frequencies until something is found
831 */
832static int s3c24xx_i2c_clockrate(struct s3c24xx_i2c *i2c, unsigned int *got)
833{
834	struct s3c2410_platform_i2c *pdata = i2c->pdata;
835	unsigned long clkin = clk_get_rate(i2c->clk);
836	unsigned int divs, div1;
837	unsigned long target_frequency;
838	u32 iiccon;
839	int freq;
840
841	i2c->clkrate = clkin;
842	clkin /= 1000;	/* clkin now in KHz */
843
844	dev_dbg(i2c->dev, "pdata desired frequency %lu\n", pdata->frequency);
845
846	target_frequency = pdata->frequency ?: I2C_MAX_STANDARD_MODE_FREQ;
847
848	target_frequency /= 1000; /* Target frequency now in KHz */
849
850	freq = s3c24xx_i2c_calcdivisor(clkin, target_frequency, &div1, &divs);
851
852	if (freq > target_frequency) {
853		dev_err(i2c->dev,
854			"Unable to achieve desired frequency %luKHz."	\
855			" Lowest achievable %dKHz\n", target_frequency, freq);
856		return -EINVAL;
857	}
858
859	*got = freq;
860
861	iiccon = readl(i2c->regs + S3C2410_IICCON);
862	iiccon &= ~(S3C2410_IICCON_SCALEMASK | S3C2410_IICCON_TXDIV_512);
863	iiccon |= (divs-1);
864
865	if (div1 == 512)
866		iiccon |= S3C2410_IICCON_TXDIV_512;
867
868	if (i2c->quirks & QUIRK_POLL)
869		iiccon |= S3C2410_IICCON_SCALE(2);
870
871	writel(iiccon, i2c->regs + S3C2410_IICCON);
872
873	if (i2c->quirks & QUIRK_S3C2440) {
874		unsigned long sda_delay;
875
876		if (pdata->sda_delay) {
877			sda_delay = clkin * pdata->sda_delay;
878			sda_delay = DIV_ROUND_UP(sda_delay, 1000000);
879			sda_delay = DIV_ROUND_UP(sda_delay, 5);
880			if (sda_delay > 3)
881				sda_delay = 3;
882			sda_delay |= S3C2410_IICLC_FILTER_ON;
883		} else
884			sda_delay = 0;
885
886		dev_dbg(i2c->dev, "IICLC=%08lx\n", sda_delay);
887		writel(sda_delay, i2c->regs + S3C2440_IICLC);
888	}
889
890	return 0;
891}
892
893#if defined(CONFIG_ARM_S3C24XX_CPUFREQ)
894
895#define freq_to_i2c(_n) container_of(_n, struct s3c24xx_i2c, freq_transition)
896
897static int s3c24xx_i2c_cpufreq_transition(struct notifier_block *nb,
898					  unsigned long val, void *data)
899{
900	struct s3c24xx_i2c *i2c = freq_to_i2c(nb);
901	unsigned int got;
902	int delta_f;
903	int ret;
904
905	delta_f = clk_get_rate(i2c->clk) - i2c->clkrate;
906
907	/* if we're post-change and the input clock has slowed down
908	 * or at pre-change and the clock is about to speed up, then
909	 * adjust our clock rate. <0 is slow, >0 speedup.
910	 */
911
912	if ((val == CPUFREQ_POSTCHANGE && delta_f < 0) ||
913	    (val == CPUFREQ_PRECHANGE && delta_f > 0)) {
914		i2c_lock_bus(&i2c->adap, I2C_LOCK_ROOT_ADAPTER);
915		ret = s3c24xx_i2c_clockrate(i2c, &got);
916		i2c_unlock_bus(&i2c->adap, I2C_LOCK_ROOT_ADAPTER);
917
918		if (ret < 0)
919			dev_err(i2c->dev, "cannot find frequency (%d)\n", ret);
920		else
921			dev_info(i2c->dev, "setting freq %d\n", got);
922	}
923
924	return 0;
925}
926
927static inline int s3c24xx_i2c_register_cpufreq(struct s3c24xx_i2c *i2c)
928{
929	i2c->freq_transition.notifier_call = s3c24xx_i2c_cpufreq_transition;
930
931	return cpufreq_register_notifier(&i2c->freq_transition,
932					 CPUFREQ_TRANSITION_NOTIFIER);
933}
934
935static inline void s3c24xx_i2c_deregister_cpufreq(struct s3c24xx_i2c *i2c)
936{
937	cpufreq_unregister_notifier(&i2c->freq_transition,
938				    CPUFREQ_TRANSITION_NOTIFIER);
939}
940
941#else
942static inline int s3c24xx_i2c_register_cpufreq(struct s3c24xx_i2c *i2c)
943{
944	return 0;
945}
946
947static inline void s3c24xx_i2c_deregister_cpufreq(struct s3c24xx_i2c *i2c)
948{
949}
950#endif
951
952#ifdef CONFIG_OF
953static int s3c24xx_i2c_parse_dt_gpio(struct s3c24xx_i2c *i2c)
954{
955	int i;
956
957	if (i2c->quirks & QUIRK_NO_GPIO)
958		return 0;
959
960	for (i = 0; i < 2; i++) {
961		i2c->gpios[i] = devm_gpiod_get_index(i2c->dev, NULL,
962						     i, GPIOD_ASIS);
963		if (IS_ERR(i2c->gpios[i])) {
964			dev_err(i2c->dev, "i2c gpio invalid at index %d\n", i);
965			return -EINVAL;
966		}
967	}
968	return 0;
969}
970
971#else
972static int s3c24xx_i2c_parse_dt_gpio(struct s3c24xx_i2c *i2c)
973{
974	return 0;
975}
976#endif
977
978/*
979 * initialise the controller, set the IO lines and frequency
980 */
981static int s3c24xx_i2c_init(struct s3c24xx_i2c *i2c)
982{
983	struct s3c2410_platform_i2c *pdata;
984	unsigned int freq;
985
986	/* get the plafrom data */
987
988	pdata = i2c->pdata;
989
990	/* write slave address */
991
992	writeb(pdata->slave_addr, i2c->regs + S3C2410_IICADD);
993
994	dev_info(i2c->dev, "slave address 0x%02x\n", pdata->slave_addr);
995
996	writel(0, i2c->regs + S3C2410_IICCON);
997	writel(0, i2c->regs + S3C2410_IICSTAT);
998
999	/* we need to work out the divisors for the clock... */
1000
1001	if (s3c24xx_i2c_clockrate(i2c, &freq) != 0) {
1002		dev_err(i2c->dev, "cannot meet bus frequency required\n");
1003		return -EINVAL;
1004	}
1005
1006	/* todo - check that the i2c lines aren't being dragged anywhere */
1007
1008	dev_info(i2c->dev, "bus frequency set to %d KHz\n", freq);
1009	dev_dbg(i2c->dev, "S3C2410_IICCON=0x%02x\n",
1010		readl(i2c->regs + S3C2410_IICCON));
1011
1012	return 0;
1013}
1014
1015#ifdef CONFIG_OF
1016/*
1017 * Parse the device tree node and retreive the platform data.
1018 */
1019static void
1020s3c24xx_i2c_parse_dt(struct device_node *np, struct s3c24xx_i2c *i2c)
1021{
1022	struct s3c2410_platform_i2c *pdata = i2c->pdata;
1023	int id;
1024
1025	if (!np)
1026		return;
1027
1028	pdata->bus_num = -1; /* i2c bus number is dynamically assigned */
1029	of_property_read_u32(np, "samsung,i2c-sda-delay", &pdata->sda_delay);
1030	of_property_read_u32(np, "samsung,i2c-slave-addr", &pdata->slave_addr);
1031	of_property_read_u32(np, "samsung,i2c-max-bus-freq",
1032				(u32 *)&pdata->frequency);
1033	/*
1034	 * Exynos5's legacy i2c controller and new high speed i2c
1035	 * controller have muxed interrupt sources. By default the
1036	 * interrupts for 4-channel HS-I2C controller are enabled.
1037	 * If nodes for first four channels of legacy i2c controller
1038	 * are available then re-configure the interrupts via the
1039	 * system register.
1040	 */
1041	id = of_alias_get_id(np, "i2c");
1042	i2c->sysreg = syscon_regmap_lookup_by_phandle(np,
1043			"samsung,sysreg-phandle");
1044	if (IS_ERR(i2c->sysreg))
1045		return;
1046
1047	regmap_update_bits(i2c->sysreg, EXYNOS5_SYS_I2C_CFG, BIT(id), 0);
1048}
1049#else
1050static void
1051s3c24xx_i2c_parse_dt(struct device_node *np, struct s3c24xx_i2c *i2c) { }
1052#endif
1053
1054static int s3c24xx_i2c_probe(struct platform_device *pdev)
1055{
1056	struct s3c24xx_i2c *i2c;
1057	struct s3c2410_platform_i2c *pdata = NULL;
1058	struct resource *res;
1059	int ret;
1060
1061	if (!pdev->dev.of_node) {
1062		pdata = dev_get_platdata(&pdev->dev);
1063		if (!pdata) {
1064			dev_err(&pdev->dev, "no platform data\n");
1065			return -EINVAL;
1066		}
1067	}
1068
1069	i2c = devm_kzalloc(&pdev->dev, sizeof(struct s3c24xx_i2c), GFP_KERNEL);
1070	if (!i2c)
1071		return -ENOMEM;
1072
1073	i2c->pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
1074	if (!i2c->pdata)
1075		return -ENOMEM;
1076
1077	i2c->quirks = s3c24xx_get_device_quirks(pdev);
1078	i2c->sysreg = ERR_PTR(-ENOENT);
1079	if (pdata)
1080		memcpy(i2c->pdata, pdata, sizeof(*pdata));
1081	else
1082		s3c24xx_i2c_parse_dt(pdev->dev.of_node, i2c);
1083
1084	strlcpy(i2c->adap.name, "s3c2410-i2c", sizeof(i2c->adap.name));
1085	i2c->adap.owner = THIS_MODULE;
1086	i2c->adap.algo = &s3c24xx_i2c_algorithm;
1087	i2c->adap.retries = 2;
1088	i2c->adap.class = I2C_CLASS_DEPRECATED;
1089	i2c->tx_setup = 50;
1090
1091	init_waitqueue_head(&i2c->wait);
1092
1093	/* find the clock and enable it */
1094	i2c->dev = &pdev->dev;
1095	i2c->clk = devm_clk_get(&pdev->dev, "i2c");
1096	if (IS_ERR(i2c->clk)) {
1097		dev_err(&pdev->dev, "cannot get clock\n");
1098		return -ENOENT;
1099	}
1100
1101	dev_dbg(&pdev->dev, "clock source %p\n", i2c->clk);
1102
1103	/* map the registers */
1104	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1105	i2c->regs = devm_ioremap_resource(&pdev->dev, res);
1106
1107	if (IS_ERR(i2c->regs))
1108		return PTR_ERR(i2c->regs);
1109
1110	dev_dbg(&pdev->dev, "registers %p (%p)\n",
1111		i2c->regs, res);
1112
1113	/* setup info block for the i2c core */
1114	i2c->adap.algo_data = i2c;
1115	i2c->adap.dev.parent = &pdev->dev;
1116	i2c->pctrl = devm_pinctrl_get_select_default(i2c->dev);
1117
1118	/* inititalise the i2c gpio lines */
1119	if (i2c->pdata->cfg_gpio)
1120		i2c->pdata->cfg_gpio(to_platform_device(i2c->dev));
1121	else if (IS_ERR(i2c->pctrl) && s3c24xx_i2c_parse_dt_gpio(i2c))
1122		return -EINVAL;
1123
1124	/* initialise the i2c controller */
1125	ret = clk_prepare_enable(i2c->clk);
1126	if (ret) {
1127		dev_err(&pdev->dev, "I2C clock enable failed\n");
1128		return ret;
1129	}
1130
1131	ret = s3c24xx_i2c_init(i2c);
1132	clk_disable(i2c->clk);
1133	if (ret != 0) {
1134		dev_err(&pdev->dev, "I2C controller init failed\n");
1135		clk_unprepare(i2c->clk);
1136		return ret;
1137	}
1138
1139	/*
1140	 * find the IRQ for this unit (note, this relies on the init call to
1141	 * ensure no current IRQs pending
1142	 */
1143	if (!(i2c->quirks & QUIRK_POLL)) {
1144		i2c->irq = ret = platform_get_irq(pdev, 0);
1145		if (ret < 0) {
1146			dev_err(&pdev->dev, "cannot find IRQ\n");
1147			clk_unprepare(i2c->clk);
1148			return ret;
1149		}
1150
1151		ret = devm_request_irq(&pdev->dev, i2c->irq, s3c24xx_i2c_irq,
1152				       0, dev_name(&pdev->dev), i2c);
1153		if (ret != 0) {
1154			dev_err(&pdev->dev, "cannot claim IRQ %d\n", i2c->irq);
1155			clk_unprepare(i2c->clk);
1156			return ret;
1157		}
1158	}
1159
1160	ret = s3c24xx_i2c_register_cpufreq(i2c);
1161	if (ret < 0) {
1162		dev_err(&pdev->dev, "failed to register cpufreq notifier\n");
1163		clk_unprepare(i2c->clk);
1164		return ret;
1165	}
1166
1167	/*
1168	 * Note, previous versions of the driver used i2c_add_adapter()
1169	 * to add the bus at any number. We now pass the bus number via
1170	 * the platform data, so if unset it will now default to always
1171	 * being bus 0.
1172	 */
1173	i2c->adap.nr = i2c->pdata->bus_num;
1174	i2c->adap.dev.of_node = pdev->dev.of_node;
1175
1176	platform_set_drvdata(pdev, i2c);
1177
1178	pm_runtime_enable(&pdev->dev);
1179
1180	ret = i2c_add_numbered_adapter(&i2c->adap);
1181	if (ret < 0) {
1182		pm_runtime_disable(&pdev->dev);
1183		s3c24xx_i2c_deregister_cpufreq(i2c);
1184		clk_unprepare(i2c->clk);
1185		return ret;
1186	}
1187
1188	dev_info(&pdev->dev, "%s: S3C I2C adapter\n", dev_name(&i2c->adap.dev));
1189	return 0;
1190}
1191
1192static int s3c24xx_i2c_remove(struct platform_device *pdev)
1193{
1194	struct s3c24xx_i2c *i2c = platform_get_drvdata(pdev);
1195
1196	clk_unprepare(i2c->clk);
1197
1198	pm_runtime_disable(&pdev->dev);
1199
1200	s3c24xx_i2c_deregister_cpufreq(i2c);
1201
1202	i2c_del_adapter(&i2c->adap);
1203
1204	return 0;
1205}
1206
1207#ifdef CONFIG_PM_SLEEP
1208static int s3c24xx_i2c_suspend_noirq(struct device *dev)
1209{
1210	struct s3c24xx_i2c *i2c = dev_get_drvdata(dev);
1211
1212	i2c_mark_adapter_suspended(&i2c->adap);
1213
1214	if (!IS_ERR(i2c->sysreg))
1215		regmap_read(i2c->sysreg, EXYNOS5_SYS_I2C_CFG, &i2c->sys_i2c_cfg);
1216
1217	return 0;
1218}
1219
1220static int s3c24xx_i2c_resume_noirq(struct device *dev)
1221{
1222	struct s3c24xx_i2c *i2c = dev_get_drvdata(dev);
1223	int ret;
1224
1225	if (!IS_ERR(i2c->sysreg))
1226		regmap_write(i2c->sysreg, EXYNOS5_SYS_I2C_CFG, i2c->sys_i2c_cfg);
1227
1228	ret = clk_enable(i2c->clk);
1229	if (ret)
1230		return ret;
1231	s3c24xx_i2c_init(i2c);
1232	clk_disable(i2c->clk);
1233	i2c_mark_adapter_resumed(&i2c->adap);
1234
1235	return 0;
1236}
1237#endif
1238
1239#ifdef CONFIG_PM
1240static const struct dev_pm_ops s3c24xx_i2c_dev_pm_ops = {
1241	SET_NOIRQ_SYSTEM_SLEEP_PM_OPS(s3c24xx_i2c_suspend_noirq,
1242				      s3c24xx_i2c_resume_noirq)
1243};
1244
1245#define S3C24XX_DEV_PM_OPS (&s3c24xx_i2c_dev_pm_ops)
1246#else
1247#define S3C24XX_DEV_PM_OPS NULL
1248#endif
1249
1250static struct platform_driver s3c24xx_i2c_driver = {
1251	.probe		= s3c24xx_i2c_probe,
1252	.remove		= s3c24xx_i2c_remove,
1253	.id_table	= s3c24xx_driver_ids,
1254	.driver		= {
1255		.name	= "s3c-i2c",
1256		.pm	= S3C24XX_DEV_PM_OPS,
1257		.of_match_table = of_match_ptr(s3c24xx_i2c_match),
1258	},
1259};
1260
1261static int __init i2c_adap_s3c_init(void)
1262{
1263	return platform_driver_register(&s3c24xx_i2c_driver);
1264}
1265subsys_initcall(i2c_adap_s3c_init);
1266
1267static void __exit i2c_adap_s3c_exit(void)
1268{
1269	platform_driver_unregister(&s3c24xx_i2c_driver);
1270}
1271module_exit(i2c_adap_s3c_exit);
1272
1273MODULE_DESCRIPTION("S3C24XX I2C Bus driver");
1274MODULE_AUTHOR("Ben Dooks <ben@simtec.co.uk>");
1275MODULE_LICENSE("GPL");
1276