xref: /freebsd/sys/arm/broadcom/bcm2835/bcm2835_bsc.c (revision dd21556857e8d40f66bf5ad54754d9d52669ebf7)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Tsubai Masanari.
5  * Copyright (c) 2012 Oleksandr Tymoshenko <gonzo@freebsd.org>
6  * Copyright (c) 2013 Luiz Otavio O Souza <loos@freebsd.org>
7  * Copyright (c) 2017 Ian Lepore <ian@freebsd.org>
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE 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 THE 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 #include <sys/cdefs.h>
33 /*
34  * Driver for bcm2835 i2c-compatible two-wire bus, named 'BSC' on this SoC.
35  *
36  * This controller can only perform complete transfers, it does not provide
37  * low-level control over sending start/repeat-start/stop sequences on the bus.
38  * In addition, bugs in the silicon make it somewhat difficult to perform a
39  * repeat-start, and limit the repeat-start to a read following a write on
40  * the same slave device.  (The i2c protocol allows a repeat start to change
41  * direction or not, and change slave address or not at any time.)
42  *
43  * The repeat-start bug and workaround are described in a problem report at
44  * https://github.com/raspberrypi/linux/issues/254 with the crucial part being
45  * in a comment block from a fragment of a GPU i2c driver, containing this:
46  *
47  * -----------------------------------------------------------------------------
48  * - See i2c.v: The I2C peripheral samples the values for rw_bit and xfer_count
49  * - in the IDLE state if start is set.
50  * -
51  * - We want to generate a ReSTART not a STOP at the end of the TX phase. In
52  * - order to do that we must ensure the state machine goes RACK1 -> RACK2 ->
53  * - SRSTRT1 (not RACK1 -> RACK2 -> SSTOP1).
54  * -
55  * - So, in the RACK2 state when (TX) xfer_count==0 we must therefore have
56  * - already set, ready to be sampled:
57  * -  READ ; rw_bit     <= I2CC bit 0 -- must be "read"
58  * -  ST;    start      <= I2CC bit 7 -- must be "Go" in order to not issue STOP
59  * -  DLEN;  xfer_count <= I2CDLEN    -- must be equal to our read amount
60  * -
61  * - The plan to do this is:
62  * -  1. Start the sub-address write, but don't let it finish
63  * -     (keep xfer_count > 0)
64  * -  2. Populate READ, DLEN and ST in preparation for ReSTART read sequence
65  * -  3. Let TX finish (write the rest of the data)
66  * -  4. Read back data as it arrives
67  * -----------------------------------------------------------------------------
68  *
69  * The transfer function below scans the list of messages passed to it, looking
70  * for a read following a write to the same slave.  When it finds that, it
71  * starts the write without prefilling the tx fifo, which holds xfer_count>0,
72  * then presets the direction, length, and start command for the following read,
73  * as described above.  Then the tx fifo is filled and the rest of the transfer
74  * proceeds as normal, with the controller automatically supplying a
75  * repeat-start on the bus when the write operation finishes.
76  *
77  * XXX I suspect the controller may be able to do a repeat-start on any
78  * write->read or write->write transition, even when the slave addresses differ.
79  * It's unclear whether the slave address can be prestaged along with the
80  * direction and length while the write xfer_count is being held at zero.  In
81  * fact, if it can't do this, then it couldn't be used to read EDID data.
82  */
83 
84 #include <sys/param.h>
85 #include <sys/systm.h>
86 #include <sys/kernel.h>
87 #include <sys/lock.h>
88 #include <sys/module.h>
89 #include <sys/mutex.h>
90 #include <sys/bus.h>
91 #include <machine/resource.h>
92 #include <machine/bus.h>
93 #include <sys/rman.h>
94 #include <sys/sysctl.h>
95 
96 #include <dev/iicbus/iicbus.h>
97 #include <dev/iicbus/iiconf.h>
98 #include <dev/ofw/ofw_bus.h>
99 #include <dev/ofw/ofw_bus_subr.h>
100 
101 #include <arm/broadcom/bcm2835/bcm2835_bscreg.h>
102 #include <arm/broadcom/bcm2835/bcm2835_bscvar.h>
103 
104 #include "iicbus_if.h"
105 
106 static struct ofw_compat_data compat_data[] = {
107 	{"broadcom,bcm2835-bsc",	1},
108 	{"brcm,bcm2708-i2c",		1},
109 	{"brcm,bcm2835-i2c",		1},
110 	{NULL,				0}
111 };
112 
113 #define DEVICE_DEBUGF(sc, lvl, fmt, args...) \
114     if ((lvl) <= (sc)->sc_debug) \
115         device_printf((sc)->sc_dev, fmt, ##args)
116 
117 #define DEBUGF(sc, lvl, fmt, args...) \
118     if ((lvl) <= (sc)->sc_debug) \
119         printf(fmt, ##args)
120 
121 static void bcm_bsc_intr(void *);
122 static int bcm_bsc_detach(device_t);
123 
124 static void
125 bcm_bsc_modifyreg(struct bcm_bsc_softc *sc, uint32_t off, uint32_t mask,
126 	uint32_t value)
127 {
128 	uint32_t reg;
129 
130 	mtx_assert(&sc->sc_mtx, MA_OWNED);
131 	reg = BCM_BSC_READ(sc, off);
132 	reg &= ~mask;
133 	reg |= value;
134 	BCM_BSC_WRITE(sc, off, reg);
135 }
136 
137 static int
138 bcm_bsc_clock_proc(SYSCTL_HANDLER_ARGS)
139 {
140 	struct bcm_bsc_softc *sc;
141 	uint32_t clk;
142 
143 	sc = (struct bcm_bsc_softc *)arg1;
144 	BCM_BSC_LOCK(sc);
145 	clk = BCM_BSC_READ(sc, BCM_BSC_CLOCK);
146 	BCM_BSC_UNLOCK(sc);
147 	clk &= 0xffff;
148 	if (clk == 0)
149 		clk = 32768;
150 	clk = BCM_BSC_CORE_CLK / clk;
151 
152 	return (sysctl_handle_int(oidp, &clk, 0, req));
153 }
154 
155 static int
156 bcm_bsc_clkt_proc(SYSCTL_HANDLER_ARGS)
157 {
158 	struct bcm_bsc_softc *sc;
159 	uint32_t clkt;
160 	int error;
161 
162 	sc = (struct bcm_bsc_softc *)arg1;
163 
164 	BCM_BSC_LOCK(sc);
165 	clkt = BCM_BSC_READ(sc, BCM_BSC_CLKT);
166 	BCM_BSC_UNLOCK(sc);
167 	clkt &= 0xffff;
168 	error = sysctl_handle_int(oidp, &clkt, sizeof(clkt), req);
169 	if (error != 0 || req->newptr == NULL)
170 		return (error);
171 
172 	BCM_BSC_LOCK(sc);
173 	BCM_BSC_WRITE(sc, BCM_BSC_CLKT, clkt & 0xffff);
174 	BCM_BSC_UNLOCK(sc);
175 
176 	return (0);
177 }
178 
179 static int
180 bcm_bsc_fall_proc(SYSCTL_HANDLER_ARGS)
181 {
182 	struct bcm_bsc_softc *sc;
183 	uint32_t clk, reg;
184 	int error;
185 
186 	sc = (struct bcm_bsc_softc *)arg1;
187 
188 	BCM_BSC_LOCK(sc);
189 	reg = BCM_BSC_READ(sc, BCM_BSC_DELAY);
190 	BCM_BSC_UNLOCK(sc);
191 	reg >>= 16;
192 	error = sysctl_handle_int(oidp, &reg, sizeof(reg), req);
193 	if (error != 0 || req->newptr == NULL)
194 		return (error);
195 
196 	BCM_BSC_LOCK(sc);
197 	clk = BCM_BSC_READ(sc, BCM_BSC_CLOCK);
198 	clk = BCM_BSC_CORE_CLK / clk;
199 	if (reg > clk / 2)
200 		reg = clk / 2 - 1;
201 	bcm_bsc_modifyreg(sc, BCM_BSC_DELAY, 0xffff0000, reg << 16);
202 	BCM_BSC_UNLOCK(sc);
203 
204 	return (0);
205 }
206 
207 static int
208 bcm_bsc_rise_proc(SYSCTL_HANDLER_ARGS)
209 {
210 	struct bcm_bsc_softc *sc;
211 	uint32_t clk, reg;
212 	int error;
213 
214 	sc = (struct bcm_bsc_softc *)arg1;
215 
216 	BCM_BSC_LOCK(sc);
217 	reg = BCM_BSC_READ(sc, BCM_BSC_DELAY);
218 	BCM_BSC_UNLOCK(sc);
219 	reg &= 0xffff;
220 	error = sysctl_handle_int(oidp, &reg, sizeof(reg), req);
221 	if (error != 0 || req->newptr == NULL)
222 		return (error);
223 
224 	BCM_BSC_LOCK(sc);
225 	clk = BCM_BSC_READ(sc, BCM_BSC_CLOCK);
226 	clk = BCM_BSC_CORE_CLK / clk;
227 	if (reg > clk / 2)
228 		reg = clk / 2 - 1;
229 	bcm_bsc_modifyreg(sc, BCM_BSC_DELAY, 0xffff, reg);
230 	BCM_BSC_UNLOCK(sc);
231 
232 	return (0);
233 }
234 
235 static void
236 bcm_bsc_sysctl_init(struct bcm_bsc_softc *sc)
237 {
238 	struct sysctl_ctx_list *ctx;
239 	struct sysctl_oid *tree_node;
240 	struct sysctl_oid_list *tree;
241 
242 	/*
243 	 * Add system sysctl tree/handlers.
244 	 */
245 	ctx = device_get_sysctl_ctx(sc->sc_dev);
246 	tree_node = device_get_sysctl_tree(sc->sc_dev);
247 	tree = SYSCTL_CHILDREN(tree_node);
248 	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "frequency",
249 	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_NEEDGIANT,
250 	    sc, sizeof(*sc),
251 	    bcm_bsc_clock_proc, "IU", "I2C BUS clock frequency");
252 	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "clock_stretch",
253 	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_NEEDGIANT,
254 	    sc, sizeof(*sc),
255 	    bcm_bsc_clkt_proc, "IU", "I2C BUS clock stretch timeout");
256 	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "fall_edge_delay",
257 	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_NEEDGIANT,
258 	    sc, sizeof(*sc),
259 	    bcm_bsc_fall_proc, "IU", "I2C BUS falling edge delay");
260 	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "rise_edge_delay",
261 	    CTLFLAG_RW | CTLTYPE_UINT | CTLFLAG_NEEDGIANT,
262 	    sc, sizeof(*sc),
263 	    bcm_bsc_rise_proc, "IU", "I2C BUS rising edge delay");
264 	SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "debug",
265 	    CTLFLAG_RWTUN, &sc->sc_debug, 0,
266 	    "Enable debug; 1=reads/writes, 2=add starts/stops");
267 }
268 
269 static void
270 bcm_bsc_reset(struct bcm_bsc_softc *sc)
271 {
272 
273 	/* Enable the BSC Controller, disable interrupts. */
274 	BCM_BSC_WRITE(sc, BCM_BSC_CTRL, BCM_BSC_CTRL_I2CEN);
275 	/* Clear pending interrupts. */
276 	BCM_BSC_WRITE(sc, BCM_BSC_STATUS, BCM_BSC_STATUS_CLKT |
277 	    BCM_BSC_STATUS_ERR | BCM_BSC_STATUS_DONE);
278 	/* Clear the FIFO. */
279 	bcm_bsc_modifyreg(sc, BCM_BSC_CTRL, BCM_BSC_CTRL_CLEAR0,
280 	    BCM_BSC_CTRL_CLEAR0);
281 }
282 
283 static int
284 bcm_bsc_probe(device_t dev)
285 {
286 
287 	if (!ofw_bus_status_okay(dev))
288 		return (ENXIO);
289 
290 	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0)
291 		return (ENXIO);
292 
293 	device_set_desc(dev, "BCM2708/2835 BSC controller");
294 
295 	return (BUS_PROBE_DEFAULT);
296 }
297 
298 static int
299 bcm_bsc_attach(device_t dev)
300 {
301 	struct bcm_bsc_softc *sc;
302 	int rid;
303 
304 	sc = device_get_softc(dev);
305 	sc->sc_dev = dev;
306 
307 	rid = 0;
308 	sc->sc_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
309 	    RF_ACTIVE);
310 	if (!sc->sc_mem_res) {
311 		device_printf(dev, "cannot allocate memory window\n");
312 		return (ENXIO);
313 	}
314 
315 	sc->sc_bst = rman_get_bustag(sc->sc_mem_res);
316 	sc->sc_bsh = rman_get_bushandle(sc->sc_mem_res);
317 
318 	rid = 0;
319 	sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
320 	    RF_ACTIVE | RF_SHAREABLE);
321 	if (!sc->sc_irq_res) {
322 		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
323 		device_printf(dev, "cannot allocate interrupt\n");
324 		return (ENXIO);
325 	}
326 
327 	/* Hook up our interrupt handler. */
328 	if (bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_MISC | INTR_MPSAFE,
329 	    NULL, bcm_bsc_intr, sc, &sc->sc_intrhand)) {
330 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
331 		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
332 		device_printf(dev, "cannot setup the interrupt handler\n");
333 		return (ENXIO);
334 	}
335 
336 	mtx_init(&sc->sc_mtx, "bcm_bsc", NULL, MTX_DEF);
337 
338 	bcm_bsc_sysctl_init(sc);
339 
340 	/* Enable the BSC controller.  Flush the FIFO. */
341 	BCM_BSC_LOCK(sc);
342 	bcm_bsc_reset(sc);
343 	BCM_BSC_UNLOCK(sc);
344 
345 	sc->sc_iicbus = device_add_child(dev, "iicbus", DEVICE_UNIT_ANY);
346 	if (sc->sc_iicbus == NULL) {
347 		bcm_bsc_detach(dev);
348 		return (ENXIO);
349 	}
350 
351 	/* Probe and attach the iicbus when interrupts are available. */
352 	bus_delayed_attach_children(dev);
353 	return (0);
354 }
355 
356 static int
357 bcm_bsc_detach(device_t dev)
358 {
359 	struct bcm_bsc_softc *sc;
360 
361 	bus_generic_detach(dev);
362 
363 	sc = device_get_softc(dev);
364 	mtx_destroy(&sc->sc_mtx);
365 	if (sc->sc_intrhand)
366 		bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_intrhand);
367 	if (sc->sc_irq_res)
368 		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
369 	if (sc->sc_mem_res)
370 		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
371 
372 	return (0);
373 }
374 
375 static void
376 bcm_bsc_empty_rx_fifo(struct bcm_bsc_softc *sc)
377 {
378 	uint32_t status;
379 
380 	/* Assumes sc_totlen > 0 and BCM_BSC_STATUS_RXD is asserted on entry. */
381 	do {
382 		if (sc->sc_resid == 0) {
383 			sc->sc_data  = sc->sc_curmsg->buf;
384 			sc->sc_dlen  = sc->sc_curmsg->len;
385 			sc->sc_resid = sc->sc_dlen;
386 			++sc->sc_curmsg;
387 		}
388 		do {
389 			*sc->sc_data = BCM_BSC_READ(sc, BCM_BSC_DATA);
390 			DEBUGF(sc, 1, "0x%02x ", *sc->sc_data);
391 			++sc->sc_data;
392 			--sc->sc_resid;
393 			--sc->sc_totlen;
394 			status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
395 		} while (sc->sc_resid > 0 && (status & BCM_BSC_STATUS_RXD));
396 	} while (sc->sc_totlen > 0 && (status & BCM_BSC_STATUS_RXD));
397 }
398 
399 static void
400 bcm_bsc_fill_tx_fifo(struct bcm_bsc_softc *sc)
401 {
402 	uint32_t status;
403 
404 	/* Assumes sc_totlen > 0 and BCM_BSC_STATUS_TXD is asserted on entry. */
405 	do {
406 		if (sc->sc_resid == 0) {
407 			sc->sc_data  = sc->sc_curmsg->buf;
408 			sc->sc_dlen  = sc->sc_curmsg->len;
409 			sc->sc_resid = sc->sc_dlen;
410 			++sc->sc_curmsg;
411 		}
412 		do {
413 			BCM_BSC_WRITE(sc, BCM_BSC_DATA, *sc->sc_data);
414 			DEBUGF(sc, 1, "0x%02x ", *sc->sc_data);
415 			++sc->sc_data;
416 			--sc->sc_resid;
417 			--sc->sc_totlen;
418 			status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
419 		} while (sc->sc_resid > 0 && (status & BCM_BSC_STATUS_TXD));
420 		/*
421 		 * If a repeat-start was pending and we just hit the end of a tx
422 		 * buffer, see if it's also the end of the writes that preceeded
423 		 * the repeat-start.  If so, log the repeat-start and the start
424 		 * of the following read, and return because we're not writing
425 		 * anymore (and TXD will be true because there's room to write
426 		 * in the fifo).
427 		 */
428 		if (sc->sc_replen > 0 && sc->sc_resid == 0) {
429 			sc->sc_replen -= sc->sc_dlen;
430 			if (sc->sc_replen == 0) {
431 				DEBUGF(sc, 1, " err=0\n");
432 				DEVICE_DEBUGF(sc, 2, "rstart 0x%02x\n",
433 				    sc->sc_curmsg->slave | 0x01);
434 				DEVICE_DEBUGF(sc, 1,
435 				    "read   0x%02x len %d: ",
436 				    sc->sc_curmsg->slave | 0x01,
437 				    sc->sc_totlen);
438 				sc->sc_flags |= BCM_I2C_READ;
439 				return;
440 			}
441 		}
442 	} while (sc->sc_totlen > 0 && (status & BCM_BSC_STATUS_TXD));
443 }
444 
445 static void
446 bcm_bsc_intr(void *arg)
447 {
448 	struct bcm_bsc_softc *sc;
449 	uint32_t status;
450 
451 	sc = (struct bcm_bsc_softc *)arg;
452 
453 	BCM_BSC_LOCK(sc);
454 
455 	/* The I2C interrupt is shared among all the BSC controllers. */
456 	if ((sc->sc_flags & BCM_I2C_BUSY) == 0) {
457 		BCM_BSC_UNLOCK(sc);
458 		return;
459 	}
460 
461 	status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
462 	DEBUGF(sc, 4, " <intrstatus=0x%08x> ", status);
463 
464 	/* RXD and DONE can assert together, empty fifo before checking done. */
465 	if ((sc->sc_flags & BCM_I2C_READ) && (status & BCM_BSC_STATUS_RXD))
466 		bcm_bsc_empty_rx_fifo(sc);
467 
468 	/* Check for completion. */
469 	if (status & (BCM_BSC_STATUS_ERRBITS | BCM_BSC_STATUS_DONE)) {
470 		sc->sc_flags |= BCM_I2C_DONE;
471 		if (status & BCM_BSC_STATUS_ERRBITS)
472 			sc->sc_flags |= BCM_I2C_ERROR;
473 		/* Disable interrupts. */
474 		bcm_bsc_reset(sc);
475 		wakeup(sc);
476 	} else if (!(sc->sc_flags & BCM_I2C_READ)) {
477 		/*
478 		 * Don't check for TXD until after determining whether the
479 		 * transfer is complete; TXD will be asserted along with ERR or
480 		 * DONE if there is room in the fifo.
481 		 */
482 		if ((status & BCM_BSC_STATUS_TXD) && sc->sc_totlen > 0)
483 			bcm_bsc_fill_tx_fifo(sc);
484 	}
485 
486 	BCM_BSC_UNLOCK(sc);
487 }
488 
489 static int
490 bcm_bsc_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
491 {
492 	struct bcm_bsc_softc *sc;
493 	struct iic_msg *endmsgs, *nxtmsg;
494 	uint32_t readctl, status;
495 	int err;
496 	uint16_t curlen;
497 	uint8_t curisread, curslave, nxtisread, nxtslave;
498 
499 	sc = device_get_softc(dev);
500 	BCM_BSC_LOCK(sc);
501 
502 	/* If the controller is busy wait until it is available. */
503 	while (sc->sc_flags & BCM_I2C_BUSY)
504 		mtx_sleep(dev, &sc->sc_mtx, 0, "bscbusw", 0);
505 
506 	/* Now we have control over the BSC controller. */
507 	sc->sc_flags = BCM_I2C_BUSY;
508 
509 	DEVICE_DEBUGF(sc, 3, "Transfer %d msgs\n", nmsgs);
510 
511 	/* Clear the FIFO and the pending interrupts. */
512 	bcm_bsc_reset(sc);
513 
514 	/*
515 	 * Perform all the transfers requested in the array of msgs.  Note that
516 	 * it is bcm_bsc_empty_rx_fifo() and bcm_bsc_fill_tx_fifo() that advance
517 	 * sc->sc_curmsg through the array of messages, as the data from each
518 	 * message is fully consumed, but it is this loop that notices when we
519 	 * have no more messages to process.
520 	 */
521 	err = 0;
522 	sc->sc_resid = 0;
523 	sc->sc_curmsg = msgs;
524 	endmsgs = &msgs[nmsgs];
525 	while (sc->sc_curmsg < endmsgs) {
526 		readctl = 0;
527 		curslave = sc->sc_curmsg->slave >> 1;
528 		curisread = sc->sc_curmsg->flags & IIC_M_RD;
529 		sc->sc_replen = 0;
530 		sc->sc_totlen = sc->sc_curmsg->len;
531 		/*
532 		 * Scan for scatter/gather IO (same slave and direction) or
533 		 * repeat-start (read following write for the same slave).
534 		 */
535 		for (nxtmsg = sc->sc_curmsg + 1; nxtmsg < endmsgs; ++nxtmsg) {
536 			nxtslave = nxtmsg->slave >> 1;
537 			if (curslave == nxtslave) {
538 				nxtisread = nxtmsg->flags & IIC_M_RD;
539 				if (curisread == nxtisread) {
540 					/*
541 					 * Same slave and direction, this
542 					 * message will be part of the same
543 					 * transfer as the previous one.
544 					 */
545 					sc->sc_totlen += nxtmsg->len;
546 					continue;
547 				} else if (curisread == IIC_M_WR) {
548 					/*
549 					 * Read after write to same slave means
550 					 * repeat-start, remember how many bytes
551 					 * come before the repeat-start, switch
552 					 * the direction to IIC_M_RD, and gather
553 					 * up following reads to the same slave.
554 					 */
555 					curisread = IIC_M_RD;
556 					sc->sc_replen = sc->sc_totlen;
557 					sc->sc_totlen += nxtmsg->len;
558 					continue;
559 				}
560 			}
561 			break;
562 		}
563 
564 		/*
565 		 * curslave and curisread temporaries from above may refer to
566 		 * the after-repstart msg, reset them to reflect sc_curmsg.
567 		 */
568 		curisread = (sc->sc_curmsg->flags & IIC_M_RD) ? 1 : 0;
569 		curslave = sc->sc_curmsg->slave | curisread;
570 
571 		/* Write the slave address. */
572 		BCM_BSC_WRITE(sc, BCM_BSC_SLAVE, curslave >> 1);
573 
574 		DEVICE_DEBUGF(sc, 2, "start  0x%02x\n", curslave);
575 
576 		/*
577 		 * Either set up read length and direction variables for a
578 		 * simple transfer or get the hardware started on the first
579 		 * piece of a transfer that involves a repeat-start and set up
580 		 * the read length and direction vars for the second piece.
581 		 */
582 		if (sc->sc_replen == 0) {
583 			DEVICE_DEBUGF(sc, 1, "%-6s 0x%02x len %d: ",
584 			    (curisread) ? "read" : "write", curslave,
585 			    sc->sc_totlen);
586 			curlen = sc->sc_totlen;
587 			if (curisread) {
588 				readctl = BCM_BSC_CTRL_READ;
589 				sc->sc_flags |= BCM_I2C_READ;
590 			} else {
591 				readctl = 0;
592 				sc->sc_flags &= ~BCM_I2C_READ;
593 			}
594 		} else {
595 			DEVICE_DEBUGF(sc, 1, "%-6s 0x%02x len %d: ",
596 			    (curisread) ? "read" : "write", curslave,
597 			    sc->sc_replen);
598 
599 			/*
600 			 * Start the write transfer with an empty fifo and wait
601 			 * for the 'transfer active' status bit to light up;
602 			 * that indicates that the hardware has latched the
603 			 * direction and length for the write, and we can safely
604 			 * reload those registers and issue the start for the
605 			 * following read; interrupts are not enabled here.
606 			 */
607 			BCM_BSC_WRITE(sc, BCM_BSC_DLEN, sc->sc_replen);
608 			BCM_BSC_WRITE(sc, BCM_BSC_CTRL, BCM_BSC_CTRL_I2CEN |
609 			    BCM_BSC_CTRL_ST);
610 			do {
611 				status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
612 				if (status & BCM_BSC_STATUS_ERR) {
613 					/* no ACK on slave addr */
614 					err = EIO;
615 					goto xfer_done;
616 				}
617 			} while ((status & BCM_BSC_STATUS_TA) == 0);
618 			/*
619 			 * Set curlen and readctl for the repeat-start read that
620 			 * we need to set up below, but set sc_flags to write,
621 			 * because that is the operation in progress right now.
622 			 */
623 			curlen = sc->sc_totlen - sc->sc_replen;
624 			readctl = BCM_BSC_CTRL_READ;
625 			sc->sc_flags &= ~BCM_I2C_READ;
626 		}
627 
628 		/*
629 		 * Start the transfer with interrupts enabled, then if doing a
630 		 * write, fill the tx fifo.  Not prefilling the fifo until after
631 		 * this start command is the key workaround for making
632 		 * repeat-start work, and it's harmless to do it in this order
633 		 * for a regular write too.
634 		 */
635 		BCM_BSC_WRITE(sc, BCM_BSC_DLEN, curlen);
636 		BCM_BSC_WRITE(sc, BCM_BSC_CTRL, readctl | BCM_BSC_CTRL_I2CEN |
637 		    BCM_BSC_CTRL_ST | BCM_BSC_CTRL_INT_ALL);
638 
639 		if (!(sc->sc_curmsg->flags & IIC_M_RD)) {
640 			bcm_bsc_fill_tx_fifo(sc);
641 		}
642 
643 		/* Wait for the transaction to complete. */
644 		while (err == 0 && !(sc->sc_flags & BCM_I2C_DONE)) {
645 			err = mtx_sleep(sc, &sc->sc_mtx, 0, "bsciow", hz);
646 		}
647 		/* Check for errors. */
648 		if (err == 0 && (sc->sc_flags & BCM_I2C_ERROR))
649 			err = EIO;
650 xfer_done:
651 		DEBUGF(sc, 1, " err=%d\n", err);
652 		DEVICE_DEBUGF(sc, 2, "stop\n");
653 		if (err != 0)
654 			break;
655 	}
656 
657 	/* Disable interrupts, clean fifo, etc. */
658 	bcm_bsc_reset(sc);
659 
660 	/* Clean the controller flags. */
661 	sc->sc_flags = 0;
662 
663 	/* Wake up the threads waiting for bus. */
664 	wakeup(dev);
665 
666 	BCM_BSC_UNLOCK(sc);
667 
668 	return (err);
669 }
670 
671 static int
672 bcm_bsc_iicbus_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
673 {
674 	struct bcm_bsc_softc *sc;
675 	uint32_t busfreq;
676 
677 	sc = device_get_softc(dev);
678 	BCM_BSC_LOCK(sc);
679 	bcm_bsc_reset(sc);
680 	if (sc->sc_iicbus == NULL)
681 		busfreq = 100000;
682 	else
683 		busfreq = IICBUS_GET_FREQUENCY(sc->sc_iicbus, speed);
684 	BCM_BSC_WRITE(sc, BCM_BSC_CLOCK, BCM_BSC_CORE_CLK / busfreq);
685 	BCM_BSC_UNLOCK(sc);
686 
687 	return (IIC_ENOADDR);
688 }
689 
690 static phandle_t
691 bcm_bsc_get_node(device_t bus, device_t dev)
692 {
693 
694 	/* We only have one child, the I2C bus, which needs our own node. */
695 	return (ofw_bus_get_node(bus));
696 }
697 
698 static device_method_t bcm_bsc_methods[] = {
699 	/* Device interface */
700 	DEVMETHOD(device_probe,		bcm_bsc_probe),
701 	DEVMETHOD(device_attach,	bcm_bsc_attach),
702 	DEVMETHOD(device_detach,	bcm_bsc_detach),
703 
704 	/* iicbus interface */
705 	DEVMETHOD(iicbus_reset,		bcm_bsc_iicbus_reset),
706 	DEVMETHOD(iicbus_callback,	iicbus_null_callback),
707 	DEVMETHOD(iicbus_transfer,	bcm_bsc_transfer),
708 
709 	/* ofw_bus interface */
710 	DEVMETHOD(ofw_bus_get_node,	bcm_bsc_get_node),
711 
712 	DEVMETHOD_END
713 };
714 
715 static driver_t bcm_bsc_driver = {
716 	"iichb",
717 	bcm_bsc_methods,
718 	sizeof(struct bcm_bsc_softc),
719 };
720 
721 DRIVER_MODULE(iicbus, bcm2835_bsc, iicbus_driver, 0, 0);
722 DRIVER_MODULE(bcm2835_bsc, simplebus, bcm_bsc_driver, 0, 0);
723