code:
/*	$OpenBSD: sab.c,v 1.31 2013/05/30 16:15:01 deraadt Exp $	*/

/*
 * Copyright (c) 2001 Jason L. Wright (jason@thought.net)
 * 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.
 *
 * 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.
 *
 * Effort sponsored in part by the Defense Advanced Research Projects
 * Agency (DARPA) and Air Force Research Laboratory, Air Force
 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
 *
 */

/*
 * SAB82532 Dual UART driver
 */

#include <sys/types.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/conf.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/kernel.h>
#include <sys/proc.h>
#include <sys/tty.h>
#include <sys/time.h>
#include <sys/syslog.h>

#include <machine/autoconf.h>
#include <machine/openfirm.h>
#include <machine/conf.h>
#include <machine/cpu.h>
#include <machine/psl.h>

#include <dev/cons.h>
#include <ddb/db_output.h>

#include <sparc64/dev/ebusreg.h>
#include <sparc64/dev/ebusvar.h>
#include <sparc64/dev/cons.h>
#include <sparc64/dev/sab82532reg.h>

#define	SAB_CARD(x)	((minor(x) >> 6) & 3)
#define	SAB_PORT(x)	(minor(x) & 7)
#define	SAB_DIALOUT(x)	(minor(x) & 0x10)
#define	SABTTY_RBUF_SIZE	1024	/* must be divisible by 2 */

struct sab_softc {
	struct device		sc_dv;
	struct intrhand *	sc_ih;
	bus_space_tag_t		sc_bt;
	bus_space_handle_t	sc_bh;
	struct sabtty_softc *	sc_child[SAB_NCHAN];
	u_int			sc_nchild;
	void *			sc_softintr;
	int			sc_node;
};

struct sabtty_attach_args {
	u_int sbt_portno;
};

struct sabtty_softc {
	struct device		sc_dv;
	struct sab_softc *	sc_parent;
	bus_space_tag_t		sc_bt;
	bus_space_handle_t	sc_bh;
	struct tty *		sc_tty;
	u_int			sc_portno;
	u_int8_t		sc_pvr_dtr, sc_pvr_dsr;
	u_int8_t		sc_imr0, sc_imr1;
	int			sc_openflags;
	u_char *		sc_txp;
	int			sc_txc;
	int			sc_flags;
#define SABTTYF_STOP		0x01
#define	SABTTYF_DONE		0x02
#define	SABTTYF_RINGOVERFLOW	0x04
#define	SABTTYF_CDCHG		0x08
#define	SABTTYF_CONS_IN		0x10
#define	SABTTYF_CONS_OUT	0x20
#define	SABTTYF_TXDRAIN		0x40
#define	SABTTYF_DONTDDB		0x80
	int			sc_speed;
	u_int8_t		sc_rbuf[SABTTY_RBUF_SIZE];
	u_int8_t		*sc_rend, *sc_rput, *sc_rget;
	u_int8_t		sc_polling, sc_pollrfc;
};

struct sabtty_softc *sabtty_cons_input;
struct sabtty_softc *sabtty_cons_output;

#define	SAB_READ(sc,r)		\
    bus_space_read_1((sc)->sc_bt, (sc)->sc_bh, (r))
#define	SAB_WRITE(sc,r,v)	\
    bus_space_write_1((sc)->sc_bt, (sc)->sc_bh, (r), (v))
#define	SAB_WRITE_BLOCK(sc,r,p,c)	\
    bus_space_write_region_1((sc)->sc_bt, (sc)->sc_bh, (r), (p), (c))

int sab_match(struct device *, void *, void *);
void sab_attach(struct device *, struct device *, void *);

int sab_print(void *, const char *);
int sab_intr(void *);
void sab_softintr(void *);
void sab_cnputc(dev_t, int);
int sab_cngetc(dev_t);
void sab_cnpollc(dev_t, int);

int sabtty_match(struct device *, void *, void *);
void sabtty_attach(struct device *, struct device *, void *);
int sabtty_activate(struct device *, int);

void sabtty_start(struct tty *);
int sabtty_param(struct tty *, struct termios *);
int sabtty_intr(struct sabtty_softc *, int *);
void sabtty_softintr(struct sabtty_softc *);
int sabtty_mdmctrl(struct sabtty_softc *, int, int);
int sabtty_cec_wait(struct sabtty_softc *);
int sabtty_tec_wait(struct sabtty_softc *);
void sabtty_reset(struct sabtty_softc *);
void sabtty_flush(struct sabtty_softc *);
int sabtty_speed(int);
void sabtty_console_flags(struct sabtty_softc *);
void sabtty_console_speed(struct sabtty_softc *);
void sabtty_cnpollc(struct sabtty_softc *, int);
void sabtty_shutdown(struct sabtty_softc *);
int sabttyparam(struct sabtty_softc *, struct tty *, struct termios *);

int sabttyopen(dev_t, int, int, struct proc *);
int sabttyclose(dev_t, int, int, struct proc *);
int sabttyread(dev_t, struct uio *, int);
int sabttywrite(dev_t, struct uio *, int);
int sabttyioctl(dev_t, u_long, caddr_t, int, struct proc *);
int sabttystop(struct tty *, int);
struct tty *sabttytty(dev_t);
void sabtty_cnputc(struct sabtty_softc *, int);
int sabtty_cngetc(struct sabtty_softc *);
void sabtty_abort(struct sabtty_softc *);

struct cfattach sab_ca = {
	sizeof(struct sab_softc), sab_match, sab_attach
};

struct cfdriver sab_cd = {
	NULL, "sab", DV_DULL
};

struct cfattach sabtty_ca = {
	sizeof(struct sabtty_softc), sabtty_match, sabtty_attach,
	NULL, sabtty_activate
};

struct cfdriver sabtty_cd = {
	NULL, "sabtty", DV_TTY
};

struct sabtty_rate {
	int baud;
	int n, m;
};

struct sabtty_rate sabtty_baudtable[] = {
	{      50,	35,     10 },
	{      75,	47,	9 },
	{     110,	32,	9 },
	{     134,	53,	8 },
	{     150,	47,	8 },
	{     200,	35,	8 },
	{     300,	47,	7 },
	{     600,	47,	6 },
	{    1200,	47,	5 },
	{    1800,	31,	5 },
	{    2400,	47,	4 },
	{    4800,	47,	3 },
	{    9600,	47,	2 },
	{   19200,	47,	1 },
	{   38400,	23,	1 },
	{   57600,	15,	1 },
	{  115200,	 7,	1 },
	{  230400,	 3,	1 },
	{  460800,	 1,	1 },
	{   76800,	11,	1 },
	{  153600,	 5,	1 },
	{  307200,	 3,	1 },
	{  614400,	 3,	0 },
	{  921600,	 0,	1 },
};

int
sab_match(parent, match, aux)
	struct device *parent;
	void *match, *aux;
{
	struct ebus_attach_args *ea = aux;
	char *compat;

	if (strcmp(ea->ea_name, "se") == 0 ||
	    strcmp(ea->ea_name, "FJSV,se") == 0)
		return (1);
	compat = getpropstring(ea->ea_node, "compatible");
	if (compat != NULL && !strcmp(compat, "sab82532"))
		return (1);
	return (0);
}

void
sab_attach(parent, self, aux)
	struct device *parent;
	struct device *self;
	void *aux;
{
	struct sab_softc *sc = (struct sab_softc *)self;
	struct ebus_attach_args *ea = aux;
	u_int8_t r;
	u_int i;

	sc->sc_bt = ea->ea_memtag;
	sc->sc_node = ea->ea_node;

	/* Use prom mapping, if available. */
	if (ea->ea_nvaddrs) {
		if (bus_space_map(sc->sc_bt, ea->ea_vaddrs[0],
		    0, BUS_SPACE_MAP_PROMADDRESS, &sc->sc_bh) != 0) {
			printf(": can't map register space\n");
			return;
		}
	} else if (ebus_bus_map(sc->sc_bt, 0,
	    EBUS_PADDR_FROM_REG(&ea->ea_regs[0]), ea->ea_regs[0].size, 0, 0,
	    &sc->sc_bh) != 0) {
		printf(": can't map register space\n");
		return;
	}

	BUS_SPACE_SET_FLAGS(sc->sc_bt, sc->sc_bh, BSHDB_NO_ACCESS);

	sc->sc_ih = bus_intr_establish(sc->sc_bt, ea->ea_intrs[0],
	    IPL_TTY, 0, sab_intr, sc, self->dv_xname);
	if (sc->sc_ih == NULL) {
		printf(": can't map interrupt\n");
		return;
	}

	sc->sc_softintr = softintr_establish(IPL_TTY, sab_softintr, sc);
	if (sc->sc_softintr == NULL) {
		printf(": can't get soft intr\n");
		return;
	}

	printf(": rev ");
	r = SAB_READ(sc, SAB_VSTR) & SAB_VSTR_VMASK;
	switch (r) {
	case SAB_VSTR_V_1:
		printf("1");
		break;
	case SAB_VSTR_V_2:
		printf("2");
		break;
	case SAB_VSTR_V_32:
		printf("3.2");
		break;
	default:
		printf("unknown(0x%x)", r);
		break;
	}
	printf("\n");

	/* Let current output drain */
	DELAY(100000);

	/* Set all pins, except DTR pins to be inputs */
	SAB_WRITE(sc, SAB_PCR, ~(SAB_PVR_DTR_A | SAB_PVR_DTR_B));
	/* Disable port interrupts */
	SAB_WRITE(sc, SAB_PIM, 0xff);
	SAB_WRITE(sc, SAB_PVR, SAB_PVR_DTR_A | SAB_PVR_DTR_B | SAB_PVR_MAGIC);
	SAB_WRITE(sc, SAB_IPC, SAB_IPC_ICPL);

	for (i = 0; i < SAB_NCHAN; i++) {
		struct sabtty_attach_args sta;

		sta.sbt_portno = i;
		sc->sc_child[i] = (struct sabtty_softc *)config_found_sm(self,
		    &sta, sab_print, sabtty_match);
		if (sc->sc_child[i] != NULL)
			sc->sc_nchild++;
	}
}

int
sabtty_activate(struct device *self, int act)
{
	struct sabtty_softc *sc = (struct sabtty_softc *)self;
	int ret = 0;

	switch (act) {
	case DVACT_POWERDOWN:
		if (sc->sc_flags & SABTTYF_CONS_IN)
			sabtty_shutdown(sc);
		break;
	}

	return (ret);
}

int
sab_print(args, name)
	void *args;
	const char *name;
{
	struct sabtty_attach_args *sa = args;

	if (name)
		printf("sabtty at %s", name);
	printf(" port %d", sa->sbt_portno);
	return (UNCONF);
}

int
sab_intr(vsc)
	void *vsc;
{
	struct sab_softc *sc = vsc;
	int r = 0, needsoft = 0;
	u_int8_t gis;

	gis = SAB_READ(sc, SAB_GIS);

	/* channel A */
	if ((gis & (SAB_GIS_ISA1 | SAB_GIS_ISA0)) && sc->sc_child[0] &&
	    sc->sc_child[0]->sc_tty)
		r |= sabtty_intr(sc->sc_child[0], &needsoft);

	/* channel B */
	if ((gis & (SAB_GIS_ISB1 | SAB_GIS_ISB0)) && sc->sc_child[1] &&
	    sc->sc_child[1]->sc_tty)
		r |= sabtty_intr(sc->sc_child[1], &needsoft);

	if (needsoft)
		softintr_schedule(sc->sc_softintr);

	return (r);
}

void
sab_softintr(vsc)
	void *vsc;
{
	struct sab_softc *sc = vsc;

	if (sc->sc_child[0] && sc->sc_child[0]->sc_tty)
		sabtty_softintr(sc->sc_child[0]);
	if (sc->sc_child[1] && sc->sc_child[1]->sc_tty)
		sabtty_softintr(sc->sc_child[1]);
}

int
sabtty_match(parent, match, aux)
	struct device *parent;
	void *match, *aux;
{
	struct sabtty_attach_args *sa = aux;

	if (sa->sbt_portno < SAB_NCHAN)
		return (1);
	return (0);
}

void
sabtty_attach(parent, self, aux)
	struct device *parent;
	struct device *self;
	void *aux;
{
	struct sabtty_softc *sc = (struct sabtty_softc *)self;
	struct sabtty_attach_args *sa = aux;
	int r;

	sc->sc_tty = ttymalloc(0);
	sc->sc_tty->t_oproc = sabtty_start;
	sc->sc_tty->t_param = sabtty_param;

	sc->sc_parent = (struct sab_softc *)parent;
	sc->sc_bt = sc->sc_parent->sc_bt;
	sc->sc_portno = sa->sbt_portno;
	sc->sc_rend = sc->sc_rbuf + SABTTY_RBUF_SIZE;

	switch (sa->sbt_portno) {
	case 0:	/* port A */
		sc->sc_pvr_dtr = SAB_PVR_DTR_A;
		sc->sc_pvr_dsr = SAB_PVR_DSR_A;
		r = bus_space_subregion(sc->sc_bt, sc->sc_parent->sc_bh,
		    SAB_CHAN_A, SAB_CHANLEN, &sc->sc_bh);
		break;
	case 1:	/* port B */
		sc->sc_pvr_dtr = SAB_PVR_DTR_B;
		sc->sc_pvr_dsr = SAB_PVR_DSR_B;
		r = bus_space_subregion(sc->sc_bt, sc->sc_parent->sc_bh,
		    SAB_CHAN_B, SAB_CHANLEN, &sc->sc_bh);
		break;
	default:
		printf(": invalid channel: %u\n", sa->sbt_portno);
		return;
	}
	if (r != 0) {
		printf(": failed to allocate register subregion\n");
		return;
	}

	sabtty_console_flags(sc);
	sabtty_console_speed(sc);

	if (sc->sc_flags & (SABTTYF_CONS_IN | SABTTYF_CONS_OUT)) {
		struct termios t;
		char *acc;

		switch (sc->sc_flags & (SABTTYF_CONS_IN | SABTTYF_CONS_OUT)) {
		case SABTTYF_CONS_IN:
			acc = " input";
			break;
		case SABTTYF_CONS_OUT:
			acc = " output";
			break;
		case SABTTYF_CONS_IN|SABTTYF_CONS_OUT:
		default:
			acc = "";
			break;
		}

		if (sc->sc_flags & SABTTYF_CONS_OUT) {
			/* Let current output drain */
			DELAY(100000);
		}

		t.c_ispeed = 0;
		t.c_ospeed = sc->sc_speed;
		t.c_cflag = CREAD | CS8 | HUPCL;
		sc->sc_tty->t_ospeed = 0;
		sabttyparam(sc, sc->sc_tty, &t);

		if (sc->sc_flags & SABTTYF_CONS_IN) {
			sabtty_cons_input = sc;
			cn_tab->cn_pollc = sab_cnpollc;
			cn_tab->cn_getc = sab_cngetc;
			cn_tab->cn_dev = makedev(77/*XXX*/, self->dv_unit);
		}

		if (sc->sc_flags & SABTTYF_CONS_OUT) {
			sabtty_cons_output = sc;
			cn_tab->cn_putc = sab_cnputc;
			cn_tab->cn_dev = makedev(77/*XXX*/, self->dv_unit);
		}
		printf(": console%s", acc);
	} else {
		/* Not a console... */
		sabtty_reset(sc);
	}

	printf("\n");
}

