code:
/*	$OpenBSD: i2svar.h,v 1.8 2011/06/07 16:29:51 mpi Exp $	*/

/*-
 * Copyright (c) 2001,2003 Tsubai Masanari.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#if !defined(I2S_H_INCLUDE)
#define I2S_H_INCLUDE

#define I2S_DMALIST_MAX		32
#define I2S_DMASEG_MAX		NBPG

struct i2s_dma {
	bus_dmamap_t map;
	caddr_t addr;
	bus_dma_segment_t segs[I2S_DMALIST_MAX];
	int nsegs;
	size_t size;
	struct i2s_dma *next;
};

struct i2s_softc {
	struct device sc_dev;
	int sc_flags;
	int sc_node;
	u_int sc_baseaddr;

	void (*sc_ointr)(void *);	/* dma completion intr handler */
	void *sc_oarg;			/* arg for sc_ointr() */
	int sc_opages;			/* # of output pages */

	void (*sc_iintr)(void *);	/* dma completion intr handler */
	void *sc_iarg;			/* arg for sc_iintr() */

	u_int sc_record_source;		/* recording source mask */
	u_int sc_output_mask;		/* output source mask */

	void (*sc_setvolume)(struct i2s_softc *, int, int);
	void (*sc_setbass)(struct i2s_softc *, int);
	void (*sc_settreble)(struct i2s_softc *, int);
	void (*sc_setinput)(struct i2s_softc *, int);

	u_char *sc_reg;
	void *sc_i2c;

	u_int sc_rate;
	u_int sc_vol_l;
	u_int sc_vol_r;
	u_int sc_bass;
	u_int sc_treble;
	u_int sc_mute;

	u_int sc_spkr;			/* amp mute gpio offset */
	u_int sc_hp;			/* headphone mute gpio offset */
	u_int sc_hp_detect;		/* headphone detect gpio */
	u_int sc_hp_active;
	u_int sc_line;			/* line out mute gpio offset */
	u_int sc_line_detect;		/* line detect gpio */
	u_int sc_line_active;
	u_int sc_hw_reset;		/* hw reset gpio */

	bus_dma_tag_t sc_dmat;
	dbdma_regmap_t *sc_odma;
	dbdma_regmap_t *sc_idma;
	struct dbdma_command *sc_odmacmd, *sc_odmap;
	struct dbdma_command *sc_idmacmd, *sc_idmap;
	dbdma_t sc_odbdma, sc_idbdma;

	struct i2s_dma *sc_dmas;
};

void i2s_attach(struct device *, struct i2s_softc *, struct confargs *);
int i2s_intr(void *);
int i2s_open(void *, int);
void i2s_close(void *);
int i2s_query_encoding(void *, struct audio_encoding *);
int i2s_set_params(void *, int, int, struct audio_params *, struct audio_params *);
void i2s_get_default_params(struct audio_params *);
int i2s_round_blocksize(void *, int);
int i2s_halt_output(void *);
int i2s_halt_input(void *);
int i2s_set_port(void *, mixer_ctrl_t *);
int i2s_get_port(void *, mixer_ctrl_t *);
int i2s_query_devinfo(void *, mixer_devinfo_t *);
size_t i2s_round_buffersize(void *, int, size_t);
paddr_t i2s_mappage(void *, void *, off_t, int);
int i2s_get_props(void *);
int i2s_trigger_output(void *, void *, void *, int, void (*)(void *),
    void *, struct audio_params *);
int i2s_trigger_input(void *, void *, void *, int, void (*)(void *),
    void *, struct audio_params *);
int i2s_set_rate(struct i2s_softc *, int);
void i2s_gpio_init(struct i2s_softc *, int, struct device *);
void *i2s_allocm(void *, int, size_t, int, int);
int deq_reset(struct i2s_softc *);

#endif


code:
/*	$OpenBSD: if_bm.c,v 1.34 2015/07/08 07:21:49 mpi Exp $	*/
/*	$NetBSD: if_bm.c,v 1.1 1999/01/01 01:27:52 tsubai Exp $	*/

/*-
 * Copyright (C) 1998, 1999 Tsubai Masanari.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "bpfilter.h"

#include <sys/param.h>
#include <sys/device.h>
#include <sys/ioctl.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/systm.h>
#include <sys/timeout.h>
#include <sys/kernel.h>

#include <net/if.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <net/if_media.h>

#if NBPFILTER > 0
#include <net/bpf.h>
#include <net/bpfdesc.h>
#endif

#include <uvm/uvm_extern.h>

#include <dev/mii/mii.h>
#include <dev/mii/miivar.h>
#include <dev/mii/mii_bitbang.h>

#include <dev/ofw/openfirm.h>

#include <machine/bus.h>
#include <machine/autoconf.h>

#include <macppc/dev/dbdma.h>
#include <macppc/dev/if_bmreg.h>

#define BMAC_TXBUFS	2
#define BMAC_RXBUFS	16
#define BMAC_BUFLEN	2048
#define	BMAC_BUFSZ	((BMAC_RXBUFS + BMAC_TXBUFS + 2) * BMAC_BUFLEN)

struct bmac_softc {
	struct device sc_dev;
	struct arpcom arpcom;	/* per-instance network data */
	struct timeout sc_tick_ch;
	vaddr_t sc_regs;
	bus_dma_tag_t sc_dmat;
	bus_dmamap_t sc_bufmap;
	bus_dma_segment_t sc_bufseg[1];
	dbdma_regmap_t *sc_txdma, *sc_rxdma;
	dbdma_command_t *sc_txcmd, *sc_rxcmd;
	dbdma_t sc_rxdbdma, sc_txdbdma;
	caddr_t sc_txbuf;
	paddr_t sc_txbuf_pa;
	caddr_t sc_rxbuf;
	paddr_t sc_rxbuf_pa;
	int sc_rxlast;
	int sc_flags;
	int sc_debug;
	int txcnt_outstanding;
	struct mii_data sc_mii;
};

#define BMAC_BMACPLUS	0x01

extern u_int *heathrow_FCR;

static __inline int bmac_read_reg(struct bmac_softc *, int);
static __inline void bmac_write_reg(struct bmac_softc *, int, int);
static __inline void bmac_set_bits(struct bmac_softc *, int, int);
static __inline void bmac_reset_bits(struct bmac_softc *, int, int);

static int bmac_match(struct device *, void *, void *);
static void bmac_attach(struct device *, struct device *, void *);
static void bmac_reset_chip(struct bmac_softc *);
static void bmac_init(struct bmac_softc *);
static void bmac_init_dma(struct bmac_softc *);
static int bmac_intr(void *);
static int bmac_rint(void *);
static void bmac_reset(struct bmac_softc *);
static void bmac_stop(struct bmac_softc *);
static void bmac_start(struct ifnet *);
static void bmac_transmit_packet(struct bmac_softc *, paddr_t, int);
static int bmac_put(struct bmac_softc *, caddr_t, struct mbuf *);
static struct mbuf *bmac_get(struct bmac_softc *, caddr_t, int);
static void bmac_watchdog(struct ifnet *);
static int bmac_ioctl(struct ifnet *, u_long, caddr_t);
static int bmac_mediachange(struct ifnet *);
static void bmac_mediastatus(struct ifnet *, struct ifmediareq *);
static void bmac_setladrf(struct bmac_softc *);

int bmac_mii_readreg(struct device *, int, int);
void bmac_mii_writereg(struct device *, int, int, int);
void bmac_mii_statchg(struct device *);
void bmac_mii_tick(void *);
u_int32_t bmac_mbo_read(struct device *);
void bmac_mbo_write(struct device *, u_int32_t);

struct cfattach bm_ca = {
	sizeof(struct bmac_softc), bmac_match, bmac_attach
};

struct mii_bitbang_ops bmac_mbo = {
	bmac_mbo_read, bmac_mbo_write,
	{ MIFDO, MIFDI, MIFDC, MIFDIR, 0 }
};

struct cfdriver bm_cd = {
	NULL, "bm", DV_IFNET
};

int
bmac_read_reg(struct bmac_softc *sc, int off)
{
	return in16rb(sc->sc_regs + off);
}

void
bmac_write_reg(struct bmac_softc *sc, int off, int val)
{
	out16rb(sc->sc_regs + off, val);
}

void
bmac_set_bits(struct bmac_softc *sc, int off, int val)
{
	val |= bmac_read_reg(sc, off);
	bmac_write_reg(sc, off, val);
}

void
bmac_reset_bits(struct bmac_softc *sc, int off, int val)
{
	bmac_write_reg(sc, off, bmac_read_reg(sc, off) & ~val);
}

int
bmac_match(struct device *parent, void *cf, void *aux)
{
	struct confargs *ca = aux;

	if (ca->ca_nreg < 24 || ca->ca_nintr < 12)
		return (0);

	if (strcmp(ca->ca_name, "bmac") == 0)		/* bmac */
		return (1);
	if (strcmp(ca->ca_name, "ethernet") == 0)	/* bmac+ */
		return (1);

	return (0);
}

void
bmac_attach(struct device *parent, struct device *self, void *aux)
{
	struct confargs *ca = aux;
	struct bmac_softc *sc = (void *)self;
	struct ifnet *ifp = &sc->arpcom.ac_if;
	struct mii_data *mii = &sc->sc_mii;
	u_char laddr[6];
	int nseg, error;

	timeout_set(&sc->sc_tick_ch, bmac_mii_tick, sc);

	sc->sc_flags =0;
	if (strcmp(ca->ca_name, "ethernet") == 0) {
		sc->sc_flags |= BMAC_BMACPLUS;
	}

	ca->ca_reg[0] += ca->ca_baseaddr;
	ca->ca_reg[2] += ca->ca_baseaddr;
	ca->ca_reg[4] += ca->ca_baseaddr;

	sc->sc_regs = (vaddr_t)mapiodev(ca->ca_reg[0], NBPG);

	bmac_write_reg(sc, INTDISABLE, NoEventsMask);

	if (OF_getprop(ca->ca_node, "local-mac-address", laddr, 6) == -1 &&
	    OF_getprop(ca->ca_node, "mac-address", laddr, 6) == -1) {
		printf(": cannot get mac-address\n");
		return;
	}
	bcopy(laddr, sc->arpcom.ac_enaddr, 6);

	sc->sc_dmat = ca->ca_dmat;
	sc->sc_txdma = mapiodev(ca->ca_reg[2], 0x100);
	sc->sc_rxdma = mapiodev(ca->ca_reg[4], 0x100);
	sc->sc_txdbdma = dbdma_alloc(sc->sc_dmat, BMAC_TXBUFS);
	sc->sc_txcmd = sc->sc_txdbdma->d_addr;
	sc->sc_rxdbdma = dbdma_alloc(sc->sc_dmat, BMAC_RXBUFS + 1);
	sc->sc_rxcmd = sc->sc_rxdbdma->d_addr;

	error = bus_dmamem_alloc(sc->sc_dmat, BMAC_BUFSZ,
	    PAGE_SIZE, 0, sc->sc_bufseg, 1, &nseg, BUS_DMA_NOWAIT);
	if (error) {
		printf(": cannot allocate buffers (%d)\n", error);
		return;
	}

	error = bus_dmamem_map(sc->sc_dmat, sc->sc_bufseg, nseg,
	    BMAC_BUFSZ, &sc->sc_txbuf, BUS_DMA_NOWAIT);
	if (error) {
		printf(": cannot map buffers (%d)\n", error);
		bus_dmamem_free(sc->sc_dmat, sc->sc_bufseg, 1);
		return;
	}

	error = bus_dmamap_create(sc->sc_dmat, BMAC_BUFSZ, 1, BMAC_BUFSZ, 0,
	    BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &sc->sc_bufmap);
	if (error) {
		printf(": cannot create buffer dmamap (%d)\n", error);
		bus_dmamem_unmap(sc->sc_dmat, sc->sc_txbuf, BMAC_BUFSZ);
		bus_dmamem_free(sc->sc_dmat, sc->sc_bufseg, 1);
		return;
	}

	error = bus_dmamap_load(sc->sc_dmat, sc->sc_bufmap, sc->sc_txbuf,
	    BMAC_BUFSZ, NULL, BUS_DMA_NOWAIT);
	if (error) {
		printf(": cannot load buffers dmamap (%d)\n", error);
		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufmap);
		bus_dmamem_unmap(sc->sc_dmat, sc->sc_txbuf, BMAC_BUFSZ);
		bus_dmamem_free(sc->sc_dmat, sc->sc_bufseg, nseg);
		return;
	}

	sc->sc_txbuf_pa = sc->sc_bufmap->dm_segs->ds_addr;
	sc->sc_rxbuf = sc->sc_txbuf + BMAC_BUFLEN * BMAC_TXBUFS;
	sc->sc_rxbuf_pa = sc->sc_txbuf_pa + BMAC_BUFLEN * BMAC_TXBUFS;

	printf(" irq %d,%d: address %s\n", ca->ca_intr[0], ca->ca_intr[2],
		ether_sprintf(laddr));

	mac_intr_establish(parent, ca->ca_intr[0], IST_LEVEL, IPL_NET,
	    bmac_intr, sc, sc->sc_dev.dv_xname);
	mac_intr_establish(parent, ca->ca_intr[2], IST_LEVEL, IPL_NET,
	    bmac_rint, sc, sc->sc_dev.dv_xname);

	bcopy(sc->sc_dev.dv_xname, ifp->if_xname, IFNAMSIZ);
	ifp->if_softc = sc;
	ifp->if_ioctl = bmac_ioctl;
	ifp->if_start = bmac_start;
	ifp->if_flags =
		IFF_BROADCAST | IFF_SIMPLEX | IFF_NOTRAILERS | IFF_MULTICAST;
	ifp->if_watchdog = bmac_watchdog;
	IFQ_SET_READY(&ifp->if_snd);

	mii->mii_ifp = ifp;
	mii->mii_readreg = bmac_mii_readreg;
	mii->mii_writereg = bmac_mii_writereg;
	mii->mii_statchg = bmac_mii_statchg;

	ifmedia_init(&mii->mii_media, 0, bmac_mediachange, bmac_mediastatus);
	mii_attach(&sc->sc_dev, mii, 0xffffffff, MII_PHY_ANY,
	    MII_OFFSET_ANY, 0);

	/* Choose a default media. */
	if (LIST_FIRST(&mii->mii_phys) == NULL) {
		ifmedia_add(&mii->mii_media, IFM_ETHER|IFM_10_T, 0, NULL);
		ifmedia_set(&mii->mii_media, IFM_ETHER|IFM_10_T);
	} else
		ifmedia_set(&mii->mii_media, IFM_ETHER|IFM_AUTO);

	bmac_reset_chip(sc);

	if_attach(ifp);
	ether_ifattach(ifp);
}

