1/* -------------------------------------------------------------------------
2 * i2c-algo-bit.c i2c driver algorithms for bit-shift adapters
3 * -------------------------------------------------------------------------
4 *   Copyright (C) 1995-2000 Simon G. Vogl
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19    MA 02110-1301 USA.
20 * ------------------------------------------------------------------------- */
21
22/* With some changes from Frodo Looijaard <frodol@dds.nl>, Kyösti Mälkki
23   <kmalkki@cc.hut.fi> and Jean Delvare <khali@linux-fr.org> */
24
25#include <linux/kernel.h>
26#include <linux/module.h>
27#include <linux/delay.h>
28#include <linux/init.h>
29#include <linux/errno.h>
30#include <linux/sched.h>
31#include <linux/i2c.h>
32#include <linux/i2c-algo-bit.h>
33
34
35/* ----- global defines ----------------------------------------------- */
36
37#ifdef DEBUG
38#define bit_dbg(level, dev, format, args...) \
39	do { \
40		if (i2c_debug >= level) \
41			dev_dbg(dev, format, ##args); \
42	} while (0)
43#else
44#define bit_dbg(level, dev, format, args...) \
45	do {} while (0)
46#endif /* DEBUG */
47
48/* ----- global variables ---------------------------------------------	*/
49
50static int bit_test;	/* see if the line-setting functions work	*/
51module_param(bit_test, int, S_IRUGO);
52MODULE_PARM_DESC(bit_test, "lines testing - 0 off; 1 report; 2 fail if stuck");
53
54#ifdef DEBUG
55static int i2c_debug = 1;
56module_param(i2c_debug, int, S_IRUGO | S_IWUSR);
57MODULE_PARM_DESC(i2c_debug,
58		 "debug level - 0 off; 1 normal; 2 verbose; 3 very verbose");
59#endif
60
61/* --- setting states on the bus with the right timing: ---------------	*/
62
63#define setsda(adap, val)	adap->setsda(adap->data, val)
64#define setscl(adap, val)	adap->setscl(adap->data, val)
65#define getsda(adap)		adap->getsda(adap->data)
66#define getscl(adap)		adap->getscl(adap->data)
67
68static inline void sdalo(struct i2c_algo_bit_data *adap)
69{
70	setsda(adap, 0);
71	udelay((adap->udelay + 1) / 2);
72}
73
74static inline void sdahi(struct i2c_algo_bit_data *adap)
75{
76	setsda(adap, 1);
77	udelay((adap->udelay + 1) / 2);
78}
79
80static inline void scllo(struct i2c_algo_bit_data *adap)
81{
82	setscl(adap, 0);
83	udelay(adap->udelay / 2);
84}
85
86/*
87 * Raise scl line, and do checking for delays. This is necessary for slower
88 * devices.
89 */
90static int sclhi(struct i2c_algo_bit_data *adap)
91{
92	unsigned long start;
93
94	setscl(adap, 1);
95
96	/* Not all adapters have scl sense line... */
97	if (!adap->getscl)
98		goto done;
99
100	start = jiffies;
101	while (!getscl(adap)) {
102		/* This hw knows how to read the clock line, so we wait
103		 * until it actually gets high.  This is safer as some
104		 * chips may hold it low ("clock stretching") while they
105		 * are processing data internally.
106		 */
107		if (time_after(jiffies, start + adap->timeout)) {
108			/* Test one last time, as we may have been preempted
109			 * between last check and timeout test.
110			 */
111			if (getscl(adap))
112				break;
113			return -ETIMEDOUT;
114		}
115		cpu_relax();
116	}
117#ifdef DEBUG
118	if (jiffies != start && i2c_debug >= 3)
119		pr_debug("i2c-algo-bit: needed %ld jiffies for SCL to go "
120			 "high\n", jiffies - start);
121#endif
122
123done:
124	udelay(adap->udelay);
125	return 0;
126}
127
128
129/* --- other auxiliary functions --------------------------------------	*/
130static void i2c_start(struct i2c_algo_bit_data *adap)
131{
132	/* assert: scl, sda are high */
133	setsda(adap, 0);
134	udelay(adap->udelay);
135	scllo(adap);
136}
137
138static void i2c_repstart(struct i2c_algo_bit_data *adap)
139{
140	/* assert: scl is low */
141	sdahi(adap);
142	sclhi(adap);
143	setsda(adap, 0);
144	udelay(adap->udelay);
145	scllo(adap);
146}
147
148
149static void i2c_stop(struct i2c_algo_bit_data *adap)
150{
151	/* assert: scl is low */
152	sdalo(adap);
153	sclhi(adap);
154	setsda(adap, 1);
155	udelay(adap->udelay);
156}
157
158
159
160/* send a byte without start cond., look for arbitration,
161   check ackn. from slave */
162/* returns:
163 * 1 if the device acknowledged
164 * 0 if the device did not ack
165 * -ETIMEDOUT if an error occurred (while raising the scl line)
166 */
167static int i2c_outb(struct i2c_adapter *i2c_adap, unsigned char c)
168{
169	int i;
170	int sb;
171	int ack;
172	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
173
174	/* assert: scl is low */
175	for (i = 7; i >= 0; i--) {
176		sb = (c >> i) & 1;
177		setsda(adap, sb);
178		udelay((adap->udelay + 1) / 2);
179		if (sclhi(adap) < 0) { /* timed out */
180			bit_dbg(1, &i2c_adap->dev, "i2c_outb: 0x%02x, "
181				"timeout at bit #%d\n", (int)c, i);
182			return -ETIMEDOUT;
183		}
184		/* FIXME do arbitration here:
185		 * if (sb && !getsda(adap)) -> ouch! Get out of here.
186		 *
187		 * Report a unique code, so higher level code can retry
188		 * the whole (combined) message and *NOT* issue STOP.
189		 */
190		scllo(adap);
191	}
192	sdahi(adap);
193	if (sclhi(adap) < 0) { /* timeout */
194		bit_dbg(1, &i2c_adap->dev, "i2c_outb: 0x%02x, "
195			"timeout at ack\n", (int)c);
196		return -ETIMEDOUT;
197	}
198
199	/* read ack: SDA should be pulled down by slave, or it may
200	 * NAK (usually to report problems with the data we wrote).
201	 */
202	ack = !getsda(adap);    /* ack: sda is pulled low -> success */
203	bit_dbg(2, &i2c_adap->dev, "i2c_outb: 0x%02x %s\n", (int)c,
204		ack ? "A" : "NA");
205
206	scllo(adap);
207	return ack;
208	/* assert: scl is low (sda undef) */
209}
210
211
212static int i2c_inb(struct i2c_adapter *i2c_adap)
213{
214	/* read byte via i2c port, without start/stop sequence	*/
215	/* acknowledge is sent in i2c_read.			*/
216	int i;
217	unsigned char indata = 0;
218	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
219
220	/* assert: scl is low */
221	sdahi(adap);
222	for (i = 0; i < 8; i++) {
223		if (sclhi(adap) < 0) { /* timeout */
224			bit_dbg(1, &i2c_adap->dev, "i2c_inb: timeout at bit "
225				"#%d\n", 7 - i);
226			return -ETIMEDOUT;
227		}
228		indata *= 2;
229		if (getsda(adap))
230			indata |= 0x01;
231		setscl(adap, 0);
232		udelay(i == 7 ? adap->udelay / 2 : adap->udelay);
233	}
234	/* assert: scl is low */
235	return indata;
236}
237
238/*
239 * Sanity check for the adapter hardware - check the reaction of
240 * the bus lines only if it seems to be idle.
241 */
242static int test_bus(struct i2c_adapter *i2c_adap)
243{
244	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
245	const char *name = i2c_adap->name;
246	int scl, sda, ret;
247
248	if (adap->pre_xfer) {
249		ret = adap->pre_xfer(i2c_adap);
250		if (ret < 0)
251			return -ENODEV;
252	}
253
254	if (adap->getscl == NULL)
255		pr_info("%s: Testing SDA only, SCL is not readable\n", name);
256
257	sda = getsda(adap);
258	scl = (adap->getscl == NULL) ? 1 : getscl(adap);
259	if (!scl || !sda) {
260		printk(KERN_WARNING
261		       "%s: bus seems to be busy (scl=%d, sda=%d)\n",
262		       name, scl, sda);
263		goto bailout;
264	}
265
266	sdalo(adap);
267	sda = getsda(adap);
268	scl = (adap->getscl == NULL) ? 1 : getscl(adap);
269	if (sda) {
270		printk(KERN_WARNING "%s: SDA stuck high!\n", name);
271		goto bailout;
272	}
273	if (!scl) {
274		printk(KERN_WARNING "%s: SCL unexpected low "
275		       "while pulling SDA low!\n", name);
276		goto bailout;
277	}
278
279	sdahi(adap);
280	sda = getsda(adap);
281	scl = (adap->getscl == NULL) ? 1 : getscl(adap);
282	if (!sda) {
283		printk(KERN_WARNING "%s: SDA stuck low!\n", name);
284		goto bailout;
285	}
286	if (!scl) {
287		printk(KERN_WARNING "%s: SCL unexpected low "
288		       "while pulling SDA high!\n", name);
289		goto bailout;
290	}
291
292	scllo(adap);
293	sda = getsda(adap);
294	scl = (adap->getscl == NULL) ? 0 : getscl(adap);
295	if (scl) {
296		printk(KERN_WARNING "%s: SCL stuck high!\n", name);
297		goto bailout;
298	}
299	if (!sda) {
300		printk(KERN_WARNING "%s: SDA unexpected low "
301		       "while pulling SCL low!\n", name);
302		goto bailout;
303	}
304
305	sclhi(adap);
306	sda = getsda(adap);
307	scl = (adap->getscl == NULL) ? 1 : getscl(adap);
308	if (!scl) {
309		printk(KERN_WARNING "%s: SCL stuck low!\n", name);
310		goto bailout;
311	}
312	if (!sda) {
313		printk(KERN_WARNING "%s: SDA unexpected low "
314		       "while pulling SCL high!\n", name);
315		goto bailout;
316	}
317
318	if (adap->post_xfer)
319		adap->post_xfer(i2c_adap);
320
321	pr_info("%s: Test OK\n", name);
322	return 0;
323bailout:
324	sdahi(adap);
325	sclhi(adap);
326
327	if (adap->post_xfer)
328		adap->post_xfer(i2c_adap);
329
330	return -ENODEV;
331}
332
333/* ----- Utility functions
334 */
335
336/* try_address tries to contact a chip for a number of
337 * times before it gives up.
338 * return values:
339 * 1 chip answered
340 * 0 chip did not answer
341 * -x transmission error
342 */
343static int try_address(struct i2c_adapter *i2c_adap,
344		       unsigned char addr, int retries)
345{
346	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
347	int i, ret = 0;
348
349	for (i = 0; i <= retries; i++) {
350		ret = i2c_outb(i2c_adap, addr);
351		if (ret == 1 || i == retries)
352			break;
353		bit_dbg(3, &i2c_adap->dev, "emitting stop condition\n");
354		i2c_stop(adap);
355		udelay(adap->udelay);
356		yield();
357		bit_dbg(3, &i2c_adap->dev, "emitting start condition\n");
358		i2c_start(adap);
359	}
360	if (i && ret)
361		bit_dbg(1, &i2c_adap->dev, "Used %d tries to %s client at "
362			"0x%02x: %s\n", i + 1,
363			addr & 1 ? "read from" : "write to", addr >> 1,
364			ret == 1 ? "success" : "failed, timeout?");
365	return ret;
366}
367
368static int sendbytes(struct i2c_adapter *i2c_adap, struct i2c_msg *msg)
369{
370	const unsigned char *temp = msg->buf;
371	int count = msg->len;
372	unsigned short nak_ok = msg->flags & I2C_M_IGNORE_NAK;
373	int retval;
374	int wrcount = 0;
375
376	while (count > 0) {
377		retval = i2c_outb(i2c_adap, *temp);
378
379		/* OK/ACK; or ignored NAK */
380		if ((retval > 0) || (nak_ok && (retval == 0))) {
381			count--;
382			temp++;
383			wrcount++;
384
385		/* A slave NAKing the master means the slave didn't like
386		 * something about the data it saw.  For example, maybe
387		 * the SMBus PEC was wrong.
388		 */
389		} else if (retval == 0) {
390			dev_err(&i2c_adap->dev, "sendbytes: NAK bailout.\n");
391			return -EIO;
392
393		/* Timeout; or (someday) lost arbitration
394		 *
395		 * FIXME Lost ARB implies retrying the transaction from
396		 * the first message, after the "winning" master issues
397		 * its STOP.  As a rule, upper layer code has no reason
398		 * to know or care about this ... it is *NOT* an error.
399		 */
400		} else {
401			dev_err(&i2c_adap->dev, "sendbytes: error %d\n",
402					retval);
403			return retval;
404		}
405	}
406	return wrcount;
407}
408
409static int acknak(struct i2c_adapter *i2c_adap, int is_ack)
410{
411	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
412
413	/* assert: sda is high */
414	if (is_ack)		/* send ack */
415		setsda(adap, 0);
416	udelay((adap->udelay + 1) / 2);
417	if (sclhi(adap) < 0) {	/* timeout */
418		dev_err(&i2c_adap->dev, "readbytes: ack/nak timeout\n");
419		return -ETIMEDOUT;
420	}
421	scllo(adap);
422	return 0;
423}
424
425static int readbytes(struct i2c_adapter *i2c_adap, struct i2c_msg *msg)
426{
427	int inval;
428	int rdcount = 0;	/* counts bytes read */
429	unsigned char *temp = msg->buf;
430	int count = msg->len;
431	const unsigned flags = msg->flags;
432
433	while (count > 0) {
434		inval = i2c_inb(i2c_adap);
435		if (inval >= 0) {
436			*temp = inval;
437			rdcount++;
438		} else {   /* read timed out */
439			break;
440		}
441
442		temp++;
443		count--;
444
445		/* Some SMBus transactions require that we receive the
446		   transaction length as the first read byte. */
447		if (rdcount == 1 && (flags & I2C_M_RECV_LEN)) {
448			if (inval <= 0 || inval > I2C_SMBUS_BLOCK_MAX) {
449				if (!(flags & I2C_M_NO_RD_ACK))
450					acknak(i2c_adap, 0);
451				dev_err(&i2c_adap->dev, "readbytes: invalid "
452					"block length (%d)\n", inval);
453				return -EPROTO;
454			}
455			/* The original count value accounts for the extra
456			   bytes, that is, either 1 for a regular transaction,
457			   or 2 for a PEC transaction. */
458			count += inval;
459			msg->len += inval;
460		}
461
462		bit_dbg(2, &i2c_adap->dev, "readbytes: 0x%02x %s\n",
463			inval,
464			(flags & I2C_M_NO_RD_ACK)
465				? "(no ack/nak)"
466				: (count ? "A" : "NA"));
467
468		if (!(flags & I2C_M_NO_RD_ACK)) {
469			inval = acknak(i2c_adap, count);
470			if (inval < 0)
471				return inval;
472		}
473	}
474	return rdcount;
475}
476
477/* doAddress initiates the transfer by generating the start condition (in
478 * try_address) and transmits the address in the necessary format to handle
479 * reads, writes as well as 10bit-addresses.
480 * returns:
481 *  0 everything went okay, the chip ack'ed, or IGNORE_NAK flag was set
482 * -x an error occurred (like: -ENXIO if the device did not answer, or
483 *	-ETIMEDOUT, for example if the lines are stuck...)
484 */
485static int bit_doAddress(struct i2c_adapter *i2c_adap, struct i2c_msg *msg)
486{
487	unsigned short flags = msg->flags;
488	unsigned short nak_ok = msg->flags & I2C_M_IGNORE_NAK;
489	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
490
491	unsigned char addr;
492	int ret, retries;
493
494	retries = nak_ok ? 0 : i2c_adap->retries;
495
496	if (flags & I2C_M_TEN) {
497		/* a ten bit address */
498		addr = 0xf0 | ((msg->addr >> 7) & 0x06);
499		bit_dbg(2, &i2c_adap->dev, "addr0: %d\n", addr);
500		/* try extended address code...*/
501		ret = try_address(i2c_adap, addr, retries);
502		if ((ret != 1) && !nak_ok)  {
503			dev_err(&i2c_adap->dev,
504				"died at extended address code\n");
505			return -ENXIO;
506		}
507		/* the remaining 8 bit address */
508		ret = i2c_outb(i2c_adap, msg->addr & 0xff);
509		if ((ret != 1) && !nak_ok) {
510			/* the chip did not ack / xmission error occurred */
511			dev_err(&i2c_adap->dev, "died at 2nd address code\n");
512			return -ENXIO;
513		}
514		if (flags & I2C_M_RD) {
515			bit_dbg(3, &i2c_adap->dev, "emitting repeated "
516				"start condition\n");
517			i2c_repstart(adap);
518			/* okay, now switch into reading mode */
519			addr |= 0x01;
520			ret = try_address(i2c_adap, addr, retries);
521			if ((ret != 1) && !nak_ok) {
522				dev_err(&i2c_adap->dev,
523					"died at repeated address code\n");
524				return -EIO;
525			}
526		}
527	} else {		/* normal 7bit address	*/
528		addr = msg->addr << 1;
529		if (flags & I2C_M_RD)
530			addr |= 1;
531		if (flags & I2C_M_REV_DIR_ADDR)
532			addr ^= 1;
533		ret = try_address(i2c_adap, addr, retries);
534		if ((ret != 1) && !nak_ok)
535			return -ENXIO;
536	}
537
538	return 0;
539}
540
541static int bit_xfer(struct i2c_adapter *i2c_adap,
542		    struct i2c_msg msgs[], int num)
543{
544	struct i2c_msg *pmsg;
545	struct i2c_algo_bit_data *adap = i2c_adap->algo_data;
546	int i, ret;
547	unsigned short nak_ok;
548
549	if (adap->pre_xfer) {
550		ret = adap->pre_xfer(i2c_adap);
551		if (ret < 0)
552			return ret;
553	}
554
555	bit_dbg(3, &i2c_adap->dev, "emitting start condition\n");
556	i2c_start(adap);
557	for (i = 0; i < num; i++) {
558		pmsg = &msgs[i];
559		nak_ok = pmsg->flags & I2C_M_IGNORE_NAK;
560		if (!(pmsg->flags & I2C_M_NOSTART)) {
561			if (i) {
562				bit_dbg(3, &i2c_adap->dev, "emitting "
563					"repeated start condition\n");
564				i2c_repstart(adap);
565			}
566			ret = bit_doAddress(i2c_adap, pmsg);
567			if ((ret != 0) && !nak_ok) {
568				bit_dbg(1, &i2c_adap->dev, "NAK from "
569					"device addr 0x%02x msg #%d\n",
570					msgs[i].addr, i);
571				goto bailout;
572			}
573		}
574		if (pmsg->flags & I2C_M_RD) {
575			/* read bytes into buffer*/
576			ret = readbytes(i2c_adap, pmsg);
577			if (ret >= 1)
578				bit_dbg(2, &i2c_adap->dev, "read %d byte%s\n",
579					ret, ret == 1 ? "" : "s");
580			if (ret < pmsg->len) {
581				if (ret >= 0)
582					ret = -EIO;
583				goto bailout;
584			}
585		} else {
586			/* write bytes from buffer */
587			ret = sendbytes(i2c_adap, pmsg);
588			if (ret >= 1)
589				bit_dbg(2, &i2c_adap->dev, "wrote %d byte%s\n",
590					ret, ret == 1 ? "" : "s");
591			if (ret < pmsg->len) {
592				if (ret >= 0)
593					ret = -EIO;
594				goto bailout;
595			}
596		}
597	}
598	ret = i;
599
600bailout:
601	bit_dbg(3, &i2c_adap->dev, "emitting stop condition\n");
602	i2c_stop(adap);
603
604	if (adap->post_xfer)
605		adap->post_xfer(i2c_adap);
606	return ret;
607}
608
609static u32 bit_func(struct i2c_adapter *adap)
610{
611	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
612	       I2C_FUNC_SMBUS_READ_BLOCK_DATA |
613	       I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
614	       I2C_FUNC_10BIT_ADDR | I2C_FUNC_PROTOCOL_MANGLING;
615}
616
617
618/* -----exported algorithm data: -------------------------------------	*/
619
620const struct i2c_algorithm i2c_bit_algo = {
621	.master_xfer	= bit_xfer,
622	.functionality	= bit_func,
623};
624EXPORT_SYMBOL(i2c_bit_algo);
625
626/*
627 * registering functions to load algorithms at runtime
628 */
629static int __i2c_bit_add_bus(struct i2c_adapter *adap,
630			     int (*add_adapter)(struct i2c_adapter *))
631{
632	struct i2c_algo_bit_data *bit_adap = adap->algo_data;
633	int ret;
634
635	if (bit_test) {
636		ret = test_bus(adap);
637		if (bit_test >= 2 && ret < 0)
638			return -ENODEV;
639	}
640
641	/* register new adapter to i2c module... */
642	adap->algo = &i2c_bit_algo;
643	adap->retries = 3;
644
645	ret = add_adapter(adap);
646	if (ret < 0)
647		return ret;
648
649	/* Complain if SCL can't be read */
650	if (bit_adap->getscl == NULL) {
651		dev_warn(&adap->dev, "Not I2C compliant: can't read SCL\n");
652		dev_warn(&adap->dev, "Bus may be unreliable\n");
653	}
654	return 0;
655}
656
657int i2c_bit_add_bus(struct i2c_adapter *adap)
658{
659	return __i2c_bit_add_bus(adap, i2c_add_adapter);
660}
661EXPORT_SYMBOL(i2c_bit_add_bus);
662
663int i2c_bit_add_numbered_bus(struct i2c_adapter *adap)
664{
665	return __i2c_bit_add_bus(adap, i2c_add_numbered_adapter);
666}
667EXPORT_SYMBOL(i2c_bit_add_numbered_bus);
668
669MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
670MODULE_DESCRIPTION("I2C-Bus bit-banging algorithm");
671MODULE_LICENSE("GPL");
672