xref: /freebsd/sys/arm/freescale/imx/imx_i2c.c (revision b64c5a0ace59af62eff52bfe110a521dc73c937b)
1 /*-
2  * Copyright (C) 2008-2009 Semihalf, Michal Hajduk
3  * Copyright (c) 2012, 2013 The FreeBSD Foundation
4  * Copyright (c) 2015 Ian Lepore <ian@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Oleksandr Rybalko
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  * I2C driver for Freescale i.MX hardware.
34  *
35  * Note that the hardware is capable of running as both a master and a slave.
36  * This driver currently implements only master-mode operations.
37  *
38  * This driver supports multi-master i2c buses, by detecting bus arbitration
39  * loss and returning IIC_EBUSBSY status.  Notably, it does not do any kind of
40  * retries if some other master jumps onto the bus and interrupts one of our
41  * transfer cycles resulting in arbitration loss in mid-transfer.  The caller
42  * must handle retries in a way that makes sense for the slave being addressed.
43  */
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/bus.h>
48 #include <sys/gpio.h>
49 #include <sys/kernel.h>
50 #include <sys/limits.h>
51 #include <sys/module.h>
52 #include <sys/resource.h>
53 #include <sys/sysctl.h>
54 
55 #include <machine/bus.h>
56 #include <machine/resource.h>
57 #include <sys/rman.h>
58 
59 #include <arm/freescale/imx/imx_ccmvar.h>
60 
61 #include <dev/iicbus/iiconf.h>
62 #include <dev/iicbus/iicbus.h>
63 #include <dev/iicbus/iic_recover_bus.h>
64 #include "iicbus_if.h"
65 
66 #include <dev/ofw/openfirm.h>
67 #include <dev/ofw/ofw_bus.h>
68 #include <dev/ofw/ofw_bus_subr.h>
69 
70 #include <dev/fdt/fdt_pinctrl.h>
71 #include <dev/gpio/gpiobusvar.h>
72 
73 #if defined(__aarch64__)
74 #define	IMX_ENABLE_CLOCKS
75 #endif
76 
77 #ifdef IMX_ENABLE_CLOCKS
78 #include <dev/clk/clk.h>
79 #endif
80 
81 #define I2C_ADDR_REG		0x00 /* I2C slave address register */
82 #define I2C_FDR_REG		0x04 /* I2C frequency divider register */
83 #define I2C_CONTROL_REG		0x08 /* I2C control register */
84 #define I2C_STATUS_REG		0x0C /* I2C status register */
85 #define I2C_DATA_REG		0x10 /* I2C data register */
86 #define I2C_DFSRR_REG		0x14 /* I2C Digital Filter Sampling rate */
87 
88 #define I2CCR_MEN		(1 << 7) /* Module enable */
89 #define I2CCR_MSTA		(1 << 5) /* Master/slave mode */
90 #define I2CCR_MTX		(1 << 4) /* Transmit/receive mode */
91 #define I2CCR_TXAK		(1 << 3) /* Transfer acknowledge */
92 #define I2CCR_RSTA		(1 << 2) /* Repeated START */
93 
94 #define I2CSR_MCF		(1 << 7) /* Data transfer */
95 #define I2CSR_MASS		(1 << 6) /* Addressed as a slave */
96 #define I2CSR_MBB		(1 << 5) /* Bus busy */
97 #define I2CSR_MAL		(1 << 4) /* Arbitration lost */
98 #define I2CSR_SRW		(1 << 2) /* Slave read/write */
99 #define I2CSR_MIF		(1 << 1) /* Module interrupt */
100 #define I2CSR_RXAK		(1 << 0) /* Received acknowledge */
101 
102 #define I2C_BAUD_RATE_FAST	0x31
103 #define I2C_BAUD_RATE_DEF	0x3F
104 #define I2C_DFSSR_DIV		0x10
105 
106 /*
107  * A table of available divisors and the associated coded values to put in the
108  * FDR register to achieve that divisor.. There is no algorithmic relationship I
109  * can see between divisors and the codes that go into the register.  The table
110  * begins and ends with entries that handle insane configuration values.
111  */
112 struct clkdiv {
113 	u_int divisor;
114 	u_int regcode;
115 };
116 static struct clkdiv clkdiv_table[] = {
117         {    0, 0x20 }, {   22, 0x20 }, {   24, 0x21 }, {   26, 0x22 },
118         {   28, 0x23 }, {   30, 0x00 }, {   32, 0x24 }, {   36, 0x25 },
119         {   40, 0x26 }, {   42, 0x03 }, {   44, 0x27 }, {   48, 0x28 },
120         {   52, 0x05 }, {   56, 0x29 }, {   60, 0x06 }, {   64, 0x2a },
121         {   72, 0x2b }, {   80, 0x2c }, {   88, 0x09 }, {   96, 0x2d },
122         {  104, 0x0a }, {  112, 0x2e }, {  128, 0x2f }, {  144, 0x0c },
123         {  160, 0x30 }, {  192, 0x31 }, {  224, 0x32 }, {  240, 0x0f },
124         {  256, 0x33 }, {  288, 0x10 }, {  320, 0x34 }, {  384, 0x35 },
125         {  448, 0x36 }, {  480, 0x13 }, {  512, 0x37 }, {  576, 0x14 },
126         {  640, 0x38 }, {  768, 0x39 }, {  896, 0x3a }, {  960, 0x17 },
127         { 1024, 0x3b }, { 1152, 0x18 }, { 1280, 0x3c }, { 1536, 0x3d },
128         { 1792, 0x3e }, { 1920, 0x1b }, { 2048, 0x3f }, { 2304, 0x1c },
129         { 2560, 0x1d }, { 3072, 0x1e }, { 3840, 0x1f }, {UINT_MAX, 0x1f}
130 };
131 
132 static struct ofw_compat_data compat_data[] = {
133 	{"fsl,imx21-i2c",  1},
134 	{"fsl,imx6q-i2c",  1},
135 	{"fsl,imx-i2c",	   1},
136 	{NULL,             0}
137 };
138 
139 struct i2c_softc {
140 	device_t		dev;
141 	device_t		iicbus;
142 	struct resource		*res;
143 	int			rid;
144 	sbintime_t		byte_time_sbt;
145 	int			rb_pinctl_idx;
146 	gpio_pin_t		rb_sclpin;
147 	gpio_pin_t 		rb_sdapin;
148 	u_int			debug;
149 	u_int			slave;
150 #ifdef IMX_ENABLE_CLOCKS
151 	clk_t			ipgclk;
152 #endif
153 };
154 
155 #define DEVICE_DEBUGF(sc, lvl, fmt, args...) \
156     if ((lvl) <= (sc)->debug) \
157         device_printf((sc)->dev, fmt, ##args)
158 
159 #define DEBUGF(sc, lvl, fmt, args...) \
160     if ((lvl) <= (sc)->debug) \
161         printf(fmt, ##args)
162 
163 static phandle_t i2c_get_node(device_t, device_t);
164 static int i2c_probe(device_t);
165 static int i2c_attach(device_t);
166 static int i2c_detach(device_t);
167 
168 static int i2c_repeated_start(device_t, u_char, int);
169 static int i2c_start(device_t, u_char, int);
170 static int i2c_stop(device_t);
171 static int i2c_reset(device_t, u_char, u_char, u_char *);
172 static int i2c_read(device_t, char *, int, int *, int, int);
173 static int i2c_write(device_t, const char *, int, int *, int);
174 
175 static device_method_t i2c_methods[] = {
176 	DEVMETHOD(device_probe,			i2c_probe),
177 	DEVMETHOD(device_attach,		i2c_attach),
178 	DEVMETHOD(device_detach,		i2c_detach),
179 
180 	/* OFW methods */
181 	DEVMETHOD(ofw_bus_get_node,		i2c_get_node),
182 
183 	DEVMETHOD(iicbus_callback,		iicbus_null_callback),
184 	DEVMETHOD(iicbus_repeated_start,	i2c_repeated_start),
185 	DEVMETHOD(iicbus_start,			i2c_start),
186 	DEVMETHOD(iicbus_stop,			i2c_stop),
187 	DEVMETHOD(iicbus_reset,			i2c_reset),
188 	DEVMETHOD(iicbus_read,			i2c_read),
189 	DEVMETHOD(iicbus_write,			i2c_write),
190 	DEVMETHOD(iicbus_transfer,		iicbus_transfer_gen),
191 
192 	DEVMETHOD_END
193 };
194 
195 static driver_t i2c_driver = {
196 	"imx_i2c",
197 	i2c_methods,
198 	sizeof(struct i2c_softc),
199 };
200 
201 DRIVER_MODULE(imx_i2c, simplebus, i2c_driver, 0, 0);
202 DRIVER_MODULE(ofw_iicbus, imx_i2c, ofw_iicbus_driver, 0, 0);
203 MODULE_DEPEND(imx_i2c, iicbus, 1, 1, 1);
204 SIMPLEBUS_PNP_INFO(compat_data);
205 
206 static phandle_t
207 i2c_get_node(device_t bus, device_t dev)
208 {
209 	/*
210 	 * Share controller node with iicbus device
211 	 */
212 	return ofw_bus_get_node(bus);
213 }
214 
215 static __inline void
216 i2c_write_reg(struct i2c_softc *sc, bus_size_t off, uint8_t val)
217 {
218 
219 	bus_write_1(sc->res, off, val);
220 }
221 
222 static __inline uint8_t
223 i2c_read_reg(struct i2c_softc *sc, bus_size_t off)
224 {
225 
226 	return (bus_read_1(sc->res, off));
227 }
228 
229 static __inline void
230 i2c_flag_set(struct i2c_softc *sc, bus_size_t off, uint8_t mask)
231 {
232 	uint8_t status;
233 
234 	status = i2c_read_reg(sc, off);
235 	status |= mask;
236 	i2c_write_reg(sc, off, status);
237 }
238 
239 /* Wait for bus to become busy or not-busy. */
240 static int
241 wait_for_busbusy(struct i2c_softc *sc, int wantbusy)
242 {
243 	int retry, srb;
244 
245 	retry = 1000;
246 	while (retry --) {
247 		srb = i2c_read_reg(sc, I2C_STATUS_REG) & I2CSR_MBB;
248 		if ((srb && wantbusy) || (!srb && !wantbusy))
249 			return (IIC_NOERR);
250 		DELAY(1);
251 	}
252 	return (IIC_ETIMEOUT);
253 }
254 
255 /* Wait for transfer to complete, optionally check RXAK. */
256 static int
257 wait_for_xfer(struct i2c_softc *sc, int checkack)
258 {
259 	int retry, sr;
260 
261 	/*
262 	 * Sleep for about the time it takes to transfer a byte (with precision
263 	 * set to tolerate 5% oversleep).  We calculate the approximate byte
264 	 * transfer time when we set the bus speed divisor.  Slaves are allowed
265 	 * to do clock-stretching so the actual transfer time can be larger, but
266 	 * this gets the bulk of the waiting out of the way without tying up the
267 	 * processor the whole time.
268 	 */
269 	pause_sbt("imxi2c", sc->byte_time_sbt, sc->byte_time_sbt / 20, 0);
270 
271 	retry = 10000;
272 	while (retry --) {
273 		sr = i2c_read_reg(sc, I2C_STATUS_REG);
274 		if (sr & I2CSR_MIF) {
275                         if (sr & I2CSR_MAL)
276 				return (IIC_EBUSERR);
277 			else if (checkack && (sr & I2CSR_RXAK))
278 				return (IIC_ENOACK);
279 			else
280 				return (IIC_NOERR);
281 		}
282 		DELAY(1);
283 	}
284 	return (IIC_ETIMEOUT);
285 }
286 
287 /*
288  * Implement the error handling shown in the state diagram of the imx6 reference
289  * manual.  If there was an error, then:
290  *  - Clear master mode (MSTA and MTX).
291  *  - Wait for the bus to become free or for a timeout to happen.
292  *  - Disable the controller.
293  */
294 static int
295 i2c_error_handler(struct i2c_softc *sc, int error)
296 {
297 
298 	if (error != 0) {
299 		i2c_write_reg(sc, I2C_STATUS_REG, 0);
300 		i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN);
301 		wait_for_busbusy(sc, false);
302 		i2c_write_reg(sc, I2C_CONTROL_REG, 0);
303 	}
304 	return (error);
305 }
306 
307 static int
308 i2c_recover_getsda(void *ctx)
309 {
310 	bool active;
311 
312 	gpio_pin_is_active(((struct i2c_softc *)ctx)->rb_sdapin, &active);
313 	return (active);
314 }
315 
316 static void
317 i2c_recover_setsda(void *ctx, int value)
318 {
319 
320 	gpio_pin_set_active(((struct i2c_softc *)ctx)->rb_sdapin, value);
321 }
322 
323 static int
324 i2c_recover_getscl(void *ctx)
325 {
326 	bool active;
327 
328 	gpio_pin_is_active(((struct i2c_softc *)ctx)->rb_sclpin, &active);
329 	return (active);
330 
331 }
332 
333 static void
334 i2c_recover_setscl(void *ctx, int value)
335 {
336 
337 	gpio_pin_set_active(((struct i2c_softc *)ctx)->rb_sclpin, value);
338 }
339 
340 static int
341 i2c_recover_bus(struct i2c_softc *sc)
342 {
343 	struct iicrb_pin_access pins;
344 	int err;
345 
346 	/*
347 	 * If we have gpio pinmux config, reconfigure the pins to gpio mode,
348 	 * invoke iic_recover_bus which checks for a hung bus and bitbangs a
349 	 * recovery sequence if necessary, then configure the pins back to i2c
350 	 * mode (idx 0).
351 	 */
352 	if (sc->rb_pinctl_idx == 0)
353 		return (0);
354 
355 	fdt_pinctrl_configure(sc->dev, sc->rb_pinctl_idx);
356 
357 	pins.ctx = sc;
358 	pins.getsda = i2c_recover_getsda;
359 	pins.setsda = i2c_recover_setsda;
360 	pins.getscl = i2c_recover_getscl;
361 	pins.setscl = i2c_recover_setscl;
362 	err = iic_recover_bus(&pins);
363 
364 	fdt_pinctrl_configure(sc->dev, 0);
365 
366 	return (err);
367 }
368 
369 static int
370 i2c_probe(device_t dev)
371 {
372 
373 	if (!ofw_bus_status_okay(dev))
374 		return (ENXIO);
375 
376 	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0)
377 		return (ENXIO);
378 
379 	device_set_desc(dev, "Freescale i.MX I2C");
380 
381 	return (BUS_PROBE_DEFAULT);
382 }
383 
384 static int
385 i2c_attach(device_t dev)
386 {
387 	char wrkstr[16];
388 	struct i2c_softc *sc;
389 	phandle_t node;
390 	int err, cfgidx;
391 
392 	sc = device_get_softc(dev);
393 	sc->dev = dev;
394 	sc->rid = 0;
395 
396 #ifdef IMX_ENABLE_CLOCKS
397 	if (clk_get_by_ofw_index(sc->dev, 0, 0, &sc->ipgclk) != 0) {
398 		device_printf(dev, "could not get ipg clock");
399 		return (ENOENT);
400 	}
401 
402 	err = clk_enable(sc->ipgclk);
403 	if (err != 0) {
404 		device_printf(sc->dev, "could not enable ipg clock\n");
405 		return (err);
406 	}
407 #endif
408 
409 	sc->res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &sc->rid,
410 	    RF_ACTIVE);
411 	if (sc->res == NULL) {
412 		device_printf(dev, "could not allocate resources");
413 		return (ENXIO);
414 	}
415 
416 	sc->iicbus = device_add_child(dev, "iicbus", DEVICE_UNIT_ANY);
417 	if (sc->iicbus == NULL) {
418 		device_printf(dev, "could not add iicbus child");
419 		return (ENXIO);
420 	}
421 
422 	/* Set up debug-enable sysctl. */
423 	SYSCTL_ADD_INT(device_get_sysctl_ctx(sc->dev),
424 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)),
425 	    OID_AUTO, "debug", CTLFLAG_RWTUN, &sc->debug, 0,
426 	    "Enable debug; 1=reads/writes, 2=add starts/stops");
427 
428 	/*
429 	 * Set up for bus recovery using gpio pins, if the pinctrl and gpio
430 	 * properties are present.  This is optional.  If all the config data is
431 	 * not in place, we just don't do gpio bitbang bus recovery.
432 	 */
433 	node = ofw_bus_get_node(sc->dev);
434 
435 	err = gpio_pin_get_by_ofw_property(dev, node, "scl-gpios",
436 	    &sc->rb_sclpin);
437 	if (err != 0)
438 		goto no_recovery;
439 	err = gpio_pin_get_by_ofw_property(dev, node, "sda-gpios",
440 	    &sc->rb_sdapin);
441 	if (err != 0)
442 		goto no_recovery;
443 
444 	/*
445 	 * Preset the gpio pins to output high (idle bus state).  The signal
446 	 * won't actually appear on the pins until the bus recovery code changes
447 	 * the pinmux config from i2c to gpio.
448 	 */
449 	gpio_pin_setflags(sc->rb_sclpin, GPIO_PIN_OUTPUT);
450 	gpio_pin_setflags(sc->rb_sdapin, GPIO_PIN_OUTPUT);
451 	gpio_pin_set_active(sc->rb_sclpin, true);
452 	gpio_pin_set_active(sc->rb_sdapin, true);
453 
454 	/*
455 	 * Obtain the index of pinctrl node for bus recovery using gpio pins,
456 	 * then confirm that pinctrl properties exist for that index and for the
457 	 * default pinctrl-0.  If sc->rb_pinctl_idx is non-zero, the reset code
458 	 * will also do a bus recovery, so setting this value must be last.
459 	 */
460 	err = ofw_bus_find_string_index(node, "pinctrl-names", "gpio", &cfgidx);
461 	if (err == 0) {
462 		snprintf(wrkstr, sizeof(wrkstr), "pinctrl-%d", cfgidx);
463 		if (OF_hasprop(node, "pinctrl-0") && OF_hasprop(node, wrkstr))
464 			sc->rb_pinctl_idx = cfgidx;
465 	}
466 
467 no_recovery:
468 
469 	/* We don't do a hardware reset here because iicbus_attach() does it. */
470 
471 	/* Probe and attach the iicbus when interrupts are available. */
472 	bus_delayed_attach_children(dev);
473 	return (0);
474 }
475 
476 static int
477 i2c_detach(device_t dev)
478 {
479 	struct i2c_softc *sc;
480 	int error;
481 
482 	sc = device_get_softc(dev);
483 
484 #ifdef IMX_ENABLE_CLOCKS
485 	error = clk_disable(sc->ipgclk);
486 	if (error != 0) {
487 		device_printf(sc->dev, "could not disable ipg clock\n");
488 		return (error);
489 	}
490 #endif
491 
492 	if ((error = bus_generic_detach(sc->dev)) != 0) {
493 		device_printf(sc->dev, "cannot detach child devices\n");
494 		return (error);
495 	}
496 
497 	if (sc->iicbus != NULL)
498 		device_delete_child(dev, sc->iicbus);
499 
500 	/* Release bus-recover pins; gpio_pin_release() handles NULL args. */
501 	gpio_pin_release(sc->rb_sclpin);
502 	gpio_pin_release(sc->rb_sdapin);
503 
504 	if (sc->res != NULL)
505 		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->res);
506 
507 	return (0);
508 }
509 
510 static int
511 i2c_repeated_start(device_t dev, u_char slave, int timeout)
512 {
513 	struct i2c_softc *sc;
514 	int error;
515 
516 	sc = device_get_softc(dev);
517 
518 	if ((i2c_read_reg(sc, I2C_STATUS_REG) & I2CSR_MBB) == 0) {
519 		return (IIC_EBUSERR);
520 	}
521 
522 	/*
523 	 * Set repeated start condition, delay (per reference manual, min 156nS)
524 	 * before writing slave address, wait for ack after write.
525 	 */
526 	i2c_flag_set(sc, I2C_CONTROL_REG, I2CCR_RSTA);
527 	DELAY(1);
528 	i2c_write_reg(sc, I2C_STATUS_REG, 0x0);
529 	i2c_write_reg(sc, I2C_DATA_REG, slave);
530 	sc->slave = slave;
531 	DEVICE_DEBUGF(sc, 2, "rstart 0x%02x\n", sc->slave);
532 	error = wait_for_xfer(sc, true);
533 	return (i2c_error_handler(sc, error));
534 }
535 
536 static int
537 i2c_start_ll(device_t dev, u_char slave, int timeout)
538 {
539 	struct i2c_softc *sc;
540 	int error;
541 
542 	sc = device_get_softc(dev);
543 
544 	i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN);
545 	DELAY(10); /* Delay for controller to sample bus state. */
546 	if (i2c_read_reg(sc, I2C_STATUS_REG) & I2CSR_MBB) {
547 		return (i2c_error_handler(sc, IIC_EBUSERR));
548 	}
549 	i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN | I2CCR_MSTA | I2CCR_MTX);
550 	if ((error = wait_for_busbusy(sc, true)) != IIC_NOERR)
551 		return (i2c_error_handler(sc, error));
552 	i2c_write_reg(sc, I2C_STATUS_REG, 0);
553 	i2c_write_reg(sc, I2C_DATA_REG, slave);
554 	sc->slave = slave;
555 	DEVICE_DEBUGF(sc, 2, "start  0x%02x\n", sc->slave);
556 	error = wait_for_xfer(sc, true);
557 	return (i2c_error_handler(sc, error));
558 }
559 
560 static int
561 i2c_start(device_t dev, u_char slave, int timeout)
562 {
563 	struct i2c_softc *sc;
564 	int error;
565 
566 	sc = device_get_softc(dev);
567 
568 	/*
569 	 * Invoke the low-level code to put the bus into master mode and address
570 	 * the given slave.  If that fails, idle the controller and attempt a
571 	 * bus recovery, and then try again one time.  Signaling a start and
572 	 * addressing the slave is the only operation that a low-level driver
573 	 * can safely retry without any help from the upper layers that know
574 	 * more about the slave device.
575 	 */
576 	if ((error = i2c_start_ll(dev, slave, timeout)) != 0) {
577 		i2c_write_reg(sc, I2C_CONTROL_REG, 0x0);
578 		if ((error = i2c_recover_bus(sc)) != 0)
579 			return (error);
580 		error = i2c_start_ll(dev, slave, timeout);
581 	}
582 	return (error);
583 }
584 
585 static int
586 i2c_stop(device_t dev)
587 {
588 	struct i2c_softc *sc;
589 
590 	sc = device_get_softc(dev);
591 
592 	i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN);
593 	wait_for_busbusy(sc, false);
594 	i2c_write_reg(sc, I2C_CONTROL_REG, 0);
595 	DEVICE_DEBUGF(sc, 2, "stop   0x%02x\n", sc->slave);
596 	return (IIC_NOERR);
597 }
598 
599 static int
600 i2c_reset(device_t dev, u_char speed, u_char addr, u_char *oldadr)
601 {
602 	struct i2c_softc *sc;
603 	u_int busfreq, div, i, ipgfreq;
604 #ifdef IMX_ENABLE_CLOCKS
605 	int err;
606 	uint64_t freq;
607 #endif
608 
609 	sc = device_get_softc(dev);
610 
611 	DEVICE_DEBUGF(sc, 1, "reset\n");
612 
613 	/*
614 	 * Look up the divisor that gives the nearest speed that doesn't exceed
615 	 * the configured value for the bus.
616 	 */
617 #ifdef IMX_ENABLE_CLOCKS
618 	err = clk_get_freq(sc->ipgclk, &freq);
619 	if (err != 0) {
620 		device_printf(sc->dev, "cannot get frequency\n");
621 		return (err);
622 	}
623 	ipgfreq = (int32_t)freq;
624 #else
625 	ipgfreq = imx_ccm_ipg_hz();
626 #endif
627 	busfreq = IICBUS_GET_FREQUENCY(sc->iicbus, speed);
628 	div = howmany(ipgfreq, busfreq);
629 	for (i = 0; i < nitems(clkdiv_table); i++) {
630 		if (clkdiv_table[i].divisor >= div)
631 			break;
632 	}
633 
634 	/*
635 	 * Calculate roughly how long it will take to transfer a byte (which
636 	 * requires 9 clock cycles) at the new bus speed.  This value is used to
637 	 * pause() while waiting for transfer-complete.  With a 66MHz IPG clock
638 	 * and the actual i2c bus speeds that leads to, for nominal 100KHz and
639 	 * 400KHz bus speeds the transfer times are roughly 104uS and 22uS.
640 	 */
641 	busfreq = ipgfreq / clkdiv_table[i].divisor;
642 	sc->byte_time_sbt = SBT_1US * (9000000 / busfreq);
643 
644 	/*
645 	 * Disable the controller (do the reset), and set the new clock divisor.
646 	 */
647 	i2c_write_reg(sc, I2C_STATUS_REG, 0x0);
648 	i2c_write_reg(sc, I2C_CONTROL_REG, 0x0);
649 	i2c_write_reg(sc, I2C_FDR_REG, (uint8_t)clkdiv_table[i].regcode);
650 
651 	/*
652 	 * Now that the controller is idle, perform bus recovery.  If the bus
653 	 * isn't hung, this a fairly fast no-op.
654 	 */
655 	return (i2c_recover_bus(sc));
656 }
657 
658 static int
659 i2c_read(device_t dev, char *buf, int len, int *read, int last, int delay)
660 {
661 	struct i2c_softc *sc;
662 	int error, reg;
663 
664 	sc = device_get_softc(dev);
665 	*read = 0;
666 
667 	DEVICE_DEBUGF(sc, 1, "read   0x%02x len %d: ", sc->slave, len);
668 	if (len) {
669 		if (len == 1)
670 			i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN |
671 			    I2CCR_MSTA | I2CCR_TXAK);
672 		else
673 			i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN |
674 			    I2CCR_MSTA);
675                 /* Dummy read to prime the receiver. */
676 		i2c_write_reg(sc, I2C_STATUS_REG, 0x0);
677 		i2c_read_reg(sc, I2C_DATA_REG);
678 	}
679 
680 	error = 0;
681 	*read = 0;
682 	while (*read < len) {
683 		if ((error = wait_for_xfer(sc, false)) != IIC_NOERR)
684 			break;
685 		i2c_write_reg(sc, I2C_STATUS_REG, 0x0);
686 		if (last) {
687 			if (*read == len - 2) {
688 				/* NO ACK on last byte */
689 				i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN |
690 				    I2CCR_MSTA | I2CCR_TXAK);
691 			} else if (*read == len - 1) {
692 				/* Transfer done, signal stop. */
693 				i2c_write_reg(sc, I2C_CONTROL_REG, I2CCR_MEN |
694 				    I2CCR_TXAK);
695 				wait_for_busbusy(sc, false);
696 			}
697 		}
698 		reg = i2c_read_reg(sc, I2C_DATA_REG);
699 		DEBUGF(sc, 1, "0x%02x ", reg);
700 		*buf++ = reg;
701 		(*read)++;
702 	}
703 	DEBUGF(sc, 1, "\n");
704 
705 	return (i2c_error_handler(sc, error));
706 }
707 
708 static int
709 i2c_write(device_t dev, const char *buf, int len, int *sent, int timeout)
710 {
711 	struct i2c_softc *sc;
712 	int error;
713 
714 	sc = device_get_softc(dev);
715 
716 	error = 0;
717 	*sent = 0;
718 	DEVICE_DEBUGF(sc, 1, "write  0x%02x len %d: ", sc->slave, len);
719 	while (*sent < len) {
720 		DEBUGF(sc, 1, "0x%02x ", *buf);
721 		i2c_write_reg(sc, I2C_STATUS_REG, 0x0);
722 		i2c_write_reg(sc, I2C_DATA_REG, *buf++);
723 		if ((error = wait_for_xfer(sc, true)) != IIC_NOERR)
724 			break;
725 		(*sent)++;
726 	}
727 	DEBUGF(sc, 1, "\n");
728 	return (i2c_error_handler(sc, error));
729 }
730