/*
 * Reset and enable bmac by heathrow FCR.
 */
void
bmac_reset_chip(struct bmac_softc *sc)
{
	u_int v;

	dbdma_reset(sc->sc_txdma);
	dbdma_reset(sc->sc_rxdma);

	v = in32rb(heathrow_FCR);

	v |= EnetEnable;
	out32rb(heathrow_FCR, v);
	delay(50000);

	/* assert reset */
	v |= ResetEnetCell;
	out32rb(heathrow_FCR, v);
	delay(50000);

	/* deassert reset */
	v &= ~ResetEnetCell;
	out32rb(heathrow_FCR, v);
	delay(50000);

	/* enable */
	v |= EnetEnable;
	out32rb(heathrow_FCR, v);
	delay(50000);

	/* make certain they stay set? */
	out32rb(heathrow_FCR, v);
	v = in32rb(heathrow_FCR);
}

void
bmac_init(struct bmac_softc *sc)
{
	struct ifnet *ifp = &sc->arpcom.ac_if;
	struct ether_header *eh;
	caddr_t data;
	int tb;
	int i, bmcr;
	u_short *p;

	bmac_reset_chip(sc);

	/* XXX */
	bmcr = bmac_mii_readreg((struct device *)sc, 0, MII_BMCR);
	bmcr &= ~BMCR_ISO;
	bmac_mii_writereg((struct device *)sc, 0, MII_BMCR, bmcr);

	bmac_write_reg(sc, RXRST, RxResetValue);
	bmac_write_reg(sc, TXRST, TxResetBit);

	/* Wait for reset completion. */
	for (i = 1000; i > 0; i -= 10) {
		if ((bmac_read_reg(sc, TXRST) & TxResetBit) == 0)
			break;
		delay(10);
	}
	if (i <= 0)
		printf("%s: reset timeout\n", ifp->if_xname);

	if (! (sc->sc_flags & BMAC_BMACPLUS))
		bmac_set_bits(sc, XCVRIF, ClkBit|SerialMode|COLActiveLow);

	tb = ppc_mftbl();
	bmac_write_reg(sc, RSEED, tb);
	bmac_set_bits(sc, XIFC, TxOutputEnable);
	bmac_read_reg(sc, PAREG);

	/* Reset various counters. */
	bmac_write_reg(sc, NCCNT, 0);
	bmac_write_reg(sc, NTCNT, 0);
	bmac_write_reg(sc, EXCNT, 0);
	bmac_write_reg(sc, LTCNT, 0);
	bmac_write_reg(sc, FRCNT, 0);
	bmac_write_reg(sc, LECNT, 0);
	bmac_write_reg(sc, AECNT, 0);
	bmac_write_reg(sc, FECNT, 0);
	bmac_write_reg(sc, RXCV, 0);

	/* Set tx fifo information. */
	bmac_write_reg(sc, TXTH, 4);	/* 4 octets before tx starts */

	bmac_write_reg(sc, TXFIFOCSR, 0);
	bmac_write_reg(sc, TXFIFOCSR, TxFIFOEnable);

	/* Set rx fifo information. */
	bmac_write_reg(sc, RXFIFOCSR, 0);
	bmac_write_reg(sc, RXFIFOCSR, RxFIFOEnable);

	/* Clear status register. */
	bmac_read_reg(sc, STATUS);

	bmac_write_reg(sc, HASH3, 0);
	bmac_write_reg(sc, HASH2, 0);
	bmac_write_reg(sc, HASH1, 0);
	bmac_write_reg(sc, HASH0, 0);

	/* Set MAC address. */
	p = (u_short *)sc->arpcom.ac_enaddr;
	bmac_write_reg(sc, MADD0, *p++);
	bmac_write_reg(sc, MADD1, *p++);
	bmac_write_reg(sc, MADD2, *p);

	bmac_write_reg(sc, RXCFG,
		RxCRCEnable | RxHashFilterEnable | RxRejectOwnPackets);

	if (ifp->if_flags & IFF_PROMISC)
		bmac_set_bits(sc, RXCFG, RxPromiscEnable);

	bmac_init_dma(sc);

	/* Configure Media. */
	mii_mediachg(&sc->sc_mii);

	/* Enable TX/RX */
	bmac_set_bits(sc, RXCFG, RxMACEnable);
	bmac_set_bits(sc, TXCFG, TxMACEnable);

	bmac_write_reg(sc, INTDISABLE, NormalIntEvents);

	ifp->if_flags |= IFF_RUNNING;
	ifp->if_flags &= ~IFF_OACTIVE;
	ifp->if_timer = 0;

	data = sc->sc_txbuf;
	eh = (struct ether_header *)data;

	bzero(data, sizeof(*eh) + ETHERMIN);
	bcopy(sc->arpcom.ac_enaddr, eh->ether_dhost, ETHER_ADDR_LEN);
	bcopy(sc->arpcom.ac_enaddr, eh->ether_shost, ETHER_ADDR_LEN);
	bmac_transmit_packet(sc, sc->sc_txbuf_pa, sizeof(*eh) + ETHERMIN);

	bmac_start(ifp);

	timeout_add_sec(&sc->sc_tick_ch, 1);
}

