1 /*
2  * SuperH Mobile I2C Controller
3  *
4  * Copyright (C) 2008 Magnus Damm
5  *
6  * Portions of the code based on out-of-tree driver i2c-sh7343.c
7  * Copyright (c) 2006 Carlos Munoz <carlos@kenati.com>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 
23 #include <linux/kernel.h>
24 #include <linux/module.h>
25 #include <linux/init.h>
26 #include <linux/delay.h>
27 #include <linux/platform_device.h>
28 #include <linux/interrupt.h>
29 #include <linux/i2c.h>
30 #include <linux/err.h>
31 #include <linux/clk.h>
32 #include <linux/io.h>
33 
34 /* Transmit operation:                                                      */
35 /*                                                                          */
36 /* 0 byte transmit                                                          */
37 /* BUS:     S     A8     ACK   P                                            */
38 /* IRQ:       DTE   WAIT                                                    */
39 /* ICIC:                                                                    */
40 /* ICCR: 0x94 0x90                                                          */
41 /* ICDR:      A8                                                            */
42 /*                                                                          */
43 /* 1 byte transmit                                                          */
44 /* BUS:     S     A8     ACK   D8(1)   ACK   P                              */
45 /* IRQ:       DTE   WAIT         WAIT                                       */
46 /* ICIC:      -DTE                                                          */
47 /* ICCR: 0x94       0x90                                                    */
48 /* ICDR:      A8    D8(1)                                                   */
49 /*                                                                          */
50 /* 2 byte transmit                                                          */
51 /* BUS:     S     A8     ACK   D8(1)   ACK   D8(2)   ACK   P                */
52 /* IRQ:       DTE   WAIT         WAIT          WAIT                         */
53 /* ICIC:      -DTE                                                          */
54 /* ICCR: 0x94                    0x90                                       */
55 /* ICDR:      A8    D8(1)        D8(2)                                      */
56 /*                                                                          */
57 /* 3 bytes or more, +---------+ gets repeated                               */
58 /*                                                                          */
59 /*                                                                          */
60 /* Receive operation:                                                       */
61 /*                                                                          */
62 /* 0 byte receive - not supported since slave may hold SDA low              */
63 /*                                                                          */
64 /* 1 byte receive       [TX] | [RX]                                         */
65 /* BUS:     S     A8     ACK | D8(1)   ACK   P                              */
66 /* IRQ:       DTE   WAIT     |   WAIT     DTE                               */
67 /* ICIC:      -DTE           |   +DTE                                       */
68 /* ICCR: 0x94       0x81     |   0xc0                                       */
69 /* ICDR:      A8             |            D8(1)                             */
70 /*                                                                          */
71 /* 2 byte receive        [TX]| [RX]                                         */
72 /* BUS:     S     A8     ACK | D8(1)   ACK   D8(2)   ACK   P                */
73 /* IRQ:       DTE   WAIT     |   WAIT          WAIT     DTE                 */
74 /* ICIC:      -DTE           |                 +DTE                         */
75 /* ICCR: 0x94       0x81     |                 0xc0                         */
76 /* ICDR:      A8             |                 D8(1)    D8(2)               */
77 /*                                                                          */
78 /* 3 byte receive       [TX] | [RX]                                         */
79 /* BUS:     S     A8     ACK | D8(1)   ACK   D8(2)   ACK   D8(3)   ACK    P */
80 /* IRQ:       DTE   WAIT     |   WAIT          WAIT         WAIT      DTE   */
81 /* ICIC:      -DTE           |                              +DTE            */
82 /* ICCR: 0x94       0x81     |                              0xc0            */
83 /* ICDR:      A8             |                 D8(1)        D8(2)     D8(3) */
84 /*                                                                          */
85 /* 4 bytes or more, this part is repeated    +---------+                    */
86 /*                                                                          */
87 /*                                                                          */
88 /* Interrupt order and BUSY flag                                            */
89 /*     ___                                                 _                */
90 /* SDA ___\___XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXAAAAAAAAA___/                 */
91 /* SCL      \_/1\_/2\_/3\_/4\_/5\_/6\_/7\_/8\___/9\_____/                   */
92 /*                                                                          */
93 /*        S   D7  D6  D5  D4  D3  D2  D1  D0              P                 */
94 /*                                           ___                            */
95 /* WAIT IRQ ________________________________/   \___________                */
96 /* TACK IRQ ____________________________________/   \_______                */
97 /* DTE  IRQ __________________________________________/   \_                */
98 /* AL   IRQ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX                */
99 /*         _______________________________________________                  */
100 /* BUSY __/                                               \_                */
101 /*                                                                          */
102 
103 enum sh_mobile_i2c_op {
104 	OP_START = 0,
105 	OP_TX_FIRST,
106 	OP_TX,
107 	OP_TX_STOP,
108 	OP_TX_TO_RX,
109 	OP_RX,
110 	OP_RX_STOP,
111 	OP_RX_STOP_DATA,
112 };
113 
114 struct sh_mobile_i2c_data {
115 	struct device *dev;
116 	void __iomem *reg;
117 	struct i2c_adapter adap;
118 
119 	struct clk *clk;
120 	u_int8_t iccl;
121 	u_int8_t icch;
122 
123 	spinlock_t lock;
124 	wait_queue_head_t wait;
125 	struct i2c_msg *msg;
126 	int pos;
127 	int sr;
128 };
129 
130 #define NORMAL_SPEED		100000 /* FAST_SPEED 400000 */
131 
132 /* Register offsets */
133 #define ICDR(pd)		(pd->reg + 0x00)
134 #define ICCR(pd)		(pd->reg + 0x04)
135 #define ICSR(pd)		(pd->reg + 0x08)
136 #define ICIC(pd)		(pd->reg + 0x0c)
137 #define ICCL(pd)		(pd->reg + 0x10)
138 #define ICCH(pd)		(pd->reg + 0x14)
139 
140 /* Register bits */
141 #define ICCR_ICE		0x80
142 #define ICCR_RACK		0x40
143 #define ICCR_TRS		0x10
144 #define ICCR_BBSY		0x04
145 #define ICCR_SCP		0x01
146 
147 #define ICSR_SCLM		0x80
148 #define ICSR_SDAM		0x40
149 #define SW_DONE			0x20
150 #define ICSR_BUSY		0x10
151 #define ICSR_AL			0x08
152 #define ICSR_TACK		0x04
153 #define ICSR_WAIT		0x02
154 #define ICSR_DTE		0x01
155 
156 #define ICIC_ALE		0x08
157 #define ICIC_TACKE		0x04
158 #define ICIC_WAITE		0x02
159 #define ICIC_DTEE		0x01
160 
161 static void activate_ch(struct sh_mobile_i2c_data *pd)
162 {
163 	unsigned long i2c_clk;
164 	u_int32_t num;
165 	u_int32_t denom;
166 	u_int32_t tmp;
167 
168 	/* Make sure the clock is enabled */
169 	clk_enable(pd->clk);
170 
171 	/* Get clock rate after clock is enabled */
172 	i2c_clk = clk_get_rate(pd->clk);
173 
174 	/* Calculate the value for iccl. From the data sheet:
175 	 * iccl = (p clock / transfer rate) * (L / (L + H))
176 	 * where L and H are the SCL low/high ratio (5/4 in this case).
177 	 * We also round off the result.
178 	 */
179 	num = i2c_clk * 5;
180 	denom = NORMAL_SPEED * 9;
181 	tmp = num * 10 / denom;
182 	if (tmp % 10 >= 5)
183 		pd->iccl = (u_int8_t)((num/denom) + 1);
184 	else
185 		pd->iccl = (u_int8_t)(num/denom);
186 
187 	/* Calculate the value for icch. From the data sheet:
188 	   icch = (p clock / transfer rate) * (H / (L + H)) */
189 	num = i2c_clk * 4;
190 	tmp = num * 10 / denom;
191 	if (tmp % 10 >= 5)
192 		pd->icch = (u_int8_t)((num/denom) + 1);
193 	else
194 		pd->icch = (u_int8_t)(num/denom);
195 
196 	/* Enable channel and configure rx ack */
197 	iowrite8(ioread8(ICCR(pd)) | ICCR_ICE, ICCR(pd));
198 
199 	/* Mask all interrupts */
200 	iowrite8(0, ICIC(pd));
201 
202 	/* Set the clock */
203 	iowrite8(pd->iccl, ICCL(pd));
204 	iowrite8(pd->icch, ICCH(pd));
205 }
206 
207 static void deactivate_ch(struct sh_mobile_i2c_data *pd)
208 {
209 	/* Clear/disable interrupts */
210 	iowrite8(0, ICSR(pd));
211 	iowrite8(0, ICIC(pd));
212 
213 	/* Disable channel */
214 	iowrite8(ioread8(ICCR(pd)) & ~ICCR_ICE, ICCR(pd));
215 
216 	/* Disable clock */
217 	clk_disable(pd->clk);
218 }
219 
220 static unsigned char i2c_op(struct sh_mobile_i2c_data *pd,
221 			    enum sh_mobile_i2c_op op, unsigned char data)
222 {
223 	unsigned char ret = 0;
224 	unsigned long flags;
225 
226 	dev_dbg(pd->dev, "op %d, data in 0x%02x\n", op, data);
227 
228 	spin_lock_irqsave(&pd->lock, flags);
229 
230 	switch (op) {
231 	case OP_START: /* issue start and trigger DTE interrupt */
232 		iowrite8(0x94, ICCR(pd));
233 		break;
234 	case OP_TX_FIRST: /* disable DTE interrupt and write data */
235 		iowrite8(ICIC_WAITE | ICIC_ALE | ICIC_TACKE, ICIC(pd));
236 		iowrite8(data, ICDR(pd));
237 		break;
238 	case OP_TX: /* write data */
239 		iowrite8(data, ICDR(pd));
240 		break;
241 	case OP_TX_STOP: /* write data and issue a stop afterwards */
242 		iowrite8(data, ICDR(pd));
243 		iowrite8(0x90, ICCR(pd));
244 		break;
245 	case OP_TX_TO_RX: /* select read mode */
246 		iowrite8(0x81, ICCR(pd));
247 		break;
248 	case OP_RX: /* just read data */
249 		ret = ioread8(ICDR(pd));
250 		break;
251 	case OP_RX_STOP: /* enable DTE interrupt, issue stop */
252 		iowrite8(ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE,
253 			 ICIC(pd));
254 		iowrite8(0xc0, ICCR(pd));
255 		break;
256 	case OP_RX_STOP_DATA: /* enable DTE interrupt, read data, issue stop */
257 		iowrite8(ICIC_DTEE | ICIC_WAITE | ICIC_ALE | ICIC_TACKE,
258 			 ICIC(pd));
259 		ret = ioread8(ICDR(pd));
260 		iowrite8(0xc0, ICCR(pd));
261 		break;
262 	}
263 
264 	spin_unlock_irqrestore(&pd->lock, flags);
265 
266 	dev_dbg(pd->dev, "op %d, data out 0x%02x\n", op, ret);
267 	return ret;
268 }
269 
270 static int sh_mobile_i2c_is_first_byte(struct sh_mobile_i2c_data *pd)
271 {
272 	if (pd->pos == -1)
273 		return 1;
274 
275 	return 0;
276 }
277 
278 static int sh_mobile_i2c_is_last_byte(struct sh_mobile_i2c_data *pd)
279 {
280 	if (pd->pos == (pd->msg->len - 1))
281 		return 1;
282 
283 	return 0;
284 }
285 
286 static void sh_mobile_i2c_get_data(struct sh_mobile_i2c_data *pd,
287 				   unsigned char *buf)
288 {
289 	switch (pd->pos) {
290 	case -1:
291 		*buf = (pd->msg->addr & 0x7f) << 1;
292 		*buf |= (pd->msg->flags & I2C_M_RD) ? 1 : 0;
293 		break;
294 	default:
295 		*buf = pd->msg->buf[pd->pos];
296 	}
297 }
298 
299 static int sh_mobile_i2c_isr_tx(struct sh_mobile_i2c_data *pd)
300 {
301 	unsigned char data;
302 
303 	if (pd->pos == pd->msg->len)
304 		return 1;
305 
306 	sh_mobile_i2c_get_data(pd, &data);
307 
308 	if (sh_mobile_i2c_is_last_byte(pd))
309 		i2c_op(pd, OP_TX_STOP, data);
310 	else if (sh_mobile_i2c_is_first_byte(pd))
311 		i2c_op(pd, OP_TX_FIRST, data);
312 	else
313 		i2c_op(pd, OP_TX, data);
314 
315 	pd->pos++;
316 	return 0;
317 }
318 
319 static int sh_mobile_i2c_isr_rx(struct sh_mobile_i2c_data *pd)
320 {
321 	unsigned char data;
322 	int real_pos;
323 
324 	do {
325 		if (pd->pos <= -1) {
326 			sh_mobile_i2c_get_data(pd, &data);
327 
328 			if (sh_mobile_i2c_is_first_byte(pd))
329 				i2c_op(pd, OP_TX_FIRST, data);
330 			else
331 				i2c_op(pd, OP_TX, data);
332 			break;
333 		}
334 
335 		if (pd->pos == 0) {
336 			i2c_op(pd, OP_TX_TO_RX, 0);
337 			break;
338 		}
339 
340 		real_pos = pd->pos - 2;
341 
342 		if (pd->pos == pd->msg->len) {
343 			if (real_pos < 0) {
344 				i2c_op(pd, OP_RX_STOP, 0);
345 				break;
346 			}
347 			data = i2c_op(pd, OP_RX_STOP_DATA, 0);
348 		} else
349 			data = i2c_op(pd, OP_RX, 0);
350 
351 		if (real_pos >= 0)
352 			pd->msg->buf[real_pos] = data;
353 	} while (0);
354 
355 	pd->pos++;
356 	return pd->pos == (pd->msg->len + 2);
357 }
358 
359 static irqreturn_t sh_mobile_i2c_isr(int irq, void *dev_id)
360 {
361 	struct platform_device *dev = dev_id;
362 	struct sh_mobile_i2c_data *pd = platform_get_drvdata(dev);
363 	unsigned char sr;
364 	int wakeup;
365 
366 	sr = ioread8(ICSR(pd));
367 	pd->sr |= sr; /* remember state */
368 
369 	dev_dbg(pd->dev, "i2c_isr 0x%02x 0x%02x %s %d %d!\n", sr, pd->sr,
370 	       (pd->msg->flags & I2C_M_RD) ? "read" : "write",
371 	       pd->pos, pd->msg->len);
372 
373 	if (sr & (ICSR_AL | ICSR_TACK)) {
374 		/* don't interrupt transaction - continue to issue stop */
375 		iowrite8(sr & ~(ICSR_AL | ICSR_TACK), ICSR(pd));
376 		wakeup = 0;
377 	} else if (pd->msg->flags & I2C_M_RD)
378 		wakeup = sh_mobile_i2c_isr_rx(pd);
379 	else
380 		wakeup = sh_mobile_i2c_isr_tx(pd);
381 
382 	if (sr & ICSR_WAIT) /* TODO: add delay here to support slow acks */
383 		iowrite8(sr & ~ICSR_WAIT, ICSR(pd));
384 
385 	if (wakeup) {
386 		pd->sr |= SW_DONE;
387 		wake_up(&pd->wait);
388 	}
389 
390 	return IRQ_HANDLED;
391 }
392 
393 static int start_ch(struct sh_mobile_i2c_data *pd, struct i2c_msg *usr_msg)
394 {
395 	if (usr_msg->len == 0 && (usr_msg->flags & I2C_M_RD)) {
396 		dev_err(pd->dev, "Unsupported zero length i2c read\n");
397 		return -EIO;
398 	}
399 
400 	/* Initialize channel registers */
401 	iowrite8(ioread8(ICCR(pd)) & ~ICCR_ICE, ICCR(pd));
402 
403 	/* Enable channel and configure rx ack */
404 	iowrite8(ioread8(ICCR(pd)) | ICCR_ICE, ICCR(pd));
405 
406 	/* Set the clock */
407 	iowrite8(pd->iccl, ICCL(pd));
408 	iowrite8(pd->icch, ICCH(pd));
409 
410 	pd->msg = usr_msg;
411 	pd->pos = -1;
412 	pd->sr = 0;
413 
414 	/* Enable all interrupts to begin with */
415 	iowrite8(ICIC_WAITE | ICIC_ALE | ICIC_TACKE | ICIC_DTEE, ICIC(pd));
416 	return 0;
417 }
418 
419 static int sh_mobile_i2c_xfer(struct i2c_adapter *adapter,
420 			      struct i2c_msg *msgs,
421 			      int num)
422 {
423 	struct sh_mobile_i2c_data *pd = i2c_get_adapdata(adapter);
424 	struct i2c_msg	*msg;
425 	int err = 0;
426 	u_int8_t val;
427 	int i, k, retry_count;
428 
429 	activate_ch(pd);
430 
431 	/* Process all messages */
432 	for (i = 0; i < num; i++) {
433 		msg = &msgs[i];
434 
435 		err = start_ch(pd, msg);
436 		if (err)
437 			break;
438 
439 		i2c_op(pd, OP_START, 0);
440 
441 		/* The interrupt handler takes care of the rest... */
442 		k = wait_event_timeout(pd->wait,
443 				       pd->sr & (ICSR_TACK | SW_DONE),
444 				       5 * HZ);
445 		if (!k)
446 			dev_err(pd->dev, "Transfer request timed out\n");
447 
448 		retry_count = 1000;
449 again:
450 		val = ioread8(ICSR(pd));
451 
452 		dev_dbg(pd->dev, "val 0x%02x pd->sr 0x%02x\n", val, pd->sr);
453 
454 		/* the interrupt handler may wake us up before the
455 		 * transfer is finished, so poll the hardware
456 		 * until we're done.
457 		 */
458 		if (val & ICSR_BUSY) {
459 			udelay(10);
460 			if (retry_count--)
461 				goto again;
462 
463 			err = -EIO;
464 			dev_err(pd->dev, "Polling timed out\n");
465 			break;
466 		}
467 
468 		/* handle missing acknowledge and arbitration lost */
469 		if ((val | pd->sr) & (ICSR_TACK | ICSR_AL)) {
470 			err = -EIO;
471 			break;
472 		}
473 	}
474 
475 	deactivate_ch(pd);
476 
477 	if (!err)
478 		err = num;
479 	return err;
480 }
481 
482 static u32 sh_mobile_i2c_func(struct i2c_adapter *adapter)
483 {
484 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
485 }
486 
487 static struct i2c_algorithm sh_mobile_i2c_algorithm = {
488 	.functionality	= sh_mobile_i2c_func,
489 	.master_xfer	= sh_mobile_i2c_xfer,
490 };
491 
492 static int sh_mobile_i2c_hook_irqs(struct platform_device *dev, int hook)
493 {
494 	struct resource *res;
495 	int ret = -ENXIO;
496 	int q, m;
497 	int k = 0;
498 	int n = 0;
499 
500 	while ((res = platform_get_resource(dev, IORESOURCE_IRQ, k))) {
501 		for (n = res->start; hook && n <= res->end; n++) {
502 			if (request_irq(n, sh_mobile_i2c_isr, IRQF_DISABLED,
503 					dev_name(&dev->dev), dev))
504 				goto rollback;
505 		}
506 		k++;
507 	}
508 
509 	if (hook)
510 		return k > 0 ? 0 : -ENOENT;
511 
512 	k--;
513 	ret = 0;
514 
515  rollback:
516 	for (q = k; k >= 0; k--) {
517 		for (m = n; m >= res->start; m--)
518 			free_irq(m, dev);
519 
520 		res = platform_get_resource(dev, IORESOURCE_IRQ, k - 1);
521 		m = res->end;
522 	}
523 
524 	return ret;
525 }
526 
527 static int sh_mobile_i2c_probe(struct platform_device *dev)
528 {
529 	struct sh_mobile_i2c_data *pd;
530 	struct i2c_adapter *adap;
531 	struct resource *res;
532 	char clk_name[8];
533 	int size;
534 	int ret;
535 
536 	pd = kzalloc(sizeof(struct sh_mobile_i2c_data), GFP_KERNEL);
537 	if (pd == NULL) {
538 		dev_err(&dev->dev, "cannot allocate private data\n");
539 		return -ENOMEM;
540 	}
541 
542 	snprintf(clk_name, sizeof(clk_name), "i2c%d", dev->id);
543 	pd->clk = clk_get(&dev->dev, clk_name);
544 	if (IS_ERR(pd->clk)) {
545 		dev_err(&dev->dev, "cannot get clock \"%s\"\n", clk_name);
546 		ret = PTR_ERR(pd->clk);
547 		goto err;
548 	}
549 
550 	ret = sh_mobile_i2c_hook_irqs(dev, 1);
551 	if (ret) {
552 		dev_err(&dev->dev, "cannot request IRQ\n");
553 		goto err_clk;
554 	}
555 
556 	pd->dev = &dev->dev;
557 	platform_set_drvdata(dev, pd);
558 
559 	res = platform_get_resource(dev, IORESOURCE_MEM, 0);
560 	if (res == NULL) {
561 		dev_err(&dev->dev, "cannot find IO resource\n");
562 		ret = -ENOENT;
563 		goto err_irq;
564 	}
565 
566 	size = (res->end - res->start) + 1;
567 
568 	pd->reg = ioremap(res->start, size);
569 	if (pd->reg == NULL) {
570 		dev_err(&dev->dev, "cannot map IO\n");
571 		ret = -ENXIO;
572 		goto err_irq;
573 	}
574 
575 	/* setup the private data */
576 	adap = &pd->adap;
577 	i2c_set_adapdata(adap, pd);
578 
579 	adap->owner = THIS_MODULE;
580 	adap->algo = &sh_mobile_i2c_algorithm;
581 	adap->dev.parent = &dev->dev;
582 	adap->retries = 5;
583 	adap->nr = dev->id;
584 
585 	strlcpy(adap->name, dev->name, sizeof(adap->name));
586 
587 	spin_lock_init(&pd->lock);
588 	init_waitqueue_head(&pd->wait);
589 
590 	ret = i2c_add_numbered_adapter(adap);
591 	if (ret < 0) {
592 		dev_err(&dev->dev, "cannot add numbered adapter\n");
593 		goto err_all;
594 	}
595 
596 	return 0;
597 
598  err_all:
599 	iounmap(pd->reg);
600  err_irq:
601 	sh_mobile_i2c_hook_irqs(dev, 0);
602  err_clk:
603 	clk_put(pd->clk);
604  err:
605 	kfree(pd);
606 	return ret;
607 }
608 
609 static int sh_mobile_i2c_remove(struct platform_device *dev)
610 {
611 	struct sh_mobile_i2c_data *pd = platform_get_drvdata(dev);
612 
613 	i2c_del_adapter(&pd->adap);
614 	iounmap(pd->reg);
615 	sh_mobile_i2c_hook_irqs(dev, 0);
616 	clk_put(pd->clk);
617 	kfree(pd);
618 	return 0;
619 }
620 
621 static struct platform_driver sh_mobile_i2c_driver = {
622 	.driver		= {
623 		.name		= "i2c-sh_mobile",
624 		.owner		= THIS_MODULE,
625 	},
626 	.probe		= sh_mobile_i2c_probe,
627 	.remove		= sh_mobile_i2c_remove,
628 };
629 
630 static int __init sh_mobile_i2c_adap_init(void)
631 {
632 	return platform_driver_register(&sh_mobile_i2c_driver);
633 }
634 
635 static void __exit sh_mobile_i2c_adap_exit(void)
636 {
637 	platform_driver_unregister(&sh_mobile_i2c_driver);
638 }
639 
640 module_init(sh_mobile_i2c_adap_init);
641 module_exit(sh_mobile_i2c_adap_exit);
642 
643 MODULE_DESCRIPTION("SuperH Mobile I2C Bus Controller driver");
644 MODULE_AUTHOR("Magnus Damm");
645 MODULE_LICENSE("GPL v2");
646