int
sabtty_intr(sc, needsoftp)
	struct sabtty_softc *sc;
	int *needsoftp;
{
	u_int8_t isr0, isr1;
	int i, len = 0, needsoft = 0, r = 0, clearfifo = 0;

	isr0 = SAB_READ(sc, SAB_ISR0);
	isr1 = SAB_READ(sc, SAB_ISR1);

	if (isr0 || isr1)
		r = 1;

	if (isr0 & SAB_ISR0_RPF) {
		len = 32;
		clearfifo = 1;
	}
	if (isr0 & SAB_ISR0_TCD) {
		len = (32 - 1) & SAB_READ(sc, SAB_RBCL);
		clearfifo = 1;
	}
	if (isr0 & SAB_ISR0_TIME) {
		sabtty_cec_wait(sc);
		SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RFRD);
	}
	if (isr0 & SAB_ISR0_RFO) {
		sc->sc_flags |= SABTTYF_RINGOVERFLOW;
		clearfifo = 1;
	}
	if (len != 0) {
		u_int8_t *ptr;

		ptr = sc->sc_rput;
		for (i = 0; i < len; i++) {
			*ptr++ = SAB_READ(sc, SAB_RFIFO);
			if (ptr == sc->sc_rend)
				ptr = sc->sc_rbuf;
			if (ptr == sc->sc_rget) {
				if (ptr == sc->sc_rbuf)
					ptr = sc->sc_rend;
				ptr--;
				sc->sc_flags |= SABTTYF_RINGOVERFLOW;
			}
		}
		sc->sc_rput = ptr;
		needsoft = 1;
	}

	if (clearfifo) {
		sabtty_cec_wait(sc);
		SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RMC);
	}

	if (isr0 & SAB_ISR0_CDSC) {
		sc->sc_flags |= SABTTYF_CDCHG;
		needsoft = 1;
	}

	if (isr1 & SAB_ISR1_BRKT)
		sabtty_abort(sc);

	if (isr1 & (SAB_ISR1_XPR | SAB_ISR1_ALLS)) {
		if ((SAB_READ(sc, SAB_STAR) & SAB_STAR_XFW) &&
		    (sc->sc_flags & SABTTYF_STOP) == 0) {
			if (sc->sc_txc < 32)
				len = sc->sc_txc;
			else
				len = 32;

			if (len > 0) {
				SAB_WRITE_BLOCK(sc, SAB_XFIFO, sc->sc_txp, len);
				sc->sc_txp += len;
				sc->sc_txc -= len;

				sabtty_cec_wait(sc);
				SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_XF);

				/*
				 * Prevent the false end of xmit from
				 * confusing things below.
				 */
				isr1 &= ~SAB_ISR1_ALLS;
			}
		}

		if ((sc->sc_txc == 0) || (sc->sc_flags & SABTTYF_STOP)) {
			if ((sc->sc_imr1 & SAB_IMR1_XPR) == 0) {
				sc->sc_imr1 |= SAB_IMR1_XPR;
				sc->sc_imr1 &= ~SAB_IMR1_ALLS;
				SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
			}
		}
	}

	if ((isr1 & SAB_ISR1_ALLS) && ((sc->sc_txc == 0) ||
	    (sc->sc_flags & SABTTYF_STOP))) {
		if (sc->sc_flags & SABTTYF_TXDRAIN)
			wakeup(sc);
		sc->sc_flags &= ~SABTTYF_STOP;
		sc->sc_flags |= SABTTYF_DONE;
		sc->sc_imr1 |= SAB_IMR1_ALLS;
		SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
		needsoft = 1;
	}

	if (needsoft)
		*needsoftp = needsoft;
	return (r);
}

void
sabtty_softintr(sc)
	struct sabtty_softc *sc;
{
	struct tty *tp = sc->sc_tty;
	int s, flags;
	u_int8_t r;

	if (tp == NULL)
		return;

	if ((tp->t_state & TS_ISOPEN) == 0)
		return;

	while (sc->sc_rget != sc->sc_rput) {
		int data;
		u_int8_t stat;

		data = sc->sc_rget[0];
		stat = sc->sc_rget[1];
		sc->sc_rget += 2;
		if (stat & SAB_RSTAT_PE)
			data |= TTY_PE;
		if (stat & SAB_RSTAT_FE)
			data |= TTY_FE;
		if (sc->sc_rget == sc->sc_rend)
			sc->sc_rget = sc->sc_rbuf;

		(*linesw[tp->t_line].l_rint)(data, tp);
	}

	s = splhigh();
	flags = sc->sc_flags;
	sc->sc_flags &= ~(SABTTYF_DONE|SABTTYF_CDCHG|SABTTYF_RINGOVERFLOW);
	splx(s);

	if (flags & SABTTYF_CDCHG) {
		s = spltty();
		r = SAB_READ(sc, SAB_VSTR) & SAB_VSTR_CD;
		splx(s);

		(*linesw[tp->t_line].l_modem)(tp, r);
	}

	if (flags & SABTTYF_RINGOVERFLOW)
		log(LOG_WARNING, "%s: ring overflow\n", sc->sc_dv.dv_xname);

	if (flags & SABTTYF_DONE) {
		ndflush(&tp->t_outq, sc->sc_txp - tp->t_outq.c_cf);
		tp->t_state &= ~TS_BUSY;
		(*linesw[tp->t_line].l_start)(tp);
	}
}

int
sabttyopen(dev, flags, mode, p)
	dev_t dev;
	int flags, mode;
	struct proc *p;
{
	struct sab_softc *bc;
	struct sabtty_softc *sc;
	struct tty *tp;
	int card = SAB_CARD(dev), port = SAB_PORT(dev), s, s1;

	if (card >= sab_cd.cd_ndevs)
		return (ENXIO);
	bc = sab_cd.cd_devs[card];
	if (bc == NULL)
		return (ENXIO);

	if (port >= bc->sc_nchild)
		return (ENXIO);
	sc = bc->sc_child[port];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	tp->t_dev = dev;

	if ((tp->t_state & TS_ISOPEN) == 0) {
		tp->t_state |= TS_WOPEN;

		ttychars(tp);
		tp->t_iflag = TTYDEF_IFLAG;
		tp->t_oflag = TTYDEF_OFLAG;
		tp->t_cflag = TTYDEF_CFLAG;
		if (sc->sc_openflags & TIOCFLAG_CLOCAL)
			tp->t_cflag |= CLOCAL;
		if (sc->sc_openflags & TIOCFLAG_CRTSCTS)
			tp->t_cflag |= CRTSCTS;
		if (sc->sc_openflags & TIOCFLAG_MDMBUF)
			tp->t_cflag |= MDMBUF;
		tp->t_lflag = TTYDEF_LFLAG;
		if (sc->sc_flags & (SABTTYF_CONS_IN | SABTTYF_CONS_OUT))
			tp->t_ispeed = tp->t_ospeed = sc->sc_speed;
		else
			tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;

		sc->sc_rput = sc->sc_rget = sc->sc_rbuf;

		s = spltty();

		ttsetwater(tp);

		s1 = splhigh();
		sabtty_reset(sc);
		sabtty_param(tp, &tp->t_termios);
		sc->sc_imr0 = SAB_IMR0_PERR | SAB_IMR0_FERR | SAB_IMR0_PLLA;
		SAB_WRITE(sc, SAB_IMR0, sc->sc_imr0);
		sc->sc_imr1 = SAB_IMR1_BRK | SAB_IMR1_ALLS | SAB_IMR1_XDU |
		    SAB_IMR1_TIN | SAB_IMR1_CSC | SAB_IMR1_XMR | SAB_IMR1_XPR;
		SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
		SAB_WRITE(sc, SAB_CCR0, SAB_READ(sc, SAB_CCR0) | SAB_CCR0_PU);
		sabtty_cec_wait(sc);
		SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_XRES);
		sabtty_cec_wait(sc);
		SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RRES);
		sabtty_cec_wait(sc);
		splx(s1);

		sabtty_flush(sc);

		if ((sc->sc_openflags & TIOCFLAG_SOFTCAR) ||
		    (SAB_READ(sc, SAB_VSTR) & SAB_VSTR_CD))
			tp->t_state |= TS_CARR_ON;
		else
			tp->t_state &= ~TS_CARR_ON;
	} else if ((tp->t_state & TS_XCLUDE) &&
	    (!suser(p, 0))) {
		return (EBUSY);
	} else {
		s = spltty();
	}

	if ((flags & O_NONBLOCK) == 0) {
		while ((tp->t_cflag & CLOCAL) == 0 &&
		    (tp->t_state & TS_CARR_ON) == 0) {
			int error;

			tp->t_state |= TS_WOPEN;
			error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH,
			    "sabttycd", 0);
			if (error != 0) {
				splx(s);
				tp->t_state &= ~TS_WOPEN;
				return (error);
			}
		}
	}

	splx(s);

	s = (*linesw[tp->t_line].l_open)(dev, tp, p);
	if (s != 0) {
		if (tp->t_state & TS_ISOPEN)
			return (s);

		if (tp->t_cflag & HUPCL) {
			sabtty_mdmctrl(sc, 0, DMSET);
			(void)tsleep(sc, TTIPRI, ttclos, hz);
		}

		if ((sc->sc_flags & (SABTTYF_CONS_IN | SABTTYF_CONS_OUT)) == 0) {
			/* Flush and power down if we're not the console */
			sabtty_flush(sc);
			sabtty_reset(sc);
		}
	}
	return (s);
}

int
sabttyclose(dev, flags, mode, p)
	dev_t dev;
	int flags, mode;
	struct proc *p;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(dev)];
	struct tty *tp = sc->sc_tty;
	int s;

	(*linesw[tp->t_line].l_close)(tp, flags, p);

	s = spltty();

	if ((tp->t_state & TS_ISOPEN) == 0) {
		/* Wait for output drain */
		sc->sc_imr1 &= ~SAB_IMR1_ALLS;
		SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
		sc->sc_flags |= SABTTYF_TXDRAIN;
		(void)tsleep(sc, TTIPRI, ttclos, 5 * hz);
		sc->sc_imr1 |= SAB_IMR1_ALLS;
		SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
		sc->sc_flags &= ~SABTTYF_TXDRAIN;

		if (tp->t_cflag & HUPCL) {
			sabtty_mdmctrl(sc, 0, DMSET);
			(void)tsleep(bc, TTIPRI, ttclos, hz);
		}

		if ((sc->sc_flags & (SABTTYF_CONS_IN | SABTTYF_CONS_OUT)) == 0) {
			/* Flush and power down if we're not the console */
			sabtty_flush(sc);
			sabtty_reset(sc);
		}
	}

	ttyclose(tp);
	splx(s);

	return (0);
}

int
sabttyread(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(dev)];
	struct tty *tp = sc->sc_tty;

	return ((*linesw[tp->t_line].l_read)(tp, uio, flags));
}

int
sabttywrite(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(dev)];
	struct tty *tp = sc->sc_tty;

	return ((*linesw[tp->t_line].l_write)(tp, uio, flags));
}

int
sabttyioctl(dev, cmd, data, flags, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flags;
	struct proc *p;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(dev)];
	struct tty *tp = sc->sc_tty;
	int error;

	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flags, p);
	if (error >= 0)
		return (error);

	error = ttioctl(tp, cmd, data, flags, p);
	if (error >= 0)
		return (error);

	error = 0;

	switch (cmd) {
	case TIOCSBRK:
		SAB_WRITE(sc, SAB_DAFO,
		    SAB_READ(sc, SAB_DAFO) | SAB_DAFO_XBRK);
		break;
	case TIOCCBRK:
		SAB_WRITE(sc, SAB_DAFO,
		    SAB_READ(sc, SAB_DAFO) & ~SAB_DAFO_XBRK);
		break;
	case TIOCSDTR:
		sabtty_mdmctrl(sc, TIOCM_DTR, DMBIS);
		break;
	case TIOCCDTR:
		sabtty_mdmctrl(sc, TIOCM_DTR, DMBIC);
		break;
	case TIOCMBIS:
		sabtty_mdmctrl(sc, *((int *)data), DMBIS);
		break;
	case TIOCMBIC:
		sabtty_mdmctrl(sc, *((int *)data), DMBIC);
		break;
	case TIOCMGET:
		*((int *)data) = sabtty_mdmctrl(sc, 0, DMGET);
		break;
	case TIOCMSET:
		sabtty_mdmctrl(sc, *((int *)data), DMSET);
		break;
	case TIOCGFLAGS:
		*((int *)data) = sc->sc_openflags;
		break;
	case TIOCSFLAGS:
		if (suser(p, 0))
			error = EPERM;
		else
			sc->sc_openflags = *((int *)data) &
			    (TIOCFLAG_SOFTCAR | TIOCFLAG_CLOCAL |
			     TIOCFLAG_CRTSCTS | TIOCFLAG_MDMBUF);
		break;
	default:
		error = ENOTTY;
	}

	return (error);
}

struct tty *
sabttytty(dev)
	dev_t dev;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(dev)];

	return (sc->sc_tty);
}

int
sabttystop(tp, flags)
	struct tty *tp;
	int flags;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(tp->t_dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(tp->t_dev)];
	int s;

	s = spltty();
	if (tp->t_state & TS_BUSY) {
		if ((tp->t_state & TS_TTSTOP) == 0)
			tp->t_state |= TS_FLUSH;
		sc->sc_flags |= SABTTYF_STOP;
		sc->sc_imr1 &= ~SAB_IMR1_ALLS;
		SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
	}
	splx(s);
	return (0);
}

int
sabtty_mdmctrl(sc, bits, how)
	struct sabtty_softc *sc;
	int bits, how;
{
	u_int8_t r;
	int s;

	s = spltty();
	switch (how) {
	case DMGET:
		bits = 0;
		if (SAB_READ(sc, SAB_STAR) & SAB_STAR_CTS)
			bits |= TIOCM_CTS;
		if ((SAB_READ(sc, SAB_VSTR) & SAB_VSTR_CD) == 0)
			bits |= TIOCM_CD;

		r = SAB_READ(sc, SAB_PVR);
		if ((r & sc->sc_pvr_dtr) == 0)
			bits |= TIOCM_DTR;
		if ((r & sc->sc_pvr_dsr) == 0)
			bits |= TIOCM_DSR;

		r = SAB_READ(sc, SAB_MODE);
		if ((r & (SAB_MODE_RTS|SAB_MODE_FRTS)) == SAB_MODE_RTS)
			bits |= TIOCM_RTS;
		break;
	case DMSET:
		r = SAB_READ(sc, SAB_MODE);
		if (bits & TIOCM_RTS) {
			r &= ~SAB_MODE_FRTS;
			r |= SAB_MODE_RTS;
		} else
			r |= SAB_MODE_FRTS | SAB_MODE_RTS;
		SAB_WRITE(sc, SAB_MODE, r);

		r = SAB_READ(sc, SAB_PVR);
		if (bits & TIOCM_DTR)
			r &= ~sc->sc_pvr_dtr;
		else
			r |= sc->sc_pvr_dtr;
		SAB_WRITE(sc, SAB_PVR, r);
		break;
	case DMBIS:
		if (bits & TIOCM_RTS) {
			r = SAB_READ(sc, SAB_MODE);
			r &= ~SAB_MODE_FRTS;
			r |= SAB_MODE_RTS;
			SAB_WRITE(sc, SAB_MODE, r);
		}
		if (bits & TIOCM_DTR) {
			r = SAB_READ(sc, SAB_PVR);
			r &= ~sc->sc_pvr_dtr;
			SAB_WRITE(sc, SAB_PVR, r);
		}
		break;
	case DMBIC:
		if (bits & TIOCM_RTS) {
			r = SAB_READ(sc, SAB_MODE);
			r |= SAB_MODE_FRTS | SAB_MODE_RTS;
			SAB_WRITE(sc, SAB_MODE, r);
		}
		if (bits & TIOCM_DTR) {
			r = SAB_READ(sc, SAB_PVR);
			r |= sc->sc_pvr_dtr;
			SAB_WRITE(sc, SAB_PVR, r);
		}
		break;
	}
	splx(s);
	return (bits);
}