void
bmac_init_dma(struct bmac_softc *sc)
{
	dbdma_command_t *cmd = sc->sc_rxcmd;
	int i;

	dbdma_reset(sc->sc_txdma);
	dbdma_reset(sc->sc_rxdma);

	bzero(sc->sc_txcmd, BMAC_TXBUFS * sizeof(dbdma_command_t));
	bzero(sc->sc_rxcmd, (BMAC_RXBUFS + 1) * sizeof(dbdma_command_t));

	for (i = 0; i < BMAC_RXBUFS; i++) {
		DBDMA_BUILD(cmd, DBDMA_CMD_IN_LAST, 0, BMAC_BUFLEN,
			sc->sc_rxbuf_pa + BMAC_BUFLEN * i,
			DBDMA_INT_ALWAYS, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
		cmd++;
	}
	DBDMA_BUILD(cmd, DBDMA_CMD_NOP, 0, 0, 0,
		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_ALWAYS);
	dbdma_st32(&cmd->d_cmddep, sc->sc_rxdbdma->d_paddr);

	sc->sc_rxlast = 0;

	dbdma_start(sc->sc_rxdma, sc->sc_rxdbdma);
}

int
bmac_intr(void *v)
{
	struct bmac_softc *sc = v;
	struct ifnet *ifp = &sc->arpcom.ac_if;
	int stat;

#ifdef BMAC_DEBUG
	printf("bmac_intr called\n");
#endif
	stat = bmac_read_reg(sc, STATUS);
	if (stat == 0)
		return (0);

#ifdef BMAC_DEBUG
	printf("bmac_intr status = 0x%x\n", stat);
#endif

	if (stat & IntFrameSent) {
		ifp->if_flags &= ~IFF_OACTIVE;
		ifp->if_timer = 0;
		ifp->if_opackets++;
		bmac_start(ifp);
	}

	/* XXX should do more! */

	return (1);
}

int
bmac_rint(void *v)
{
	struct bmac_softc *sc = v;
	struct ifnet *ifp = &sc->arpcom.ac_if;
	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
	struct mbuf *m;
	dbdma_command_t *cmd;
	int status, resid, count, datalen;
	int i, n;
	void *data;
#ifdef BMAC_DEBUG
	printf("bmac_rint() called\n");
#endif

	i = sc->sc_rxlast;
	for (n = 0; n < BMAC_RXBUFS; n++, i++) {
		if (i == BMAC_RXBUFS)
			i = 0;
		cmd = &sc->sc_rxcmd[i];
		status = dbdma_ld16(&cmd->d_status);
		resid = dbdma_ld16(&cmd->d_resid);

#ifdef BMAC_DEBUG
		if (status != 0 && status != 0x8440 && status != 0x9440)
			printf("bmac_rint status = 0x%x\n", status);
#endif

		if ((status & DBDMA_CNTRL_ACTIVE) == 0)	/* 0x9440 | 0x8440 */
			continue;
		count = dbdma_ld16(&cmd->d_count);
		datalen = count - resid;		/* 2 == framelen */
		if (datalen < sizeof(struct ether_header)) {
			printf("%s: short packet len = %d\n",
				ifp->if_xname, datalen);
			goto next;
		}
		DBDMA_BUILD_CMD(cmd, DBDMA_CMD_STOP, 0, 0, 0, 0);
		data = sc->sc_rxbuf + BMAC_BUFLEN * i;

		/* XXX Sometimes bmac reads one extra byte. */
		if (datalen == ETHER_MAX_LEN + 1)
			datalen--;

		/* Trim the CRC. */
		datalen -= ETHER_CRC_LEN;

		m = bmac_get(sc, data, datalen);
		if (m == NULL) {
			ifp->if_ierrors++;
			goto next;
		}

		ml_enqueue(&ml, m);

next:
		DBDMA_BUILD_CMD(cmd, DBDMA_CMD_IN_LAST, 0, DBDMA_INT_ALWAYS,
			DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

		cmd->d_status = 0;
		cmd->d_resid = 0;
		sc->sc_rxlast = i + 1;
	}
	dbdma_continue(sc->sc_rxdma);

	if_input(ifp, &ml);
	return (1);
}

void
bmac_reset(struct bmac_softc *sc)
{
	int s;

	s = splnet();
	bmac_init(sc);
	splx(s);
}

void
bmac_stop(struct bmac_softc *sc)
{
	struct ifnet *ifp = &sc->arpcom.ac_if;
	int s;

	s = splnet();

	/* timeout */
	timeout_del(&sc->sc_tick_ch);
	mii_down(&sc->sc_mii);

	/* Disable TX/RX. */
	bmac_reset_bits(sc, TXCFG, TxMACEnable);
	bmac_reset_bits(sc, RXCFG, RxMACEnable);

	/* Disable all interrupts. */
	bmac_write_reg(sc, INTDISABLE, NoEventsMask);

	dbdma_stop(sc->sc_txdma);
	dbdma_stop(sc->sc_rxdma);

	ifp->if_flags &= ~(IFF_UP | IFF_RUNNING);
	ifp->if_timer = 0;

	splx(s);
}

void
bmac_start(struct ifnet *ifp)
{
	struct bmac_softc *sc = ifp->if_softc;
	struct mbuf *m;
	int tlen;

	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
		return;

	while (1) {
		if (ifp->if_flags & IFF_OACTIVE)
			return;

		IFQ_DEQUEUE(&ifp->if_snd, m);
		if (m == NULL)
			break;
#if NBPFILTER > 0
		/*
		 * If BPF is listening on this interface, let it see the
		 * packet before we commit it to the wire.
		 */
		if (ifp->if_bpf)
			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
#endif

		ifp->if_flags |= IFF_OACTIVE;
		tlen = bmac_put(sc, sc->sc_txbuf, m);

		/* 5 seconds to watch for failing to transmit */
		ifp->if_timer = 5;
		ifp->if_opackets++;		/* # of pkts */

		bmac_transmit_packet(sc, sc->sc_txbuf_pa, tlen);
	}
}

void
bmac_transmit_packet(struct bmac_softc *sc, paddr_t pa, int len)
{
	dbdma_command_t *cmd = sc->sc_txcmd;

	DBDMA_BUILD(cmd, DBDMA_CMD_OUT_LAST, 0, len, pa,
		DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	cmd++;
	DBDMA_BUILD(cmd, DBDMA_CMD_STOP, 0, 0, 0,
		DBDMA_INT_ALWAYS, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

	dbdma_start(sc->sc_txdma, sc->sc_txdbdma);
}

int
bmac_put(struct bmac_softc *sc, caddr_t buff, struct mbuf *m)
{
	struct mbuf *n;
	int len, tlen = 0;

	for (; m; m = n) {
		len = m->m_len;
		if (len == 0) {
			n = m_free(m);
			continue;
		}
		bcopy(mtod(m, caddr_t), buff, len);
		buff += len;
		tlen += len;
		n = m_free(m);
	}
	if (tlen > NBPG)
		panic("%s: putpacket packet overflow", sc->sc_dev.dv_xname);

	return (tlen);
}

struct mbuf *
bmac_get(struct bmac_softc *sc, caddr_t pkt, int totlen)
{
	struct mbuf *m;
	struct mbuf *top, **mp;
	int len;

	MGETHDR(m, M_DONTWAIT, MT_DATA);
	if (m == NULL)
		return (0);
	m->m_pkthdr.len = totlen;
	len = MHLEN;
	top = 0;
	mp = ⊤

	while (totlen > 0) {
		if (top) {
			MGET(m, M_DONTWAIT, MT_DATA);
			if (m == NULL) {
				m_freem(top);
				return (0);
			}
			len = MLEN;
		}
		if (totlen >= MINCLSIZE) {
			MCLGET(m, M_DONTWAIT);
			if ((m->m_flags & M_EXT) == 0) {
				m_free(m);
				m_freem(top);
				return (0);
			}
			len = MCLBYTES;
		}
		m->m_len = len = min(totlen, len);
		bcopy(pkt, mtod(m, caddr_t), len);
		pkt += len;
		totlen -= len;
		*mp = m;
		mp = &m->m_next;
	}

	return (top);
}

void
bmac_watchdog(struct ifnet *ifp)
{
	struct bmac_softc *sc = ifp->if_softc;

	bmac_reset_bits(sc, RXCFG, RxMACEnable);
	bmac_reset_bits(sc, TXCFG, TxMACEnable);

	printf("%s: device timeout\n", ifp->if_xname);
	ifp->if_oerrors++;

	bmac_reset(sc);
}

int
bmac_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
	struct bmac_softc *sc = ifp->if_softc;
	struct ifaddr *ifa = (struct ifaddr *)data;
	struct ifreq *ifr = (struct ifreq *)data;
	int s, error = 0;

	s = splnet();

	switch (cmd) {
	case SIOCSIFADDR:
		ifp->if_flags |= IFF_UP;

		switch (ifa->ifa_addr->sa_family) {
		case AF_INET:
			bmac_init(sc);
			arp_ifinit(&sc->arpcom, ifa);
			break;
		default:
			bmac_init(sc);
			break;
		}
		break;

	case SIOCSIFFLAGS:
		if ((ifp->if_flags & IFF_UP) == 0 &&
		    (ifp->if_flags & IFF_RUNNING) != 0) {
			/*
			 * If interface is marked down and it is running, then
			 * stop it.
			 */
			bmac_stop(sc);
			ifp->if_flags &= ~IFF_RUNNING;
		} else if ((ifp->if_flags & IFF_UP) != 0 &&
		    (ifp->if_flags & IFF_RUNNING) == 0) {
			/*
			 * If interface is marked up and it is stopped, then
			 * start it.
			 */
			bmac_init(sc);
		} else {
			/*
			 * Reset the interface to pick up changes in any other
			 * flags that affect hardware registers.
			 */
			/*bmac_stop(sc);*/
			bmac_init(sc);
		}
#ifdef BMAC_DEBUG
		if (ifp->if_flags & IFF_DEBUG)
			sc->sc_debug = 1;
		else
			sc->sc_debug = 0;
#endif
		break;

	case SIOCGIFMEDIA:
	case SIOCSIFMEDIA:
		error = ifmedia_ioctl(ifp, ifr, &sc->sc_mii.mii_media, cmd);
		break;

	default:
		error = ether_ioctl(ifp, &sc->arpcom, cmd, data);
	}

	if (error == ENETRESET) {
		if (ifp->if_flags & IFF_RUNNING) {
			bmac_init(sc);
			bmac_setladrf(sc);
		}
		error = 0;
	}

	splx(s);
	return (error);
}

int
bmac_mediachange(struct ifnet *ifp)
{
	struct bmac_softc *sc = ifp->if_softc;

	return mii_mediachg(&sc->sc_mii);
}

void
bmac_mediastatus(struct ifnet *ifp, struct ifmediareq *ifmr)
{
	struct bmac_softc *sc = ifp->if_softc;

	mii_pollstat(&sc->sc_mii);

	ifmr->ifm_status = sc->sc_mii.mii_media_status;
	ifmr->ifm_active = sc->sc_mii.mii_media_active;
}

/*
 * Set up the logical address filter.
 */
void
bmac_setladrf(struct bmac_softc *sc)
{
	struct arpcom *ac = &sc->arpcom;
	struct ifnet *ifp = &sc->arpcom.ac_if;
	struct ether_multi *enm;
	struct ether_multistep step;
	u_int32_t crc;
	u_int16_t hash[4];
	int x;

	/*
	 * Set up multicast address filter by passing all multicast addresses
	 * through a crc generator, and then using the high order 6 bits as an
	 * index into the 64 bit logical address filter.  The high order bit
	 * selects the word, while the rest of the bits select the bit within
	 * the word.
	 */

	if (ifp->if_flags & IFF_PROMISC) {
		bmac_set_bits(sc, RXCFG, RxPromiscEnable);
		return;
	}

	if (ac->ac_multirangecnt > 0)
		ifp->if_flags |= IFF_ALLMULTI;

	if (ifp->if_flags & IFF_ALLMULTI) {
		hash[3] = hash[2] = hash[1] = hash[0] = 0xffff;
		goto chipit;
	}

	hash[3] = hash[2] = hash[1] = hash[0] = 0;
	ETHER_FIRST_MULTI(step, ac, enm);
	while (enm != NULL) {
		crc = ether_crc32_le(enm->enm_addrlo, ETHER_ADDR_LEN);

		/* Just want the 6 most significant bits. */
		crc >>= 26;

		/* Set the corresponding bit in the filter. */
		hash[crc >> 4] |= 1 << (crc & 0xf);

		ETHER_NEXT_MULTI(step, enm);
	}

	ifp->if_flags &= ~IFF_ALLMULTI;

chipit:
	bmac_write_reg(sc, HASH0, hash[0]);
	bmac_write_reg(sc, HASH1, hash[1]);
	bmac_write_reg(sc, HASH2, hash[2]);
	bmac_write_reg(sc, HASH3, hash[3]);
	x = bmac_read_reg(sc, RXCFG);
	x &= ~RxPromiscEnable;
	x |= RxHashFilterEnable;
	bmac_write_reg(sc, RXCFG, x);
}

int
bmac_mii_readreg(struct device *dev, int phy, int reg)
{
	return mii_bitbang_readreg(dev, &bmac_mbo, phy, reg);
}

void
bmac_mii_writereg(struct device *dev, int phy, int reg, int val)
{
	mii_bitbang_writereg(dev, &bmac_mbo, phy, reg, val);
}

u_int32_t
bmac_mbo_read(struct device *dev)
{
	struct bmac_softc *sc = (void *)dev;

	return bmac_read_reg(sc, MIFCSR);
}

void
bmac_mbo_write(struct device *dev, u_int32_t val)
{
	struct bmac_softc *sc = (void *)dev;

	bmac_write_reg(sc, MIFCSR, val);
}

void
bmac_mii_statchg(struct device *dev)
{
	struct bmac_softc *sc = (void *)dev;
	int x;

	/* Update duplex mode in TX configuration */
	x = bmac_read_reg(sc, TXCFG);
	if ((IFM_OPTIONS(sc->sc_mii.mii_media_active) & IFM_FDX) != 0)
		x |= TxFullDuplex;
	else
		x &= ~TxFullDuplex;
	bmac_write_reg(sc, TXCFG, x);

#ifdef BMAC_DEBUG
	printf("bmac_mii_statchg 0x%x\n",
		IFM_OPTIONS(sc->sc_mii.mii_media_active));
#endif
}

void
bmac_mii_tick(void *v)
{
	struct bmac_softc *sc = v;
	int s;

	s = splnet();
	mii_tick(&sc->sc_mii);
	splx(s);

	timeout_add_sec(&sc->sc_tick_ch, 1);
}

license: unknown


code:
/*	$OpenBSD: if_bmreg.h,v 1.3 2005/10/09 04:24:50 brad Exp $	*/
/*	$NetBSD: if_bmreg.h,v 1.2 2000/01/25 14:38:50 tsubai Exp $	*/

/*
 * Copyright 1991-1998 by Open Software Foundation, Inc.
 *              All Rights Reserved
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appears in all copies and
 * that both the copyright notice and this permission notice appear in
 * supporting documentation.
 *
 * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
 * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* -------------------------------------------------------------------- */
/* Heathrow (F)eature (C)ontrol (R)egister Addresses			*/
/* -------------------------------------------------------------------- */
#define EnetEnable	0x60000000	/* enable Enet Xcvr/Controller */
#define ResetEnetCell	0x80000000	/* reset Enet cell */

/* -------------------------------------------------------------------- */
/*	BigMac Register Numbers & Bit Assignments			*/
/* -------------------------------------------------------------------- */
#define XIFC		0x0000
#define  TxOutputEnable		0x0001
#define  MIILoopbackBits	0x0006
#define  MIIBufferEnable	0x0008
#define  SQETestEnable		0x0010
#define LinkStatus	0x0100
#define TXFIFOCSR	0x0100
#define  TxFIFOEnable		0x0001
#define  TxFIFO128		0x0000
#define TXTH		0x0110
#define RXFIFOCSR	0x0120
#define  RxFIFOEnable		TxFIFOEnable
#define  RxFIFO128		TxFIFO128
#define MEMADD		0x0130
#define MEMDATAHI	0x0140
#define MEMDATALO	0x0150
#define XCVRIF		0x0160
#define  COLActiveLow		0x0002
#define  SerialMode		0x0004
#define  ClkBit			0x0008
#define CHIPID		0x0170
#define MIFCSR		0x0180
#define  MIFDC			0x0001	/* MII clock */
#define  MIFDO			0x0002	/* MII data out */
#define  MIFDIR			0x0004	/* MII direction (1: write) */
#define  MIFDI			0x0008	/* MII data in */
#define SROMCSR		0x0190
#define TXPNTR		0x01A0
#define RXPNTR		0x01B0
#define STATUS		0x0200
#define INTDISABLE	0x0210
#define  IntFrameReceived	0x0001
#define  IntRxFrameCntExp	0x0002
#define  IntRxAlignCntExp	0x0004
#define  IntRxCRCCntExp		0x0008
#define  IntRxLenCntExp		0x0010
#define  IntRxOverFlow		0x0020
#define  IntRxCodeViolation	0x0040
#define  IntSQETestError	0x0080
#define  IntFrameSent		0x0100
#define  IntTxUnderrun		0x0200
#define  IntTxMaxSizeError	0x0400
#define  IntTxNormalCollExp	0x0800
#define  IntTxExcessCollExp	0x1000
#define  IntTxLateCollExp	0x2000
#define  IntTxNetworkCollExp	0x4000
#define  IntTxDeferTimerExp	0x8000
#define  NormalIntEvents	~(IntFrameSent)
#define  NoEventsMask		0xFFFF

#define TxNeverGiveUp	0x0400
#define TXRST		0x0420
#define  TxResetBit		0x0001
#define TXCFG		0x0430
#define  TxMACEnable		0x0001
#define  TxThreshold		0x0004
#define  TxFullDuplex		0x0200
#define IPG1		0x0440
#define IPG2		0x0450
#define ALIMIT		0x0460
#define SLOT		0x0470
#define PALEN		0x0480
#define PAPAT		0x0490
#define TXSFD		0x04A0
#define JAM		0x04B0
#define TXMAX		0x04C0
#define TXMIN		0x04D0
#define PAREG		0x04E0
#define DCNT		0x04F0
#define NCCNT		0x0500
#define NTCNT		0x0510
#define EXCNT		0x0520
#define LTCNT		0x0530
#define RSEED		0x0540
#define TXSM		0x0550
#define RXRST		0x0620
#define  RxResetValue		0x0000
#define RXCFG		0x0630
#define  RxMACEnable		0x0001
#define  ReservedValue		0x0004
#define  RxPromiscEnable	0x0040
#define  RxCRCEnable		0x0100
#define  RxRejectOwnPackets	0x0200
#define  RxHashFilterEnable	0x0800
#define  RxAddrFilterEnable	0x1000
#define RXMAX		0x0640
#define RXMIN		0x0650
#define MADD2		0x0660
#define MADD1		0x0670
#define MADD0		0x0680
#define FRCNT		0x0690
#define LECNT		0x06A0
#define AECNT		0x06B0
#define FECNT		0x06C0
#define RXSM		0x06D0
#define RXCV		0x06E0
#define HASH3		0x0700
#define HASH2		0x0710
#define HASH1		0x0720
#define HASH0		0x0730
#define AFR2		0x0740
#define AFR1		0x0750
#define AFR0		0x0760
#define AFCR		0x0770
#define  EnableAllCompares	0x0fff

/* -------------------------------------------------------------------- */
/*	Misc. Bit definitions for BMac Status word			*/
/* -------------------------------------------------------------------- */
#define RxAbortBit	0x8000	/* status bit in BMac status for rx packets */
#define RxLengthMask	0x3FFF	/* bits that determine length of rx packets */


code:
/*	$OpenBSD: if_mc.c,v 1.22 2015/07/08 07:21:49 mpi Exp $	*/
/*	$NetBSD: if_mc.c,v 1.9.16.1 2006/06/21 14:53:13 yamt Exp $	*/

/*-
 * Copyright (c) 1997 David Huang <khym@bga.com>
 * All rights reserved.
 *
 * Portions of this code are based on code by Denton Gentry <denny1@home.com>
 * and Yanagisawa Takeshi <yanagisw@aa.ap.titech.ac.jp>.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
 * AMD AM79C940 (MACE) driver with DBDMA bus attachment and DMA routines
 * for onboard ethernet found on most old world macs.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/buf.h>
#include <sys/protosw.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#include <sys/device.h>
#include <sys/timeout.h>

#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_media.h>

#include <netinet/in.h>
#include <netinet/if_ether.h>

#include "bpfilter.h"
#if NBPFILTER > 0
#include <net/bpf.h>
#include <net/bpfdesc.h>
#endif

#include <dev/ofw/openfirm.h>
#include <machine/pio.h>
#include <machine/bus.h>
#include <machine/autoconf.h>

#include <macppc/dev/dbdma.h>

#define MC_REGSPACING   	16
#define MC_REGSIZE      	MACE_NREGS * MC_REGSPACING
#define MACE_REG(x)     	((x)*MC_REGSPACING)
#define MACE_BUFLEN		2048
#define MACE_TXBUFS		2
#define MACE_RXBUFS		8

#define MC_RXDMABUFS		4

#define MACE_BUFSZ       	((MACE_RXBUFS + MACE_TXBUFS + 2) * MACE_BUFLEN)

#define NIC_GET(sc, reg)	(in8rb(sc->sc_reg + MACE_REG(reg)))

#define NIC_PUT(sc, reg, val)   (out8rb(sc->sc_reg + MACE_REG(reg), (val)))

/*
 * AMD MACE (Am79C940) register definitions
 */
#define	MACE_RCVFIFO		0   /* Receive FIFO [15-00] (read only) */
#define	MACE_XMTFIFO		1   /* Transmit FIFO [15-00] (write only) */
#define	MACE_XMTFC		2   /* Transmit Frame Control (read/write) */
#define	MACE_XMTFS		3   /* Transmit Frame Status (read only) */
#define	MACE_XMTRC		4   /* Transmit Retry Count (read only) */
#define	MACE_RCVFC		5   /* Receive Frame Control (read/write) */
#define	MACE_RCVFS		6   /* Receive Frame Status (4 bytes) (read only) */
#define	MACE_FIFOFC		7   /* FIFO Frame Count (read only) */
#define	MACE_IR			8   /* Interrupt Register (read only) */
#define	MACE_IMR		9   /* Interrupt Mask Register (read/write) */
#define	MACE_PR			10  /* Poll Register (read only) */
#define	MACE_BIUCC		11  /* BIU Configuration Control (read/write) */
#define	MACE_FIFOCC		12  /* FIFO Configuration Control (read/write) */
#define	MACE_MACCC		13  /* MAC Configuration Control (read/write) */
#define	MACE_PLSCC		14  /* PLS Configuration Control (read/write) */
#define	MACE_PHYCC		15  /* PHY Confiuration Control (read/write) */
#define	MACE_CHIPIDL		16  /* Chip ID Register [07-00] (read only) */
#define	MACE_CHIPIDH		17  /* Chip ID Register [15-08] (read only) */
#define	MACE_IAC		18  /* Internal Address Configuration (read/write) */
/*	RESERVED		19     Reserved (read/write as 0) */
#define	MACE_LADRF		20  /* Logical Address Filter (8 bytes) (read/write) */
#define	MACE_PADR		21  /* Physical Address (6 bytes) (read/write) */
/*	RESERVED		22     Reserved (read/write as 0) */
/*	RESERVED		23     Reserved (read/write as 0) */
#define	MACE_MPC		24  /* Missed Packet Count (read only) */
/*	RESERVED		25     Reserved (read/write as 0) */
#define	MACE_RNTPC		26  /* Runt Packet Count (read only) */
#define	MACE_RCVCC		27  /* Receive Collision Count (read only) */
/*	RESERVED		28     Reserved (read/write as 0) */
#define	MACE_UTR		29  /* User Test Register (read/write) */
#define	MACE_RTR1		30  /* Reserved Test Register 1 (read/write as 0) */
#define	MACE_RTR2		31  /* Reserved Test Register 2 (read/write as 0) */

#define	MACE_NREGS		32

/* 2: Transmit Frame Control (XMTFC) */
#define	DRTRY			0x80	/* Disable Retry */
#define	DXMTFCS			0x08	/* Disable Transmit FCS */
#define	APADXMT			0x01	/* Auto Pad Transmit */

/* 3: Transmit Frame Status (XMTFS) */
#define	XMTSV			0x80	/* Transmit Status Valid */
#define	UFLO			0x40	/* Underflow */
#define	LCOL			0x20	/* Late Collision */
#define	MORE			0x10	/* More than one retry needed */
#define	ONE			0x08	/* Exactly one retry needed */
#define	DEFER			0x04	/* Transmission deferred */
#define	LCAR			0x02	/* Loss of Carrier */
#define	RTRY			0x01	/* Retry Error */

/* 4: Transmit Retry Count (XMTRC) */
#define	EXDEF			0x80	/* Excessive Defer */
#define	XMTRC			0x0f	/* Transmit Retry Count */

/* 5: Receive Frame Control (RCVFC) */
#define	LLRCV			0x08	/* Low Latency Receive */
#define	MR			0x04	/* Match/Reject */
#define	ASTRPRCV		0x01	/* Auto Strip Receive */

/* 6: Receive Frame Status (RCVFS) */
/* 4 byte register; read 4 times to get all of the bytes */
/* Read 1: RFS0 - Receive Message Byte Count [7-0] (RCVCNT) */

/* Read 2: RFS1 - Receive Status (RCVSTS) */
#define	OFLO			0x80	/* Overflow flag */
#define	CLSN			0x40	/* Collision flag */
#define	FRAM			0x20	/* Framing Error flag */
#define	FCS			0x10	/* FCS Error flag */
#define	RCVCNT			0x0f	/* Receive Message Byte Count [11-8] */

/* Read 3: RFS2 - Runt Packet Count (RNTPC) [7-0] */

/* Read 4: RFS3 - Receive Collision Count (RCVCC) [7-0] */

/* 7: FIFO Frame Count (FIFOFC) */
#define	RCVFC			0xf0	/* Receive Frame Count */
#define	XMTFC			0x0f	/* Transmit Frame Count */

/* 8: Interrupt Register (IR) */
#define	JAB			0x80	/* Jabber Error */
#define	BABL			0x40	/* Babble Error */
#define	CERR			0x20	/* Collision Error */
#define	RCVCCO			0x10	/* Receive Collision Count Overflow */
#define	RNTPCO			0x08	/* Runt Packet Count Overflow */
#define	MPCO			0x04	/* Missed Packet Count Overflow */
#define	RCVINT			0x02	/* Receive Interrupt */
#define	XMTINT			0x01	/* Transmit Interrupt */

/* 9: Interrut Mask Register (IMR) */
#define	JABM			0x80	/* Jabber Error Mask */
#define	BABLM			0x40	/* Babble Error Mask */
#define	CERRM			0x20	/* Collision Error Mask */
#define	RCVCCOM			0x10	/* Receive Collision Count Overflow Mask */
#define	RNTPCOM			0x08	/* Runt Packet Count Overflow Mask */
#define	MPCOM			0x04	/* Missed Packet Count Overflow Mask */
#define	RCVINTM			0x02	/* Receive Interrupt Mask */
#define	XMTINTM			0x01	/* Transmit Interrupt Mask */

/* 10: Poll Register (PR) */
#define	XMTSV			0x80	/* Transmit Status Valid */
#define	TDTREQ			0x40	/* Transmit Data Transfer Request */
#define	RDTREQ			0x20	/* Receive Data Transfer Request */

/* 11: BIU Configuration Control (BIUCC) */
#define	BSWP			0x40	/* Byte Swap */
#define	XMTSP			0x30	/* Transmit Start Point */
#define	XMTSP_4			0x00	/* 4 bytes */
#define	XMTSP_16		0x10	/* 16 bytes */
#define	XMTSP_64		0x20	/* 64 bytes */
#define	XMTSP_112		0x30	/* 112 bytes */
#define	SWRST			0x01	/* Software Reset */

/* 12: FIFO Configuration Control (FIFOCC) */
#define	XMTFW			0xc0	/* Transmit FIFO Watermark */
#define	XMTFW_8			0x00	/* 8 write cycles */
#define	XMTFW_16		0x40	/* 16 write cycles */
#define	XMTFW_32		0x80	/* 32 write cycles */
#define	RCVFW			0x30	/* Receive FIFO Watermark */
#define	RCVFW_16		0x00	/* 16 bytes */
#define	RCVFW_32		0x10	/* 32 bytes */
#define	RCVFW_64		0x20	/* 64 bytes */
#define	XMTFWU			0x08	/* Transmit FIFO Watermark Update */
#define	RCVFWU			0x04	/* Receive FIFO Watermark Update */
#define	XMTBRST			0x02	/* Transmit Burst */
#define	RCVBRST			0x01	/* Receive Burst */

/* 13: MAC Configuration (MACCC) */
#define	PROM			0x80	/* Promiscuous */
#define	DXMT2PD			0x40	/* Disable Transmit Two Part Deferral */
#define	EMBA			0x20	/* Enable Modified Back-off Algorithm */
#define	DRCVPA			0x08	/* Disable Receive Physical Address */
#define	DRCVBC			0x04	/* Disable Receive Broadcast */
#define	ENXMT			0x02	/* Enable Transmit */
#define	ENRCV			0x01	/* Enable Receive */

/* 14: PLS Configuration Control (PLSCC) */
#define	XMTSEL			0x08	/* Transmit Mode Select */
#define	PORTSEL			0x06	/* Port Select */
#define	PORTSEL_AUI		0x00	/* Select AUI */
#define	PORTSEL_10BT		0x02	/* Select 10BASE-T */
#define	PORTSEL_DAI		0x04	/* Select DAI port */
#define	PORTSEL_GPSI		0x06	/* Select GPSI */
#define	ENPLSIO			0x01	/* Enable PLS I/O */

/* 15: PHY Configuration (PHYCC) */
#define	LNKFL			0x80	/* Link Fail */
#define	DLNKTST			0x40	/* Disable Link Test */
#define	REVPOL			0x20	/* Reversed Polarity */
#define	DAPC			0x10	/* Disable Auto Polarity Correction */
#define	LRT			0x08	/* Low Receive Threshold */
#define	ASEL			0x04	/* Auto Select */
#define	RWAKE			0x02	/* Remote Wake */
#define	AWAKE			0x01	/* Auto Wake */

/* 18: Internal Address Configuration (IAC) */
#define	ADDRCHG			0x80	/* Address Change */
#define	PHYADDR			0x04	/* Physical Address Reset */
#define	LOGADDR			0x02	/* Logical Address Reset */

/* 28: User Test Register (UTR) */
#define	RTRE			0x80	/* Reserved Test Register Enable */
#define	RTRD			0x40	/* Reserved Test Register Disable */
#define	RPA			0x20	/* Run Packet Accept */
#define	FCOLL			0x10	/* Force Collision */
#define	RCVFCSE			0x08	/* Receive FCS Enable */
#define	LOOP			0x06	/* Loopback Control */
#define	LOOP_NONE		0x00	/* No Loopback */
#define	LOOP_EXT		0x02	/* External Loopback */
#define	LOOP_INT		0x04	/* Internal Loopback, excludes MENDEC */
#define	LOOP_INT_MENDEC		0x06	/* Internal Loopback, includes MENDEC */

struct mc_rxframe {
	u_int8_t		rx_rcvcnt;
	u_int8_t		rx_rcvsts;
	u_int8_t		rx_rntpc;
	u_int8_t		rx_rcvcc;
	u_char			*rx_frame;
};

struct mc_softc {
	struct device	   	sc_dev;		/* base device glue */
	struct arpcom	   	sc_arpcom;	/* Ethernet common part */
	struct timeout	  	sc_tick_ch;

	struct mc_rxframe       sc_rxframe;
	u_int8_t		sc_biucc;
	u_int8_t		sc_fifocc;
	u_int8_t		sc_plscc;
	u_int8_t		sc_enaddr[6];
	u_int8_t		sc_pad[2];
	int			sc_havecarrier; /* carrier status */

	char			*sc_reg;
	bus_dma_tag_t		sc_dmat;
	bus_dmamap_t		sc_bufmap;
	bus_dma_segment_t       sc_bufseg[1];

	dbdma_regmap_t		*sc_txdma;
	dbdma_regmap_t		*sc_rxdma;
	dbdma_command_t		*sc_txdmacmd;
	dbdma_command_t		*sc_rxdmacmd;
	dbdma_t			sc_txdbdma;
	dbdma_t			sc_rxdbdma;

	caddr_t			sc_txbuf;
	caddr_t			sc_rxbuf;
	paddr_t			sc_txbuf_pa;
	paddr_t			sc_rxbuf_pa;
	int			sc_tail;
	int			sc_rxset;
	int			sc_txset;
	int			sc_txseti;
};

int	mc_match(struct device *, void *, void *);
void	mc_attach(struct device *, struct device *, void *);

struct  cfattach mc_ca = {
	sizeof(struct mc_softc), mc_match, mc_attach
};

struct cfdriver mc_cd = {
	NULL, "mc", DV_IFNET
};

void	mc_init(struct mc_softc *sc);
void	mc_put(struct mc_softc *sc, u_int len);
int	mc_dmaintr(void *arg);
void	mc_reset_rxdma(struct mc_softc *sc);
void	mc_reset_txdma(struct mc_softc *sc);
int     mc_stop(struct mc_softc *sc);
int     mc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
void    mc_start(struct ifnet *ifp);
void    mc_reset(struct mc_softc *sc);
void    mc_tint(struct mc_softc *sc);
void	mc_rint(struct mc_softc *sc);
int	mc_intr(void *);
void	mc_watchdog(struct ifnet *ifp);

u_int   maceput(struct mc_softc *sc, struct mbuf *);
void    mace_read(struct mc_softc *, caddr_t, int);
struct mbuf *mace_get(struct mc_softc *, caddr_t, int);
static void mace_calcladrf(struct mc_softc *, u_int8_t *);
void	mc_putpacket(struct mc_softc *, u_int);

int
mc_match(struct device *parent, void *arg, void *aux)
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "mace") != 0)
		return 0;

	/* requires 6 regs */
	if (ca->ca_nreg / sizeof(int) != 6)
		return 0;

	/* requires 3 intrs */
	if (ca->ca_nintr / sizeof(int) != 3)
		return 0;

	return 1;
}

