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