int
sabttyparam(sc, tp, t)
	struct sabtty_softc *sc;
	struct tty *tp;
	struct termios *t;
{
	int s, ospeed;
	tcflag_t cflag;
	u_int8_t dafo, r;

	ospeed = sabtty_speed(t->c_ospeed);
	if (ospeed < 0 || (t->c_ispeed && t->c_ispeed != t->c_ospeed))
		return (EINVAL);

	s = spltty();

	/* hang up line if ospeed is zero, otherwise raise dtr */
	sabtty_mdmctrl(sc, TIOCM_DTR,
	    (t->c_ospeed == 0) ? DMBIC : DMBIS);

	dafo = SAB_READ(sc, SAB_DAFO);

	cflag = t->c_cflag;

	if (sc->sc_flags & (SABTTYF_CONS_IN | SABTTYF_CONS_OUT)) {
		cflag |= CLOCAL;
		cflag &= ~HUPCL;
	}

	if (cflag & CSTOPB)
		dafo |= SAB_DAFO_STOP;
	else
		dafo &= ~SAB_DAFO_STOP;

	dafo &= ~SAB_DAFO_CHL_CSIZE;
	switch (cflag & CSIZE) {
	case CS5:
		dafo |= SAB_DAFO_CHL_CS5;
		break;
	case CS6:
		dafo |= SAB_DAFO_CHL_CS6;
		break;
	case CS7:
		dafo |= SAB_DAFO_CHL_CS7;
		break;
	default:
		dafo |= SAB_DAFO_CHL_CS8;
		break;
	}

	dafo &= ~SAB_DAFO_PARMASK;
	if (cflag & PARENB) {
		if (cflag & PARODD)
			dafo |= SAB_DAFO_PAR_ODD;
		else
			dafo |= SAB_DAFO_PAR_EVEN;
	} else
		dafo |= SAB_DAFO_PAR_NONE;

	if (ospeed != 0) {
		SAB_WRITE(sc, SAB_BGR, ospeed & 0xff);
		r = SAB_READ(sc, SAB_CCR2);
		r &= ~(SAB_CCR2_BR9 | SAB_CCR2_BR8);
		r |= (ospeed >> 2) & (SAB_CCR2_BR9 | SAB_CCR2_BR8);
		SAB_WRITE(sc, SAB_CCR2, r);
	}

	r = SAB_READ(sc, SAB_MODE);
	r |= SAB_MODE_RAC;
	if (cflag & CRTSCTS) {
		r &= ~(SAB_MODE_RTS | SAB_MODE_FCTS);
		r |= SAB_MODE_FRTS;
		sc->sc_imr1 &= ~SAB_IMR1_CSC;
	} else {
		r |= SAB_MODE_RTS | SAB_MODE_FCTS;
		r &= ~SAB_MODE_FRTS;
		sc->sc_imr1 |= SAB_IMR1_CSC;
	}
	SAB_WRITE(sc, SAB_MODE, r);
	SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);

	tp->t_cflag = cflag;

	splx(s);
	return (0);
}

int
sabtty_param(tp, t)
	struct tty *tp;
	struct termios *t;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(tp->t_dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(tp->t_dev)];

	return (sabttyparam(sc, tp, t));
}

void
sabtty_start(tp)
	struct tty *tp;
{
	struct sab_softc *bc = sab_cd.cd_devs[SAB_CARD(tp->t_dev)];
	struct sabtty_softc *sc = bc->sc_child[SAB_PORT(tp->t_dev)];
	int s;

	s = spltty();
	if ((tp->t_state & (TS_TTSTOP | TS_TIMEOUT | TS_BUSY)) == 0) {
		ttwakeupwr(tp);
		if (tp->t_outq.c_cc) {
			sc->sc_txc = ndqb(&tp->t_outq, 0);
			sc->sc_txp = tp->t_outq.c_cf;
			tp->t_state |= TS_BUSY;
			sc->sc_imr1 &= ~(SAB_ISR1_XPR | SAB_ISR1_ALLS);
			SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
		}
	}
	splx(s);
}

int
sabtty_cec_wait(struct sabtty_softc *sc)
{
	int i = 50000;

	for (;;) {
		if ((SAB_READ(sc, SAB_STAR) & SAB_STAR_CEC) == 0)
			return (0);
		if (--i == 0)
			return (1);
		DELAY(1);
	}
}

int
sabtty_tec_wait(struct sabtty_softc *sc)
{
	int i = 200000;

	for (;;) {
		if ((SAB_READ(sc, SAB_STAR) & SAB_STAR_TEC) == 0)
			return (0);
		if (--i == 0)
			return (1);
		DELAY(1);
	}
}

void
sabtty_reset(sc)
	struct sabtty_softc *sc;
{
	/* power down */
	SAB_WRITE(sc, SAB_CCR0, 0);

	/* set basic configuration */
	SAB_WRITE(sc, SAB_CCR0,
	    SAB_CCR0_MCE | SAB_CCR0_SC_NRZ | SAB_CCR0_SM_ASYNC);
	SAB_WRITE(sc, SAB_CCR1, SAB_CCR1_ODS | SAB_CCR1_BCR | SAB_CCR1_CM_7);
	SAB_WRITE(sc, SAB_CCR2, SAB_CCR2_BDF | SAB_CCR2_SSEL | SAB_CCR2_TOE);
	SAB_WRITE(sc, SAB_CCR3, 0);
	SAB_WRITE(sc, SAB_CCR4, SAB_CCR4_MCK4 | SAB_CCR4_EBRG);
	SAB_WRITE(sc, SAB_MODE, SAB_MODE_RTS | SAB_MODE_FCTS | SAB_MODE_RAC);
	SAB_WRITE(sc, SAB_RFC,
	    SAB_RFC_DPS | SAB_RFC_RFDF | SAB_RFC_RFTH_32CHAR);

	/* clear interrupts */
	sc->sc_imr0 = sc->sc_imr1 = 0xff;
	SAB_WRITE(sc, SAB_IMR0, sc->sc_imr0);
	SAB_WRITE(sc, SAB_IMR1, sc->sc_imr1);
	SAB_READ(sc, SAB_ISR0);
	SAB_READ(sc, SAB_ISR1);
}

void
sabtty_flush(sc)
	struct sabtty_softc *sc;
{
	/* clear rx fifo */
	sabtty_cec_wait(sc);
	SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RRES);

	/* clear tx fifo */
	sabtty_cec_wait(sc);
	SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_XRES);
}

int
sabtty_speed(rate)
	int rate;
{
	int i, len, r;

	if (rate == 0)
		return (0);
	len = sizeof(sabtty_baudtable)/sizeof(sabtty_baudtable[0]);
	for (i = 0; i < len; i++) {
		if (rate == sabtty_baudtable[i].baud) {
			r = sabtty_baudtable[i].n |
			    (sabtty_baudtable[i].m << 6);
			return (r);
		}
	}
	return (-1);
}

void
sabtty_cnputc(sc, c)
	struct sabtty_softc *sc;
	int c;
{
	sabtty_tec_wait(sc);
	SAB_WRITE(sc, SAB_TIC, c);
	sabtty_tec_wait(sc);
}

int
sabtty_cngetc(sc)
	struct sabtty_softc *sc;
{
	u_int8_t r, len, ipc;

	ipc = SAB_READ(sc, SAB_IPC);
	SAB_WRITE(sc, SAB_IPC, ipc | SAB_IPC_VIS);

again:
	do {
		r = SAB_READ(sc, SAB_STAR);
	} while ((r & SAB_STAR_RFNE) == 0);

	/*
	 * Ok, at least one byte in RFIFO, ask for permission to access RFIFO
	 * (I hate this chip... hate hate hate).
	 */
	sabtty_cec_wait(sc);
	SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RFRD);

	/* Wait for RFIFO to come ready */
	do {
		r = SAB_READ(sc, SAB_ISR0);
	} while ((r & SAB_ISR0_TCD) == 0);

	len = SAB_READ(sc, SAB_RBCL) & (32 - 1);
	if (len == 0)
		goto again;	/* Shouldn't happen... */

	r = SAB_READ(sc, SAB_RFIFO);

	/*
	 * Blow away everything left in the FIFO...
	 */
	sabtty_cec_wait(sc);
	SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RMC);
	SAB_WRITE(sc, SAB_IPC, ipc);
	return (r);
}

void
sabtty_cnpollc(sc, on)
	struct sabtty_softc *sc;
	int on;
{
	u_int8_t r;

	if (on) {
		if (sc->sc_polling)
			return;
		SAB_WRITE(sc, SAB_IPC, SAB_READ(sc, SAB_IPC) | SAB_IPC_VIS);
		r = sc->sc_pollrfc = SAB_READ(sc, SAB_RFC);
		r &= ~(SAB_RFC_RFDF);
		SAB_WRITE(sc, SAB_RFC, r);
		sabtty_cec_wait(sc);
		SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RRES);
		sc->sc_polling = 1;
	} else {
		if (!sc->sc_polling)
			return;
		SAB_WRITE(sc, SAB_IPC, SAB_READ(sc, SAB_IPC) & ~SAB_IPC_VIS);
		SAB_WRITE(sc, SAB_RFC, sc->sc_pollrfc);
		sabtty_cec_wait(sc);
		SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RRES);
		sc->sc_polling = 0;
	}
}

void
sab_cnputc(dev, c)
	dev_t dev;
	int c;
{
	struct sabtty_softc *sc = sabtty_cons_output;

	if (sc == NULL)
		return;
	sabtty_cnputc(sc, c);
}

void
sab_cnpollc(dev, on)
	dev_t dev;
	int on;
{
	struct sabtty_softc *sc = sabtty_cons_input;

	sabtty_cnpollc(sc, on);
}

int
sab_cngetc(dev)
	dev_t dev;
{
	struct sabtty_softc *sc = sabtty_cons_input;

	if (sc == NULL)
		return (-1);
	return (sabtty_cngetc(sc));
}

void
sabtty_console_flags(sc)
	struct sabtty_softc *sc;
{
	int node, channel, options, cookie;
	char buf[255];

	node = sc->sc_parent->sc_node;
	channel = sc->sc_portno;

	options = OF_finddevice("/options");

	/* Default to channel 0 if there are no explicit prom args */
	cookie = 0;

	if (node == OF_instance_to_package(OF_stdin())) {
		if (OF_getprop(options, "input-device", buf,
		    sizeof(buf)) != -1) {
			if (strncmp("ttyb", buf, strlen("ttyb")) == 0)
				cookie = 1;
		}

		if (channel == cookie)
			sc->sc_flags |= SABTTYF_CONS_IN;
	}

	/* Default to same channel if there are no explicit prom args */

	if (node == OF_instance_to_package(OF_stdout())) {
		if (OF_getprop(options, "output-device", buf,
		    sizeof(buf)) != -1) {
			if (strncmp("ttyb", buf, strlen("ttyb")) == 0)
				cookie = 1;
		}

		if (channel == cookie)
			sc->sc_flags |= SABTTYF_CONS_OUT;
	}
}

void
sabtty_console_speed(sc)
	struct sabtty_softc *sc;
{
	char *name;
	int node, channel, options;

	node = sc->sc_parent->sc_node;
	channel = sc->sc_portno;

	if (getpropint(node, "ssp-console", -1) == channel) {
		sc->sc_speed = getpropspeed(node, "ssp-console-modes");
		return;
	}
	if (getpropint(node, "ssp-control", -1) == channel) {
		sc->sc_speed = getpropspeed(node, "ssp-control-modes");
		return;
	}

	options = OF_finddevice("/options");
	name = sc->sc_portno ? "ttyb-mode" : "ttya-mode";
	sc->sc_speed = getpropspeed(options, name);
}

void
sabtty_abort(sc)
	struct sabtty_softc *sc;
{

	if (sc->sc_flags & SABTTYF_CONS_IN) {
#ifdef DDB
		extern int db_active, db_console;

		if (db_console == 0)
			return;
		if (db_active == 0)
			Debugger();
		else
			callrom();
#else
		callrom();
#endif
	}
}

void
sabtty_shutdown(struct sabtty_softc *sc)
{
	/* Have to put the chip back into single char mode */
	sc->sc_flags |= SABTTYF_DONTDDB;
	SAB_WRITE(sc, SAB_RFC, SAB_READ(sc, SAB_RFC) & ~SAB_RFC_RFDF);
	sabtty_cec_wait(sc);
	SAB_WRITE(sc, SAB_CMDR, SAB_CMDR_RRES);
	sabtty_cec_wait(sc);
	SAB_WRITE(sc, SAB_IPC, SAB_READ(sc, SAB_IPC) | SAB_IPC_VIS);
}


code:
/*	$OpenBSD: sab82532reg.h,v 1.3 2003/06/02 20:02:49 jason Exp $	*/

/*
 * Copyright (c) 2001 Jason L. Wright (jason@thought.net)
 * 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.
 *
 * 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.
 *
 * Effort sponsored in part by the Defense Advanced Research Projects
 * Agency (DARPA) and Air Force Research Laboratory, Air Force
 * Materiel Command, USAF, under agreement number F30602-01-2-0537.
 *
 */

/*
 * Register definitions for SAB82532 based on "Enhanced Serial Communication
 * Controller ESCC2 Version 3.2 User's Manual 07.96" from:
 * http://www.infineon.com
 */

#define	SAB_NCHAN	2	/* number of channels */
#define	SAB_CHANLEN	0x40	/* length of channel register set */

#define	SAB_CHAN_A	0x00	/* channel A register offset */
#define	SAB_CHAN_B	0x40	/* channel B register offset */

#define	SAB_RFIFO	0x00	/* r: rx fifo */
#define	SAB_XFIFO	0x00	/* w: tx fifo */
#define	SAB_STAR	0x20	/* r: status register */
#define	SAB_CMDR	0x20	/* w: command register */
#define	SAB_MODE	0x22	/* rw: mode register */
#define	SAB_TIMR	0x23	/* rw: timer register */
#define	SAB_XON		0x24	/* rw: xon character */
#define	SAB_XOFF	0x25	/* rw: xoff character */
#define	SAB_TCR		0x26	/* rw: termination character */
#define	SAB_DAFO	0x27	/* rw: data format */
#define	SAB_RFC		0x28	/* rw: rfifo control register */
#define	SAB_RBCL	0x2a	/* r: rx byte count low */
#define	SAB_TBCL	0x2a	/* w: tx byte count low */
#define	SAB_RBCH	0x2b	/* r: rx byte count high */
#define	SAB_XBCH	0x2b	/* w: tx byte count high */
#define	SAB_CCR0	0x2c	/* rw: channel configuration register 0 */
#define	SAB_CCR1	0x2d	/* rw: channel configuration register 1 */
#define	SAB_CCR2	0x2e	/* rw: channel configuration register 2 */
#define	SAB_CCR3	0x2f	/* rw: channel configuration register 3 */
#define	SAB_TSAX	0x30	/* w: time-slot assignment register tx */
#define	SAB_TSAR	0x31	/* w: time-slot assignment register rx */
#define	SAB_XCCR	0x32	/* w: tx channel capacity register */
#define	SAB_RCCR	0x33	/* w: receive channel capacity register */
#define	SAB_VSTR	0x34	/* r: version status */
#define	SAB_BGR		0x34	/* w: baud rate generator */
#define	SAB_TIC		0x35	/* w: transmit immediate character */
#define	SAB_MXN		0x36	/* w: mask xon character */
#define	SAB_MXF		0x37	/* w: mask xoff character */
#define	SAB_GIS		0x38	/* r: global interrupt status */
#define	SAB_IVA		0x38	/* w: interrupt vector address */
#define	SAB_IPC		0x39	/* rw: interrupt port configuration */
#define	SAB_ISR0	0x3a	/* r: interrupt status 0 */
#define	SAB_IMR0	0x3a	/* w: interrupt mask 0 */
#define	SAB_ISR1	0x3b	/* r: interrupt status 1 */
#define	SAB_IMR1	0x3b	/* w: interrupt mask 1 */
#define	SAB_PVR		0x3c	/* rw: port value register */
#define	SAB_PIS		0x3d	/* r: port interrupt status */
#define	SAB_PIM		0x3d	/* w: port interrupt mask */
#define	SAB_PCR		0x3e	/* w: port configuration register */
#define	SAB_CCR4	0x3f	/* rw: channel configuration register 4 */