void
mc_attach(struct device *parent, struct device *self, void *aux)
{
	struct confargs *ca = aux;
	struct mc_softc *sc = (struct mc_softc *)self;
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	u_int8_t lladdr[ETHER_ADDR_LEN];
	int nseg, error;

	if (OF_getprop(ca->ca_node, "local-mac-address", lladdr,
	    ETHER_ADDR_LEN) != ETHER_ADDR_LEN) {
		printf(": failed to get MAC address.\n");
		return;
	}

	ca->ca_reg[0] += ca->ca_baseaddr;
	ca->ca_reg[2] += ca->ca_baseaddr;
	ca->ca_reg[4] += ca->ca_baseaddr;

	if ((sc->sc_reg = mapiodev(ca->ca_reg[0], ca->ca_reg[1])) == NULL) {
		printf(": cannot map registers\n");
		return;
	}

	sc->sc_dmat = ca->ca_dmat;
	sc->sc_tail = 0;

	if ((sc->sc_txdma = mapiodev(ca->ca_reg[2], ca->ca_reg[3])) == NULL) {
		printf(": cannot map TX DMA registers\n");
		goto notxdma;
	}
	if ((sc->sc_rxdma = mapiodev(ca->ca_reg[4], ca->ca_reg[5])) == NULL) {
		printf(": cannot map RX DMA registers\n");
		goto norxdma;
	}
	if ((sc->sc_txdbdma = dbdma_alloc(sc->sc_dmat, 2)) == NULL) {
		printf(": cannot alloc TX DMA descriptors\n");
		goto notxdbdma;
	}
	sc->sc_txdmacmd = sc->sc_txdbdma->d_addr;

	if ((sc->sc_rxdbdma = dbdma_alloc(sc->sc_dmat, 8 + 1)) == NULL) {
		printf(": cannot alloc RX DMA descriptors\n");
		goto norxdbdma;
	}
	sc->sc_rxdmacmd = sc->sc_rxdbdma->d_addr;

	if ((error = bus_dmamem_alloc(sc->sc_dmat, MACE_BUFSZ, PAGE_SIZE, 0,
	    sc->sc_bufseg, 1, &nseg, BUS_DMA_NOWAIT))) {
		printf(": cannot allocate DMA mem (%d)\n", error);
		goto nodmamem;
	}

	if ((error = bus_dmamem_map(sc->sc_dmat, sc->sc_bufseg, nseg,
	    MACE_BUFSZ, &sc->sc_txbuf, BUS_DMA_NOWAIT))) {
		printf(": cannot map DMA mem (%d)\n", error);
		goto nodmamap;
	}

	if ((error = bus_dmamap_create(sc->sc_dmat, MACE_BUFSZ, 1, MACE_BUFSZ,
	    0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &sc->sc_bufmap))) {
		printf(": cannot create DMA map (%d)\n", error);
		goto nodmacreate;
	}

	if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_bufmap, sc->sc_txbuf,
	    MACE_BUFSZ, NULL, BUS_DMA_NOWAIT))) {
		printf(": cannot load DMA map (%d)\n", error);
		goto nodmaload;
	}

	sc->sc_txbuf_pa = sc->sc_bufmap->dm_segs->ds_addr;
	sc->sc_rxbuf = sc->sc_txbuf + MACE_BUFLEN * MACE_TXBUFS;
	sc->sc_rxbuf_pa = sc->sc_txbuf_pa + MACE_BUFLEN * MACE_TXBUFS;

	printf(": irq %d,%d,%d", ca->ca_intr[0], ca->ca_intr[1],
	    ca->ca_intr[2]);

	/* disable receive DMA */
	dbdma_reset(sc->sc_rxdma);

	/* disable transmit DMA */
	dbdma_reset(sc->sc_txdma);

	/* install interrupt handlers */
	mac_intr_establish(parent, ca->ca_intr[2], IST_LEVEL, IPL_NET,
	    mc_dmaintr, sc, sc->sc_dev.dv_xname);
	mac_intr_establish(parent, ca->ca_intr[0],  IST_LEVEL, IPL_NET,
	    mc_intr, sc, sc->sc_dev.dv_xname);

	sc->sc_biucc = XMTSP_64;
	sc->sc_fifocc = XMTFW_16 | RCVFW_64 | XMTFWU | RCVFWU |
	    XMTBRST | RCVBRST;
	sc->sc_plscc = PORTSEL_GPSI | ENPLSIO;

	/* reset the chip and disable all interrupts */
	NIC_PUT(sc, MACE_BIUCC, SWRST);
	DELAY(100);

	NIC_PUT(sc, MACE_IMR, ~0);

	bcopy(lladdr, sc->sc_enaddr, ETHER_ADDR_LEN);
	bcopy(sc->sc_enaddr, sc->sc_arpcom.ac_enaddr, ETHER_ADDR_LEN);
	printf(": address %s\n", ether_sprintf(lladdr));

	bcopy(sc->sc_dev.dv_xname, ifp->if_xname, IFNAMSIZ);
	ifp->if_softc = sc;
	ifp->if_ioctl = mc_ioctl;
	ifp->if_start = mc_start;
	ifp->if_flags =
		IFF_BROADCAST | IFF_SIMPLEX | IFF_NOTRAILERS | IFF_MULTICAST;
	ifp->if_watchdog = mc_watchdog;
	ifp->if_timer = 0;
	IFQ_SET_READY(&ifp->if_snd);

	if_attach(ifp);
	ether_ifattach(ifp);

	return;
