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