/* SAB_STAR: status register */
#define	SAB_STAR_XDOV	0x80	/* transmit data overflow */
#define	SAB_STAR_XFW	0x40	/* transmit fifo write enable */
#define	SAB_STAR_RFNE	0x20	/* rfifo not empty */
#define	SAB_STAR_FCS	0x10	/* flow control status */
#define	SAB_STAR_TEC	0x08	/* tx immediate char is executing */
#define	SAB_STAR_CEC	0x04	/* command is executing */
#define	SAB_STAR_CTS	0x02	/* cts status: 0:inactive/high,1:active/low */

/* SAB_CMDR: command register */
#define	SAB_CMDR_RMC	0x80	/* receive message complete */
#define	SAB_CMDR_RRES	0x40	/* receiver reset */
#define	SAB_CMDR_RFRD	0x20	/* receive fifo read enable */
#define	SAB_CMDR_STI	0x10	/* start timer */
#define	SAB_CMDR_XF	0x08	/* transmit frame */
#define	SAB_CMDR_XRES	0x01	/* transmit reset */

/* SAB_MODE: mode register */
#define	SAB_MODE_FRTS	0x40	/* flow control using rts */
#define	SAB_MODE_FCTS	0x20	/* flow control using cts */
#define	SAB_MODE_FLON	0x10	/* flow control on */
#define	SAB_MODE_RAC	0x08	/* receiver active */
#define	SAB_MODE_RTS	0x04	/* request to send */
#define	SAB_MODE_TRS	0x02	/* timer resolution */
#define	SAB_MODE_TLP	0x01	/* test loop */

/* SAB_TIMR: timer register */
#define	SAB_TIMR_CNT	0xe0	/* count mask */
#define	SAB_TIMR_VAL	0x1f	/* value mask */

/* SAB_DAFO: data format */
#define	SAB_DAFO_XBRK	0x40	/* transmit break */
#define	SAB_DAFO_STOP	0x20	/* stop bit: 0:1 bit, 1:2 bits */
#define	SAB_DAFO_PAR1	0x10	/* parity 1, see below */
#define	SAB_DAFO_PAR0	0x08	/* parity 0, see below */
#define	SAB_DAFO_PARE	0x04	/* parity enable */
#define	SAB_DAFO_CHL1	0x02	/* character length 1, see below */
#define	SAB_DAFO_CHL0	0x01	/* character length 0, see below */

#define	SAB_DAFO_CHL_CSIZE	(SAB_DAFO_CHL1|SAB_DAFO_CHL0)
#define	SAB_DAFO_CHL_CS5	(SAB_DAFO_CHL1|SAB_DAFO_CHL0)
#define	SAB_DAFO_CHL_CS6	(SAB_DAFO_CHL1)
#define	SAB_DAFO_CHL_CS7	(SAB_DAFO_CHL0)
#define	SAB_DAFO_CHL_CS8	(0)

#define	SAB_DAFO_PARMASK	(SAB_DAFO_PAR1|SAB_DAFO_PAR0|SAB_DAFO_PARE)
#define	SAB_DAFO_PAR_MARK	(SAB_DAFO_PAR1|SAB_DAFO_PAR0|SAB_DAFO_PARE)
#define	SAB_DAFO_PAR_EVEN	(SAB_DAFO_PAR1|SAB_DAFO_PARE)
#define	SAB_DAFO_PAR_ODD	(SAB_DAFO_PAR0|SAB_DAFO_PARE)
#define	SAB_DAFO_PAR_SPACE	(SAB_DAFO_PARE)
#define	SAB_DAFO_PAR_NONE	(0)

/* SAB_RFC: rfifo control register */
#define	SAB_RFC_DPS	0x40	/* disable parity storage */
#define	SAB_RFC_DXS	0x20	/* disable storage of xon/xoff characters */
#define	SAB_RFC_RFDF	0x10	/* rfifo data format: 0 data,1 data+stat */
#define	SAB_RFC_RFTH1	0x08	/* rfifo threshold level 1, see below */
#define	SAB_RFC_RFTH0	0x04	/* rfifo threshold level 0, see below */
#define	SAB_RFC_TCDE	0x01	/* termination character detection enable */

#define	SAB_RFC_RFTH_MASK	(SAB_RFC_RFTH1|SAB_RFC_RFTH0)
#define	SAB_RFC_RFTH_32CHAR	(SAB_RFC_RFTH1|SAB_RFC_RFTH0)
#define	SAB_RFC_RFTH_16CHAR	(SAB_RFC_RFTH1)
#define	SAB_RFC_RFTH_4CHAR	(SAB_RFC_RFTH0)
#define	SAB_RFC_RFTH_1CHAR	(0)

/* SAB_RBCH: received byte count high */
#define	SAB_RBCH_DMA	0x80	/* read back of XBCH DMA bit */
#define	SAB_RBCH_CAS	0x20	/* read back of XBCH CAS bit */
#define	SAB_RBCH_CNT	0x0f	/* ms 4 bits of rx byte count (not used) */

/* SAB_XBCH: transmit byte count high */
#define	SAB_XBCH_DMA	0x80	/* dma mode: 1:dma, 0:interrupt */
#define	SAB_XBCH_CAS	0x20	/* carrier detect auto-start */
#define	SAB_XBCH_XC	0x10	/* transmit continuously */
#define	SAB_XBCH_CNT	0x0f	/* ms 4 bits of tx byte count */

/* SAB_CCR0: channel configuration register 0 */
#define	SAB_CCR0_PU	0x80	/* 0:power-down, 1:power-up */
#define	SAB_CCR0_MCE	0x40	/* master clock enable */
#define	SAB_CCR0_SC2	0x10	/* serial port config 2, see below */
#define	SAB_CCR0_SC1	0x08	/* serial port config 1, see below */
#define	SAB_CCR0_SC0	0x04	/* serial port config 0, see below */
#define	SAB_CCR0_SM1	0x02	/* serial mode 1, see below */
#define	SAB_CCR0_SM0	0x01	/* serial mode 0, see below */

#define	SAB_CCR0_SC_MASK	(SAB_CCR0_SC2|SAB_CCR0_SC1|SAB_CCR0_SC0)
#define	SAB_CCR0_SC_NRZ		(0)
#define	SAB_CCR0_SC_NRZI	(SAB_CCR0_SC1)
#define	SAB_CCR0_SC_FM0		(SAB_CCR0_SC2)
#define	SAB_CCR0_SC_FM1		(SAB_CCR0_SC2|SAB_CCR0_SC0)
#define	SAB_CCR0_SC_MANCHESTER	(SAB_CCR0_SC2|SAB_CCR0_SC1)

#define	SAB_CCR0_SM_MASK	(SAB_CCR0_SM1|SAB_CCR0_SM0)
#define	SAB_CCR0_SM_DLC		(0)
#define	SAB_CCR0_SM_DLCLOOP	(SAB_CCR0_SM0)
#define	SAB_CCR0_SM_BISYNC	(SAB_CCR0_SM1)
#define	SAB_CCR0_SM_ASYNC	(SAB_CCR0_SM1|SAB_CCR0_SM0)

/* SAB_CCR1: channel configuration register 1 */
#define	SAB_CCR1_ODS	0x10	/* Output driver select:1:pushpull,0:odrain */
#define	SAB_CCR1_BCR	0x08	/* bit clock rate: 1:async, 0:isochronous */
#define	SAB_CCR1_CM2	0x04	/* clock mode 2, see below */
#define	SAB_CCR1_CM1	0x02	/* clock mode 1, see below */
#define	SAB_CCR1_CM0	0x01	/* clock mode 0, see below */

#define	SAB_CCR1_CM_MASK	(SAB_CCR1_CM2|SAB_CCR1_CM1|SAB_CCR1_CM0)
#define	SAB_CCR1_CM_7		(SAB_CCR1_CM2|SAB_CCR1_CM1|SAB_CCR1_CM0)

/* SAB_CCR2: channel configuration register 2, depends on clock mode above */
/* clock mode 0a, 1, 4, 5 */
#define	SAB_CCR2_SOC1	0x80	/* special output 1, below */
#define	SAB_CCR2_SOC0	0x40	/* special output 0, below */
#define	SAB_CCR2_SOC_MASK	(SAB_CCR2_SOC1|SAB_CCR2_SOC0)
#define	SAB_CCR2_SOC_RTSHIGH	(SAB_CCR2_SOC1)
#define	SAB_CCR2_SOC_RTSNORM	(0)
#define	SAB_CCR2_SOC_RTSRX	(SAB_CCR2_SOC1|SAB_CCR2_SOC0)
/* clock mode 0b, 2, 3, 6, 7 */
#define	SAB_CCR2_BR9	0x80	/* baud rate bit 9 */
#define	SAB_CCR2_BR8	0x40	/* baud rate bit 8 */
#define	SAB_CCR2_BDF	0x20	/* baud rate division factor: 0:1: 1:BRG */
#define	SAB_CCR2_SSEL	0x10	/* clock source select */
/* clock mode 5 */
#define	SAB_CCR2_XCS0	0x20	/* tx clock shift, bit 0 */
#define	SAB_CCR2_RCS0	0x10	/* rx clock shift, bit 0 */
/* clock mode 0b, 2, 3, 4, 5, 6, 7 */
#define	SAB_CCR2_TOE	0x08	/* tx clock output enable */
/* clock mode 0a, 0b, 1, 2, 3, 4, 5, 6, 7 */
#define	SAB_CCR2_RWX	0x04	/* read/write exchange (dma mode only) */
#define	SAB_CCR2_DIV	0x01	/* data inversion (nrz) */

/* SAB_CCR3: channel configuration register 3 (v2 or greater) */
#define	SAB_CCR3_PSD	0x01	/* dpll phase shift disable (nrz/nrzi) */

/* SAB_TSAX: time-slot assignment register transmit (clock mode 5 only) */
#define	SAB_TSAX_TSNX	0xfc	/* time-slot number transmit */
#define	SAB_TSAX_XCS2	0x02	/* transmit clock shift bit 2 */
#define	SAB_TSAX_XCS1	0x01	/* transmit clock shift bit 1 */

/* SAB_TSAR: time-slot assignment register receive (clock mode 5 only) */
#define	SAB_TSAR_TSNR	0xfc	/* time-slot number receive */
#define	SAB_TSAR_RCS2	0x02	/* receive clock shift bit 2 */
#define	SAB_TSAR_RCS1	0x01	/* receive clock shift bit 1 */

/* SAB_VSTR: version status register */
#define	SAB_VSTR_CD	0x80	/* carrier detect status */
#define	SAB_VSTR_DPLA	0x40	/* dpll asynchronous */
#define	SAB_VSTR_VMASK	0x0f	/* chip version mask: */
#define	SAB_VSTR_V_1	0x00	/*   version 1 */
#define	SAB_VSTR_V_2	0x01	/*   version 2 */
#define	SAB_VSTR_V_32	0x02	/*   version 3.2 */

/* SAB_GIS: global interrupt status register */
#define	SAB_GIS_PI	0x80	/* universal port interrupt */
#define	SAB_GIS_ISA1	0x08	/* interrupt status a1 */
#define	SAB_GIS_ISA0	0x04	/* interrupt status a0 */
#define	SAB_GIS_ISB1	0x02	/* interrupt status b1 */
#define	SAB_GIS_ISB0	0x01	/* interrupt status b0 */

/* SAB_IVA: interrupt vector address */
#define	SAB_IVA_MASK	0xf8	/* interrupt vector address mask */

/* SAB_IPC: interrupt port configuration */
#define	SAB_IPC_VIS	0x80	/* masked interrupt bits visible */
#define	SAB_IPC_SLAMASK	0x18	/* slave address mask */
#define	SAB_IPC_CASM	0x04	/* cascading mode */
#define	SAB_IPC_ICMASK	0x03	/* port config mask: */
#define	SAB_IPC_ICOD	0x00	/*   open drain output */
#define	SAB_IPC_ICPL	0x01	/*   push/pull active low output */
#define	SAB_IPC_ICPH	0x03	/*   push/pull active high output */

/* SAB_ISR0: interrupt status 0 */
#define	SAB_ISR0_TCD	0x80	/* termination character detected */
#define	SAB_ISR0_TIME	0x40	/* time-out limit exceeded */
#define	SAB_ISR0_PERR	0x20	/* parity error */
#define	SAB_ISR0_FERR	0x10	/* framing error */
#define	SAB_ISR0_PLLA	0x08	/* dpll asynchronous */
#define	SAB_ISR0_CDSC	0x04	/* carrier detect status change */
#define	SAB_ISR0_RFO	0x02	/* rfifo overflow */
#define	SAB_ISR0_RPF	0x01	/* receive pool full */

/* SAB_ISR1: interrupt status 1 */
#define	SAB_ISR1_BRK	0x80	/* break detected */
#define	SAB_ISR1_BRKT	0x40	/* break terminated */
#define	SAB_ISR1_ALLS	0x20	/* all sent */
#define	SAB_ISR1_XOFF	0x10	/* xoff detected */
#define	SAB_ISR1_TIN	0x08	/* timer interrupt */
#define	SAB_ISR1_CSC	0x04	/* clear to send status change */
#define	SAB_ISR1_XON	0x02	/* xon detected */
#define	SAB_ISR1_XPR	0x01	/* transmit pool ready */

/* SAB_IMR0: interrupt mask 0 */
#define	SAB_IMR0_TCD	0x80	/* termination character detected */
#define	SAB_IMR0_TIME	0x40	/* time-out limit exceeded */
#define	SAB_IMR0_PERR	0x20	/* parity error */
#define	SAB_IMR0_FERR	0x10	/* framing error */
#define	SAB_IMR0_PLLA	0x08	/* dpll asynchronous */
#define	SAB_IMR0_CDSC	0x04	/* carrier detect status change */
#define	SAB_IMR0_RFO	0x02	/* rfifo overflow */
#define	SAB_IMR0_RPF	0x01	/* receive pool full */

/* SAB_ISR1: interrupt mask 1 */
#define	SAB_IMR1_BRK	0x80	/* break detected */
#define	SAB_IMR1_BRKT	0x40	/* break terminated */
#define	SAB_IMR1_ALLS	0x20	/* all sent */
#define	SAB_IMR1_XDU	0x10	/* xoff detected */
#define	SAB_IMR1_TIN	0x08	/* timer interrupt */
#define	SAB_IMR1_CSC	0x04	/* clear to send status change */
#define	SAB_IMR1_XMR	0x02	/* xon detected */
#define	SAB_IMR1_XPR	0x01	/* transmit pool ready */

/* SAB_PVR: port value register */
#define	SAB_PVR_DSR_A	0x01	/* port A DSR */
#define	SAB_PVR_DTR_A	0x02	/* port A DTR */
#define	SAB_PVR_DTR_B	0x04	/* port B DTR */
#define	SAB_PVR_DSR_B	0x08	/* port B DSR */
#define	SAB_PVR_MAGIC	0x10	/* dunno... */

