code:
/*	$OpenBSD: magma.c,v 1.29 2015/02/10 21:56:09 miod Exp $	*/

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

/*
 * Driver for Magma SBus Serial/Parallel cards using the Cirrus Logic
 * CD1400 & CD1190 chips
 */

#include "magma.h"

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

#include <sparc/autoconf.h>
#include <sparc/conf.h>
#include <sparc/cpu.h>
#include <sparc/ctlreg.h>

#include <sparc/sparc/asm.h>

#include <dev/ic/cd1400reg.h>
#include <dev/ic/cd1190reg.h>

#include <sparc/bppioctl.h>
#include <sparc/dev/magmareg.h>

#ifdef MAGMA_DEBUG
#define dprintf(x) printf x
#else
#define dprintf(x)
#endif

/*
 * Supported cards table.
 *
 *  The table below lists the cards that this driver is likely to
 *  be able to support.
 *
 *  Cards with parallel ports: except for the LC2+1Sp, they all use
 *  the CD1190 chip which I know nothing about.  I've tried to leave
 *  hooks for it so it shouldn't be too hard to add support later.
 *  (I think somebody is working on this separately)
 *
 *  Thanks to Bruce at Magma for telling me the hardware offsets.
 */
static const struct magma_board_info supported_cards[] = {
	{
		"MAGMA_Sp", "MAGMA,4_Sp", "Magma 4 Sp", 4, 0,
		1, 0xa000, 0xc000, 0xe000, { 0x8000, 0, 0, 0 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,8_Sp", "Magma 8 Sp", 8, 0,
		2, 0xa000, 0xc000, 0xe000, { 0x4000, 0x6000, 0, 0 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,_8HS_Sp", "Magma Fast 8 Sp", 8, 0,
		2, 0x2000, 0x4000, 0x6000, { 0x8000, 0xa000, 0, 0 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,_8SP_422", "Magma 8 Sp - 422", 8, 0,
		2, 0x2000, 0x4000, 0x6000, { 0x8000, 0xa000, 0, 0 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,12_Sp", "Magma 12 Sp", 12, 0,
		3, 0xa000, 0xc000, 0xe000, { 0x2000, 0x4000, 0x6000, 0 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,16_Sp", "Magma 16 Sp", 16, 0,
		4, 0xd000, 0xe000, 0xf000, { 0x8000, 0x9000, 0xa000, 0xb000 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,16_Sp_2", "Magma 16 Sp", 16, 0,
		4, 0x2000, 0x4000, 0x6000, { 0x8000, 0xa000, 0xc000, 0xe000 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,16HS_Sp", "Magma Fast 16 Sp", 16, 0,
		4, 0x2000, 0x4000, 0x6000, { 0x8000, 0xa000, 0xc000, 0xe000 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,21_Sp", "Magma LC 2+1 Sp", 2, 1,
		1, 0xa000, 0xc000, 0xe000, { 0x8000, 0, 0, 0 },
		0, { 0, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,21HS_Sp", "Magma 2+1 Sp", 2, 1,
		1, 0xa000, 0xc000, 0xe000, { 0x4000, 0, 0, 0 },
		1, { 0x6000, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,41_Sp", "Magma 4+1 Sp", 4, 1,
		1, 0xa000, 0xc000, 0xe000, { 0x4000, 0, 0, 0 },
		1, { 0x6000, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,82_Sp", "Magma 8+2 Sp", 8, 2,
		2, 0xd000, 0xe000, 0xf000, { 0x8000, 0x9000, 0, 0 },
		2, { 0xa000, 0xb000 }
	},
	{
		"MAGMA_Sp", "MAGMA,P1_Sp", "Magma P1 Sp", 0, 1,
		0, 0, 0, 0, { 0, 0, 0, 0 },
		1, { 0x8000, 0 }
	},
	{
		"MAGMA_Sp", "MAGMA,P2_Sp", "Magma P2 Sp", 0, 2,
		0, 0, 0, 0, { 0, 0, 0, 0 },
		2, { 0x4000, 0x8000 }
	},
	{
		"MAGMA 2+1HS Sp", "", "Magma 2+1HS Sp", 2, 0,
		1, 0xa000, 0xc000, 0xe000, { 0x4000, 0, 0, 0 },
		1, { 0x8000, 0 }
	},
	{
		NULL, NULL, NULL, 0, 0,
		0, 0, 0, 0, { 0, 0, 0, 0 },
		0, { 0, 0 }
	}
};

/************************************************************************
 *
 *  Autoconfig Stuff
 */

struct cfattach magma_ca = {
	sizeof(struct magma_softc), magma_match, magma_attach
};

struct cfdriver magma_cd = {
	NULL, "magma", DV_DULL
};

struct cfattach mtty_ca = {
	sizeof(struct mtty_softc), mtty_match, mtty_attach
};

struct cfdriver mtty_cd = {
	NULL, "mtty", DV_TTY
};

struct cfattach mbpp_ca = {
	sizeof(struct mbpp_softc), mbpp_match, mbpp_attach
};

struct cfdriver mbpp_cd = {
	NULL, "mbpp", DV_DULL
};

/************************************************************************
 *
 *  CD1400 Routines
 *
 *	cd1400_compute_baud		calculate COR/BPR register values
 *	cd1400_write_ccr		write a value to CD1400 ccr
 *	cd1400_read_reg			read from a CD1400 register
 *	cd1400_write_reg		write to a CD1400 register
 *	cd1400_enable_transmitter	enable transmitting on CD1400 channel
 */

/*
 * compute the bpr/cor pair for any baud rate
 * returns 0 for success, 1 for failure
 */
int
cd1400_compute_baud(speed, clock, cor, bpr)
	speed_t speed;
	int clock;
	int *cor, *bpr;
{
	int c, co, br;

	if (speed < 50 || speed > 150000)
		return (1);

	for (c = 0, co = 8 ; co <= 2048 ; co <<= 2, c++) {
		br = ((clock * 1000000) + (co * speed) / 2) / (co * speed);
		if (br < 0x100) {
			*bpr = br;
			*cor = c;
			return (0);
		}
	}

	return (1);
}

/*
 * Write a CD1400 channel command, should have a timeout?
 */
__inline void
cd1400_write_ccr(cd, cmd)
	struct cd1400 *cd;
	u_char cmd;
{
	while (cd1400_read_reg(cd, CD1400_CCR))
		;

	cd1400_write_reg(cd, CD1400_CCR, cmd);
}

/*
 * read a value from a cd1400 register
 */
__inline u_char
cd1400_read_reg(cd, reg)
	struct cd1400 *cd;
	int reg;
{
	return (cd->cd_reg[reg]);
}

/*
 * write a value to a cd1400 register
 */
__inline void
cd1400_write_reg(cd, reg, value)
	struct cd1400 *cd;
	int reg;
	u_char value;
{
	cd->cd_reg[reg] = value;
}

/*
 * enable transmit service requests for cd1400 channel
 */
void
cd1400_enable_transmitter(cd, channel)
	struct cd1400 *cd;
	int channel;
{
	register int s, srer;

	s = spltty();
	cd1400_write_reg(cd, CD1400_CAR, channel);
	srer = cd1400_read_reg(cd, CD1400_SRER);
	SET(srer, CD1400_SRER_TXRDY);
	cd1400_write_reg(cd, CD1400_SRER, srer);
	splx(s);
}

/************************************************************************
 *
 *  CD1190 Routines
 */

/* XXX well, there are none yet */

/************************************************************************
 *
 *  Magma Routines
 *
 * magma_match		reports if we have a magma board available
 * magma_attach		attaches magma boards to the sbus
 * magma_hard		hardware level interrupt routine
 * magma_soft		software level interrupt routine
 */

int
magma_match(parent, vcf, args)
	struct device *parent;
	void *vcf, *args;
{
	struct confargs *ca = args;
	struct romaux *ra = &ca->ca_ra;
	const struct magma_board_info *card;

	for (card = supported_cards; ; card++) {
		if (card->mb_sbusname == NULL)
			/* End of table: no match */
			return (0);
		if (strcmp(ra->ra_name, card->mb_sbusname) == 0)
			break;
	}

#if defined(MAGMA_DEBUG)
{
	int i;

	printf("magma: matched `%s', nvaddrs %d, nreg %d, nintr %d\n",
	    ra->ra_name, ra->ra_nvaddrs, ra->ra_nreg, ra->ra_nintr);
	printf("magma: magma_prom `%s'\n",
	    getpropstring(ra->ra_node, "magma_prom"));
	printf("magma: intlevels `%s'\n",
	    getpropstring(ra->ra_node, "intlevels"));
	printf("magma: chiprev `%s'\n",
	    getpropstring(ra->ra_node, "chiprev"));
	printf("magma: clock `%s'\n",
	    getpropstring(ra->ra_node, "clock"));

	for (i = 0 ; i < ra->ra_nreg ; i++)
		printf("magma: reg  %d; ra_iospace = %d, ra_paddr = 0x%x, ra_len = %d\n",
		    i, ra->ra_reg[i].rr_iospace,
		    (int)ra->ra_reg[i].rr_paddr, ra->ra_reg[i].rr_len);
	for (i = 0 ; i < ra->ra_nintr ; i++)
		printf("magma: intr %d; pri = %d, vec = %d\n",
		    i, ra->ra_intr[i].int_pri, ra->ra_intr[i].int_vec);
}
#endif

	return (1);
}

void
magma_attach(parent, dev, args)
	struct device *parent;
	struct device *dev;
	void *args;
{
	struct confargs *ca = args;
	struct romaux *ra = &ca->ca_ra;
	struct magma_softc *sc = (struct magma_softc *)dev;
	const struct magma_board_info *card;
	char magma_prom[40], *clockstr;
	int chip, cd_clock, len;
	void *base;

	len = getprop(ra->ra_node, "magma_prom",
	    magma_prom, sizeof(magma_prom) - 1);
	if (len == -1)
		len = 0;
	magma_prom[len] = '\0';

	for (card = supported_cards; card->mb_name != NULL; card++) {
		if (strcmp(ra->ra_name, card->mb_sbusname) != 0)
			continue;
		if (strcmp(magma_prom, card->mb_name) == 0)
			break;
	}

	if (card->mb_name == NULL) {
		printf(" %s (unsupported)\n", magma_prom);
		return;
	}

	clockstr = getpropstring(ra->ra_node, "clock");
	if (strlen(clockstr) == 0)
		cd_clock = 0;
	else {
		cd_clock = 0;
		while (*clockstr != '\0')
			cd_clock = cd_clock * 10 + *clockstr++ - '0';
	}

	dprintf((" addr 0x%x", sc));
	printf(" pri %d softpri %d:", ra->ra_intr[0].int_pri, IPL_TTY);
	printf(" %s\n", card->mb_realname);

	sc->ms_board = card;
	sc->ms_ncd1400 = card->mb_ncd1400;
	sc->ms_ncd1190 = card->mb_ncd1190;

	base = mapiodev(&(ra->ra_reg[0]), 0, ra->ra_reg[0].rr_len);

	/* the SVCACK* lines are daisychained */
	sc->ms_svcackr = base + card->mb_svcackr;
	sc->ms_svcackt = base + card->mb_svcackt;
	sc->ms_svcackm = base + card->mb_svcackm;

	/* Init the cd1400 chips */
	for (chip = 0 ; chip < card->mb_ncd1400 ; chip++) {
		struct cd1400 *cd = &sc->ms_cd1400[chip];

		cd->cd_reg = base + card->mb_cd1400[chip];

		cd->cd_clock = cd_clock;

		/* getpropstring(ra->ra_node, "chiprev"); */
		/* seemingly the Magma drivers just ignore the propstring */
		cd->cd_chiprev = cd1400_read_reg(cd, CD1400_GFRCR);

		dprintf(("%s attach CD1400 %d addr 0x%x rev %x clock %dMHz\n",
		    sc->ms_dev.dv_xname, chip,
		    cd->cd_reg, cd->cd_chiprev, cd->cd_clock));

		/* clear GFRCR */
		cd1400_write_reg(cd, CD1400_GFRCR, 0x00);

		/* reset whole chip */
		cd1400_write_ccr(cd, CD1400_CCR_CMDRESET | CD1400_CCR_FULLRESET);

		/* wait for revision code to be restored */
		while (cd1400_read_reg(cd, CD1400_GFRCR) != cd->cd_chiprev)
		        ;

		/* set the Prescaler Period Register to tick at 1ms */
		cd1400_write_reg(cd, CD1400_PPR,
		    ((cd->cd_clock * 1000000 / CD1400_PPR_PRESCALER + 500) /
		    1000));

		/*
		 * The LC2+1Sp card is the only card that doesn't have a CD1190
		 * for the parallel port, but uses channel 0 of the CD1400, so
		 * we make a note of it for later and set up the CD1400 for
		 * parallel mode operation.
		 */
		if (card->mb_npar && card->mb_ncd1190 == 0) {
			cd1400_write_reg(cd, CD1400_GCR, CD1400_GCR_PARALLEL);
			cd->cd_parmode = 1;
		}
	}

	/* init the cd1190 chips */
	for (chip = 0 ; chip < card->mb_ncd1190 ; chip++) {
		struct cd1190 *cd = &sc->ms_cd1190[chip];

		cd->cd_reg = base + card->mb_cd1190[chip];
		dprintf(("%s attach CD1190 %d addr 0x%x (failed)\n",
		    sc->ms_dev.dv_xname, chip, cd->cd_reg));
		/* XXX don't know anything about these chips yet */
	}

	/* configure the children */
	(void)config_found(dev, mtty_match, NULL);
	(void)config_found(dev, mbpp_match, NULL);

	/*
	 * enable the interrupt handlers
	 */
	sc->ms_hardint.ih_fun = magma_hard;
	sc->ms_hardint.ih_arg = sc;
	intr_establish(ra->ra_intr[0].int_pri, &sc->ms_hardint, -1,
	    dev->dv_xname);

	sc->ms_softint = softintr_establish(IPL_SOFTTTY, magma_soft, sc);
}

/*
 * hard interrupt routine
 *
 *  returns 1 if it handled it, otherwise 0
 *
 *  runs at interrupt priority
 */
int
magma_hard(arg)
	void *arg;
{
	struct magma_softc *sc = arg;
	struct cd1400 *cd;
	int chip, status = 0;
	int serviced = 0;
	int needsoftint = 0;

	/*
	 * check status of all the CD1400 chips
	 */
	for (chip = 0 ; chip < sc->ms_ncd1400 ; chip++)
		status |= cd1400_read_reg(&sc->ms_cd1400[chip], CD1400_SVRR);

	if (ISSET(status, CD1400_SVRR_RXRDY)) {
		/* enter rx service context */
		u_char rivr = *sc->ms_svcackr;
		int port = rivr >> 4;

		if (rivr & (1 << 3)) {			/* parallel port */
		struct mbpp_port *mbpp;
		int n_chars;

			mbpp = &sc->ms_mbpp->ms_port[port];
			cd = mbpp->mp_cd1400;

			/* don't think we have to handle exceptions */
			n_chars = cd1400_read_reg(cd, CD1400_RDCR);
			while (n_chars--) {
				if (mbpp->mp_cnt == 0) {
					SET(mbpp->mp_flags, MBPPF_WAKEUP);
					needsoftint = 1;
					break;
				}
				*mbpp->mp_ptr = cd1400_read_reg(cd, CD1400_RDSR);
				mbpp->mp_ptr++;
				mbpp->mp_cnt--;
			}
		} else {				/* serial port */
			register struct mtty_port *mtty;
			register u_char *ptr, n_chars, line_stat;

			mtty = &sc->ms_mtty->ms_port[port];
			cd = mtty->mp_cd1400;

			if (ISSET(rivr, CD1400_RIVR_EXCEPTION)) {
				line_stat = cd1400_read_reg(cd, CD1400_RDSR);
				n_chars = 1;
			} else { /* no exception, received data OK */
				line_stat = 0;
				n_chars = cd1400_read_reg(cd, CD1400_RDCR);
			}

			ptr = mtty->mp_rput;
			while (n_chars--) {
				*ptr++ = line_stat;
				*ptr++ = cd1400_read_reg(cd, CD1400_RDSR);
				if (ptr == mtty->mp_rend)
				    ptr = mtty->mp_rbuf;
				if (ptr == mtty->mp_rget) {
					if (ptr == mtty->mp_rbuf)
					    ptr = mtty->mp_rend;
					ptr -= 2;
					SET(mtty->mp_flags, MTTYF_RING_OVERFLOW);
					break;
				}
			}
			mtty->mp_rput = ptr;

			needsoftint = 1;
		}

		/* end service context */
		cd1400_write_reg(cd, CD1400_EOSRR, 0);
		serviced = 1;
	} /* if (rx_service...) */

	if (ISSET(status, CD1400_SVRR_MDMCH)) {
		/* enter mdm service context */
		u_char mivr = *sc->ms_svcackm;
		int port = mivr >> 4;
		struct mtty_port *mtty;
		int carrier;
		u_char msvr;

		/*
		 * Handle CD (LC2+1Sp = DSR) changes.
		 */
		mtty = &sc->ms_mtty->ms_port[port];
		cd = mtty->mp_cd1400;
		msvr = cd1400_read_reg(cd, CD1400_MSVR2);
		carrier = ISSET(msvr,
		    cd->cd_parmode ? CD1400_MSVR2_DSR : CD1400_MSVR2_CD);

		if (mtty->mp_carrier != carrier) {
			SET(mtty->mp_flags, MTTYF_CARRIER_CHANGED);
			mtty->mp_carrier = carrier;
			needsoftint = 1;
		}

		/* end service context */
		cd1400_write_reg(cd, CD1400_EOSRR, 0);
		serviced = 1;
	} /* if (mdm_service...) */

	if (ISSET(status, CD1400_SVRR_TXRDY)) {
		/* enter tx service context */
		u_char tivr = *sc->ms_svcackt;
		int port = tivr >> 4;

		if (tivr & (1 << 3)) {	/* parallel port */
			struct mbpp_port *mbpp;

			mbpp = &sc->ms_mbpp->ms_port[port];
			cd = mbpp->mp_cd1400;

			if (mbpp->mp_cnt) {
				int count = 0;

				/* fill the fifo */
				while (mbpp->mp_cnt &&
				    count++ < CD1400_PAR_FIFO_SIZE) {
					cd1400_write_reg(cd, CD1400_TDR,
					    *mbpp->mp_ptr);
					mbpp->mp_ptr++;
					mbpp->mp_cnt--;
				}
			} else {
				/*
				 * fifo is empty and we got no more data to
				 * send, so shut off interrupts and signal for
				 * a wakeup, which can't be done here in case
				 * we beat mbpp_send to the tsleep call
				 * (we are running at psl > spltty).
				 */
				cd1400_write_reg(cd, CD1400_SRER, 0);
				SET(mbpp->mp_flags, MBPPF_WAKEUP);
				needsoftint = 1;
			}
		} else {		/* serial port */
			struct mtty_port *mtty;
			struct tty *tp;

			mtty = &sc->ms_mtty->ms_port[port];
			cd = mtty->mp_cd1400;
			tp = mtty->mp_tty;

			if (!ISSET(mtty->mp_flags, MTTYF_STOP)) {
				register int count = 0;

				/* check if we should start/stop a break */
				if (ISSET(mtty->mp_flags, MTTYF_SET_BREAK)) {
					cd1400_write_reg(cd, CD1400_TDR, 0);
					cd1400_write_reg(cd, CD1400_TDR, 0x81);
					/* should we delay too? */
					CLR(mtty->mp_flags, MTTYF_SET_BREAK);
					count += 2;
				}

				if (ISSET(mtty->mp_flags, MTTYF_CLR_BREAK)) {
					cd1400_write_reg(cd, CD1400_TDR, 0);
					cd1400_write_reg(cd, CD1400_TDR, 0x83);
					CLR(mtty->mp_flags, MTTYF_CLR_BREAK);
					count += 2;
				}

				/*
				 * I don't quite fill the fifo in case the last
				 * one is a NULL which I have to double up
				 * because its the escape code for embedded
				 * transmit characters.
				 */
				while (mtty->mp_txc > 0 &&
				    count < CD1400_TX_FIFO_SIZE - 1) {
					register u_char ch;

					ch = *mtty->mp_txp;

					mtty->mp_txc--;
					mtty->mp_txp++;

					if (ch == 0) {
						cd1400_write_reg(cd,
						    CD1400_TDR, ch);
						count++;
					}

					cd1400_write_reg(cd, CD1400_TDR, ch);
					count++;
				}
			}

			/*
			 * If we ran out of work or are requested to STOP then
			 * shut off the txrdy interrupts and signal DONE to
			 * flush out the chars we have sent.
			 */
			if (mtty->mp_txc == 0 ||
			    ISSET(mtty->mp_flags, MTTYF_STOP)) {
				register int srer;

				srer = cd1400_read_reg(cd, CD1400_SRER);
				CLR(srer, CD1400_SRER_TXRDY);
				cd1400_write_reg(cd, CD1400_SRER, srer);
				CLR(mtty->mp_flags, MTTYF_STOP);

				SET(mtty->mp_flags, MTTYF_DONE);
				needsoftint = 1;
			}
		}

		/* end service context */
		cd1400_write_reg(cd, CD1400_EOSRR, 0);
		serviced = 1;
	} /* if (tx_service...) */

	/* XXX service CD1190 interrupts too
	for (chip = 0 ; chip < sc->ms_ncd1190 ; chip++) {
	}
	*/

	if (needsoftint)	/* trigger the soft interrupt */
		softintr_schedule(sc->ms_softint);

	return (serviced);
}

/*
 * magma soft interrupt handler
 *
 *  runs at spltty()
 */
void
magma_soft(arg)
	void *arg;
{
	struct magma_softc *sc = arg;
	struct mtty_softc *mtty = sc->ms_mtty;
	struct mbpp_softc *mbpp = sc->ms_mbpp;
	int port;
	int s, flags;

	/*
	 * check the tty ports (if any) to see what needs doing
	 */
	if (mtty) {
		for (port = 0 ; port < mtty->ms_nports ; port++) {
			struct mtty_port *mp = &mtty->ms_port[port];
			struct tty *tp = mp->mp_tty;

			if (!ISSET(tp->t_state, TS_ISOPEN))
				continue;

			/*
			 * handle any received data
			 */
			while (mp->mp_rget != mp->mp_rput) {
				u_char stat;
				int data;

				stat = mp->mp_rget[0];
				data = mp->mp_rget[1];
				mp->mp_rget =
				    ((mp->mp_rget + 2) == mp->mp_rend) ?
				      mp->mp_rbuf : (mp->mp_rget + 2);

				if (stat & (CD1400_RDSR_BREAK | CD1400_RDSR_FE))
					data |= TTY_FE;
				if (stat & CD1400_RDSR_PE)
					data |= TTY_PE;

				if (stat & CD1400_RDSR_OE)
					log(LOG_WARNING,
					    "%s%x: fifo overflow\n",
					    mtty->ms_dev.dv_xname, port);

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

			s = splhigh();	/* block out hard interrupt routine */
			flags = mp->mp_flags;
			CLR(mp->mp_flags, MTTYF_DONE | MTTYF_CARRIER_CHANGED |
			    MTTYF_RING_OVERFLOW);
			splx(s);	/* ok */

			if (ISSET(flags, MTTYF_CARRIER_CHANGED)) {
				dprintf(("%s%x: cd %s\n",
				    mtty->ms_dev.dv_xname, port,
				    mp->mp_carrier ? "on" : "off"));
				(*linesw[tp->t_line].l_modem)(tp,
				    mp->mp_carrier);
			}

			if (ISSET(flags, MTTYF_RING_OVERFLOW)) {
				log(LOG_WARNING,
				    "%s%x: ring buffer overflow\n",
				    mtty->ms_dev.dv_xname, port);
			}

			if (ISSET(flags, MTTYF_DONE)) {
				ndflush(&tp->t_outq,
				    mp->mp_txp - tp->t_outq.c_cf);
				CLR(tp->t_state, TS_BUSY);
				/* might be some more */
				(*linesw[tp->t_line].l_start)(tp);
			}
		} /* for (each mtty...) */
	}

	/*
	 * check the bpp ports (if any) to see what needs doing
	 */
	if (mbpp) {
		for (port = 0 ; port < mbpp->ms_nports ; port++) {
			struct mbpp_port *mp = &mbpp->ms_port[port];

			if (!ISSET(mp->mp_flags, MBPPF_OPEN))
				continue;

			s = splhigh();	/* block out hard intr routine */
			flags = mp->mp_flags;
			CLR(mp->mp_flags, MBPPF_WAKEUP);
			splx(s);

			if (ISSET(flags, MBPPF_WAKEUP)) {
				wakeup(mp);
			}
		} /* for (each mbpp...) */
	}
}

/************************************************************************
 *
 *  MTTY Routines
 *
 *	mtty_match		match one mtty device
 *	mtty_attach		attach mtty devices
 *	mttyopen		open mtty device
 *	mttyclose		close mtty device
 *	mttyread		read from mtty
 *	mttywrite		write to mtty
 *	mttyioctl		do ioctl on mtty
 *	mttytty			return tty pointer for mtty
 *	mttystop		stop mtty device
 *	mtty_start		start mtty device
 *	mtty_param		set mtty parameters
 *	mtty_modem_control	set modem control lines
 */

int
mtty_match(parent, vcf, args)
	struct device *parent;
	void *vcf, *args;
{
	struct magma_softc *sc = (struct magma_softc *)parent;

	return (args == mtty_match && sc->ms_board->mb_nser &&
	    sc->ms_mtty == NULL);
}

void
mtty_attach(parent, dev, args)
	struct device *parent;
	struct device *dev;
	void *args;
{
	struct magma_softc *sc = (struct magma_softc *)parent;
	struct mtty_softc *ms = (struct mtty_softc *)dev;
	int port, chip, chan;

	sc->ms_mtty = ms;
	dprintf((" addr 0x%x", ms));

	for (port = chip = chan = 0 ; port < sc->ms_board->mb_nser ; port++) {
		struct mtty_port *mp = &ms->ms_port[port];
		struct tty *tp;

		mp->mp_cd1400 = &sc->ms_cd1400[chip];
		if (mp->mp_cd1400->cd_parmode && chan == 0)
			chan = 1; /* skip channel 0 if parmode */
		mp->mp_channel = chan;

		tp = ttymalloc(0);
		tp->t_oproc = mtty_start;
		tp->t_param = mtty_param;

		mp->mp_tty = tp;

		mp->mp_rbuf = malloc(MTTY_RBUF_SIZE, M_DEVBUF, M_NOWAIT);
		if (mp->mp_rbuf == NULL)
			break;

		mp->mp_rend = mp->mp_rbuf + MTTY_RBUF_SIZE;

		chan = (chan + 1) % CD1400_NO_OF_CHANNELS;
		if (chan == 0)
			chip++;
	}

	ms->ms_nports = port;
	printf(": %d tty%s\n", port, port == 1 ? "" : "s");
}

/*
 * open routine. returns zero if successful, else error code
 */
int
mttyopen(dev, flags, mode, p)
	dev_t dev;
	int flags;
	int mode;
	struct proc *p;
{
	int card = MAGMA_CARD(dev);
	int port = MAGMA_PORT(dev);
	struct mtty_softc *ms;
	struct mtty_port *mp;
	struct tty *tp;
	struct cd1400 *cd;
	int s;

	if (card >= mtty_cd.cd_ndevs || (ms = mtty_cd.cd_devs[card]) == NULL ||
	    port >= ms->ms_nports)
		return (ENXIO);	/* device not configured */

	mp = &ms->ms_port[port];
	tp = mp->mp_tty;
	tp->t_dev = dev;

	if (!ISSET(tp->t_state, TS_ISOPEN)) {
		SET(tp->t_state, TS_WOPEN);

		/* set defaults */
		ttychars(tp);
		tp->t_iflag = TTYDEF_IFLAG;
		tp->t_oflag = TTYDEF_OFLAG;
		tp->t_cflag = TTYDEF_CFLAG;
		if (ISSET(mp->mp_openflags, TIOCFLAG_CLOCAL))
			SET(tp->t_cflag, CLOCAL);
		if (ISSET(mp->mp_openflags, TIOCFLAG_CRTSCTS))
			SET(tp->t_cflag, CRTSCTS);
		if (ISSET(mp->mp_openflags, TIOCFLAG_MDMBUF))
			SET(tp->t_cflag, MDMBUF);
		tp->t_lflag = TTYDEF_LFLAG;
		tp->t_ispeed = tp->t_ospeed = TTYDEF_SPEED;

		/* init ring buffer */
		mp->mp_rput = mp->mp_rget = mp->mp_rbuf;

		s = spltty();

		/* reset CD1400 channel */
		cd = mp->mp_cd1400;
		cd1400_write_reg(cd, CD1400_CAR, mp->mp_channel);
		cd1400_write_ccr(cd, CD1400_CCR_CMDRESET);

		/* encode the port number in top half of LIVR */
		cd1400_write_reg(cd, CD1400_LIVR, port << 4);

		/* sets parameters and raises DTR */
		(void)mtty_param(tp, &tp->t_termios);

		/* set tty watermarks */
		ttsetwater(tp);

		/* enable service requests */
		cd1400_write_reg(cd, CD1400_SRER,
		    CD1400_SRER_RXDATA | CD1400_SRER_MDMCH);

		/* tell the tty about the carrier status */
		if (ISSET(mp->mp_openflags, TIOCFLAG_SOFTCAR) || mp->mp_carrier)
			SET(tp->t_state, TS_CARR_ON);
		else
			CLR(tp->t_state, TS_CARR_ON);
	} else if (ISSET(tp->t_state, TS_XCLUDE) && suser(p, 0) != 0) {
		return (EBUSY);	/* superuser can break exclusive access */
	} else {
		s = spltty();
	}

	/* wait for carrier if necessary */
	if (!ISSET(flags, O_NONBLOCK)) {
		while (!ISSET(tp->t_cflag, CLOCAL) &&
		    !ISSET(tp->t_state, TS_CARR_ON)) {
			int error;

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

	splx(s);

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

/*
 * close routine. returns zero if successful, else error code
 */
int
mttyclose(dev, flag, mode, p)
	dev_t dev;
	int flag;
	int mode;
	struct proc *p;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(dev)];
	struct tty *tp = mp->mp_tty;
	int s;

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

	/*
	 * If HUPCL is set, and the tty is no longer open,
	 * shut down the port.
	 */
	if (ISSET(tp->t_cflag, HUPCL) || !ISSET(tp->t_state, TS_ISOPEN)) {
		/* XXX wait until FIFO is empty before turning off the channel
		struct cd1400 *cd = mp->mp_cd1400;
		*/

		/* drop DTR and RTS */
		(void)mtty_modem_control(mp, 0, DMSET);

		/* turn off the channel
		cd1400_write_reg(cd, CD1400_CAR, mp->mp_channel);
		cd1400_write_ccr(cd, CD1400_CCR_CMDRESET);
		*/
	}

	splx(s);
	ttyclose(tp);

	return (0);
}

/*
 * Read routine
 */
int
mttyread(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(dev)];
	struct tty *tp = mp->mp_tty;

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

/*
 * Write routine
 */
int
mttywrite(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(dev)];
	struct tty *tp = mp->mp_tty;

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

/*
 * return tty pointer
 */
struct tty *
mttytty(dev)
	dev_t dev;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(dev)];

	return (mp->mp_tty);
}

/*
 * ioctl routine
 */
int
mttyioctl(dev, cmd, data, flags, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flags;
	struct proc *p;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(dev)];
	struct tty *tp = mp->mp_tty;
	int error;

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

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

	error = 0;

	switch(cmd) {
	case TIOCSBRK:	/* set break */
		SET(mp->mp_flags, MTTYF_SET_BREAK);
		cd1400_enable_transmitter(mp->mp_cd1400, mp->mp_channel);
		break;

	case TIOCCBRK:	/* clear break */
		SET(mp->mp_flags, MTTYF_CLR_BREAK);
		cd1400_enable_transmitter(mp->mp_cd1400, mp->mp_channel);
		break;

	case TIOCSDTR:	/* set DTR */
		mtty_modem_control(mp, TIOCM_DTR, DMBIS);
		break;

	case TIOCCDTR:	/* clear DTR */
		mtty_modem_control(mp, TIOCM_DTR, DMBIC);
		break;

	case TIOCMSET:	/* set modem lines */
		mtty_modem_control(mp, *((int *)data), DMSET);
		break;

	case TIOCMBIS:	/* bit set modem lines */
		mtty_modem_control(mp, *((int *)data), DMBIS);
		break;

	case TIOCMBIC:	/* bit clear modem lines */
		mtty_modem_control(mp, *((int *)data), DMBIC);
		break;

	case TIOCMGET:	/* get modem lines */
		*((int *)data) = mtty_modem_control(mp, 0, DMGET);
		break;

	case TIOCGFLAGS:
		*((int *)data) = mp->mp_openflags;
		break;

	case TIOCSFLAGS:
		if (suser(p, 0))
			error = EPERM;
		else
			mp->mp_openflags = *((int *)data) &
				(TIOCFLAG_SOFTCAR | TIOCFLAG_CLOCAL |
				TIOCFLAG_CRTSCTS | TIOCFLAG_MDMBUF);
		break;

	default:
		error = ENOTTY;
	}

	return (error);
}

/*
 * Stop output, e.g., for ^S or output flush.
 */
int
mttystop(tp, flags)
	struct tty *tp;
	int flags;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(tp->t_dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(tp->t_dev)];
	int s;

	s = spltty();

	if (ISSET(tp->t_state, TS_BUSY)) {
		if (!ISSET(tp->t_state, TS_TTSTOP))
			SET(tp->t_state, TS_FLUSH);

		/*
		 * the transmit interrupt routine will disable transmit when it
		 * notices that MTTYF_STOP has been set.
		 */
		SET(mp->mp_flags, MTTYF_STOP);
	}

	splx(s);
	return (0);
}

/*
 * Start output, after a stop.
 */
void
mtty_start(tp)
	struct tty *tp;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(tp->t_dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(tp->t_dev)];
	int s;

	s = spltty();

	/*
	 * We only need to do something if we are not already busy
	 * or delaying or stopped.
	 */
	if (!ISSET(tp->t_state, TS_TTSTOP | TS_TIMEOUT | TS_BUSY)) {

		/*
		 * If we are sleeping and output has drained below
		 * low water mark, awaken.
		 */
		ttwakeupwr(tp);

		/*
		 * If there is something to send, start transmitting.
		 */
		if (tp->t_outq.c_cc) {
			mp->mp_txc = ndqb(&tp->t_outq, 0);
			mp->mp_txp = tp->t_outq.c_cf;
			SET(tp->t_state, TS_BUSY);
			cd1400_enable_transmitter(mp->mp_cd1400,
			    mp->mp_channel);
		}
	}

	splx(s);
}

/*
 * set/get modem line status
 *
 * bits can be: TIOCM_DTR, TIOCM_RTS, TIOCM_CTS, TIOCM_CD, TIOCM_RI, TIOCM_DSR
 *
 * note that DTR and RTS lines are exchanged, and that DSR is
 * not available on the LC2+1Sp card (used as CD)
 *
 * only let them fiddle with RTS if CRTSCTS is not enabled
 */
int
mtty_modem_control(mp, bits, howto)
	struct mtty_port *mp;
	int bits;
	int howto;
{
	struct cd1400 *cd = mp->mp_cd1400;
	struct tty *tp = mp->mp_tty;
	int s, msvr;

	s = spltty();

	cd1400_write_reg(cd, CD1400_CAR, mp->mp_channel);

	switch(howto) {
	case DMGET:	/* get bits */
		bits = 0;

		bits |= TIOCM_LE;

		msvr = cd1400_read_reg(cd, CD1400_MSVR1);
		if (msvr & CD1400_MSVR1_RTS)
			bits |= TIOCM_DTR;

		msvr = cd1400_read_reg(cd, CD1400_MSVR2);
		if (msvr & CD1400_MSVR2_DTR)
			bits |= TIOCM_RTS;
		if (msvr & CD1400_MSVR2_CTS)
		    bits |= TIOCM_CTS;
		if (msvr & CD1400_MSVR2_RI)
		    bits |= TIOCM_RI;
		if (msvr & CD1400_MSVR2_DSR)
		    bits |= (cd->cd_parmode ? TIOCM_CD : TIOCM_DSR);
		if (msvr & CD1400_MSVR2_CD)
		    bits |= (cd->cd_parmode ? 0 : TIOCM_CD);

		break;

	case DMSET:	/* reset bits */
		if (!ISSET(tp->t_cflag, CRTSCTS))
			cd1400_write_reg(cd, CD1400_MSVR2,
			    ((bits & TIOCM_RTS) ? CD1400_MSVR2_DTR : 0));

		cd1400_write_reg(cd, CD1400_MSVR1,
		    ((bits & TIOCM_DTR) ? CD1400_MSVR1_RTS : 0));

		break;

	case DMBIS:	/* set bits */
		if ((bits & TIOCM_RTS) && !ISSET(tp->t_cflag, CRTSCTS))
			cd1400_write_reg(cd, CD1400_MSVR2, CD1400_MSVR2_DTR);

		if (bits & TIOCM_DTR)
			cd1400_write_reg(cd, CD1400_MSVR1, CD1400_MSVR1_RTS);

		break;

	case DMBIC:	/* clear bits */
		if ((bits & TIOCM_RTS) && !ISSET(tp->t_cflag, CRTSCTS))
			cd1400_write_reg(cd, CD1400_MSVR2, 0);

		if (bits & TIOCM_DTR)
			cd1400_write_reg(cd, CD1400_MSVR1, 0);

		break;
	}

	splx(s);
	return (bits);
}

/*
 * Set tty parameters, returns error or 0 on success
 */
int
mtty_param(tp, t)
	struct tty *tp;
	struct termios *t;
{
	struct mtty_softc *ms = mtty_cd.cd_devs[MAGMA_CARD(tp->t_dev)];
	struct mtty_port *mp = &ms->ms_port[MAGMA_PORT(tp->t_dev)];
	struct cd1400 *cd = mp->mp_cd1400;
	int rbpr, tbpr, rcor, tcor;
	u_char mcor1 = 0, mcor2 = 0;
	int s, opt;

	if (t->c_ospeed &&
	    cd1400_compute_baud(t->c_ospeed, cd->cd_clock, &tcor, &tbpr))
		return (EINVAL);

	if (t->c_ispeed &&
	    cd1400_compute_baud(t->c_ispeed, cd->cd_clock, &rcor, &rbpr))
		return (EINVAL);

	s = spltty();

	/* hang up the line if ospeed is zero, else raise DTR */
	(void)mtty_modem_control(mp, TIOCM_DTR,
	    (t->c_ospeed == 0 ? DMBIC : DMBIS));

	/* select channel, done in mtty_modem_control() */
	/* cd1400_write_reg(cd, CD1400_CAR, mp->mp_channel); */

	/* set transmit speed */
	if (t->c_ospeed) {
		cd1400_write_reg(cd, CD1400_TCOR, tcor);
		cd1400_write_reg(cd, CD1400_TBPR, tbpr);
	}

	/* set receive speed */
	if (t->c_ispeed) {
		cd1400_write_reg(cd, CD1400_RCOR, rcor);
		cd1400_write_reg(cd, CD1400_RBPR, rbpr);
	}

	/* enable transmitting and receiving on this channel */
	opt = CD1400_CCR_CMDCHANCTL | CD1400_CCR_XMTEN | CD1400_CCR_RCVEN;
	cd1400_write_ccr(cd, opt);

	/* set parity, data and stop bits */
	opt = 0;
	if (ISSET(t->c_cflag, PARENB))
		opt |= (ISSET(t->c_cflag, PARODD) ?
		    CD1400_COR1_PARODD : CD1400_COR1_PARNORMAL);

	if (!ISSET(t->c_iflag, INPCK))
		opt |= CD1400_COR1_NOINPCK; /* no parity checking */

	if (ISSET(t->c_cflag, CSTOPB))
		opt |= CD1400_COR1_STOP2;

	switch (t->c_cflag & CSIZE) {
	case CS5:
		opt |= CD1400_COR1_CS5;
		break;

	case CS6:
		opt |= CD1400_COR1_CS6;
		break;

	case CS7:
		opt |= CD1400_COR1_CS7;
		break;

	default:
		opt |= CD1400_COR1_CS8;
		break;
	}

	cd1400_write_reg(cd, CD1400_COR1, opt);

	/*
	 * enable Embedded Transmit Commands (for breaks)
	 * use the CD1400 automatic CTS flow control if CRTSCTS is set
	 */
	opt = CD1400_COR2_ETC;
	if (ISSET(t->c_cflag, CRTSCTS))
		opt |= CD1400_COR2_CCTS_OFLOW;
	cd1400_write_reg(cd, CD1400_COR2, opt);

	cd1400_write_reg(cd, CD1400_COR3, MTTY_RX_FIFO_THRESHOLD);

	cd1400_write_ccr(cd, CD1400_CCR_CMDCORCHG | CD1400_CCR_COR1 |
	    CD1400_CCR_COR2 | CD1400_CCR_COR3);

	cd1400_write_reg(cd, CD1400_COR4, CD1400_COR4_PFO_EXCEPTION);
	cd1400_write_reg(cd, CD1400_COR5, 0);

	/*
	 * if automatic RTS handshaking enabled, set DTR threshold
	 * (RTS and DTR lines are switched, CD1400 thinks its DTR)
	 */
	if (ISSET(t->c_cflag, CRTSCTS))
		mcor1 = MTTY_RX_DTR_THRESHOLD;

	/* set up `carrier detect' interrupts */
	if (cd->cd_parmode) {
		SET(mcor1, CD1400_MCOR1_DSRzd);
		SET(mcor2, CD1400_MCOR2_DSRod);
	} else {
		SET(mcor1, CD1400_MCOR1_CDzd);
		SET(mcor2, CD1400_MCOR2_CDod);
	}

	cd1400_write_reg(cd, CD1400_MCOR1, mcor1);
	cd1400_write_reg(cd, CD1400_MCOR2, mcor2);

	/* receive timeout 2ms */
	cd1400_write_reg(cd, CD1400_RTPR, 2);

	splx(s);
	return (0);
}

/************************************************************************
 *
 *  MBPP Routines
 *
 *	mbpp_match	match one mbpp device
 *	mbpp_attach	attach mbpp devices
 *	mbppopen	open mbpp device
 *	mbppclose	close mbpp device
 *	mbppread	read from mbpp
 *	mbppwrite	write to mbpp
 *	mbppioctl	do ioctl on mbpp
 *	mbpppoll	do poll on mbpp
 *	mbpp_rw		general rw routine
 *	mbpp_timeout	rw timeout
 *	mbpp_start	rw start after delay
 *	mbpp_send	send data
 *	mbpp_recv	recv data
 */

int
mbpp_match(parent, vcf, args)
	struct device *parent;
	void *vcf, *args;
{
	register struct magma_softc *sc = (struct magma_softc *)parent;

	return (args == mbpp_match && sc->ms_board->mb_npar &&
	    sc->ms_mbpp == NULL);
}

void
mbpp_attach(parent, dev, args)
	struct device *parent;
	struct device *dev;
	void *args;
{
	struct magma_softc *sc = (struct magma_softc *)parent;
	struct mbpp_softc *ms = (struct mbpp_softc *)dev;
	struct mbpp_port *mp;
	int port;

	sc->ms_mbpp = ms;
	dprintf((" addr 0x%x", ms));

	for (port = 0 ; port < sc->ms_board->mb_npar ; port++) {
		mp = &ms->ms_port[port];

		if (sc->ms_ncd1190)
			mp->mp_cd1190 = &sc->ms_cd1190[port];
		else
			mp->mp_cd1400 = &sc->ms_cd1400[0];

		timeout_set(&mp->mp_timeout_tmo, mbpp_timeout, mp);
		timeout_set(&mp->mp_start_tmo, mbpp_start, mp);
	}

	ms->ms_nports = port;
	printf(": %d port%s\n", port, port == 1 ? "" : "s");
}

/*
 * open routine. returns zero if successful, else error code
 */
int
mbppopen(dev, flags, mode, p)
	dev_t dev;
	int flags;
	int mode;
	struct proc *p;
{
	int card = MAGMA_CARD(dev);
	int port = MAGMA_PORT(dev);
	struct mbpp_softc *ms;
	struct mbpp_port *mp;
	int s;

	if (card >= mbpp_cd.cd_ndevs || (ms = mbpp_cd.cd_devs[card]) == NULL ||
	    port >= ms->ms_nports)
		return (ENXIO);

	mp = &ms->ms_port[port];

	s = spltty();
	if (ISSET(mp->mp_flags, MBPPF_OPEN)) {
		splx(s);
		return (EBUSY);
	}
	SET(mp->mp_flags, MBPPF_OPEN);
	splx(s);

	/* set defaults */
	mp->mp_burst = BPP_BURST;
	mp->mp_timeout = mbpp_mstohz(BPP_TIMEOUT);
	mp->mp_delay = mbpp_mstohz(BPP_DELAY);

	/* init chips */
	if (mp->mp_cd1400) {	/* CD1400 */
		struct cd1400 *cd = mp->mp_cd1400;

		/* set up CD1400 channel */
		s = spltty();
		cd1400_write_reg(cd, CD1400_CAR, 0);
		cd1400_write_ccr(cd, CD1400_CCR_CMDRESET);
		cd1400_write_reg(cd, CD1400_LIVR, (1 << 3));
		splx(s);
	} else {		/* CD1190 */
		mp->mp_flags = 0;
		return (ENXIO);
	}

	return (0);
}

/*
 * close routine. returns zero if successful, else error code
 */
int
mbppclose(dev, flag, mode, p)
	dev_t dev;
	int flag;
	int mode;
	struct proc *p;
{
	struct mbpp_softc *ms = mbpp_cd.cd_devs[MAGMA_CARD(dev)];
	struct mbpp_port *mp = &ms->ms_port[MAGMA_PORT(dev)];

	mp->mp_flags = 0;
	return (0);
}

/*
 * Read routine
 */
int
mbppread(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	return (mbpp_rw(dev, uio));
}

/*
 * Write routine
 */
int
mbppwrite(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	return (mbpp_rw(dev, uio));
}

/*
 * ioctl routine
 */
int
mbppioctl(dev, cmd, data, flags, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flags;
	struct proc *p;
{
	struct mbpp_softc *ms = mbpp_cd.cd_devs[MAGMA_CARD(dev)];
	register struct mbpp_port *mp = &ms->ms_port[MAGMA_PORT(dev)];
	struct bpp_param *bp;
	int error = 0;
	int s;

	switch(cmd) {
	case BPPIOCSPARAM:
		bp = (struct bpp_param *)data;
		if (bp->bp_burst < BPP_BURST_MIN ||
		    bp->bp_burst > BPP_BURST_MAX ||
		    bp->bp_delay < BPP_DELAY_MIN ||
		    bp->bp_delay > BPP_DELAY_MIN) {
			error = EINVAL;
		} else {
			mp->mp_burst = bp->bp_burst;
			mp->mp_timeout = mbpp_mstohz(bp->bp_timeout);
			mp->mp_delay = mbpp_mstohz(bp->bp_delay);
		}
		break;
	case BPPIOCGPARAM:
		bp = (struct bpp_param *)data;
		bp->bp_burst = mp->mp_burst;
		bp->bp_timeout = mbpp_hztoms(mp->mp_timeout);
		bp->bp_delay = mbpp_hztoms(mp->mp_delay);
		break;
	case BPPIOCGSTAT:
		/* XXX make this more generic */
		s = spltty();
		cd1400_write_reg(mp->mp_cd1400, CD1400_CAR, 0);
		*(int *)data = cd1400_read_reg(mp->mp_cd1400, CD1400_PSVR);
		splx(s);
		break;
	default:
		error = ENOTTY;
	}

	return (error);
}

/*
 * poll routine
 */
int
mbpppoll(dev, events, p)
	dev_t dev;
	int events;
	struct proc *p;
{
	return (seltrue(dev, events, p));
}

int
mbpp_rw(dev, uio)
	dev_t dev;
	struct uio *uio;
{
	int card = MAGMA_CARD(dev);
	int port = MAGMA_PORT(dev);
	struct mbpp_softc *ms = mbpp_cd.cd_devs[card];
	register struct mbpp_port *mp = &ms->ms_port[port];
	caddr_t buffer, ptr;
	int buflen, cnt, len;
	int s, error = 0;
	int gotdata = 0;

	if (uio->uio_resid == 0)
		return (0);

	buflen = min(uio->uio_resid, mp->mp_burst);
	buffer = malloc(buflen, M_DEVBUF, M_WAITOK);

	SET(mp->mp_flags, MBPPF_UIO);

	/*
	 * start timeout, if needed
	 */
	if (mp->mp_timeout > 0) {
		SET(mp->mp_flags, MBPPF_TIMEOUT);
		timeout_add(&mp->mp_timeout_tmo, mp->mp_timeout);
	}

	len = cnt = 0;
	while (uio->uio_resid > 0) {
		len = min(buflen, uio->uio_resid);
		ptr = buffer;

		if (uio->uio_rw == UIO_WRITE) {
			error = uiomovei(ptr, len, uio);
			if (error)
				break;
		}
again:		/* goto bad */
		/* timed out?  */
		if (!ISSET(mp->mp_flags, MBPPF_UIO))
			break;

		/*
		 * perform the operation
		 */
		if (uio->uio_rw == UIO_WRITE) {
			cnt = mbpp_send(mp, ptr, len);
		} else {
			cnt = mbpp_recv(mp, ptr, len);
		}

		if (uio->uio_rw == UIO_READ) {
			if (cnt) {
				error = uiomovei(ptr, cnt, uio);
				if (error)
					break;
				gotdata++;
			}
			else if (gotdata)	/* consider us done */
				break;
		}

		/* timed out?  */
		if (!ISSET(mp->mp_flags, MBPPF_UIO))
			break;

		/*
		 * poll delay?
		 */
		if (mp->mp_delay > 0) {
			s = spltty();	/* XXX */
			SET(mp->mp_flags, MBPPF_DELAY);
			timeout_add(&mp->mp_start_tmo, mp->mp_delay);
			error = tsleep(mp, PCATCH | PZERO, "mbppdelay", 0);
			splx(s);
			if (error)
				break;
		}

		/*
		 * Don't call uiomove again until we used all the data we
		 * grabbed.
		 */
		if (uio->uio_rw == UIO_WRITE && cnt != len) {
			ptr += cnt;
			len -= cnt;
			cnt = 0;
			goto again;
		}
	}

	/*
	 * clear timeouts
	 */
	s = spltty();	/* XXX */
	if (ISSET(mp->mp_flags, MBPPF_TIMEOUT)) {
		timeout_del(&mp->mp_timeout_tmo);
		CLR(mp->mp_flags, MBPPF_TIMEOUT);
	}
	if (ISSET(mp->mp_flags, MBPPF_DELAY)) {
		timeout_del(&mp->mp_start_tmo);
		CLR(mp->mp_flags, MBPPF_DELAY);
	}
	splx(s);

	/*
	 * Adjust for those chars that we uiomoved but never actually wrote.
	 */
	if (uio->uio_rw == UIO_WRITE && cnt != len) {
		uio->uio_resid += (len - cnt);
	}

	free(buffer, M_DEVBUF, 0);
	return (error);
}

void
mbpp_timeout(arg)
	void *arg;
{
	struct mbpp_port *mp = arg;

	CLR(mp->mp_flags, MBPPF_UIO | MBPPF_TIMEOUT);
	wakeup(mp);
}

void
mbpp_start(arg)
	void *arg;
{
	struct mbpp_port *mp = arg;

	CLR(mp->mp_flags, MBPPF_DELAY);
	wakeup(mp);
}

int
mbpp_send(mp, ptr, len)
	struct mbpp_port *mp;
	caddr_t ptr;
	int len;
{
	int s;
	struct cd1400 *cd = mp->mp_cd1400;

	/* set up io information */
	mp->mp_ptr = ptr;
	mp->mp_cnt = len;

	/* start transmitting */
	s = spltty();
	if (cd) {
		cd1400_write_reg(cd, CD1400_CAR, 0);

		/* output strobe width ~1microsecond */
		cd1400_write_reg(cd, CD1400_TBPR, 10);

		/* enable channel */
		cd1400_write_ccr(cd, CD1400_CCR_CMDCHANCTL | CD1400_CCR_XMTEN);
		cd1400_write_reg(cd, CD1400_SRER, CD1400_SRER_TXRDY);
	}

	/* zzz... */
	tsleep(mp, PCATCH | PZERO, "mbpp_send", 0);

	/* stop transmitting */
	if (cd) {
		cd1400_write_reg(cd, CD1400_CAR, 0);

		/* disable transmitter */
		cd1400_write_reg(cd, CD1400_SRER, 0);
		cd1400_write_ccr(cd, CD1400_CCR_CMDCHANCTL | CD1400_CCR_XMTDIS);

		/* flush fifo */
		cd1400_write_ccr(cd, CD1400_CCR_CMDRESET | CD1400_CCR_FTF);
	}
	splx(s);

	/* return number of chars sent */
	return (len - mp->mp_cnt);
}

int
mbpp_recv(mp, ptr, len)
	struct mbpp_port *mp;
	caddr_t ptr;
	int len;
{
	int s;
	struct cd1400 *cd = mp->mp_cd1400;

	/* set up io information */
	mp->mp_ptr = ptr;
	mp->mp_cnt = len;

	/* start receiving */
	s = spltty();
	if (cd) {
		int rcor, rbpr;

		cd1400_write_reg(cd, CD1400_CAR, 0);

		/* input strobe at 100kbaud (10microseconds) */
		cd1400_compute_baud(100000, cd->cd_clock, &rcor, &rbpr);
		cd1400_write_reg(cd, CD1400_RCOR, rcor);
		cd1400_write_reg(cd, CD1400_RBPR, rbpr);

		/* rx threshold */
		cd1400_write_reg(cd, CD1400_COR3, MBPP_RX_FIFO_THRESHOLD);
		cd1400_write_ccr(cd, CD1400_CCR_CMDCORCHG | CD1400_CCR_COR3);

		/* enable channel */
		cd1400_write_ccr(cd, CD1400_CCR_CMDCHANCTL | CD1400_CCR_RCVEN);
		cd1400_write_reg(cd, CD1400_SRER, CD1400_SRER_RXDATA);
	}

	/* zzz... */
	tsleep(mp, PCATCH | PZERO, "mbpp_recv", 0);

	/* stop receiving */
	if (cd) {
		cd1400_write_reg(cd, CD1400_CAR, 0);

		/* disable receiving */
		cd1400_write_reg(cd, CD1400_SRER, 0);
		cd1400_write_ccr(cd, CD1400_CCR_CMDCHANCTL | CD1400_CCR_RCVDIS);
	}
	splx(s);

	/* return number of chars received */
	return (len - mp->mp_cnt);
}

int
mbpp_hztoms(h)
	int h;
{
	int m = h;

	if (m > 0)
		m = m * 1000 / hz;
	return (m);
}

int
mbpp_mstohz(m)
	int m;
{
	int h = m;

	if (h > 0) {
		h = h * hz / 1000;
		if (h == 0)
			h = 1000 / hz;
	}
	return (h);
}


code:
/*	$OpenBSD: magmareg.h,v 1.12 2014/03/29 18:09:30 guenther Exp $	*/

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

/*  The mapping of minor device number -> card and port is done as
 * follows by default:
 *
 *  +---+---+---+---+---+---+---+---+
 *  | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
 *  +---+---+---+---+---+---+---+---+
 *    |   |   |   |   |   |   |   |
 *    |   |   |   |   +---+---+---+---> port number
 *    |   |   |   |
 *    |   |   |   +-------------------> dialout (on tty ports)
 *    |   |   |
 *    |   |   +-----------------------> unused
 *    |   |
 *    +---+---------------------------> card number
 *
 */

#define MAGMA_MAX_CARDS		4
#define MAGMA_MAX_TTY		16
#define MAGMA_MAX_BPP		2
#define MAGMA_MAX_CD1400	4
#define MAGMA_MAX_CD1190	2

#define MAGMA_CARD(x)	((minor(x) >> 6) & 0x03)
#define MAGMA_PORT(x)	(minor(x) & 0x0f)

#define MTTY_DIALOUT(x) (minor(x) & 0x10)

/*
 * Supported Card Types
 */
struct magma_board_info {
	const char *mb_sbusname;	/* sbus name */
	const char *mb_name;		/* cardname to match against */
	const char *mb_realname;	/* english card name */
	int mb_nser;			/* number of serial ports */
	int mb_npar;			/* number of parallel ports */
	int mb_ncd1400;			/* number of CD1400 chips */
	int mb_svcackr;			/* svcackr offset */
	int mb_svcackt;			/* svcackt offset */
	int mb_svcackm;			/* svcackm offset */
	int mb_cd1400[MAGMA_MAX_CD1400];/* cd1400 chip register offsets */
	int mb_ncd1190;			/* number of CD1190 chips */
	int mb_cd1190[MAGMA_MAX_CD1190];/* cd1190 chip register offsets */
};

/*
 * cd1400 chip data
 */
struct cd1400 {
	volatile u_char *cd_reg;	/* chip registers */
	int cd_chiprev;			/* chip revision */
	int cd_clock;			/* clock speed in MHz */
	int cd_parmode;			/* parallel mode operation */
};

/*
 * cd1190 chip data
 */
struct cd1190 {
	volatile u_char *cd_reg;	/* chip registers */
	int cd_chiprev;			/* chip revision */
};

/* software state for each card */
struct magma_softc {
	struct device ms_dev;		/* required. must be first in softc */

	/* cd1400 chip info */
	int ms_ncd1400;
	struct cd1400 ms_cd1400[MAGMA_MAX_CD1400];
	volatile u_char *ms_svcackr;	/* CD1400 service acknowledge receive */
	volatile u_char *ms_svcackt;	/* CD1400 service acknowledge transmit */
	volatile u_char *ms_svcackm;	/* CD1400 service acknowledge modem */

	/* cd1190 chip info */
	int ms_ncd1190;
	struct cd1190 ms_cd1190[MAGMA_MAX_CD1190];

	const struct magma_board_info *ms_board;	/* what am I? */

	struct mtty_softc *ms_mtty;
	struct mbpp_softc *ms_mbpp;

	struct intrhand ms_hardint;	/* hard interrupt handler */
	void	*ms_softint;		/* soft interrupt handler */
};

#define MTTY_RBUF_SIZE		(2 * 512)
#define MTTY_RX_FIFO_THRESHOLD	6
#define MTTY_RX_DTR_THRESHOLD	9

struct mtty_port {
	struct cd1400 *mp_cd1400;	/* ptr to chip */
	int mp_channel;			/* and channel */
	struct tty *mp_tty;

	int mp_openflags;	/* default tty flags */
	int mp_flags;		/* port flags */
	int mp_carrier;		/* state of carrier */

	u_char *mp_rbuf;	/* ring buffer start */
	u_char *mp_rend;	/* ring buffer end */
	u_char *mp_rget;	/* ring buffer read pointer */
	u_char *mp_rput;	/* ring buffer write pointer */

	u_char *mp_txp;		/* transmit character pointer */
	int mp_txc;		/* transmit character counter */
};

#define MTTYF_CARRIER_CHANGED	(1<<0)
#define MTTYF_SET_BREAK		(1<<1)
#define MTTYF_CLR_BREAK		(1<<2)
#define MTTYF_DONE		(1<<3)
#define MTTYF_STOP		(1<<4)
#define MTTYF_RING_OVERFLOW	(1<<5)

struct mtty_softc {
	struct device ms_dev;		/* device info */
	int ms_nports;			/* tty ports */
	struct mtty_port ms_port[MAGMA_MAX_TTY];
};

#define MBPP_RX_FIFO_THRESHOLD	25

struct mbpp_port {
	struct cd1400 *mp_cd1400;	/* for LC2+1Sp card */
	struct cd1190 *mp_cd1190;	/* all the others   */

	int mp_flags;

	struct bpp_param mp_param;
#define mp_burst mp_param.bp_burst
#define mp_timeout mp_param.bp_timeout
#define mp_delay mp_param.bp_delay

	u_char *mp_ptr;			/* pointer to io data */
	int mp_cnt;			/* count of io chars */

	struct timeout mp_timeout_tmo;	/* for mbpp_timeout() */
	struct timeout mp_start_tmo;	/* for mbpp_start() */
};

#define MBPPF_OPEN	(1<<0)
#define MBPPF_TIMEOUT	(1<<1)
#define MBPPF_UIO	(1<<2)
#define MBPPF_DELAY	(1<<3)
#define MBPPF_WAKEUP	(1<<4)

struct mbpp_softc {
	struct device ms_dev;		/* device info */
	int ms_nports;			/* parallel ports */
	struct mbpp_port ms_port[MAGMA_MAX_BPP];
};

/* internal function prototypes */

int cd1400_compute_baud(speed_t, int, int *, int *);
__inline void cd1400_write_ccr(struct cd1400 *, u_char);
__inline u_char cd1400_read_reg(struct cd1400 *, int);
__inline void cd1400_write_reg(struct cd1400 *, int, u_char);
void cd1400_enable_transmitter(struct cd1400 *, int);

int magma_match(struct device *, void *, void *);
void magma_attach(struct device *, struct device *, void *);
int magma_hard(void *);
void magma_soft(void *);

int mtty_match(struct device *, void *, void *);
void mtty_attach(struct device *, struct device *, void *);
int mtty_modem_control(struct mtty_port *, int, int);
int mtty_param(struct tty *, struct termios *);
void mtty_start(struct tty *);

int mbpp_match(struct device *, void *, void *);
void mbpp_attach(struct device *, struct device *, void *);
int mbpp_rw(dev_t, struct uio *);
void mbpp_timeout(void *);
void mbpp_start(void *);
int mbpp_send(struct mbpp_port *, caddr_t, int);
int mbpp_recv(struct mbpp_port *, caddr_t, int);
int mbpp_hztoms(int);
int mbpp_mstohz(int);

license: unknown


code:
/*	$OpenBSD: mgx.c,v 1.18 2015/03/28 19:07:07 miod Exp $	*/
/*
 * Copyright (c) 2003, Miodrag Vallat.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
 * Driver for the Southland Media Systems (now Quantum 3D) MGX and MGXPlus
 * frame buffers.
 *
 * This board is built of an Alliance Promotion AT24 chip, and a simple
 * SBus-PCI glue logic. It also sports an EEPROM to store configuration
 * parameters, which can be controlled from SunOS or Solaris with the
 * mgxconfig utility.
 *
 * We currently don't reprogram the video mode at all, so only the resolution
 * and depth set by the PROM (or mgxconfig) will be used.
 *
 * Also, interrupts are not handled.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/buf.h>
#include <sys/device.h>
#include <sys/ioctl.h>
#include <sys/malloc.h>
#include <sys/mman.h>
#include <sys/tty.h>
#include <sys/conf.h>

#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <machine/pmap.h>
#include <machine/cpu.h>
#include <machine/conf.h>

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wsdisplayvar.h>
#include <dev/rasops/rasops.h>
#include <machine/fbvar.h>

#include <dev/ic/vgareg.h>
#include <dev/ic/atxxreg.h>

/*
 * MGX PROM register layout
 *
 * The cards FCode registers 9 regions:
 *
 * region  offset     size    description
 *      0 00000000  00010000  FCode (32KB only)
 *      1 00100000  00010000  FCode, repeated
 *      2 00200000  00001000  unknown, repeats every 0x100
 *                            with little differences, could be the EEPROM image
 *      3 00400000  00001000  PCI configuration space
 *      4 00500000  00001000  CRTC
 *      5 00600000  00001000  AT24 registers (offset 0xb0000)
 *      6 00700000  00010000  unknown
 *      7 00800000  00800000  unknown
 *      8 01000000  00400000  video memory
 */

#define	MGX_NREG			9
#define	MGX_REG_CRTC			4	/* video control and ramdac */
#define	MGX_REG_ATREG			5	/* AT24 registers */
#define	MGX_REG_ATREG_OFFSET	0x000b0000
#define	MGX_REG_ATREG_SIZE	0x00000400
#define	MGX_REG_VRAM8			8	/* 8-bit memory space */

/*
 * MGX CRTC access
 *
 * The CRTC only answers to the following ``port'' locations:
 * - a subset of the VGA registers:
 *   3c0, 3c1 (ATC)
 *   3c4, 3c5 (TS sequencer)
 *   3c6-3c9 (DAC)
 *   3c2, 3cc (Misc)
 *   3ce, 3cf (GDC)
 *
 * - the CRTC (6845-style) registers:
 *   3d4 index register
 *   3d5 data register
 */

#define	VGA_BASE		0x03c0
#define	TS_INDEX		(VGA_BASE + VGA_TS_INDEX)
#define	TS_DATA			(VGA_BASE + VGA_TS_DATA)
#define	CD_DISABLEVIDEO	0x0020
#define	CMAP_WRITE_INDEX	(VGA_BASE + 0x08)
#define	CMAP_DATA		(VGA_BASE + 0x09)

/* per-display variables */
struct mgx_softc {
	struct	sunfb	sc_sunfb;		/* common base device */
	struct	rom_reg sc_phys;		/* for mmap() */
	u_int8_t	sc_cmap[256 * 3];	/* shadow colormap */
	vaddr_t		sc_vidc;		/* ramdac registers */
	vaddr_t		sc_xreg;		/* AT24 registers */
	uint32_t	sc_dec;			/* dec register template */
};

void	mgx_burner(void *, u_int ,u_int);
int	mgx_ioctl(void *, u_long, caddr_t, int, struct proc *);
paddr_t	mgx_mmap(void *, off_t, int);

struct wsdisplay_accessops mgx_accessops = {
	.ioctl = mgx_ioctl,
	.mmap = mgx_mmap,
	.burn_screen = mgx_burner
};

int	mgx_getcmap(u_int8_t *, struct wsdisplay_cmap *);
void	mgx_loadcmap(struct mgx_softc *, int, int);
int	mgx_putcmap(u_int8_t *, struct wsdisplay_cmap *);
void	mgx_setcolor(void *, u_int, u_int8_t, u_int8_t, u_int8_t);

int	mgx_ras_copycols(void *, int, int, int, int);
int	mgx_ras_copyrows(void *, int, int, int);
int	mgx_ras_do_cursor(struct rasops_info *);
int	mgx_ras_erasecols(void *, int, int, int, long int);
int	mgx_ras_eraserows(void *, int, int, long int);
void	mgx_ras_init(struct mgx_softc *, uint);

uint8_t	mgx_read_1(vaddr_t, uint);
uint16_t mgx_read_2(vaddr_t, uint);
void	mgx_write_1(vaddr_t, uint, uint8_t);
void	mgx_write_4(vaddr_t, uint, uint32_t);

int	mgx_wait_engine(struct mgx_softc *);
int	mgx_wait_fifo(struct mgx_softc *, uint);

/*
 * Attachment Glue
 */

int	mgxmatch(struct device *, void *, void *);
void	mgxattach(struct device *, struct device *, void *);

struct cfattach mgx_ca = {
	sizeof(struct mgx_softc), mgxmatch, mgxattach
};

struct cfdriver mgx_cd = {
	NULL, "mgx", DV_DULL
};

/*
 * Match an MGX or MGX+ card.
 */
int
mgxmatch(struct device *parent, void *vcf, void *aux)
{
	struct confargs *ca = aux;
	struct romaux *ra = &ca->ca_ra;

	if (strcmp(ra->ra_name, "SMSI,mgx") != 0 &&
	    strcmp(ra->ra_name, "mgx") != 0)
		return (0);

	return (1);
}

/*
 * Attach an MGX frame buffer.
 * This will keep the frame buffer in the actual PROM mode, and attach
 * a wsdisplay child device to itself.
 */
void
mgxattach(struct device *parent, struct device *self, void *args)
{
	struct mgx_softc *sc = (struct mgx_softc *)self;
	struct confargs *ca = args;
	int node, fbsize;
	int isconsole;
	uint16_t chipid;

	node = ca->ca_ra.ra_node;

	printf(": %s", getpropstring(node, "model"));

	isconsole = node == fbnode;

	/* Check registers */
	if (ca->ca_ra.ra_nreg < MGX_NREG) {
		printf("\n%s: expected %d registers, got %d\n",
		    self->dv_xname, MGX_NREG, ca->ca_ra.ra_nreg);
		return;
	}

	sc->sc_vidc = (vaddr_t)mapiodev(&ca->ca_ra.ra_reg[MGX_REG_CRTC],
	    0, PAGE_SIZE);
	sc->sc_xreg = (vaddr_t)mapiodev(&ca->ca_ra.ra_reg[MGX_REG_ATREG],
	    MGX_REG_ATREG_OFFSET, MGX_REG_ATREG_SIZE);

	/*
	 * Check the chip ID. If it's not an AT24, prefer not to access
	 * the extended registers at all.
	 */
	chipid = mgx_read_2(sc->sc_xreg, ATR_ID);
	if (chipid != ID_AT24) {
		sc->sc_xreg = (vaddr_t)0;
	}

	/* enable video */
	mgx_burner(sc, 1, 0);

	fb_setsize(&sc->sc_sunfb, 8, 1152, 900, node, ca->ca_bustype);

	/* Sanity check frame buffer memory */
	fbsize = getpropint(node, "fb_size", 0);
	if (fbsize != 0 && sc->sc_sunfb.sf_fbsize > fbsize) {
		printf("\n%s: expected at least %d bytes of vram, but card "
		    "only provides %d\n",
		    self->dv_xname, sc->sc_sunfb.sf_fbsize, fbsize);
		return;
	}

	/* Map the frame buffer memory area we're interested in */
	sc->sc_phys = ca->ca_ra.ra_reg[MGX_REG_VRAM8];
	sc->sc_sunfb.sf_ro.ri_bits = mapiodev(&sc->sc_phys,
	    0, round_page(sc->sc_sunfb.sf_fbsize));
	sc->sc_sunfb.sf_ro.ri_hw = sc;

	printf(", %dx%d\n",
	    sc->sc_sunfb.sf_width, sc->sc_sunfb.sf_height);

	fbwscons_init(&sc->sc_sunfb, isconsole);

	bzero(sc->sc_cmap, sizeof(sc->sc_cmap));
	fbwscons_setcolormap(&sc->sc_sunfb, mgx_setcolor);

	if (chipid != ID_AT24) {
		printf("%s: unexpected engine id %04x\n",
		    self->dv_xname, chipid);
	}

	mgx_ras_init(sc, chipid);

	if (isconsole)
		fbwscons_console_init(&sc->sc_sunfb, -1);

	fbwscons_attach(&sc->sc_sunfb, &mgx_accessops, isconsole);
}

/*
 * Register Access
 *
 * On big-endian systems such as the sparc, it is necessary to flip
 * the low-order bits of the addresses to reach the right register.
 */

uint8_t
mgx_read_1(vaddr_t regs, uint offs)
{
#if _BYTE_ORDER == _LITTLE_ENDIAN
	return *(volatile uint8_t *)(regs + offs);
#else
	return *(volatile uint8_t *)(regs + (offs ^ 3));
#endif
}

uint16_t
mgx_read_2(vaddr_t regs, uint offs)
{
#if _BYTE_ORDER == _LITTLE_ENDIAN
	return *(volatile uint16_t *)(regs + offs);
#else
	return *(volatile uint16_t *)(regs + (offs ^ 2));
#endif
}

void
mgx_write_1(vaddr_t regs, uint offs, uint8_t val)
{
#if _BYTE_ORDER == _LITTLE_ENDIAN
	*(volatile uint8_t *)(regs + offs) = val;
#else
	*(volatile uint8_t *)(regs + (offs ^ 3)) = val;
#endif
}

void
mgx_write_4(vaddr_t regs, uint offs, uint32_t val)
{
	*(volatile uint32_t *)(regs + offs) = val;
}

/*
 * Wsdisplay Operations
 */

int
mgx_ioctl(void *dev, u_long cmd, caddr_t data, int flags, struct proc *p)
{
	struct mgx_softc *sc = dev;
	struct wsdisplay_cmap *cm;
	struct wsdisplay_fbinfo *wdf;
	int error;

	switch (cmd) {
	case WSDISPLAYIO_GTYPE:
		*(u_int *)data = WSDISPLAY_TYPE_MGX;
		break;
	case WSDISPLAYIO_GINFO:
		wdf = (struct wsdisplay_fbinfo *)data;
		wdf->height = sc->sc_sunfb.sf_height;
		wdf->width = sc->sc_sunfb.sf_width;
		wdf->depth = sc->sc_sunfb.sf_depth;
		wdf->cmsize = 256;
		break;
	case WSDISPLAYIO_LINEBYTES:
		*(u_int *)data = sc->sc_sunfb.sf_linebytes;
		break;

	case WSDISPLAYIO_GETCMAP:
		cm = (struct wsdisplay_cmap *)data;
		error = mgx_getcmap(sc->sc_cmap, cm);
		if (error != 0)
			return (error);
		break;
	case WSDISPLAYIO_PUTCMAP:
		cm = (struct wsdisplay_cmap *)data;
		error = mgx_putcmap(sc->sc_cmap, cm);
		if (error != 0)
			return (error);
		mgx_loadcmap(sc, cm->index, cm->count);
		break;

	case WSDISPLAYIO_SVIDEO:
	case WSDISPLAYIO_GVIDEO:
		break;

	default:
		return (-1);
	}

	return (0);
}

paddr_t
mgx_mmap(void *v, off_t offset, int prot)
{
	struct mgx_softc *sc = v;

	if (offset & PGOFSET)
		return (-1);

	/* Allow mapping as a dumb framebuffer from offset 0 */
	if (offset >= 0 && offset < sc->sc_sunfb.sf_fbsize) {
		return (REG2PHYS(&sc->sc_phys, offset) | PMAP_NC);
	}

	return (-1);
}

void
mgx_burner(void *v, u_int on, u_int flags)
{
	struct mgx_softc *sc = v;
	uint mode;

#ifdef notyet
	if (sc->sc_xreg != 0) {
		mode = mgx_read_1(sc->sc_xreg, ATR_DPMS);
		if (on)
			CLR(mode, DPMS_HSYNC_DISABLE | DPMS_VSYNC_DISABLE);
		else {
			SET(mode, DPMS_HSYNC_DISABLE);
#if 0	/* needs ramdac reprogramming on resume */
			if (flags & WSDISPLAY_BURN_VBLANK)
				SET(mode, DPMS_VSYNC_DISABLE);
#endif
		}
		mgx_write_1(sc->sc_xreg, ATR_DPMS, mode);
		return;
	}
#endif

	mgx_write_1(sc->sc_vidc, TS_INDEX, 1);	/* TS mode register */
	mode = mgx_read_1(sc->sc_vidc, TS_DATA);
	if (on)
		mode &= ~CD_DISABLEVIDEO;
	else
		mode |= CD_DISABLEVIDEO;
	mgx_write_1(sc->sc_vidc, TS_DATA, mode);
}

/*
 * Colormap Handling Routines
 */

void
mgx_setcolor(void *v, u_int index, u_int8_t r, u_int8_t g, u_int8_t b)
{
	struct mgx_softc *sc = v;
	u_int i = index * 3;

	sc->sc_cmap[i++] = r;
	sc->sc_cmap[i++] = g;
	sc->sc_cmap[i] = b;

	mgx_loadcmap(sc, index, 1);
}

void
mgx_loadcmap(struct mgx_softc *sc, int start, int ncolors)
{
	u_int8_t *color;
	int i;

	mgx_write_1(sc->sc_vidc, CMAP_WRITE_INDEX, start);
	color = sc->sc_cmap + start * 3;
	for (i = ncolors * 3; i != 0; i--)
		mgx_write_1(sc->sc_vidc, CMAP_DATA, *color++);
}

int
mgx_getcmap(u_int8_t *cm, struct wsdisplay_cmap *rcm)
{
	u_int index = rcm->index, count = rcm->count, i;
	int error;

	if (index >= 256 || count > 256 - index)
		return (EINVAL);

	index *= 3;
	for (i = 0; i < count; i++) {
		if ((error =
		    copyout(cm + index++, &rcm->red[i], 1)) != 0)
			return (error);
		if ((error =
		    copyout(cm + index++, &rcm->green[i], 1)) != 0)
			return (error);
		if ((error =
		    copyout(cm + index++, &rcm->blue[i], 1)) != 0)
			return (error);
	}

	return (0);
}

int
mgx_putcmap(u_int8_t *cm, struct wsdisplay_cmap *rcm)
{
	u_int index = rcm->index, count = rcm->count, i;
	int error;

	if (index >= 256 || count > 256 - index)
		return (EINVAL);

	index *= 3;
	for (i = 0; i < count; i++) {
		if ((error =
		    copyin(&rcm->red[i], cm + index++, 1)) != 0)
			return (error);
		if ((error =
		    copyin(&rcm->green[i], cm + index++, 1)) != 0)
			return (error);
		if ((error =
		    copyin(&rcm->blue[i], cm + index++, 1)) != 0)
			return (error);
	}

	return (0);
}

/*
 * Accelerated Text Console Code
 *
 * The X driver makes sure there are at least as many FIFOs available as
 * registers to write. They can thus be considered as write slots.
 *
 * The code below expects to run on at least an AT24 chip, and does not
 * care for the AP6422 which has fewer FIFOs; some operations would need
 * to be done in two steps to support this chip.
 */

int
mgx_wait_engine(struct mgx_softc *sc)
{
	uint i;
	uint stat;

	for (i = 10000; i != 0; i--) {
		stat = mgx_read_1(sc->sc_xreg, ATR_BLT_STATUS);
		if (!ISSET(stat, BLT_HOST_BUSY | BLT_ENGINE_BUSY))
			break;
	}

	return i;
}

int
mgx_wait_fifo(struct mgx_softc *sc, uint nfifo)
{
	uint i;
	uint stat;

	for (i = 10000; i != 0; i--) {
		stat = (mgx_read_1(sc->sc_xreg, ATR_FIFO_STATUS) & FIFO_MASK) >>
		    FIFO_SHIFT;
		if (stat >= nfifo)
			break;
		mgx_write_1(sc->sc_xreg, ATR_FIFO_STATUS, 0);
	}

	return i;
}

void
mgx_ras_init(struct mgx_softc *sc, uint chipid)
{
	/*
	 * Check the chip ID. If it's not a 6424, do not plug the
	 * accelerated routines.
	 */

	if (chipid != ID_AT24)
		return;

	/*
	 * Wait until the chip is completely idle.
	 */

	if (mgx_wait_engine(sc) == 0)
		return;
	if (mgx_wait_fifo(sc, FIFO_AT24) == 0)
		return;

	/*
	 * Compute the invariant bits of the DEC register.
	 */

	switch (sc->sc_sunfb.sf_depth) {
	case 8:
		sc->sc_dec = DEC_DEPTH_8 << DEC_DEPTH_SHIFT;
		break;
	case 15:
	case 16:
		sc->sc_dec = DEC_DEPTH_16 << DEC_DEPTH_SHIFT;
		break;
	case 32:
		sc->sc_dec = DEC_DEPTH_32 << DEC_DEPTH_SHIFT;
		break;
	default:
		return;	/* not supported */
	}

	switch (sc->sc_sunfb.sf_width) {
	case 640:
		sc->sc_dec |= DEC_WIDTH_640 << DEC_WIDTH_SHIFT;
		break;
	case 800:
		sc->sc_dec |= DEC_WIDTH_800 << DEC_WIDTH_SHIFT;
		break;
	case 1024:
		sc->sc_dec |= DEC_WIDTH_1024 << DEC_WIDTH_SHIFT;
		break;
	case 1152:
		sc->sc_dec |= DEC_WIDTH_1152 << DEC_WIDTH_SHIFT;
		break;
	case 1280:
		sc->sc_dec |= DEC_WIDTH_1280 << DEC_WIDTH_SHIFT;
		break;
	case 1600:
		sc->sc_dec |= DEC_WIDTH_1600 << DEC_WIDTH_SHIFT;
		break;
	default:
		return;	/* not supported */
	}

	sc->sc_sunfb.sf_ro.ri_ops.copycols = mgx_ras_copycols;
	sc->sc_sunfb.sf_ro.ri_ops.copyrows = mgx_ras_copyrows;
	sc->sc_sunfb.sf_ro.ri_ops.erasecols = mgx_ras_erasecols;
	sc->sc_sunfb.sf_ro.ri_ops.eraserows = mgx_ras_eraserows;
	sc->sc_sunfb.sf_ro.ri_do_cursor = mgx_ras_do_cursor;

#ifdef notneeded
	mgx_write_1(sc->sc_xreg, ATR_CLIP_CONTROL, 1);
	mgx_write_4(sc->sc_xreg, ATR_CLIP_LEFTTOP, ATR_DUAL(0, 0));
	mgx_write_4(sc->sc_xreg, ATR_CLIP_RIGHTBOTTOM,
	    ATR_DUAL(sc->sc_sunfb.sf_width - 1, sc->sc_sunfb.sf_depth - 1));
#else
	mgx_write_1(sc->sc_xreg, ATR_CLIP_CONTROL, 0);
#endif
	mgx_write_1(sc->sc_xreg, ATR_BYTEMASK, 0xff);
}

int
mgx_ras_copycols(void *v, int row, int src, int dst, int n)
{
	struct rasops_info *ri = v;
	struct mgx_softc *sc = ri->ri_hw;
	uint dec = sc->sc_dec;

	n *= ri->ri_font->fontwidth;
	src *= ri->ri_font->fontwidth;
	src += ri->ri_xorigin;
	dst *= ri->ri_font->fontwidth;
	dst += ri->ri_xorigin;
	row *= ri->ri_font->fontheight;
	row += ri->ri_yorigin;

	dec |= (DEC_COMMAND_BLT << DEC_COMMAND_SHIFT) |
	    (DEC_START_DIMX << DEC_START_SHIFT);
	if (src < dst) {
		src += n - 1;
		dst += n - 1;
		dec |= DEC_DIR_X_REVERSE;
	}
	mgx_wait_fifo(sc, 5);
	mgx_write_1(sc->sc_xreg, ATR_ROP, ROP_SRC);
	mgx_write_4(sc->sc_xreg, ATR_DEC, dec);
	mgx_write_4(sc->sc_xreg, ATR_SRC_XY, ATR_DUAL(row, src));
	mgx_write_4(sc->sc_xreg, ATR_DST_XY, ATR_DUAL(row, dst));
	mgx_write_4(sc->sc_xreg, ATR_WH, ATR_DUAL(ri->ri_font->fontheight, n));
	mgx_wait_engine(sc);

	return 0;
}

int
mgx_ras_copyrows(void *v, int src, int dst, int n)
{
	struct rasops_info *ri = v;
	struct mgx_softc *sc = ri->ri_hw;
	uint dec = sc->sc_dec;

	n *= ri->ri_font->fontheight;
	src *= ri->ri_font->fontheight;
	src += ri->ri_yorigin;
	dst *= ri->ri_font->fontheight;
	dst += ri->ri_yorigin;

	dec |= (DEC_COMMAND_BLT << DEC_COMMAND_SHIFT) |
	    (DEC_START_DIMX << DEC_START_SHIFT);
	if (src < dst) {
		src += n - 1;
		dst += n - 1;
		dec |= DEC_DIR_Y_REVERSE;
	}
	mgx_wait_fifo(sc, 5);
	mgx_write_1(sc->sc_xreg, ATR_ROP, ROP_SRC);
	mgx_write_4(sc->sc_xreg, ATR_DEC, dec);
	mgx_write_4(sc->sc_xreg, ATR_SRC_XY, ATR_DUAL(src, ri->ri_xorigin));
	mgx_write_4(sc->sc_xreg, ATR_DST_XY, ATR_DUAL(dst, ri->ri_xorigin));
	mgx_write_4(sc->sc_xreg, ATR_WH, ATR_DUAL(n, ri->ri_emuwidth));
	mgx_wait_engine(sc);

	return 0;
}

int
mgx_ras_erasecols(void *v, int row, int col, int n, long int attr)
{
	struct rasops_info *ri = v;
	struct mgx_softc *sc = ri->ri_hw;
	int fg, bg;
	uint dec = sc->sc_dec;

	ri->ri_ops.unpack_attr(v, attr, &fg, &bg, NULL);
	bg = ri->ri_devcmap[bg];

	n *= ri->ri_font->fontwidth;
	col *= ri->ri_font->fontwidth;
	col += ri->ri_xorigin;
	row *= ri->ri_font->fontheight;
	row += ri->ri_yorigin;

	dec |= (DEC_COMMAND_RECT << DEC_COMMAND_SHIFT) |
	    (DEC_START_DIMX << DEC_START_SHIFT);
	mgx_wait_fifo(sc, 5);
	mgx_write_1(sc->sc_xreg, ATR_ROP, ROP_SRC);
	mgx_write_4(sc->sc_xreg, ATR_FG, bg);
	mgx_write_4(sc->sc_xreg, ATR_DEC, dec);
	mgx_write_4(sc->sc_xreg, ATR_DST_XY, ATR_DUAL(row, col));
	mgx_write_4(sc->sc_xreg, ATR_WH, ATR_DUAL(ri->ri_font->fontheight, n));
	mgx_wait_engine(sc);

	return 0;
}

int
mgx_ras_eraserows(void *v, int row, int n, long int attr)
{
	struct rasops_info *ri = v;
	struct mgx_softc *sc = ri->ri_hw;
	int fg, bg;
	uint dec = sc->sc_dec;

	ri->ri_ops.unpack_attr(v, attr, &fg, &bg, NULL);
	bg = ri->ri_devcmap[bg];

	dec |= (DEC_COMMAND_RECT << DEC_COMMAND_SHIFT) |
	    (DEC_START_DIMX << DEC_START_SHIFT);
	mgx_wait_fifo(sc, 5);
	mgx_write_1(sc->sc_xreg, ATR_ROP, ROP_SRC);
	mgx_write_4(sc->sc_xreg, ATR_FG, bg);
	mgx_write_4(sc->sc_xreg, ATR_DEC, dec);
	if (n == ri->ri_rows && ISSET(ri->ri_flg, RI_FULLCLEAR)) {
		mgx_write_4(sc->sc_xreg, ATR_DST_XY, ATR_DUAL(0, 0));
		mgx_write_4(sc->sc_xreg, ATR_WH,
		    ATR_DUAL(ri->ri_height, ri->ri_width));
	} else {
		n *= ri->ri_font->fontheight;
		row *= ri->ri_font->fontheight;
		row += ri->ri_yorigin;

		mgx_write_4(sc->sc_xreg, ATR_DST_XY,
		    ATR_DUAL(row, ri->ri_xorigin));
		mgx_write_4(sc->sc_xreg, ATR_WH, ATR_DUAL(n, ri->ri_emuwidth));
	}
	mgx_wait_engine(sc);

	return 0;
}

int
mgx_ras_do_cursor(struct rasops_info *ri)
{
	struct mgx_softc *sc = ri->ri_hw;
	int row, col;
	uint dec = sc->sc_dec;

	row = ri->ri_crow * ri->ri_font->fontheight + ri->ri_yorigin;
	col = ri->ri_ccol * ri->ri_font->fontwidth + ri->ri_xorigin;

	dec |= (DEC_COMMAND_BLT << DEC_COMMAND_SHIFT) |
	    (DEC_START_DIMX << DEC_START_SHIFT);
	mgx_wait_fifo(sc, 5);
	mgx_write_1(sc->sc_xreg, ATR_ROP, (uint8_t)~ROP_SRC);
	mgx_write_4(sc->sc_xreg, ATR_DEC, dec);
	mgx_write_4(sc->sc_xreg, ATR_SRC_XY, ATR_DUAL(row, col));
	mgx_write_4(sc->sc_xreg, ATR_DST_XY, ATR_DUAL(row, col));
	mgx_write_4(sc->sc_xreg, ATR_WH,
	    ATR_DUAL(ri->ri_font->fontheight, ri->ri_font->fontwidth));
	mgx_wait_engine(sc);

	return 0;
}


code:
/*	$OpenBSD: obio.c,v 1.25 2015/03/30 20:30:22 miod Exp $	*/
/*	$NetBSD: obio.c,v 1.37 1997/07/29 09:58:11 fair Exp $	*/

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

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

#ifdef DEBUG
#include <sys/proc.h>
#include <sys/syslog.h>
#endif

#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <machine/pmap.h>
#include <machine/oldmon.h>
#include <machine/cpu.h>
#include <machine/ctlreg.h>
#include <sparc/sparc/asm.h>
#include <sparc/sparc/vaddrs.h>
#include <sparc/sparc/cpuvar.h>
#include <sparc/dev/sbusvar.h>
#include <sparc/dev/vmereg.h>

struct vmebus_softc {
	struct device	 sc_dev;	/* base device */
	struct vmebusreg *sc_reg; 	/* VME control registers */
	struct vmebusvec *sc_vec;	/* VME interrupt vector */
	struct rom_range *sc_range;	/* ROM range property */
	int		 sc_nrange;
};
struct  vmebus_softc *vmebus_sc;/*XXX*/

struct bus_softc {
	union {
		struct	device scu_dev;		/* base device */
		struct	sbus_softc scu_sbus;	/* obio is another sbus slot */
		struct	vmebus_softc scu_vme;
	} bu;
};

/* autoconfiguration driver */
int	busmatch(struct device *, void *, void *);
void	obioattach(struct device *, struct device *, void *);
void	vmesattach(struct device *, struct device *, void *);
void	vmelattach(struct device *, struct device *, void *);
void	vmeattach(struct device *, struct device *, void *);

int	busprint(void *, const char *);
int	vmeprint(void *, const char *);
int	busattach(struct device *, void *, void *, int);
int	obio_scan(struct device *, void *, void *);
int 	vmes_scan(struct device *, void *, void *);
int 	vmel_scan(struct device *, void *, void *);
void	vmebus_translate(struct device *, struct confargs *, int);
int 	vmeintr(void *);

struct cfattach obio_ca = {
	sizeof(struct bus_softc), busmatch, obioattach
};

struct cfdriver obio_cd = {
	NULL, "obio", DV_DULL
};

struct cfattach vmel_ca = {
	sizeof(struct bus_softc), busmatch, vmelattach
};

struct cfdriver vmel_cd = {
	NULL, "vmel", DV_DULL
};

struct cfattach vmes_ca = {
	sizeof(struct bus_softc), busmatch, vmesattach
};

struct cfdriver vmes_cd = {
	NULL, "vmes", DV_DULL
};

struct cfattach vme_ca = {
	sizeof(struct bus_softc), busmatch, vmeattach
};

struct cfdriver vme_cd = {
	NULL, "vme", DV_DULL
};

struct intrhand **vmeints;

/*
 * 4/110 comment: the 4/110 chops off the top 4 bits of an OBIO address.
 *	this confuses autoconf.  for example, if you try and map
 *	0xfe000000 in obio space on a 4/110 it actually maps 0x0e000000.
 *	this is easy to verify with the PROM.   this causes problems
 *	with devices like "esp0 at obio0 addr 0xfa000000" because the
 *	4/110 treats it as esp0 at obio0 addr 0x0a000000" which is the
 *	address of the 4/110's "sw0" scsi chip.   the same thing happens
 *	between zs1 and zs2.    since the sun4 line is "closed" and
 *	we know all the "obio" devices that will ever be on it we just
 *	put in some special case "if"'s in the match routines of esp,
 *	dma, and zs.
 */

int
busmatch(parent, vcf, aux)
	struct device *parent;
	void *vcf, *aux;
{
	register struct cfdata *cf = vcf;
	register struct confargs *ca = aux;
	register struct romaux *ra = &ca->ca_ra;

	if (CPU_ISSUN4M)
		return (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0);

	if (!CPU_ISSUN4)
		return (0);

	return (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0);
}

int
busprint(args, obio)
	void *args;
	const char *obio;
{
	register struct confargs *ca = args;

	if (ca->ca_ra.ra_name == NULL)
		ca->ca_ra.ra_name = "<unknown>";

	if (obio)
		printf("%s at %s", ca->ca_ra.ra_name, obio);

	printf(" addr %p", ca->ca_ra.ra_paddr);

	if (CPU_ISSUN4 && ca->ca_ra.ra_intr[0].int_vec != -1)
		printf(" vec 0x%x", ca->ca_ra.ra_intr[0].int_vec);

	return (UNCONF);
}

int
vmeprint(args, name)
	void *args;
	const char *name;
{
	register struct confargs *ca = args;

	if (name)
		printf("%s at %s", ca->ca_ra.ra_name, name);
	return (UNCONF);
}

void
obioattach(parent, self, args)
	struct device *parent, *self;
	void *args;
{
#if defined(SUN4M)
	register struct bus_softc *sc = (struct bus_softc *)self;
	struct confargs oca, *ca = args;
	register struct romaux *ra = &ca->ca_ra;
	register int node0, node;
	register char *name;
	register const char *sp;
	const char *const *ssp;
	int rlen;
	extern int autoconf_nzs;

	static const char *const special4m[] = {
		/* find these first */
		"eeprom",
		"counter",
#if 0 /* Not all sun4m's have an `auxio' */
		"auxio",
#endif
		"",
		/* place device to ignore here */
		"interrupt",
		NULL
	};
#endif

	if (CPU_ISSUN4) {
		if (self->dv_unit > 0) {
			printf(" unsupported\n");
			return;
		}
		printf("\n");

		(void)config_search(obio_scan, self, args);
		bus_untmp();
	}

#if defined(SUN4M)
	if (!CPU_ISSUN4M)
		return;

	/*
	 * There is only one obio bus (it is in fact one of the SBus slots)
	 * How about VME?
	 */
	if (self->dv_unit > 0) {
		printf(" unsupported\n");
		return;
	}

	printf("\n");

	if (ra->ra_bp != NULL && strcmp(ra->ra_bp->name, "obio") == 0)
		oca.ca_ra.ra_bp = ra->ra_bp + 1;
	else
		oca.ca_ra.ra_bp = NULL;

	node = ra->ra_node;
	rlen = getproplen(node, "ranges");
	if (rlen > 0) {
		sc->bu.scu_sbus.sc_nrange = rlen / sizeof(struct rom_range);
		sc->bu.scu_sbus.sc_range =
			(struct rom_range *)malloc(rlen, M_DEVBUF, M_NOWAIT);
		if (sc->bu.scu_sbus.sc_range == 0)
			panic("obio: PROM ranges too large: %d", rlen);
		(void)getprop(node, "ranges", sc->bu.scu_sbus.sc_range, rlen);
	}

	/*
	 * Loop through ROM children, fixing any relative addresses
	 * and then configuring each device.
	 * We first do the crucial ones, such as eeprom, etc.
	 */
	node0 = firstchild(ra->ra_node);
	for (ssp = special4m ; *(sp = *ssp) != 0; ssp++) {
		if ((node = findnode(node0, sp)) == 0) {
			printf("could not find %s amongst obio devices\n", sp);
			panic(sp);
		}
		if (!romprop(&oca.ca_ra, sp, node))
			continue;

		sbus_translate(self, &oca);
		oca.ca_bustype = BUS_OBIO;
		oca.ca_dmat = ca->ca_dmat;
		config_found(self, (void *)&oca, busprint);
	}

	for (node = node0; node; node = nextsibling(node)) {
		name = getpropstring(node, "name");
		for (ssp = special4m ; (sp = *ssp) != NULL; ssp++)
			if (strcmp(name, sp) == 0)
				break;

		if (sp != NULL || !romprop(&oca.ca_ra, name, node))
			continue;

		if (strcmp(name, "zs") == 0)
			/* XXX - see autoconf.c for this hack */
			autoconf_nzs++;

		/* Translate into parent address spaces */
		sbus_translate(self, &oca);
		oca.ca_bustype = BUS_OBIO;
		oca.ca_dmat = ca->ca_dmat;
		config_found(self, (void *)&oca, busprint);
	}
#endif
}

void
vmesattach(parent, self, args)
	struct device *parent, *self;
	void *args;
{
	if (self->dv_unit > 0 ||
	    (CPU_ISSUN4M && strcmp(parent->dv_cfdata->cf_driver->cd_name, "vme") != 0)) {
		printf(" unsupported\n");
		return;
	}
	printf("\n");

	if (vmeints == NULL) {
		vmeints = malloc(256 * sizeof(struct intrhand *), M_TEMP,
		    M_NOWAIT | M_ZERO);
		if (vmeints == NULL)
			panic("vmesattach: can't allocate intrhand");
	}
	(void)config_search(vmes_scan, self, args);
	bus_untmp();
}

void
vmelattach(parent, self, args)
	struct device *parent, *self;
	void *args;
{
	if (self->dv_unit > 0 ||
	    (CPU_ISSUN4M && strcmp(parent->dv_cfdata->cf_driver->cd_name, "vme") != 0)) {
		printf(" unsupported\n");
		return;
	}
	printf("\n");

	if (vmeints == NULL) {
		vmeints = malloc(256 * sizeof(struct intrhand *), M_TEMP,
		    M_NOWAIT | M_ZERO);
		if (vmeints == NULL)
			panic("vmelattach: can't allocate intrhand");
	}
	(void)config_search(vmel_scan, self, args);
	bus_untmp();
}

void
vmeattach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct vmebus_softc *sc = (struct vmebus_softc *)self;
	struct confargs *ca = aux;
	register struct romaux *ra = &ca->ca_ra;
	int node, rlen;
	struct confargs oca;

	if (!CPU_ISSUN4M || self->dv_unit > 0) {
		printf(" unsupported\n");
		return;
	}

	node = ra->ra_node;

	sc->sc_reg = (struct vmebusreg *)
		mapiodev(&ra->ra_reg[0], 0, ra->ra_reg[0].rr_len);
	sc->sc_vec = (struct vmebusvec *)
		mapiodev(&ra->ra_reg[1], 0, ra->ra_reg[1].rr_len);

	/*
	 * Get "range" property, though we don't do anything with it yet.
	 */
	rlen = getproplen(node, "ranges");
	if (rlen > 0) {
		sc->sc_nrange = rlen / sizeof(struct rom_range);
		sc->sc_range =
			(struct rom_range *)malloc(rlen, M_DEVBUF, M_NOWAIT);
		if (sc->sc_range == 0)
			panic("vme: PROM ranges too large: %d", rlen);
		(void)getprop(node, "ranges", sc->sc_range, rlen);
	}

	vmebus_sc = sc;
	printf(": version 0x%x\n",
	       sc->sc_reg->vmebus_cr & VMEBUS_CR_IMPL);

	if (ra->ra_bp != NULL && strcmp(ra->ra_bp->name, "vme") == 0)
		oca.ca_ra.ra_bp = ra->ra_bp + 1;
	else
		oca.ca_ra.ra_bp = NULL;

	oca.ca_ra.ra_name = "vmes";
	oca.ca_bustype = BUS_MAIN;
	oca.ca_dmat = ca->ca_dmat;
	config_found(self, (void *)&oca, vmeprint);

	oca.ca_ra.ra_name = "vmel";
	oca.ca_bustype = BUS_MAIN;
	oca.ca_dmat = ca->ca_dmat;
	config_found(self, (void *)&oca, vmeprint);
}

void
vmebus_translate(dev, ca, bustype)
	struct device *dev;
	struct confargs *ca;
	int bustype;
{
	struct vmebus_softc *sc = (struct vmebus_softc *)dev;
	register int j;
	int cspace;

	if (sc->sc_nrange == 0)
		panic("vmebus: no ranges");

	/*
	 * Find VMEbus modifier based on address space.
	 * XXX - should not be encoded in `ra_paddr'
	 */
	if (((u_long)ca->ca_ra.ra_paddr & 0xffff0000) == 0xffff0000)
		cspace = VMEMOD_A16_D_S;
	else if (((u_long)ca->ca_ra.ra_paddr & 0xff000000) == 0xff000000)
		cspace = VMEMOD_A24_D_S;
	else
		cspace = VMEMOD_A32_D_S;

	cspace |= (bustype == BUS_VME32) ? VMEMOD_D32 : 0;

	/* Translate into parent address spaces */
	for (j = 0; j < sc->sc_nrange; j++) {
		if (sc->sc_range[j].cspace == cspace) {
#if notyet
			ca->ca_ra.ra_paddr +=
				sc->sc_range[j].poffset;
#endif
			ca->ca_ra.ra_iospace =
				sc->sc_range[j].pspace;
			break;
		}
	}
}

int bt2pmt[] = {
	PMAP_OBIO,
	PMAP_OBIO,
	PMAP_VME16,
	PMAP_VME32,
	PMAP_OBIO
};

int
busattach(parent, vcf, args, bustype)
	struct device *parent;
	void *vcf, *args;
	int bustype;
{
#if defined(SUN4) || defined(SUN4M)
	register struct cfdata *cf = vcf;
	register struct confargs *ca = args;
	struct confargs oca;
	paddr_t pa = (paddr_t)cf->cf_loc[0];
	caddr_t tmp;

	if (bustype == BUS_OBIO && CPU_ISSUN4) {
		/*
		 * avoid sun4m entries which don't have valid PA's.
		 * no point in even probing them.
		 */
		if (cf->cf_loc[0] == -1) return 0;

		/*
		 * On the 4/100 obio addresses must be mapped at
		 * 0x0YYYYYYY, but alias higher up (the kernel
		 * configuration file uses addresses with the top
		 * four bits set). We ignore 4/[23]00 devices here.
		 */
		if (cpuinfo.cpu_type == CPUTYP_4_100) {
			if ((pa & 0xf0000000) != 0xf0000000)
				return 0;
		}
	}

	oca.ca_ra.ra_paddr = (void *)pa;
	oca.ca_ra.ra_len = 0;
	oca.ca_ra.ra_nreg = 1;
	if (CPU_ISSUN4M)
		vmebus_translate(parent->dv_parent, &oca, bustype);
	else
		oca.ca_ra.ra_iospace = bt2pmt[bustype];

	if (oca.ca_ra.ra_paddr)
		tmp = (caddr_t)mapdev(oca.ca_ra.ra_reg, TMPMAP_VA, 0, NBPG);
	else
		tmp = NULL;
	oca.ca_ra.ra_vaddr = tmp;
	oca.ca_ra.ra_intr[0].int_pri = cf->cf_loc[1];
	if (bustype == BUS_VME16 || bustype == BUS_VME32)
		oca.ca_ra.ra_intr[0].int_vec = cf->cf_loc[2];
	else
		oca.ca_ra.ra_intr[0].int_vec = -1;
	oca.ca_ra.ra_nintr = 1;
	oca.ca_ra.ra_name = cf->cf_driver->cd_name;
	if (ca->ca_ra.ra_bp != NULL &&
	  ((bustype == BUS_VME16 && strcmp(ca->ca_ra.ra_bp->name,"vmes") ==0) ||
	   (bustype == BUS_VME32 && strcmp(ca->ca_ra.ra_bp->name,"vmel") ==0) ||
	   (bustype == BUS_OBIO && strcmp(ca->ca_ra.ra_bp->name,"obio") == 0)))
		oca.ca_ra.ra_bp = ca->ca_ra.ra_bp + 1;
	else
		oca.ca_ra.ra_bp = NULL;
	oca.ca_bustype = bustype;

	if ((*cf->cf_attach->ca_match)(parent, cf, &oca) == 0)
		return 0;

	/*
	 * check if XXmatch routine replaced the temporary mapping with
	 * a real mapping.   If not, then make sure we don't pass the
	 * tmp mapping to the attach routine.
	 */
	if (oca.ca_ra.ra_vaddr == tmp)
		oca.ca_ra.ra_vaddr = NULL; /* wipe out tmp address */
	/*
	 * the match routine will set "ra_len" if it wants us to
	 * establish a mapping for it.
	 * (which won't be seen on future XXmatch calls,
	 * so not as useful as it seems.)
	 */
	if (oca.ca_ra.ra_len)
		oca.ca_ra.ra_vaddr =
		    bus_map(oca.ca_ra.ra_reg, oca.ca_ra.ra_len);

	config_attach(parent, cf, &oca, busprint);
	return 1;
#else
	return 0;
#endif
}

int
obio_scan(parent, child, args)
	struct device *parent;
	void *child, *args;
{
	return busattach(parent, child, args, BUS_OBIO);
}

int
vmes_scan(parent, child, args)
	struct device *parent;
	void *child, *args;
{
	return busattach(parent, child, args, BUS_VME16);
}

int
vmel_scan(parent, child, args)
	struct device *parent;
	void *child, *args;
{
	return busattach(parent, child, args, BUS_VME32);
}

int pil_to_vme[] = {
	-1,	/* pil 0 */
	-1,	/* pil 1 */
	1,	/* pil 2 */
	2,	/* pil 3 */
	-1,	/* pil 4 */
	3,	/* pil 5 */
	-1,	/* pil 6 */
	4,	/* pil 7 */
	-1,	/* pil 8 */
	5,	/* pil 9 */
	-1,	/* pil 10 */
	6,	/* pil 11 */
	-1,	/* pil 12 */
	7,	/* pil 13 */
	-1,	/* pil 14 */
	-1,	/* pil 15 */
};

int
vmeintr(arg)
	void *arg;
{
	int pil = (int)arg, level, vec;
	struct intrhand *ih;
	int r, i = 0;

	level = (pil_to_vme[pil] << 1) | 1;

	if (CPU_ISSUN4) {
		vec = ldcontrolb((caddr_t)(AC_VMEINTVEC | level));
	} else if (CPU_ISSUN4M) {
		vec = vmebus_sc->sc_vec->vmebusvec[level];
	} else
		panic("vme: spurious interrupt");

	if (vec == -1) {
		printf("vme: spurious interrupt\n");
		return 0;
	}

	for (ih = vmeints[vec]; ih; ih = ih->ih_next)
		if (ih->ih_fun) {
			r = (ih->ih_fun)(ih->ih_arg);
			if (r > 0) {
				ih->ih_count.ec_count++;
				return (r);
			}
			i |= r;
		}
	return (i);
}

void
vmeintr_establish(vec, level, ih, ipl_block, name)
	int vec, level;
	struct intrhand *ih;
	int ipl_block;
	const char *name;
{
	struct intrhand *ihs;

	if (vmeints == NULL)
		panic("vmeintr_establish: interrupt vector not allocated");

	if (vec == -1)
		panic("vmeintr_establish: uninitialized vec");

	if (vmeints[vec] == NULL)
		vmeints[vec] = ih;
	else {
		for (ihs = vmeints[vec]; ihs->ih_next; ihs = ihs->ih_next)
			;
		ihs->ih_next = ih;
	}

	if (name != NULL) {
		ih->ih_vec = vec;
		evcount_attach(&ih->ih_count, name, &ih->ih_vec);
	}

	/* ensure the interrupt subsystem will call us at this level */
	for (ihs = intrhand[level]; ihs; ihs = ihs->ih_next)
		if (ihs->ih_fun == vmeintr)
			return;

	ihs = malloc(sizeof(*ihs), M_TEMP, M_NOWAIT | M_ZERO);
	if (ihs == NULL)
		panic("vme_addirq");
	ihs->ih_fun = vmeintr;
	ihs->ih_arg = (void *)level;
	intr_establish(level, ihs, ipl_block, NULL);
}

#define	getpte(va)		lda(va, ASI_PTE)

/*
 * If we can find a mapping that was established by the rom, use it.
 * Else, create a new mapping.
 */
void *
bus_map(pa, len)
	struct rom_reg *pa;
	int len;
{
#ifdef SUN4
	if (CPU_ISSUN4 && len <= NBPG) {
		paddr_t paddr;
		vaddr_t va;
		u_long	pf, pte;
		int pgtype = PMAP_T2PTE_4(pa->rr_iospace);

		if (cpuinfo.cpu_type == CPUTYP_4_100)
			paddr = ((paddr_t)pa->rr_paddr) & 0x0fffffff;
		else
			paddr = (paddr_t)pa->rr_paddr;
		pf = paddr >> PGSHIFT;

		for (va = OLDMON_STARTVADDR; va < OLDMON_ENDVADDR; va += NBPG) {
			pte = getpte(va);
			if ((pte & PG_V) != 0 && (pte & PG_TYPE) == pgtype &&
			    (pte & PG_PFNUM) == pf)
				return ((void *)
				    (va | ((u_long)pa->rr_paddr & PGOFSET)) );
					/* note: preserve page offset */
		}
	}
#endif

	return mapiodev(pa, 0, len);
}

void
bus_untmp()
{
	pmap_remove(pmap_kernel(), TMPMAP_VA, TMPMAP_VA+NBPG);
	pmap_update(pmap_kernel());
}