xref: /freebsd/sys/arm/ti/ti_i2c.c (revision 145992504973bd16cf3518af9ba5ce185fefa82a)
1 /*-
2  * Copyright (c) 2011
3  *	Ben Gray <ben.r.gray@gmail.com>.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /**
29  * Driver for the I2C module on the TI SoC.
30  *
31  * This driver is heavily based on the TWI driver for the AT91 (at91_twi.c).
32  *
33  * CAUTION: The I2Ci registers are limited to 16 bit and 8 bit data accesses,
34  * 32 bit data access is not allowed and can corrupt register content.
35  *
36  * This driver currently doesn't use DMA for the transfer, although I hope to
37  * incorporate that sometime in the future.  The idea being that for transaction
38  * larger than a certain size the DMA engine is used, for anything less the
39  * normal interrupt/fifo driven option is used.
40  *
41  *
42  * WARNING: This driver uses mtx_sleep and interrupts to perform transactions,
43  * which means you can't do a transaction during startup before the interrupts
44  * have been enabled.  Hint - the freebsd function config_intrhook_establish().
45  */
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/bus.h>
53 #include <sys/conf.h>
54 #include <sys/kernel.h>
55 #include <sys/lock.h>
56 #include <sys/mbuf.h>
57 #include <sys/malloc.h>
58 #include <sys/module.h>
59 #include <sys/mutex.h>
60 #include <sys/rman.h>
61 #include <machine/bus.h>
62 
63 #include <dev/fdt/fdt_common.h>
64 #include <dev/ofw/openfirm.h>
65 #include <dev/ofw/ofw_bus.h>
66 #include <dev/ofw/ofw_bus_subr.h>
67 
68 #include <arm/ti/ti_prcm.h>
69 #include <arm/ti/ti_i2c.h>
70 
71 #include <dev/iicbus/iiconf.h>
72 #include <dev/iicbus/iicbus.h>
73 
74 #include "iicbus_if.h"
75 
76 /**
77  *	I2C device driver context, a pointer to this is stored in the device
78  *	driver structure.
79  */
80 struct ti_i2c_softc
81 {
82 	device_t		sc_dev;
83 	uint32_t		device_id;
84 	struct resource*	sc_irq_res;
85 	struct resource*	sc_mem_res;
86 	device_t		sc_iicbus;
87 
88 	void*			sc_irq_h;
89 
90 	struct mtx		sc_mtx;
91 
92 	volatile uint16_t	sc_stat_flags;	/* contains the status flags last IRQ */
93 
94 	uint16_t		sc_i2c_addr;
95 	uint16_t		sc_rev;
96 };
97 
98 struct ti_i2c_clock_config
99 {
100 	int speed;
101 	int bitrate;
102 	uint8_t psc;		/* Fast/Standard mode prescale divider */
103 	uint8_t scll;		/* Fast/Standard mode SCL low time */
104 	uint8_t sclh;		/* Fast/Standard mode SCL high time */
105 	uint8_t hsscll;		/* High Speed mode SCL low time */
106 	uint8_t hssclh;		/* High Speed mode SCL high time */
107 };
108 
109 static struct ti_i2c_clock_config ti_i2c_clock_configs[] = {
110 
111 #if defined(SOC_OMAP4)
112 	{ IIC_SLOW,      100000, 23,  13,  15, 0,  0},
113 	{ IIC_FAST,      400000,  9,   5,   7, 0,  0},
114 	{ IIC_FASTEST,	3310000,  1, 113, 115, 7, 10},
115 #elif defined(SOC_TI_AM335X)
116 	{ IIC_SLOW,      100000,  3,  53,  55, 0,  0},
117 	{ IIC_FAST,      400000,  3,   8,  10, 0,  0},
118 	{ IIC_FASTEST,   400000,  3,   8,  10, 0,  0}, /* This might be higher */
119 #else
120 #error "TI I2C driver is not supported on this SoC"
121 #endif
122 	{ -1, 0 }
123 };
124 
125 
126 #define TI_I2C_REV1  0x003C      /* OMAP3 */
127 #define TI_I2C_REV2  0x000A      /* OMAP4 */
128 
129 /**
130  *	Locking macros used throughout the driver
131  */
132 #define TI_I2C_LOCK(_sc)             mtx_lock(&(_sc)->sc_mtx)
133 #define	TI_I2C_UNLOCK(_sc)           mtx_unlock(&(_sc)->sc_mtx)
134 #define TI_I2C_LOCK_INIT(_sc) \
135 	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->sc_dev), \
136 	         "ti_i2c", MTX_DEF)
137 #define TI_I2C_LOCK_DESTROY(_sc)      mtx_destroy(&_sc->sc_mtx);
138 #define TI_I2C_ASSERT_LOCKED(_sc)     mtx_assert(&_sc->sc_mtx, MA_OWNED);
139 #define TI_I2C_ASSERT_UNLOCKED(_sc)   mtx_assert(&_sc->sc_mtx, MA_NOTOWNED);
140 
141 #ifdef DEBUG
142 #define ti_i2c_dbg(_sc, fmt, args...) \
143     device_printf((_sc)->sc_dev, fmt, ##args)
144 #else
145 #define ti_i2c_dbg(_sc, fmt, args...)
146 #endif
147 
148 static devclass_t ti_i2c_devclass;
149 
150 /* bus entry points */
151 
152 static int ti_i2c_probe(device_t dev);
153 static int ti_i2c_attach(device_t dev);
154 static int ti_i2c_detach(device_t dev);
155 static void ti_i2c_intr(void *);
156 
157 /* OFW routine */
158 static phandle_t ti_i2c_get_node(device_t bus, device_t dev);
159 
160 /* helper routines */
161 static int ti_i2c_activate(device_t dev);
162 static void ti_i2c_deactivate(device_t dev);
163 
164 /**
165  *	ti_i2c_read_2 - reads a 16-bit value from one of the I2C registers
166  *	@sc: I2C device context
167  *	@off: the byte offset within the register bank to read from.
168  *
169  *
170  *	LOCKING:
171  *	No locking required
172  *
173  *	RETURNS:
174  *	16-bit value read from the register.
175  */
176 static inline uint16_t
177 ti_i2c_read_2(struct ti_i2c_softc *sc, bus_size_t off)
178 {
179 	return bus_read_2(sc->sc_mem_res, off);
180 }
181 
182 /**
183  *	ti_i2c_write_2 - writes a 16-bit value to one of the I2C registers
184  *	@sc: I2C device context
185  *	@off: the byte offset within the register bank to read from.
186  *	@val: the value to write into the register
187  *
188  *	LOCKING:
189  *	No locking required
190  *
191  *	RETURNS:
192  *	16-bit value read from the register.
193  */
194 static inline void
195 ti_i2c_write_2(struct ti_i2c_softc *sc, bus_size_t off, uint16_t val)
196 {
197 	bus_write_2(sc->sc_mem_res, off, val);
198 }
199 
200 /**
201  *	ti_i2c_read_reg - reads a 16-bit value from one of the I2C registers
202  *	    take into account revision-dependent register offset
203  *	@sc: I2C device context
204  *	@off: the byte offset within the register bank to read from.
205  *
206  *
207  *	LOCKING:
208  *	No locking required
209  *
210  *	RETURNS:
211  *	16-bit value read from the register.
212  */
213 static inline uint16_t
214 ti_i2c_read_reg(struct ti_i2c_softc *sc, bus_size_t off)
215 {
216 	/* XXXOMAP3: FIXME add registers mapping here */
217 	return bus_read_2(sc->sc_mem_res, off);
218 }
219 
220 /**
221  *	ti_i2c_write_reg - writes a 16-bit value to one of the I2C registers
222  *	    take into account revision-dependent register offset
223  *	@sc: I2C device context
224  *	@off: the byte offset within the register bank to read from.
225  *	@val: the value to write into the register
226  *
227  *	LOCKING:
228  *	No locking required
229  *
230  *	RETURNS:
231  *	16-bit value read from the register.
232  */
233 static inline void
234 ti_i2c_write_reg(struct ti_i2c_softc *sc, bus_size_t off, uint16_t val)
235 {
236 	/* XXXOMAP3: FIXME add registers mapping here */
237 	bus_write_2(sc->sc_mem_res, off, val);
238 }
239 
240 /**
241  *	ti_i2c_set_intr_enable - writes the interrupt enable register
242  *	@sc: I2C device context
243  *	@ie: bitmask of the interrupts to enable
244  *
245  *	This function is needed as writing the I2C_IE register on the OMAP4 devices
246  *	doesn't seem to actually enable the interrupt, rather you have to write
247  *	through the I2C_IRQENABLE_CLR and I2C_IRQENABLE_SET registers.
248  *
249  *	LOCKING:
250  *	No locking required
251  *
252  *	RETURNS:
253  *	Nothing.
254  */
255 static inline void
256 ti_i2c_set_intr_enable(struct ti_i2c_softc *sc, uint16_t ie)
257 {
258 	/* XXXOMAP3: FIXME */
259 	ti_i2c_write_2(sc, I2C_REG_IRQENABLE_CLR, 0xffff);
260 	if (ie)
261 		ti_i2c_write_2(sc, I2C_REG_IRQENABLE_SET, ie);
262 }
263 
264 /**
265  *	ti_i2c_reset - attach function for the driver
266  *	@dev: i2c device handle
267  *
268  *
269  *
270  *	LOCKING:
271  *	Called from timer context
272  *
273  *	RETURNS:
274  *	EH_HANDLED or EH_NOT_HANDLED
275  */
276 static int
277 ti_i2c_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
278 {
279 	struct ti_i2c_softc *sc = device_get_softc(dev);
280 	struct ti_i2c_clock_config *clkcfg;
281 	uint16_t con_reg;
282 
283 	clkcfg = ti_i2c_clock_configs;
284 	while (clkcfg->speed != -1) {
285 		if (clkcfg->speed == speed)
286 			break;
287 		/* take slow if speed is unknown */
288 		if ((speed == IIC_UNKNOWN) && (clkcfg->speed == IIC_SLOW))
289 			break;
290 		clkcfg++;
291 	}
292 	if (clkcfg->speed == -1)
293 		return (EINVAL);
294 
295 	TI_I2C_LOCK(sc);
296 
297 	if (oldaddr)
298 		*oldaddr = sc->sc_i2c_addr;
299 	sc->sc_i2c_addr = addr;
300 
301 	/* First disable the controller while changing the clocks */
302 	con_reg = ti_i2c_read_reg(sc, I2C_REG_CON);
303 	ti_i2c_write_reg(sc, I2C_REG_CON, 0x0000);
304 
305 	/* Program the prescaler */
306 	ti_i2c_write_reg(sc, I2C_REG_PSC, clkcfg->psc);
307 
308 	/* Set the bitrate */
309 	ti_i2c_write_reg(sc, I2C_REG_SCLL, clkcfg->scll | (clkcfg->hsscll<<8));
310 	ti_i2c_write_reg(sc, I2C_REG_SCLH, clkcfg->sclh | (clkcfg->hssclh<<8));
311 
312 	/* Set the remote slave address */
313 	ti_i2c_write_reg(sc, I2C_REG_SA, addr);
314 
315 	/* Check if we are dealing with high speed mode */
316 	if ((clkcfg->hsscll + clkcfg->hssclh) > 0)
317 		con_reg  = I2C_CON_OPMODE_HS;
318 	else
319 		con_reg  = I2C_CON_OPMODE_STD;
320 
321 	/* Enable the I2C module again */
322 	ti_i2c_write_reg(sc, I2C_REG_CON, I2C_CON_I2C_EN | con_reg);
323 
324 	TI_I2C_UNLOCK(sc);
325 
326 	return 0;
327 }
328 
329 /**
330  *	ti_i2c_intr - interrupt handler for the I2C module
331  *	@dev: i2c device handle
332  *
333  *
334  *
335  *	LOCKING:
336  *	Called from timer context
337  *
338  *	RETURNS:
339  *	EH_HANDLED or EH_NOT_HANDLED
340  */
341 static void
342 ti_i2c_intr(void *arg)
343 {
344 	struct ti_i2c_softc *sc = (struct ti_i2c_softc*) arg;
345 	uint16_t status;
346 
347 	status = ti_i2c_read_reg(sc, I2C_REG_STAT);
348 	if (status == 0)
349 		return;
350 
351 	TI_I2C_LOCK(sc);
352 
353 	/* save the flags */
354 	sc->sc_stat_flags |= status;
355 
356 	/* clear the status flags */
357 	ti_i2c_write_reg(sc, I2C_REG_STAT, status);
358 
359 	/* wakeup the process the started the transaction */
360 	wakeup(sc);
361 
362 	TI_I2C_UNLOCK(sc);
363 
364 	return;
365 }
366 
367 /**
368  *	ti_i2c_wait - waits for the specific event to occur
369  *	@sc: i2c driver context
370  *	@flags: the event(s) to wait on, this is a bitmask of the I2C_STAT_??? flags
371  *	@statp: if not null will contain the status flags upon return
372  *	@timo: the number of ticks to wait
373  *
374  *
375  *
376  *	LOCKING:
377  *	The driver context must be locked before calling this function. Internally
378  *	the function sleeps, releasing the lock as it does so, however the lock is
379  *	always retaken before this function returns.
380  *
381  *	RETURNS:
382  *	0 if the event(s) were tripped within timeout period
383  *	EBUSY if timedout waiting for the events
384  *	ENXIO if a NACK event was received
385  */
386 static int
387 ti_i2c_wait(struct ti_i2c_softc *sc, uint16_t flags, uint16_t *statp, int timo)
388 {
389 	int waittime = timo;
390 	int start_ticks = ticks;
391 	int rc;
392 
393 	TI_I2C_ASSERT_LOCKED(sc);
394 
395 	/* check if the condition has already occured, the interrupt routine will
396 	 * clear the status flags.
397 	 */
398 	if ((sc->sc_stat_flags & flags) == 0) {
399 
400 		/* condition(s) haven't occured so sleep on the IRQ */
401 		while (waittime > 0) {
402 
403 			rc = mtx_sleep(sc, &sc->sc_mtx, 0, "I2Cwait", waittime);
404 			if (rc == EWOULDBLOCK) {
405 				/* timed-out, simply break out of the loop */
406 				break;
407 			} else {
408 				/* IRQ has been tripped, but need to sanity check we have the
409 				 * right events in the status flag.
410 				 */
411 				if ((sc->sc_stat_flags & flags) != 0)
412 					break;
413 
414 				/* event hasn't been tripped so wait some more */
415 				waittime -= (ticks - start_ticks);
416 				start_ticks = ticks;
417 			}
418 		}
419 	}
420 
421 	/* copy the actual status bits */
422 	if (statp != NULL)
423 		*statp = sc->sc_stat_flags;
424 
425 	/* return the status found */
426 	if ((sc->sc_stat_flags & flags) != 0)
427 		rc = 0;
428 	else
429 		rc = EBUSY;
430 
431 	/* clear the flags set by the interrupt handler */
432 	sc->sc_stat_flags = 0;
433 
434 	return (rc);
435 }
436 
437 /**
438  *	ti_i2c_wait_for_free_bus - waits for the bus to become free
439  *	@sc: i2c driver context
440  *	@timo: the time to wait for the bus to become free
441  *
442  *
443  *
444  *	LOCKING:
445  *	The driver context must be locked before calling this function. Internally
446  *	the function sleeps, releasing the lock as it does so, however the lock is
447  *	always taken before this function returns.
448  *
449  *	RETURNS:
450  *	0 if the event(s) were tripped within timeout period
451  *	EBUSY if timedout waiting for the events
452  *	ENXIO if a NACK event was received
453  */
454 static int
455 ti_i2c_wait_for_free_bus(struct ti_i2c_softc *sc, int timo)
456 {
457 	/* check if the bus is free, BB bit = 0 */
458 	if ((ti_i2c_read_reg(sc, I2C_REG_STAT) & I2C_STAT_BB) == 0)
459 		return 0;
460 
461 	/* enable bus free interrupts */
462 	ti_i2c_set_intr_enable(sc, I2C_IE_BF);
463 
464 	/* wait for the bus free interrupt to be tripped */
465 	return ti_i2c_wait(sc, I2C_STAT_BF, NULL, timo);
466 }
467 
468 /**
469  *	ti_i2c_read_bytes - attempts to perform a read operation
470  *	@sc: i2c driver context
471  *	@buf: buffer to hold the received bytes
472  *	@len: the number of bytes to read
473  *
474  *	This function assumes the slave address is already set
475  *
476  *	LOCKING:
477  *	The context lock should be held before calling this function
478  *
479  *	RETURNS:
480  *	0 on function succeeded
481  *	EINVAL if invalid message is passed as an arg
482  */
483 static int
484 ti_i2c_read_bytes(struct ti_i2c_softc *sc, uint8_t *buf, uint16_t len)
485 {
486 	int      timo = (hz / 4);
487 	int      err = 0;
488 	uint16_t con_reg;
489 	uint16_t events;
490 	uint16_t status;
491 	uint32_t amount = 0;
492 	uint32_t sofar = 0;
493 	uint32_t i;
494 
495 	/* wait for the bus to become free */
496 	err = ti_i2c_wait_for_free_bus(sc, timo);
497 	if (err != 0) {
498 		device_printf(sc->sc_dev, "bus never freed\n");
499 		return (err);
500 	}
501 
502 	/* set the events to wait for */
503 	events = I2C_IE_RDR |   /* Receive draining interrupt */
504 	         I2C_IE_RRDY |  /* Receive Data Ready interrupt */
505 	         I2C_IE_ARDY |  /* Register Access Ready interrupt */
506 	         I2C_IE_NACK |  /* No Acknowledgment interrupt */
507 	         I2C_IE_AL;
508 
509 	/* enable interrupts for the events we want */
510 	ti_i2c_set_intr_enable(sc, events);
511 
512 	/* write the number of bytes to read */
513 	ti_i2c_write_reg(sc, I2C_REG_CNT, len);
514 
515 	/* clear the write bit and initiate the read transaction. Setting the STT
516 	 * (start) bit initiates the transfer.
517 	 */
518 	con_reg = ti_i2c_read_reg(sc, I2C_REG_CON);
519 	con_reg &= ~I2C_CON_TRX;
520 	con_reg |=  I2C_CON_MST | I2C_CON_STT | I2C_CON_STP;
521 	ti_i2c_write_reg(sc, I2C_REG_CON, con_reg);
522 
523 	/* reading loop */
524 	while (1) {
525 
526 		/* wait for an event */
527 		err = ti_i2c_wait(sc, events, &status, timo);
528 		if (err != 0) {
529 			break;
530 		}
531 
532 		/* check for the error conditions */
533 		if (status & I2C_STAT_NACK) {
534 			/* no ACK from slave */
535 			ti_i2c_dbg(sc, "NACK\n");
536 			err = ENXIO;
537 			break;
538 		}
539 		if (status & I2C_STAT_AL) {
540 			/* arbitration lost */
541 			ti_i2c_dbg(sc, "Arbitration lost\n");
542 			err = ENXIO;
543 			break;
544 		}
545 
546 		/* check if we have finished */
547 		if (status & I2C_STAT_ARDY) {
548 			/* register access ready - transaction complete basically */
549 			ti_i2c_dbg(sc, "ARDY transaction complete\n");
550 			err = 0;
551 			break;
552 		}
553 
554 		/* read some data */
555 		if (status & I2C_STAT_RDR) {
556 			/* Receive draining interrupt - last data received */
557 			ti_i2c_dbg(sc, "Receive draining interrupt\n");
558 
559 			/* get the number of bytes in the FIFO */
560 			amount = ti_i2c_read_reg(sc, I2C_REG_BUFSTAT);
561 			amount >>= 8;
562 			amount &= 0x3f;
563 		}
564 		else if (status & I2C_STAT_RRDY) {
565 			/* Receive data ready interrupt - enough data received */
566 			ti_i2c_dbg(sc, "Receive data ready interrupt\n");
567 
568 			/* get the number of bytes in the FIFO */
569 			amount = ti_i2c_read_reg(sc, I2C_REG_BUF);
570 			amount >>= 8;
571 			amount &= 0x3f;
572 			amount += 1;
573 		}
574 
575 		/* sanity check we haven't overwritten the array */
576 		if ((sofar + amount) > len) {
577 			ti_i2c_dbg(sc, "to many bytes to read\n");
578 			amount = (len - sofar);
579 		}
580 
581 		/* read the bytes from the fifo */
582 		for (i = 0; i < amount; i++) {
583 			buf[sofar++] = (uint8_t)(ti_i2c_read_reg(sc, I2C_REG_DATA) & 0xff);
584 		}
585 
586 		/* attempt to clear the receive ready bits */
587 		ti_i2c_write_reg(sc, I2C_REG_STAT, I2C_STAT_RDR | I2C_STAT_RRDY);
588 	}
589 
590 	/* reset the registers regardless if there was an error or not */
591 	ti_i2c_set_intr_enable(sc, 0x0000);
592 	ti_i2c_write_reg(sc, I2C_REG_CON, I2C_CON_I2C_EN | I2C_CON_MST | I2C_CON_STP);
593 
594 	return (err);
595 }
596 
597 /**
598  *	ti_i2c_write_bytes - attempts to perform a read operation
599  *	@sc: i2c driver context
600  *	@buf: buffer containing the bytes to write
601  *	@len: the number of bytes to write
602  *
603  *	This function assumes the slave address is already set
604  *
605  *	LOCKING:
606  *	The context lock should be held before calling this function
607  *
608  *	RETURNS:
609  *	0 on function succeeded
610  *	EINVAL if invalid message is passed as an arg
611  */
612 static int
613 ti_i2c_write_bytes(struct ti_i2c_softc *sc, const uint8_t *buf, uint16_t len)
614 {
615 	int      timo = (hz / 4);
616 	int      err = 0;
617 	uint16_t con_reg;
618 	uint16_t events;
619 	uint16_t status;
620 	uint32_t amount = 0;
621 	uint32_t sofar = 0;
622 	uint32_t i;
623 
624 	/* wait for the bus to become free */
625 	err = ti_i2c_wait_for_free_bus(sc, timo);
626 	if (err != 0)
627 		return (err);
628 
629 	/* set the events to wait for */
630 	events = I2C_IE_XDR |   /* Transmit draining interrupt */
631 	         I2C_IE_XRDY |  /* Transmit Data Ready interrupt */
632 	         I2C_IE_ARDY |  /* Register Access Ready interrupt */
633 	         I2C_IE_NACK |  /* No Acknowledgment interrupt */
634 	         I2C_IE_AL;
635 
636 	/* enable interrupts for the events we want*/
637 	ti_i2c_set_intr_enable(sc, events);
638 
639 	/* write the number of bytes to write */
640 	ti_i2c_write_reg(sc, I2C_REG_CNT, len);
641 
642 	/* set the write bit and initiate the write transaction. Setting the STT
643 	 * (start) bit initiates the transfer.
644 	 */
645 	con_reg = ti_i2c_read_reg(sc, I2C_REG_CON);
646 	con_reg |= I2C_CON_TRX | I2C_CON_MST | I2C_CON_STT | I2C_CON_STP;
647 	ti_i2c_write_reg(sc, I2C_REG_CON, con_reg);
648 
649 	/* writing loop */
650 	while (1) {
651 
652 		/* wait for an event */
653 		err = ti_i2c_wait(sc, events, &status, timo);
654 		if (err != 0) {
655 			break;
656 		}
657 
658 		/* check for the error conditions */
659 		if (status & I2C_STAT_NACK) {
660 			/* no ACK from slave */
661 			ti_i2c_dbg(sc, "NACK\n");
662 			err = ENXIO;
663 			break;
664 		}
665 		if (status & I2C_STAT_AL) {
666 			/* arbitration lost */
667 			ti_i2c_dbg(sc, "Arbitration lost\n");
668 			err = ENXIO;
669 			break;
670 		}
671 
672 		/* check if we have finished */
673 		if (status & I2C_STAT_ARDY) {
674 			/* register access ready - transaction complete basically */
675 			ti_i2c_dbg(sc, "ARDY transaction complete\n");
676 			err = 0;
677 			break;
678 		}
679 
680 		/* read some data */
681 		if (status & I2C_STAT_XDR) {
682 			/* Receive draining interrupt - last data received */
683 			ti_i2c_dbg(sc, "Transmit draining interrupt\n");
684 
685 			/* get the number of bytes in the FIFO */
686 			amount = ti_i2c_read_reg(sc, I2C_REG_BUFSTAT);
687 			amount &= 0x3f;
688 		}
689 		else if (status & I2C_STAT_XRDY) {
690 			/* Receive data ready interrupt - enough data received */
691 			ti_i2c_dbg(sc, "Transmit data ready interrupt\n");
692 
693 			/* get the number of bytes in the FIFO */
694 			amount = ti_i2c_read_reg(sc, I2C_REG_BUF);
695 			amount &= 0x3f;
696 			amount += 1;
697 		}
698 
699 		/* sanity check we haven't overwritten the array */
700 		if ((sofar + amount) > len) {
701 			ti_i2c_dbg(sc, "to many bytes to write\n");
702 			amount = (len - sofar);
703 		}
704 
705 		/* write the bytes from the fifo */
706 		for (i = 0; i < amount; i++) {
707 			ti_i2c_write_reg(sc, I2C_REG_DATA, buf[sofar++]);
708 		}
709 
710 		/* attempt to clear the transmit ready bits */
711 		ti_i2c_write_reg(sc, I2C_REG_STAT, I2C_STAT_XDR | I2C_STAT_XRDY);
712 	}
713 
714 	/* reset the registers regardless if there was an error or not */
715 	ti_i2c_set_intr_enable(sc, 0x0000);
716 	ti_i2c_write_reg(sc, I2C_REG_CON, I2C_CON_I2C_EN | I2C_CON_MST | I2C_CON_STP);
717 
718 	return (err);
719 }
720 
721 /**
722  *	ti_i2c_transfer - called to perform the transfer
723  *	@dev: i2c device handle
724  *	@msgs: the messages to send/receive
725  *	@nmsgs: the number of messages in the msgs array
726  *
727  *
728  *	LOCKING:
729  *	Internally locked
730  *
731  *	RETURNS:
732  *	0 on function succeeded
733  *	EINVAL if invalid message is passed as an arg
734  */
735 static int
736 ti_i2c_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
737 {
738 	struct ti_i2c_softc *sc = device_get_softc(dev);
739 	int err = 0;
740 	uint32_t i;
741 	uint16_t len;
742 	uint8_t *buf;
743 
744 	TI_I2C_LOCK(sc);
745 
746 	for (i = 0; i < nmsgs; i++) {
747 
748 		len = msgs[i].len;
749 		buf = msgs[i].buf;
750 
751 		/* zero byte transfers aren't allowed */
752 		if (len == 0 || buf == NULL) {
753 			err = EINVAL;
754 			goto out;
755 		}
756 
757 		/* set the slave address */
758 		ti_i2c_write_reg(sc, I2C_REG_SA, msgs[i].slave);
759 
760 		/* perform the read or write */
761 		if (msgs[i].flags & IIC_M_RD) {
762 			err = ti_i2c_read_bytes(sc, buf, len);
763 		} else {
764 			err = ti_i2c_write_bytes(sc, buf, len);
765 		}
766 
767 	}
768 
769 out:
770 	TI_I2C_UNLOCK(sc);
771 
772 	return (err);
773 }
774 
775 /**
776  *	ti_i2c_callback - not sure about this one
777  *	@dev: i2c device handle
778  *
779  *
780  *
781  *	LOCKING:
782  *	Called from timer context
783  *
784  *	RETURNS:
785  *	EH_HANDLED or EH_NOT_HANDLED
786  */
787 static int
788 ti_i2c_callback(device_t dev, int index, caddr_t data)
789 {
790 	int error = 0;
791 
792 	switch (index) {
793 		case IIC_REQUEST_BUS:
794 			break;
795 
796 		case IIC_RELEASE_BUS:
797 			break;
798 
799 		default:
800 			error = EINVAL;
801 	}
802 
803 	return (error);
804 }
805 
806 /**
807  *	ti_i2c_activate - initialises and activates an I2C bus
808  *	@dev: i2c device handle
809  *	@num: the number of the I2C controller to activate; 1, 2 or 3
810  *
811  *
812  *	LOCKING:
813  *	Assumed called in an atomic context.
814  *
815  *	RETURNS:
816  *	nothing
817  */
818 static int
819 ti_i2c_activate(device_t dev)
820 {
821 	struct ti_i2c_softc *sc = (struct ti_i2c_softc*) device_get_softc(dev);
822 	unsigned int timeout = 0;
823 	uint16_t con_reg;
824 	int err;
825 	clk_ident_t clk;
826 
827 	/*
828 	 * The following sequence is taken from the OMAP3530 technical reference
829 	 *
830 	 * 1. Enable the functional and interface clocks (see Section 18.3.1.1.1).
831 	 */
832 	clk = I2C0_CLK + sc->device_id;
833 	err = ti_prcm_clk_enable(clk);
834 	if (err)
835 		return (err);
836 
837 	/* There seems to be a bug in the I2C reset mechanism, for some reason you
838 	 * need to disable the I2C module before issuing the reset and then enable
839 	 * it again after to detect the reset done.
840 	 *
841 	 * I found this out by looking at the Linux driver implementation, thanks
842 	 * linux guys!
843 	 */
844 
845 	/* Disable the I2C controller */
846 	ti_i2c_write_reg(sc, I2C_REG_CON, 0x0000);
847 
848 	/* Issue a softreset to the controller */
849 	/* XXXOMAP3: FIXME */
850 	bus_write_2(sc->sc_mem_res, I2C_REG_SYSC, 0x0002);
851 
852 	/* Re-enable the module and then check for the reset done */
853 	ti_i2c_write_reg(sc, I2C_REG_CON, I2C_CON_I2C_EN);
854 
855 	while ((ti_i2c_read_reg(sc, I2C_REG_SYSS) & 0x01) == 0x00) {
856 		if (timeout++ > 100) {
857 			return (EBUSY);
858 		}
859 		DELAY(100);
860 	}
861 
862 	/* Disable the I2C controller once again, now that the reset has finished */
863 	ti_i2c_write_reg(sc, I2C_REG_CON, 0x0000);
864 
865 	/* 2. Program the prescaler to obtain an approximately 12-MHz internal
866 	 *    sampling clock (I2Ci_INTERNAL_CLK) by programming the corresponding
867 	 *    value in the I2Ci.I2C_PSC[3:0] PSC field.
868 	 *    This value depends on the frequency of the functional clock (I2Ci_FCLK).
869 	 *    Because this frequency is 96MHz, the I2Ci.I2C_PSC[7:0] PSC field value
870 	 *    is 0x7.
871 	 */
872 
873 	/* Program the prescaler to obtain an approximately 12-MHz internal
874 	 * sampling clock.
875 	 */
876 	ti_i2c_write_reg(sc, I2C_REG_PSC, 0x0017);
877 
878 	/* 3. Program the I2Ci.I2C_SCLL[7:0] SCLL and I2Ci.I2C_SCLH[7:0] SCLH fields
879 	 *    to obtain a bit rate of 100K bps or 400K bps. These values depend on
880 	 *    the internal sampling clock frequency (see Table 18-12).
881 	 */
882 
883 	/* Set the bitrate to 100kbps */
884 	ti_i2c_write_reg(sc, I2C_REG_SCLL, 0x000d);
885 	ti_i2c_write_reg(sc, I2C_REG_SCLH, 0x000f);
886 
887 	/* 4. (Optional) Program the I2Ci.I2C_SCLL[15:8] HSSCLL and
888 	 *    I2Ci.I2C_SCLH[15:8] HSSCLH fields to obtain a bit rate of 400K bps or
889 	 *    3.4M bps (for the second phase of HS mode). These values depend on the
890 	 *    internal sampling clock frequency (see Table 18-12).
891 	 *
892 	 * 5. (Optional) If a bit rate of 3.4M bps is used and the bus line
893 	 *    capacitance exceeds 45 pF, program the CONTROL.CONTROL_DEVCONF1[12]
894 	 *    I2C1HSMASTER bit for I2C1, the CONTROL.CONTROL_DEVCONF1[13]
895 	 *    I2C2HSMASTER bit for I2C2, or the CONTROL.CONTROL_DEVCONF1[14]
896 	 *    I2C3HSMASTER bit for I2C3.
897 	 */
898 
899 	/* 6. Configure the Own Address of the I2C controller by storing it in the
900 	 *    I2Ci.I2C_OA0 register. Up to four Own Addresses can be programmed in
901 	 *    the I2Ci.I2C_OAi registers (with I = 0, 1, 2, 3) for each I2C
902 	 *    controller.
903 	 *
904 	 * Note: For a 10-bit address, set the corresponding expand Own Address bit
905 	 * in the I2Ci.I2C_CON register.
906 	 */
907 
908 	/* Driver currently always in single master mode so ignore this step */
909 
910 	/* 7. Set the TX threshold (in transmitter mode) and the RX threshold (in
911 	 *    receiver mode) by setting the I2Ci.I2C_BUF[5:0]XTRSH field to (TX
912 	 *    threshold - 1) and the I2Ci.I2C_BUF[13:8]RTRSH field to (RX threshold
913 	 *    - 1), where the TX and RX thresholds are greater than or equal to 1.
914 	 */
915 
916 	/* Set the FIFO buffer threshold, note I2C1 & I2C2 have 8 byte FIFO, whereas
917 	 * I2C3 has 64 bytes.  Threshold set to 5 for now.
918 	 */
919 	ti_i2c_write_reg(sc, I2C_REG_BUF, 0x0404);
920 
921 	/*
922 	 * 8. Take the I2C controller out of reset by setting the I2Ci.I2C_CON[15]
923 	 *    I2C_EN bit to 1.
924 	 */
925 	ti_i2c_write_reg(sc, I2C_REG_CON, I2C_CON_I2C_EN | I2C_CON_OPMODE_STD);
926 
927 	/*
928 	 * To initialize the I2C controller, perform the following steps:
929 	 *
930 	 * 1. Configure the I2Ci.I2C_CON register:
931 	 *    · For master or slave mode, set the I2Ci.I2C_CON[10] MST bit (0: slave,
932 	 *      1: master).
933 	 *    · For transmitter or receiver mode, set the I2Ci.I2C_CON[9] TRX bit
934 	 *      (0: receiver, 1: transmitter).
935 	 */
936 	con_reg = ti_i2c_read_reg(sc, I2C_REG_CON);
937 	con_reg |= I2C_CON_MST;
938 	ti_i2c_write_reg(sc, I2C_REG_CON, con_reg);
939 
940 	/* 2. If using an interrupt to transmit/receive data, set to 1 the
941 	 *    corresponding bit in the I2Ci.I2C_IE register (the I2Ci.I2C_IE[4]
942 	 *    XRDY_IE bit for the transmit interrupt, the I2Ci.I2C_IE[3] RRDY bit
943 	 *    for the receive interrupt).
944 	 */
945 	ti_i2c_set_intr_enable(sc, I2C_IE_XRDY | I2C_IE_RRDY);
946 
947 	/* 3. If using DMA to receive/transmit data, set to 1 the corresponding bit
948 	 *    in the I2Ci.I2C_BUF register (the I2Ci.I2C_BUF[15] RDMA_EN bit for the
949 	 *    receive DMA channel, the I2Ci.I2C_BUF[7] XDMA_EN bit for the transmit
950 	 *    DMA channel).
951 	 */
952 
953 	/* not using DMA for now, so ignore this */
954 
955 	return (0);
956 }
957 
958 /**
959  *	ti_i2c_deactivate - deactivates the controller and releases resources
960  *	@dev: i2c device handle
961  *
962  *
963  *
964  *	LOCKING:
965  *	Assumed called in an atomic context.
966  *
967  *	RETURNS:
968  *	nothing
969  */
970 static void
971 ti_i2c_deactivate(device_t dev)
972 {
973 	struct ti_i2c_softc *sc = device_get_softc(dev);
974 	clk_ident_t clk;
975 
976 	/* Disable the controller - cancel all transactions */
977 	ti_i2c_write_reg(sc, I2C_REG_CON, 0x0000);
978 
979 	/* Release the interrupt handler */
980 	if (sc->sc_irq_h) {
981 		bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_irq_h);
982 		sc->sc_irq_h = 0;
983 	}
984 
985 	bus_generic_detach(sc->sc_dev);
986 
987 	/* Unmap the I2C controller registers */
988 	if (sc->sc_mem_res != 0) {
989 		bus_release_resource(dev, SYS_RES_MEMORY, rman_get_rid(sc->sc_irq_res),
990 							 sc->sc_mem_res);
991 		sc->sc_mem_res = NULL;
992 	}
993 
994 	/* Release the IRQ resource */
995 	if (sc->sc_irq_res != NULL) {
996 		bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->sc_irq_res),
997 							 sc->sc_irq_res);
998 		sc->sc_irq_res = NULL;
999 	}
1000 
1001 	/* Finally disable the functional and interface clocks */
1002 	clk = I2C0_CLK + sc->device_id;
1003 	ti_prcm_clk_disable(clk);
1004 
1005 	return;
1006 }
1007 
1008 /**
1009  *	ti_i2c_probe - probe function for the driver
1010  *	@dev: i2c device handle
1011  *
1012  *
1013  *
1014  *	LOCKING:
1015  *
1016  *
1017  *	RETURNS:
1018  *	Always returns 0
1019  */
1020 static int
1021 ti_i2c_probe(device_t dev)
1022 {
1023 	if (!ofw_bus_is_compatible(dev, "ti,i2c"))
1024 		return (ENXIO);
1025 
1026 	device_set_desc(dev, "TI I2C Controller");
1027 	return (0);
1028 }
1029 
1030 /**
1031  *	ti_i2c_attach - attach function for the driver
1032  *	@dev: i2c device handle
1033  *
1034  *	Initialised driver data structures and activates the I2C controller.
1035  *
1036  *	LOCKING:
1037  *
1038  *
1039  *	RETURNS:
1040  *
1041  */
1042 static int
1043 ti_i2c_attach(device_t dev)
1044 {
1045 	struct ti_i2c_softc *sc = device_get_softc(dev);
1046 	phandle_t node;
1047 	pcell_t did;
1048 	int err;
1049 	int rid;
1050 
1051 	sc->sc_dev = dev;
1052 
1053 	/* Get the i2c device id from FDT */
1054 	node = ofw_bus_get_node(dev);
1055 	if ((OF_getprop(node, "i2c-device-id", &did, sizeof(did))) <= 0) {
1056 		device_printf(dev, "missing i2c-device-id attribute in FDT\n");
1057 		return (ENXIO);
1058 	}
1059 	sc->device_id = fdt32_to_cpu(did);
1060 
1061 	TI_I2C_LOCK_INIT(sc);
1062 
1063 	/* Get the memory resource for the register mapping */
1064 	rid = 0;
1065 	sc->sc_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
1066 	                                        RF_ACTIVE);
1067 	if (sc->sc_mem_res == NULL)
1068 		panic("%s: Cannot map registers", device_get_name(dev));
1069 
1070 	/* Allocate an IRQ resource for the MMC controller */
1071 	rid = 0;
1072 	sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1073 	                                        RF_ACTIVE | RF_SHAREABLE);
1074 	if (sc->sc_irq_res == NULL) {
1075 		err = ENOMEM;
1076 		goto out;
1077 	}
1078 
1079 	/* XXXOMAP3: FIXME get proper revision here */
1080 	/* First read the version number of the I2C module */
1081 	sc->sc_rev = ti_i2c_read_2(sc, I2C_REG_REVNB_HI) & 0xff;
1082 
1083 	device_printf(dev, "I2C revision %d.%d\n", sc->sc_rev >> 4,
1084 	    sc->sc_rev & 0xf);
1085 
1086 	/* Activate the H/W */
1087 	err = ti_i2c_activate(dev);
1088 	if (err) {
1089 		device_printf(dev, "ti_i2c_activate failed\n");
1090 		goto out;
1091 	}
1092 
1093 	/* activate the interrupt */
1094 	err = bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_MISC | INTR_MPSAFE,
1095 				NULL, ti_i2c_intr, sc, &sc->sc_irq_h);
1096 	if (err)
1097 		goto out;
1098 
1099 	/* Attach to the iicbus */
1100 	if ((sc->sc_iicbus = device_add_child(dev, "iicbus", -1)) == NULL)
1101 		device_printf(dev, "could not allocate iicbus instance\n");
1102 
1103 	/* Probe and attach the iicbus */
1104 	bus_generic_attach(dev);
1105 
1106 out:
1107 	if (err) {
1108 		ti_i2c_deactivate(dev);
1109 		TI_I2C_LOCK_DESTROY(sc);
1110 	}
1111 
1112 	return (err);
1113 }
1114 
1115 /**
1116  *	ti_i2c_detach - detach function for the driver
1117  *	@dev: i2c device handle
1118  *
1119  *
1120  *
1121  *	LOCKING:
1122  *
1123  *
1124  *	RETURNS:
1125  *	Always returns 0
1126  */
1127 static int
1128 ti_i2c_detach(device_t dev)
1129 {
1130 	struct ti_i2c_softc *sc = device_get_softc(dev);
1131 	int rv;
1132 
1133 	ti_i2c_deactivate(dev);
1134 
1135 	if (sc->sc_iicbus && (rv = device_delete_child(dev, sc->sc_iicbus)) != 0)
1136 		return (rv);
1137 
1138 	TI_I2C_LOCK_DESTROY(sc);
1139 
1140 	return (0);
1141 }
1142 
1143 
1144 static phandle_t
1145 ti_i2c_get_node(device_t bus, device_t dev)
1146 {
1147 	/*
1148 	 * Share controller node with iibus device
1149 	 */
1150 	return ofw_bus_get_node(bus);
1151 }
1152 
1153 static device_method_t ti_i2c_methods[] = {
1154 	/* Device interface */
1155 	DEVMETHOD(device_probe,		ti_i2c_probe),
1156 	DEVMETHOD(device_attach,	ti_i2c_attach),
1157 	DEVMETHOD(device_detach,	ti_i2c_detach),
1158 
1159 	/* OFW methods */
1160 	DEVMETHOD(ofw_bus_get_node,	ti_i2c_get_node),
1161 
1162 	/* iicbus interface */
1163 	DEVMETHOD(iicbus_callback,	ti_i2c_callback),
1164 	DEVMETHOD(iicbus_reset,		ti_i2c_reset),
1165 	DEVMETHOD(iicbus_transfer,	ti_i2c_transfer),
1166 	{ 0, 0 }
1167 };
1168 
1169 static driver_t ti_i2c_driver = {
1170 	"iichb",
1171 	ti_i2c_methods,
1172 	sizeof(struct ti_i2c_softc),
1173 };
1174 
1175 DRIVER_MODULE(ti_iic, simplebus, ti_i2c_driver, ti_i2c_devclass, 0, 0);
1176 DRIVER_MODULE(iicbus, ti_iic, iicbus_driver, iicbus_devclass, 0, 0);
1177 
1178 MODULE_DEPEND(ti_iic, ti_prcm, 1, 1, 1);
1179 MODULE_DEPEND(ti_iic, iicbus, 1, 1, 1);
1180