/* SAB_CCR4: channel configuration register 4 */
#define	SAB_CCR4_MCK4	0x80	/* master clock divide by 4 */
#define	SAB_CCR4_EBRG	0x40	/* enhanced baud rate generator mode */
#define	SAB_CCR4_TST1	0x20	/* test pin */
#define	SAB_CCR4_ICD	0x10	/* invert polarity of carrier detect */

/* Receive status byte */
#define	SAB_RSTAT_PE	0x80	/* parity error */
#define	SAB_RSTAT_FE	0x40	/* framing error */
#define	SAB_RSTAT_PAR	0x01	/* parity bit */

license: unknown


code:
/*	$OpenBSD: sbbc.c,v 1.11 2012/10/20 12:00:33 miod Exp $	*/
/*
 * Copyright (c) 2008 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/conf.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/timeout.h>
#include <sys/tty.h>
#include <sys/systm.h>

#ifdef DDB
#include <ddb/db_var.h>
#endif

#include <machine/autoconf.h>
#include <machine/conf.h>
#include <machine/openfirm.h>
#include <machine/sparc64.h>

#include <dev/cons.h>

#include <dev/pci/pcidevs.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>

#include <dev/clock_subr.h>

extern todr_chip_handle_t todr_handle;

#define SBBC_PCI_BAR	PCI_MAPREG_START

#define SBBC_REGS_OFFSET	0x800000
#define SBBC_REGS_SIZE		0x6230
#define SBBC_EPLD_OFFSET	0x8e0000
#define SBBC_EPLD_SIZE		0x20
#define SBBC_SRAM_OFFSET	0x900000
#define SBBC_SRAM_SIZE		0x20000	/* 128KB SRAM */

#define SBBC_PCI_INT_STATUS	0x2320
#define SBBC_PCI_INT_ENABLE	0x2330
#define SBBC_PCI_ENABLE_INT_A	0x11

#define SBBC_EPLD_INTERRUPT	0x13
#define SBBC_EPLD_INTERRUPT_ON	0x01

#define SBBC_SRAM_CONS_IN		0x00000001
#define SBBC_SRAM_CONS_OUT		0x00000002
#define SBBC_SRAM_CONS_BRK		0x00000004
#define SBBC_SRAM_CONS_SPACE_IN		0x00000008
#define SBBC_SRAM_CONS_SPACE_OUT	0x00000010

#define SBBC_MAX_TAGS	32

struct sbbc_sram_tag {
	char		tag_key[8];
	uint32_t	tag_size;
	uint32_t	tag_offset;
};

struct sbbc_sram_toc {
	char			toc_magic[8];
	uint8_t			toc_reserved;
	uint8_t			toc_type;
	uint16_t		toc_version;
	uint32_t		toc_ntags;
	struct sbbc_sram_tag 	toc_tag[SBBC_MAX_TAGS];
};

/* Time of day service. */
struct sbbc_sram_tod {
	uint32_t	tod_magic;
	uint32_t	tod_version;
	uint64_t	tod_time;
	uint64_t	tod_skew;
	uint32_t	tod_reserved;
	uint32_t	tod_heartbeat;
	uint32_t	tod_timeout;
};

#define SBBC_TOD_MAGIC		0x54443100 /* "TD1" */
#define SBBC_TOD_VERSION	1

/* Console service. */
struct sbbc_sram_cons {
	uint32_t cons_magic;
	uint32_t cons_version;
	uint32_t cons_size;

	uint32_t cons_in_begin;
	uint32_t cons_in_end;
	uint32_t cons_in_rdptr;
	uint32_t cons_in_wrptr;

	uint32_t cons_out_begin;
	uint32_t cons_out_end;
	uint32_t cons_out_rdptr;
	uint32_t cons_out_wrptr;
};

#define SBBC_CONS_MAGIC		0x434f4e00 /* "CON" */
#define SBBC_CONS_VERSION	1

struct sbbc_softc {
	struct device		sc_dv;
	bus_space_tag_t		sc_iot;
	bus_space_handle_t	sc_regs_ioh;
	bus_space_handle_t	sc_epld_ioh;
	bus_space_handle_t	sc_sram_ioh;
	caddr_t			sc_sram;
	uint32_t		sc_sram_toc;
	void *			sc_ih;

	struct sparc_bus_space_tag sc_bbt;

	struct tty		*sc_tty;
	caddr_t			sc_sram_cons;
	uint32_t		*sc_sram_solscie;
	uint32_t		*sc_sram_solscir;
	uint32_t		*sc_sram_scsolie;
	uint32_t		*sc_sram_scsolir;
	void			*sc_cons_si;
};

struct sbbc_softc *sbbc_cons_input;
struct sbbc_softc *sbbc_cons_output;

int	sbbc_match(struct device *, void *, void *);
void	sbbc_attach(struct device *, struct device *, void *);

struct cfattach sbbc_ca = {
	sizeof(struct sbbc_softc), sbbc_match, sbbc_attach
};

struct cfdriver sbbc_cd = {
	NULL, "sbbc", DV_DULL
};

int	sbbc_intr(void *);
void	sbbc_send_intr(struct sbbc_softc *sc);

void	sbbc_attach_tod(struct sbbc_softc *, uint32_t);
int	sbbc_tod_gettime(todr_chip_handle_t, struct timeval *);
int	sbbc_tod_settime(todr_chip_handle_t, struct timeval *);

void	sbbc_attach_cons(struct sbbc_softc *, uint32_t);
void	sbbc_intr_cons(struct sbbc_softc *, uint32_t);
void	sbbc_softintr_cons(void *);
int	sbbc_cnlookc(dev_t, int *);
int	sbbc_cngetc(dev_t);
void	sbbc_cnputc(dev_t, int);
void	sbbcstart(struct tty *);
int	sbbcparam(struct tty *, struct termios *);

int
sbbc_match(struct device *parent, void *match, void *aux)
{
	struct pci_attach_args *pa = aux;

	if (PCI_VENDOR(pa->pa_id) == PCI_VENDOR_SUN &&
	    (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_SUN_SBBC))
		return (1);

	return (0);
}

void
sbbc_attach(struct device *parent, struct device *self, void *aux)
{
	struct sbbc_softc *sc = (void *)self;
	struct pci_attach_args *pa = aux;
	struct sbbc_sram_toc *toc;
	bus_addr_t base;
	bus_size_t size;
	pci_intr_handle_t ih;
	int chosen, iosram;
	int i;

	/* XXX Don't byteswap. */
	sc->sc_bbt = *pa->pa_memt;
	sc->sc_bbt.sasi = ASI_PRIMARY;
	sc->sc_iot = &sc->sc_bbt;

	if (pci_mapreg_info(pa->pa_pc, pa->pa_tag, SBBC_PCI_BAR,
	    PCI_MAPREG_TYPE_MEM, &base, &size, NULL)) {
		printf(": can't find register space\n");
		return;
	}

	if (bus_space_map(sc->sc_iot, base + SBBC_REGS_OFFSET,
	    SBBC_REGS_SIZE, 0, &sc->sc_regs_ioh)) {
		printf(": can't map register space\n");
		return;
	}

	if (bus_space_map(sc->sc_iot, base + SBBC_EPLD_OFFSET,
	    SBBC_EPLD_SIZE, 0, &sc->sc_epld_ioh)) {
		printf(": can't map EPLD registers\n");
		goto unmap_regs;
	}

	if (bus_space_map(sc->sc_iot, base + SBBC_SRAM_OFFSET,
	    SBBC_SRAM_SIZE, 0, &sc->sc_sram_ioh)) {
		printf(": can't map SRAM\n");
		goto unmap_epld;
	}

	if (pci_intr_map(pa, &ih)) {
		printf(": unable to map interrupt\n");
		goto unmap_sram;
	}
	printf(": %s\n", pci_intr_string(pa->pa_pc, ih));

	sc->sc_ih = pci_intr_establish(pa->pa_pc, ih, IPL_TTY,
	    sbbc_intr, sc, sc->sc_dv.dv_xname);
	if (sc->sc_ih == NULL) {
		printf("%s: unable to establish interrupt\n", sc->sc_dv.dv_xname);
		goto unmap_sram;
	}

	bus_space_write_4(sc->sc_iot, sc->sc_regs_ioh,
	    SBBC_PCI_INT_ENABLE, SBBC_PCI_ENABLE_INT_A);

	/* Check if we are the chosen one. */
	chosen = OF_finddevice("/chosen");
	if (OF_getprop(chosen, "iosram", &iosram, sizeof(iosram)) <= 0 ||
	    PCITAG_NODE(pa->pa_tag) != iosram)
		return;

	/* SRAM TOC offset defaults to 0. */
	if (OF_getprop(chosen, "iosram-toc", &sc->sc_sram_toc,
	    sizeof(sc->sc_sram_toc)) <= 0)
		sc->sc_sram_toc = 0;

	sc->sc_sram = bus_space_vaddr(sc->sc_iot, sc->sc_sram_ioh);
	toc = (struct sbbc_sram_toc *)(sc->sc_sram + sc->sc_sram_toc);

	for (i = 0; i < toc->toc_ntags; i++) {
		if (strcmp(toc->toc_tag[i].tag_key, "SOLSCIE") == 0)
			sc->sc_sram_solscie = (uint32_t *)
			    (sc->sc_sram + toc->toc_tag[i].tag_offset);
		if (strcmp(toc->toc_tag[i].tag_key, "SOLSCIR") == 0)
			sc->sc_sram_solscir = (uint32_t *)
			    (sc->sc_sram + toc->toc_tag[i].tag_offset);
		if (strcmp(toc->toc_tag[i].tag_key, "SCSOLIE") == 0)
			sc->sc_sram_scsolie = (uint32_t *)
			    (sc->sc_sram + toc->toc_tag[i].tag_offset);
		if (strcmp(toc->toc_tag[i].tag_key, "SCSOLIR") == 0)
			sc->sc_sram_scsolir = (uint32_t *)
			    (sc->sc_sram + toc->toc_tag[i].tag_offset);
	}

	for (i = 0; i < toc->toc_ntags; i++) {
		if (strcmp(toc->toc_tag[i].tag_key, "TODDATA") == 0)
			sbbc_attach_tod(sc, toc->toc_tag[i].tag_offset);
		if (strcmp(toc->toc_tag[i].tag_key, "SOLCONS") == 0)
			sbbc_attach_cons(sc, toc->toc_tag[i].tag_offset);
	}

	return;

 unmap_sram:
	bus_space_unmap(sc->sc_iot, sc->sc_sram_ioh, SBBC_SRAM_SIZE);
 unmap_epld:
	bus_space_unmap(sc->sc_iot, sc->sc_sram_ioh, SBBC_EPLD_SIZE);
 unmap_regs:
	bus_space_unmap(sc->sc_iot, sc->sc_sram_ioh, SBBC_REGS_SIZE);
}

int
sbbc_intr(void *arg)
{
	struct sbbc_softc *sc = arg;
	uint32_t status, reason;

	status = bus_space_read_4(sc->sc_iot, sc->sc_regs_ioh,
	    SBBC_PCI_INT_STATUS);
	if (status == 0)
		return (0);

	/* Sigh, we cannot use compare and swap for non-cachable memory. */
	reason = *sc->sc_sram_scsolir;
	*sc->sc_sram_scsolir = 0;

	sbbc_intr_cons(sc, reason);

	/* Ack interrupt. */
	bus_space_write_4(sc->sc_iot, sc->sc_regs_ioh,
	    SBBC_PCI_INT_STATUS, status);
	return (1);
}

void
sbbc_send_intr(struct sbbc_softc *sc)
{
	bus_space_write_1(sc->sc_iot, sc->sc_epld_ioh,
	    SBBC_EPLD_INTERRUPT, SBBC_EPLD_INTERRUPT_ON);
}

void
sbbc_attach_tod(struct sbbc_softc *sc, uint32_t offset)
{
	struct sbbc_sram_tod *tod;
	todr_chip_handle_t handle;

	tod = (struct sbbc_sram_tod *)(sc->sc_sram + offset);
	if (tod->tod_magic != SBBC_TOD_MAGIC ||
	    tod->tod_version < SBBC_TOD_VERSION)
		return;

	handle = malloc(sizeof(struct todr_chip_handle), M_DEVBUF, M_NOWAIT);
	if (handle == NULL)
		panic("couldn't allocate todr_handle");

	handle->cookie = tod;
	handle->todr_gettime = sbbc_tod_gettime;
	handle->todr_settime = sbbc_tod_settime;

	handle->bus_cookie = NULL;
	handle->todr_setwen = NULL;
	todr_handle = handle;
}

int
sbbc_tod_gettime(todr_chip_handle_t handle, struct timeval *tv)
{
	struct sbbc_sram_tod *tod = handle->cookie;

	tv->tv_sec = tod->tod_time + tod->tod_skew;
	tv->tv_usec = 0;
	return (0);
}

int
sbbc_tod_settime(todr_chip_handle_t handle, struct timeval *tv)
{
	struct sbbc_sram_tod *tod = handle->cookie;

	tod->tod_skew = tv->tv_sec - tod->tod_time;
	return (0);
}

void
sbbc_attach_cons(struct sbbc_softc *sc, uint32_t offset)
{
	struct sbbc_sram_cons *cons;
	int sgcn_is_input, sgcn_is_output, node, maj;
	char buf[32];

	if (sc->sc_sram_solscie == NULL || sc->sc_sram_solscir == NULL ||
	    sc->sc_sram_scsolie == NULL || sc->sc_sram_scsolir == NULL)
		return;

	cons = (struct sbbc_sram_cons *)(sc->sc_sram + offset);
	if (cons->cons_magic != SBBC_CONS_MAGIC ||
	    cons->cons_version < SBBC_CONS_VERSION)
		return;

	sc->sc_sram_cons = sc->sc_sram + offset;
	sbbc_cons_input = sbbc_cons_output = sc;
	sgcn_is_input = sgcn_is_output = 0;

	sc->sc_cons_si = softintr_establish(IPL_TTY, sbbc_softintr_cons, sc);
	if (sc->sc_cons_si == NULL)
		panic("%s: can't establish soft interrupt",
		    sc->sc_dv.dv_xname);

	*sc->sc_sram_solscie |= SBBC_SRAM_CONS_OUT;
	*sc->sc_sram_scsolie |= SBBC_SRAM_CONS_IN | SBBC_SRAM_CONS_BRK;

	/* Take over console input. */
	prom_serengeti_set_console_input("CON_CLNT");

	/* Check for console input. */
	node = OF_instance_to_package(OF_stdin());
	if (OF_getprop(node, "name", buf, sizeof(buf)) > 0)
		sgcn_is_input = (strcmp(buf, "sgcn") == 0);

	/* Check for console output. */
	node = OF_instance_to_package(OF_stdout());
	if (OF_getprop(node, "name", buf, sizeof(buf)) > 0)
		sgcn_is_output = (strcmp(buf, "sgcn") == 0);

	if (sgcn_is_input) {
		cn_tab->cn_pollc = nullcnpollc;
		cn_tab->cn_getc = sbbc_cngetc;
	}

	if (sgcn_is_output)
		cn_tab->cn_putc = sbbc_cnputc;

	if (sgcn_is_input || sgcn_is_output) {
		/* Locate the major number. */
		for (maj = 0; maj < nchrdev; maj++)
			if (cdevsw[maj].d_open == sbbcopen)
				break;
		cn_tab->cn_dev = makedev(maj, sc->sc_dv.dv_unit);

		/* Let current output drain. */
		DELAY(2000000);

		printf("%s: console\n", sc->sc_dv.dv_xname);
	}
}

