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