1 /*-
2  * Copyright (C) 2008 MARVELL INTERNATIONAL LTD.
3  * All rights reserved.
4  *
5  * Developed by Semihalf.
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  * 3. Neither the name of MARVELL nor the names of contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
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  * Driver for the TWSI (aka I2C, aka IIC) bus controller found on Marvell
34  * and Allwinner SoCs. Supports master operation only.
35  *
36  * Calls to DELAY() are needed per Application Note AN-179 "TWSI Software
37  * Guidelines for Discovery(TM), Horizon (TM) and Feroceon(TM) Devices".
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD: stable/12/sys/dev/iicbus/twsi/twsi.c 371452 2021-12-26 10:17:16Z avg $");
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/bus.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/module.h>
50 #include <sys/resource.h>
51 #include <sys/rman.h>
52 #include <sys/sysctl.h>
53 
54 #include <machine/_inttypes.h>
55 #include <machine/bus.h>
56 #include <machine/resource.h>
57 
58 #include <dev/iicbus/iiconf.h>
59 #include <dev/iicbus/iicbus.h>
60 
61 #include <dev/iicbus/twsi/twsi.h>
62 
63 #include "iicbus_if.h"
64 
65 #define	TWSI_CONTROL_ACK	(1 << 2)
66 #define	TWSI_CONTROL_IFLG	(1 << 3)
67 #define	TWSI_CONTROL_STOP	(1 << 4)
68 #define	TWSI_CONTROL_START	(1 << 5)
69 #define	TWSI_CONTROL_TWSIEN	(1 << 6)
70 #define	TWSI_CONTROL_INTEN	(1 << 7)
71 
72 #define	TWSI_STATUS_BUS_ERROR		0x00
73 #define	TWSI_STATUS_START		0x08
74 #define	TWSI_STATUS_RPTD_START		0x10
75 #define	TWSI_STATUS_ADDR_W_ACK		0x18
76 #define	TWSI_STATUS_ADDR_W_NACK		0x20
77 #define	TWSI_STATUS_DATA_WR_ACK		0x28
78 #define	TWSI_STATUS_DATA_WR_NACK	0x30
79 #define	TWSI_STATUS_ARBITRATION_LOST	0x38
80 #define	TWSI_STATUS_ADDR_R_ACK		0x40
81 #define	TWSI_STATUS_ADDR_R_NACK		0x48
82 #define	TWSI_STATUS_DATA_RD_ACK		0x50
83 #define	TWSI_STATUS_DATA_RD_NOACK	0x58
84 #define	TWSI_STATUS_IDLE		0xf8
85 
86 #define	TWSI_DEBUG
87 #undef TWSI_DEBUG
88 
89 #define	debugf(sc, fmt, args...)	if ((sc)->debug)	\
90     device_printf((sc)->dev, "%s: " fmt, __func__, ##args)
91 
92 static struct resource_spec res_spec[] = {
93 	{ SYS_RES_MEMORY, 0, RF_ACTIVE },
94 	{ SYS_RES_IRQ, 0, RF_ACTIVE | RF_SHAREABLE},
95 	{ -1, 0 }
96 };
97 
98 static __inline uint32_t
TWSI_READ(struct twsi_softc * sc,bus_size_t off)99 TWSI_READ(struct twsi_softc *sc, bus_size_t off)
100 {
101 	uint32_t val;
102 
103 	val = bus_read_4(sc->res[0], off);
104 	if (sc->debug > 1)
105 		debugf(sc, "read %x from %lx\n", val, off);
106 	return (val);
107 }
108 
109 static __inline void
TWSI_WRITE(struct twsi_softc * sc,bus_size_t off,uint32_t val)110 TWSI_WRITE(struct twsi_softc *sc, bus_size_t off, uint32_t val)
111 {
112 
113 	if (sc->debug > 1)
114 		debugf(sc, "Writing %x to %lx\n", val, off);
115 	bus_write_4(sc->res[0], off, val);
116 }
117 
118 static __inline void
twsi_control_clear(struct twsi_softc * sc,uint32_t mask)119 twsi_control_clear(struct twsi_softc *sc, uint32_t mask)
120 {
121 	uint32_t val;
122 
123 	val = TWSI_READ(sc, sc->reg_control);
124 	debugf(sc, "read val=%x\n", val);
125 	val &= ~(TWSI_CONTROL_STOP | TWSI_CONTROL_START);
126 	val &= ~mask;
127 	debugf(sc, "write val=%x\n", val);
128 	TWSI_WRITE(sc, sc->reg_control, val);
129 }
130 
131 static __inline void
twsi_control_set(struct twsi_softc * sc,uint32_t mask)132 twsi_control_set(struct twsi_softc *sc, uint32_t mask)
133 {
134 	uint32_t val;
135 
136 	val = TWSI_READ(sc, sc->reg_control);
137 	debugf(sc, "read val=%x\n", val);
138 	val &= ~(TWSI_CONTROL_STOP | TWSI_CONTROL_START);
139 	val |= mask;
140 	debugf(sc, "write val=%x\n", val);
141 	TWSI_WRITE(sc, sc->reg_control, val);
142 }
143 
144 static __inline void
twsi_clear_iflg(struct twsi_softc * sc)145 twsi_clear_iflg(struct twsi_softc *sc)
146 {
147 
148 	DELAY(1000);
149 	/* There are two ways of clearing IFLAG. */
150 	if (sc->iflag_w1c)
151 		twsi_control_set(sc, TWSI_CONTROL_IFLG);
152 	else
153 		twsi_control_clear(sc, TWSI_CONTROL_IFLG);
154 	DELAY(1000);
155 }
156 
157 
158 /*
159  * timeout given in us
160  * returns
161  *   0 on successful mask change
162  *   non-zero on timeout
163  */
164 static int
twsi_poll_ctrl(struct twsi_softc * sc,int timeout,uint32_t mask)165 twsi_poll_ctrl(struct twsi_softc *sc, int timeout, uint32_t mask)
166 {
167 
168 	timeout /= 10;
169 	debugf(sc, "Waiting for ctrl reg to match mask %x\n", mask);
170 	while (!(TWSI_READ(sc, sc->reg_control) & mask)) {
171 		DELAY(10);
172 		if (--timeout < 0)
173 			return (timeout);
174 	}
175 	debugf(sc, "done\n");
176 	return (0);
177 }
178 
179 
180 /*
181  * 'timeout' is given in us. Note also that timeout handling is not exact --
182  * twsi_locked_start() total wait can be more than 2 x timeout
183  * (twsi_poll_ctrl() is called twice). 'mask' can be either TWSI_STATUS_START
184  * or TWSI_STATUS_RPTD_START
185  */
186 static int
twsi_locked_start(device_t dev,struct twsi_softc * sc,int32_t mask,u_char slave,int timeout)187 twsi_locked_start(device_t dev, struct twsi_softc *sc, int32_t mask,
188     u_char slave, int timeout)
189 {
190 	int read_access, iflg_set = 0;
191 	uint32_t status;
192 
193 	mtx_assert(&sc->mutex, MA_OWNED);
194 
195 	if (mask == TWSI_STATUS_RPTD_START)
196 		/* read IFLG to know if it should be cleared later; from NBSD */
197 		iflg_set = TWSI_READ(sc, sc->reg_control) & TWSI_CONTROL_IFLG;
198 
199 	debugf(sc, "send start\n");
200 	twsi_control_set(sc, TWSI_CONTROL_START);
201 
202 	if (mask == TWSI_STATUS_RPTD_START && iflg_set) {
203 		debugf(sc, "IFLG set, clearing (mask=%x)\n", mask);
204 		twsi_clear_iflg(sc);
205 	}
206 
207 	/*
208 	 * Without this delay we timeout checking IFLG if the timeout is 0.
209 	 * NBSD driver always waits here too.
210 	 */
211 	DELAY(1000);
212 
213 	if (twsi_poll_ctrl(sc, timeout, TWSI_CONTROL_IFLG)) {
214 		debugf(sc, "timeout sending %sSTART condition\n",
215 		    mask == TWSI_STATUS_START ? "" : "repeated ");
216 		return (IIC_ETIMEOUT);
217 	}
218 
219 	status = TWSI_READ(sc, sc->reg_status);
220 	debugf(sc, "status=%x\n", status);
221 
222 	if (status != mask) {
223 		debugf(sc, "wrong status (%02x) after sending %sSTART condition\n",
224 		    status, mask == TWSI_STATUS_START ? "" : "repeated ");
225 		return (IIC_ESTATUS);
226 	}
227 
228 	TWSI_WRITE(sc, sc->reg_data, slave);
229 	twsi_clear_iflg(sc);
230 	DELAY(1000);
231 
232 	if (twsi_poll_ctrl(sc, timeout, TWSI_CONTROL_IFLG)) {
233 		debugf(sc, "timeout sending slave address (timeout=%d)\n", timeout);
234 		return (IIC_ETIMEOUT);
235 	}
236 
237 	read_access = (slave & 0x1) ? 1 : 0;
238 	status = TWSI_READ(sc, sc->reg_status);
239 	if (status != (read_access ?
240 	    TWSI_STATUS_ADDR_R_ACK : TWSI_STATUS_ADDR_W_ACK)) {
241 		debugf(sc, "no ACK (status: %02x) after sending slave address\n",
242 		    status);
243 		return (IIC_ENOACK);
244 	}
245 
246 	return (IIC_NOERR);
247 }
248 
249 #ifdef EXT_RESOURCES
250 #define	TWSI_BAUD_RATE_RAW(C,M,N)	((C)/((10*(M+1))<<(N)))
251 #define	ABSSUB(a,b)	(((a) > (b)) ? (a) - (b) : (b) - (a))
252 
253 static int
twsi_calc_baud_rate(struct twsi_softc * sc,const u_int target,int * param)254 twsi_calc_baud_rate(struct twsi_softc *sc, const u_int target,
255   int *param)
256 {
257 	uint64_t clk;
258 	uint32_t cur, diff, diff0;
259 	int m, n, m0, n0;
260 
261 	/* Calculate baud rate. */
262 	diff0 = 0xffffffff;
263 
264 	if (clk_get_freq(sc->clk_core, &clk) < 0)
265 		return (-1);
266 
267 	debugf(sc, "Bus clock is at %ju\n", clk);
268 
269 	for (n = 0; n < 8; n++) {
270 		for (m = 0; m < 16; m++) {
271 			cur = TWSI_BAUD_RATE_RAW(clk,m,n);
272 			diff = ABSSUB(target, cur);
273 			if (diff < diff0) {
274 				m0 = m;
275 				n0 = n;
276 				diff0 = diff;
277 			}
278 		}
279 	}
280 	*param = TWSI_BAUD_RATE_PARAM(m0, n0);
281 
282 	return (0);
283 }
284 #endif /* EXT_RESOURCES */
285 
286 /*
287  * Only slave mode supported, disregard [old]addr
288  */
289 static int
twsi_reset(device_t dev,u_char speed,u_char addr,u_char * oldaddr)290 twsi_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
291 {
292 	struct twsi_softc *sc;
293 	uint32_t param;
294 #ifdef EXT_RESOURCES
295 	u_int busfreq;
296 #endif
297 
298 	sc = device_get_softc(dev);
299 
300 #ifdef EXT_RESOURCES
301 	busfreq = IICBUS_GET_FREQUENCY(sc->iicbus, speed);
302 
303 	if (twsi_calc_baud_rate(sc, busfreq, &param) == -1) {
304 #endif
305 		switch (speed) {
306 		case IIC_SLOW:
307 		case IIC_FAST:
308 			param = sc->baud_rate[speed].param;
309 			debugf(sc, "Using IIC_FAST mode with speed param=%x\n", param);
310 			break;
311 		case IIC_FASTEST:
312 		case IIC_UNKNOWN:
313 		default:
314 			param = sc->baud_rate[IIC_FAST].param;
315 			debugf(sc, "Using IIC_FASTEST/UNKNOWN mode with speed param=%x\n", param);
316 			break;
317 		}
318 #ifdef EXT_RESOURCES
319 	}
320 #endif
321 
322 	debugf(sc, "Using clock param=%x\n", param);
323 
324 	mtx_lock(&sc->mutex);
325 	TWSI_WRITE(sc, sc->reg_soft_reset, 0x1);
326 	TWSI_WRITE(sc, sc->reg_baud_rate, param);
327 	TWSI_WRITE(sc, sc->reg_control, TWSI_CONTROL_TWSIEN);
328 	DELAY(1000);
329 	mtx_unlock(&sc->mutex);
330 
331 	return (0);
332 }
333 
334 static int
twsi_stop(device_t dev)335 twsi_stop(device_t dev)
336 {
337 	struct twsi_softc *sc;
338 
339 	sc = device_get_softc(dev);
340 
341 	debugf(sc, "%s\n", __func__);
342 	mtx_lock(&sc->mutex);
343 	twsi_control_clear(sc, TWSI_CONTROL_ACK);
344 	twsi_control_set(sc, TWSI_CONTROL_STOP);
345 	twsi_clear_iflg(sc);
346 	DELAY(1000);
347 	mtx_unlock(&sc->mutex);
348 
349 	return (IIC_NOERR);
350 }
351 
352 /*
353  * timeout is given in us
354  */
355 static int
twsi_repeated_start(device_t dev,u_char slave,int timeout)356 twsi_repeated_start(device_t dev, u_char slave, int timeout)
357 {
358 	struct twsi_softc *sc;
359 	int rv;
360 
361 	sc = device_get_softc(dev);
362 
363 	debugf(sc, "%s: slave=%x\n", __func__, slave);
364 	mtx_lock(&sc->mutex);
365 	rv = twsi_locked_start(dev, sc, TWSI_STATUS_RPTD_START, slave,
366 	    timeout);
367 	mtx_unlock(&sc->mutex);
368 
369 	if (rv) {
370 		twsi_stop(dev);
371 		return (rv);
372 	} else
373 		return (IIC_NOERR);
374 }
375 
376 /*
377  * timeout is given in us
378  */
379 static int
twsi_start(device_t dev,u_char slave,int timeout)380 twsi_start(device_t dev, u_char slave, int timeout)
381 {
382 	struct twsi_softc *sc;
383 	int rv;
384 
385 	sc = device_get_softc(dev);
386 
387 	debugf(sc, "%s: slave=%x\n", __func__, slave);
388 	mtx_lock(&sc->mutex);
389 	rv = twsi_locked_start(dev, sc, TWSI_STATUS_START, slave, timeout);
390 	mtx_unlock(&sc->mutex);
391 
392 	if (rv) {
393 		twsi_stop(dev);
394 		return (rv);
395 	} else
396 		return (IIC_NOERR);
397 }
398 
399 static int
twsi_read(device_t dev,char * buf,int len,int * read,int last,int delay)400 twsi_read(device_t dev, char *buf, int len, int *read, int last, int delay)
401 {
402 	struct twsi_softc *sc;
403 	uint32_t status;
404 	int last_byte, rv;
405 
406 	sc = device_get_softc(dev);
407 
408 	mtx_lock(&sc->mutex);
409 	*read = 0;
410 	while (*read < len) {
411 		/*
412 		 * Check if we are reading last byte of the last buffer,
413 		 * do not send ACK then, per I2C specs
414 		 */
415 		last_byte = ((*read == len - 1) && last) ? 1 : 0;
416 		if (last_byte)
417 			twsi_control_clear(sc, TWSI_CONTROL_ACK);
418 		else
419 			twsi_control_set(sc, TWSI_CONTROL_ACK);
420 
421 		twsi_clear_iflg(sc);
422 		DELAY(1000);
423 
424 		if (twsi_poll_ctrl(sc, delay, TWSI_CONTROL_IFLG)) {
425 			debugf(sc, "timeout reading data (delay=%d)\n", delay);
426 			rv = IIC_ETIMEOUT;
427 			goto out;
428 		}
429 
430 		status = TWSI_READ(sc, sc->reg_status);
431 		if (status != (last_byte ?
432 		    TWSI_STATUS_DATA_RD_NOACK : TWSI_STATUS_DATA_RD_ACK)) {
433 			debugf(sc, "wrong status (%02x) while reading\n", status);
434 			rv = IIC_ESTATUS;
435 			goto out;
436 		}
437 
438 		*buf++ = TWSI_READ(sc, sc->reg_data);
439 		(*read)++;
440 	}
441 	rv = IIC_NOERR;
442 out:
443 	mtx_unlock(&sc->mutex);
444 	return (rv);
445 }
446 
447 static int
twsi_write(device_t dev,const char * buf,int len,int * sent,int timeout)448 twsi_write(device_t dev, const char *buf, int len, int *sent, int timeout)
449 {
450 	struct twsi_softc *sc;
451 	uint32_t status;
452 	int rv;
453 
454 	sc = device_get_softc(dev);
455 
456 	mtx_lock(&sc->mutex);
457 	*sent = 0;
458 	while (*sent < len) {
459 		TWSI_WRITE(sc, sc->reg_data, *buf++);
460 
461 		twsi_clear_iflg(sc);
462 		DELAY(1000);
463 		if (twsi_poll_ctrl(sc, timeout, TWSI_CONTROL_IFLG)) {
464 			debugf(sc, "timeout writing data (timeout=%d)\n", timeout);
465 			rv = IIC_ETIMEOUT;
466 			goto out;
467 		}
468 
469 		status = TWSI_READ(sc, sc->reg_status);
470 		if (status != TWSI_STATUS_DATA_WR_ACK) {
471 			debugf(sc, "wrong status (%02x) while writing\n", status);
472 			rv = IIC_ESTATUS;
473 			goto out;
474 		}
475 		(*sent)++;
476 	}
477 	rv = IIC_NOERR;
478 out:
479 	mtx_unlock(&sc->mutex);
480 	return (rv);
481 }
482 
483 static void
twsi_error(struct twsi_softc * sc,int err)484 twsi_error(struct twsi_softc *sc, int err)
485 {
486 	/*
487 	 * Must send stop condition to abort the current transfer.
488 	 */
489 	debugf(sc, "Sending STOP condition for error %d\n", err);
490 	sc->transfer = 0;
491 	sc->error = err;
492 	sc->control_val = 0;
493 	TWSI_WRITE(sc, sc->reg_control, sc->control_val | TWSI_CONTROL_STOP);
494 }
495 
496 static int
twsi_transfer(device_t dev,struct iic_msg * msgs,uint32_t nmsgs)497 twsi_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
498 {
499 	struct twsi_softc *sc;
500 	uint32_t status;
501 	int error;
502 
503 	sc = device_get_softc(dev);
504 
505 	if (!sc->have_intr)
506 		return (iicbus_transfer_gen(dev, msgs, nmsgs));
507 
508 	mtx_lock(&sc->mutex);
509 	KASSERT(sc->transfer == 0,
510 	    ("starting a transfer while another is active"));
511 
512 	debugf(sc, "transmitting %d messages\n", nmsgs);
513 	status = TWSI_READ(sc, sc->reg_status);
514 	debugf(sc, "status=0x%x\n", status);
515 	if (status != TWSI_STATUS_IDLE) {
516 		debugf(sc, "Bad status at start of transfer\n");
517 		twsi_error(sc, IIC_ESTATUS);
518 		goto end;
519 	}
520 
521 	sc->nmsgs = nmsgs;
522 	sc->msgs = msgs;
523 	sc->msg_idx = 0;
524 	sc->transfer = 1;
525 	sc->error = 0;
526 
527 #ifdef TWSI_DEBUG
528 	for (int i = 0; i < nmsgs; i++)
529 		debugf(sc, "msg %d is %d bytes long\n", i, msgs[i].len);
530 #endif
531 
532 	/* Send start and re-enable interrupts */
533 	sc->control_val = TWSI_CONTROL_TWSIEN | TWSI_CONTROL_INTEN;
534 	TWSI_WRITE(sc, sc->reg_control, sc->control_val | TWSI_CONTROL_START);
535 	msleep_sbt(sc, &sc->mutex, 0, "twsi", 3000 * SBT_1MS, SBT_1MS, 0);
536 	debugf(sc, "pause finish\n");
537 	if (sc->error == 0 && sc->transfer != 0) {
538 		device_printf(sc->dev, "transfer timeout\n");
539 		sc->error = IIC_ETIMEOUT;
540 		sc->transfer = 0;
541 	}
542 
543 	if (sc->error != 0)
544 		debugf(sc, "Error: %d\n", sc->error);
545 
546 end:
547 	/* Disable module and interrupts */
548 	debugf(sc, "status=0x%x\n", TWSI_READ(sc, sc->reg_status));
549 	TWSI_WRITE(sc, sc->reg_control, 0);
550 	debugf(sc, "status=0x%x\n", TWSI_READ(sc, sc->reg_status));
551 	error = sc->error;
552 	mtx_unlock(&sc->mutex);
553 
554 	return (error);
555 }
556 
557 static void
twsi_intr(void * arg)558 twsi_intr(void *arg)
559 {
560 	struct twsi_softc *sc;
561 	uint32_t status;
562 	bool message_done;
563 	bool send_start;
564 
565 	sc = arg;
566 	send_start = false;
567 
568 	mtx_lock(&sc->mutex);
569 	debugf(sc, "Got interrupt, current msg=%u\n", sc->msg_idx);
570 
571 	status = TWSI_READ(sc, sc->reg_status);
572 	debugf(sc, "reg control = 0x%x, status = 0x%x\n",
573 	    TWSI_READ(sc, sc->reg_control), status);
574 
575 	if (sc->transfer == 0) {
576 		device_printf(sc->dev, "interrupt without active transfer, "
577 		    "status = 0x%x\n", status);
578 		TWSI_WRITE(sc, sc->reg_control, sc->control_val |
579 		    TWSI_CONTROL_STOP);
580 		goto end;
581 	}
582 
583 restart:
584 	message_done = false;
585 
586 	switch (status) {
587 	case TWSI_STATUS_START:
588 	case TWSI_STATUS_RPTD_START:
589 		/* Transmit the address */
590 		debugf(sc, "Send address 0x%x\n",
591 		    sc->msgs[sc->msg_idx].slave);
592 
593 		if (sc->msgs[sc->msg_idx].flags & IIC_M_RD)
594 			TWSI_WRITE(sc, sc->reg_data,
595 			    sc->msgs[sc->msg_idx].slave | LSB);
596 		else
597 			TWSI_WRITE(sc, sc->reg_data,
598 			    sc->msgs[sc->msg_idx].slave & ~LSB);
599 		break;
600 
601 	case TWSI_STATUS_ADDR_W_ACK:
602 		debugf(sc, "Address ACK-ed (write)\n");
603 
604 		if (sc->msgs[sc->msg_idx].len > 0) {
605 			/* Directly send the first byte */
606 			sc->sent_bytes = 1;
607 			debugf(sc, "Sending byte 0 (of %d) = %x\n",
608 			    sc->msgs[sc->msg_idx].len,
609 			    sc->msgs[sc->msg_idx].buf[0]);
610 			TWSI_WRITE(sc, sc->reg_data,
611 			    sc->msgs[sc->msg_idx].buf[0]);
612 		} else {
613 			debugf(sc, "Zero-length write, sending STOP\n");
614 			TWSI_WRITE(sc, sc->reg_control,
615 			    sc->control_val | TWSI_CONTROL_STOP);
616 		}
617 		break;
618 
619 	case TWSI_STATUS_ADDR_R_ACK:
620 		debugf(sc, "Address ACK-ed (read)\n");
621 		sc->recv_bytes = 0;
622 
623 		if (sc->msgs[sc->msg_idx].len == 0) {
624 			debugf(sc, "Zero-length read, sending STOP\n");
625 			TWSI_WRITE(sc, sc->reg_control,
626 			    sc->control_val | TWSI_CONTROL_STOP);
627 		} else if (sc->msgs[sc->msg_idx].len == 1) {
628 			sc->control_val &= ~TWSI_CONTROL_ACK;
629 		} else {
630 			sc->control_val |= TWSI_CONTROL_ACK;
631 		}
632 		break;
633 
634 	case TWSI_STATUS_ADDR_W_NACK:
635 	case TWSI_STATUS_ADDR_R_NACK:
636 		debugf(sc, "Address NACK-ed\n");
637 		twsi_error(sc, IIC_ENOACK);
638 		break;
639 	case TWSI_STATUS_DATA_WR_NACK:
640 		debugf(sc, "Data byte NACK-ed\n");
641 		twsi_error(sc, IIC_ENOACK);
642 		break;
643 	case TWSI_STATUS_DATA_WR_ACK:
644 		KASSERT(sc->sent_bytes <= sc->msgs[sc->msg_idx].len,
645 		    ("sent_bytes beyond message length"));
646 		debugf(sc, "ACK received after transmitting data\n");
647 		if (sc->sent_bytes == sc->msgs[sc->msg_idx].len) {
648 			debugf(sc, "Done TX data\n");
649 
650 			/* Send stop, no interrupts on stop */
651 			if (!(sc->msgs[sc->msg_idx].flags & IIC_M_NOSTOP)) {
652 				TWSI_WRITE(sc, sc->reg_control,
653 				    sc->control_val | TWSI_CONTROL_STOP);
654 			} else {
655 				debugf(sc, "NOSTOP flag\n");
656 			}
657 			message_done = true;
658 			break;
659 		}
660 
661 		debugf(sc, "Sending byte %d (of %d) = 0x%x\n",
662 		    sc->sent_bytes,
663 		    sc->msgs[sc->msg_idx].len,
664 		    sc->msgs[sc->msg_idx].buf[sc->sent_bytes]);
665 		TWSI_WRITE(sc, sc->reg_data,
666 		    sc->msgs[sc->msg_idx].buf[sc->sent_bytes]);
667 		sc->sent_bytes++;
668 		break;
669 
670 	case TWSI_STATUS_DATA_RD_ACK:
671 		debugf(sc, "Received and ACK-ed data\n");
672 		KASSERT(sc->recv_bytes < sc->msgs[sc->msg_idx].len,
673 		    ("receiving beyond the end of buffer"));
674 
675 		sc->msgs[sc->msg_idx].buf[sc->recv_bytes] =
676 		    TWSI_READ(sc, sc->reg_data);
677 		debugf(sc, "Received byte %d (of %d) = 0x%x\n",
678 		    sc->recv_bytes,
679 		    sc->msgs[sc->msg_idx].len,
680 		    sc->msgs[sc->msg_idx].buf[sc->recv_bytes]);
681 		sc->recv_bytes++;
682 
683 		/* If we only have one byte left, disable ACK */
684 		if (sc->msgs[sc->msg_idx].len - sc->recv_bytes == 1) {
685 			sc->control_val &= ~TWSI_CONTROL_ACK;
686 		} else if (sc->msgs[sc->msg_idx].len == sc->recv_bytes) {
687 			/*
688 			 * We should not have ACK-ed the last byte.
689 			 * The protocol state machine is in invalid state.
690 			 */
691 			debugf(sc, "RX all but asked for more?\n");
692 			twsi_error(sc, IIC_ESTATUS);
693 		}
694 		break;
695 
696 	case TWSI_STATUS_DATA_RD_NOACK:
697 		debugf(sc, "Received and NACK-ed data\n");
698 		KASSERT(sc->recv_bytes == sc->msgs[sc->msg_idx].len - 1,
699 		    ("sent NACK before receiving all requested data"));
700 		sc->msgs[sc->msg_idx].buf[sc->recv_bytes] =
701 		    TWSI_READ(sc, sc->reg_data);
702 		debugf(sc, "Received byte %d (of %d) = 0x%x\n",
703 		    sc->recv_bytes,
704 		    sc->msgs[sc->msg_idx].len,
705 		    sc->msgs[sc->msg_idx].buf[sc->recv_bytes]);
706 		sc->recv_bytes++;
707 
708 		if (sc->msgs[sc->msg_idx].len == sc->recv_bytes) {
709 			debugf(sc, "Done RX data\n");
710 			if (!(sc->msgs[sc->msg_idx].flags & IIC_M_NOSTOP)) {
711 				debugf(sc, "Send STOP\n");
712 				TWSI_WRITE(sc, sc->reg_control,
713 				    sc->control_val | TWSI_CONTROL_STOP);
714 			}
715 			message_done = true;
716 		} else {
717 			/*
718 			 * We should not have NACK-ed yet.
719 			 * The protocol state machine is in invalid state.
720 			 */
721 			debugf(sc, "NACK-ed before receving all bytes?\n");
722 			twsi_error(sc, IIC_ESTATUS);
723 		}
724 		break;
725 
726 	case TWSI_STATUS_BUS_ERROR:
727 		debugf(sc, "Bus error\n");
728 		twsi_error(sc, IIC_EBUSERR);
729 		break;
730 	case TWSI_STATUS_ARBITRATION_LOST:
731 		debugf(sc, "Arbitration lost\n");
732 		twsi_error(sc, IIC_EBUSBSY);
733 		break;
734 	default:
735 		debugf(sc, "unexpected status 0x%x\n", status);
736 		twsi_error(sc, IIC_ESTATUS);
737 		break;
738 	}
739 
740 	if (message_done) {
741 		sc->msg_idx++;
742 		if (sc->msg_idx == sc->nmsgs) {
743 			debugf(sc, "All messages transmitted\n");
744 			sc->transfer = 0;
745 			sc->error = 0;
746 		} else if ((sc->msgs[sc->msg_idx].flags & IIC_M_NOSTART) == 0) {
747 			debugf(sc, "Send (repeated) start\n");
748 			send_start = true;
749 		} else {
750 			/* Just keep transmitting data. */
751 			KASSERT((sc->msgs[sc->msg_idx - 1].flags & IIC_M_NOSTOP) != 0,
752 			    ("NOSTART message after STOP"));
753 			KASSERT((sc->msgs[sc->msg_idx].flags & IIC_M_RD) ==
754 			    (sc->msgs[sc->msg_idx - 1].flags & IIC_M_RD),
755 			    ("change of transfer direction without a START"));
756 			debugf(sc, "NOSTART message after NOSTOP\n");
757 			sc->sent_bytes = 0;
758 			sc->recv_bytes = 0;
759 			if ((sc->msgs[sc->msg_idx].flags & IIC_M_RD) == 0) {
760 				status = TWSI_STATUS_ADDR_W_ACK;
761 				goto restart;
762 			} else {
763 				debugf(sc, "Read+NOSTART unsupported\n");
764 				twsi_error(sc, IIC_ESTATUS);
765 			}
766 		}
767 	}
768 end:
769 	/*
770 	 * Newer Allwinner chips clear IFLG after writing 1 to it.
771 	 */
772 	debugf(sc, "Refresh reg_control\n");
773 	TWSI_WRITE(sc, sc->reg_control, sc->control_val |
774 	    (sc->iflag_w1c ? TWSI_CONTROL_IFLG : 0) |
775 	    (send_start ? TWSI_CONTROL_START : 0));
776 
777 	debugf(sc, "Done with interrupt, transfer = %d\n", sc->transfer);
778 	if (sc->transfer == 0)
779 		wakeup(sc);
780 	mtx_unlock(&sc->mutex);
781 }
782 
783 static void
twsi_intr_start(void * pdev)784 twsi_intr_start(void *pdev)
785 {
786 	struct twsi_softc *sc;
787 
788 	sc = device_get_softc(pdev);
789 
790 	if ((bus_setup_intr(pdev, sc->res[1], INTR_TYPE_MISC | INTR_MPSAFE,
791 	      NULL, twsi_intr, sc, &sc->intrhand)))
792 		device_printf(pdev, "unable to register interrupt handler\n");
793 
794 	sc->have_intr = true;
795 }
796 
797 int
twsi_attach(device_t dev)798 twsi_attach(device_t dev)
799 {
800 	struct twsi_softc *sc;
801 	struct sysctl_ctx_list *ctx;
802 	struct sysctl_oid *tree_node;
803 	struct sysctl_oid_list *tree;
804 
805 	sc = device_get_softc(dev);
806 	sc->dev = dev;
807 
808 	mtx_init(&sc->mutex, device_get_nameunit(dev), "twsi", MTX_DEF);
809 
810 	if (bus_alloc_resources(dev, res_spec, sc->res)) {
811 		device_printf(dev, "could not allocate resources\n");
812 		twsi_detach(dev);
813 		return (ENXIO);
814 	}
815 
816 #ifdef TWSI_DEBUG
817 	sc->debug = 1;
818 #endif
819 	ctx = device_get_sysctl_ctx(dev);
820 	tree_node = device_get_sysctl_tree(dev);
821 	tree = SYSCTL_CHILDREN(tree_node);
822 	SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "debug", CTLFLAG_RWTUN,
823 	    &sc->debug, 0, "Set debug level (zero to disable)");
824 
825 	/* Attach the iicbus. */
826 	if ((sc->iicbus = device_add_child(dev, "iicbus", -1)) == NULL) {
827 		device_printf(dev, "could not allocate iicbus instance\n");
828 		twsi_detach(dev);
829 		return (ENXIO);
830 	}
831 	bus_generic_attach(dev);
832 
833 	config_intrhook_oneshot(twsi_intr_start, dev);
834 
835 	return (0);
836 }
837 
838 int
twsi_detach(device_t dev)839 twsi_detach(device_t dev)
840 {
841 	struct twsi_softc *sc;
842 	int rv;
843 
844 	sc = device_get_softc(dev);
845 
846 	if ((rv = bus_generic_detach(dev)) != 0)
847 		return (rv);
848 
849 	if (sc->iicbus != NULL)
850 		if ((rv = device_delete_child(dev, sc->iicbus)) != 0)
851 			return (rv);
852 
853 	if (sc->intrhand != NULL)
854 		bus_teardown_intr(sc->dev, sc->res[1], sc->intrhand);
855 
856 	bus_release_resources(dev, res_spec, sc->res);
857 
858 	mtx_destroy(&sc->mutex);
859 	return (0);
860 }
861 
862 static device_method_t twsi_methods[] = {
863 	/* device interface */
864 	DEVMETHOD(device_detach,	twsi_detach),
865 
866 	/* Bus interface */
867 	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
868 	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
869 	DEVMETHOD(bus_alloc_resource,	bus_generic_alloc_resource),
870 	DEVMETHOD(bus_release_resource,	bus_generic_release_resource),
871 	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
872 	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
873 	DEVMETHOD(bus_adjust_resource,	bus_generic_adjust_resource),
874 	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
875 	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
876 
877 	/* iicbus interface */
878 	DEVMETHOD(iicbus_callback, iicbus_null_callback),
879 	DEVMETHOD(iicbus_repeated_start, twsi_repeated_start),
880 	DEVMETHOD(iicbus_start,		twsi_start),
881 	DEVMETHOD(iicbus_stop,		twsi_stop),
882 	DEVMETHOD(iicbus_write,		twsi_write),
883 	DEVMETHOD(iicbus_read,		twsi_read),
884 	DEVMETHOD(iicbus_reset,		twsi_reset),
885 	DEVMETHOD(iicbus_transfer,	twsi_transfer),
886 	{ 0, 0 }
887 };
888 
889 DEFINE_CLASS_0(twsi, twsi_driver, twsi_methods,
890     sizeof(struct twsi_softc));
891