bcm2835_bsc.c revision 331722
1/*-
2 * Copyright (c) 2001 Tsubai Masanari.
3 * Copyright (c) 2012 Oleksandr Tymoshenko <gonzo@freebsd.org>
4 * Copyright (c) 2013 Luiz Otavio O Souza <loos@freebsd.org>
5 * Copyright (c) 2017 Ian Lepore <ian@freebsd.org>
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 */
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: stable/11/sys/arm/broadcom/bcm2835/bcm2835_bsc.c 331722 2018-03-29 02:50:57Z eadler $");
32
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_gpio.h>
102#include <arm/broadcom/bcm2835/bcm2835_bscreg.h>
103#include <arm/broadcom/bcm2835/bcm2835_bscvar.h>
104
105#include "iicbus_if.h"
106
107static struct ofw_compat_data compat_data[] = {
108	{"broadcom,bcm2835-bsc",	1},
109	{"brcm,bcm2708-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
121static void bcm_bsc_intr(void *);
122static int bcm_bsc_detach(device_t);
123
124static void
125bcm_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
137static int
138bcm_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
155static int
156bcm_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
179static int
180bcm_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
207static int
208bcm_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
235static void
236bcm_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, sc, sizeof(*sc),
250	    bcm_bsc_clock_proc, "IU", "I2C BUS clock frequency");
251	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "clock_stretch",
252	    CTLFLAG_RW | CTLTYPE_UINT, sc, sizeof(*sc),
253	    bcm_bsc_clkt_proc, "IU", "I2C BUS clock stretch timeout");
254	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "fall_edge_delay",
255	    CTLFLAG_RW | CTLTYPE_UINT, sc, sizeof(*sc),
256	    bcm_bsc_fall_proc, "IU", "I2C BUS falling edge delay");
257	SYSCTL_ADD_PROC(ctx, tree, OID_AUTO, "rise_edge_delay",
258	    CTLFLAG_RW | CTLTYPE_UINT, sc, sizeof(*sc),
259	    bcm_bsc_rise_proc, "IU", "I2C BUS rising edge delay");
260	SYSCTL_ADD_INT(ctx, tree, OID_AUTO, "debug",
261	    CTLFLAG_RWTUN, &sc->sc_debug, 0,
262	    "Enable debug; 1=reads/writes, 2=add starts/stops");
263}
264
265static void
266bcm_bsc_reset(struct bcm_bsc_softc *sc)
267{
268
269	/* Enable the BSC Controller, disable interrupts. */
270	BCM_BSC_WRITE(sc, BCM_BSC_CTRL, BCM_BSC_CTRL_I2CEN);
271	/* Clear pending interrupts. */
272	BCM_BSC_WRITE(sc, BCM_BSC_STATUS, BCM_BSC_STATUS_CLKT |
273	    BCM_BSC_STATUS_ERR | BCM_BSC_STATUS_DONE);
274	/* Clear the FIFO. */
275	bcm_bsc_modifyreg(sc, BCM_BSC_CTRL, BCM_BSC_CTRL_CLEAR0,
276	    BCM_BSC_CTRL_CLEAR0);
277}
278
279static int
280bcm_bsc_probe(device_t dev)
281{
282
283	if (!ofw_bus_status_okay(dev))
284		return (ENXIO);
285
286	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0)
287		return (ENXIO);
288
289	device_set_desc(dev, "BCM2708/2835 BSC controller");
290
291	return (BUS_PROBE_DEFAULT);
292}
293
294static int
295bcm_bsc_attach(device_t dev)
296{
297	struct bcm_bsc_softc *sc;
298	unsigned long start;
299	device_t gpio;
300	int i, rid;
301
302	sc = device_get_softc(dev);
303	sc->sc_dev = dev;
304
305	rid = 0;
306	sc->sc_mem_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
307	    RF_ACTIVE);
308	if (!sc->sc_mem_res) {
309		device_printf(dev, "cannot allocate memory window\n");
310		return (ENXIO);
311	}
312
313	sc->sc_bst = rman_get_bustag(sc->sc_mem_res);
314	sc->sc_bsh = rman_get_bushandle(sc->sc_mem_res);
315
316	/* Check the unit we are attaching by its base address. */
317	start = rman_get_start(sc->sc_mem_res);
318	for (i = 0; i < nitems(bcm_bsc_pins); i++) {
319		if (bcm_bsc_pins[i].start == (start & BCM_BSC_BASE_MASK))
320			break;
321	}
322	if (i == nitems(bcm_bsc_pins)) {
323		device_printf(dev, "only bsc0 and bsc1 are supported\n");
324		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
325		return (ENXIO);
326	}
327
328	/*
329	 * Configure the GPIO pins to ALT0 function to enable BSC control
330	 * over the pins.
331	 */
332	gpio = devclass_get_device(devclass_find("gpio"), 0);
333	if (!gpio) {
334		device_printf(dev, "cannot find gpio0\n");
335		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
336		return (ENXIO);
337	}
338	bcm_gpio_set_alternate(gpio, bcm_bsc_pins[i].sda, BCM_GPIO_ALT0);
339	bcm_gpio_set_alternate(gpio, bcm_bsc_pins[i].scl, BCM_GPIO_ALT0);
340
341	rid = 0;
342	sc->sc_irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
343	    RF_ACTIVE | RF_SHAREABLE);
344	if (!sc->sc_irq_res) {
345		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
346		device_printf(dev, "cannot allocate interrupt\n");
347		return (ENXIO);
348	}
349
350	/* Hook up our interrupt handler. */
351	if (bus_setup_intr(dev, sc->sc_irq_res, INTR_TYPE_MISC | INTR_MPSAFE,
352	    NULL, bcm_bsc_intr, sc, &sc->sc_intrhand)) {
353		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
354		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
355		device_printf(dev, "cannot setup the interrupt handler\n");
356		return (ENXIO);
357	}
358
359	mtx_init(&sc->sc_mtx, "bcm_bsc", NULL, MTX_DEF);
360
361	bcm_bsc_sysctl_init(sc);
362
363	/* Enable the BSC controller.  Flush the FIFO. */
364	BCM_BSC_LOCK(sc);
365	bcm_bsc_reset(sc);
366	BCM_BSC_UNLOCK(sc);
367
368	sc->sc_iicbus = device_add_child(dev, "iicbus", -1);
369	if (sc->sc_iicbus == NULL) {
370		bcm_bsc_detach(dev);
371		return (ENXIO);
372	}
373
374	/* Probe and attach the iicbus when interrupts are available. */
375	config_intrhook_oneshot((ich_func_t)bus_generic_attach, dev);
376
377	return (0);
378}
379
380static int
381bcm_bsc_detach(device_t dev)
382{
383	struct bcm_bsc_softc *sc;
384
385	bus_generic_detach(dev);
386
387	sc = device_get_softc(dev);
388	if (sc->sc_iicbus != NULL)
389		device_delete_child(dev, sc->sc_iicbus);
390	mtx_destroy(&sc->sc_mtx);
391	if (sc->sc_intrhand)
392		bus_teardown_intr(dev, sc->sc_irq_res, sc->sc_intrhand);
393	if (sc->sc_irq_res)
394		bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq_res);
395	if (sc->sc_mem_res)
396		bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->sc_mem_res);
397
398	return (0);
399}
400
401static void
402bcm_bsc_empty_rx_fifo(struct bcm_bsc_softc *sc)
403{
404	uint32_t status;
405
406	/* Assumes sc_totlen > 0 and BCM_BSC_STATUS_RXD is asserted on entry. */
407	do {
408		if (sc->sc_resid == 0) {
409			sc->sc_data  = sc->sc_curmsg->buf;
410			sc->sc_dlen  = sc->sc_curmsg->len;
411			sc->sc_resid = sc->sc_dlen;
412			++sc->sc_curmsg;
413		}
414		do {
415			*sc->sc_data = BCM_BSC_READ(sc, BCM_BSC_DATA);
416			DEBUGF(sc, 1, "0x%02x ", *sc->sc_data);
417			++sc->sc_data;
418			--sc->sc_resid;
419			--sc->sc_totlen;
420			status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
421		} while (sc->sc_resid > 0 && (status & BCM_BSC_STATUS_RXD));
422	} while (sc->sc_totlen > 0 && (status & BCM_BSC_STATUS_RXD));
423}
424
425static void
426bcm_bsc_fill_tx_fifo(struct bcm_bsc_softc *sc)
427{
428	uint32_t status;
429
430	/* Assumes sc_totlen > 0 and BCM_BSC_STATUS_TXD is asserted on entry. */
431	do {
432		if (sc->sc_resid == 0) {
433			sc->sc_data  = sc->sc_curmsg->buf;
434			sc->sc_dlen  = sc->sc_curmsg->len;
435			sc->sc_resid = sc->sc_dlen;
436			++sc->sc_curmsg;
437		}
438		do {
439			BCM_BSC_WRITE(sc, BCM_BSC_DATA, *sc->sc_data);
440			DEBUGF(sc, 1, "0x%02x ", *sc->sc_data);
441			++sc->sc_data;
442			--sc->sc_resid;
443			--sc->sc_totlen;
444			status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
445		} while (sc->sc_resid > 0 && (status & BCM_BSC_STATUS_TXD));
446		/*
447		 * If a repeat-start was pending and we just hit the end of a tx
448		 * buffer, see if it's also the end of the writes that preceeded
449		 * the repeat-start.  If so, log the repeat-start and the start
450		 * of the following read, and return because we're not writing
451		 * anymore (and TXD will be true because there's room to write
452		 * in the fifo).
453		 */
454		if (sc->sc_replen > 0 && sc->sc_resid == 0) {
455			sc->sc_replen -= sc->sc_dlen;
456			if (sc->sc_replen == 0) {
457				DEBUGF(sc, 1, " err=0\n");
458				DEVICE_DEBUGF(sc, 2, "rstart 0x%02x\n",
459				    sc->sc_curmsg->slave | 0x01);
460				DEVICE_DEBUGF(sc, 1,
461				    "read   0x%02x len %d: ",
462				    sc->sc_curmsg->slave | 0x01,
463				    sc->sc_totlen);
464				sc->sc_flags |= BCM_I2C_READ;
465				return;
466			}
467		}
468	} while (sc->sc_totlen > 0 && (status & BCM_BSC_STATUS_TXD));
469}
470
471static void
472bcm_bsc_intr(void *arg)
473{
474	struct bcm_bsc_softc *sc;
475	uint32_t status;
476
477	sc = (struct bcm_bsc_softc *)arg;
478
479	BCM_BSC_LOCK(sc);
480
481	/* The I2C interrupt is shared among all the BSC controllers. */
482	if ((sc->sc_flags & BCM_I2C_BUSY) == 0) {
483		BCM_BSC_UNLOCK(sc);
484		return;
485	}
486
487	status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
488	DEBUGF(sc, 4, " <intrstatus=0x%08x> ", status);
489
490	/* RXD and DONE can assert together, empty fifo before checking done. */
491	if ((sc->sc_flags & BCM_I2C_READ) && (status & BCM_BSC_STATUS_RXD))
492		bcm_bsc_empty_rx_fifo(sc);
493
494	/* Check for completion. */
495	if (status & (BCM_BSC_STATUS_ERRBITS | BCM_BSC_STATUS_DONE)) {
496		sc->sc_flags |= BCM_I2C_DONE;
497		if (status & BCM_BSC_STATUS_ERRBITS)
498			sc->sc_flags |= BCM_I2C_ERROR;
499		/* Disable interrupts. */
500		bcm_bsc_reset(sc);
501		wakeup(sc);
502	} else if (!(sc->sc_flags & BCM_I2C_READ)) {
503		/*
504		 * Don't check for TXD until after determining whether the
505		 * transfer is complete; TXD will be asserted along with ERR or
506		 * DONE if there is room in the fifo.
507		 */
508		if ((status & BCM_BSC_STATUS_TXD) && sc->sc_totlen > 0)
509			bcm_bsc_fill_tx_fifo(sc);
510	}
511
512	BCM_BSC_UNLOCK(sc);
513}
514
515static int
516bcm_bsc_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
517{
518	struct bcm_bsc_softc *sc;
519	struct iic_msg *endmsgs, *nxtmsg;
520	uint32_t readctl, status;
521	int err;
522	uint16_t curlen;
523	uint8_t curisread, curslave, nxtisread, nxtslave;
524
525	sc = device_get_softc(dev);
526	BCM_BSC_LOCK(sc);
527
528	/* If the controller is busy wait until it is available. */
529	while (sc->sc_flags & BCM_I2C_BUSY)
530		mtx_sleep(dev, &sc->sc_mtx, 0, "bscbusw", 0);
531
532	/* Now we have control over the BSC controller. */
533	sc->sc_flags = BCM_I2C_BUSY;
534
535	DEVICE_DEBUGF(sc, 3, "Transfer %d msgs\n", nmsgs);
536
537	/* Clear the FIFO and the pending interrupts. */
538	bcm_bsc_reset(sc);
539
540	/*
541	 * Perform all the transfers requested in the array of msgs.  Note that
542	 * it is bcm_bsc_empty_rx_fifo() and bcm_bsc_fill_tx_fifo() that advance
543	 * sc->sc_curmsg through the array of messages, as the data from each
544	 * message is fully consumed, but it is this loop that notices when we
545	 * have no more messages to process.
546	 */
547	err = 0;
548	sc->sc_resid = 0;
549	sc->sc_curmsg = msgs;
550	endmsgs = &msgs[nmsgs];
551	while (sc->sc_curmsg < endmsgs) {
552		readctl = 0;
553		curslave = sc->sc_curmsg->slave >> 1;
554		curisread = sc->sc_curmsg->flags & IIC_M_RD;
555		sc->sc_replen = 0;
556		sc->sc_totlen = sc->sc_curmsg->len;
557		/*
558		 * Scan for scatter/gather IO (same slave and direction) or
559		 * repeat-start (read following write for the same slave).
560		 */
561		for (nxtmsg = sc->sc_curmsg + 1; nxtmsg < endmsgs; ++nxtmsg) {
562			nxtslave = nxtmsg->slave >> 1;
563			if (curslave == nxtslave) {
564				nxtisread = nxtmsg->flags & IIC_M_RD;
565				if (curisread == nxtisread) {
566					/*
567					 * Same slave and direction, this
568					 * message will be part of the same
569					 * transfer as the previous one.
570					 */
571					sc->sc_totlen += nxtmsg->len;
572					continue;
573				} else if (curisread == IIC_M_WR) {
574					/*
575					 * Read after write to same slave means
576					 * repeat-start, remember how many bytes
577					 * come before the repeat-start, switch
578					 * the direction to IIC_M_RD, and gather
579					 * up following reads to the same slave.
580					 */
581					curisread = IIC_M_RD;
582					sc->sc_replen = sc->sc_totlen;
583					sc->sc_totlen += nxtmsg->len;
584					continue;
585				}
586			}
587			break;
588		}
589
590		/*
591		 * curslave and curisread temporaries from above may refer to
592		 * the after-repstart msg, reset them to reflect sc_curmsg.
593		 */
594		curisread = (sc->sc_curmsg->flags & IIC_M_RD) ? 1 : 0;
595		curslave = sc->sc_curmsg->slave | curisread;
596
597		/* Write the slave address. */
598		BCM_BSC_WRITE(sc, BCM_BSC_SLAVE, curslave >> 1);
599
600		DEVICE_DEBUGF(sc, 2, "start  0x%02x\n", curslave);
601
602		/*
603		 * Either set up read length and direction variables for a
604		 * simple transfer or get the hardware started on the first
605		 * piece of a transfer that involves a repeat-start and set up
606		 * the read length and direction vars for the second piece.
607		 */
608		if (sc->sc_replen == 0) {
609			DEVICE_DEBUGF(sc, 1, "%-6s 0x%02x len %d: ",
610			    (curisread) ? "read" : "write", curslave,
611			    sc->sc_totlen);
612			curlen = sc->sc_totlen;
613			if (curisread) {
614				readctl = BCM_BSC_CTRL_READ;
615				sc->sc_flags |= BCM_I2C_READ;
616			} else {
617				readctl = 0;
618				sc->sc_flags &= ~BCM_I2C_READ;
619			}
620		} else {
621			DEVICE_DEBUGF(sc, 1, "%-6s 0x%02x len %d: ",
622			    (curisread) ? "read" : "write", curslave,
623			    sc->sc_replen);
624
625			/*
626			 * Start the write transfer with an empty fifo and wait
627			 * for the 'transfer active' status bit to light up;
628			 * that indicates that the hardware has latched the
629			 * direction and length for the write, and we can safely
630			 * reload those registers and issue the start for the
631			 * following read; interrupts are not enabled here.
632			 */
633			BCM_BSC_WRITE(sc, BCM_BSC_DLEN, sc->sc_replen);
634			BCM_BSC_WRITE(sc, BCM_BSC_CTRL, BCM_BSC_CTRL_I2CEN |
635			    BCM_BSC_CTRL_ST);
636			do {
637				status = BCM_BSC_READ(sc, BCM_BSC_STATUS);
638				if (status & BCM_BSC_STATUS_ERR) {
639					/* no ACK on slave addr */
640					err = EIO;
641					goto xfer_done;
642				}
643			} while ((status & BCM_BSC_STATUS_TA) == 0);
644			/*
645			 * Set curlen and readctl for the repeat-start read that
646			 * we need to set up below, but set sc_flags to write,
647			 * because that is the operation in progress right now.
648			 */
649			curlen = sc->sc_totlen - sc->sc_replen;
650			readctl = BCM_BSC_CTRL_READ;
651			sc->sc_flags &= ~BCM_I2C_READ;
652		}
653
654		/*
655		 * Start the transfer with interrupts enabled, then if doing a
656		 * write, fill the tx fifo.  Not prefilling the fifo until after
657		 * this start command is the key workaround for making
658		 * repeat-start work, and it's harmless to do it in this order
659		 * for a regular write too.
660		 */
661		BCM_BSC_WRITE(sc, BCM_BSC_DLEN, curlen);
662		BCM_BSC_WRITE(sc, BCM_BSC_CTRL, readctl | BCM_BSC_CTRL_I2CEN |
663		    BCM_BSC_CTRL_ST | BCM_BSC_CTRL_INT_ALL);
664
665		if (!(sc->sc_curmsg->flags & IIC_M_RD)) {
666			bcm_bsc_fill_tx_fifo(sc);
667		}
668
669		/* Wait for the transaction to complete. */
670		while (err == 0 && !(sc->sc_flags & BCM_I2C_DONE)) {
671			err = mtx_sleep(sc, &sc->sc_mtx, 0, "bsciow", hz);
672		}
673		/* Check for errors. */
674		if (err == 0 && (sc->sc_flags & BCM_I2C_ERROR))
675			err = EIO;
676xfer_done:
677		DEBUGF(sc, 1, " err=%d\n", err);
678		DEVICE_DEBUGF(sc, 2, "stop\n");
679		if (err != 0)
680			break;
681	}
682
683	/* Disable interrupts, clean fifo, etc. */
684	bcm_bsc_reset(sc);
685
686	/* Clean the controller flags. */
687	sc->sc_flags = 0;
688
689	/* Wake up the threads waiting for bus. */
690	wakeup(dev);
691
692	BCM_BSC_UNLOCK(sc);
693
694	return (err);
695}
696
697static int
698bcm_bsc_iicbus_reset(device_t dev, u_char speed, u_char addr, u_char *oldaddr)
699{
700	struct bcm_bsc_softc *sc;
701	uint32_t busfreq;
702
703	sc = device_get_softc(dev);
704	BCM_BSC_LOCK(sc);
705	bcm_bsc_reset(sc);
706	if (sc->sc_iicbus == NULL)
707		busfreq = 100000;
708	else
709		busfreq = IICBUS_GET_FREQUENCY(sc->sc_iicbus, speed);
710	BCM_BSC_WRITE(sc, BCM_BSC_CLOCK, BCM_BSC_CORE_CLK / busfreq);
711	BCM_BSC_UNLOCK(sc);
712
713	return (IIC_ENOADDR);
714}
715
716static phandle_t
717bcm_bsc_get_node(device_t bus, device_t dev)
718{
719
720	/* We only have one child, the I2C bus, which needs our own node. */
721	return (ofw_bus_get_node(bus));
722}
723
724static device_method_t bcm_bsc_methods[] = {
725	/* Device interface */
726	DEVMETHOD(device_probe,		bcm_bsc_probe),
727	DEVMETHOD(device_attach,	bcm_bsc_attach),
728	DEVMETHOD(device_detach,	bcm_bsc_detach),
729
730	/* iicbus interface */
731	DEVMETHOD(iicbus_reset,		bcm_bsc_iicbus_reset),
732	DEVMETHOD(iicbus_callback,	iicbus_null_callback),
733	DEVMETHOD(iicbus_transfer,	bcm_bsc_transfer),
734
735	/* ofw_bus interface */
736	DEVMETHOD(ofw_bus_get_node,	bcm_bsc_get_node),
737
738	DEVMETHOD_END
739};
740
741static devclass_t bcm_bsc_devclass;
742
743static driver_t bcm_bsc_driver = {
744	"iichb",
745	bcm_bsc_methods,
746	sizeof(struct bcm_bsc_softc),
747};
748
749DRIVER_MODULE(iicbus, bcm2835_bsc, iicbus_driver, iicbus_devclass, 0, 0);
750DRIVER_MODULE(bcm2835_bsc, simplebus, bcm_bsc_driver, bcm_bsc_devclass, 0, 0);
751