void
sbbc_intr_cons(struct sbbc_softc *sc, uint32_t reason)
{
#ifdef DDB
	if ((reason & SBBC_SRAM_CONS_BRK) && sc == sbbc_cons_input) {
		if (db_console)
			Debugger();
	}
#endif

	if ((reason & SBBC_SRAM_CONS_IN) && sc->sc_tty)
		softintr_schedule(sc->sc_cons_si);
}

void
sbbc_softintr_cons(void *arg)
{
	struct sbbc_softc *sc = arg;
	struct sbbc_sram_cons *cons = (void *)sc->sc_sram_cons;
	uint32_t rdptr = cons->cons_in_rdptr;
	struct tty *tp = sc->sc_tty;
	int c;

	while (rdptr != cons->cons_in_wrptr) {
		if (tp->t_state & TS_ISOPEN) {
			c = *(sc->sc_sram_cons + rdptr);
			(*linesw[tp->t_line].l_rint)(c, tp);
		}

		if (++rdptr == cons->cons_in_end)
			rdptr = cons->cons_in_begin;
	}

	cons->cons_in_rdptr = rdptr;
}

int
sbbc_cnlookc(dev_t dev, int *cp)
{
	struct sbbc_softc *sc = sbbc_cons_input;
	struct sbbc_sram_cons *cons = (void *)sc->sc_sram_cons;
	uint32_t rdptr = cons->cons_in_rdptr;

	if (rdptr == cons->cons_in_wrptr)
		return (0);

	*cp = *(sc->sc_sram_cons + rdptr);
	if (++rdptr == cons->cons_in_end)
		rdptr = cons->cons_in_begin;
	cons->cons_in_rdptr = rdptr;

	return (1);
}

int
sbbc_cngetc(dev_t dev)
{
	int c;

	while(!sbbc_cnlookc(dev, &c))
		;

	return (c);
}

void
sbbc_cnputc(dev_t dev, int c)
{
	struct sbbc_softc *sc = sbbc_cons_output;
	struct sbbc_sram_cons *cons = (void *)sc->sc_sram_cons;
	uint32_t wrptr = cons->cons_out_wrptr;

	*(sc->sc_sram_cons + wrptr) = c;
	if (++wrptr == cons->cons_out_end)
		wrptr = cons->cons_out_begin;
	cons->cons_out_wrptr = wrptr;

	*sc->sc_sram_solscir |= SBBC_SRAM_CONS_OUT;
	sbbc_send_intr(sc);
}

int
sbbcopen(dev_t dev, int flag, int mode, struct proc *p)
{
	struct sbbc_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= sbbc_cd.cd_ndevs)
		return (ENXIO);
	sc = sbbc_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	if (sc->sc_tty)
		tp = sc->sc_tty;
	else
		tp = sc->sc_tty = ttymalloc(0);

	tp->t_oproc = sbbcstart;
	tp->t_param = sbbcparam;
	tp->t_dev = dev;
	if ((tp->t_state & TS_ISOPEN) == 0) {
		ttychars(tp);
		tp->t_iflag = TTYDEF_IFLAG;
		tp->t_oflag = TTYDEF_OFLAG;
		tp->t_cflag = TTYDEF_CFLAG;
		tp->t_lflag = TTYDEF_LFLAG;
		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;
		ttsetwater(tp);
	} else if ((tp->t_state & TS_XCLUDE) && suser(p, 0))
		return (EBUSY);
	tp->t_state |= TS_CARR_ON;

	return ((*linesw[tp->t_line].l_open)(dev, tp, p));
}

int
sbbcclose(dev_t dev, int flag, int mode, struct proc *p)
{
	struct sbbc_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= sbbc_cd.cd_ndevs)
		return (ENXIO);
	sc = sbbc_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	(*linesw[tp->t_line].l_close)(tp, flag, p);
	ttyclose(tp);
	return (0);
}

int
sbbcread(dev_t dev, struct uio *uio, int flag)
{
	struct sbbc_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= sbbc_cd.cd_ndevs)
		return (ENXIO);
	sc = sbbc_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
}

int
sbbcwrite(dev_t dev, struct uio *uio, int flag)
{
	struct sbbc_softc *sc;
	struct tty *tp;
	int unit = minor(dev);

	if (unit >= sbbc_cd.cd_ndevs)
		return (ENXIO);
	sc = sbbc_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
}

int
sbbcioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct sbbc_softc *sc;
	struct tty *tp;
	int unit = minor(dev);
	int error;

	if (unit >= sbbc_cd.cd_ndevs)
		return (ENXIO);
	sc = sbbc_cd.cd_devs[unit];
	if (sc == NULL)
		return (ENXIO);

	tp = sc->sc_tty;
	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
	if (error >= 0)
		return error;
	error = ttioctl(tp, cmd, data, flag, p);
	if (error >= 0)
		return (error);

	return (ENOTTY);
}

void
sbbcstart(struct tty *tp)
{
	int s;

	s = spltty();
	if (tp->t_state & (TS_TTSTOP | TS_BUSY)) {
		splx(s);
		return;
	}
	ttwakeupwr(tp);
	tp->t_state |= TS_BUSY;
	while (tp->t_outq.c_cc != 0)
		sbbc_cnputc(tp->t_dev, getc(&tp->t_outq));
	tp->t_state &= ~TS_BUSY;
	splx(s);
}

int
sbbcstop(struct tty *tp, int flag)
{
	int s;

	s = spltty();
	if (tp->t_state & TS_BUSY)
		if ((tp->t_state & TS_TTSTOP) == 0)
			tp->t_state |= TS_FLUSH;
	splx(s);
	return (0);
}

struct tty *
sbbctty(dev_t dev)
{
	struct sbbc_softc *sc;
	int unit = minor(dev);

	if (unit >= sbbc_cd.cd_ndevs)
		return (NULL);
	sc = sbbc_cd.cd_devs[unit];
	if (sc == NULL)
		return (NULL);

	return sc->sc_tty;
}

int
sbbcparam(struct tty *tp, struct termios *t)
{
	tp->t_ispeed = t->c_ispeed;
	tp->t_ospeed = t->c_ospeed;
	tp->t_cflag = t->c_cflag;
	return (0);
}


code:
/*	$OpenBSD: sbus.c,v 1.43 2014/12/09 06:58:29 doug Exp $	*/
/*	$NetBSD: sbus.c,v 1.46 2001/10/07 20:30:41 eeh Exp $ */