nodmaload:
	bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufmap);
nodmacreate:
	bus_dmamem_unmap(sc->sc_dmat, sc->sc_txbuf, MACE_BUFSZ);
nodmamap:
	bus_dmamem_free(sc->sc_dmat, sc->sc_bufseg, 1);
nodmamem:
	dbdma_free(sc->sc_rxdbdma);
norxdbdma:
	dbdma_free(sc->sc_txdbdma);
notxdbdma:
	unmapiodev((void *)sc->sc_rxdma, ca->ca_reg[5]);
norxdma:
	unmapiodev((void *)sc->sc_txdma, ca->ca_reg[3]);
notxdma:
	unmapiodev(sc->sc_reg, ca->ca_reg[1]);
}

int
mc_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
	struct mc_softc *sc = ifp->if_softc;
	struct ifaddr *ifa = (struct ifaddr *)data;
	int s, err = 0;

	s = splnet();

	switch (cmd) {
	case SIOCSIFADDR:
		ifp->if_flags |= IFF_UP;
		if (!(ifp->if_flags & IFF_RUNNING))
			mc_init(sc);
		if (ifa->ifa_addr->sa_family == AF_INET)
			arp_ifinit(&sc->sc_arpcom, ifa);
		break;

	case SIOCSIFFLAGS:
		if ((ifp->if_flags & IFF_UP) == 0 &&
		    (ifp->if_flags & IFF_RUNNING) != 0) {
			/*
			 * If interface is marked down and it is running,
			 * then stop it.
			 */
			mc_stop(sc);
		} else if ((ifp->if_flags & IFF_UP) != 0 &&
		    (ifp->if_flags & IFF_RUNNING) == 0) {
			/*
			 * If interface is marked up and it is stopped,
			 * then start it.
			 */
			mc_init(sc);
		} else {
			/*
			 * reset the interface to pick up any other changes
			 * in flags
			 */
			mc_reset(sc);
			mc_start(ifp);
		}
		break;

	default:
		err = ether_ioctl(ifp, &sc->sc_arpcom, cmd, data);
	}

	if (err == ENETRESET) {
		if (ifp->if_flags & IFF_RUNNING)
			mc_reset(sc);
		err = 0;
	}

	splx(s);
	return (err);
}

/*
 * Encapsulate a packet of type family for the local net.
 */
void
mc_start(struct ifnet *ifp)
{
	struct mc_softc	*sc = ifp->if_softc;
	struct mbuf	*m;

	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
		return;

	while (1) {
		if (ifp->if_flags & IFF_OACTIVE)
			return;

		IFQ_DEQUEUE(&ifp->if_snd, m);
		if (m == NULL)
			return;

#if NBPFILTER > 0
		/*
		 * If bpf is listening on this interface, let it
		 * see the packet before we commit it to the wire.
		 */
		if (ifp->if_bpf)
			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
#endif

		/*
		 * Copy the mbuf chain into the transmit buffer.
		 */
		ifp->if_flags |= IFF_OACTIVE;
		maceput(sc, m);

		ifp->if_opackets++;		/* # of pkts */
	}
}

/*
 * reset and restart the MACE.  Called in case of fatal
 * hardware/software errors.
 */
void
mc_reset(struct mc_softc *sc)
{
	mc_stop(sc);
	mc_init(sc);
}

void
mc_init(struct mc_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	u_int8_t maccc, ladrf[8];
	int s, i;

	s = splnet();

	NIC_PUT(sc, MACE_BIUCC, sc->sc_biucc);
	NIC_PUT(sc, MACE_FIFOCC, sc->sc_fifocc);
	NIC_PUT(sc, MACE_IMR, ~0); /* disable all interrupts */
	NIC_PUT(sc, MACE_PLSCC, sc->sc_plscc);

	NIC_PUT(sc, MACE_UTR, RTRD); /* disable reserved test registers */

	/* set MAC address */
	NIC_PUT(sc, MACE_IAC, ADDRCHG);
	while (NIC_GET(sc, MACE_IAC) & ADDRCHG)
		;
	NIC_PUT(sc, MACE_IAC, PHYADDR);
	for (i = 0; i < ETHER_ADDR_LEN; i++)
		out8rb(sc->sc_reg + MACE_REG(MACE_PADR) + i,
		    sc->sc_enaddr[i]);

	/* set logical address filter */
	mace_calcladrf(sc, ladrf);

	NIC_PUT(sc, MACE_IAC, ADDRCHG);
	while (NIC_GET(sc, MACE_IAC) & ADDRCHG)
		;
	NIC_PUT(sc, MACE_IAC, LOGADDR);
	for (i = 0; i < 8; i++)
		out8rb(sc->sc_reg + MACE_REG(MACE_LADRF) + i,
		    ladrf[i]);

	NIC_PUT(sc, MACE_XMTFC, APADXMT);
	/*
	* No need to autostrip padding on receive... Ethernet frames
	* don't have a length field, unlike 802.3 frames, so the MACE
	* can't figure out the length of the packet anyways.
	*/
	NIC_PUT(sc, MACE_RCVFC, 0);

	maccc = ENXMT | ENRCV;
	if (ifp->if_flags & IFF_PROMISC)
		maccc |= PROM;

	NIC_PUT(sc, MACE_MACCC, maccc);

	mc_reset_rxdma(sc);
	mc_reset_txdma(sc);
	/*
	* Enable all interrupts except receive, since we use the DMA
	* completion interrupt for that.
	*/
	NIC_PUT(sc, MACE_IMR, RCVINTM);

	/* flag interface as "running" */
	ifp->if_flags |= IFF_RUNNING;
	ifp->if_flags &= ~IFF_OACTIVE;

	splx(s);
}

/*
 * Close down an interface and free its buffers.
 * Called on final close of device, or if mcinit() fails
 * part way through.
 */
int
mc_stop(struct mc_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	int s;

	s = splnet();

	NIC_PUT(sc, MACE_BIUCC, SWRST);
	DELAY(100);

	ifp->if_timer = 0;
	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);

	splx(s);
	return (0);
}

/*
 * Called if any Tx packets remain unsent after 5 seconds,
 * In all cases we just reset the chip, and any retransmission
 * will be handled by higher level protocol timeouts.
 */
