code:
/*	$OpenBSD: dhu.c,v 1.19 2010/09/20 06:33:48 matthew Exp $	*/
/*	$NetBSD: dhu.c,v 1.19 2000/06/04 06:17:01 matt Exp $	*/
/*
 * Copyright (c) 2003, Hugh Graham.
 * Copyright (c) 1996  Ken C. Wellsch.  All rights reserved.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * 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.
 */

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

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

#include <arch/vax/qbus/ubavar.h>
#include <arch/vax/qbus/dhureg.h>

#define	NDHULINE 	16

#define DHU_M2U(c)	((c)>>4)	/* convert minor(dev) to unit # */
#define DHU_LINE(u)	((u)&0xF)	/* extract line # from minor(dev) */

struct	dhu_softc {
	struct	device	sc_dev;		/* Device struct used by config */
	struct	evcount	sc_rintrcnt;	/* Interrupt statistics */
	struct	evcount	sc_tintrcnt;	/* Interrupt statistics */
	int	sc_rcvec, sc_tcvec;
	int		sc_type;	/* controller type, DHU or DHV */
	int		sc_lines;	/* number of lines */
	bus_space_tag_t	sc_iot;
	bus_space_handle_t sc_ioh;
	bus_dma_tag_t	sc_dmat;
	struct {
		struct	tty *dhu_tty;	/* what we work on */
		bus_dmamap_t dhu_dmah;
		int	dhu_state;	/* to manage TX output status */
		short	dhu_cc;		/* character count on TX */
		short	dhu_modem;	/* modem bits state */
	} sc_dhu[NDHULINE];
};

#define IS_DHU			16	/* Unibus DHU-11 board linecount */
#define IS_DHV			 8	/* Q-bus DHV-11 or DHQ-11 */

#define STATE_IDLE		000	/* no current output in progress */
#define STATE_DMA_RUNNING	001	/* DMA TX in progress */
#define STATE_DMA_STOPPED	002	/* DMA TX was aborted */
#define STATE_TX_ONE_CHAR	004	/* did a single char directly */

/* Flags used to monitor modem bits, make them understood outside driver */

#define DML_DTR		TIOCM_DTR
#define DML_RTS		TIOCM_RTS
#define DML_CTS		TIOCM_CTS
#define DML_DCD		TIOCM_CD
#define DML_RI		TIOCM_RI
#define DML_DSR		TIOCM_DSR
#define DML_BRK		0100000		/* no equivalent, we will mask */

#define DHU_READ_WORD(reg) \
	bus_space_read_2(sc->sc_iot, sc->sc_ioh, reg)
#define DHU_WRITE_WORD(reg, val) \
	bus_space_write_2(sc->sc_iot, sc->sc_ioh, reg, val)
#define DHU_READ_BYTE(reg) \
	bus_space_read_1(sc->sc_iot, sc->sc_ioh, reg)
#define DHU_WRITE_BYTE(reg, val) \
	bus_space_write_1(sc->sc_iot, sc->sc_ioh, reg, val)

/*  On a stock DHV, channel pairs (0/1, 2/3, etc.) must use */
/* a baud rate from the same group.  So limiting to B is likely */
/* best, although clone boards like the ABLE QHV allow all settings. */

static const struct speedtab dhuspeedtab[] = {
  {       0,	0		},	/* Groups  */
  {      50,	DHU_LPR_B50	},	/* A	   */
  {      75,	DHU_LPR_B75	},	/* 	 B */
  {     110,	DHU_LPR_B110	},	/* A and B */
  {     134,	DHU_LPR_B134	},	/* A and B */
  {     150,	DHU_LPR_B150	},	/* 	 B */
  {     300,	DHU_LPR_B300	},	/* A and B */
  {     600,	DHU_LPR_B600	},	/* A and B */
  {    1200,	DHU_LPR_B1200	},	/* A and B */
  {    1800,	DHU_LPR_B1800	},	/* 	 B */
  {    2000,	DHU_LPR_B2000	},	/* 	 B */
  {    2400,	DHU_LPR_B2400	},	/* A and B */
  {    4800,	DHU_LPR_B4800	},	/* A and B */
  {    7200,	DHU_LPR_B7200	},	/* A	   */
  {    9600,	DHU_LPR_B9600	},	/* A and B */
  {   19200,	DHU_LPR_B19200	},	/* 	 B */
  {   38400,	DHU_LPR_B38400	},	/* A	   */
  {      -1,	-1		}
};

static int	dhu_match(struct device *, struct cfdata *, void *);
static void	dhu_attach(struct device *, struct device *, void *);
static	void	dhurint(void *);
static	void	dhuxint(void *);
static	void	dhustart(struct tty *);
static	int	dhuparam(struct tty *, struct termios *);
static	int	dhuiflow(struct tty *, int);
static unsigned	dhumctl(struct dhu_softc *,int, int, int);
	int	dhuopen(dev_t, int, int, struct proc *);
	int	dhuclose(dev_t, int, int, struct proc *);
	int	dhuread(dev_t, struct uio *, int);
	int	dhuwrite(dev_t, struct uio *, int);
	int	dhuioctl(dev_t, u_long, caddr_t, int, struct proc *);
	void	dhustop(struct tty *, int);
struct tty *	dhutty(dev_t);

struct	cfattach dhu_ca = {
	sizeof(struct dhu_softc), (cfmatch_t)dhu_match, dhu_attach
};

struct	cfdriver dhu_cd = {
	NULL, "dhu", DV_TTY
};

/* Autoconfig handles: setup the controller to interrupt, */
/* then complete the housecleaning for full operation */

static int
dhu_match(parent, cf, aux)
        struct device *parent;
	struct cfdata *cf;
        void *aux;
{
	struct uba_attach_args *ua = aux;
	int n;

	/* Reset controller to initialize, enable TX/RX interrupts */
	/* to catch floating vector info elsewhere when completed */

	bus_space_write_2(ua->ua_iot, ua->ua_ioh, DHU_UBA_CSR,
	    DHU_CSR_MASTER_RESET | DHU_CSR_RXIE | DHU_CSR_TXIE);

	/* Now wait up to 3 seconds for self-test to complete. */

	for (n = 0; n < 300; n++) {
		DELAY(10000);
		if ((bus_space_read_2(ua->ua_iot, ua->ua_ioh, DHU_UBA_CSR) &
		    DHU_CSR_MASTER_RESET) == 0)
			break;
	}

	/* If the RESET did not clear after 3 seconds, */
	/* the controller must be broken. */

	if (n >= 300)
		return 0;

	/* Check whether diagnostic run has signalled a failure. */

	if ((bus_space_read_2(ua->ua_iot, ua->ua_ioh, DHU_UBA_CSR) &
	    DHU_CSR_DIAG_FAIL) != 0)
		return 0;

       	return 1;
}

static void
dhu_attach(parent, self, aux)
        struct device *parent, *self;
        void *aux;
{
	struct dhu_softc *sc = (void *)self;
	struct uba_attach_args *ua = aux;
	unsigned c;
	int n, i;

	sc->sc_iot = ua->ua_iot;
	sc->sc_ioh = ua->ua_ioh;
	sc->sc_dmat = ua->ua_dmat;
	/* Process the 8 bytes of diagnostic info put into */
	/* the FIFO following the master reset operation. */

	printf("\n%s:", self->dv_xname);
	for (n = 0; n < 8; n++) {
		c = DHU_READ_WORD(DHU_UBA_RBUF);

		if ((c&DHU_DIAG_CODE) == DHU_DIAG_CODE) {
			if ((c&0200) == 0000)
				printf(" rom(%d) version %d",
					((c>>1)&01), ((c>>2)&037));
			else if (((c>>2)&07) != 0)
				printf(" diag-error(proc%d)=%x",
					((c>>1)&01), ((c>>2)&07));
		}
	}

	c = DHU_READ_WORD(DHU_UBA_STAT);

	sc->sc_type = (c & DHU_STAT_DHU) ? IS_DHU : IS_DHV;

	if (sc->sc_type == IS_DHU) {
		if (c & DHU_STAT_MDL)
			sc->sc_lines = 16;	/* "Modem Low" */
		else
			sc->sc_lines = 8;	/* Has modem support */
	} else
		sc->sc_lines = 8;

	printf("\n%s: DH%s-11 %d lines\n", self->dv_xname,
	    (sc->sc_type == IS_DHU) ? "U" : "V", sc->sc_lines);

	for (i = 0; i < sc->sc_lines; i++) {
		struct tty *tp;
		tp = sc->sc_dhu[i].dhu_tty = ttymalloc(0);
		sc->sc_dhu[i].dhu_state = STATE_IDLE;
		bus_dmamap_create(sc->sc_dmat, tp->t_outq.c_cn, 1,
		    tp->t_outq.c_cn, 0, BUS_DMA_ALLOCNOW|BUS_DMA_NOWAIT,
		    &sc->sc_dhu[i].dhu_dmah);
		bus_dmamap_load(sc->sc_dmat, sc->sc_dhu[i].dhu_dmah,
		    tp->t_outq.c_cs, tp->t_outq.c_cn, 0, BUS_DMA_NOWAIT);

	}

	/* Now establish RX & TX interrupt handlers */

	uba_intr_establish(ua->ua_icookie, ua->ua_cvec,
	    dhurint, sc, &sc->sc_rintrcnt);
	uba_intr_establish(ua->ua_icookie, ua->ua_cvec + 4,
	    dhuxint, sc, &sc->sc_tintrcnt);

	sc->sc_rcvec = ua->ua_cvec;
	evcount_attach(&sc->sc_rintrcnt, sc->sc_dev.dv_xname, &sc->sc_rcvec);
	sc->sc_tcvec = ua->ua_cvec + 4;
	evcount_attach(&sc->sc_tintrcnt, sc->sc_dev.dv_xname, &sc->sc_tcvec);
}

/* Receiver Interrupt */