/*-
 * Copyright (c) 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Paul Kranenburg.
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 THE FOUNDATION OR CONTRIBUTORS
 * 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.
 */

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * 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. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 THE REGENTS OR CONTRIBUTORS 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.
 *
 *	@(#)sbus.c	8.1 (Berkeley) 6/11/93
 */

/*
 * Copyright (c) 1999 Eduardo Horvath
 *
 * 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.
 *
 * 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.
 *
 */

/*
 * SBus stuff.
 */

#include <sys/param.h>
#include <sys/proc.h>
#include <sys/signalvar.h>
#include <sys/extent.h>
#include <sys/malloc.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/reboot.h>

#include <machine/bus.h>
#include <sparc64/sparc64/cache.h>
#include <sparc64/dev/iommureg.h>
#include <sparc64/dev/iommuvar.h>
#include <sparc64/dev/sbusreg.h>
#include <sparc64/dev/starfire.h>
#include <dev/sbus/sbusvar.h>
#include <dev/sbus/xboxvar.h>

#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <machine/cpu.h>
#include <machine/openfirm.h>
#include <machine/sparc64.h>

#ifdef DEBUG
#define SDB_DVMA	0x1
#define SDB_INTR	0x2
#define SDB_CHILD	0x4
int sbus_debug = 0;
#define DPRINTF(l, s)   do { if (sbus_debug & l) printf s; } while (0)
#else
#define DPRINTF(l, s)
#endif

bus_space_tag_t sbus_alloc_bustag(struct sbus_softc *, int);
bus_dma_tag_t sbus_alloc_dma_tag(struct sbus_softc *, bus_dma_tag_t);
int sbus_get_intr(struct sbus_softc *, int,
    struct sbus_intr **, int *, int);
int sbus_overtemp(void *);
int _sbus_bus_map(bus_space_tag_t, bus_space_tag_t,
    bus_addr_t,		/*offset*/
    bus_size_t,		/*size*/
    int,		/*flags*/
    bus_space_handle_t *);
void *sbus_intr_establish(bus_space_tag_t, bus_space_tag_t,
    int,		/*SBus interrupt level*/
    int,		/*`device class' priority*/
    int,		/*flags*/
    int (*)(void *),	/*handler*/
    void *,		/*handler arg*/
    const char *);	/*what*/
void	sbus_attach_common(struct sbus_softc *, int, int);

/* autoconfiguration driver */
void	sbus_mb_attach(struct device *, struct device *, void *);
void	sbus_xbox_attach(struct device *, struct device *, void *);
int	sbus_mb_match(struct device *, void *, void *);
int	sbus_xbox_match(struct device *, void *, void *);

struct cfattach sbus_mb_ca = {
	sizeof(struct sbus_softc), sbus_mb_match, sbus_mb_attach
};

struct cfattach sbus_xbox_ca = {
	sizeof(struct sbus_softc), sbus_xbox_match, sbus_xbox_attach
};

struct cfdriver sbus_cd = {
	NULL, "sbus", DV_DULL
};

/*
 * DVMA routines
 */
int sbus_dmamap_create(bus_dma_tag_t, bus_dma_tag_t, bus_size_t, int,
    bus_size_t, bus_size_t, int, bus_dmamap_t *);

/*
 * Child devices receive the SBus interrupt level in their attach
 * arguments. We translate these to CPU IPLs using the following
 * tables. Note: obio bus interrupt levels are identical to the
 * processor IPL.
 *
 * The second set of tables is used when the SBus interrupt level
 * cannot be had from the PROM as an `interrupt' property. We then
 * fall back on the `intr' property which contains the CPU IPL.
 */

/* Translate SBus interrupt level to processor IPL */
static int intr_sbus2ipl_4u[] = {
	0, 2, 3, 5, 7, 9, 11, 13
};

/*
 * This value is or'ed into the attach args' interrupt level cookie
 * if the interrupt level comes from an `intr' property, i.e. it is
 * not an SBus interrupt level.
 */
#define SBUS_INTR_COMPAT	0x80000000

/*
 * Print the location of some sbus-attached device (called just
 * before attaching that device).  If `sbus' is not NULL, the
 * device was found but not configured; print the sbus as well.
 * Return UNCONF (config_find ignores this if the device was configured).
 */
int
sbus_print(void *args, const char *busname)
{
	struct sbus_attach_args *sa = args;
	char *class;
	int i;

	if (busname != NULL) {
		printf("\"%s\" at %s", sa->sa_name, busname);
		class = getpropstring(sa->sa_node, "device_type");
		if (*class != '\0')
			printf(" class %s", class);
	}
	printf(" slot %ld offset 0x%lx", (long)sa->sa_slot,
	       (u_long)sa->sa_offset);
	for (i = 0; i < sa->sa_nintr; i++) {
		struct sbus_intr *sbi = &sa->sa_intr[i];

		printf(" vector %lx ipl %ld",
		       (u_long)sbi->sbi_vec,
		       (long)INTLEV(sbi->sbi_pri));
	}
	return (UNCONF);
}

int
sbus_mb_match(struct device *parent, void *vcf, void *aux)
{
	struct cfdata *cf = vcf;
	struct mainbus_attach_args *ma = aux;

	return (strcmp(cf->cf_driver->cd_name, ma->ma_name) == 0);
}

int
sbus_xbox_match(struct device *parent, void *vcf, void *aux)
{
	struct xbox_softc *xsc = (struct xbox_softc *)parent;

	/* Prevent multiple attachments */
	if (xsc->sc_attached == 0) {
		xsc->sc_attached = 1;
		return (1);
	}

	return (0);
}

void
sbus_xbox_attach(struct device *parent, struct device *self, void *aux)
{
	struct sbus_softc *sc = (struct sbus_softc *)self;
	struct xbox_softc *xsc = (struct xbox_softc *)parent;
	struct sbus_softc *sbus = (struct sbus_softc *)parent->dv_parent;
	struct xbox_attach_args *xa = aux;
	int node = xa->xa_node;

	sc->sc_master = sbus->sc_master;

	sc->sc_bustag = xa->xa_bustag;
	sc->sc_dmatag = sbus_alloc_dma_tag(sc, xa->xa_dmatag);

	/*
	 * Parent has already done the address translation computations.
	 */
	sc->sc_nrange = xsc->sc_nrange;
	sc->sc_range = xsc->sc_range;

	/*
	 * Record clock frequency for synchronous SCSI.
	 * IS THIS THE CORRECT DEFAULT??
	 */
	sc->sc_clockfreq = getpropint(node, "clock-frequency", 25*1000*1000);
	printf(": %s MHz\n", clockfreq(sc->sc_clockfreq));

	sbus_attach_common(sc, node, 1);
}

void
sbus_mb_attach(struct device *parent, struct device *self, void *aux)
{
	struct sbus_softc *sc = (struct sbus_softc *)self;
	struct mainbus_attach_args *ma = aux;
	int node = ma->ma_node;
	struct intrhand *ih;
	int ipl, error;
	struct sysioreg *sysio;
	char buf[32];
	char *name;

	sc->sc_master = sc;

	sc->sc_bustag = ma->ma_bustag;

	/* Find interrupt group no */
	sc->sc_ign = ma->ma_interrupts[0] & INTMAP_IGN;

	/*
	 * Collect address translations from the OBP.
	 */
	error = getprop(node, "ranges", sizeof(struct sbus_range),
			 &sc->sc_nrange, (void **)&sc->sc_range);
	if (error)
		panic("%s: error getting ranges property", sc->sc_dev.dv_xname);

	/*
	 * Record clock frequency for synchronous SCSI.
	 * IS THIS THE CORRECT DEFAULT??
	 */
	sc->sc_clockfreq = getpropint(node, "clock-frequency", 25*1000*1000);
	printf(": clock = %s MHz\n", clockfreq(sc->sc_clockfreq));

	bus_space_map(sc->sc_bustag,
	    ma->ma_address[0], sizeof(struct sysioreg),
	    BUS_SPACE_MAP_PROMADDRESS, &sc->sc_bh);
	sysio = bus_space_vaddr(sc->sc_bustag, sc->sc_bh);

	/* initialize the IOMMU */

	/* punch in our copies */
	sc->sc_is.is_bustag = sc->sc_bustag;
	bus_space_subregion(sc->sc_bustag, sc->sc_bh,
	    offsetof(struct sysioreg, sys_iommu),
	    sizeof(struct iommureg), &sc->sc_is.is_iommu);

	/* initialize our strbuf_ctl */
	sc->sc_is.is_sb[0] = &sc->sc_sb;
	if (bus_space_subregion(sc->sc_bustag, sc->sc_bh,
	    offsetof(struct sysioreg, sys_strbuf),
	    sizeof(struct iommu_strbuf), &sc->sc_sb.sb_sb) == 0) {
		/* point sb_flush to our flush buffer */
		sc->sc_sb.sb_flush = &sc->sc_flush;
		sc->sc_sb.sb_bustag = sc->sc_bustag;
	} else
		sc->sc_sb.sb_flush = NULL;

	/* give us a nice name.. */
	name = (char *)malloc(32, M_DEVBUF, M_NOWAIT);
	if (name == 0)
		panic("couldn't malloc iommu name");
	snprintf(name, 32, "%s dvma", sc->sc_dev.dv_xname);

	printf("%s: ", sc->sc_dev.dv_xname);
	iommu_init(name, &sc->sc_is, 0, -1);

	/* Initialize Starfire PC interrupt translation. */
	if (OF_getprop(findroot(), "name", buf, sizeof(buf)) > 0 &&
	    strcmp(buf, "SUNW,Ultra-Enterprise-10000") == 0)
		starfire_pc_ittrans_init(ma->ma_upaid);

	/* Enable the over temp intr */
	ih = malloc(sizeof(*ih), M_DEVBUF, M_NOWAIT | M_ZERO);
	if (ih == NULL)
		panic("couldn't malloc intrhand");
	ih->ih_map = &sysio->therm_int_map;
	ih->ih_clr = NULL; /* &sysio->therm_clr_int; */
	ih->ih_fun = sbus_overtemp;
	ipl = 1;
	ih->ih_pil = (1 << ipl);
	ih->ih_number = INTVEC(*(ih->ih_map));
	strlcpy(ih->ih_name, sc->sc_dev.dv_xname, sizeof(ih->ih_name));
	intr_establish(ipl, ih);
	*(ih->ih_map) |= INTMAP_V;

	/*
	 * Note: the stupid SBus IOMMU ignores the high bits of an address, so a
	 * NULL DMA pointer will be translated by the first page of the IOTSB.
	 * To avoid bugs we'll alloc and ignore the first entry in the IOTSB.
	 */
	{
		u_long dummy;

		if (extent_alloc_subregion(sc->sc_is.is_dvmamap,
		    sc->sc_is.is_dvmabase, sc->sc_is.is_dvmabase + NBPG, NBPG,
		    NBPG, 0, 0, EX_NOWAIT | EX_BOUNDZERO,
		    (u_long *)&dummy) != 0)
			panic("sbus iommu: can't toss first dvma page");
	}

	sc->sc_dmatag = sbus_alloc_dma_tag(sc, ma->ma_dmatag);

	sbus_attach_common(sc, node, 0);
}

/*
 * Attach an SBus (main part).
 */
void
sbus_attach_common(struct sbus_softc *sc, int node, int indirect)
{
	bus_space_tag_t sbt;
	struct sbus_attach_args sa;
	int node0;

	/* Setup interrupt translation tables */
	sc->sc_intr2ipl = intr_sbus2ipl_4u;

	sbt = sbus_alloc_bustag(sc, indirect);

	/*
	 * Get the SBus burst transfer size if burst transfers are supported
	 */
	sc->sc_burst = getpropint(node, "burst-sizes", 0);

	/*
	 * Loop through ROM children, fixing any relative addresses
	 * and then configuring each device.
	 * `specials' is an array of device names that are treated
	 * specially:
	 */
	node0 = firstchild(node);
	for (node = node0; node; node = nextsibling(node)) {
		if (!checkstatus(node))
			continue;

		if (sbus_setup_attach_args(sc, sbt, sc->sc_dmatag,
					   node, &sa) != 0) {
			DPRINTF(SDB_CHILD,
			    ("sbus_attach: %s: incomplete\n",
			    getpropstring(node, "name")));
			continue;
		}
		(void) config_found(&sc->sc_dev, (void *)&sa, sbus_print);
		sbus_destroy_attach_args(&sa);
	}
}

int
sbus_setup_attach_args(struct sbus_softc *sc, bus_space_tag_t bustag,
    bus_dma_tag_t dmatag, int node, struct sbus_attach_args *sa)
{
	int	error;
	int	n;

	bzero(sa, sizeof(struct sbus_attach_args));
	error = getprop(node, "name", 1, &n, (void **)&sa->sa_name);
	if (error != 0)
		return (error);
	sa->sa_name[n] = '\0';

	sa->sa_bustag = bustag;
	sa->sa_dmatag = dmatag;
	sa->sa_node = node;
	sa->sa_frequency = sc->sc_clockfreq;

	error = getprop(node, "reg", sizeof(struct sbus_reg),
			 &sa->sa_nreg, (void **)&sa->sa_reg);
	if (error != 0) {
		char buf[32];
		if (error != ENOENT ||
		    !node_has_property(node, "device_type") ||
		    strcmp(getpropstringA(node, "device_type", buf),
			   "hierarchical") != 0)
			return (error);
	}
	for (n = 0; n < sa->sa_nreg; n++) {
		/* Convert to relative addressing, if necessary */
		u_int32_t base = sa->sa_reg[n].sbr_offset;
		if (SBUS_ABS(base)) {
			sa->sa_reg[n].sbr_slot = SBUS_ABS_TO_SLOT(base);
			sa->sa_reg[n].sbr_offset = SBUS_ABS_TO_OFFSET(base);
		}
	}

	if ((error = sbus_get_intr(sc, node, &sa->sa_intr, &sa->sa_nintr,
	    sa->sa_slot)) != 0)
		return (error);

	error = getprop(node, "address", sizeof(u_int32_t),
			 &sa->sa_npromvaddrs, (void **)&sa->sa_promvaddrs);
	if (error != 0 && error != ENOENT)
		return (error);

	return (0);
}

void
sbus_destroy_attach_args(struct sbus_attach_args *sa)
{
	if (sa->sa_name != NULL)
		free(sa->sa_name, M_DEVBUF, 0);

	if (sa->sa_nreg != 0)
		free(sa->sa_reg, M_DEVBUF, 0);

	if (sa->sa_intr)
		free(sa->sa_intr, M_DEVBUF, 0);

	if (sa->sa_promvaddrs)
		free((void *)sa->sa_promvaddrs, M_DEVBUF, 0);

	bzero(sa, sizeof(struct sbus_attach_args)); /*DEBUG*/
}

int
_sbus_bus_map(bus_space_tag_t t, bus_space_tag_t t0, bus_addr_t addr,
    bus_size_t size, int flags, bus_space_handle_t *hp)
{
	struct sbus_softc *sc = t->cookie;
	int64_t slot = BUS_ADDR_IOSPACE(addr);
	int64_t offset = BUS_ADDR_PADDR(addr);
	int i;

	if (t->parent == NULL || t->parent->sparc_bus_map == NULL) {
		printf("\n_psycho_bus_map: invalid parent");
		return (EINVAL);
	}

	if (flags & BUS_SPACE_MAP_PROMADDRESS) {
		return ((*t->parent->sparc_bus_map)(t, t0, addr,
					size, flags, hp));
	}

	for (i = 0; i < sc->sc_nrange; i++) {
		bus_addr_t paddr;

		if (sc->sc_range[i].cspace != slot)
			continue;

		/* We've found the connection to the parent bus */
		paddr = sc->sc_range[i].poffset + offset;
		paddr |= ((bus_addr_t)sc->sc_range[i].pspace << 32);
		DPRINTF(SDB_DVMA, ("_sbus_bus_map: mapping paddr "
			"slot %lx offset %lx poffset %lx paddr %lx\n",
		    (long)slot, (long)offset, (long)sc->sc_range[i].poffset,
		    (long)paddr));
		return ((*t->parent->sparc_bus_map)(t, t0, paddr,
					size, flags, hp));
	}

	return (EINVAL);
}

bus_addr_t
sbus_bus_addr(bus_space_tag_t t, u_int btype, u_int offset)
{
	bus_addr_t baddr = ~(bus_addr_t)0;
	int slot = btype;
	struct sbus_softc *sc = t->cookie;
	int i;

	for (i = 0; i < sc->sc_nrange; i++) {
		if (sc->sc_range[i].cspace != slot)
			continue;

		baddr = sc->sc_range[i].poffset + offset;
		baddr |= (bus_addr_t)sc->sc_range[i].pspace << 32;
	}

	return (baddr);
}

/*
 * Handle an overtemp situation.
 *
 * SPARCs have temperature sensors which generate interrupts
 * if the machine's temperature exceeds a certain threshold.
 * This handles the interrupt and powers off the machine.
 * The same needs to be done to PCI controller drivers.
 */
int
sbus_overtemp(void *arg)
{
	/* Should try a clean shutdown first */
	printf("DANGER: OVER TEMPERATURE detected\nShutting down...\n");
	delay(20);
	prsignal(initprocess, SIGUSR2);
	return (1);
}

/*
 * Get interrupt attributes for an SBus device.
 */
int
sbus_get_intr(struct sbus_softc *sc, int node, struct sbus_intr **ipp, int *np,
    int slot)
{
	int *ipl;
	int n, i;
	char buf[32];

	/*
	 * The `interrupts' property contains the SBus interrupt level.
	 */
	ipl = NULL;
	if (getprop(node, "interrupts", sizeof(int), np, (void **)&ipl) == 0) {
		struct sbus_intr *ip;
		int pri;

		/* Default to interrupt level 2 -- otherwise unused */
		pri = INTLEVENCODE(2);

		/* Change format to an `struct sbus_intr' array */
		ip = mallocarray(*np, sizeof(struct sbus_intr), M_DEVBUF,
		    M_NOWAIT);
		if (ip == NULL)
			return (ENOMEM);

		/*
		 * Now things get ugly.  We need to take this value which is
		 * the interrupt vector number and encode the IPL into it
		 * somehow. Luckily, the interrupt vector has lots of free
		 * space and we can easily stuff the IPL in there for a while.
		 */
		getpropstringA(node, "device_type", buf);
		if (!buf[0])
			getpropstringA(node, "name", buf);

		for (i = 0; intrmap[i].in_class; i++)
			if (strcmp(intrmap[i].in_class, buf) == 0) {
				pri = INTLEVENCODE(intrmap[i].in_lev);
				break;
			}

		/*
		 * SBus card devices need the slot number encoded into
		 * the vector as this is generally not done.
		 */
		if ((ipl[0] & INTMAP_OBIO) == 0)
			pri |= slot << 3;

		for (n = 0; n < *np; n++) {
			/*
			 * We encode vector and priority into sbi_pri so we
			 * can pass them as a unit.  This will go away if
			 * sbus_establish ever takes an sbus_intr instead
			 * of an integer level.
			 * Stuff the real vector in sbi_vec.
			 */

			ip[n].sbi_pri = pri | ipl[n];
			ip[n].sbi_vec = ipl[n];
		}
		free(ipl, M_DEVBUF, 0);
		*ipp = ip;
	}

	return (0);
}

/*
 * Install an interrupt handler for an SBus device.
 */
void *
sbus_intr_establish(bus_space_tag_t t, bus_space_tag_t t0, int pri, int level,
    int flags, int (*handler)(void *), void *arg, const char *what)
{
	struct sbus_softc *sc = t->cookie;
	struct sysioreg *sysio;
	struct intrhand *ih;
	volatile u_int64_t *map = NULL;
	volatile u_int64_t *clr = NULL;
	int ipl;
	long vec = pri;

	/* Pick the master SBus as all do not have IOMMU registers */
	sc = sc->sc_master;

	sysio = bus_space_vaddr(sc->sc_bustag, sc->sc_bh);

	if ((flags & BUS_INTR_ESTABLISH_SOFTINTR) != 0)
		ipl = 1 << vec;
	else if ((vec & SBUS_INTR_COMPAT) != 0)
		ipl = 1 << (vec & ~SBUS_INTR_COMPAT);
	else {
		/* Decode and remove IPL */
		ipl = level;
		if (ipl == IPL_NONE)
			ipl = 1 << INTLEV(vec);
		if (ipl == IPL_NONE) {
			printf("ERROR: no IPL, setting IPL 2.\n");
			ipl = 2;
		}
		vec = INTVEC(vec);
		DPRINTF(SDB_INTR,
		    ("\nsbus: intr[%ld]%lx: %lx\nHunting for IRQ...\n",
		    (long)ipl, (long)vec, (u_long)intrlev[vec]));
		if ((vec & INTMAP_OBIO) == 0) {
			/* We're in an SBus slot */
			/* Register the map and clear intr registers */
			bus_space_handle_t maph;
			int slot = INTSLOT(pri);

			map = &(&sysio->sbus_slot0_int)[slot];
			clr = &sysio->sbus0_clr_int[vec];
#ifdef DEBUG
			if (sbus_debug & SDB_INTR) {
				int64_t intrmap = *map;

				printf("SBus %lx IRQ as %llx in slot %d\n",
				       (long)vec, (long long)intrmap, slot);
				printf("\tmap addr %p clr addr %p\n",
				    map, clr);
			}
#endif
			/* Enable the interrupt */
			vec |= INTMAP_V;
			/* Insert IGN */
			vec |= sc->sc_ign;
			/*
			 * This would be cleaner if the underlying interrupt
			 * infrastructure took a bus tag/handle pair.  Even
			 * if not, the following could be done with a write
			 * to the appropriate offset from sc->sc_bustag and
			 * sc->sc_bh.
			 */
			bus_space_map(sc->sc_bustag, (bus_addr_t)map, 8,
			    BUS_SPACE_MAP_PROMADDRESS, &maph);
			bus_space_write_8(sc->sc_bustag, maph, 0, vec);
		} else {
			bus_space_handle_t maph;
			volatile int64_t *intrptr = &sysio->scsi_int_map;
			int64_t intrmap = 0;
			int i;

			/* Insert IGN */
			vec |= sc->sc_ign;
			for (i = 0; &intrptr[i] <=
			    (int64_t *)&sysio->reserved_int_map &&
			    INTVEC(intrmap = intrptr[i]) != INTVEC(vec); i++)
				;
			if (INTVEC(intrmap) == INTVEC(vec)) {
				DPRINTF(SDB_INTR,
				    ("OBIO %lx IRQ as %lx in slot %d\n",
				    vec, (long)intrmap, i));
				/* Register the map and clear intr registers */
				map = &intrptr[i];
				intrptr = (int64_t *)&sysio->scsi_clr_int;
				clr = &intrptr[i];
				/* Enable the interrupt */
				intrmap |= INTMAP_V;
				/*
				 * This would be cleaner if the underlying
				 * interrupt infrastructure took a bus tag/
				 * handle pair.  Even if not, the following
				 * could be done with a write to the
				 * appropriate offset from sc->sc_bustag and
				 * sc->sc_bh.
				 */
				bus_space_map(sc->sc_bustag,
				    (bus_addr_t)map, 8,
				    BUS_SPACE_MAP_PROMADDRESS, &maph);
				bus_space_write_8(sc->sc_bustag, maph, 0,
				    (u_long)intrmap);
			} else
				panic("IRQ not found!");
		}
	}
#ifdef DEBUG
	if (sbus_debug & SDB_INTR) { long i; for (i = 0; i < 400000000; i++); }
#endif

	ih = bus_intr_allocate(t0, handler, arg, vec, ipl, map, clr, what);
	if (ih == NULL)
		return (ih);

	intr_establish(ih->ih_pil, ih);

	return (ih);
}

bus_space_tag_t
sbus_alloc_bustag(struct sbus_softc *sc, int indirect)
{
	struct sparc_bus_space_tag *sbt;

	sbt = malloc(sizeof(*sbt), M_DEVBUF, M_NOWAIT | M_ZERO);
	if (sbt == NULL)
		return (NULL);

	strlcpy(sbt->name, sc->sc_dev.dv_xname, sizeof(sbt->name));
	sbt->cookie = sc;
	if (indirect)
		sbt->parent = sc->sc_bustag->parent;
	else
		sbt->parent = sc->sc_bustag;
	sbt->default_type = SBUS_BUS_SPACE;
	sbt->asi = ASI_PRIMARY;
	sbt->sasi = ASI_PRIMARY;
	sbt->sparc_bus_map = _sbus_bus_map;
	sbt->sparc_bus_mmap = sc->sc_bustag->sparc_bus_mmap;
	sbt->sparc_intr_establish = sbus_intr_establish;
	return (sbt);
}

bus_dma_tag_t
sbus_alloc_dma_tag(struct sbus_softc *sc, bus_dma_tag_t psdt)
{
	bus_dma_tag_t sdt;

	sdt = (bus_dma_tag_t)malloc(sizeof(struct sparc_bus_dma_tag),
	    M_DEVBUF, M_NOWAIT | M_ZERO);
	if (sdt == NULL)
		/* Panic? */
		return (psdt);

	sdt->_cookie = sc;
	sdt->_parent = psdt;
	sdt->_dmamap_create	= sbus_dmamap_create;
	sdt->_dmamap_destroy	= iommu_dvmamap_destroy;
	sdt->_dmamap_load	= iommu_dvmamap_load;
	sdt->_dmamap_load_raw	= iommu_dvmamap_load_raw;
	sdt->_dmamap_unload	= iommu_dvmamap_unload;
	sdt->_dmamap_sync	= iommu_dvmamap_sync;
	sdt->_dmamem_alloc	= iommu_dvmamem_alloc;
	sdt->_dmamem_free	= iommu_dvmamem_free;
	return (sdt);
}

int
sbus_dmamap_create(bus_dma_tag_t t, bus_dma_tag_t t0, bus_size_t size,
    int nsegments, bus_size_t maxsegsz, bus_size_t boundary, int flags,
    bus_dmamap_t *dmamp)
{
	struct sbus_softc *sc = t->_cookie;

	/* Disallow DMA on secondary SBuses for now */
	if (sc != sc->sc_master)
		return (EINVAL);

        return (iommu_dvmamap_create(t, t0, &sc->sc_sb, size, nsegments,
	    maxsegsz, boundary, flags, dmamp));
}


code:
/*	$OpenBSD: sbusreg.h,v 1.4 2008/07/14 20:01:37 miod Exp $	*/
/*	$NetBSD: sbusreg.h,v 1.7 1999/06/07 05:28:03 eeh Exp $ */

/*
 * Copyright (c) 1996-1999 Eduardo Horvath
 *
 * 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.
 *
 * 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.
 *
 */

/*
 * SBus device addresses are obtained from the FORTH PROMs.  They come
 * in `absolute' and `relative' address flavors, so we have to handle both.
 * Relative addresses do *not* include the slot number.
 */
#define	SBUS_BASE		0xf8000000
#define	SBUS_ADDR(slot, off)	(SBUS_BASE + ((slot) << 25) + (off))
#define	SBUS_ABS(a)		((unsigned)(a) >= SBUS_BASE)
#define	SBUS_ABS_TO_SLOT(a)	(((a) - SBUS_BASE) >> 25)
#define	SBUS_ABS_TO_OFFSET(a)	(((a) - SBUS_BASE) & 0x1ffffff)

/*
 * Sun4u SBus definitions.  Here's where we deal w/the machine
 * dependencies of sysio.
 *
 * SYSIO implements or is the interface to several things:
 *
 * o The SBus interface itself
 * o The IOMMU
 * o The DVMA units
 * o The interrupt controller
 * o The counter/timers
 *
 * Since it has registers to control lots of different things
 * as well as several on-board SBus devices and external SBus
 * slots scattered throughout its address space, it's a pain.
 *
 * One good point, however, is that all registers are 64-bit.
 */

struct sysioreg {
	struct upareg {
		u_int64_t	upa_portid;		/* UPA port ID register */		/* 1fe.0000.0000 */
		u_int64_t	upa_config;		/* UPA config register */		/* 1fe.0000.0008 */
	} sys_upa;

	u_int64_t	sys_csr;		/* SYSIO control/status register */	/* 1fe.0000.0010 */
	u_int64_t	pad0;
	u_int64_t	sys_ecccr;		/* ECC control register */		/* 1fe.0000.0020 */
	u_int64_t	reserved;							/* 1fe.0000.0028 */
	u_int64_t	sys_ue_afsr;		/* Uncorrectable Error AFSR */		/* 1fe.0000.0030 */
	u_int64_t	sys_ue_afar;		/* Uncorrectable Error AFAR */		/* 1fe.0000.0038 */
	u_int64_t	sys_ce_afsr;		/* Correctable Error AFSR */		/* 1fe.0000.0040 */
	u_int64_t	sys_ce_afar;		/* Correctable Error AFAR */		/* 1fe.0000.0048 */

	u_int64_t	pad1[22];

	struct perfmon {
		u_int64_t	pm_cr;			/* Performance monitor control reg */	/* 1fe.0000.0100 */
		u_int64_t	pm_count;		/* Performance monitor counter reg */	/* 1fe.0000.0108 */
	} sys_pm;

	u_int64_t	pad2[990];

	struct sbusreg {
		u_int64_t	sbus_cr;		/* SBus Control Register */		/* 1fe.0000.2000 */
		u_int64_t	reserved;							/* 1fe.0000.2008 */
		u_int64_t	sbus_afsr;		/* SBus AFSR */				/* 1fe.0000.2010 */
		u_int64_t	sbus_afar;		/* SBus AFAR */				/* 1fe.0000.2018 */
		u_int64_t	sbus_config0;	/* SBus Slot 0 config register */	/* 1fe.0000.2020 */
		u_int64_t	sbus_config1;	/* SBus Slot 1 config register */	/* 1fe.0000.2028 */
		u_int64_t	sbus_config2;	/* SBus Slot 2 config register */	/* 1fe.0000.2030 */
		u_int64_t	sbus_config3;	/* SBus Slot 3 config register */	/* 1fe.0000.2038 */
		u_int64_t	sbus_config13;	/* Slot 13 config register <audio> */	/* 1fe.0000.2040 */
		u_int64_t	sbus_config14;	/* Slot 14 config register <macio> */	/* 1fe.0000.2048 */
		u_int64_t	sbus_config15;	/* Slot 15 config register <slavio> */	/* 1fe.0000.2050 */
	} sys_sbus;

	u_int64_t	pad3[117];

	struct iommureg sys_iommu;							/* 1fe.0000.2400-25f8 */

	u_int64_t	pad4[64];

	struct iommu_strbuf	sys_strbuf;						/* 1fe.0000.2800-2810 */

	u_int64_t	pad5[125];

	u_int64_t	sbus_slot0_int;		/* SBus slot 0 interrupt map reg */	/* 1fe.0000.2c00 */
	u_int64_t	sbus_slot1_int;		/* SBus slot 1 interrupt map reg */	/* 1fe.0000.2c08 */
	u_int64_t	sbus_slot2_int;		/* SBus slot 2 interrupt map reg */	/* 1fe.0000.2c10 */
	u_int64_t	sbus_slot3_int;		/* SBus slot 3 interrupt map reg */	/* 1fe.0000.2c18 */
	u_int64_t	intr_retry;		/* interrupt retry timer reg */		/* 1fe.0000.2c20 */

	u_int64_t	pad6[123];

	u_int64_t	scsi_int_map;		/* SCSI interrupt map reg */		/* 1fe.0000.3000 */
	u_int64_t	ether_int_map;		/* ethernet interrupt map reg */	/* 1fe.0000.3008 */
	u_int64_t	bpp_int_map;		/* parallel interrupt map reg */	/* 1fe.0000.3010 */
	u_int64_t	audio_int_map;		/* audio interrupt map reg */		/* 1fe.0000.3018 */
	u_int64_t	power_int_map;		/* power fail interrupt map reg */	/* 1fe.0000.3020 */
	u_int64_t	ser_kbd_ms_int_map;	/* serial/kbd/mouse interrupt map reg *//* 1fe.0000.3028 */
	u_int64_t	fd_int_map;		/* floppy interrupt map reg */		/* 1fe.0000.3030 */
	u_int64_t	therm_int_map;		/* thermal warn interrupt map reg */	/* 1fe.0000.3038 */
	u_int64_t	kbd_int_map;		/* kbd [unused] interrupt map reg */	/* 1fe.0000.3040 */
	u_int64_t	mouse_int_map;		/* mouse [unused] interrupt map reg */	/* 1fe.0000.3048 */
	u_int64_t	serial_int_map;		/* second serial interrupt map reg */	/* 1fe.0000.3050 */
	u_int64_t	pad7;
	u_int64_t	timer0_int_map;		/* timer 0 interrupt map reg */		/* 1fe.0000.3060 */
	u_int64_t	timer1_int_map;		/* timer 1 interrupt map reg */		/* 1fe.0000.3068 */
	u_int64_t	ue_int_map;		/* UE interrupt map reg */		/* 1fe.0000.3070 */
	u_int64_t	ce_int_map;		/* CE interrupt map reg */		/* 1fe.0000.3078 */
	u_int64_t	sbus_async_int_map;	/* SBus error interrupt map reg */	/* 1fe.0000.3080 */
	u_int64_t	pwrmgt_int_map;		/* power mgmt wake interrupt map reg */	/* 1fe.0000.3088 */
	u_int64_t	upagr_int_map;		/* UPA graphics interrupt map reg */	/* 1fe.0000.3090 */
	u_int64_t	reserved_int_map;	/* reserved interrupt map reg */	/* 1fe.0000.3098 */

	u_int64_t	pad8[108];

	/* Note: clear interrupt 0 registers are not really used */
	u_int64_t	sbus0_clr_int[8];	/* SBus slot 0 clear int regs 0..7 */	/* 1fe.0000.3400-3438 */
	u_int64_t	sbus1_clr_int[8];	/* SBus slot 1 clear int regs 0..7 */	/* 1fe.0000.3440-3478 */
	u_int64_t	sbus2_clr_int[8];	/* SBus slot 2 clear int regs 0..7 */	/* 1fe.0000.3480-34b8 */
	u_int64_t	sbus3_clr_int[8];	/* SBus slot 3 clear int regs 0..7 */	/* 1fe.0000.34c0-34f8 */

	u_int64_t	pad9[96];

	u_int64_t	scsi_clr_int;		/* SCSI clear int reg */		/* 1fe.0000.3800 */
	u_int64_t	ether_clr_int;		/* ethernet clear int reg */		/* 1fe.0000.3808 */
	u_int64_t	bpp_clr_int;		/* parallel clear int reg */		/* 1fe.0000.3810 */
	u_int64_t	audio_clr_int;		/* audio clear int reg */		/* 1fe.0000.3818 */
	u_int64_t	power_clr_int;		/* power fail clear int reg */		/* 1fe.0000.3820 */
	u_int64_t	ser_kb_ms_clr_int;	/* serial/kbd/mouse clear int reg */	/* 1fe.0000.3828 */
	u_int64_t	fd_clr_int;		/* floppy clear int reg */		/* 1fe.0000.3830 */
	u_int64_t	therm_clr_int;		/* thermal warn clear int reg */	/* 1fe.0000.3838 */
	u_int64_t	kbd_clr_int;		/* kbd [unused] clear int reg */	/* 1fe.0000.3840 */
	u_int64_t	mouse_clr_int;		/* mouse [unused] clear int reg */	/* 1fe.0000.3848 */
	u_int64_t	serial_clr_int;		/* second serial clear int reg */	/* 1fe.0000.3850 */
	u_int64_t	pad10;
	u_int64_t	timer0_clr_int;		/* timer 0 clear int reg */		/* 1fe.0000.3860 */
	u_int64_t	timer1_clr_int;		/* timer 1 clear int reg */		/* 1fe.0000.3868 */
	u_int64_t	ue_clr_int;		/* UE clear int reg */			/* 1fe.0000.3870 */
	u_int64_t	ce_clr_int;		/* CE clear int reg */			/* 1fe.0000.3878 */
	u_int64_t	sbus_clr_async_int;	/* SBus error clr interrupt reg */	/* 1fe.0000.3880 */
	u_int64_t	pwrmgt_clr_int;		/* power mgmt wake clr interrupt reg */	/* 1fe.0000.3888 */

	u_int64_t	pad11[110];

	struct timer_counter {
		u_int64_t	tc_count;	/* timer/counter 0/1 count register */	/* ife.0000.3c00,3c10 */
		u_int64_t	tc_limit;	/* timer/counter 0/1 limit register */	/* ife.0000.3c08,3c18 */
	} tc[2];

	u_int64_t	pad12[252];

	u_int64_t	sys_svadiag;		/* SBus virtual addr diag reg */	/* 1fe.0000.4400 */

	u_int64_t	pad13[31];

	u_int64_t	iommu_queue_diag[16];	/* IOMMU LRU queue diag */		/* 1fe.0000.4500-457f */
	u_int64_t	tlb_tag_diag[16];	/* TLB tag diag */			/* 1fe.0000.4580-45ff */
	u_int64_t	tlb_data_diag[32];	/* TLB data RAM diag */			/* 1fe.0000.4600-46ff */

	u_int64_t	pad14[32];

	u_int64_t	sbus_int_diag;		/* SBus int state diag reg */		/* 1fe.0000.4800 */
	u_int64_t	obio_int_diag;		/* OBIO and misc int state diag reg */	/* 1fe.0000.4808 */

	u_int64_t	pad15[254];

	u_int64_t	strbuf_data_diag[128];	/* streaming buffer data RAM diag */	/* 1fe.0000.5000-53f8 */
	u_int64_t	strbuf_error_diag[128];	/* streaming buffer error status diag *//* 1fe.0000.5400-57f8 */
	u_int64_t	strbuf_pg_tag_diag[16];	/* streaming buffer page tag diag */	/* 1fe.0000.5800-5878 */
	u_int64_t	pad16[16];
	u_int64_t	strbuf_ln_tag_diag[16];	/* streaming buffer line tag diag */	/* 1fe.0000.5900-5978 */
};


code:
/*	$OpenBSD: sbusvar.h,v 1.10 2008/06/26 05:42:13 ray Exp $	*/
/*	$NetBSD: sbusvar.h,v 1.7 1999/06/05 05:30:43 mrg Exp $ */

/*-
 * Copyright (c) 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Paul Kranenburg.
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 THE FOUNDATION OR CONTRIBUTORS
 * 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.
 */

/*
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * 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. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 THE REGENTS OR CONTRIBUTORS 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.
 *
 *	@(#)sbusvar.h	8.1 (Berkeley) 6/11/93
 */

#ifndef _SBUS_VAR_SPARC64_H_
#define _SBUS_VAR_SPARC64_H_

#include <machine/bus.h>

#include <sparc64/dev/iommuvar.h>

/*
 * Most devices are configured according to information kept in
 * the FORTH PROMs.  In particular, we extract the `name', `reg',
 * and `address' properties of each device attached to the mainbus;
 * other drives may also use this information.  The mainbus itself
 * (which `is' the CPU, in some sense) gets just the node, with a
 * fake name ("mainbus").
 */

/* variables per SBus */
struct sbus_softc {
	struct	device		sc_dev;		/* base device */
	bus_space_tag_t		sc_bustag;
	bus_space_handle_t	sc_bh;
	bus_dma_tag_t		sc_dmatag;
	int			sc_clockfreq;	/* clock frequency (in Hz) */
	struct sbus_range	*sc_range;
	int			sc_nrange;
	int			sc_burst;	/* burst transfer sizes supported */
	int			*sc_intr2ipl;	/* Interrupt level translation */
	int			*sc_intr_compat;/* `intr' property to sbus compat */

	int			sc_ign;		/* Interrupt group number for this sysio */
	struct iommu_state	sc_is;		/* IOMMU state, see iommureg.h */
	struct strbuf_ctl	sc_sb;		/* Streaming buffer control */
	int64_t			sc_flush;	/* Streaming buffer flush */
	struct sbus_softc	*sc_master;	/* main SBus */
};

bus_addr_t sbus_bus_addr(bus_space_tag_t, u_int, u_int);

#endif /* _SBUS_VAR_SPARC64_H_ */