void
mc_watchdog(struct ifnet *ifp)
{
	struct mc_softc *sc = ifp->if_softc;

	printf("mcwatchdog: resetting chip\n");
	mc_reset(sc);
}

int
mc_intr(void *arg)
{
	struct mc_softc *sc = arg;
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	u_int8_t ir;

	ir = NIC_GET(sc, MACE_IR) & ~NIC_GET(sc, MACE_IMR);

	if (ir & JAB) {
#ifdef MCDEBUG
		printf("%s: jabber error\n", sc->sc_dev.dv_xname);
#endif
		ifp->if_oerrors++;
	}

	if (ir & BABL) {
#ifdef MCDEBUG
		printf("%s: babble\n", sc->sc_dev.dv_xname);
#endif
		ifp->if_oerrors++;
	 }

	if (ir & CERR) {
#ifdef MCDEBUG
		printf("%s: collision error\n", sc->sc_dev.dv_xname);
#endif
		ifp->if_collisions++;
	 }

	/*
	 * Pretend we have carrier; if we don't this will be cleared
	 * shortly.
	 */
	sc->sc_havecarrier = 1;

	if (ir & XMTINT)
		mc_tint(sc);

	if (ir & RCVINT)
		mc_rint(sc);

	return(1);
}

void
mc_tint(struct mc_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	u_int8_t xmtrc, xmtfs;

	xmtrc = NIC_GET(sc, MACE_XMTRC);
	xmtfs = NIC_GET(sc, MACE_XMTFS);

	if ((xmtfs & XMTSV) == 0)
		return;

	if (xmtfs & UFLO) {
		printf("%s: underflow\n", sc->sc_dev.dv_xname);
		mc_reset(sc);
		return;
	}

	if (xmtfs & LCOL) {
		printf("%s: late collision\n", sc->sc_dev.dv_xname);
		ifp->if_oerrors++;
		ifp->if_collisions++;
	}

	if (xmtfs & MORE)
		/* Real number is unknown. */
		ifp->if_collisions += 2;
	else if (xmtfs & ONE)
		ifp->if_collisions++;
	else if (xmtfs & RTRY) {
		printf("%s: excessive collisions\n", sc->sc_dev.dv_xname);
		ifp->if_collisions += 16;
		ifp->if_oerrors++;
	}

	if (xmtfs & LCAR) {
		sc->sc_havecarrier = 0;
		printf("%s: lost carrier\n", sc->sc_dev.dv_xname);
		ifp->if_oerrors++;
	}

	ifp->if_flags &= ~IFF_OACTIVE;
	ifp->if_timer = 0;
	mc_start(ifp);
}

void
mc_rint(struct mc_softc *sc)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
#define rxf	sc->sc_rxframe
	u_int len;

	len = (rxf.rx_rcvcnt | ((rxf.rx_rcvsts & 0xf) << 8)) - 4;

#ifdef MCDEBUG
	if (rxf.rx_rcvsts & 0xf0)
		printf("%s: rcvcnt %02x rcvsts %02x rntpc 0x%02x rcvcc 0x%02x\n",
		    sc->sc_dev.dv_xname, rxf.rx_rcvcnt, rxf.rx_rcvsts,
		    rxf.rx_rntpc, rxf.rx_rcvcc);
#endif

	if (rxf.rx_rcvsts & OFLO) {
#ifdef MCDEBUG
		printf("%s: receive FIFO overflow\n", sc->sc_dev.dv_xname);
#endif
		ifp->if_ierrors++;
		return;
	}

	if (rxf.rx_rcvsts & CLSN)
		ifp->if_collisions++;

	if (rxf.rx_rcvsts & FRAM) {
#ifdef MCDEBUG
		printf("%s: framing error\n", sc->sc_dev.dv_xname);
#endif
		ifp->if_ierrors++;
		return;
	}

	if (rxf.rx_rcvsts & FCS) {
#ifdef MCDEBUG
		printf("%s: frame control checksum error\n", sc->sc_dev.dv_xname);
#endif
		ifp->if_ierrors++;
		return;
	}

	mace_read(sc, rxf.rx_frame, len);
#undef  rxf
}
/*
 * stuff packet into MACE (at splnet)
 */
u_int
maceput(struct mc_softc *sc, struct mbuf *m)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	struct mbuf *n;
	u_int len, totlen = 0;
	u_char *buff;

	buff = sc->sc_txbuf;

	for (; m; m = n) {
		u_char *data = mtod(m, u_char *);
		len = m->m_len;
		totlen += len;
		bcopy(data, buff, len);
		buff += len;
		n = m_free(m);
	}

	if (totlen > PAGE_SIZE)
		panic("%s: maceput: packet overflow", sc->sc_dev.dv_xname);

#if 0
	if (totlen < ETHERMIN + sizeof(struct ether_header)) {
		int pad = ETHERMIN + sizeof(struct ether_header) - totlen;
		bzero(sc->sc_txbuf + totlen, pad);
		totlen = ETHERMIN + sizeof(struct ether_header);
	}
#endif

	/* 5 seconds to watch for failing to transmit */
	ifp->if_timer = 5;
	mc_putpacket(sc, totlen);
	return (totlen);
}

void
mace_read(struct mc_softc *sc, caddr_t pkt, int len)
{
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
	struct mbuf *m;

	if (len <= sizeof(struct ether_header) ||
	    len > ETHERMTU + sizeof(struct ether_header)) {
#ifdef MCDEBUG
		printf("%s: invalid packet size %d; dropping\n",
		    sc->sc_dev.dv_xname, len);
#endif
		ifp->if_ierrors++;
		return;
	}

	m = mace_get(sc, pkt, len);
	if (m == NULL) {
		ifp->if_ierrors++;
		return;
	}

	ml_enqueue(&ml, m);
	if_input(ifp, &ml);
}

/*
 * Pull data off an interface.
 * Len is length of data, with local net header stripped.
 * We copy the data into mbufs.  When full cluster sized units are present
 * we copy into clusters.
 */
struct mbuf *
mace_get(struct mc_softc *sc, caddr_t pkt, int totlen)
{
	 struct mbuf *m;
	 struct mbuf *top, **mp;
	 int len;

	 MGETHDR(m, M_DONTWAIT, MT_DATA);
	 if (m == NULL)
		  return (NULL);

	 m->m_pkthdr.len = totlen;
	 len = MHLEN;
	 top = 0;
	 mp = ⊤

	 while (totlen > 0) {
		  if (top) {
			   MGET(m, M_DONTWAIT, MT_DATA);
			   if (m == NULL) {
				    m_freem(top);
				    return (NULL);
			   }
			   len = MLEN;
		  }
		  if (totlen >= MINCLSIZE) {
			   MCLGET(m, M_DONTWAIT);
			   if ((m->m_flags & M_EXT) == 0) {
				    m_free(m);
				    m_freem(top);
				    return (NULL);
			   }
			   len = MCLBYTES;
		  }
		  m->m_len = len = min(totlen, len);
		  bcopy(pkt, mtod(m, caddr_t), len);
		  pkt += len;
		  totlen -= len;
		  *mp = m;
		  mp = &m->m_next;
	 }

	 return (top);
}

void
mc_putpacket(struct mc_softc *sc, u_int len)
{
	dbdma_command_t *cmd = sc->sc_txdmacmd;

	DBDMA_BUILD(cmd, DBDMA_CMD_OUT_LAST, 0, len, sc->sc_txbuf_pa,
	   DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	cmd++;
	DBDMA_BUILD(cmd, DBDMA_CMD_STOP, 0, 0, 0, DBDMA_INT_ALWAYS,
	   DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

	dbdma_start(sc->sc_txdma, sc->sc_txdbdma);
}

/*
 * Interrupt handler for the MACE DMA completion interrupts
 */
int
mc_dmaintr(void *arg)
{
	struct mc_softc *sc = arg;
	int status, offset, statoff;
	int datalen, resid;
	int i, n, count;
	dbdma_command_t *cmd;

	/* We've received some packets from the MACE */
	/* Loop through, processing each of the packets */
	i = sc->sc_tail;
	for (n = 0; n < MC_RXDMABUFS; n++, i++) {
		if (i == MC_RXDMABUFS)
			i = 0;

		cmd = &sc->sc_rxdmacmd[i];
		status = dbdma_ld16(&cmd->d_status);
		resid = dbdma_ld16(&cmd->d_resid);

		if ((status & DBDMA_CNTRL_ACTIVE) == 0) {
			continue;
		}

		count = dbdma_ld16(&cmd->d_count);
		datalen = count - resid;
		datalen -= 4; /* 4 == status bytes */

		if (datalen < 4 + sizeof(struct ether_header)) {
			printf("short packet len=%d\n", datalen);
			/* continue; */
			goto next;
		}
		DBDMA_BUILD_CMD(cmd, DBDMA_CMD_STOP, 0, 0, 0, 0);

		offset = i * MACE_BUFLEN;
		statoff = offset + datalen;
		sc->sc_rxframe.rx_rcvcnt = sc->sc_rxbuf[statoff + 0];
		sc->sc_rxframe.rx_rcvsts = sc->sc_rxbuf[statoff + 1];
		sc->sc_rxframe.rx_rntpc  = sc->sc_rxbuf[statoff + 2];
		sc->sc_rxframe.rx_rcvcc  = sc->sc_rxbuf[statoff + 3];
		sc->sc_rxframe.rx_frame  = sc->sc_rxbuf + offset;

		mc_rint(sc);

next:
		DBDMA_BUILD_CMD(cmd, DBDMA_CMD_IN_LAST, 0, DBDMA_INT_ALWAYS,
		    DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

		cmd->d_status = 0;
		cmd->d_resid = 0;
		sc->sc_tail = i + 1;
	}

	dbdma_continue(sc->sc_rxdma);

	return 1;
}

void
mc_reset_rxdma(struct mc_softc *sc)
{
	dbdma_command_t *cmd = sc->sc_rxdmacmd;
	int i;
	u_int8_t maccc;

	/* Disable receiver, reset the DMA channels */
	maccc = NIC_GET(sc, MACE_MACCC);
	NIC_PUT(sc, MACE_MACCC, maccc & ~ENRCV);

	dbdma_reset(sc->sc_rxdma);

	bzero(sc->sc_rxdmacmd, 8 * sizeof(dbdma_command_t));
	for (i = 0; i < MC_RXDMABUFS; i++) {
		DBDMA_BUILD(cmd, DBDMA_CMD_IN_LAST, 0, MACE_BUFLEN,
		    sc->sc_rxbuf_pa + MACE_BUFLEN * i, DBDMA_INT_ALWAYS,
		    DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
		cmd++;
	}

	DBDMA_BUILD(cmd, DBDMA_CMD_NOP, 0, 0, 0,
	    DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_ALWAYS);
	dbdma_st32(&cmd->d_cmddep, sc->sc_rxdbdma->d_paddr);
	cmd++;

	sc->sc_tail = 0;

	dbdma_start(sc->sc_rxdma, sc->sc_rxdbdma);
	/* Reenable receiver, reenable DMA */
	NIC_PUT(sc, MACE_MACCC, maccc);
}

void
mc_reset_txdma(struct mc_softc *sc)
{
	dbdma_command_t *cmd = sc->sc_txdmacmd;
	dbdma_regmap_t *dmareg = sc->sc_txdma;
	u_int8_t maccc;

	/* disable transmitter */
	maccc = NIC_GET(sc, MACE_MACCC);
	NIC_PUT(sc, MACE_MACCC, maccc & ~ENXMT);

	dbdma_reset(sc->sc_txdma);

	bzero(sc->sc_txdmacmd, 2 * sizeof(dbdma_command_t));
	DBDMA_BUILD(cmd, DBDMA_CMD_OUT_LAST, 0, 0, sc->sc_txbuf_pa,
	    DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);
	cmd++;
	DBDMA_BUILD(cmd, DBDMA_CMD_STOP, 0, 0, 0,
	    DBDMA_INT_NEVER, DBDMA_WAIT_NEVER, DBDMA_BRANCH_NEVER);

	out32rb(&dmareg->d_cmdptrhi, 0);
	out32rb(&dmareg->d_cmdptrlo, sc->sc_txdbdma->d_paddr);

	/* restore old value */
	NIC_PUT(sc, MACE_MACCC, maccc);
}

/*
 * Go through the list of multicast addresses and calculate the logical
 * address filter.
 */
void
mace_calcladrf(struct mc_softc *sc, u_int8_t *af)
{
	struct ether_multi *enm;
	u_int32_t crc;
	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
	struct arpcom *ac = &sc->sc_arpcom;
	struct ether_multistep step;
	/*
	 * Set up multicast address filter by passing all multicast addresses
	 * through a crc generator, and then using the high order 6 bits as an
	 * index into the 64 bit logical address filter.  The high order bit
	 * selects the word, while the rest of the bits select the bit within
	 * the word.
	 */

	if (ac->ac_multirangecnt > 0)
		goto allmulti;

	*((u_int32_t *)af) = *((u_int32_t *)af + 1) = 0;
	ETHER_FIRST_MULTI(step, ac, enm);
	while (enm != NULL) {
		crc = ether_crc32_le(enm->enm_addrlo, sizeof(enm->enm_addrlo));

		/* Just want the 6 most significant bits. */
		crc >>= 26;

		/* Set the corresponding bit in the filter. */
		af[crc >> 3] |= 1 << (crc & 7);

		ETHER_NEXT_MULTI(step, enm);
	}
	ifp->if_flags &= ~IFF_ALLMULTI;
	return;

allmulti:
	ifp->if_flags |= IFF_ALLMULTI;
	*((u_int32_t *)af) = *((u_int32_t *)af + 1) = 0xffffffff;
}


code:
/*	$OpenBSD: if_wi_obio.c,v 1.18 2014/12/22 02:26:53 tedu Exp $	*/

/*
 * Copyright (c) 1997, 1998, 1999
 *	Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Bill Paul.
 * 4. Neither the name of the author nor the names of any co-contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 *
 *	From: if_wi.c,v 1.7 1999/07/04 14:40:22 wpaul Exp $
 */

/*
 * Lucent WaveLAN/IEEE 802.11 PCMCIA driver for OpenBSD.
 *
 * Originally written by Bill Paul <wpaul@ctr.columbia.edu>
 * Electrical Engineering Department
 * Columbia University, New York City
 */
 /*
  * modified for apple obio by Dale Rahn
  */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/timeout.h>
#include <sys/socket.h>
#include <sys/device.h>
#include <sys/tree.h>

#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_media.h>

#include <netinet/in.h>
#include <netinet/if_ether.h>

#include <net80211/ieee80211.h>
#include <net80211/ieee80211_ioctl.h>
#include <net80211/ieee80211_var.h>

#include <machine/bus.h>
#include <machine/autoconf.h>

#include <dev/ic/if_wireg.h>
#include <dev/ic/if_wi_ieee.h>
#include <dev/ic/if_wivar.h>

int	wi_obio_match(struct device *, void *, void *);
void	wi_obio_attach(struct device *, struct device *, void *);
int	wi_obio_detach(struct device *, int);
int	wi_obio_activate(struct device *, int);
void	wi_obio_attach(struct device *, struct device *, void *);
int	wi_obio_enable(struct wi_softc *sc);
void	wi_obio_disable(struct wi_softc *sc);

struct wi_obio_softc {
	struct wi_softc sc_wi;
	u_int keywest;
};

struct cfattach wi_obio_ca = {
	sizeof (struct wi_obio_softc), wi_obio_match, wi_obio_attach,
	wi_obio_detach, wi_obio_activate
};

int
wi_obio_match(parent, match, aux)
	struct device *parent;
	void *match, *aux;
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "radio") == 0 &&
	    ca->ca_nintr >= 4 && ca->ca_nreg >= 8)
		return (1);
	return (0);
}

void
wi_obio_attach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct wi_obio_softc	*psc = (struct wi_obio_softc *)self;
	struct wi_softc		*sc = &psc->sc_wi;
	struct confargs		*ca = aux;

	printf(" irq %d:", ca->ca_intr[0]);

	sc->wi_btag = ca->ca_iot;
	ca->ca_reg[0] += ca->ca_baseaddr;
	if (bus_space_map(sc->wi_btag, ca->ca_reg[0], ca->ca_reg[1], 0, &sc->wi_bhandle)) {
		printf("can't map i/o space\n");
	}
	/* FSCKING hackery */
	psc->keywest = (u_int) mapiodev(0x80000000, 0x1d000);

	/* Establish the interrupt. */
	mac_intr_establish(parent, ca->ca_intr[0], IST_LEVEL, IPL_NET,
		wi_intr, psc, sc->sc_dev.dv_xname);

	/* Make sure interrupts are disabled. */
	CSR_WRITE_2(sc, WI_INT_EN, 0);
	CSR_WRITE_2(sc, WI_EVENT_ACK, 0xffff);

	wi_obio_enable(sc);

	printf("\n");
	wi_attach(sc, &wi_func_io);
}

