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