xref: /freebsd/sys/arm/ti/ti_i2c.c (revision 5e53a4f90f82c4345f277dd87cc9292f26e04a29)
1 /*-
2  * Copyright (c) 2011 Ben Gray <ben.r.gray@gmail.com>.
3  * Copyright (c) 2014 Luiz Otavio O Souza <loos@freebsd.org>.
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 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/bus.h>
48 #include <sys/conf.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/mbuf.h>
52 #include <sys/malloc.h>
53 #include <sys/module.h>
54 #include <sys/mutex.h>
55 #include <sys/rman.h>
56 #include <sys/sysctl.h>
57 #include <machine/bus.h>
58 
59 #include <dev/ofw/openfirm.h>
60 #include <dev/ofw/ofw_bus.h>
61 #include <dev/ofw/ofw_bus_subr.h>
62 
63 #include <arm/ti/ti_cpuid.h>
64 #include <arm/ti/ti_prcm.h>
65 #include <arm/ti/ti_hwmods.h>
66 #include <arm/ti/ti_i2c.h>
67 
68 #include <dev/iicbus/iiconf.h>
69 #include <dev/iicbus/iicbus.h>
70 
71 #include "iicbus_if.h"
72 
73 /**
74  *	I2C device driver context, a pointer to this is stored in the device
75  *	driver structure.
76  */
77 struct ti_i2c_softc
78 {
79 	device_t		sc_dev;
80 	clk_ident_t		clk_id;
81 	struct resource*	sc_irq_res;
82 	struct resource*	sc_mem_res;
83 	device_t		sc_iicbus;
84 
85 	void*			sc_irq_h;
86 
87 	struct mtx		sc_mtx;
88 
89 	struct iic_msg*		sc_buffer;
90 	int			sc_bus_inuse;
91 	int			sc_buffer_pos;
92 	int			sc_error;
93 	int			sc_fifo_trsh;
94 	int			sc_timeout;
95 
96 	uint16_t		sc_con_reg;
97 	uint16_t		sc_rev;
98 };
99 
100 struct ti_i2c_clock_config
101 {
102 	u_int   frequency;	/* Bus frequency in Hz */
103 	uint8_t psc;		/* Fast/Standard mode prescale divider */
104 	uint8_t scll;		/* Fast/Standard mode SCL low time */
105 	uint8_t sclh;		/* Fast/Standard mode SCL high time */
106 	uint8_t hsscll;		/* High Speed mode SCL low time */
107 	uint8_t hssclh;		/* High Speed mode SCL high time */
108 };
109 
110 #if defined(SOC_OMAP4)
111 /*
112  * OMAP4 i2c bus clock is 96MHz / ((psc + 1) * (scll + 7 + sclh + 5)).
113  * The prescaler values for 100KHz and 400KHz modes come from the table in the
114  * OMAP4 TRM.  The table doesn't list 1MHz; these values should give that speed.
115  */
116 static struct ti_i2c_clock_config ti_omap4_i2c_clock_configs[] = {
117 	{  100000, 23,  13,  15,  0,  0},
118 	{  400000,  9,   5,   7,  0,  0},
119 	{ 1000000,  3,   5,   7,  0,  0},
120 /*	{ 3200000,  1, 113, 115,  7, 10}, - HS mode */
121 	{       0 /* Table terminator */ }
122 };
123 #endif
124 
125 #if defined(SOC_TI_AM335X)
126 /*
127  * AM335x i2c bus clock is 48MHZ / ((psc + 1) * (scll + 7 + sclh + 5))
128  * In all cases we prescale the clock to 24MHz as recommended in the manual.
129  */
130 static struct ti_i2c_clock_config ti_am335x_i2c_clock_configs[] = {
131 	{  100000, 1, 111, 117, 0, 0},
132 	{  400000, 1,  23,  25, 0, 0},
133 	{ 1000000, 1,   5,   7, 0, 0},
134 	{       0 /* Table terminator */ }
135 };
136 #endif
137 
138 /**
139  *	Locking macros used throughout the driver
140  */
141 #define	TI_I2C_LOCK(_sc)		mtx_lock(&(_sc)->sc_mtx)
142 #define	TI_I2C_UNLOCK(_sc)		mtx_unlock(&(_sc)->sc_mtx)
143 #define	TI_I2C_LOCK_INIT(_sc)						\
144 	mtx_init(&_sc->sc_mtx, device_get_nameunit(_sc->sc_dev),	\
145 	    "ti_i2c", MTX_DEF)
146 #define	TI_I2C_LOCK_DESTROY(_sc)	mtx_destroy(&_sc->sc_mtx)
147 #define	TI_I2C_ASSERT_LOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_OWNED)
148 #define	TI_I2C_ASSERT_UNLOCKED(_sc)	mtx_assert(&_sc->sc_mtx, MA_NOTOWNED)
149 
150 #ifdef DEBUG
151 #define	ti_i2c_dbg(_sc, fmt, args...)					\
152 	device_printf((_sc)->sc_dev, fmt, ##args)
153 #else
154 #define	ti_i2c_dbg(_sc, fmt, args...)
155 #endif
156 
157 /**
158  *	ti_i2c_read_2 - reads a 16-bit value from one of the I2C registers
159  *	@sc: I2C device context
160  *	@off: the byte offset within the register bank to read from.
161  *
162  *
163  *	LOCKING:
164  *	No locking required
165  *
166  *	RETURNS:
167  *	16-bit value read from the register.
168  */
169 static inline uint16_t
170 ti_i2c_read_2(struct ti_i2c_softc *sc, bus_size_t off)
171 {
172 
173 	return (bus_read_2(sc->sc_mem_res, off));
174 }
175 
176 /**
177  *	ti_i2c_write_2 - writes a 16-bit value to one of the I2C registers
178  *	@sc: I2C device context
179  *	@off: the byte offset within the register bank to read from.
180  *	@val: the value to write into the register
181  *
182  *	LOCKING:
183  *	No locking required
184  *
185  *	RETURNS:
186  *	16-bit value read from the register.
187  */
188 static inline void
189 ti_i2c_write_2(struct ti_i2c_softc *sc, bus_size_t off, uint16_t val)
190 {
191 
192 	bus_write_2(sc->sc_mem_res, off, val);
193 }
194 
195 static int
196 ti_i2c_transfer_intr(struct ti_i2c_softc* sc, uint16_t status)
197 {
198 	int amount, done, i;
199 
200 	done = 0;
201 	amount = 0;
202 	/* Check for the error conditions. */
203 	if (status & I2C_STAT_NACK) {
204 		/* No ACK from slave. */
205 		ti_i2c_dbg(sc, "NACK\n");
206 		ti_i2c_write_2(sc, I2C_REG_STATUS, I2C_STAT_NACK);
207 		sc->sc_error = ENXIO;
208 	} else if (status & I2C_STAT_AL) {
209 		/* Arbitration lost. */
210 		ti_i2c_dbg(sc, "Arbitration lost\n");
211 		ti_i2c_write_2(sc, I2C_REG_STATUS, I2C_STAT_AL);
212 		sc->sc_error = ENXIO;
213 	}
214 
215 	/* Check if we have finished. */
216 	if (status & I2C_STAT_ARDY) {
217 		/* Register access ready - transaction complete basically. */
218 		ti_i2c_dbg(sc, "ARDY transaction complete\n");
219 		if (sc->sc_error != 0 && sc->sc_buffer->flags & IIC_M_NOSTOP) {
220 			ti_i2c_write_2(sc, I2C_REG_CON,
221 			    sc->sc_con_reg | I2C_CON_STP);
222 		}
223 		ti_i2c_write_2(sc, I2C_REG_STATUS,
224 		    I2C_STAT_ARDY | I2C_STAT_RDR | I2C_STAT_RRDY |
225 		    I2C_STAT_XDR | I2C_STAT_XRDY);
226 		return (1);
227 	}
228 
229 	if (sc->sc_buffer->flags & IIC_M_RD) {
230 		/* Read some data. */
231 		if (status & I2C_STAT_RDR) {
232 			/*
233 			 * Receive draining interrupt - last data received.
234 			 * The set FIFO threshold won't be reached to trigger
235 			 * RRDY.
236 			 */
237 			ti_i2c_dbg(sc, "Receive draining interrupt\n");
238 
239 			/*
240 			 * Drain the FIFO.  Read the pending data in the FIFO.
241 			 */
242 			amount = sc->sc_buffer->len - sc->sc_buffer_pos;
243 		} else if (status & I2C_STAT_RRDY) {
244 			/*
245 			 * Receive data ready interrupt - FIFO has reached the
246 			 * set threshold.
247 			 */
248 			ti_i2c_dbg(sc, "Receive data ready interrupt\n");
249 
250 			amount = min(sc->sc_fifo_trsh,
251 			    sc->sc_buffer->len - sc->sc_buffer_pos);
252 		}
253 
254 		/* Read the bytes from the fifo. */
255 		for (i = 0; i < amount; i++)
256 			sc->sc_buffer->buf[sc->sc_buffer_pos++] =
257 			    (uint8_t)(ti_i2c_read_2(sc, I2C_REG_DATA) & 0xff);
258 
259 		if (status & I2C_STAT_RDR)
260 			ti_i2c_write_2(sc, I2C_REG_STATUS, I2C_STAT_RDR);
261 		if (status & I2C_STAT_RRDY)
262 			ti_i2c_write_2(sc, I2C_REG_STATUS, I2C_STAT_RRDY);
263 
264 	} else {
265 		/* Write some data. */
266 		if (status & I2C_STAT_XDR) {
267 			/*
268 			 * Transmit draining interrupt - FIFO level is below
269 			 * the set threshold and the amount of data still to
270 			 * be transferred won't reach the set FIFO threshold.
271 			 */
272 			ti_i2c_dbg(sc, "Transmit draining interrupt\n");
273 
274 			/*
275 			 * Drain the TX data.  Write the pending data in the
276 			 * FIFO.
277 			 */
278 			amount = sc->sc_buffer->len - sc->sc_buffer_pos;
279 		} else if (status & I2C_STAT_XRDY) {
280 			/*
281 			 * Transmit data ready interrupt - the FIFO level
282 			 * is below the set threshold.
283 			 */
284 			ti_i2c_dbg(sc, "Transmit data ready interrupt\n");
285 
286 			amount = min(sc->sc_fifo_trsh,
287 			    sc->sc_buffer->len - sc->sc_buffer_pos);
288 		}
289 
290 		/* Write the bytes from the fifo. */
291 		for (i = 0; i < amount; i++)
292 			ti_i2c_write_2(sc, I2C_REG_DATA,
293 			    sc->sc_buffer->buf[sc->sc_buffer_pos++]);
294 
295 		if (status & I2C_STAT_XDR)
296 			ti_i2c_write_2(sc, I2C_REG_STATUS, I2C_STAT_XDR);
297 		if (status & I2C_STAT_XRDY)
298 			ti_i2c_write_2(sc, I2C_REG_STATUS, I2C_STAT_XRDY);
299 	}
300 
301 	return (done);
302 }
303 
304 /**
305  *	ti_i2c_intr - interrupt handler for the I2C module
306  *	@dev: i2c device handle
307  *
308  *
309  *
310  *	LOCKING:
311  *	Called from timer context
312  *
313  *	RETURNS:
314  *	EH_HANDLED or EH_NOT_HANDLED
315  */
316 static void
317 ti_i2c_intr(void *arg)
318 {
319 	int done;
320 	struct ti_i2c_softc *sc;
321 	uint16_t events, status;
322 
323  	sc = (struct ti_i2c_softc *)arg;
324 
325 	TI_I2C_LOCK(sc);
326 
327 	status = ti_i2c_read_2(sc, I2C_REG_STATUS);
328 	if (status == 0) {
329 		TI_I2C_UNLOCK(sc);
330 		return;
331 	}
332 
333 	/* Save enabled interrupts. */
334 	events = ti_i2c_read_2(sc, I2C_REG_IRQENABLE_SET);
335 
336 	/* We only care about enabled interrupts. */
337 	status &= events;
338 
339 	done = 0;
340 
341 	if (sc->sc_buffer != NULL)
342 		done = ti_i2c_transfer_intr(sc, status);
343 	else {
344 		ti_i2c_dbg(sc, "Transfer interrupt without buffer\n");
345 		sc->sc_error = EINVAL;
346 		done = 1;
347 	}
348 
349 	if (done)
350 		/* Wakeup the process that started the transaction. */
351 		wakeup(sc);
352 
353 	TI_I2C_UNLOCK(sc);
354 }
355 
356 /**
357  *	ti_i2c_transfer - called to perform the transfer
358  *	@dev: i2c device handle
359  *	@msgs: the messages to send/receive
360  *	@nmsgs: the number of messages in the msgs array
361  *
362  *
363  *	LOCKING:
364  *	Internally locked
365  *
366  *	RETURNS:
367  *	0 on function succeeded
368  *	EINVAL if invalid message is passed as an arg
369  */
370 static int
371 ti_i2c_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
372 {
373 	int err, i, repstart, timeout;
374 	struct ti_i2c_softc *sc;
375 	uint16_t reg;
376 
377  	sc = device_get_softc(dev);
378 	TI_I2C_LOCK(sc);
379 
380 	/* If the controller is busy wait until it is available. */
381 	while (sc->sc_bus_inuse == 1)
382 		mtx_sleep(sc, &sc->sc_mtx, 0, "i2cbuswait", 0);
383 
384 	/* Now we have control over the I2C controller. */
385 	sc->sc_bus_inuse = 1;
386 
387 	err = 0;
388 	repstart = 0;
389 	for (i = 0; i < nmsgs; i++) {
390 
391 		sc->sc_buffer = &msgs[i];
392 		sc->sc_buffer_pos = 0;
393 		sc->sc_error = 0;
394 
395 		/* Zero byte transfers aren't allowed. */
396 		if (sc->sc_buffer == NULL || sc->sc_buffer->buf == NULL ||
397 		    sc->sc_buffer->len == 0) {
398 			err = EINVAL;
399 			break;
400 		}
401 
402 		/* Check if the i2c bus is free. */
403 		if (repstart == 0) {
404 			/*
405 			 * On repeated start we send the START condition while
406 			 * the bus _is_ busy.
407 			 */
408 			timeout = 0;
409 			while (ti_i2c_read_2(sc, I2C_REG_STATUS_RAW) & I2C_STAT_BB) {
410 				if (timeout++ > 100) {
411 					err = EBUSY;
412 					goto out;
413 				}
414 				DELAY(1000);
415 			}
416 			timeout = 0;
417 		} else
418 			repstart = 0;
419 
420 		if (sc->sc_buffer->flags & IIC_M_NOSTOP)
421 			repstart = 1;
422 
423 		/* Set the slave address. */
424 		ti_i2c_write_2(sc, I2C_REG_SA, msgs[i].slave >> 1);
425 
426 		/* Write the data length. */
427 		ti_i2c_write_2(sc, I2C_REG_CNT, sc->sc_buffer->len);
428 
429 		/* Clear the RX and the TX FIFO. */
430 		reg = ti_i2c_read_2(sc, I2C_REG_BUF);
431 		reg |= I2C_BUF_RXFIFO_CLR | I2C_BUF_TXFIFO_CLR;
432 		ti_i2c_write_2(sc, I2C_REG_BUF, reg);
433 
434 		reg = sc->sc_con_reg | I2C_CON_STT;
435 		if (repstart == 0)
436 			reg |= I2C_CON_STP;
437 		if ((sc->sc_buffer->flags & IIC_M_RD) == 0)
438 			reg |= I2C_CON_TRX;
439 		ti_i2c_write_2(sc, I2C_REG_CON, reg);
440 
441 		/* Wait for an event. */
442 		err = mtx_sleep(sc, &sc->sc_mtx, 0, "i2ciowait", sc->sc_timeout);
443 		if (err == 0)
444 			err = sc->sc_error;
445 
446 		if (err)
447 			break;
448 	}
449 
450 out:
451 	if (timeout == 0) {
452 		while (ti_i2c_read_2(sc, I2C_REG_STATUS_RAW) & I2C_STAT_BB) {
453 			if (timeout++ > 100)
454 				break;
455 			DELAY(1000);
456 		}
457 	}
458 	/* Put the controller in master mode again. */
459 	if ((ti_i2c_read_2(sc, I2C_REG_CON) & I2C_CON_MST) == 0)
460 		ti_i2c_write_2(sc, I2C_REG_CON, sc->sc_con_reg);
461 
462 	sc->sc_buffer = NULL;
463 	sc->sc_bus_inuse = 0;
464 
465 	/* Wake up the processes that are waiting for the bus. */
466 	wakeup(sc);
467 
468 	TI_I2C_UNLOCK(sc);
469 
470 	return (err);
471 }
472 
473 static int
474 ti_i2c_reset(struct ti_i2c_softc *sc, u_char speed)
475 {
476 	int timeout;
477 	struct ti_i2c_clock_config *clkcfg;
478 	u_int busfreq;
479 	uint16_t fifo_trsh, reg, scll, sclh;
480 
481 	switch (ti_chip()) {
482 #ifdef SOC_OMAP4
483 	case CHIP_OMAP_4:
484 		clkcfg = ti_omap4_i2c_clock_configs;
485 		break;
486 #endif
487 #ifdef SOC_TI_AM335X
488 	case CHIP_AM335X:
489 		clkcfg = ti_am335x_i2c_clock_configs;
490 		break;
491 #endif
492 	default:
493 		panic("Unknown TI SoC, unable to reset the i2c");
494 	}
495 
496 	/*
497 	 * If we haven't attached the bus yet, just init at the default slow
498 	 * speed.  This lets us get the hardware initialized enough to attach
499 	 * the bus which is where the real speed configuration is handled. After
500 	 * the bus is attached, get the configured speed from it.  Search the
501 	 * configuration table for the best speed we can do that doesn't exceed
502 	 * the requested speed.
503 	 */
504 	if (sc->sc_iicbus == NULL)
505 		busfreq = 100000;
506 	else
507 		busfreq = IICBUS_GET_FREQUENCY(sc->sc_iicbus, speed);
508 	for (;;) {
509 		if (clkcfg[1].frequency == 0 || clkcfg[1].frequency > busfreq)
510 			break;
511 		clkcfg++;
512 	}
513 
514 	/*
515 	 * 23.1.4.3 - HS I2C Software Reset
516 	 *    From OMAP4 TRM at page 4068.
517 	 *
518 	 * 1. Ensure that the module is disabled.
519 	 */
520 	sc->sc_con_reg = 0;
521 	ti_i2c_write_2(sc, I2C_REG_CON, sc->sc_con_reg);
522 
523 	/* 2. Issue a softreset to the controller. */
524 	bus_write_2(sc->sc_mem_res, I2C_REG_SYSC, I2C_REG_SYSC_SRST);
525 
526 	/*
527 	 * 3. Enable the module.
528 	 *    The I2Ci.I2C_SYSS[0] RDONE bit is asserted only after the module
529 	 *    is enabled by setting the I2Ci.I2C_CON[15] I2C_EN bit to 1.
530 	 */
531 	ti_i2c_write_2(sc, I2C_REG_CON, I2C_CON_I2C_EN);
532 
533  	/* 4. Wait for the software reset to complete. */
534 	timeout = 0;
535 	while ((ti_i2c_read_2(sc, I2C_REG_SYSS) & I2C_SYSS_RDONE) == 0) {
536 		if (timeout++ > 100)
537 			return (EBUSY);
538 		DELAY(100);
539 	}
540 
541 	/*
542 	 * Disable the I2C controller once again, now that the reset has
543 	 * finished.
544 	 */
545 	ti_i2c_write_2(sc, I2C_REG_CON, sc->sc_con_reg);
546 
547 	/*
548 	 * The following sequence is taken from the OMAP4 TRM at page 4077.
549 	 *
550 	 * 1. Enable the functional and interface clocks (see Section
551 	 *    23.1.5.1.1.1.1).  Done at ti_i2c_activate().
552 	 *
553 	 * 2. Program the prescaler to obtain an approximately 12MHz internal
554 	 *    sampling clock (I2Ci_INTERNAL_CLK) by programming the
555 	 *    corresponding value in the I2Ci.I2C_PSC[3:0] PSC field.
556 	 *    This value depends on the frequency of the functional clock
557 	 *    (I2Ci_FCLK).  Because this frequency is 96MHz, the
558 	 *    I2Ci.I2C_PSC[7:0] PSC field value is 0x7.
559 	 */
560 	ti_i2c_write_2(sc, I2C_REG_PSC, clkcfg->psc);
561 
562 	/*
563 	 * 3. Program the I2Ci.I2C_SCLL[7:0] SCLL and I2Ci.I2C_SCLH[7:0] SCLH
564 	 *    bit fields to obtain a bit rate of 100 Kbps, 400 Kbps or 1Mbps.
565 	 *    These values depend on the internal sampling clock frequency
566 	 *    (see Table 23-8).
567 	 */
568 	scll = clkcfg->scll & I2C_SCLL_MASK;
569 	sclh = clkcfg->sclh & I2C_SCLH_MASK;
570 
571 	/*
572 	 * 4. (Optional) Program the I2Ci.I2C_SCLL[15:8] HSSCLL and
573 	 *    I2Ci.I2C_SCLH[15:8] HSSCLH fields to obtain a bit rate of
574 	 *    400K bps or 3.4M bps (for the second phase of HS mode).  These
575 	 *    values depend on the internal sampling clock frequency (see
576 	 *    Table 23-8).
577 	 *
578 	 * 5. (Optional) If a bit rate of 3.4M bps is used and the bus line
579 	 *    capacitance exceeds 45 pF, (see Section 18.4.8, PAD Functional
580 	 *    Multiplexing and Configuration).
581 	 */
582 	switch (ti_chip()) {
583 #ifdef SOC_OMAP4
584 	case CHIP_OMAP_4:
585 		if ((clkcfg->hsscll + clkcfg->hssclh) > 0) {
586 			scll |= clkcfg->hsscll << I2C_HSSCLL_SHIFT;
587 			sclh |= clkcfg->hssclh << I2C_HSSCLH_SHIFT;
588 			sc->sc_con_reg |= I2C_CON_OPMODE_HS;
589 		}
590 		break;
591 #endif
592 	}
593 
594 	/* Write the selected bit rate. */
595 	ti_i2c_write_2(sc, I2C_REG_SCLL, scll);
596 	ti_i2c_write_2(sc, I2C_REG_SCLH, sclh);
597 
598 	/*
599 	 * 6. Configure the Own Address of the I2C controller by storing it in
600 	 *    the I2Ci.I2C_OA0 register.  Up to four Own Addresses can be
601 	 *    programmed in the I2Ci.I2C_OAi registers (where i = 0, 1, 2, 3)
602 	 *    for each I2C controller.
603 	 *
604 	 * Note: For a 10-bit address, set the corresponding expand Own Address
605 	 * bit in the I2Ci.I2C_CON register.
606 	 *
607 	 * Driver currently always in single master mode so ignore this step.
608 	 */
609 
610 	/*
611 	 * 7. Set the TX threshold (in transmitter mode) and the RX threshold
612 	 *    (in receiver mode) by setting the I2Ci.I2C_BUF[5:0]XTRSH field to
613 	 *    (TX threshold - 1) and the I2Ci.I2C_BUF[13:8]RTRSH field to (RX
614 	 *    threshold - 1), where the TX and RX thresholds are greater than
615 	 *    or equal to 1.
616 	 *
617 	 * The threshold is set to 5 for now.
618 	 */
619 	fifo_trsh = (sc->sc_fifo_trsh - 1) & I2C_BUF_TRSH_MASK;
620 	reg = fifo_trsh | (fifo_trsh << I2C_BUF_RXTRSH_SHIFT);
621 	ti_i2c_write_2(sc, I2C_REG_BUF, reg);
622 
623 	/*
624 	 * 8. Take the I2C controller out of reset by setting the
625 	 *    I2Ci.I2C_CON[15] I2C_EN bit to 1.
626 	 *
627 	 * 23.1.5.1.1.1.2 - Initialize the I2C Controller
628 	 *
629 	 * To initialize the I2C controller, perform the following steps:
630 	 *
631 	 * 1. Configure the I2Ci.I2C_CON register:
632 	 *     . For master or slave mode, set the I2Ci.I2C_CON[10] MST bit
633 	 *       (0: slave, 1: master).
634 	 *     . For transmitter or receiver mode, set the I2Ci.I2C_CON[9] TRX
635 	 *       bit (0: receiver, 1: transmitter).
636 	 */
637 
638 	/* Enable the I2C controller in master mode. */
639 	sc->sc_con_reg |= I2C_CON_I2C_EN | I2C_CON_MST;
640 	ti_i2c_write_2(sc, I2C_REG_CON, sc->sc_con_reg);
641 
642 	/*
643 	 * 2. If using an interrupt to transmit/receive data, set the
644 	 *    corresponding bit in the I2Ci.I2C_IE register (the I2Ci.I2C_IE[4]
645 	 *    XRDY_IE bit for the transmit interrupt, the I2Ci.I2C_IE[3] RRDY
646 	 *    bit for the receive interrupt).
647 	 */
648 
649 	/* Set the interrupts we want to be notified. */
650 	reg = I2C_IE_XDR |	/* Transmit draining interrupt. */
651 	    I2C_IE_XRDY |	/* Transmit Data Ready interrupt. */
652 	    I2C_IE_RDR |	/* Receive draining interrupt. */
653 	    I2C_IE_RRDY |	/* Receive Data Ready interrupt. */
654 	    I2C_IE_ARDY |	/* Register Access Ready interrupt. */
655 	    I2C_IE_NACK |	/* No Acknowledgment interrupt. */
656 	    I2C_IE_AL;		/* Arbitration lost interrupt. */
657 
658 	/* Enable the interrupts. */
659 	ti_i2c_write_2(sc, I2C_REG_IRQENABLE_SET, reg);
660 
661 	/*
662 	 * 3. If using DMA to receive/transmit data, set to 1 the corresponding
663 	 *    bit in the I2Ci.I2C_BUF register (the I2Ci.I2C_BUF[15] RDMA_EN
664 	 *    bit for the receive DMA channel, the I2Ci.I2C_BUF[7] XDMA_EN bit
665 	 *    for the transmit DMA channel).
666 	 *
667 	 * Not using DMA for now, so ignore this.
668 	 */
669 
670 	return (0);
671 }
672 
673 static int
674 ti_i2c_iicbus_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
675 {
676 	struct ti_i2c_softc *sc;
677 	int err;
678 
679 	sc = device_get_softc(dev);
680 	TI_I2C_LOCK(sc);
681 	err = ti_i2c_reset(sc, speed);
682 	TI_I2C_UNLOCK(sc);
683 	if (err)
684 		return (err);
685 
686 	return (IIC_ENOADDR);
687 }
688 
689 static int
690 ti_i2c_activate(device_t dev)
691 {
692 	int err;
693 	struct ti_i2c_softc *sc;
694 
695 	sc = (struct ti_i2c_softc*)device_get_softc(dev);
696 
697 	/*
698 	 * 1. Enable the functional and interface clocks (see Section
699 	 * 23.1.5.1.1.1.1).
700 	 */
701 	err = ti_prcm_clk_enable(sc->clk_id);
702 	if (err)
703 		return (err);
704 
705 	return (ti_i2c_reset(sc, IIC_UNKNOWN));
706 }
707 
708 /**
709  *	ti_i2c_deactivate - deactivates the controller and releases resources
710  *	@dev: i2c device handle
711  *
712  *
713  *
714  *	LOCKING:
715  *	Assumed called in an atomic context.
716  *
717  *	RETURNS:
718  *	nothing
719  */
720 static void
721 ti_i2c_deactivate(device_t dev)
722 {
723 	struct ti_i2c_softc *sc = device_get_softc(dev);
724 
725 	/* Disable the controller - cancel all transactions. */
726 	ti_i2c_write_2(sc, I2C_REG_IRQENABLE_CLR, 0xffff);
727 	ti_i2c_write_2(sc, I2C_REG_STATUS, 0xffff);
728 	ti_i2c_write_2(sc, I2C_REG_CON, 0);
729 
730 	/* Release the interrupt handler. */
731 	if (sc->sc_irq_h != NULL) {
732 		bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_irq_h);
733 		sc->sc_irq_h = NULL;
734 	}
735 
736 	bus_generic_detach(sc->sc_dev);
737 
738 	/* Unmap the I2C controller registers. */
739 	if (sc->sc_mem_res != NULL) {
740 		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
741 		sc->sc_mem_res = NULL;
742 	}
743 
744 	/* Release the IRQ resource. */
745 	if (sc->sc_irq_res != NULL) {
746 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
747 		sc->sc_irq_res = NULL;
748 	}
749 
750 	/* Finally disable the functional and interface clocks. */
751 	ti_prcm_clk_disable(sc->clk_id);
752 }
753 
754 static int
755 ti_i2c_sysctl_clk(SYSCTL_HANDLER_ARGS)
756 {
757 	int clk, psc, sclh, scll;
758 	struct ti_i2c_softc *sc;
759 
760 	sc = arg1;
761 
762 	TI_I2C_LOCK(sc);
763 	/* Get the system prescaler value. */
764 	psc = (int)ti_i2c_read_2(sc, I2C_REG_PSC) + 1;
765 
766 	/* Get the bitrate. */
767 	scll = (int)ti_i2c_read_2(sc, I2C_REG_SCLL) & I2C_SCLL_MASK;
768 	sclh = (int)ti_i2c_read_2(sc, I2C_REG_SCLH) & I2C_SCLH_MASK;
769 
770 	clk = I2C_CLK / psc / (scll + 7 + sclh + 5);
771 	TI_I2C_UNLOCK(sc);
772 
773 	return (sysctl_handle_int(oidp, &clk, 0, req));
774 }
775 
776 static int
777 ti_i2c_sysctl_timeout(SYSCTL_HANDLER_ARGS)
778 {
779 	struct ti_i2c_softc *sc;
780 	unsigned int val;
781 	int err;
782 
783 	sc = arg1;
784 
785 	/*
786 	 * MTX_DEF lock can't be held while doing uimove in
787 	 * sysctl_handle_int
788 	 */
789 	TI_I2C_LOCK(sc);
790 	val = sc->sc_timeout;
791 	TI_I2C_UNLOCK(sc);
792 
793 	err = sysctl_handle_int(oidp, &val, 0, req);
794 	/* Write request? */
795 	if ((err == 0) && (req->newptr != NULL)) {
796 		TI_I2C_LOCK(sc);
797 		sc->sc_timeout = val;
798 		TI_I2C_UNLOCK(sc);
799 	}
800 
801 	return (err);
802 }
803 
804 static int
805 ti_i2c_probe(device_t dev)
806 {
807 
808 	if (!ofw_bus_status_okay(dev))
809 		return (ENXIO);
810 	if (!ofw_bus_is_compatible(dev, "ti,omap4-i2c"))
811 		return (ENXIO);
812 	device_set_desc(dev, "TI I2C Controller");
813 
814 	return (0);
815 }
816 
817 static int
818 ti_i2c_attach(device_t dev)
819 {
820 	int err, rid;
821 	phandle_t node;
822 	struct ti_i2c_softc *sc;
823 	struct sysctl_ctx_list *ctx;
824 	struct sysctl_oid_list *tree;
825 	uint16_t fifosz;
826 
827  	sc = device_get_softc(dev);
828 	sc->sc_dev = dev;
829 
830 	/* Get the i2c device id from FDT. */
831 	node = ofw_bus_get_node(dev);
832 	/* i2c ti,hwmods bindings is special: it start with index 1 */
833 	sc->clk_id = ti_hwmods_get_clock(dev);
834 	if (sc->clk_id == INVALID_CLK_IDENT) {
835 		device_printf(dev, "failed to get device id using ti,hwmod\n");
836 		return (ENXIO);
837 	}
838 
839 	/* Get the memory resource for the register mapping. */
840 	rid = 0;
841 	sc->sc_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
842 	    RF_ACTIVE);
843 	if (sc->sc_mem_res == NULL) {
844 		device_printf(dev, "Cannot map registers.\n");
845 		return (ENXIO);
846 	}
847 
848 	/* Allocate our IRQ resource. */
849 	rid = 0;
850 	sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
851 	    RF_ACTIVE | RF_SHAREABLE);
852 	if (sc->sc_irq_res == NULL) {
853 		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
854 		device_printf(dev, "Cannot allocate interrupt.\n");
855 		return (ENXIO);
856 	}
857 
858 	TI_I2C_LOCK_INIT(sc);
859 
860 	/* First of all, we _must_ activate the H/W. */
861 	err = ti_i2c_activate(dev);
862 	if (err) {
863 		device_printf(dev, "ti_i2c_activate failed\n");
864 		goto out;
865 	}
866 
867 	/* Read the version number of the I2C module */
868 	sc->sc_rev = ti_i2c_read_2(sc, I2C_REG_REVNB_HI) & 0xff;
869 
870 	/* Get the fifo size. */
871 	fifosz = ti_i2c_read_2(sc, I2C_REG_BUFSTAT);
872 	fifosz >>= I2C_BUFSTAT_FIFODEPTH_SHIFT;
873 	fifosz &= I2C_BUFSTAT_FIFODEPTH_MASK;
874 
875 	device_printf(dev, "I2C revision %d.%d FIFO size: %d bytes\n",
876 	    sc->sc_rev >> 4, sc->sc_rev & 0xf, 8 << fifosz);
877 
878 	/* Set the FIFO threshold to 5 for now. */
879 	sc->sc_fifo_trsh = 5;
880 
881 	/* Set I2C bus timeout */
882 	sc->sc_timeout = 5*hz;
883 
884 	ctx = device_get_sysctl_ctx(dev);
885 	tree = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
886 	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "i2c_clock",
887 	    CTLFLAG_RD | CTLTYPE_UINT | CTLFLAG_MPSAFE, sc, 0,
888 	    ti_i2c_sysctl_clk, "IU", "I2C bus clock");
889 
890 	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "i2c_timeout",
891 	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_MPSAFE, sc, 0,
892 	    ti_i2c_sysctl_timeout, "IU", "I2C bus timeout (in ticks)");
893 
894 	/* Activate the interrupt. */
895 	err = bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_MISC | INTR_MPSAFE,
896 	    NULL, ti_i2c_intr, sc, &sc->sc_irq_h);
897 	if (err)
898 		goto out;
899 
900 	/* Attach the iicbus. */
901 	if ((sc->sc_iicbus = device_add_child(dev, "iicbus", -1)) == NULL) {
902 		device_printf(dev, "could not allocate iicbus instance\n");
903 		err = ENXIO;
904 		goto out;
905 	}
906 
907 	/* Probe and attach the iicbus when interrupts are available. */
908 	config_intrhook_oneshot((ich_func_t)bus_generic_attach, dev);
909 
910 out:
911 	if (err) {
912 		ti_i2c_deactivate(dev);
913 		TI_I2C_LOCK_DESTROY(sc);
914 	}
915 
916 	return (err);
917 }
918 
919 static int
920 ti_i2c_detach(device_t dev)
921 {
922 	struct ti_i2c_softc *sc;
923 	int rv;
924 
925  	sc = device_get_softc(dev);
926 	ti_i2c_deactivate(dev);
927 	TI_I2C_LOCK_DESTROY(sc);
928 	if (sc->sc_iicbus &&
929 	    (rv = device_delete_child(dev, sc->sc_iicbus)) != 0)
930 		return (rv);
931 
932 	return (0);
933 }
934 
935 static phandle_t
936 ti_i2c_get_node(device_t bus, device_t dev)
937 {
938 
939 	/* Share controller node with iibus device. */
940 	return (ofw_bus_get_node(bus));
941 }
942 
943 static device_method_t ti_i2c_methods[] = {
944 	/* Device interface */
945 	DEVMETHOD(device_probe,		ti_i2c_probe),
946 	DEVMETHOD(device_attach,	ti_i2c_attach),
947 	DEVMETHOD(device_detach,	ti_i2c_detach),
948 
949 	/* Bus interface */
950 	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
951 	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
952 	DEVMETHOD(bus_alloc_resource,	bus_generic_alloc_resource),
953 	DEVMETHOD(bus_release_resource,	bus_generic_release_resource),
954 	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
955 	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
956 	DEVMETHOD(bus_adjust_resource,	bus_generic_adjust_resource),
957 	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
958 	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
959 
960 	/* OFW methods */
961 	DEVMETHOD(ofw_bus_get_node,	ti_i2c_get_node),
962 
963 	/* iicbus interface */
964 	DEVMETHOD(iicbus_callback,	iicbus_null_callback),
965 	DEVMETHOD(iicbus_reset,		ti_i2c_iicbus_reset),
966 	DEVMETHOD(iicbus_transfer,	ti_i2c_transfer),
967 
968 	DEVMETHOD_END
969 };
970 
971 static driver_t ti_i2c_driver = {
972 	"iichb",
973 	ti_i2c_methods,
974 	sizeof(struct ti_i2c_softc),
975 };
976 
977 static devclass_t ti_i2c_devclass;
978 
979 DRIVER_MODULE(ti_iic, simplebus, ti_i2c_driver, ti_i2c_devclass, 0, 0);
980 DRIVER_MODULE(iicbus, ti_iic, iicbus_driver, iicbus_devclass, 0, 0);
981 
982 MODULE_DEPEND(ti_iic, ti_prcm, 1, 1, 1);
983 MODULE_DEPEND(ti_iic, iicbus, 1, 1, 1);
984