int
wi_obio_detach(dev, flags)
	struct device *dev;
	int flags;
{
	struct wi_obio_softc *psc = (struct wi_obio_softc *)dev;
	struct wi_softc *sc = &psc->sc_wi;
	struct ifnet *ifp = &sc->sc_ic.ic_if;

	/*
	obio_io_unmap(psc->sc_pf, psc->sc_io_window);
	obio_io_free(psc->sc_pf, &psc->sc_pcioh);
	*/

	wi_obio_disable(sc);
	ether_ifdetach(ifp);
	if_detach(ifp);

	return (0);
}

int
wi_obio_activate(dev, act)
	struct device *dev;
	int act;
{
	struct wi_obio_softc *psc = (struct wi_obio_softc *)dev;
	struct wi_softc *sc = &psc->sc_wi;
	struct ifnet *ifp = &sc->sc_ic.ic_if;
	int s;

	s = splnet();
	switch (act) {
	case DVACT_DEACTIVATE:
		ifp->if_timer = 0;
		if (ifp->if_flags & IFF_RUNNING)
			wi_stop(sc);
		wi_obio_disable(sc);
		break;
	}
	splx(s);
	return (0);
}

/* THIS IS CRAP */

int
wi_obio_enable(sc)
	struct wi_softc *sc;
{
	struct wi_obio_softc *psc = (struct wi_obio_softc *)sc;
	const u_int keywest = psc->keywest;	/* XXX */
	const u_int fcr2 = keywest + 0x40;
	const u_int gpio = keywest + 0x6a;
	const u_int extint_gpio = keywest + 0x58;
	u_int x;

	x = in32rb(fcr2);
	x |= 0x4;
	out32rb(fcr2, x);

	/* Enable card slot. */
	out8(gpio + 0x0f, 5);
	delay(1000);
	out8(gpio + 0x0f, 4);
	delay(1000);

	x = in32rb(fcr2);
	x &= ~0x8000000;

	out32rb(fcr2, x);
	/* out8(gpio + 0x10, 4); */

	out8(extint_gpio + 0x0b, 0);
	out8(extint_gpio + 0x0a, 0x28);
	out8(extint_gpio + 0x0d, 0x28);
	out8(gpio + 0x0d, 0x28);
	out8(gpio + 0x0e, 0x28);
	out32rb(keywest + 0x1c000, 0);

	/* Initialize the card. */
	out32rb(keywest + 0x1a3e0, 0x41);
	x = in32rb(fcr2);
	x |= 0x8000000;
	out32rb(fcr2, x);

	return 0;
}

void
wi_obio_disable(sc)
	struct wi_softc *sc;
{
	struct wi_obio_softc *psc = (struct wi_obio_softc *)sc;
	const u_int keywest = psc->keywest;	/* XXX */
	const u_int fcr2 = keywest + 0x40;
	u_int x;

	x = in32rb(fcr2);
	x &= ~0x4;
	out32rb(fcr2, x);
	/* out8(gpio + 0x10, 0); */
}


code:
/*	$OpenBSD: kiic.c,v 1.4 2013/10/09 17:53:29 mpi Exp $	*/
/*	$NetBSD: kiic.c,v 1.1 2003/12/27 02:19:34 grant Exp $	*/

/*-
 * Copyright (c) 2001 Tsubai Masanari.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/param.h>
#include <sys/device.h>
#include <sys/systm.h>

#include <dev/ofw/openfirm.h>
#include <uvm/uvm_extern.h>
#include <machine/autoconf.h>

#include <macppc/dev/kiicvar.h>
#include <macppc/dev/maci2cvar.h>

int kiic_match(struct device *, void *, void *);
void kiic_attach(struct device *, struct device *, void *);
inline u_int kiic_readreg(struct kiic_softc *, int);
inline void kiic_writereg(struct kiic_softc *, int, u_int);
void kiic_setmode(struct kiic_softc *, u_int, u_int);
void kiic_setspeed(struct kiic_softc *, u_int);
int kiic_intr(struct kiic_softc *);
int kiic_poll(struct kiic_softc *, int);
int kiic_start(struct kiic_softc *, int, int, void *, int);
int kiic_read(struct kiic_softc *, int, int, void *, int);
int kiic_write(struct kiic_softc *, int, int, const void *, int);

/* I2C glue */
int kiic_i2c_acquire_bus(void *, int);
void kiic_i2c_release_bus(void *, int);
int kiic_i2c_exec(void *, i2c_op_t, i2c_addr_t, const void *, size_t,
    void *, size_t, int);

struct cfattach kiic_ca = {
	sizeof(struct kiic_softc), kiic_match, kiic_attach
};
struct cfattach kiic_memc_ca = {
	sizeof(struct kiic_softc), kiic_match, kiic_attach
};

struct cfdriver kiic_cd = {
	NULL, "kiic", DV_DULL
};

int
kiic_match(struct device *parent, void *match, void *aux)
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "i2c") == 0 &&
	   ca->ca_nreg >= 4)
		return (1);

	return (0);
}

void
kiic_attach(struct device *parent, struct device *self, void *aux)
{
	struct kiic_softc *sc = (struct kiic_softc *)self;
	struct confargs *ca = aux;
	struct i2cbus_attach_args iba;
	int rate, node = ca->ca_node;
	char name[32];
	uint32_t reg;

	ca->ca_reg[0] += ca->ca_baseaddr;

	if (OF_getprop(node, "AAPL,i2c-rate", &rate, 4) != 4) {
		printf(": cannot get i2c-rate\n");
		return;
	}
	if (OF_getprop(node, "AAPL,address", &sc->sc_paddr, 4) != 4) {
		printf(": unable to find i2c address\n");
		return;
	}
	if (OF_getprop(node, "AAPL,address-step", &sc->sc_regstep, 4) != 4) {
		printf(": unable to find i2c address step\n");
		return;
	}
	sc->sc_reg = mapiodev(sc->sc_paddr, (DATA+1)*sc->sc_regstep);

	printf("\n");

	kiic_writereg(sc, STATUS, 0);
	kiic_writereg(sc, ISR, 0);
	kiic_writereg(sc, IER, 0);

	kiic_setmode(sc, I2C_STDSUBMODE, 0);
	kiic_setspeed(sc, I2C_100kHz);		/* XXX rate */

	rw_init(&sc->sc_buslock, sc->sc_dev.dv_xname);
	kiic_writereg(sc, IER,I2C_INT_DATA|I2C_INT_ADDR|I2C_INT_STOP);

	sc->sc_busnode = node;

	node = OF_child(ca->ca_node);
	if (OF_getprop(node, "name", name, sizeof(name)) > 0) {
		if (strcmp(name, "i2c-bus") == 0) {
			if (OF_getprop(node, "reg", &reg, sizeof(reg)) > 0)
				sc->sc_busport = reg;

			sc->sc_busnode = node;
		}
	}

	sc->sc_i2c_tag.ic_cookie = sc;
	sc->sc_i2c_tag.ic_acquire_bus = kiic_i2c_acquire_bus;
	sc->sc_i2c_tag.ic_release_bus = kiic_i2c_release_bus;
	sc->sc_i2c_tag.ic_exec = kiic_i2c_exec;

	bzero(&iba, sizeof(iba));
	iba.iba_name = "iic";
	iba.iba_tag = &sc->sc_i2c_tag;
	iba.iba_bus_scan = maciic_scan;
	iba.iba_bus_scan_arg = &sc->sc_busnode;
	config_found(&sc->sc_dev, &iba, NULL);
}

u_int
kiic_readreg(struct kiic_softc *sc, int reg)
{
	u_char *addr = sc->sc_reg + sc->sc_regstep * reg;

	return (*addr);
}

void
kiic_writereg(struct kiic_softc *sc, int reg, u_int val)
{
	u_char *addr = sc->sc_reg + sc->sc_regstep * reg;

	*addr = val;
	asm volatile ("eieio");
	delay(10);
}

void
kiic_setmode(struct kiic_softc *sc, u_int mode, u_int bus)
{
	u_int x;

	KASSERT((mode & ~I2C_MODE) == 0);
	x = kiic_readreg(sc, MODE);
	x &= ~(I2C_MODE);
	if (bus)
		x |= I2C_BUS1;
	else
		x &= ~I2C_BUS1;
	x |= mode;
	kiic_writereg(sc, MODE, x);
}

void
kiic_setspeed(struct kiic_softc *sc, u_int speed)
{
	u_int x;

	KASSERT((speed & ~I2C_SPEED) == 0);
	x = kiic_readreg(sc, MODE);
	x &= ~I2C_SPEED;
	x |= speed;
	kiic_writereg(sc, MODE, x);
}

int
kiic_intr(struct kiic_softc *sc)
{
	u_int isr, x;

	isr = kiic_readreg(sc, ISR);
	if (isr & I2C_INT_ADDR) {
#if 0
		if ((kiic_readreg(sc, STATUS) & I2C_ST_LASTAAK) == 0) {
			/* No slave responded. */
			sc->sc_flags |= I2C_ERROR;
			goto out;
		}
#endif

		if (sc->sc_flags & I2C_READING) {
			if (sc->sc_resid > 1) {
				x = kiic_readreg(sc, CONTROL);
				x |= I2C_CT_AAK;
				kiic_writereg(sc, CONTROL, x);
			}
		} else {
			kiic_writereg(sc, DATA, *sc->sc_data++);
			sc->sc_resid--;
		}
	}

	if (isr & I2C_INT_DATA) {
		if (sc->sc_flags & I2C_READING) {
			if (sc->sc_resid > 0) {
				*sc->sc_data++ = kiic_readreg(sc, DATA);
				sc->sc_resid--;
			}
			if (sc->sc_resid == 0) {	/* Completed */
				kiic_writereg(sc, CONTROL, 0);
				goto out;
			}
		} else {
#if 0
			if ((kiic_readreg(sc, STATUS) & I2C_ST_LASTAAK) == 0) {
				/* No slave responded. */
				sc->sc_flags |= I2C_ERROR;
				goto out;
			}
#endif

			if (sc->sc_resid == 0) {
				x = kiic_readreg(sc, CONTROL) | I2C_CT_STOP;
				kiic_writereg(sc, CONTROL, x);
			} else {
				kiic_writereg(sc, DATA, *sc->sc_data++);
				sc->sc_resid--;
			}
		}
	}

out:
	if (isr & I2C_INT_STOP) {
		kiic_writereg(sc, CONTROL, 0);
		sc->sc_flags &= ~I2C_BUSY;
	}

	kiic_writereg(sc, ISR, isr);

	return (1);
}