static void
dhurint(arg)
	void *arg;
{
	struct	dhu_softc *sc = arg;
	struct tty *tp;
	int cc, line;
	unsigned c, delta;
	int overrun = 0;

	while ((c = DHU_READ_WORD(DHU_UBA_RBUF)) & DHU_RBUF_DATA_VALID) {

		/* Ignore diagnostic FIFO entries. */

		if ((c & DHU_DIAG_CODE) == DHU_DIAG_CODE)
			continue;

		cc = c & 0xFF;
		line = DHU_LINE(c>>8);
		tp = sc->sc_dhu[line].dhu_tty;

		/* LINK.TYPE is set so we get modem control FIFO entries */

		if ((c & DHU_DIAG_CODE) == DHU_MODEM_CODE) {
			c = (c << 8);
			/* Do MDMBUF flow control, wakeup sleeping opens */
			if (c & DHU_STAT_DCD) {
				if (!(tp->t_state & TS_CARR_ON))
				    (void)(*linesw[tp->t_line].l_modem)(tp, 1);
			}
			else if ((tp->t_state & TS_CARR_ON) &&
			    (*linesw[tp->t_line].l_modem)(tp, 0) == 0)
				(void) dhumctl(sc, line, 0, DMSET);

			/* Do CRTSCTS flow control */
			delta = c ^ sc->sc_dhu[line].dhu_modem;
			sc->sc_dhu[line].dhu_modem = c;
			if ((delta & DHU_STAT_CTS) &&
			    (tp->t_state & TS_ISOPEN) &&
			    (tp->t_cflag & CRTSCTS)) {
				if (c & DHU_STAT_CTS) {
					tp->t_state &= ~TS_TTSTOP;
					ttstart(tp);
				} else {
					tp->t_state |= TS_TTSTOP;
					dhustop(tp, 0);
				}
			}
			continue;
		}

		if (!(tp->t_state & TS_ISOPEN)) {
			wakeup((caddr_t)&tp->t_rawq);
			continue;
		}

		if ((c & DHU_RBUF_OVERRUN_ERR) && overrun == 0) {
			log(LOG_WARNING, "%s: silo overflow, line %d\n",
				sc->sc_dev.dv_xname, line);
			overrun = 1;
		}
		/* A BREAK key will appear as a NULL with a framing error */
		if (c & DHU_RBUF_FRAMING_ERR)
			cc |= TTY_FE;
		if (c & DHU_RBUF_PARITY_ERR)
			cc |= TTY_PE;

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

/* Transmitter Interrupt */

static void
dhuxint(arg)
	void *arg;
{
	struct	dhu_softc *sc = arg;
	struct tty *tp;
	int line, i;

	while ((i = DHU_READ_BYTE(DHU_UBA_CSR_HI)) & (DHU_CSR_TX_ACTION >> 8)) {

		line = DHU_LINE(i);

		tp = sc->sc_dhu[line].dhu_tty;

		if (i & (DHU_CSR_TX_DMA_ERROR >> 8))
			printf("dhu%d: DMA ERROR on line: %d\n",
			    DHU_M2U(minor(tp->t_dev)), line);

		if (i & (DHU_CSR_DIAG_FAIL >> 8))
			printf("dhu%d: DIAG FAIL on line: %d\n",
			    DHU_M2U(minor(tp->t_dev)), line);

		tp->t_state &= ~TS_BUSY;

		if (tp->t_state & TS_FLUSH)
			tp->t_state &= ~TS_FLUSH;
		else {
			if (sc->sc_dhu[line].dhu_state == STATE_DMA_STOPPED)
				sc->sc_dhu[line].dhu_cc -=
				DHU_READ_WORD(DHU_UBA_TBUFCNT);
			ndflush(&tp->t_outq, sc->sc_dhu[line].dhu_cc);
			sc->sc_dhu[line].dhu_cc = 0;
		}

		sc->sc_dhu[line].dhu_state = STATE_IDLE;

		if (tp->t_line)
			(*linesw[tp->t_line].l_start)(tp);
		else
			dhustart(tp);
	}
}

int
dhuopen(dev, flag, mode, p)
	dev_t dev;
	int flag, mode;
	struct proc *p;
{
	struct tty *tp;
	int unit, line;
	struct dhu_softc *sc;
	int s, error = 0;

	unit = DHU_M2U(minor(dev));
	line = DHU_LINE(minor(dev));

	if (unit >= dhu_cd.cd_ndevs || dhu_cd.cd_devs[unit] == NULL)
		return (ENXIO);

	sc = dhu_cd.cd_devs[unit];

	if (line >= sc->sc_lines)
		return ENXIO;

	if (sc->sc_type == IS_DHU) {
		s = spltty();		/* CSR 3:0 must be 0 */
		DHU_WRITE_BYTE(DHU_UBA_CSR, DHU_CSR_RXIE);
		DHU_WRITE_BYTE(DHU_UBA_RXTIME, 10);
		splx(s);		/* RX int delay 10ms */
	}

	s = spltty();
	DHU_WRITE_BYTE(DHU_UBA_CSR, DHU_CSR_RXIE | line);
	sc->sc_dhu[line].dhu_modem = DHU_READ_WORD(DHU_UBA_STAT);
	splx(s);

	tp = sc->sc_dhu[line].dhu_tty;

	tp->t_oproc   = dhustart;
	tp->t_param   = dhuparam;
	tp->t_hwiflow = dhuiflow;
	tp->t_dev = dev;
	if ((tp->t_state & TS_ISOPEN) == 0) {
		tp->t_state |= TS_WOPEN; /* XXX */
		ttychars(tp);
		if (tp->t_ispeed == 0) {
			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;
		}
		(void) dhuparam(tp, &tp->t_termios);
		ttsetwater(tp);
	} else if ((tp->t_state & TS_XCLUDE) && suser(curproc, 0) != 0)
		return (EBUSY);
	/* Use DMBIS and *not* DMSET or else we clobber incoming bits */
	if (dhumctl(sc, line, DML_DTR|DML_RTS, DMBIS) & DML_DCD)
		tp->t_state |= TS_CARR_ON;
	s = spltty();
	while (!(flag & O_NONBLOCK) && !(tp->t_cflag & CLOCAL) &&
	       !(tp->t_state & TS_CARR_ON)) {
		tp->t_state |= TS_WOPEN; /* XXX */
		error = ttysleep(tp, (caddr_t)&tp->t_rawq,
				TTIPRI | PCATCH, ttopen, 0);
		if (error)
			break;
	}
	splx(s);
	if (error)
		return (error);
	return ((*linesw[tp->t_line].l_open)(dev, tp, p));
}

/*ARGSUSED*/
int
dhuclose(dev, flag, mode, p)
	dev_t dev;
	int flag, mode;
	struct proc *p;
{
	struct tty *tp;
	int unit, line;
	struct dhu_softc *sc;

	unit = DHU_M2U(minor(dev));
	line = DHU_LINE(minor(dev));

	sc = dhu_cd.cd_devs[unit];

	tp = sc->sc_dhu[line].dhu_tty;

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

	/* Make sure a BREAK state is not left enabled. */

	(void) dhumctl(sc, line, DML_BRK, DMBIC);

	/* Do a hangup if so required. */

	if ((tp->t_cflag & HUPCL) || (tp->t_state & TS_WOPEN) || /* XXX */
	    !(tp->t_state & TS_ISOPEN))
		(void) dhumctl(sc, line, 0, DMSET);

	return (ttyclose(tp));
}

int
dhuread(dev, uio, flag)
	dev_t dev;
	struct uio *uio;
{
	struct dhu_softc *sc;
	struct tty *tp;

	sc = dhu_cd.cd_devs[DHU_M2U(minor(dev))];

	tp = sc->sc_dhu[DHU_LINE(minor(dev))].dhu_tty;
	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
}

int
dhuwrite(dev, uio, flag)
	dev_t dev;
	struct uio *uio;
{
	struct dhu_softc *sc;
	struct tty *tp;

	sc = dhu_cd.cd_devs[DHU_M2U(minor(dev))];

	tp = sc->sc_dhu[DHU_LINE(minor(dev))].dhu_tty;
	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
}

/*ARGSUSED*/
int
dhuioctl(dev, cmd, data, flag, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flag;
	struct proc *p;
{
	struct dhu_softc *sc;
	struct tty *tp;
	int unit, line;
	int error;

	unit = DHU_M2U(minor(dev));
	line = DHU_LINE(minor(dev));
	sc = dhu_cd.cd_devs[unit];
	tp = sc->sc_dhu[line].dhu_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);

	switch (cmd) {

	case TIOCSBRK:
		(void) dhumctl(sc, line, DML_BRK, DMBIS);
		break;

	case TIOCCBRK:
		(void) dhumctl(sc, line, DML_BRK, DMBIC);
		break;

	case TIOCSDTR:
		(void) dhumctl(sc, line, DML_DTR|DML_RTS, DMBIS);
		break;

	case TIOCCDTR:
		(void) dhumctl(sc, line, DML_DTR|DML_RTS, DMBIC);
		break;

	case TIOCMSET:
		(void) dhumctl(sc, line, *(int *)data, DMSET);
		break;

	case TIOCMBIS:
		(void) dhumctl(sc, line, *(int *)data, DMBIS);
		break;

	case TIOCMBIC:
		(void) dhumctl(sc, line, *(int *)data, DMBIC);
		break;

	case TIOCMGET:
		*(int *)data = (dhumctl(sc, line, 0, DMGET) & ~DML_BRK);
		break;

	default:
		return (ENOTTY);
	}
	return (0);
}

struct tty *
dhutty(dev)
        dev_t dev;
{
	struct dhu_softc *sc = dhu_cd.cd_devs[DHU_M2U(minor(dev))];
	struct tty *tp = sc->sc_dhu[DHU_LINE(minor(dev))].dhu_tty;
        return (tp);
}

/*ARGSUSED*/
void
dhustop(tp, flag)
	struct tty *tp;
{
	struct dhu_softc *sc;
	int line;
	int s;

	s = spltty();

	if (tp->t_state & TS_BUSY) {

		sc = dhu_cd.cd_devs[DHU_M2U(minor(tp->t_dev))];
		line = DHU_LINE(minor(tp->t_dev));

		if (sc->sc_dhu[line].dhu_state == STATE_DMA_RUNNING) {

			sc->sc_dhu[line].dhu_state = STATE_DMA_STOPPED;

			DHU_WRITE_BYTE(DHU_UBA_CSR, DHU_CSR_RXIE | line);
			DHU_WRITE_WORD(DHU_UBA_LNCTRL,
			    DHU_READ_WORD(DHU_UBA_LNCTRL) |
			    DHU_LNCTRL_DMA_ABORT);
		}

		if (!(tp->t_state & TS_TTSTOP))
			tp->t_state |= TS_FLUSH;
	}
	splx(s);
}

static void
dhustart(tp)
	struct tty *tp;
{
	struct dhu_softc *sc;
	int line, cc;
	int addr;
	int s;

	s = spltty();

	if (tp->t_state & (TS_TIMEOUT|TS_BUSY|TS_TTSTOP))
		goto out;
	ttwakeupwr(tp);
	if (tp->t_outq.c_cc == 0)
		goto out;
	cc = ndqb(&tp->t_outq, 0);
	if (cc == 0)
		goto out;

	tp->t_state |= TS_BUSY;

	sc = dhu_cd.cd_devs[DHU_M2U(minor(tp->t_dev))];

	line = DHU_LINE(minor(tp->t_dev));

	DHU_WRITE_BYTE(DHU_UBA_CSR, DHU_CSR_RXIE | line);

	sc->sc_dhu[line].dhu_cc = cc;

	if (cc == 1 && sc->sc_type == IS_DHV) {

		sc->sc_dhu[line].dhu_state = STATE_TX_ONE_CHAR;

		DHU_WRITE_WORD(DHU_UBA_TXCHAR,
		    DHU_TXCHAR_DATA_VALID | *tp->t_outq.c_cf);
	} else {
		sc->sc_dhu[line].dhu_state = STATE_DMA_RUNNING;

		addr = sc->sc_dhu[line].dhu_dmah->dm_segs[0].ds_addr +
			(tp->t_outq.c_cf - tp->t_outq.c_cs);

		DHU_WRITE_WORD(DHU_UBA_TBUFCNT, cc);
		DHU_WRITE_WORD(DHU_UBA_TBUFAD1, addr & 0xFFFF);
		DHU_WRITE_WORD(DHU_UBA_TBUFAD2, ((addr>>16) & 0x3F) |
		    DHU_TBUFAD2_TX_ENABLE);
		DHU_WRITE_WORD(DHU_UBA_LNCTRL,
		    DHU_READ_WORD(DHU_UBA_LNCTRL) & ~DHU_LNCTRL_DMA_ABORT);
		DHU_WRITE_WORD(DHU_UBA_TBUFAD2,
		    DHU_READ_WORD(DHU_UBA_TBUFAD2) | DHU_TBUFAD2_DMA_START);
	}
out:
	splx(s);
	return;
}

static int
dhuparam(tp, t)
	struct tty *tp;
	struct termios *t;
{
	struct dhu_softc *sc;
	int cflag = t->c_cflag;
	int ispeed = ttspeedtab(t->c_ispeed, dhuspeedtab);
	int ospeed = ttspeedtab(t->c_ospeed, dhuspeedtab);
	unsigned lpr, lnctrl;
	int unit, line;
	int s;

	unit = DHU_M2U(minor(tp->t_dev));
	line = DHU_LINE(minor(tp->t_dev));

	sc = dhu_cd.cd_devs[unit];

	/* check requested parameters */
        if (ospeed < 0 || ispeed < 0)
                return (EINVAL);

        tp->t_ispeed = t->c_ispeed;
        tp->t_ospeed = t->c_ospeed;
        tp->t_cflag = cflag;

	if (ospeed == 0) {
		(void) dhumctl(sc, line, 0, DMSET);	/* hang up line */
		return (0);
	}

	s = spltty();
	DHU_WRITE_BYTE(DHU_UBA_CSR, DHU_CSR_RXIE | line);

	lpr = ((ispeed&017)<<8) | ((ospeed&017)<<12) ;

	switch (cflag & CSIZE) {

	case CS5:
		lpr |= DHU_LPR_5_BIT_CHAR;
		break;

	case CS6:
		lpr |= DHU_LPR_6_BIT_CHAR;
		break;

	case CS7:
		lpr |= DHU_LPR_7_BIT_CHAR;
		break;

	default:
		lpr |= DHU_LPR_8_BIT_CHAR;
		break;
	}

	if (cflag & PARENB)
		lpr |= DHU_LPR_PARENB;
	if (!(cflag & PARODD))
		lpr |= DHU_LPR_EPAR;
	if (cflag & CSTOPB)
		lpr |= DHU_LPR_2_STOP;

	DHU_WRITE_WORD(DHU_UBA_LPR, lpr);

	DHU_WRITE_WORD(DHU_UBA_TBUFAD2,
	    DHU_READ_WORD(DHU_UBA_TBUFAD2) | DHU_TBUFAD2_TX_ENABLE);

	lnctrl = DHU_READ_WORD(DHU_UBA_LNCTRL);

	/* Setting LINK.TYPE enables modem signal change interrupts. */

	lnctrl |= (DHU_LNCTRL_RX_ENABLE | DHU_LNCTRL_LINK_TYPE);

	/* Enable the auto XON/XOFF feature on the controller */

	if (t->c_iflag & IXON)
		lnctrl |= DHU_LNCTRL_OAUTO;
	else
		lnctrl &= ~DHU_LNCTRL_OAUTO;

	if (t->c_iflag & IXOFF)
		lnctrl |= DHU_LNCTRL_IAUTO;
	else
		lnctrl &= ~DHU_LNCTRL_IAUTO;

	DHU_WRITE_WORD(DHU_UBA_LNCTRL, lnctrl);

	splx(s);
	return (0);
}

static int
dhuiflow(tp, flag)
	struct tty *tp;
	int flag;
{
	struct dhu_softc *sc;
	int line = DHU_LINE(minor(tp->t_dev));

	if (tp->t_cflag & CRTSCTS) {
		sc = dhu_cd.cd_devs[DHU_M2U(minor(tp->t_dev))];
		(void) dhumctl(sc, line, DML_RTS, ((flag)? DMBIC: DMBIS));
		return (1);
	}
	return (0);
}

static unsigned
dhumctl(sc, line, bits, how)
	struct dhu_softc *sc;
	int line, bits, how;
{
	unsigned status;
	unsigned lnctrl;
	unsigned mbits;
	int s;

	s = spltty();

	DHU_WRITE_BYTE(DHU_UBA_CSR, DHU_CSR_RXIE | line);

	mbits = 0;

	/* external signals as seen from the port */

	status = DHU_READ_WORD(DHU_UBA_STAT);

	if (status & DHU_STAT_CTS)
		mbits |= DML_CTS;

	if (status & DHU_STAT_DCD)
		mbits |= DML_DCD;

	if (status & DHU_STAT_DSR)
		mbits |= DML_DSR;

	if (status & DHU_STAT_RI)
		mbits |= DML_RI;

	/* internal signals/state delivered to port */

	lnctrl = DHU_READ_WORD(DHU_UBA_LNCTRL);

	if (lnctrl & DHU_LNCTRL_RTS)
		mbits |= DML_RTS;

	if (lnctrl & DHU_LNCTRL_DTR)
		mbits |= DML_DTR;

	if (lnctrl & DHU_LNCTRL_BREAK)
		mbits |= DML_BRK;

	switch (how) {

	case DMSET:
		mbits = bits;
		break;

	case DMBIS:
		mbits |= bits;
		break;

	case DMBIC:
		mbits &= ~bits;
		break;

	case DMGET:
		splx(s);
		return (mbits);
	}

	if (mbits & DML_RTS)
		lnctrl |= DHU_LNCTRL_RTS;
	else
		lnctrl &= ~DHU_LNCTRL_RTS;

	if (mbits & DML_DTR)
		lnctrl |= DHU_LNCTRL_DTR;
	else
		lnctrl &= ~DHU_LNCTRL_DTR;

	if (mbits & DML_BRK)
		lnctrl |= DHU_LNCTRL_BREAK;
	else
		lnctrl &= ~DHU_LNCTRL_BREAK;

	DHU_WRITE_WORD(DHU_UBA_LNCTRL, lnctrl);

	splx(s);
	return (mbits);
}


code:
/*	$OpenBSD: dhureg.h,v 1.4 2003/04/06 01:33:32 hugh Exp $	*/
/*	$NetBSD: dhureg.h,v 1.4 1999/05/28 20:17:29 ragge Exp $	*/
/*
 * Copyright (c) 1996  Ken C. Wellsch.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. 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.
 */

#ifdef notdef
union w_b
{
	u_short word;
	struct {
		u_char byte_lo;
		u_char byte_hi;
	} bytes;
};

struct DHUregs
{
	volatile union w_b u_csr;	/* Control/Status Register (R/W) */
	volatile u_short dhu_rbuf;	/* Receive Buffer (R only) */
#define dhu_txchar	 dhu_rbuf	/* Transmit Character (W only) */
	volatile u_short dhu_lpr;	/* Line Parameter Register (R/W) */
	volatile u_short dhu_stat;	/* Line Status (R only) */
	volatile u_short dhu_lnctrl;	/* Line Control (R/W) */
	volatile u_short dhu_tbufad1;	/* Transmit Buffer Address 1 (R/W) */
	volatile u_short dhu_tbufad2;	/* Transmit Buffer Address 2 (R/W) */
	volatile u_short dhu_tbufcnt;	/* Transmit Buffer Count (R/W) */
};

#define dhu_csr		u_csr.word
#define dhu_csr_lo	u_csr.bytes.byte_lo
#define dhu_csr_hi	u_csr.bytes.byte_hi

typedef struct DHUregs dhuregs;
#endif

#define	DHU_UBA_CSR	0
#define	DHU_UBA_CSR_HI	1
#define	DHU_UBA_RBUF	2
#define	DHU_UBA_TXCHAR	2
#define	DHU_UBA_RXTIME	DHU_UBA_TXCHAR	/* on a real dhu only */
#define	DHU_UBA_LPR	4
#define	DHU_UBA_STAT	6
#define	DHU_UBA_FIFO	DHU_UBA_STAT	/* on a real dhu only */
#define	DHU_UBA_LNCTRL	8
#define	DHU_UBA_TBUFAD1	10
#define	DHU_UBA_TBUFAD2	12
#define	DHU_UBA_TBUFCNT	14

/* CSR bits */

#define DHU_CSR_TX_ACTION	0100000
#define DHU_CSR_TXIE		0040000
#define DHU_CSR_DIAG_FAIL	0020000
#define DHU_CSR_TX_DMA_ERROR	0010000
#define DHU_CSR_TX_LINE_MASK	0007400
#define DHU_CSR_RX_DATA_AVAIL	0000200
#define DHU_CSR_RXIE		0000100
#define DHU_CSR_MASTER_RESET	0000040
#define DHU_CSR_UNUSED		0000020
#define DHU_CSR_CHANNEL_MASK	0000017

/* RBUF bits */

#define DHU_RBUF_DATA_VALID	0100000
#define DHU_RBUF_OVERRUN_ERR	0040000
#define DHU_RBUF_FRAMING_ERR	0020000
#define DHU_RBUF_PARITY_ERR	0010000
#define DHU_RBUF_RX_LINE_MASK	0007400

#define DHU_DIAG_CODE		0070001
#define DHU_MODEM_CODE		0070000

/* TXCHAR bits */

#define DHU_TXCHAR_DATA_VALID	0100000

/* LPR bits */

#define DHU_LPR_B50		0x0
#define DHU_LPR_B75		0x1
#define DHU_LPR_B110		0x2
#define DHU_LPR_B134		0x3
#define DHU_LPR_B150		0x4
#define DHU_LPR_B300		0x5
#define DHU_LPR_B600		0x6
#define DHU_LPR_B1200		0x7
#define DHU_LPR_B1800		0x8
#define DHU_LPR_B2000		0x9
#define DHU_LPR_B2400		0xA
#define DHU_LPR_B4800		0xB
#define DHU_LPR_B7200		0xC
#define DHU_LPR_B9600		0xD
#define DHU_LPR_B19200		0xE
#define DHU_LPR_B38400		0xF

#define DHU_LPR_5_BIT_CHAR	0000000
#define DHU_LPR_6_BIT_CHAR	0000010
#define DHU_LPR_7_BIT_CHAR	0000020
#define DHU_LPR_8_BIT_CHAR	0000030
#define DHU_LPR_PARENB		0000040
#define DHU_LPR_EPAR		0000100
#define DHU_LPR_2_STOP		0000200

/* STAT bits */

#define DHU_STAT_DSR		0100000
#define DHU_STAT_RI		0020000
#define DHU_STAT_DCD		0010000
#define DHU_STAT_CTS		0004000
#define DHU_STAT_MDL		0001000
#define DHU_STAT_DHU		0000400

/* LNCTRL bits */

#define DHU_LNCTRL_DMA_ABORT	0000001
#define DHU_LNCTRL_IAUTO	0000002
#define DHU_LNCTRL_RX_ENABLE	0000004
#define DHU_LNCTRL_BREAK	0000010
#define DHU_LNCTRL_OAUTO	0000020
#define DHU_LNCTRL_FORCE_XOFF	0000040
#define DHU_LNCTRL_LINK_TYPE	0000400
#define DHU_LNCTRL_DTR		0001000
#define DHU_LNCTRL_RTS		0010000

/* TBUFAD2 bits */

#define DHU_TBUFAD2_DMA_START	0000200
#define DHU_TBUFAD2_TX_ENABLE	0100000

license: unknown


code:
/*	$OpenBSD: dl.c,v 1.12 2010/07/02 17:27:01 nicm Exp $	*/
/*	$NetBSD: dl.c,v 1.11 2000/01/24 02:40:29 matt Exp $	*/

/*-
 * Copyright (c) 1996, 1997 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Jason R. Thorpe.
 *
 * 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) 1997  Ben Harris.  All rights reserved.
 * Copyright (c) 1996  Ken C. Wellsch.  All rights reserved.
 * Copyright (c) 1982, 1986, 1990, 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * 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.
 */

/*
 * dl.c -- Device driver for the DL11 and DLV11 serial cards.
 *
 * OS-interface code derived from the dz and dca (hp300) drivers.
 */

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

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

#include <arch/vax/qbus/ubavar.h>
#include <arch/vax/qbus/dlreg.h>

struct dl_softc {
	struct device	sc_dev;
	bus_space_tag_t	sc_iot;
	bus_space_handle_t sc_ioh;
	struct tty	*sc_tty;
};

static	int	dl_match(struct device *, struct cfdata *, void *);
static	void	dl_attach(struct device *, struct device *, void *);
static	void	dlrint(void *);
static	void	dlxint(void *);
static	void	dlstart(struct tty *);
static	int	dlparam(struct tty *, struct termios *);
static	void	dlbrk(struct dl_softc *, int);
struct	tty *	dltty(dev_t);
	int	dlopen(dev_t, int, int, struct proc *);
	int	dlclose(dev_t, int, int, struct proc *);
	int	dlread(dev_t, struct uio *, int);
	int	dlwrite(dev_t, struct uio *, int);
	int	dlioctl(dev_t, int, caddr_t, int, struct proc *);
	void	dlstop(struct tty *, int);

struct cfattach dl_ca = {
	sizeof(struct dl_softc), (cfmatch_t)dl_match, dl_attach
};

struct	cfdriver dl_cd = {
	NULL, "dl", DV_TTY
};

#define	DL_READ_WORD(reg) \
	bus_space_read_2(sc->sc_iot, sc->sc_ioh, reg)
#define	DL_WRITE_WORD(reg, val) \
	bus_space_write_2(sc->sc_iot, sc->sc_ioh, reg, val)
#define	DL_WRITE_BYTE(reg, val) \
	bus_space_write_1(sc->sc_iot, sc->sc_ioh, reg, val)

/* Autoconfig handles: setup the controller to interrupt, */
/* then complete the housecleaning for full operation */

static int
dl_match (parent, cf, aux)
	struct device * parent;
	struct cfdata *cf;
	void *aux;
{
	struct uba_attach_args *ua = aux;

#ifdef DL_DEBUG
	printf("Probing for dl at %lo ... ", (long)ua->ua_iaddr);
#endif

	bus_space_write_2(ua->ua_iot, ua->ua_ioh, DL_UBA_XCSR, DL_XCSR_TXIE);
	if (bus_space_read_2(ua->ua_iot, ua->ua_ioh, DL_UBA_XCSR) !=
	    (DL_XCSR_TXIE | DL_XCSR_TX_READY)) {
#ifdef DL_DEBUG
	        printf("failed (step 1; XCSR = %.4b)\n",
		    bus_space_read_2(ua->ua_iot, ua->ua_ioh, DL_UBA_XCSR),
		    DL_XCSR_BITS);
#endif
		return 0;
	}

	/*
	 * We have to force an interrupt so the uba driver can work
	 * out where we are.  Unfortunately, the only way to make a
	 * DL11 interrupt is to get it to send or receive a
	 * character.  We'll send a NUL and hope it doesn't hurt
	 * anything.
	 */

	bus_space_write_1(ua->ua_iot, ua->ua_ioh, DL_UBA_XBUFL, '\0');
#if 0 /* This test seems to fail 2/3 of the time :-( */
	if (dladdr->dl_xcsr != (DL_XCSR_TXIE)) {
#ifdef DL_DEBUG
	        printf("failed (step 2; XCSR = %.4b)\n", dladdr->dl_xcsr,
		       DL_XCSR_BITS);
#endif
		return 0;
	}
#endif
	DELAY(100000); /* delay 1/10 s for character to transmit */
	if (bus_space_read_2(ua->ua_iot, ua->ua_ioh, DL_UBA_XCSR) !=
	    (DL_XCSR_TXIE | DL_XCSR_TX_READY)) {
#ifdef DL_DEBUG
	        printf("failed (step 3; XCSR = %.4b)\n",
		    bus_space_read_2(ua->ua_iot, ua->ua_ioh, DL_UBA_XCSR),
		    DL_XCSR_BITS);
#endif
		return 0;
	}

        /* What else do I need to do? */

	return 1;

}

static void
dl_attach (parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct dl_softc *sc = (void *)self;
	register struct uba_attach_args *ua = aux;

	sc->sc_iot = ua->ua_iot;
	sc->sc_ioh = ua->ua_ioh;

	/* Tidy up the device */

	DL_WRITE_WORD(DL_UBA_RCSR, DL_RCSR_RXIE);
	DL_WRITE_WORD(DL_UBA_XCSR, DL_XCSR_TXIE);

	/* Initialize our softc structure. Should be done in open? */

	sc->sc_tty = ttymalloc(0);

	/* Now register the TX & RX interrupt handlers */
	uba_intr_establish(ua->ua_icookie, ua->ua_cvec    , dlxint, sc);
	uba_intr_establish(ua->ua_icookie, ua->ua_cvec - 4, dlrint, sc);

	printf("\n");
}

/* Receiver Interrupt Handler */

static void
dlrint(arg)
	void *arg;
{
	struct	dl_softc *sc = arg;
	register struct tty *tp;
	register int cc;
	register unsigned c;

	if (DL_READ_WORD(DL_UBA_RCSR) & DL_RCSR_RX_DONE) {
	        c = DL_READ_WORD(DL_UBA_RBUF);
		cc = c & 0xFF;
		tp = sc->sc_tty;

		if (!(tp->t_state & TS_ISOPEN)) {
			wakeup((caddr_t)&tp->t_rawq);
			return;
		}

		if (c & DL_RBUF_OVERRUN_ERR)
			/*
			 * XXX: This should really be logged somwhere
			 * else where we can afford the time.
			 */
			log(LOG_WARNING, "%s: rx overrun\n",
			    sc->sc_dev.dv_xname);
		if (c & DL_RBUF_FRAMING_ERR)
			cc |= TTY_FE;
		if (c & DL_RBUF_PARITY_ERR)
			cc |= TTY_PE;

		(*linesw[tp->t_line].l_rint)(cc, tp);
	} else
		log(LOG_WARNING, "%s: stray rx interrupt\n",
		    sc->sc_dev.dv_xname);
	return;
}

/* Transmitter Interrupt Handler */

static void
dlxint(arg)
	void *arg;
{
	struct dl_softc *sc = arg;
	register struct tty *tp;

	tp = sc->sc_tty;
	tp->t_state &= ~(TS_BUSY | TS_FLUSH);
	if (tp->t_line)
		(*linesw[tp->t_line].l_start)(tp);
	else
		dlstart(tp);

	return;
}

int
dlopen(dev, flag, mode, p)
	dev_t dev;
	int flag, mode;
	struct proc *p;
{
	register struct tty *tp;
	register int unit;
	struct dl_softc *sc;

	unit = minor(dev);

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

	tp = sc->sc_tty;
	if (tp == NULL)
		return ENODEV;
	tp->t_oproc = dlstart;
	tp->t_param = dlparam;
	tp->t_dev = dev;

	if (!(tp->t_state & TS_ISOPEN)) {
		ttychars(tp);
		tp->t_iflag = TTYDEF_IFLAG;
		tp->t_oflag = TTYDEF_OFLAG;
		/* No modem control, so set CLOCAL. */
		tp->t_cflag = TTYDEF_CFLAG | CLOCAL;
		tp->t_lflag = TTYDEF_LFLAG;
		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;

		dlparam(tp, &tp->t_termios);
		ttsetwater(tp);

	} else if ((tp->t_state & TS_XCLUDE) && suser(p, 0) != 0)
		return EBUSY;

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

/*ARGSUSED*/
int
dlclose(dev, flag, mode, p)
	dev_t dev;
	int flag, mode;
	struct proc *p;
{
	struct dl_softc *sc;
	register struct tty *tp;
	register int unit;

	unit = minor(dev);
	sc = dl_cd.cd_devs[unit];
      	tp = sc->sc_tty;

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

	/* Make sure a BREAK state is not left enabled. */
	dlbrk(sc, 0);

	return (ttyclose(tp));
}

int
dlread(dev, uio, flag)
	dev_t dev;
	struct uio *uio;
	int flag;
{
	register struct tty *tp;
	struct dl_softc *sc;
	register int unit;

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

int
dlwrite(dev, uio, flag)
	dev_t dev;
	struct uio *uio;
	int flag;
{
	register struct tty *tp;
	struct dl_softc *sc;
	register int unit;

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

int
dlioctl(dev, cmd, data, flag, p)
	dev_t dev;
        int cmd;
        caddr_t data;
        int flag;
        struct proc *p;
{
	struct dl_softc *sc;
        register struct tty *tp;
        register int unit;
        int error;

	unit = minor(dev);
	sc = dl_cd.cd_devs[unit];
	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);

	switch (cmd) {

        case TIOCSBRK:
                dlbrk(sc, 1);
                break;

        case TIOCCBRK:
                dlbrk(sc, 0);
                break;

        case TIOCMGET:
		/* No modem control, assume they're all low. */
                *(int *)data = 0;
                break;

        default:
                return (ENOTTY);
        }
        return (0);
}

struct tty *
dltty(dev)
	dev_t dev;
{
	register struct dl_softc* sc;

	sc = dl_cd.cd_devs[minor(dev)];
	return sc->sc_tty;
}

void
dlstop(tp, flag)
	register struct tty *tp;
	int flag;
{
	register struct dl_softc *sc;
	int unit, s;

	unit = minor(tp->t_dev);
	sc = dl_cd.cd_devs[unit];

	s = spltty();

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

static void
dlstart(tp)
	register struct tty *tp;
{
	register struct dl_softc *sc;
	register int unit;
	int s;

	unit = minor(tp->t_dev);
	sc = dl_cd.cd_devs[unit];

	s = spltty();
	if (tp->t_state & (TS_TIMEOUT|TS_BUSY|TS_TTSTOP))
		goto out;
	ttwakeupwr(tp);
	if (tp->t_outq.c_cc == 0)
		goto out;

	if (DL_READ_WORD(DL_UBA_XCSR) & DL_XCSR_TX_READY) {
		tp->t_state |= TS_BUSY;
		DL_WRITE_BYTE(DL_UBA_XBUFL, getc(&tp->t_outq));
	}
out:
	splx(s);
	return;
}

/*ARGSUSED*/
static int
dlparam(tp, t)
        register struct tty *tp;
        register struct termios *t;
{
	/*
	 * All this kind of stuff (speed, character format, whatever)
	 * is set by jumpers on the card.  Changing it is thus rather
	 * tricky for a mere device driver.
	 */
	return 0;
}

static void
dlbrk(sc, state)
	register struct dl_softc *sc;
	int state;
{
	int s = spltty();

	if (state) {
		DL_WRITE_WORD(DL_UBA_XCSR, DL_READ_WORD(DL_UBA_XCSR) |
		    DL_XCSR_TX_BREAK);
	} else {
		DL_WRITE_WORD(DL_UBA_XCSR, DL_READ_WORD(DL_UBA_XCSR) &
		    ~DL_XCSR_TX_BREAK);
	}
	splx(s);
}


code:
/*	$OpenBSD: dlreg.h,v 1.1 2000/04/27 03:14:47 bjc Exp $	*/
/*	$NetBSD: dlreg.h,v 1.3 1999/05/27 16:02:04 ragge Exp $	*/
/*
 * Copyright (c) 1997  Ben Harris.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by Ben Harris.
 * 4. 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.
 */

/*
 * dlreg.h -- Definitions for the DL11 and DLV11 serial cards.
 *
 * Style in imitation of dzreg.h.
 */

#ifdef notdef
union w_b
{
	u_short word;
	struct {
		u_char byte_lo;
		u_char byte_hi;
	} bytes;
};

struct DLregs
{
	volatile u_short dl_rcsr; /* Receive Control/Status Register (R/W) */
	volatile u_short dl_rbuf; /* Receive Buffer (R) */
	volatile u_short dl_xcsr; /* Transmit Control/Status Register (R/W) */
	volatile union w_b u_xbuf; /* Transmit Buffer (W) */
#define dl_xbuf u_xbuf.bytes.byte_lo
};

typedef struct DLregs dlregs;
#endif

#define	DL_UBA_RCSR	0
#define	DL_UBA_RBUF	2
#define	DL_UBA_XCSR	4
#define	DL_UBA_XBUFL	6

/* RCSR bits */

#define DL_RCSR_RX_DONE		0x0080 /* Receiver Done (R) */
#define DL_RCSR_RXIE		0x0040 /* Receiver Interrupt Enable (R/W) */
#define DL_RCSR_READER_ENABLE	0x0001 /* [paper-tape] Reader Enable (W) */
#define DL_RCSR_BITS		"\20\1READER_ENABLE\7RXIE\10RX_DONE\n"

/* RBUF bits */

#define DL_RBUF_ERR		0x8000 /* Error (R) */
#define DL_RBUF_OVERRUN_ERR	0x4000 /* Overrun Error (R) */
#define DL_RBUF_FRAMING_ERR	0x2000 /* Framing Error (R) */
#define DL_RBUF_PARITY_ERR	0x1000 /* Parity Error (R) */
#define DL_RBUF_DATA_MASK	0x00FF /* Receive Data (R) */
#define DL_RBUF_BITS	"\20\15PARITY_ERR\16FRAMING_ERR\17OVERRUN_ERR\20ERR\n"

/* XCSR bits */

#define DL_XCSR_TX_READY	0x0080 /* Transmitter Ready (R) */
#define DL_XCSR_TXIE		0x0040 /* Transmit Interrupt Enable (R/W) */
#define DL_XCSR_TX_BREAK	0x0001 /* Transmit Break (R/W) */
#define DL_XCSR_BITS		"\20\1TX_BREAK\7TXIE\10TX_READY\n"

/* XBUF is just data byte right justified. */


code:
/*	$OpenBSD: dz.c,v 1.22 2010/06/28 14:13:31 deraadt Exp $	*/
/*	$NetBSD: dz.c,v 1.23 2000/06/04 02:14:12 matt Exp $	*/
/*
 * Copyright (c) 1996  Ken C. Wellsch.  All rights reserved.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * 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.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/ioctl.h>
#include <sys/tty.h>
#include <sys/proc.h>
#include <sys/buf.h>
#include <sys/conf.h>
#include <sys/file.h>
#include <sys/uio.h>
#include <sys/kernel.h>
#include <sys/syslog.h>
#include <sys/device.h>
#include <sys/timeout.h>

#ifdef DDB
#include <dev/cons.h>
#endif

#include <machine/bus.h>
#include <machine/pte.h>
#include <machine/trap.h>
#include <machine/cpu.h>

#include <arch/vax/qbus/dzreg.h>
#include <arch/vax/qbus/dzvar.h>

/* Flags used to monitor modem bits, make them understood outside driver */

#define DML_DTR		TIOCM_DTR
#define DML_DCD		TIOCM_CD
#define DML_RI		TIOCM_RI
#define DML_BRK		0100000		/* no equivalent, we will mask */

static const struct speedtab dzspeedtab[] =
{
  {       0,	0		},
  {      50,	DZ_LPR_B50	},
  {      75,	DZ_LPR_B75	},
  {     110,	DZ_LPR_B110	},
  {     134,	DZ_LPR_B134	},
  {     150,	DZ_LPR_B150	},
  {     300,	DZ_LPR_B300	},
  {     600,	DZ_LPR_B600	},
  {    1200,	DZ_LPR_B1200	},
  {    1800,	DZ_LPR_B1800	},
  {    2000,	DZ_LPR_B2000	},
  {    2400,	DZ_LPR_B2400	},
  {    3600,	DZ_LPR_B3600	},
  {    4800,	DZ_LPR_B4800	},
  {    7200,	DZ_LPR_B7200	},
  {    9600,	DZ_LPR_B9600	},
  {   19200,	DZ_LPR_B19200	},
  {      -1,	-1		}
};

static	void	dzstart(struct tty *);
static	int	dzparam(struct tty *, struct termios *);
static	unsigned	dzmctl(struct dz_softc *, int, int, int);
static	void	dzscan(void *);
static	void	dzdrain(struct dz_softc *);

struct	cfdriver dz_cd = {
	NULL, "dz", DV_TTY
};

cdev_decl(dz);

/*
 * The DZ series doesn't interrupt on carrier transitions,
 * so we have to use a timer to watch it.
 */
int	dz_timer = 0;	/* true if timer started */

struct timeout dz_timeout;

void
dzattach(struct dz_softc *sc)
{
	int n;

	sc->sc_rxint = sc->sc_brk = 0;

	sc->sc_dr.dr_tcrw = sc->sc_dr.dr_tcr;
	DZ_WRITE_WORD(sc, dr_csr, DZ_CSR_MSE | DZ_CSR_RXIE | DZ_CSR_TXIE);
	dzdrain(sc);
	DZ_WRITE_BYTE(sc, dr_dtr, 0);
	DZ_WRITE_BYTE(sc, dr_break, 0);

	/* Initialize our softc structure. Should be done in open? */

	for (n = 0; n < sc->sc_type; n++) {
		sc->sc_dz[n].dz_sc = sc;
		sc->sc_dz[n].dz_line = n;
		sc->sc_dz[n].dz_tty = ttymalloc(0);
	}

	/* Alas no interrupt on modem bit changes, so we manually scan */

	if (dz_timer == 0) {
		dz_timer = 1;
		timeout_set(&dz_timeout, dzscan, NULL);
		timeout_add_sec(&dz_timeout, 1);
	}
	printf("\n");
}

/* Receiver Interrupt */

void
dzrint(void *arg)
{
	struct dz_softc *sc = arg;
	struct tty *tp;
	int cc, line;
	unsigned c;
	int overrun = 0;

	sc->sc_rxint++;

	while ((c = DZ_READ_WORD(sc, dr_rbuf)) & DZ_RBUF_DATA_VALID) {
		cc = c & 0xFF;
		line = DZ_PORT(c>>8);
		tp = sc->sc_dz[line].dz_tty;

		/* Must be caught early */
		if (sc->sc_dz[line].dz_catch &&
		    (*sc->sc_dz[line].dz_catch)(sc->sc_dz[line].dz_private, cc))
			continue;

		if (!(tp->t_state & TS_ISOPEN)) {
			wakeup((caddr_t)&tp->t_rawq);
			continue;
		}

		if ((c & DZ_RBUF_OVERRUN_ERR) && overrun == 0) {
			log(LOG_WARNING, "%s: silo overflow, line %d\n",
			    sc->sc_dev.dv_xname, line);
			overrun = 1;
		}

		/* A BREAK key will appear as a NULL with a framing error */
		if (c & DZ_RBUF_FRAMING_ERR)
			cc |= TTY_FE;
		if (c & DZ_RBUF_PARITY_ERR)
			cc |= TTY_PE;

#if defined(DDB) && (defined(VAX410) || defined(VAX43) || defined(VAX46) || defined(VAX48) || defined(VAX49) || defined(VAX53) || defined(VAX60))
		if (tp->t_dev == cn_tab->cn_dev) {
			int j = kdbrint(cc);

			if (j == 1)	/* Escape received, just return */
				continue;

			if (j == 2)	/* Second char wasn't 'D' */
				(*linesw[tp->t_line].l_rint)(27, tp);
		}
#endif

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

/* Transmitter Interrupt */

void
dzxint(void *arg)
{
	struct dz_softc *sc = arg;
	struct tty *tp;
	struct clist *cl;
	int line, ch, csr;
	u_char tcr;

	/*
	 * Switch to POLLED mode.
	 *   Some simple measurements indicated that even on
	 *  one port, by freeing the scanner in the controller
	 *  by either providing a character or turning off
	 *  the port when output is complete, the transmitter
	 *  was ready to accept more output when polled again.
	 *   With just two ports running the game "worms,"
	 *  almost every interrupt serviced both transmitters!
	 *   Each UART is double buffered, so if the scanner
	 *  is quick enough and timing works out, we can even
	 *  feed the same port twice.
	 *
	 * Ragge 980517:
	 * Do not need to turn off interrupts, already at interrupt level.
	 * Remove the pdma stuff; no great need of it right now.
	 */

	while (((csr = DZ_READ_WORD(sc, dr_csr)) & DZ_CSR_TX_READY) != 0) {

		line = DZ_PORT(csr>>8);

		tp = sc->sc_dz[line].dz_tty;
		cl = &tp->t_outq;
		tp->t_state &= ~TS_BUSY;

		/* Just send out a char if we have one */
		/* As long as we can fill the chip buffer, we just loop here */
		if (cl->c_cc) {
			tp->t_state |= TS_BUSY;
			ch = getc(cl);
			DZ_WRITE_BYTE(sc, dr_tbuf, ch);
			continue;
		}
		/* Nothing to send; clear the scan bit */
		/* Clear xmit scanner bit; dzstart may set it again */
		tcr = DZ_READ_WORD(sc, dr_tcrw);
		tcr &= 255;
		tcr &= ~(1 << line);
		DZ_WRITE_BYTE(sc, dr_tcr, tcr);
		if (sc->sc_dz[line].dz_catch)
			continue;

		if (tp->t_state & TS_FLUSH)
			tp->t_state &= ~TS_FLUSH;
		else
			ndflush(&tp->t_outq, cl->c_cc);

		(*linesw[tp->t_line].l_start)(tp);
	}
}

int
dzopen(dev_t dev, int flag, int mode, struct proc *p)
{
	struct tty *tp;
	int unit, line;
	struct	dz_softc *sc;
	int s, error = 0;

	unit = DZ_I2C(minor(dev));
	line = DZ_PORT(minor(dev));
	if (unit >= dz_cd.cd_ndevs ||  dz_cd.cd_devs[unit] == NULL)
		return (ENXIO);

	sc = dz_cd.cd_devs[unit];

	if (line >= sc->sc_type)
		return ENXIO;

	/* if some other device is using the line, it's not available */
	if (sc->sc_dz[line].dz_catch)
		return ENXIO;

	if (sc->sc_openings++ == 0)
		dzdrain(sc);

	tp = sc->sc_dz[line].dz_tty;
	if (tp == NULL)
		return (ENODEV);
	tp->t_oproc   = dzstart;
	tp->t_param   = dzparam;
	tp->t_dev = dev;
	if ((tp->t_state & TS_ISOPEN) == 0) {
		ttychars(tp);
		if (tp->t_ispeed == 0) {
			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;
		}
		(void) dzparam(tp, &tp->t_termios);
		ttsetwater(tp);
	} else if ((tp->t_state & TS_XCLUDE) && suser(p, 0) != 0)
		return (EBUSY);
	/* Use DMBIS and *not* DMSET or else we clobber incoming bits */
	if (dzmctl(sc, line, DML_DTR, DMBIS) & DML_DCD)
		tp->t_state |= TS_CARR_ON;
	s = spltty();
	while (!(flag & O_NONBLOCK) && !(tp->t_cflag & CLOCAL) &&
	       !(tp->t_state & TS_CARR_ON)) {
		error = ttysleep(tp, (caddr_t)&tp->t_rawq,
				TTIPRI | PCATCH, ttopen, 0);
		if (error)
			break;
	}
	splx(s);
	if (error)
		return (error);
	return ((*linesw[tp->t_line].l_open)(dev, tp, p));
}

/*ARGSUSED*/
int
dzclose(dev_t dev, int flag, int mode, struct proc *p)
{
	struct	dz_softc *sc;
	struct tty *tp;
	int unit, line;

	unit = DZ_I2C(minor(dev));
	line = DZ_PORT(minor(dev));
	sc = dz_cd.cd_devs[unit];

	tp = sc->sc_dz[line].dz_tty;

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

	/* Make sure a BREAK state is not left enabled. */
	(void) dzmctl(sc, line, DML_BRK, DMBIC);

	/* Do a hangup if so required. */
	if ((tp->t_cflag & HUPCL) || !(tp->t_state & TS_ISOPEN))
		(void) dzmctl(sc, line, 0, DMSET);

	sc->sc_openings--;
	return (ttyclose(tp));
}

int
dzread(dev_t dev, struct uio *uio, int flag)
{
	struct tty *tp;
	struct	dz_softc *sc;

	sc = dz_cd.cd_devs[DZ_I2C(minor(dev))];

	tp = sc->sc_dz[DZ_PORT(minor(dev))].dz_tty;
	return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
}

int
dzwrite(dev_t dev, struct uio *uio, int flag)
{
	struct tty *tp;
	struct	dz_softc *sc;

	sc = dz_cd.cd_devs[DZ_I2C(minor(dev))];

	tp = sc->sc_dz[DZ_PORT(minor(dev))].dz_tty;
	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
}

/*ARGSUSED*/
int
dzioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
{
	struct	dz_softc *sc;
	struct tty *tp;
	int unit, line;
	int error;

	unit = DZ_I2C(minor(dev));
	line = DZ_PORT(minor(dev));
	sc = dz_cd.cd_devs[unit];
	tp = sc->sc_dz[line].dz_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);

	switch (cmd) {

	case TIOCSBRK:
		(void) dzmctl(sc, line, DML_BRK, DMBIS);
		break;

	case TIOCCBRK:
		(void) dzmctl(sc, line, DML_BRK, DMBIC);
		break;

	case TIOCSDTR:
		(void) dzmctl(sc, line, DML_DTR, DMBIS);
		break;

	case TIOCCDTR:
		(void) dzmctl(sc, line, DML_DTR, DMBIC);
		break;

	case TIOCMSET:
		(void) dzmctl(sc, line, *(int *)data, DMSET);
		break;

	case TIOCMBIS:
		(void) dzmctl(sc, line, *(int *)data, DMBIS);
		break;

	case TIOCMBIC:
		(void) dzmctl(sc, line, *(int *)data, DMBIC);
		break;

	case TIOCMGET:
		*(int *)data = (dzmctl(sc, line, 0, DMGET) & ~DML_BRK);
		break;

	default:
		return (ENOTTY);
	}
	return (0);
}

struct tty *
dztty(dev_t dev)
{
	struct	dz_softc *sc = dz_cd.cd_devs[DZ_I2C(minor(dev))];
        struct tty *tp = sc->sc_dz[DZ_PORT(minor(dev))].dz_tty;

        return (tp);
}

/*ARGSUSED*/
int
dzstop(struct tty *tp, int flag)
{
	int s;

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

void
dzstart(struct tty *tp)
{
	struct dz_softc *sc;
	struct clist *cl;
	int unit, line, s;
	char state;

	unit = DZ_I2C(minor(tp->t_dev));
	line = DZ_PORT(minor(tp->t_dev));
	sc = dz_cd.cd_devs[unit];

	s = spltty();
	if (tp->t_state & (TS_TIMEOUT|TS_BUSY|TS_TTSTOP)) {
		splx(s);
		return;
	}
	cl = &tp->t_outq;
	if (cl->c_cc <= tp->t_lowat) {
		if (tp->t_state & TS_ASLEEP) {
			tp->t_state &= ~TS_ASLEEP;
			wakeup((caddr_t)cl);
		}
		selwakeup(&tp->t_wsel);
	}
	if (cl->c_cc == 0) {
		splx(s);
		return;
	}

	tp->t_state |= TS_BUSY;

	state = DZ_READ_WORD(sc, dr_tcrw) & 255;
	if ((state & (1 << line)) == 0) {
		DZ_WRITE_BYTE(sc, dr_tcr, state | (1 << line));
	}
	dzxint(sc);
	splx(s);
}

static int
dzparam(struct tty *tp, struct termios *t)
{
	struct	dz_softc *sc;
	int cflag = t->c_cflag;
	int unit, line;
	int ispeed = ttspeedtab(t->c_ispeed, dzspeedtab);
	int ospeed = ttspeedtab(t->c_ospeed, dzspeedtab);
	unsigned lpr;
	int s;

	unit = DZ_I2C(minor(tp->t_dev));
	line = DZ_PORT(minor(tp->t_dev));
	sc = dz_cd.cd_devs[unit];

	/* check requested parameters */
        if (ospeed < 0 || ispeed < 0 || ispeed != ospeed)
                return (EINVAL);

        tp->t_ispeed = t->c_ispeed;
        tp->t_ospeed = t->c_ospeed;
        tp->t_cflag = cflag;

	if (ospeed == 0) {
		(void) dzmctl(sc, line, 0, DMSET);	/* hang up line */
		return (0);
	}

	s = spltty();

	lpr = DZ_LPR_RX_ENABLE | ((ispeed&0xF)<<8) | line;

	switch (cflag & CSIZE)
	{
	  case CS5:
		lpr |= DZ_LPR_5_BIT_CHAR;
		break;
	  case CS6:
		lpr |= DZ_LPR_6_BIT_CHAR;
		break;
	  case CS7:
		lpr |= DZ_LPR_7_BIT_CHAR;
		break;
	  default:
		lpr |= DZ_LPR_8_BIT_CHAR;
		break;
	}
	if (cflag & PARENB)
		lpr |= DZ_LPR_PARENB;
	if (cflag & PARODD)
		lpr |= DZ_LPR_OPAR;
	if (cflag & CSTOPB)
		lpr |= DZ_LPR_2_STOP;

	DZ_WRITE_WORD(sc, dr_lpr, lpr);

	splx(s);
	return (0);
}

static unsigned
dzmctl(struct dz_softc *sc, int line, int bits, int how)
{
	unsigned status;
	unsigned mbits;
	unsigned bit;
	int8_t tcr;
	int s;

	s = spltty();

	tcr = DZ_READ_BYTE(sc, dr_tcr);
	bit = (1 << line);

	mbits = 0;

	/* external signals as seen from the port */

	status = DZ_READ_BYTE(sc, dr_dcd) | sc->sc_dsr;

	if (status & bit)
		mbits |= DML_DCD;

	status = DZ_READ_BYTE(sc, dr_ring);

	if (status & bit)
		mbits |= DML_RI;

	/* internal signals/state delivered to port */

	status = DZ_READ_BYTE(sc, dr_dtr);

	if (status & bit)
		mbits |= DML_DTR;

	if (sc->sc_brk & bit)
		mbits |= DML_BRK;

	switch (how)
	{
	  case DMSET:
		mbits = bits;
		break;

	  case DMBIS:
		mbits |= bits;
		break;

	  case DMBIC:
		mbits &= ~bits;
		break;

	  case DMGET:
		splx(s);
		return (mbits);
	}

	if (mbits & DML_DTR) {
		DZ_WRITE_BYTE(sc, dr_dtr, DZ_READ_BYTE(sc, dr_dtr) | bit);
	} else {
		DZ_WRITE_BYTE(sc, dr_dtr, DZ_READ_BYTE(sc, dr_dtr) & ~bit);
	}

	if (mbits & DML_BRK) {
		sc->sc_brk |= bit;
		DZ_WRITE_BYTE(sc, dr_break, sc->sc_brk);
	} else {
		sc->sc_brk &= ~bit;
		DZ_WRITE_BYTE(sc, dr_break, sc->sc_brk);
	}

	/*
	 * On VAXstation 35x0/38x0, writing to the DTR register apparently
	 * affects the TCR register.  Restore its value unconditionally.
	 */
	DZ_WRITE_BYTE(sc, dr_tcr, tcr);

	splx(s);
	return (mbits);
}

/*
 * This is called by timeout() periodically.
 * Check to see if modem status bits have changed.
 */
static void
dzscan(void *arg)
{
	struct dz_softc *sc;
	struct tty *tp;
	int n, bit, port;
	unsigned csr;
	int s;

	s = spltty();

	for (n = 0; n < dz_cd.cd_ndevs; n++) {

		if (dz_cd.cd_devs[n] == NULL)
			continue;

		sc = dz_cd.cd_devs[n];

		for (port = 0; port < sc->sc_type; port++) {

			tp = sc->sc_dz[port].dz_tty;
			bit = (1 << port);

			if ((DZ_READ_BYTE(sc, dr_dcd) | sc->sc_dsr) & bit) {
				if (!(tp->t_state & TS_CARR_ON))
					(*linesw[tp->t_line].l_modem) (tp, 1);
			} else if ((tp->t_state & TS_CARR_ON) &&
			    (*linesw[tp->t_line].l_modem)(tp, 0) == 0) {
				DZ_WRITE_BYTE(sc, dr_tcr,
				    (DZ_READ_WORD(sc, dr_tcrw) & 255) & ~bit);
			}
	    	}

		/*
		 *  If the RX interrupt rate is this high, switch
		 *  the controller to Silo Alarm - which means don't
	 	 *  interrupt until the RX silo has 16 characters in
	 	 *  it (the silo is 64 characters in all).
		 *  Avoid oscillating SA on and off by not turning
		 *  if off unless the rate is appropriately low.
		 */

		csr = DZ_READ_WORD(sc, dr_csr);

		if (sc->sc_rxint > (16*10)) {
			if ((csr & DZ_CSR_SAE) == 0)
				DZ_WRITE_WORD(sc, dr_csr, csr | DZ_CSR_SAE);
	    	} else if ((csr & DZ_CSR_SAE) != 0)
			if (sc->sc_rxint < 10)
				DZ_WRITE_WORD(sc, dr_csr, csr & ~(DZ_CSR_SAE));

		sc->sc_rxint = 0;
	}
	splx(s);
	timeout_add_sec(&dz_timeout, 1);
}

/*
 * Called after an ubareset. The DZ card is reset, but the only thing
 * that must be done is to start the receiver and transmitter again.
 * No DMA setup to care about.
 */
void
dzreset(struct device *dev)
{
	struct dz_softc *sc = (void *)dev;
	struct tty *tp;
	int i;

	for (i = 0; i < sc->sc_type; i++) {
		tp = sc->sc_dz[i].dz_tty;

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

		dzparam(tp, &tp->t_termios);
		dzmctl(sc, i, DML_DTR, DMSET);
		tp->t_state &= ~TS_BUSY;
		dzstart(tp);    /* Kick off transmitter again */
	}
}

/*
 * Drain RX fifo.
 */
static void
dzdrain(struct dz_softc *sc)
{
	while (DZ_READ_WORD(sc, dr_rbuf) & DZ_RBUF_DATA_VALID)
		/*EMPTY*/;
}


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

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

#include <machine/bus.h>
#include <machine/pte.h>
#include <machine/trap.h>
#include <machine/scb.h>

#include <arch/vax/qbus/ubavar.h>

#include <arch/vax/qbus/dzreg.h>
#include <arch/vax/qbus/dzvar.h>

static	int	dz_uba_match(struct device *, struct cfdata *, void *);
static	void	dz_uba_attach(struct device *, struct device *, void *);

struct	cfattach dz_uba_ca = {
	sizeof(struct dz_softc), (cfmatch_t)dz_uba_match, dz_uba_attach
};

/* Autoconfig handles: setup the controller to interrupt, */
/* then complete the housecleaning for full operation */

static int
dz_uba_match(parent, cf, aux)
        struct device *parent;
	struct cfdata *cf;
        void *aux;
{
	struct uba_attach_args *ua = aux;
#ifdef notdef
	bus_space_tag_t	iot = ua->ua_iot;
#endif
	bus_space_handle_t ioh = ua->ua_ioh;
	int n;

	/* Reset controller to initialize, enable TX interrupts */
	/* to catch floating vector info elsewhere when completed */

	bus_space_write_2(iot, ioh, DZ_UBA_CSR, DZ_CSR_MSE | DZ_CSR_TXIE);
	bus_space_write_1(iot, ioh, DZ_UBA_TCR, 1);

	DELAY(100000);	/* delay 1/10 second */

	bus_space_write_2(iot, ioh, DZ_UBA_CSR, DZ_CSR_RESET);

	/* Now wait up to 3 seconds for reset/clear to complete. */

	for (n = 0; n < 300; n++) {
		DELAY(10000);
		if ((bus_space_read_2(iot, ioh, DZ_UBA_CSR)&DZ_CSR_RESET) == 0)
			break;
	}

	/* If the RESET did not clear after 3 seconds, */
	/* the controller must be broken. */

	if (n >= 300)
		return (0);

	/* Register the TX interrupt handler */

       	return (1);
}

static void
dz_uba_attach(parent, self, aux)
        struct device *parent, *self;
        void *aux;
{
	struct	dz_softc *sc = (void *)self;
	struct uba_attach_args *ua = aux;

	sc->sc_iot = ua->ua_iot;
	sc->sc_ioh = ua->ua_ioh;

	sc->sc_dr.dr_csr = DZ_UBA_CSR;
	sc->sc_dr.dr_rbuf = DZ_UBA_RBUF;
	sc->sc_dr.dr_dtr = DZ_UBA_DTR;
	sc->sc_dr.dr_break = DZ_UBA_BREAK;
	sc->sc_dr.dr_tbuf = DZ_UBA_TBUF;
	sc->sc_dr.dr_tcr = DZ_UBA_TCR;
	sc->sc_dr.dr_dcd = DZ_UBA_DCD;
	sc->sc_dr.dr_ring = DZ_UBA_RING;

	sc->sc_type = DZ_DZ;

	/* Now register the TX & RX interrupt handlers */
	sc->sc_tcvec = ua->ua_cvec;
	uba_intr_establish(ua->ua_icookie, sc->sc_tcvec,
	    dzxint, sc, &sc->sc_tintrcnt);
	sc->sc_rcvec = ua->ua_cvec - 4;
	uba_intr_establish(ua->ua_icookie, sc->sc_rcvec,
	    dzrint, sc, &sc->sc_rintrcnt);
	uba_reset_establish(dzreset, self);

	evcount_attach(&sc->sc_rintrcnt, sc->sc_dev.dv_xname, &sc->sc_rcvec);
	evcount_attach(&sc->sc_tintrcnt, sc->sc_dev.dv_xname, &sc->sc_tcvec);

	dzattach(sc);
}


code:
/*	$OpenBSD: dzreg.h,v 1.3 2006/07/31 18:51:06 miod Exp $	*/
/*	$NetBSD: dzreg.h,v 1.4 1999/05/27 16:03:13 ragge Exp $ */
/*
 * Copyright (c) 1996  Ken C. Wellsch.  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. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

struct	dz_regs	{
	bus_addr_t dr_csr;
	bus_addr_t dr_rbuf;
#define dr_lpr	   dr_rbuf
	bus_addr_t dr_dtr;
	bus_addr_t dr_break;
	bus_addr_t dr_tbuf;
	bus_addr_t dr_tcr;
	bus_addr_t dr_tcrw;
	bus_addr_t dr_ring;
	bus_addr_t dr_dcd;
};
#define	DZ_UBA_CSR	0
#define	DZ_UBA_RBUF	2
#define	DZ_UBA_DTR	5
#define	DZ_UBA_BREAK	7
#define	DZ_UBA_TBUF	6
#define	DZ_UBA_TCR	4
#define	DZ_UBA_DCD	7
#define	DZ_UBA_RING	6

/* CSR bits */

#define DZ_CSR_TX_READY		0100000	/* Transmitter Ready */
#define DZ_CSR_TXIE		0040000	/* Transmitter Interrupt Enable */
#define DZ_CSR_SA		0020000	/* Silo Alarm */
#define DZ_CSR_SAE		0010000	/* Silo Alarm Enable */
#define DZ_CSR_TX_LINE_MASK	0007400	/* Which TX line */

#define DZ_CSR_RX_DONE		0000200	/* Receiver Done */
#define DZ_CSR_RXIE		0000100	/* Receiver Interrupt Enable */
#define DZ_CSR_MSE		0000040	/* Master Scan Enable */
#define DZ_CSR_RESET		0000020	/* Clear (reset) Controller */
#define DZ_CSR_MAINTENANCE	0000010
#define DZ_CSR_UNUSED		0000007

/* RBUF bits */

#define DZ_RBUF_DATA_VALID	0100000
#define DZ_RBUF_OVERRUN_ERR	0040000
#define DZ_RBUF_FRAMING_ERR	0020000
#define DZ_RBUF_PARITY_ERR	0010000
#define DZ_RBUF_RX_LINE_MASK	0007400

/* LPR bits */

#define DZ_LPR_UNUSED		0160000
#define DZ_LPR_RX_ENABLE	0010000

#define DZ_LPR_B50		0x0
#define DZ_LPR_B75		0x1
#define DZ_LPR_B110		0x2
#define DZ_LPR_B134		0x3
#define DZ_LPR_B150		0x4
#define DZ_LPR_B300		0x5
#define DZ_LPR_B600		0x6
#define DZ_LPR_B1200		0x7
#define DZ_LPR_B1800		0x8
#define DZ_LPR_B2000		0x9
#define DZ_LPR_B2400		0xA
#define DZ_LPR_B3600		0xB
#define DZ_LPR_B4800		0xC
#define DZ_LPR_B7200		0xD
#define DZ_LPR_B9600		0xE
#define DZ_LPR_B19200		0xF

#define DZ_LPR_OPAR		0000200
#define DZ_LPR_PARENB		0000100
#define DZ_LPR_2_STOP		0000040

#define DZ_LPR_5_BIT_CHAR	0000000
#define DZ_LPR_6_BIT_CHAR	0000010
#define DZ_LPR_7_BIT_CHAR	0000020
#define DZ_LPR_8_BIT_CHAR	0000030

#define DZ_LPR_CHANNEL_MASK	0000007


code:
/*	$OpenBSD: dzvar.h,v 1.7 2008/08/15 22:50:25 miod Exp $	*/
/*	$NetBSD: dzvar.h,v 1.8 2000/06/04 02:14:12 matt Exp $	*/
/*
 * Copyright (c) 1996  Ken C. Wellsch.  All rights reserved.
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * 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.
 */

/* A DZ-11 has 8 ports while a DZV/DZQ-11 has only 4. We use 8 by default */

#define	NDZLINE 	8

#define	DZ_DZ		8
#define	DZ_DZV		4
#define	DZ_DC		4

#define DZ_C2I(c)	((c)<<3)	/* convert controller # to index */
#define DZ_I2C(c)	((c)>>3)	/* convert minor to controller # */
#define DZ_PORT(u)	((u)&07)	/* extract the port # */

struct	dz_softc {
	struct	device	sc_dev;		/* Autoconf blaha */
	struct	evcount	sc_rintrcnt;	/* receive interrupt counts */
	struct	evcount	sc_tintrcnt;	/* transmit interrupt counts */
	int	sc_rcvec, sc_tcvec;	/* XXX used by attachment glue only */
	struct	dz_regs	sc_dr;		/* reg pointers */
	bus_space_tag_t	sc_iot;
	bus_space_handle_t sc_ioh;
	int		sc_type;	/* DZ11 or DZV11? */
	int		sc_rxint;	/* Receive interrupt count XXX */
	int		sc_openings;	/* # of times we've been opened */
	u_char		sc_brk;		/* Break asserted on some lines */
	u_char		sc_dsr;		/* DSR set bits if no mdm ctrl */
	struct dz_linestate {
		struct dz_softc	*dz_sc;		/* backpointer to softc */
		int		dz_line;	/* sub-driver unit number */
		void		*dz_private;	/* sub-driver data pointer */
		int		(*dz_catch)(void *, int); /* Fast catch recv */
		struct	tty *	dz_tty;		/* what we work on */
#ifdef notyet
		caddr_t		dz_mem;		/* pointers to clist output */
		caddr_t		dz_end;		/*   allowing pdma action */
#endif
	} sc_dz[NDZLINE];
};

void   dzattach(struct dz_softc *);
void   dzrint(void *);
void   dzxint(void *);
void   dzreset(struct device *);

#define	DZ_READ_BYTE(sc, adr) \
	bus_space_read_1((sc)->sc_iot, (sc)->sc_ioh, (sc)->sc_dr.adr)
#define	DZ_READ_WORD(sc, adr) \
	bus_space_read_2((sc)->sc_iot, (sc)->sc_ioh, (sc)->sc_dr.adr)
#define	DZ_WRITE_BYTE(sc, adr, val) \
	bus_space_write_1((sc)->sc_iot, (sc)->sc_ioh, (sc)->sc_dr.adr, val)
#define	DZ_WRITE_WORD(sc, adr, val) \
	bus_space_write_2((sc)->sc_iot, (sc)->sc_ioh, (sc)->sc_dr.adr, val)


code:
#	$OpenBSD: files.uba,v 1.4 2011/07/06 18:32:59 miod Exp $
#	$NetBSD: files.uba,v 1.6 1999/06/20 18:09:22 ragge Exp $
#
# Config file and device description for machine-independent
# code for devices Digital Equipment Corp. Unibus and Q22 bus.
# Included by ports that need it.
device	uba {csr}

define	qfont

file	arch/vax/qbus/uba.c				uba

# DZ-11 (-compatible) tty device driver.
device	dz {line = -1}: tty
attach	dz at uba with dz_uba
file	arch/vax/qbus/dz.c				dz needs-flag
file	arch/vax/qbus/dz_uba.c				dz_uba

# DL-11 at UBA
device	dl: tty
attach	dl at uba
file	arch/vax/qbus/dl.c				dl needs-flag

# DHU-11 at UBA
device	dhu: tty
attach	dhu at uba
file	arch/vax/qbus/dhu.c				dhu needs-flag

# UDA50/whatever disk/tape MSCP controller
device	mtc: mscp
attach	mtc at uba
device	uda: mscp
attach	uda at uba
file	arch/vax/qbus/uda.c				uda | mtc

# DEQNA/DELQA Ethernet controller
device	qe: ifnet, ether
attach	qe at uba
file	arch/vax/if/if_qe.c				qe

# DEUNA/DELUA Ethernet controller
device	de: ifnet, ether
attach	de at uba
file	arch/vax/if/if_de.c				de


code:
/*	$OpenBSD: qdreg.h,v 1.5 2007/05/25 21:27:15 krw Exp $	*/
/*	$NetBSD: qdreg.h,v 1.1 1998/03/21 10:02:39 ragge Exp $	*/
/*-
 * Copyright (c) 1982, 1986 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. 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.
 *
 *	@(#)qdreg.h	7.1 (Berkeley) 5/9/91
 */

/************************************************************************
 *									*
 *			Copyright (c) 1985, 1986 by			*
 *		Digital Equipment Corporation, Maynard, MA		*
 *			All rights reserved.				*
 *									*
 *   This software is furnished under a license and may be used and	*
 *   copied  only  in accordance with the terms of such license and	*
 *   with the  inclusion  of  the  above  copyright  notice.   This	*
 *   software  or  any	other copies thereof may not be provided or	*
 *   otherwise made available to any other person.  No title to and	*
 *   ownership of the software is hereby transferred.			*
 *									*
 *   The information in this software is subject to change  without	*
 *   notice  and should not be construed as a commitment by Digital	*
 *   Equipment Corporation.						*
 *									*
 *   Digital assumes no responsibility for the use  or	reliability	*
 *   of its software on equipment which is not supplied by Digital.	*
 *									*
 ************************************************************************/

/* Dragon ADDER reg map */
/* ADDER register bit definitions */
/* Y_SCROLL_CONSTANT */

#define SCROLL_ERASE		0x2000
#define ADDER_SCROLL_DOWN	0x1000

/* ADDER status and interrupt enable registers [1], [2], [3] */

#define DISABLE 		0x0000
#define PAUSE_COMPLETE		0x0001
#define FRAME_SYNC		0x0002
#define INIT_COMPLETE		0x0004
#define RASTEROP_COMPLETE	0x0008

#define ADDRESS_COMPLETE	0x0010
#define RX_READY		0x0020
#define TX_READY		0x0040
#define ID_SCROLL_READY 	0x0080

#define TOP_CLIP		0x0100
#define BOTTOM_CLIP		0x0200
#define LEFT_CLIP		0x0400
#define RIGHT_CLIP		0x0800
#define NO_CLIP 		0x1000
#define VSYNC			0x2000

/* ADDER command register [8], [10] */

#define OCR_zero		0x0000
#define Z_BLOCK0		0x0000
#define OCRA			0x0000
#define OCRB			0x0004
#define RASTEROP		0x02c0
#define PBT			0x03c0
#define BTPZ			0x0bb0
#define PTBZ			0x07a0
#define DTE			0x0400
#define S1E			0x0800
#define S2E			0x1000
#define VIPER_Z_LOAD		0x01A0
#define ID_LOAD 		0x0100
#define CANCEL			0x0000
#define LF_R1			0x0000
#define LF_R2			0x0010
#define LF_R3			0x0020
#define LF_R4			0x0030

/* ADDER rasterop mode register [9] */

#define NORMAL			0x0000
#define LINEAR_PATTERN		0x0002
#define X_FILL			0x0003
#define Y_FILL			0x0007
#define BASELINE		0x0008
#define HOLE_ENABLE		0x0010
#define SRC_1_INDEX_ENABLE	0x0020
#define DST_INDEX_ENABLE	0x0040
#define DST_WRITE_ENABLE	0x0080

/* ADDER source 2 size register */

#define NO_TILE 		0x0080

/* External registers base addresses */

#define CS_UPDATE_MASK		0x0060
#define CS_SCROLL_MASK		0x0040

/* VIPER registers */

#define RESOLUTION_MODE 	0x0080
#define MEMORY_BUS_WIDTH	0x0081
#define PLANE_ADDRESS		0x0083
#define LU_FUNCTION_R1		0x0084
#define LU_FUNCTION_R2		0x0085
#define LU_FUNCTION_R3		0x0086
#define LU_FUNCTION_R4		0x0087
#define MASK_1			0x0088
#define MASK_2			0x0089
#define SOURCE			0x008a
#define SOURCE_Z		0x0000
#define BACKGROUND_COLOR	0x008e
#define BACKGROUND_COLOR_Z	0x000C
#define FOREGROUND_COLOR	0x008f
#define FOREGROUND_COLOR_Z	0x0004
#define SRC1_OCR_A		0x0090
#define SRC2_OCR_A		0x0091
#define DST_OCR_A		0x0092
#define SRC1_OCR_B		0x0094
#define SRC2_OCR_B		0x0095
#define DST_OCR_B		0x0096

/* VIPER scroll registers */

#define SCROLL_CONSTANT 	0x0082
#define SCROLL_FILL		0x008b
#define SCROLL_FILL_Z		0x0008
#define LEFT_SCROLL_MASK	0x008c
#define RIGHT_SCROLL_MASK	0x008d

/* VIPER register bit definitions */

#define EXT_NONE		0x0000
#define EXT_SOURCE		0x0001
#define EXT_M1_M2		0x0002
#define INT_NONE		0x0000
#define INT_SOURCE		0x0004
#define INT_M1_M2		0x0008
#define ID			0x0010
#define NO_ID			0x0000
#define WAIT			0x0020
#define NO_WAIT 		0x0000
#define BAR_SHIFT_DELAY 	WAIT
#define NO_BAR_SHIFT_DELAY	NO_WAIT

/* VIPER logical function unit codes */

#define LF_ZEROS		0x0000
#define	LF_NOT_D		0x0003
#define LF_D_XOR_S		0x0006
#define	LF_D			0x000c
#define LF_SOURCE		0x000a
#define LF_D_OR_S		0x000d
#define LF_ONES 		0x000f
#define INV_M1_M2		0x0030
#define FULL_SRC_RESOLUTION	0X00C0 /* makes second pass like first pass */

/* VIPER scroll register [2] */

#define SCROLL_DISABLE		0x0040
#define SCROLL_ENABLE		0x0020
#define VIPER_LEFT		0x0000
#define VIPER_RIGHT		0x0010
#define VIPER_UP		0x0040
#define VIPER_DOWN		0x0000

/* Adder scroll register */

#define ADDER_UP		0x0000
#define ADDER_DOWN		0x1000

/* Misc scroll definitions */

#define UP		0
#define DOWN		1
#define LEFT		2
#define RIGHT		3
#define NODIR		4
#define SCROLL_VMAX	31
#define SCROLL_HMAX	15
#define NEW		2
#define OLD		1
#define BUSY		1
#define DRAG		1
#define SCROLL		0

/* miscellaneous defines */

#define ALL_PLANES	0xffffffff
#define UNITY		0x1fff		 /* Adder scale factor */
#define MAX_SCREEN_X	1024
#define MAX_SCREEN_Y	864
#define FONT_HEIGHT	32

	struct adder {

	    /* adder control registers */

	    u_short register_address;	/* ADDER reg pntr for use by DGA */
	    u_short request_enable;	/* DMA request enables */
	    u_short interrupt_enable;	/* interrupt enables */
	    u_short status;		/* ADDER status bits */
	    u_short reserved1;		/* test function only */
	    u_short spare1;		/* spare address (what else?) */

	    u_short reserved2;		/* test function only */
	    u_short id_data;		/* data path to I/D bus */
	    u_short command;		/* ADDER chip command register */
	    u_short rasterop_mode;	/* sets rasterop execution modes */
	    u_short cmd;		/* duplicate path to above cmd reg */
	    u_short reserved3;		/* test function only */

	    /* scroll registers */

	    u_short ID_scroll_data;	/* I/D bus scroll data */
	    u_short ID_scroll_command;	/* I/D bus scroll command */
	    u_short scroll_x_min;	/* X scroll min - left boundary */
	    u_short scroll_x_max;	/* X scroll max - right boundary */
	    u_short scroll_y_min;	/* Y scroll min - upper boundary */
	    u_short scroll_y_max;	/* Y scroll max - lower boundary */
	    u_short pause;		/* Y coord to set stat when scanned */
	    u_short y_offset_pending;	/* vertical scroll control */
	    u_short y_scroll_constant;

	    /* update control registers */

	    u_short x_index_pending;	/* x pending index */
	    u_short y_index_pending;	/* y pending index */
	    u_short x_index_new;	/* new x index */
	    u_short y_index_new;		/* new y index */
	    u_short x_index_old;		/* old x index */
	    u_short y_index_old;		/* old y index */
	    u_short x_clip_min; 	/* left clipping boundary */
	    u_short x_clip_max; 	/* right clipping boundary */
	    u_short y_clip_min; 	/* upper clipping boundary */
	    u_short y_clip_max; 	/* lower clipping boundary */
	    u_short spare2;		/* spare address (another!) */

	    /* rasterop control registers */

	    u_short source_1_dx;	/* source #1 x vector */
	    u_short source_1_dy;	/* source #1 y vector*/
	    u_short source_1_x; 	/* source #1 x origin */
	    u_short source_1_y; 	/* source #1 y origin */
	    u_short destination_x;	/* destination x origin */
	    u_short destination_y;	/* destination y origin */
	    u_short fast_dest_dx;	/* destination x fast vector */
	    u_short fast_dest_dy;	/* destination y fast vector */
	    u_short slow_dest_dx;	/* destination x slow vector */
	    u_short slow_dest_dy;	/* destination y slow vector */
	    u_short fast_scale; 	/* scale factor for fast vector */
	    u_short slow_scale; 	/* scale factor for slow vector */
	    u_short source_2_x; 	/* source #2 x origin */
	    u_short source_2_y; 	/* source #2 y origin */
	    u_short source_2_size;	/* source #2 height & width */
	    u_short error_1;		/* error regs (?) */
	    u_short error_2;

	    /* screen format control registers */

	    u_short y_scan_count_0;	/* y scan counts for vert timing */
	    u_short y_scan_count_1;
	    u_short y_scan_count_2;
	    u_short y_scan_count_3;
	    u_short x_scan_conf;	/* x scan configuration */
	    u_short x_limit;
	    u_short y_limit;
	    u_short x_scan_count_0;	/* x scan count for horiz timing */
	    u_short x_scan_count_1;
	    u_short x_scan_count_2;
	    u_short x_scan_count_3;
	    u_short x_scan_count_4;
	    u_short x_scan_count_5;
	    u_short x_scan_count_6;
	    u_short sync_phase_adj;	/* sync phase (horiz sync count) */
	};

/*---------------------
* DUART definitions */

	/* command definitions */

#define EN_RCV		0x01
#define DIS_RCV 	0x02
#define EN_XMT		0x04
#define DIS_XMT 	0x08
#define RESET_M 	0x10
#define RESET_RCV	0x20
#define RESET_XMT	0x30
#define RESET_ERR	0x40
#define RESET_BD	0x50
#define START_BREAK	0x60
#define STOP_BREAK	0x70

	/* interrupt bit definitions */

#define EI_XMT_A	0x01
#define EI_RCV_A	0x02
#define EI_XMT_B	0x10
#define EI_RCV_B	0x20

#define XMT_RDY_A	0x01
#define RCV_RDY_A	0x02
#define XMT_RDY_B	0x10
#define RCV_RDY_B	0x20

	/* status register bit definitions */

#define RCV_RDY 	0x01
#define FIFO_FULL	0x02
#define XMT_RDY 	0x04
#define XMT_EMT 	0x08
#define OVER_ERR	0x10
#define ERR_PARITY	0x20
#define FRAME_ERR	0x40
#define RCVD_BREAK	0x80

	struct duart {

	    /* channel A - LK201 */

	    short modeA;		/* ch.A mode reg (read/write) */
	    short statusA;		/* ch.A status reg (read) */
#define clkselA statusA 		/* ch.A clock slect reg (write) */
	    short cmdA; 		/* ch.A command reg (write) */
	    short dataA;		/* rcv/xmt data ch.A (read/write) */
	    short inchng;		/* input change state reg (read) */
#define auxctl inchng			/* auxiliary control reg (write) */
	    short istatus;		/* interrupt status reg (read) */
#define imask istatus			/* interrupt mask reg (write) */
	    short CThi; 		/* counter/timer hi byte (read) */
#define CTRhi CThi			/* counter/timer hi reg (write) */
	    short CTlo; 		/* counter/timer lo byte (read) */
#define CTRlo CTlo			/* counter/timer lo reg (write) */

	    /* channel B - pointing device */

	    short modeB;		/* ch.B mode reg (read/write) */
	    short statusB;		/* ch.B status reg (read) */
#define clkselB statusB 		/* ch.B clock select reg (write) */
	    short cmdB; 		/* ch.B command reg (write) */
	    short dataB;		/* ch.B rcv/xmt data (read/write) */
	    short rsrvd;
	    short inport;		/* input port (read) */
#define outconf inport			/* output port config reg (write) */
	    short strctr;		/* start counter command (read) */
#define setbits setctr			/* output bits set command (write) */
	    short stpctr;		/* stop counter command (read) */
#define resetbits stpctr		/* output bits reset cmd (write) */

};


code:
/*	$OpenBSD: qevent.h,v 1.2 2003/06/02 23:27:58 millert Exp $	*/
/*	$NetBSD: qevent.h,v 1.1 1998/03/21 10:02:39 ragge Exp $	*/
/*-
 * Copyright (c) 1982, 1986 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. 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.
 *
 *	@(#)qevent.h	7.1 (Berkeley) 5/9/91
 */

/************************************************************************
*									*
*			Copyright (c) 1985 by				*
*		Digital Equipment Corporation, Maynard, MA		*
*			All rights reserved.				*
*									*
*   This software is furnished under a license and may be used and	*
*   copied  only  in accordance with the terms of such license and	*
*   with the  inclusion  of  the  above  copyright  notice.   This	*
*   software  or  any  other copies thereof may not be provided or	*
*   otherwise made available to any other person.  No title to and	*
*   ownership of the software is hereby transferred.			*
*									*
*   The information in this software is subject to change  without	*
*   notice  and should not be construed as a commitment by Digital	*
*   Equipment Corporation.						*
*									*
*   Digital assumes no responsibility for the use  or  reliability	*
*   of its software on equipment which is not supplied by Digital.	*
*									*
************************************************************************/

/*
 * Event queue entries
 */

#ifndef _QEVENT_
#define _QEVENT_

typedef struct  _vs_event {
        unsigned short vse_x;	/* x position */
        unsigned short vse_y;	/* y position */
        unsigned short vse_time;/* 10 millisecond units (button only) */
        char    vse_type;       /* button or motion? */
        unsigned char  vse_key;	/* the key (button only) */
        char    vse_direction;	/* which direction (button only) */
        char    vse_device;	/* which device (button only) */
} vsEvent;

/* vse_type field */
#define VSE_BUTTON      0               /* button moved */
#define VSE_MMOTION     1               /* mouse moved */
#define VSE_TMOTION     2               /* tablet moved */

/* vse_direction field */
#define VSE_KBTUP       0               /* up */
#define VSE_KBTDOWN     1               /* down */
#define VSE_KBTRAW	2		/* undetermined */

/* vse_device field */
#define VSE_NULL	0		/* NULL event (for QD_GETEVENT ret) */
#define VSE_MOUSE       1               /* mouse */
#define VSE_DKB         2               /* main keyboard */
#define VSE_TABLET      3               /* graphics tablet */
#define VSE_AUX         4               /* auxiliary */
#define VSE_CONSOLE     5               /* console */

/* The event queue */

typedef struct _vs_eventqueue {
	vsEvent *events;	/* input event buffer */
	int size;		/* size of event buffer */
	int head;		/* index into events */
	int tail;		/* index into events */
} vsEventQueue;

/* mouse cursor position */

typedef struct _vs_cursor {
        short x;
        short y;
} vsCursor;

/* mouse motion rectangle */

typedef struct _vs_box {
        short bottom;
        short right;
        short left;
        short top;
} vsBox;

#endif /*_QEVENT_*/


code:
/*	$OpenBSD: uba.c,v 1.14 2015/02/01 15:27:11 miod Exp $	*/
/*	$NetBSD: uba.c,v 1.57 2001/04/26 19:16:07 ragge Exp $	*/
/*
 * Copyright (c) 1996 Jonathan Stone.
 * Copyright (c) 1994, 1996 Ludd, University of Lule}, Sweden.
 * Copyright (c) 1982, 1986 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. 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.
 *
 *	@(#)uba.c	7.10 (Berkeley) 12/16/90
 *	@(#)autoconf.c	7.20 (Berkeley) 5/9/91
 */

#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/systm.h>
#include <sys/buf.h>
#include <sys/proc.h>
#include <sys/conf.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/device.h>

#include <uvm/uvm_extern.h>

#include <machine/bus.h>
#include <machine/scb.h>
#include <machine/cpu.h>

#include <arch/vax/uba/ubareg.h>
#include <arch/vax/qbus/ubavar.h>

static int ubasearch (struct device *, struct cfdata *, void *);
static int ubaprint (void *, const char *);

struct 	cfdriver uba_cd = {
	NULL, "uba", DV_DULL
};

/*
 * If we failed to allocate uba resources, put us on a queue to wait
 * until there is available resources. Resources to compete about
 * are map registers and BDPs. This is normally only a problem on
 * Unibus systems, Qbus systems have more map registers than usable.
 */
void
uba_enqueue(struct uba_unit *uu)
{
	struct uba_softc *uh;
	int s;

	uh = (void *)((struct device *)(uu->uu_softc))->dv_parent;

	s = splvm();
	SIMPLEQ_INSERT_TAIL(&uh->uh_resq, uu, uu_resq);
	splx(s);
}

/*
 * When a routine that uses resources is finished, the next device
 * in queue for map registers etc is called. If it succeeds to get
 * resources, call next, and next, and next...
 * This routine must be called at splvm.
 */
void
uba_done(struct uba_softc *uh)
{
	struct uba_unit *uu;

	while ((uu = SIMPLEQ_FIRST(&uh->uh_resq))) {
		SIMPLEQ_REMOVE_HEAD(&uh->uh_resq, uu_resq);
		if ((*uu->uu_ready)(uu) == 0) {
			SIMPLEQ_INSERT_HEAD(&uh->uh_resq, uu, uu_resq);
			break;
		}
	}
}

/*
 * Each device that needs some handling if an ubareset occurs must
 * register for reset first through this routine.
 */
void
uba_reset_establish(void (*reset)(struct device *), struct device *dev)
{
	struct uba_softc *uh = (void *)dev->dv_parent;
	struct uba_reset *ur;

	ur = malloc(sizeof(struct uba_reset), M_DEVBUF, M_NOWAIT);
	if (ur == NULL)
		panic("uba_reset_establish");
	ur->ur_dev = dev;
	ur->ur_reset = reset;

	SIMPLEQ_INSERT_TAIL(&uh->uh_resetq, ur, ur_resetq);
}

/*
 * Allocate a bunch of map registers and map them to the given address.
 */
int
uballoc(struct uba_softc *uh, struct ubinfo *ui, int flags)
{
	int waitok = (flags & UBA_CANTWAIT) == 0;
	int error;

	if ((error = bus_dmamap_create(uh->uh_dmat, ui->ui_size, 1,
	    ui->ui_size, 0, (waitok ? BUS_DMA_WAITOK : BUS_DMA_NOWAIT),
	    &ui->ui_dmam)))
		return error;

	if ((error = bus_dmamap_load(uh->uh_dmat, ui->ui_dmam, ui->ui_vaddr,
	    ui->ui_size, NULL, (waitok ? BUS_DMA_WAITOK : BUS_DMA_NOWAIT)))) {
		bus_dmamap_destroy(uh->uh_dmat, ui->ui_dmam);
		return error;
	}
	ui->ui_baddr = ui->ui_dmam->dm_segs[0].ds_addr;
	return 0;
}

/*
 * Allocate DMA-able memory and map it on the unibus.
 */
int
ubmemalloc(struct uba_softc *uh, struct ubinfo *ui, int flags)
{
	int waitok = (flags & UBA_CANTWAIT ? BUS_DMA_NOWAIT : BUS_DMA_WAITOK);
	int error;

	if ((error = bus_dmamem_alloc(uh->uh_dmat, ui->ui_size, NBPG, 0,
	    &ui->ui_seg, 1, &ui->ui_rseg, waitok)))
		return error;
	if ((error = bus_dmamem_map(uh->uh_dmat, &ui->ui_seg, ui->ui_rseg,
	    ui->ui_size, &ui->ui_vaddr, waitok|BUS_DMA_COHERENT))) {
		bus_dmamem_free(uh->uh_dmat, &ui->ui_seg, ui->ui_rseg);
		return error;
	}
	if ((error = uballoc(uh, ui, flags))) {
		bus_dmamem_unmap(uh->uh_dmat, ui->ui_vaddr, ui->ui_size);
		bus_dmamem_free(uh->uh_dmat, &ui->ui_seg, ui->ui_rseg);
	}
	return error;
}

void
ubfree(struct uba_softc *uh, struct ubinfo *ui)
{
	bus_dmamap_unload(uh->uh_dmat, ui->ui_dmam);
	bus_dmamap_destroy(uh->uh_dmat, ui->ui_dmam);
}

void
ubmemfree(struct uba_softc *uh, struct ubinfo *ui)
{
	bus_dmamem_unmap(uh->uh_dmat, ui->ui_vaddr, ui->ui_size);
	bus_dmamem_free(uh->uh_dmat, &ui->ui_seg, ui->ui_rseg);
	ubfree(uh, ui);
}

/*
 * Generate a reset on uba number uban.	 Then
 * call each device that asked to be called during attach,
 * giving it a chance to clean up so as to be able to continue.
 */
void
ubareset(struct uba_softc *uh)
{
	struct uba_reset *ur;
	int s;

	s = splvm();
	SIMPLEQ_INIT(&uh->uh_resq);
	printf("%s: reset", uh->uh_dev.dv_xname);
	(*uh->uh_ubainit)(uh);

	ur = SIMPLEQ_FIRST(&uh->uh_resetq);
	if (ur) do {
		printf(" %s", ur->ur_dev->dv_xname);
		(*ur->ur_reset)(ur->ur_dev);
	} while ((ur = SIMPLEQ_NEXT(ur, ur_resetq)));

	printf("\n");
	splx(s);
}

/*
 * The common attach routine:
 *   Calls the scan routine to search for uba devices.
 */
void
uba_attach(struct uba_softc *sc, paddr_t iopagephys)
{

	/*
	 * Set last free interrupt vector for devices with
	 * programmable interrupt vectors.  Use is to decrement
	 * this number and use result as interrupt vector.
	 */
	sc->uh_lastiv = 0x200;
	SIMPLEQ_INIT(&sc->uh_resq);
	SIMPLEQ_INIT(&sc->uh_resetq);

	/*
	 * Allocate place for unibus I/O space in virtual space.
	 */
	if (bus_space_map(sc->uh_iot, iopagephys, UBAIOSIZE, 0, &sc->uh_ioh))
		return;

	if (sc->uh_beforescan)
		(*sc->uh_beforescan)(sc);
	/*
	 * Now start searching for devices.
	 */
	config_search((cfmatch_t)ubasearch,(struct device *)sc, NULL);

	if (sc->uh_afterscan)
		(*sc->uh_afterscan)(sc);
}

int
ubasearch(struct device *parent, struct cfdata *cf, void *aux)
{
	struct	uba_softc *sc = (struct uba_softc *)parent;
	struct	uba_attach_args ua;
	int	i, vec, br;

	ua.ua_ioh = ubdevreg(cf->cf_loc[0]) + sc->uh_ioh;
	ua.ua_iot = sc->uh_iot;
	ua.ua_dmat = sc->uh_dmat;

	if (badaddr((caddr_t)ua.ua_ioh, 2) ||
	    (sc->uh_errchk ? (*sc->uh_errchk)(sc):0))
		goto forgetit;

	scb_vecref(0, 0); /* Clear vector ref */
	i = (*cf->cf_attach->ca_match) (parent, cf, &ua);

	if (sc->uh_errchk)
		if ((*sc->uh_errchk)(sc))
			goto forgetit;
	if (i == 0)
		goto forgetit;

	i = scb_vecref(&vec, &br);
	if (i == 0)
		goto fail;
	if (vec == 0)
		goto fail;

	ua.ua_br = br;
	ua.ua_cvec = vec;
	ua.ua_iaddr = cf->cf_loc[0];

	config_attach(parent, cf, &ua, ubaprint);
	return 0;

fail:
	printf("%s%d at %s csr %o %s\n",
	    cf->cf_driver->cd_name, cf->cf_unit, parent->dv_xname,
	    cf->cf_loc[0], (i ? "zero vector" : "didn't interrupt"));

forgetit:
	return 0;
}

/*
 * Print out some interesting info common to all unibus devices.
 */
int
ubaprint(void *aux, const char *uba)
{
	struct uba_attach_args *ua = aux;

	printf(" csr %o vec %d ipl %x", ua->ua_iaddr,
	    ua->ua_cvec & 511, ua->ua_br);
	return UNCONF;
}

/*
 * Move to machdep eventually
 */
void
uba_intr_establish(icookie, vec, ifunc, iarg, ev)
	void *icookie;
	int vec;
	void (*ifunc)(void *iarg);
	void *iarg;
	struct evcount *ev;
{
	scb_vecalloc(vec, ifunc, iarg, SCB_ISTACK, ev);
}