xref: /freebsd/sys/dev/iicbus/iicbb.c (revision 7cc42f6d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1998, 2001 Nicolas Souchu
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 /*
33  * Generic I2C bit-banging code
34  *
35  * Example:
36  *
37  *	iicbus
38  *	 /  \
39  *    iicbb pcf
40  *     |  \
41  *   bti2c lpbb
42  *
43  * From Linux I2C generic interface
44  * (c) 1998 Gerd Knorr <kraxel@cs.tu-berlin.de>
45  *
46  */
47 
48 #include "opt_platform.h"
49 
50 #include <sys/param.h>
51 #include <sys/kernel.h>
52 #include <sys/systm.h>
53 #include <sys/module.h>
54 #include <sys/bus.h>
55 #include <sys/sysctl.h>
56 #include <sys/uio.h>
57 
58 #ifdef FDT
59 #include <dev/ofw/ofw_bus.h>
60 #include <dev/ofw/ofw_bus_subr.h>
61 #include <dev/fdt/fdt_common.h>
62 #endif
63 
64 #include <dev/iicbus/iiconf.h>
65 #include <dev/iicbus/iicbus.h>
66 
67 #include <dev/smbus/smbconf.h>
68 
69 #include "iicbus_if.h"
70 #include "iicbb_if.h"
71 
72 /* Based on the SMBus specification. */
73 #define	DEFAULT_SCL_LOW_TIMEOUT	(25 * 1000)
74 
75 struct iicbb_softc {
76 	device_t iicbus;
77 	u_int udelay;		/* signal toggle delay in usec */
78 	u_int io_latency;	/* approximate pin toggling latency */
79 	u_int scl_low_timeout;
80 };
81 
82 static int iicbb_attach(device_t);
83 static void iicbb_child_detached(device_t, device_t);
84 static int iicbb_detach(device_t);
85 static int iicbb_print_child(device_t, device_t);
86 static int iicbb_probe(device_t);
87 
88 static int iicbb_callback(device_t, int, caddr_t);
89 static int iicbb_start(device_t, u_char, int);
90 static int iicbb_repstart(device_t, u_char, int);
91 static int iicbb_stop(device_t);
92 static int iicbb_write(device_t, const char *, int, int *, int);
93 static int iicbb_read(device_t, char *, int, int *, int, int);
94 static int iicbb_reset(device_t, u_char, u_char, u_char *);
95 static int iicbb_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs);
96 static void iicbb_set_speed(struct iicbb_softc *sc, u_char);
97 #ifdef FDT
98 static phandle_t iicbb_get_node(device_t, device_t);
99 #endif
100 
101 static device_method_t iicbb_methods[] = {
102 	/* device interface */
103 	DEVMETHOD(device_probe,		iicbb_probe),
104 	DEVMETHOD(device_attach,	iicbb_attach),
105 	DEVMETHOD(device_detach,	iicbb_detach),
106 
107 	/* bus interface */
108 	DEVMETHOD(bus_child_detached,	iicbb_child_detached),
109 	DEVMETHOD(bus_print_child,	iicbb_print_child),
110 
111 	/* iicbus interface */
112 	DEVMETHOD(iicbus_callback,	iicbb_callback),
113 	DEVMETHOD(iicbus_start,		iicbb_start),
114 	DEVMETHOD(iicbus_repeated_start, iicbb_repstart),
115 	DEVMETHOD(iicbus_stop,		iicbb_stop),
116 	DEVMETHOD(iicbus_write,		iicbb_write),
117 	DEVMETHOD(iicbus_read,		iicbb_read),
118 	DEVMETHOD(iicbus_reset,		iicbb_reset),
119 	DEVMETHOD(iicbus_transfer,	iicbb_transfer),
120 
121 #ifdef FDT
122 	/* ofw_bus interface */
123 	DEVMETHOD(ofw_bus_get_node,	iicbb_get_node),
124 #endif
125 
126 	{ 0, 0 }
127 };
128 
129 driver_t iicbb_driver = {
130 	"iicbb",
131 	iicbb_methods,
132 	sizeof(struct iicbb_softc),
133 };
134 
135 devclass_t iicbb_devclass;
136 
137 static int
138 iicbb_probe(device_t dev)
139 {
140 	device_set_desc(dev, "I2C bit-banging driver");
141 
142 	return (0);
143 }
144 
145 static int
146 iicbb_attach(device_t dev)
147 {
148 	struct iicbb_softc *sc = (struct iicbb_softc *)device_get_softc(dev);
149 
150 	sc->iicbus = device_add_child(dev, "iicbus", -1);
151 	if (!sc->iicbus)
152 		return (ENXIO);
153 
154 	sc->scl_low_timeout = DEFAULT_SCL_LOW_TIMEOUT;
155 
156 	SYSCTL_ADD_UINT(device_get_sysctl_ctx(dev),
157 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
158 	    "delay", CTLFLAG_RD, &sc->udelay,
159 	    0, "Signal change delay controlled by bus frequency, microseconds");
160 
161 	SYSCTL_ADD_UINT(device_get_sysctl_ctx(dev),
162 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
163 	    "scl_low_timeout", CTLFLAG_RWTUN, &sc->scl_low_timeout,
164 	    0, "SCL low timeout, microseconds");
165 	SYSCTL_ADD_UINT(device_get_sysctl_ctx(dev),
166 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
167 	    "io_latency", CTLFLAG_RWTUN, &sc->io_latency,
168 	    0, "Estimate of pin toggling latency, microseconds");
169 
170 	bus_generic_attach(dev);
171 	return (0);
172 }
173 
174 static int
175 iicbb_detach(device_t dev)
176 {
177 
178 	bus_generic_detach(dev);
179 	device_delete_children(dev);
180 
181 	return (0);
182 }
183 
184 #ifdef FDT
185 static phandle_t
186 iicbb_get_node(device_t bus, device_t dev)
187 {
188 
189 	/* We only have one child, the I2C bus, which needs our own node. */
190 	return (ofw_bus_get_node(bus));
191 }
192 #endif
193 
194 static void
195 iicbb_child_detached( device_t dev, device_t child )
196 {
197 	struct iicbb_softc *sc = (struct iicbb_softc *)device_get_softc(dev);
198 
199 	if (child == sc->iicbus)
200 		sc->iicbus = NULL;
201 }
202 
203 static int
204 iicbb_print_child(device_t bus, device_t dev)
205 {
206 	int error;
207 	int retval = 0;
208 	u_char oldaddr;
209 
210 	retval += bus_print_child_header(bus, dev);
211 	/* retrieve the interface I2C address */
212 	error = IICBB_RESET(device_get_parent(bus), IIC_FASTEST, 0, &oldaddr);
213 	if (error == IIC_ENOADDR) {
214 		retval += printf(" on %s master-only\n",
215 				 device_get_nameunit(bus));
216 	} else {
217 		/* restore the address */
218 		IICBB_RESET(device_get_parent(bus), IIC_FASTEST, oldaddr, NULL);
219 
220 		retval += printf(" on %s addr 0x%x\n",
221 				 device_get_nameunit(bus), oldaddr & 0xff);
222 	}
223 
224 	return (retval);
225 }
226 
227 #define IICBB_DEBUG
228 #ifdef IICBB_DEBUG
229 static int i2c_debug = 0;
230 
231 SYSCTL_DECL(_hw_i2c);
232 SYSCTL_INT(_hw_i2c, OID_AUTO, iicbb_debug, CTLFLAG_RWTUN,
233     &i2c_debug, 0, "Enable i2c bit-banging driver debug");
234 
235 #define I2C_DEBUG(x)	do {		\
236 		if (i2c_debug) (x);	\
237 	} while (0)
238 #else
239 #define I2C_DEBUG(x)
240 #endif
241 
242 #define	I2C_GETSDA(dev)		(IICBB_GETSDA(device_get_parent(dev)))
243 #define	I2C_SETSDA(dev, x)	(IICBB_SETSDA(device_get_parent(dev), x))
244 #define	I2C_GETSCL(dev)		(IICBB_GETSCL(device_get_parent(dev)))
245 #define	I2C_SETSCL(dev, x)	(IICBB_SETSCL(device_get_parent(dev), x))
246 
247 static int
248 iicbb_waitforscl(device_t dev)
249 {
250 	struct iicbb_softc *sc = device_get_softc(dev);
251 	sbintime_t fast_timeout;
252 	sbintime_t now, timeout;
253 
254 	/* Spin for up to 1 ms, then switch to pause. */
255 	now = sbinuptime();
256 	fast_timeout = now + SBT_1MS;
257 	timeout = now + sc->scl_low_timeout * SBT_1US;
258 	do {
259 		if (I2C_GETSCL(dev))
260 			return (0);
261 		now = sbinuptime();
262 	} while (now < fast_timeout);
263 	do {
264 		I2C_DEBUG(printf("."));
265 		pause_sbt("iicbb-scl-low", SBT_1MS, C_PREL(8), 0);
266 		if (I2C_GETSCL(dev))
267 			return (0);
268 		now = sbinuptime();
269 	} while (now < timeout);
270 
271 	I2C_DEBUG(printf("*"));
272 	return (IIC_ETIMEOUT);
273 }
274 
275 /* Start the high phase of the clock. */
276 static int
277 iicbb_clockin(device_t dev, int sda)
278 {
279 
280 	/*
281 	 * Precondition: SCL is low.
282 	 * Action:
283 	 * - set SDA to the value;
284 	 * - release SCL and wait until it's high.
285 	 * The caller is responsible for keeping SCL high for udelay.
286 	 *
287 	 * There should be a data set-up time, 250 ns minimum, between setting
288 	 * SDA and raising SCL.  It's expected that the I/O access latency will
289 	 * naturally provide that delay.
290 	 */
291 	I2C_SETSDA(dev, sda);
292 	I2C_SETSCL(dev, 1);
293 	return (iicbb_waitforscl(dev));
294 }
295 
296 /*
297  * End the high phase of the clock and wait out the low phase
298  * as nothing interesting happens during it anyway.
299  */
300 static void
301 iicbb_clockout(device_t dev)
302 {
303 	struct iicbb_softc *sc = device_get_softc(dev);
304 
305 	/*
306 	 * Precondition: SCL is high.
307 	 * Action:
308 	 * - pull SCL low and hold for udelay.
309 	 */
310 	I2C_SETSCL(dev, 0);
311 	DELAY(sc->udelay);
312 }
313 
314 static int
315 iicbb_sendbit(device_t dev, int bit)
316 {
317 	struct iicbb_softc *sc = device_get_softc(dev);
318 	int err;
319 
320 	err = iicbb_clockin(dev, bit);
321 	if (err != 0)
322 		return (err);
323 	DELAY(sc->udelay);
324 	iicbb_clockout(dev);
325 	return (0);
326 }
327 
328 /*
329  * Waiting for ACKNOWLEDGE.
330  *
331  * When a chip is being addressed or has received data it will issue an
332  * ACKNOWLEDGE pulse. Therefore the MASTER must release the DATA line
333  * (set it to high level) and then release the CLOCK line.
334  * Now it must wait for the SLAVE to pull the DATA line low.
335  * Actually on the bus this looks like a START condition so nothing happens
336  * because of the fact that the IC's that have not been addressed are doing
337  * nothing.
338  *
339  * When the SLAVE has pulled this line low the MASTER will take the CLOCK
340  * line low and then the SLAVE will release the SDA (data) line.
341  */
342 static int
343 iicbb_getack(device_t dev)
344 {
345 	struct iicbb_softc *sc = device_get_softc(dev);
346 	int noack, err;
347 	int t;
348 
349 	/* Release SDA so that the slave can drive it. */
350 	err = iicbb_clockin(dev, 1);
351 	if (err != 0) {
352 		I2C_DEBUG(printf("! "));
353 		return (err);
354 	}
355 
356 	/* Sample SDA until ACK (low) or udelay runs out. */
357 	for (t = 0; t < sc->udelay; t++) {
358 		noack = I2C_GETSDA(dev);
359 		if (!noack)
360 			break;
361 		DELAY(1);
362 	}
363 
364 	DELAY(sc->udelay - t);
365 	iicbb_clockout(dev);
366 
367 	I2C_DEBUG(printf("%c ", noack ? '-' : '+'));
368 	return (noack ? IIC_ENOACK : 0);
369 }
370 
371 static int
372 iicbb_sendbyte(device_t dev, uint8_t data)
373 {
374 	int err, i;
375 
376 	for (i = 7; i >= 0; i--) {
377 		err = iicbb_sendbit(dev, (data & (1 << i)) != 0);
378 		if (err != 0) {
379 			I2C_DEBUG(printf("w!"));
380 			return (err);
381 		}
382 	}
383 	I2C_DEBUG(printf("w%02x", data));
384 	return (0);
385 }
386 
387 static int
388 iicbb_readbyte(device_t dev, bool last, uint8_t *data)
389 {
390 	struct iicbb_softc *sc = device_get_softc(dev);
391 	int i, err;
392 
393 	/*
394 	 * Release SDA so that the slave can drive it.
395 	 * We do not use iicbb_clockin() here because we need to release SDA
396 	 * only once and then we just pulse the SCL.
397 	 */
398 	*data = 0;
399 	I2C_SETSDA(dev, 1);
400 	for (i = 7; i >= 0; i--) {
401 		I2C_SETSCL(dev, 1);
402 		err = iicbb_waitforscl(dev);
403 		if (err != 0) {
404 			I2C_DEBUG(printf("r! "));
405 			return (err);
406 		}
407 		DELAY((sc->udelay + 1) / 2);
408 		if (I2C_GETSDA(dev))
409 			*data |= 1 << i;
410 		DELAY((sc->udelay + 1) / 2);
411 		iicbb_clockout(dev);
412 	}
413 
414 	/*
415 	 * Send master->slave ACK (low) for more data,
416 	 * NoACK (high) otherwise.
417 	 */
418 	iicbb_sendbit(dev, last);
419 	I2C_DEBUG(printf("r%02x%c ", *data, last ? '-' : '+'));
420 	return (0);
421 }
422 
423 static int
424 iicbb_callback(device_t dev, int index, caddr_t data)
425 {
426 	return (IICBB_CALLBACK(device_get_parent(dev), index, data));
427 }
428 
429 static int
430 iicbb_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
431 {
432 	iicbb_set_speed(device_get_softc(dev), speed);
433 	return (IICBB_RESET(device_get_parent(dev), speed, addr, oldaddr));
434 }
435 
436 static int
437 iicbb_start_impl(device_t dev, u_char slave, bool repstart)
438 {
439 	struct iicbb_softc *sc = device_get_softc(dev);
440 	int error;
441 
442 	if (!repstart) {
443 		I2C_DEBUG(printf("<<"));
444 
445 		/* SCL must be high on the idle bus. */
446 		if (iicbb_waitforscl(dev) != 0) {
447 			I2C_DEBUG(printf("C!\n"));
448 			return (IIC_EBUSERR);
449 		}
450 	} else {
451 		I2C_DEBUG(printf("<"));
452 		error = iicbb_clockin(dev, 1);
453 		if (error != 0)
454 			return (error);
455 
456 		/* SDA will go low in the middle of the SCL high phase. */
457 		DELAY((sc->udelay + 1) / 2);
458 	}
459 
460 	/*
461 	 * SDA must be high after the earlier stop condition or the end
462 	 * of Ack/NoAck pulse.
463 	 */
464 	if (!I2C_GETSDA(dev)) {
465 		I2C_DEBUG(printf("D!\n"));
466 		return (IIC_EBUSERR);
467 	}
468 
469 	/* Start: SDA high->low. */
470 	I2C_SETSDA(dev, 0);
471 
472 	/* Wait the second half of the SCL high phase. */
473 	DELAY((sc->udelay + 1) / 2);
474 
475 	/* Pull SCL low to keep the bus reserved. */
476 	iicbb_clockout(dev);
477 
478 	/* send address */
479 	error = iicbb_sendbyte(dev, slave);
480 
481 	/* check for ack */
482 	if (error == 0)
483 		error = iicbb_getack(dev);
484 	if (error != 0)
485 		(void)iicbb_stop(dev);
486 	return (error);
487 }
488 
489 /* NB: the timeout is ignored. */
490 static int
491 iicbb_start(device_t dev, u_char slave, int timeout)
492 {
493 	return (iicbb_start_impl(dev, slave, false));
494 }
495 
496 /* NB: the timeout is ignored. */
497 static int
498 iicbb_repstart(device_t dev, u_char slave, int timeout)
499 {
500 	return (iicbb_start_impl(dev, slave, true));
501 }
502 
503 static int
504 iicbb_stop(device_t dev)
505 {
506 	struct iicbb_softc *sc = device_get_softc(dev);
507 	int err = 0;
508 
509 	/*
510 	 * Stop: SDA goes from low to high in the middle of the SCL high phase.
511 	 */
512 	err = iicbb_clockin(dev, 0);
513 	if (err != 0)
514 		return (err);
515 	DELAY((sc->udelay + 1) / 2);
516 	I2C_SETSDA(dev, 1);
517 	DELAY((sc->udelay + 1) / 2);
518 
519 	I2C_DEBUG(printf("%s>>", err != 0 ? "!" : ""));
520 	I2C_DEBUG(printf("\n"));
521 	return (err);
522 }
523 
524 /* NB: the timeout is ignored. */
525 static int
526 iicbb_write(device_t dev, const char *buf, int len, int *sent, int timeout)
527 {
528 	int bytes, error = 0;
529 
530 	bytes = 0;
531 	while (len > 0) {
532 		/* send byte */
533 		iicbb_sendbyte(dev, (uint8_t)*buf++);
534 
535 		/* check for ack */
536 		error = iicbb_getack(dev);
537 		if (error != 0)
538 			break;
539 		bytes++;
540 		len--;
541 	}
542 
543 	*sent = bytes;
544 	return (error);
545 }
546 
547 /* NB: whatever delay is, it's ignored. */
548 static int
549 iicbb_read(device_t dev, char *buf, int len, int *read, int last, int delay)
550 {
551 	int bytes = 0;
552 	int err = 0;
553 
554 	while (len > 0) {
555 		err = iicbb_readbyte(dev, (len == 1) ? last : 0,
556 		    (uint8_t *)buf);
557 		if (err != 0)
558 			break;
559 		buf++;
560 		bytes++;
561 		len--;
562 	}
563 
564 	*read = bytes;
565 	return (err);
566 }
567 
568 static int
569 iicbb_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
570 {
571 	int error;
572 
573 	error = IICBB_PRE_XFER(device_get_parent(dev));
574 	if (error)
575 		return (error);
576 
577 	error = iicbus_transfer_gen(dev, msgs, nmsgs);
578 
579 	IICBB_POST_XFER(device_get_parent(dev));
580 	return (error);
581 }
582 
583 static void
584 iicbb_set_speed(struct iicbb_softc *sc, u_char speed)
585 {
586 	u_int busfreq;
587 	int period;
588 
589 	/*
590 	 * udelay is half a period, the clock is held high or low for this long.
591 	 */
592 	busfreq = IICBUS_GET_FREQUENCY(sc->iicbus, speed);
593 	period = 1000000 / 2 / busfreq;	/* Hz -> uS */
594 	period -= sc->io_latency;
595 	sc->udelay = MAX(period, 1);
596 }
597 
598 DRIVER_MODULE(iicbus, iicbb, iicbus_driver, iicbus_devclass, 0, 0);
599 
600 MODULE_DEPEND(iicbb, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
601 MODULE_VERSION(iicbb, IICBB_MODVER);
602