int
kiic_poll(struct kiic_softc *sc, int timo)
{
	while (sc->sc_flags & I2C_BUSY) {
		if (kiic_readreg(sc, ISR))
			kiic_intr(sc);
		timo -= 100;
		if (timo < 0) {
			printf("i2c_poll: timeout\n");
			return (-1);
		}
		delay(100);
	}
	return (0);
}

int
kiic_start(struct kiic_softc *sc, int addr, int subaddr, void *data, int len)
{
	int rw = (sc->sc_flags & I2C_READING) ? 1 : 0;
	int timo, x;

	KASSERT((addr & 1) == 0);

	sc->sc_data = data;
	sc->sc_resid = len;
	sc->sc_flags |= I2C_BUSY;

	timo = 1000 + len * 200;

	/* XXX TAS3001 sometimes takes 50ms to finish writing registers. */
	/* if (addr == 0x68) */
		timo += 100000;

	kiic_writereg(sc, ADDR, addr | rw);
	kiic_writereg(sc, SUBADDR, subaddr);

	x = kiic_readreg(sc, CONTROL) | I2C_CT_ADDR;
	kiic_writereg(sc, CONTROL, x);

	if (kiic_poll(sc, timo))
		return (-1);
	if (sc->sc_flags & I2C_ERROR) {
		printf("I2C_ERROR\n");
		return (-1);
	}
	if (sc->sc_resid != 0)
		return (-1);
	return (0);
}

int
kiic_read(struct kiic_softc *sc, int addr, int subaddr, void *data, int len)
{
	sc->sc_flags = I2C_READING;
	return kiic_start(sc, addr, subaddr, data, len);
}

int
kiic_write(struct kiic_softc *sc, int addr, int subaddr, const void *data, int len)
{
	sc->sc_flags = 0;
	return kiic_start(sc, addr, subaddr, (void *)data, len);
}

int
kiic_i2c_acquire_bus(void *cookie, int flags)
{
	struct kiic_softc *sc = cookie;

	return (rw_enter(&sc->sc_buslock, RW_WRITE));
}

void
kiic_i2c_release_bus(void *cookie, int flags)
{
	struct kiic_softc *sc = cookie;

	(void) rw_exit(&sc->sc_buslock);
}

int
kiic_i2c_exec(void *cookie, i2c_op_t op, i2c_addr_t addr,
    const void *cmdbuf, size_t cmdlen, void *buf, size_t len, int flags)
{
	struct kiic_softc *sc = cookie;
	u_int mode = I2C_STDSUBMODE;
	u_int8_t cmd = 0;

	if (!I2C_OP_STOP_P(op) || cmdlen > 1)
		return (EINVAL);

	if (cmdlen == 0)
		mode = I2C_STDMODE;
	else if (I2C_OP_READ_P(op))
		mode = I2C_COMBMODE;

	if (cmdlen > 0)
		cmd = *(u_int8_t *)cmdbuf;

	/*
	 * Use the value read from the "i2c-bus" child node or
	 * the 9th bit of the address to select the right bus.
	 */
	kiic_setmode(sc, mode, sc->sc_busport || addr & 0x80);
	addr &= 0x7f;

	if (I2C_OP_READ_P(op)) {
		if (kiic_read(sc, (addr << 1), cmd, buf, len) != 0)
			return (EIO);
	} else {
		if (kiic_write(sc, (addr << 1), cmd, buf, len) != 0)
			return (EIO);
	}
	return (0);
}


code:
/*	$OpenBSD: kiicvar.h,v 1.3 2013/10/09 17:53:30 mpi Exp $	*/

/*-
 * Copyright (c) 2001 Tsubai Masanari.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef KIICVAR_H
#define KIICVAR_H

#include <sys/param.h>
#include <sys/device.h>
#include <sys/systm.h>
#include <sys/rwlock.h>

#include <dev/i2c/i2cvar.h>

/* Keywest I2C Register offsets */
#define MODE	0
#define CONTROL	1
#define STATUS	2
#define ISR	3
#define IER	4
#define ADDR	5
#define SUBADDR	6
#define DATA	7

/* MODE */
#define I2C_SPEED	0x03	/* Speed mask */
#define  I2C_100kHz	0x00
#define  I2C_50kHz	0x01
#define  I2C_25kHz	0x02
#define I2C_MODE	0x0c	/* Mode mask */
#define  I2C_DUMBMODE	0x00	/*  Dumb mode */
#define  I2C_STDMODE	0x04	/*  Standard mode */
#define  I2C_STDSUBMODE	0x08	/*  Standard mode + sub address */
#define  I2C_COMBMODE	0x0c	/*  Combined mode */
#define I2C_PORT	0xf0	/* Port mask */
#define  I2C_BUS1	0x10	/* choose Bus 1 */

/* CONTROL */
#define I2C_CT_AAK	0x01	/* Send AAK */
#define I2C_CT_ADDR	0x02	/* Send address(es) */
#define I2C_CT_STOP	0x04	/* Send STOP */
#define I2C_CT_START	0x08	/* Send START */

/* STATUS */
#define I2C_ST_BUSY	0x01	/* Busy */
#define I2C_ST_LASTAAK	0x02	/* Last AAK */
#define I2C_ST_LASTRW	0x04	/* Last R/W */
#define I2C_ST_SDA	0x08	/* SDA */
#define I2C_ST_SCL	0x10	/* SCL */

/* ISR/IER */
#define I2C_INT_DATA	0x01	/* Data byte sent/received */
#define I2C_INT_ADDR	0x02	/* Address sent */
#define I2C_INT_STOP	0x04	/* STOP condition sent */
#define I2C_INT_START	0x08	/* START condition sent */

/* I2C flags */
#define I2C_BUSY	0x01
#define I2C_READING	0x02
#define I2C_ERROR	0x04

struct kiic_softc {
	struct device sc_dev;
	paddr_t sc_paddr;
	u_char *sc_reg;
	int sc_regstep;

	int sc_busnode;
	uint32_t sc_busport;
	struct rwlock sc_buslock;
	struct i2c_controller sc_i2c_tag;

	int sc_flags;
	u_char *sc_data;
	u_int sc_resid;
};

#endif


code:
/*	$OpenBSD: macgpio.c,v 1.8 2015/06/24 11:58:06 mpi Exp $	*/
/*	$NetBSD: gpio.c,v 1.2 2001/02/27 05:16:33 matt Exp $	*/

/*-
 * Copyright (C) 1998	Internet Research Institute, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by
 *	Internet Research Institute, Inc.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/device.h>
#include <sys/malloc.h>

#include <dev/ofw/openfirm.h>

#include <machine/autoconf.h>
#include <machine/pio.h>

#include "adb.h"

static void macgpio_attach (struct device *, struct device *, void *);
static int macgpio_match (struct device *, void *, void *);
static int macgpio_print (void *aux, const char *gpio);

static void macgpio_gpio_attach (struct device *, struct device *, void *);
static int macgpio_gpio_match (struct device *, void *, void *);
static int gpio_intr (void *);

struct gpio_softc {
	struct device sc_dev;
	u_int8_t *sc_port;
};

struct cfattach macgpio_ca = {
	sizeof(struct gpio_softc), macgpio_match, macgpio_attach
};

struct cfattach macgpio_gpio_ca = {
	sizeof(struct gpio_softc), macgpio_gpio_match, macgpio_gpio_attach
};

struct cfdriver macgpio_cd = {
	NULL, "macgpio", DV_DULL
};

int
macgpio_match(struct device *parent, void *cf, void *aux)
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "gpio") != 0)
		return 0;

	if (ca->ca_nreg < 8)
		return 0;

	return 1;
}

void
macgpio_attach(struct device *parent, struct device *self, void *aux)
{
	struct gpio_softc *sc = (struct gpio_softc *)self;
	struct confargs *ca = aux, ca2;
	int child;
	int namelen;
	int intr[6];
	u_int reg[20];
	char name[32];

	printf("\n");

	sc->sc_port = mapiodev(ca->ca_baseaddr + ca->ca_reg[0], ca->ca_reg[1]);

	ca2.ca_baseaddr = ca->ca_baseaddr;
	for (child = OF_child(ca->ca_node); child; child = OF_peer(child)) {
		namelen = OF_getprop(child, "name", name, sizeof(name));
		if (namelen < 0)
			continue;
		if (namelen >= sizeof(name))
			continue;

		name[namelen] = 0;
		ca2.ca_name = name;
		ca2.ca_node = child;

		ca2.ca_nreg  = OF_getprop(child, "reg", reg, sizeof(reg));
		ca2.ca_nintr = OF_getprop(child, "AAPL,interrupts", intr,
				sizeof(intr));
		if (ca2.ca_nintr == -1)
			ca2.ca_nintr = OF_getprop(child, "interrupts", intr,
					sizeof(intr));

		ca2.ca_reg = reg;
		ca2.ca_intr = intr;

		config_found(self, &ca2, macgpio_print);
	}
}

int
macgpio_print(void *aux, const char *gpio)
{
	struct confargs *ca = aux;
	if (gpio)
		printf("\"%s\" at %s", ca->ca_name, gpio);

	if (ca->ca_nreg > 0)
		printf(" offset 0x%x", ca->ca_reg[0]);

	return UNCONF;
}

int
macgpio_gpio_match(struct device *parent, void *cf, void *aux)
{
	struct confargs *ca = aux;

	if (strcmp(ca->ca_name, "extint-gpio1") != 0)
		return 0;

	if (ca->ca_nintr < 4)
		return 0;

	return 1;
}

void
macgpio_gpio_attach(struct device *parent, struct device *self, void *aux)
{
	struct gpio_softc *sc = (struct gpio_softc *)self;
	struct confargs *ca = aux;

	sc->sc_port = ((struct gpio_softc *) parent)->sc_port;
	mac_intr_establish(parent, ca->ca_intr[0], IST_LEVEL, IPL_TTY,
	    gpio_intr, sc, sc->sc_dev.dv_xname);

	printf(": irq %d\n", ca->ca_intr[0]);
}

#if NADB > 0
extern int adb_intr (void *);
extern struct cfdriver adb_cd;
#endif

int
gpio_intr(void *arg)
{
	int rv = 0;

#if NADB > 0
	if (adb_cd.cd_devs[0] != NULL)
		rv = adb_intr(adb_cd.cd_devs[0]);
#endif

	return rv;
}


code:
/*	$OpenBSD: maci2c.c,v 1.10 2010/04/09 17:01:30 jasper Exp $	*/

/*
 * Copyright (c) 2005 Mark Kettenis
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>

#define _I2C_PRIVATE
#include <dev/i2c/i2cvar.h>
#include <dev/ofw/openfirm.h>

#include <arch/macppc/dev/maci2cvar.h>

void
maciic_scan(struct device *self, struct i2cbus_attach_args *iba, void *aux)
{
	int iba_node = *(int *)aux;
	struct i2c_attach_args ia;
	char name[32];
	u_int32_t reg;
	int node;

	for (node = OF_child(iba_node); node; node = OF_peer(node)) {
		if (OF_getprop(node, "reg", &reg, sizeof reg) != sizeof reg &&
		    OF_getprop(node, "i2c-address", &reg, sizeof reg) != sizeof reg)
			continue;
		bzero(&ia, sizeof ia);
		ia.ia_tag = iba->iba_tag;
		ia.ia_addr = (reg >> 1);
		bzero(name, sizeof name);
		if (OF_getprop(node, "compatible", &name,
		    sizeof name) && name[0])
			ia.ia_name = name;
		if (ia.ia_name == NULL &&
		    OF_getprop(node, "name", &name,
		    sizeof name) && name[0]) {
			if (strcmp(name, "cereal") == 0)
				continue;
			ia.ia_name = name;
		}
		/* XXX We should write a real driver for these instead
		   of reaching over from the sound driver that sits on
		   the i2s port.  For now hide them.  */
		if (strcmp(name, "deq") == 0 || strcmp(name, "tas3004") == 0)
			continue;
		if (ia.ia_name)
			config_found(self, &ia, iic_print);
	}
}


code:
/*	$OpenBSD: maci2cvar.h,v 1.3 2006/01/01 20:52:25 deraadt Exp $	*/

/*
 * Copyright (c) 2005 Mark Kettenis
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <dev/i2c/i2cvar.h>

void	maciic_scan(struct device *sc, struct i2cbus_attach_args *iba, void *aux);