1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 *  i2c-algo-pca.c i2c driver algorithms for PCA9564 adapters
4 *    Copyright (C) 2004 Arcom Control Systems
5 *    Copyright (C) 2008 Pengutronix
6 */
7
8#include <linux/kernel.h>
9#include <linux/module.h>
10#include <linux/moduleparam.h>
11#include <linux/delay.h>
12#include <linux/jiffies.h>
13#include <linux/errno.h>
14#include <linux/i2c.h>
15#include <linux/i2c-algo-pca.h>
16
17#define DEB1(fmt, args...) do { if (i2c_debug >= 1)			\
18				 printk(KERN_DEBUG fmt, ## args); } while (0)
19#define DEB2(fmt, args...) do { if (i2c_debug >= 2)			\
20				 printk(KERN_DEBUG fmt, ## args); } while (0)
21#define DEB3(fmt, args...) do { if (i2c_debug >= 3)			\
22				 printk(KERN_DEBUG fmt, ## args); } while (0)
23
24static int i2c_debug;
25
26#define pca_outw(adap, reg, val) adap->write_byte(adap->data, reg, val)
27#define pca_inw(adap, reg) adap->read_byte(adap->data, reg)
28
29#define pca_status(adap) pca_inw(adap, I2C_PCA_STA)
30#define pca_clock(adap) adap->i2c_clock
31#define pca_set_con(adap, val) pca_outw(adap, I2C_PCA_CON, val)
32#define pca_get_con(adap) pca_inw(adap, I2C_PCA_CON)
33#define pca_wait(adap) adap->wait_for_completion(adap->data)
34
35static void pca_reset(struct i2c_algo_pca_data *adap)
36{
37	if (adap->chip == I2C_PCA_CHIP_9665) {
38		/* Ignore the reset function from the module,
39		 * we can use the parallel bus reset.
40		 */
41		pca_outw(adap, I2C_PCA_INDPTR, I2C_PCA_IPRESET);
42		pca_outw(adap, I2C_PCA_IND, 0xA5);
43		pca_outw(adap, I2C_PCA_IND, 0x5A);
44
45		/*
46		 * After a reset we need to re-apply any configuration
47		 * (calculated in pca_init) to get the bus in a working state.
48		 */
49		pca_outw(adap, I2C_PCA_INDPTR, I2C_PCA_IMODE);
50		pca_outw(adap, I2C_PCA_IND, adap->bus_settings.mode);
51		pca_outw(adap, I2C_PCA_INDPTR, I2C_PCA_ISCLL);
52		pca_outw(adap, I2C_PCA_IND, adap->bus_settings.tlow);
53		pca_outw(adap, I2C_PCA_INDPTR, I2C_PCA_ISCLH);
54		pca_outw(adap, I2C_PCA_IND, adap->bus_settings.thi);
55
56		pca_set_con(adap, I2C_PCA_CON_ENSIO);
57	} else {
58		adap->reset_chip(adap->data);
59		pca_set_con(adap, I2C_PCA_CON_ENSIO | adap->bus_settings.clock_freq);
60	}
61}
62
63/*
64 * Generate a start condition on the i2c bus.
65 *
66 * returns after the start condition has occurred
67 */
68static int pca_start(struct i2c_algo_pca_data *adap)
69{
70	int sta = pca_get_con(adap);
71	DEB2("=== START\n");
72	sta |= I2C_PCA_CON_STA;
73	sta &= ~(I2C_PCA_CON_STO|I2C_PCA_CON_SI);
74	pca_set_con(adap, sta);
75	return pca_wait(adap);
76}
77
78/*
79 * Generate a repeated start condition on the i2c bus
80 *
81 * return after the repeated start condition has occurred
82 */
83static int pca_repeated_start(struct i2c_algo_pca_data *adap)
84{
85	int sta = pca_get_con(adap);
86	DEB2("=== REPEATED START\n");
87	sta |= I2C_PCA_CON_STA;
88	sta &= ~(I2C_PCA_CON_STO|I2C_PCA_CON_SI);
89	pca_set_con(adap, sta);
90	return pca_wait(adap);
91}
92
93/*
94 * Generate a stop condition on the i2c bus
95 *
96 * returns after the stop condition has been generated
97 *
98 * STOPs do not generate an interrupt or set the SI flag, since the
99 * part returns the idle state (0xf8). Hence we don't need to
100 * pca_wait here.
101 */
102static void pca_stop(struct i2c_algo_pca_data *adap)
103{
104	int sta = pca_get_con(adap);
105	DEB2("=== STOP\n");
106	sta |= I2C_PCA_CON_STO;
107	sta &= ~(I2C_PCA_CON_STA|I2C_PCA_CON_SI);
108	pca_set_con(adap, sta);
109}
110
111/*
112 * Send the slave address and R/W bit
113 *
114 * returns after the address has been sent
115 */
116static int pca_address(struct i2c_algo_pca_data *adap,
117		       struct i2c_msg *msg)
118{
119	int sta = pca_get_con(adap);
120	int addr = i2c_8bit_addr_from_msg(msg);
121
122	DEB2("=== SLAVE ADDRESS %#04x+%c=%#04x\n",
123	     msg->addr, msg->flags & I2C_M_RD ? 'R' : 'W', addr);
124
125	pca_outw(adap, I2C_PCA_DAT, addr);
126
127	sta &= ~(I2C_PCA_CON_STO|I2C_PCA_CON_STA|I2C_PCA_CON_SI);
128	pca_set_con(adap, sta);
129
130	return pca_wait(adap);
131}
132
133/*
134 * Transmit a byte.
135 *
136 * Returns after the byte has been transmitted
137 */
138static int pca_tx_byte(struct i2c_algo_pca_data *adap,
139		       __u8 b)
140{
141	int sta = pca_get_con(adap);
142	DEB2("=== WRITE %#04x\n", b);
143	pca_outw(adap, I2C_PCA_DAT, b);
144
145	sta &= ~(I2C_PCA_CON_STO|I2C_PCA_CON_STA|I2C_PCA_CON_SI);
146	pca_set_con(adap, sta);
147
148	return pca_wait(adap);
149}
150
151/*
152 * Receive a byte
153 *
154 * returns immediately.
155 */
156static void pca_rx_byte(struct i2c_algo_pca_data *adap,
157			__u8 *b, int ack)
158{
159	*b = pca_inw(adap, I2C_PCA_DAT);
160	DEB2("=== READ %#04x %s\n", *b, ack ? "ACK" : "NACK");
161}
162
163/*
164 * Setup ACK or NACK for next received byte and wait for it to arrive.
165 *
166 * Returns after next byte has arrived.
167 */
168static int pca_rx_ack(struct i2c_algo_pca_data *adap,
169		      int ack)
170{
171	int sta = pca_get_con(adap);
172
173	sta &= ~(I2C_PCA_CON_STO|I2C_PCA_CON_STA|I2C_PCA_CON_SI|I2C_PCA_CON_AA);
174
175	if (ack)
176		sta |= I2C_PCA_CON_AA;
177
178	pca_set_con(adap, sta);
179	return pca_wait(adap);
180}
181
182static int pca_xfer(struct i2c_adapter *i2c_adap,
183		    struct i2c_msg *msgs,
184		    int num)
185{
186	struct i2c_algo_pca_data *adap = i2c_adap->algo_data;
187	struct i2c_msg *msg = NULL;
188	int curmsg;
189	int numbytes = 0;
190	int state;
191	int ret;
192	int completed = 1;
193	unsigned long timeout = jiffies + i2c_adap->timeout;
194
195	while ((state = pca_status(adap)) != 0xf8) {
196		if (time_before(jiffies, timeout)) {
197			msleep(10);
198		} else {
199			dev_dbg(&i2c_adap->dev, "bus is not idle. status is "
200				"%#04x\n", state);
201			return -EBUSY;
202		}
203	}
204
205	DEB1("{{{ XFER %d messages\n", num);
206
207	if (i2c_debug >= 2) {
208		for (curmsg = 0; curmsg < num; curmsg++) {
209			int addr, i;
210			msg = &msgs[curmsg];
211
212			addr = (0x7f & msg->addr) ;
213
214			if (msg->flags & I2C_M_RD)
215				printk(KERN_INFO "    [%02d] RD %d bytes from %#02x [%#02x, ...]\n",
216				       curmsg, msg->len, addr, (addr << 1) | 1);
217			else {
218				printk(KERN_INFO "    [%02d] WR %d bytes to %#02x [%#02x%s",
219				       curmsg, msg->len, addr, addr << 1,
220				       msg->len == 0 ? "" : ", ");
221				for (i = 0; i < msg->len; i++)
222					printk("%#04x%s", msg->buf[i], i == msg->len - 1 ? "" : ", ");
223				printk("]\n");
224			}
225		}
226	}
227
228	curmsg = 0;
229	ret = -EIO;
230	while (curmsg < num) {
231		state = pca_status(adap);
232
233		DEB3("STATE is 0x%02x\n", state);
234		msg = &msgs[curmsg];
235
236		switch (state) {
237		case 0xf8: /* On reset or stop the bus is idle */
238			completed = pca_start(adap);
239			break;
240
241		case 0x08: /* A START condition has been transmitted */
242		case 0x10: /* A repeated start condition has been transmitted */
243			completed = pca_address(adap, msg);
244			break;
245
246		case 0x18: /* SLA+W has been transmitted; ACK has been received */
247		case 0x28: /* Data byte in I2CDAT has been transmitted; ACK has been received */
248			if (numbytes < msg->len) {
249				completed = pca_tx_byte(adap,
250							msg->buf[numbytes]);
251				numbytes++;
252				break;
253			}
254			curmsg++; numbytes = 0;
255			if (curmsg == num)
256				pca_stop(adap);
257			else
258				completed = pca_repeated_start(adap);
259			break;
260
261		case 0x20: /* SLA+W has been transmitted; NOT ACK has been received */
262			DEB2("NOT ACK received after SLA+W\n");
263			pca_stop(adap);
264			ret = -ENXIO;
265			goto out;
266
267		case 0x40: /* SLA+R has been transmitted; ACK has been received */
268			completed = pca_rx_ack(adap, msg->len > 1);
269			break;
270
271		case 0x50: /* Data bytes has been received; ACK has been returned */
272			if (numbytes < msg->len) {
273				pca_rx_byte(adap, &msg->buf[numbytes], 1);
274				numbytes++;
275				completed = pca_rx_ack(adap,
276						       numbytes < msg->len - 1);
277				break;
278			}
279			curmsg++; numbytes = 0;
280			if (curmsg == num)
281				pca_stop(adap);
282			else
283				completed = pca_repeated_start(adap);
284			break;
285
286		case 0x48: /* SLA+R has been transmitted; NOT ACK has been received */
287			DEB2("NOT ACK received after SLA+R\n");
288			pca_stop(adap);
289			ret = -ENXIO;
290			goto out;
291
292		case 0x30: /* Data byte in I2CDAT has been transmitted; NOT ACK has been received */
293			DEB2("NOT ACK received after data byte\n");
294			pca_stop(adap);
295			goto out;
296
297		case 0x38: /* Arbitration lost during SLA+W, SLA+R or data bytes */
298			DEB2("Arbitration lost\n");
299			/*
300			 * The PCA9564 data sheet (2006-09-01) says "A
301			 * START condition will be transmitted when the
302			 * bus becomes free (STOP or SCL and SDA high)"
303			 * when the STA bit is set (p. 11).
304			 *
305			 * In case this won't work, try pca_reset()
306			 * instead.
307			 */
308			pca_start(adap);
309			goto out;
310
311		case 0x58: /* Data byte has been received; NOT ACK has been returned */
312			if (numbytes == msg->len - 1) {
313				pca_rx_byte(adap, &msg->buf[numbytes], 0);
314				curmsg++; numbytes = 0;
315				if (curmsg == num)
316					pca_stop(adap);
317				else
318					completed = pca_repeated_start(adap);
319			} else {
320				DEB2("NOT ACK sent after data byte received. "
321				     "Not final byte. numbytes %d. len %d\n",
322				     numbytes, msg->len);
323				pca_stop(adap);
324				goto out;
325			}
326			break;
327		case 0x70: /* Bus error - SDA stuck low */
328			DEB2("BUS ERROR - SDA Stuck low\n");
329			pca_reset(adap);
330			goto out;
331		case 0x78: /* Bus error - SCL stuck low (PCA9665) */
332		case 0x90: /* Bus error - SCL stuck low (PCA9564) */
333			DEB2("BUS ERROR - SCL Stuck low\n");
334			pca_reset(adap);
335			goto out;
336		case 0x00: /* Bus error during master or slave mode due to illegal START or STOP condition */
337			DEB2("BUS ERROR - Illegal START or STOP\n");
338			pca_reset(adap);
339			goto out;
340		default:
341			dev_err(&i2c_adap->dev, "unhandled SIO state 0x%02x\n", state);
342			break;
343		}
344
345		if (!completed)
346			goto out;
347	}
348
349	ret = curmsg;
350 out:
351	DEB1("}}} transferred %d/%d messages. "
352	     "status is %#04x. control is %#04x\n",
353	     curmsg, num, pca_status(adap),
354	     pca_get_con(adap));
355	return ret;
356}
357
358static u32 pca_func(struct i2c_adapter *adap)
359{
360	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
361}
362
363static const struct i2c_algorithm pca_algo = {
364	.master_xfer	= pca_xfer,
365	.functionality	= pca_func,
366};
367
368static unsigned int pca_probe_chip(struct i2c_adapter *adap)
369{
370	struct i2c_algo_pca_data *pca_data = adap->algo_data;
371	/* The trick here is to check if there is an indirect register
372	 * available. If there is one, we will read the value we first
373	 * wrote on I2C_PCA_IADR. Otherwise, we will read the last value
374	 * we wrote on I2C_PCA_ADR
375	 */
376	pca_outw(pca_data, I2C_PCA_INDPTR, I2C_PCA_IADR);
377	pca_outw(pca_data, I2C_PCA_IND, 0xAA);
378	pca_outw(pca_data, I2C_PCA_INDPTR, I2C_PCA_ITO);
379	pca_outw(pca_data, I2C_PCA_IND, 0x00);
380	pca_outw(pca_data, I2C_PCA_INDPTR, I2C_PCA_IADR);
381	if (pca_inw(pca_data, I2C_PCA_IND) == 0xAA) {
382		printk(KERN_INFO "%s: PCA9665 detected.\n", adap->name);
383		pca_data->chip = I2C_PCA_CHIP_9665;
384	} else {
385		printk(KERN_INFO "%s: PCA9564 detected.\n", adap->name);
386		pca_data->chip = I2C_PCA_CHIP_9564;
387	}
388	return pca_data->chip;
389}
390
391static int pca_init(struct i2c_adapter *adap)
392{
393	struct i2c_algo_pca_data *pca_data = adap->algo_data;
394
395	adap->algo = &pca_algo;
396
397	if (pca_probe_chip(adap) == I2C_PCA_CHIP_9564) {
398		static int freqs[] = {330, 288, 217, 146, 88, 59, 44, 36};
399		int clock;
400
401		if (pca_data->i2c_clock > 7) {
402			switch (pca_data->i2c_clock) {
403			case 330000:
404				pca_data->i2c_clock = I2C_PCA_CON_330kHz;
405				break;
406			case 288000:
407				pca_data->i2c_clock = I2C_PCA_CON_288kHz;
408				break;
409			case 217000:
410				pca_data->i2c_clock = I2C_PCA_CON_217kHz;
411				break;
412			case 146000:
413				pca_data->i2c_clock = I2C_PCA_CON_146kHz;
414				break;
415			case 88000:
416				pca_data->i2c_clock = I2C_PCA_CON_88kHz;
417				break;
418			case 59000:
419				pca_data->i2c_clock = I2C_PCA_CON_59kHz;
420				break;
421			case 44000:
422				pca_data->i2c_clock = I2C_PCA_CON_44kHz;
423				break;
424			case 36000:
425				pca_data->i2c_clock = I2C_PCA_CON_36kHz;
426				break;
427			default:
428				printk(KERN_WARNING
429					"%s: Invalid I2C clock speed selected."
430					" Using default 59kHz.\n", adap->name);
431			pca_data->i2c_clock = I2C_PCA_CON_59kHz;
432			}
433		} else {
434			printk(KERN_WARNING "%s: "
435				"Choosing the clock frequency based on "
436				"index is deprecated."
437				" Use the nominal frequency.\n", adap->name);
438		}
439
440		clock = pca_clock(pca_data);
441		printk(KERN_INFO "%s: Clock frequency is %dkHz\n",
442		     adap->name, freqs[clock]);
443
444		/* Store settings as these will be needed when the PCA chip is reset */
445		pca_data->bus_settings.clock_freq = clock;
446
447		pca_reset(pca_data);
448	} else {
449		int clock;
450		int mode;
451		int tlow, thi;
452		/* Values can be found on PCA9665 datasheet section 7.3.2.6 */
453		int min_tlow, min_thi;
454		/* These values are the maximum raise and fall values allowed
455		 * by the I2C operation mode (Standard, Fast or Fast+)
456		 * They are used (added) below to calculate the clock dividers
457		 * of PCA9665. Note that they are slightly different of the
458		 * real maximum, to allow the change on mode exactly on the
459		 * maximum clock rate for each mode
460		 */
461		int raise_fall_time;
462
463		if (pca_data->i2c_clock > 1265800) {
464			printk(KERN_WARNING "%s: I2C clock speed too high."
465				" Using 1265.8kHz.\n", adap->name);
466			pca_data->i2c_clock = 1265800;
467		}
468
469		if (pca_data->i2c_clock < 60300) {
470			printk(KERN_WARNING "%s: I2C clock speed too low."
471				" Using 60.3kHz.\n", adap->name);
472			pca_data->i2c_clock = 60300;
473		}
474
475		/* To avoid integer overflow, use clock/100 for calculations */
476		clock = pca_clock(pca_data) / 100;
477
478		if (pca_data->i2c_clock > I2C_MAX_FAST_MODE_PLUS_FREQ) {
479			mode = I2C_PCA_MODE_TURBO;
480			min_tlow = 14;
481			min_thi  = 5;
482			raise_fall_time = 22; /* Raise 11e-8s, Fall 11e-8s */
483		} else if (pca_data->i2c_clock > I2C_MAX_FAST_MODE_FREQ) {
484			mode = I2C_PCA_MODE_FASTP;
485			min_tlow = 17;
486			min_thi  = 9;
487			raise_fall_time = 22; /* Raise 11e-8s, Fall 11e-8s */
488		} else if (pca_data->i2c_clock > I2C_MAX_STANDARD_MODE_FREQ) {
489			mode = I2C_PCA_MODE_FAST;
490			min_tlow = 44;
491			min_thi  = 20;
492			raise_fall_time = 58; /* Raise 29e-8s, Fall 29e-8s */
493		} else {
494			mode = I2C_PCA_MODE_STD;
495			min_tlow = 157;
496			min_thi  = 134;
497			raise_fall_time = 127; /* Raise 29e-8s, Fall 98e-8s */
498		}
499
500		/* The minimum clock that respects the thi/tlow = 134/157 is
501		 * 64800 Hz. Below that, we have to fix the tlow to 255 and
502		 * calculate the thi factor.
503		 */
504		if (clock < 648) {
505			tlow = 255;
506			thi = 1000000 - clock * raise_fall_time;
507			thi /= (I2C_PCA_OSC_PER * clock) - tlow;
508		} else {
509			tlow = (1000000 - clock * raise_fall_time) * min_tlow;
510			tlow /= I2C_PCA_OSC_PER * clock * (min_thi + min_tlow);
511			thi = tlow * min_thi / min_tlow;
512		}
513
514		/* Store settings as these will be needed when the PCA chip is reset */
515		pca_data->bus_settings.mode = mode;
516		pca_data->bus_settings.tlow = tlow;
517		pca_data->bus_settings.thi = thi;
518
519		pca_reset(pca_data);
520
521		printk(KERN_INFO
522		     "%s: Clock frequency is %dHz\n", adap->name, clock * 100);
523	}
524	udelay(500); /* 500 us for oscillator to stabilise */
525
526	return 0;
527}
528
529/*
530 * registering functions to load algorithms at runtime
531 */
532int i2c_pca_add_bus(struct i2c_adapter *adap)
533{
534	int rval;
535
536	rval = pca_init(adap);
537	if (rval)
538		return rval;
539
540	return i2c_add_adapter(adap);
541}
542EXPORT_SYMBOL(i2c_pca_add_bus);
543
544int i2c_pca_add_numbered_bus(struct i2c_adapter *adap)
545{
546	int rval;
547
548	rval = pca_init(adap);
549	if (rval)
550		return rval;
551
552	return i2c_add_numbered_adapter(adap);
553}
554EXPORT_SYMBOL(i2c_pca_add_numbered_bus);
555
556MODULE_AUTHOR("Ian Campbell <icampbell@arcom.com>");
557MODULE_AUTHOR("Wolfram Sang <kernel@pengutronix.de>");
558MODULE_DESCRIPTION("I2C-Bus PCA9564/PCA9665 algorithm");
559MODULE_LICENSE("GPL");
560
561module_param(i2c_debug, int, 0);
562