xref: /freebsd/sys/dev/iicbus/iicbb.c (revision dd21556857e8d40f66bf5ad54754d9d52669ebf7)
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
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", 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
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
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
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
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
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
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
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
330 iicbb_getack(device_t dev)
331 {
332 	struct iicbb_softc *sc = device_get_softc(dev);
333 	int noack, err;
334 	int t;
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 	for (t = 0; t < sc->udelay; t++) {
345 		noack = I2C_GETSDA(dev);
346 		if (!noack)
347 			break;
348 		DELAY(1);
349 	}
350 
351 	DELAY(sc->udelay - t);
352 	iicbb_clockout(dev);
353 
354 	I2C_DEBUG(printf("%c ", noack ? '-' : '+'));
355 	return (noack ? IIC_ENOACK : 0);
356 }
357 
358 static int
359 iicbb_sendbyte(device_t dev, uint8_t data)
360 {
361 	int err, i;
362 
363 	for (i = 7; i >= 0; i--) {
364 		err = iicbb_sendbit(dev, (data & (1 << i)) != 0);
365 		if (err != 0) {
366 			I2C_DEBUG(printf("w!"));
367 			return (err);
368 		}
369 	}
370 	I2C_DEBUG(printf("w%02x", data));
371 	return (0);
372 }
373 
374 static int
375 iicbb_readbyte(device_t dev, bool last, uint8_t *data)
376 {
377 	struct iicbb_softc *sc = device_get_softc(dev);
378 	int i, err;
379 
380 	/*
381 	 * Release SDA so that the slave can drive it.
382 	 * We do not use iicbb_clockin() here because we need to release SDA
383 	 * only once and then we just pulse the SCL.
384 	 */
385 	*data = 0;
386 	I2C_SETSDA(dev, 1);
387 	for (i = 7; i >= 0; i--) {
388 		I2C_SETSCL(dev, 1);
389 		err = iicbb_waitforscl(dev);
390 		if (err != 0) {
391 			I2C_DEBUG(printf("r! "));
392 			return (err);
393 		}
394 		DELAY((sc->udelay + 1) / 2);
395 		if (I2C_GETSDA(dev))
396 			*data |= 1 << i;
397 		DELAY((sc->udelay + 1) / 2);
398 		iicbb_clockout(dev);
399 	}
400 
401 	/*
402 	 * Send master->slave ACK (low) for more data,
403 	 * NoACK (high) otherwise.
404 	 */
405 	iicbb_sendbit(dev, last);
406 	I2C_DEBUG(printf("r%02x%c ", *data, last ? '-' : '+'));
407 	return (0);
408 }
409 
410 static int
411 iicbb_callback(device_t dev, int index, caddr_t data)
412 {
413 	return (IICBB_CALLBACK(device_get_parent(dev), index, data));
414 }
415 
416 static int
417 iicbb_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
418 {
419 	iicbb_set_speed(device_get_softc(dev), speed);
420 	return (IICBB_RESET(device_get_parent(dev), speed, addr, oldaddr));
421 }
422 
423 static int
424 iicbb_start_impl(device_t dev, u_char slave, bool repstart)
425 {
426 	struct iicbb_softc *sc = device_get_softc(dev);
427 	int error;
428 
429 	if (!repstart) {
430 		I2C_DEBUG(printf("<<"));
431 
432 		/* SCL must be high on the idle bus. */
433 		if (iicbb_waitforscl(dev) != 0) {
434 			I2C_DEBUG(printf("C!\n"));
435 			return (IIC_EBUSERR);
436 		}
437 	} else {
438 		I2C_DEBUG(printf("<"));
439 		error = iicbb_clockin(dev, 1);
440 		if (error != 0)
441 			return (error);
442 
443 		/* SDA will go low in the middle of the SCL high phase. */
444 		DELAY((sc->udelay + 1) / 2);
445 	}
446 
447 	/*
448 	 * SDA must be high after the earlier stop condition or the end
449 	 * of Ack/NoAck pulse.
450 	 */
451 	if (!I2C_GETSDA(dev)) {
452 		I2C_DEBUG(printf("D!\n"));
453 		return (IIC_EBUSERR);
454 	}
455 
456 	/* Start: SDA high->low. */
457 	I2C_SETSDA(dev, 0);
458 
459 	/* Wait the second half of the SCL high phase. */
460 	DELAY((sc->udelay + 1) / 2);
461 
462 	/* Pull SCL low to keep the bus reserved. */
463 	iicbb_clockout(dev);
464 
465 	/* send address */
466 	error = iicbb_sendbyte(dev, slave);
467 
468 	/* check for ack */
469 	if (error == 0)
470 		error = iicbb_getack(dev);
471 	if (error != 0)
472 		(void)iicbb_stop(dev);
473 	return (error);
474 }
475 
476 /* NB: the timeout is ignored. */
477 static int
478 iicbb_start(device_t dev, u_char slave, int timeout)
479 {
480 	return (iicbb_start_impl(dev, slave, false));
481 }
482 
483 /* NB: the timeout is ignored. */
484 static int
485 iicbb_repstart(device_t dev, u_char slave, int timeout)
486 {
487 	return (iicbb_start_impl(dev, slave, true));
488 }
489 
490 static int
491 iicbb_stop(device_t dev)
492 {
493 	struct iicbb_softc *sc = device_get_softc(dev);
494 	int err = 0;
495 
496 	/*
497 	 * Stop: SDA goes from low to high in the middle of the SCL high phase.
498 	 */
499 	err = iicbb_clockin(dev, 0);
500 	if (err != 0)
501 		return (err);
502 	DELAY((sc->udelay + 1) / 2);
503 	I2C_SETSDA(dev, 1);
504 	DELAY((sc->udelay + 1) / 2);
505 
506 	I2C_DEBUG(printf("%s>>", err != 0 ? "!" : ""));
507 	I2C_DEBUG(printf("\n"));
508 	return (err);
509 }
510 
511 /* NB: the timeout is ignored. */
512 static int
513 iicbb_write(device_t dev, const char *buf, int len, int *sent, int timeout)
514 {
515 	int bytes, error = 0;
516 
517 	bytes = 0;
518 	while (len > 0) {
519 		/* send byte */
520 		iicbb_sendbyte(dev, (uint8_t)*buf++);
521 
522 		/* check for ack */
523 		error = iicbb_getack(dev);
524 		if (error != 0)
525 			break;
526 		bytes++;
527 		len--;
528 	}
529 
530 	*sent = bytes;
531 	return (error);
532 }
533 
534 /* NB: whatever delay is, it's ignored. */
535 static int
536 iicbb_read(device_t dev, char *buf, int len, int *read, int last, int delay)
537 {
538 	int bytes = 0;
539 	int err = 0;
540 
541 	while (len > 0) {
542 		err = iicbb_readbyte(dev, (len == 1) ? last : 0,
543 		    (uint8_t *)buf);
544 		if (err != 0)
545 			break;
546 		buf++;
547 		bytes++;
548 		len--;
549 	}
550 
551 	*read = bytes;
552 	return (err);
553 }
554 
555 static int
556 iicbb_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
557 {
558 	int error;
559 
560 	error = IICBB_PRE_XFER(device_get_parent(dev));
561 	if (error)
562 		return (error);
563 
564 	error = iicbus_transfer_gen(dev, msgs, nmsgs);
565 
566 	IICBB_POST_XFER(device_get_parent(dev));
567 	return (error);
568 }
569 
570 static void
571 iicbb_set_speed(struct iicbb_softc *sc, u_char speed)
572 {
573 	u_int busfreq;
574 	int period;
575 
576 	/*
577 	 * udelay is half a period, the clock is held high or low for this long.
578 	 */
579 	busfreq = IICBUS_GET_FREQUENCY(sc->iicbus, speed);
580 	period = 1000000 / 2 / busfreq;	/* Hz -> uS */
581 	period -= sc->io_latency;
582 	sc->udelay = MAX(period, 1);
583 }
584 
585 DRIVER_MODULE(iicbus, iicbb, iicbus_driver, 0, 0);
586 
587 MODULE_DEPEND(iicbb, iicbus, IICBUS_MINVER, IICBUS_PREFVER, IICBUS_MAXVER);
588 MODULE_VERSION(iicbb, IICBB_MODVER);
589