code:
/*	$OpenBSD: xy.c,v 1.68 2015/01/16 20:18:24 miod Exp $	*/
/*	$NetBSD: xy.c,v 1.26 1997/07/19 21:43:56 pk Exp $	*/

/*
 * Copyright (c) 1995 Charles D. Cranor
 * 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.
 */

/*
 *
 * x y . c   x y l o g i c s   4 5 0 / 4 5 1   s m d   d r i v e r
 *
 * author: Chuck Cranor <chuck@ccrc.wustl.edu>
 * id: $NetBSD: xy.c,v 1.26 1997/07/19 21:43:56 pk Exp $
 * started: 14-Sep-95
 * references: [1] Xylogics Model 753 User's Manual
 *                 part number: 166-753-001, Revision B, May 21, 1988.
 *                 "Your Partner For Performance"
 *             [2] other NetBSD disk device drivers
 *	       [3] Xylogics Model 450 User's Manual
 *		   part number: 166-017-001, Revision B, 1983.
 *	       [4] Addendum to Xylogics Model 450 Disk Controller User's
 *			Manual, Jan. 1985.
 *	       [5] The 451 Controller, Rev. B3, September 2, 1986.
 *	       [6] David Jones <dej@achilles.net>'s unfinished 450/451 driver
 *
 */

#undef XYC_DEBUG		/* full debug */
#undef XYC_DIAG			/* extra sanity checks */
#if defined(DIAGNOSTIC) && !defined(XYC_DIAG)
#define XYC_DIAG		/* link in with master DIAG option */
#endif

#include <sys/param.h>
#include <sys/proc.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/buf.h>
#include <sys/uio.h>
#include <sys/malloc.h>
#include <sys/device.h>
#include <sys/disklabel.h>
#include <sys/disk.h>
#include <sys/syslog.h>
#include <sys/dkbad.h>
#include <sys/conf.h>
#include <sys/timeout.h>
#include <sys/dkio.h>

#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <dev/sun/disklabel.h>
#include <machine/conf.h>

#include <sparc/dev/xyreg.h>
#include <sparc/dev/xyvar.h>
#include <sparc/sparc/vaddrs.h>

/*
 * macros
 */

/*
 * XYC_GO: start iopb ADDR (DVMA addr in a u_long) on XYC
 */
#define XYC_GO(XYC, ADDR) { \
	(XYC)->xyc_addr_lo = ((ADDR) & 0xff); \
	(ADDR) = ((ADDR) >> 8); \
	(XYC)->xyc_addr_hi = ((ADDR) & 0xff); \
	(ADDR) = ((ADDR) >> 8); \
	(XYC)->xyc_reloc_lo = ((ADDR) & 0xff); \
	(ADDR) = ((ADDR) >> 8); \
	(XYC)->xyc_reloc_hi = (ADDR); \
	(XYC)->xyc_csr = XYC_GBSY; /* go! */ \
}

/*
 * XYC_DONE: don't need IORQ, get error code and free (done after xyc_cmd)
 */

#define XYC_DONE(SC,ER) { \
	if ((ER) == XY_ERR_AOK) { \
		(ER) = (SC)->ciorq->errno; \
		(SC)->ciorq->mode = XY_SUB_FREE; \
		wakeup((SC)->ciorq); \
	} \
	}

/*
 * XYC_ADVANCE: advance iorq's pointers by a number of sectors
 */

#define XYC_ADVANCE(IORQ, N) { \
	if (N) { \
		(IORQ)->sectcnt -= (N); \
		(IORQ)->blockno += (N); \
		(IORQ)->dbuf += ((N)*XYFM_BPS); \
	} \
}

/*
 * note - addresses you can sleep on:
 *   [1] & of xy_softc's "state" (waiting for a chance to attach a drive)
 *   [2] & an iorq (waiting for an XY_SUB_WAIT iorq to finish)
 */

/*
 * function prototypes
 * "xyc_*" functions are internal, all others are external interfaces
 */

extern int pil_to_vme[];	/* from obio.c */

/* internals */
struct xy_iopb *xyc_chain(struct xyc_softc *, struct xy_iorq *);
int	xyc_cmd(struct xyc_softc *, int, int, int, int, int, char *, int);
const char *xyc_e2str(int);
int	xyc_entoact(int);
int	xyc_error(struct xyc_softc *, struct xy_iorq *,
		   struct xy_iopb *, int);
void	xyc_perror(struct xy_iorq *, struct xy_iopb *, int);
int	xyc_piodriver(struct xyc_softc *, struct xy_iorq *);
int	xyc_remove_iorq(struct xyc_softc *);
int	xyc_reset(struct xyc_softc *, int, struct xy_iorq *, int,
			struct xy_softc *);
inline void xyc_rqinit(struct xy_iorq *, struct xyc_softc *,
			    struct xy_softc *, int, u_long, int,
			    caddr_t, struct buf *);
void	xyc_rqtopb(struct xy_iorq *, struct xy_iopb *, int, int);
void	xyc_start(struct xyc_softc *, struct xy_iorq *);
int	xyc_startbuf(struct xyc_softc *, struct xy_softc *, struct buf *);
int	xyc_submit_iorq(struct xyc_softc *, struct xy_iorq *, int);
void	xyc_tick(void *);
int	xyc_unbusy(struct xyc *, int);
void	xyc_xyreset(struct xyc_softc *, struct xy_softc *);

/* machine interrupt hook */
int	xycintr(void *);

/* autoconf */
int	xycmatch(struct device *, void *, void *);
void	xycattach(struct device *, struct device *, void *);
int	xymatch(struct device *, void *, void *);
void	xyattach(struct device *, struct device *, void *);

static	void xydummystrat(struct buf *);
int	xygetdisklabel(dev_t, struct xy_softc *, struct disklabel *, int);

/*
 * cfdrivers: device driver interface to autoconfig
 */

struct cfattach xyc_ca = {
	sizeof(struct xyc_softc), xycmatch, xycattach
};

struct cfdriver xyc_cd = {
	NULL, "xyc", DV_DULL
};

struct cfattach xy_ca = {
	sizeof(struct xy_softc), xymatch, xyattach
};

struct cfdriver xy_cd = {
	NULL, "xy", DV_DISK
};

struct xyc_attach_args {	/* this is the "aux" args to xyattach */
	int	driveno;	/* unit number */
	char	*buf;		/* scratch buffer for reading disk label */
	char	*dvmabuf;	/* DVMA address of above */
	int	fullmode;	/* submit mode */
	int	booting;	/* are we booting or not? */
};

static void
xydummystrat(bp)
	struct buf *bp;
{
	struct xy_softc *xy;
	size_t sz;

	xy = (struct xy_softc *)xy_cd.cd_devs[DISKUNIT(bp->b_dev)];
	sz = MIN(bp->b_bcount, XYFM_BPS);
	bcopy(xy->xy_labeldata, bp->b_data, sz);
	bp->b_resid = bp->b_bcount - sz;
	if (bp->b_resid != 0) {
		bp->b_flags |= B_ERROR;
		bp->b_error = EIO;
	}
	bp->b_flags |= B_DONE;
}

int
xygetdisklabel(dev, xy, lp, spoofonly)
	dev_t dev;
	struct xy_softc *xy;
	struct disklabel *lp;
	int spoofonly;
{
	int error;

	bzero(lp, sizeof(struct disklabel));
	/* Required parameters for readdisklabel() */
	lp->d_secsize = XYFM_BPS;
	if (xy->state == XY_DRIVE_ATTACHING || xy->state == XY_DRIVE_NOLABEL) {
		/* needs to be nonzero */
		lp->d_secpercyl = 1;
	} else {
		/*
		 * Disk geometry is known for a previously found label.
		 * Use it.
		 */
		lp->d_ntracks = xy->nhead;
		lp->d_nsectors = xy->nsect;
		lp->d_ncylinders = xy->ncyl;
		lp->d_acylinders = xy->acyl;
		lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
		DL_SETDSIZE(lp, (u_int64_t)lp->d_secpercyl * lp->d_ncylinders);
	}
	lp->d_type = DTYPE_SMD;
	lp->d_version = 1;

	/* These are as defined in <ufs/ffs/fs.h> */
	lp->d_bbsize = 8192; /* BBSIZE */
	lp->d_sbsize = 8192; /* SBSIZE */

	lp->d_magic = DISKMAGIC;
	lp->d_magic2 = DISKMAGIC;
	lp->d_checksum = dkcksum(lp);

	error = readdisklabel(DISKLABELDEV(dev),
	    xy->state == XY_DRIVE_ATTACHING ? xydummystrat : xystrategy,
	    lp, spoofonly);
	if (error)
		return error;

	/*
	 * If a label was found, get our geometry from it.
	 */
	if (xy->state == XY_DRIVE_ATTACHING || xy->state == XY_DRIVE_NOLABEL) {
		/*
		 * Note that this relies upon pcyl == cyl + acyl, and will
		 * ignore the explicit pcyl value from the converted SunOS
		 * label.
		 */
		xy->pcyl = lp->d_ncylinders + lp->d_acylinders;
		xy->ncyl = lp->d_ncylinders;
		xy->acyl = lp->d_acylinders;
		xy->nhead = lp->d_ntracks;
		xy->nsect = lp->d_nsectors;
		xy->sectpercyl = lp->d_secpercyl;
	}
	return 0;
}

/*
 * a u t o c o n f i g   f u n c t i o n s
 */

/*
 * xycmatch: determine if xyc is present or not.   we do a
 * soft reset to detect the xyc.
 */

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

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

	switch (ca->ca_bustype) {
	case BUS_OBIO:
	case BUS_SBUS:
	case BUS_VME32:
	default:
		return (0);
	case BUS_VME16:
		xyc = (struct xyc *) ra->ra_vaddr;
		if (probeget((caddr_t) &xyc->xyc_rsetup, 1) == -1)
			return (0);
		if (xyc_unbusy(xyc, XYC_RESETUSEC) == XY_ERR_FAIL)
			return(0);
		return (1);
	}
}

/*
 * xycattach: attach controller
 */
void
xycattach(parent, self, aux)
	struct device *parent, *self;
	void   *aux;

{
	struct xyc_softc *xyc = (void *) self;
	struct confargs *ca = aux;
	struct xyc_attach_args xa;
	int     lcv, err, pri, res, pbsz;
	void	*tmp, *tmp2;
	void	*dtmp, *dtmp2;
	u_long	ultmp;

	/* get addressing and intr level stuff from autoconfig and load it
	 * into our xyc_softc. */

	ca->ca_ra.ra_vaddr = mapiodev(ca->ca_ra.ra_reg, 0, sizeof(struct xyc));

	xyc->xyc = (struct xyc *) ca->ca_ra.ra_vaddr;
	pri = ca->ca_ra.ra_intr[0].int_pri;
	xyc->ipl = pil_to_vme[pri];
	xyc->vector = ca->ca_ra.ra_intr[0].int_vec;
	printf(" pri %d", pri);
	xyc->no_ols = 0; /* XXX should be from config */

	for (lcv = 0; lcv < XYC_MAXDEV; lcv++)
		xyc->sc_drives[lcv] = (struct xy_softc *) 0;

	/*
	 * allocate and zero buffers
	 * check boundaries of the KVA's ... all IOPBs must reside in
 	 * the same 64K region.
	 */

	pbsz = XYC_MAXIOPB * sizeof(struct xy_iopb);
	dtmp = dtmp2 = (struct xy_iopb *)dvma_malloc(pbsz, &tmp, M_NOWAIT);
	tmp2 = tmp;
	ultmp = (u_long) dtmp;
	if ((ultmp & 0xffff0000) != ((ultmp + pbsz) & 0xffff0000)) {
		dtmp = (struct xy_iopb *)
		    dvma_malloc(pbsz, &tmp, M_NOWAIT); /* retry! */
		dvma_free(dtmp2, pbsz, &tmp2);
		ultmp = (u_long) dtmp;
		if ((ultmp & 0xffff0000) != ((ultmp + pbsz) & 0xffff0000)) {
			printf("%s: can't alloc IOPB mem in 64K\n",
				xyc->sc_dev.dv_xname);
			return;
		}
	}
	bzero(tmp, pbsz);
	xyc->iopbase = tmp;
	xyc->iopbase = dtmp; /* XXX TMP HACK */
	xyc->dvmaiopb = (struct xy_iopb *) ((u_long)dtmp - DVMA_BASE);
	xyc->reqs = malloc(XYC_MAXIOPB * sizeof(struct xy_iorq), M_DEVBUF,
	    M_NOWAIT | M_ZERO);
	if (xyc->reqs == NULL)
		panic("xyc malloc");

	/*
	 * init iorq to iopb pointers, and non-zero fields in the
	 * iopb which never change.
	 */

	for (lcv = 0; lcv < XYC_MAXIOPB; lcv++) {
		xyc->xy_chain[lcv] = NULL;
		xyc->reqs[lcv].iopb = &xyc->iopbase[lcv];
		xyc->iopbase[lcv].asr = 1;	/* always the same */
		xyc->iopbase[lcv].eef = 1;	/* always the same */
		xyc->iopbase[lcv].ecm = XY_ECM;	/* always the same */
		xyc->iopbase[lcv].aud = 1;	/* always the same */
		xyc->iopbase[lcv].relo = 1;	/* always the same */
		xyc->iopbase[lcv].thro = XY_THRO;/* always the same */
	}
	xyc->ciorq = &xyc->reqs[XYC_CTLIOPB];    /* shorthand name */
	xyc->ciopb = &xyc->iopbase[XYC_CTLIOPB]; /* shorthand name */
	xyc->xy_hand = 0;

	/* read controller parameters and insure we have a 450/451 */

	err = xyc_cmd(xyc, XYCMD_ST, 0, 0, 0, 0, 0, XY_SUB_POLL);
	res = xyc->ciopb->ctyp;
	XYC_DONE(xyc, err);
	if (res != XYCT_450) {
		if (err)
			printf(": %s: ", xyc_e2str(err));
		printf(": doesn't identify as a 450/451\n");
		return;
	}
	printf(": Xylogics 450/451");
	if (xyc->no_ols)
		printf(" [OLS disabled]"); /* 450 doesn't overlap seek right */
	printf("\n");
	if (err) {
		printf("%s: error: %s\n", xyc->sc_dev.dv_xname,
				xyc_e2str(err));
		return;
	}
	if ((xyc->xyc->xyc_csr & XYC_ADRM) == 0) {
		printf("%s: 24 bit addressing turned off\n",
			xyc->sc_dev.dv_xname);
		printf("please set hardware jumpers JM1-JM2=in, JM3-JM4=out\n");
		printf("to enable 24 bit mode and this driver\n");
		return;
	}

	/* link in interrupt with higher level software */

	xyc->sc_ih.ih_fun = xycintr;
	xyc->sc_ih.ih_arg = xyc;
	vmeintr_establish(ca->ca_ra.ra_intr[0].int_vec,
	    ca->ca_ra.ra_intr[0].int_pri, &xyc->sc_ih, IPL_BIO,
	    self->dv_xname);

	/* now we must look for disks using autoconfig */
	xa.dvmabuf = (char *)dvma_malloc(XYFM_BPS, &xa.buf, M_NOWAIT);
	xa.fullmode = XY_SUB_POLL;
	xa.booting = 1;

	if (ca->ca_ra.ra_bp && ca->ca_ra.ra_bp->val[0] == -1 &&
	    ca->ca_ra.ra_bp->val[1] == xyc->sc_dev.dv_unit) {
		bootpath_store(1, ca->ca_ra.ra_bp + 1); /* advance bootpath */
	}

	for (xa.driveno = 0; xa.driveno < XYC_MAXDEV; xa.driveno++)
		(void) config_found(self, (void *) &xa, NULL);

	dvma_free(xa.dvmabuf, XYFM_BPS, &xa.buf);
	bootpath_store(1, NULL);

	/* start the watchdog clock */
	timeout_set(&xyc->xyc_tick_tmo, xyc_tick, xyc);
	timeout_add(&xyc->xyc_tick_tmo, XYC_TICKCNT);

}

/*
 * xymatch: probe for disk.
 *
 * note: we almost always say disk is present.   this allows us to
 * spin up and configure a disk after the system is booted (we can
 * call xyattach!).
 */
int
xymatch(parent, vcf, aux)
	struct device *parent;
	void *vcf, *aux;
{
	struct cfdata *cf = vcf;
	struct xyc_attach_args *xa = aux;

	/* looking for autoconf wildcard or exact match */

	if (cf->cf_loc[0] != -1 && cf->cf_loc[0] != xa->driveno)
		return 0;

	return 1;

}

/*
 * xyattach: attach a disk.   this can be called from autoconf and also
 * from xyopen/xystrategy.
 */
void
xyattach(parent, self, aux)
	struct device *parent, *self;
	void   *aux;

{
	struct xy_softc *xy = (void *) self, *oxy;
	struct xyc_softc *xyc = (void *) parent;
	struct xyc_attach_args *xa = aux;
	int     err, spt, mb, blk, lcv, fmode, s = 0, newstate;
	struct dkbad *dkb;
	struct bootpath *bp;

	/*
	 * Always re-initialize the disk structure.  We want statistics
	 * to start with a clean slate.
	 */
	bzero(&xy->sc_dk, sizeof(xy->sc_dk));
	xy->sc_dk.dk_name = xy->sc_dev.dv_xname;

	/* if booting, init the xy_softc */

	if (xa->booting) {
		xy->state = XY_DRIVE_UNKNOWN;	/* to start */
		xy->flags = 0;
		xy->parent = xyc;

		/* init queue of waiting bufs */
		bufq_init(&xy->xy_bufq, BUFQ_DEFAULT);

		xy->xyrq = &xyc->reqs[xa->driveno];

	}
	xy->xy_drive = xa->driveno;
	fmode = xa->fullmode;
	xyc->sc_drives[xa->driveno] = xy;

	/* if not booting, make sure we are the only process in the attach for
	 * this drive.   if locked out, sleep on it. */

	if (!xa->booting) {
		s = splbio();
		while (xy->state == XY_DRIVE_ATTACHING) {
			if (tsleep(&xy->state, PRIBIO, "xyattach", 0)) {
				splx(s);
				return;
			}
		}
		printf("%s at %s",
			xy->sc_dev.dv_xname, xy->parent->sc_dev.dv_xname);
	}
	/* we now have control */

	xy->state = XY_DRIVE_ATTACHING;
	newstate = XY_DRIVE_UNKNOWN;

	/* first try and reset the drive */

	err = xyc_cmd(xyc, XYCMD_RST, 0, xy->xy_drive, 0, 0, 0, fmode);
	XYC_DONE(xyc, err);
	if (err == XY_ERR_DNRY) {
		printf(" drive %d: off-line\n", xa->driveno);
		goto done;
	}
	if (err) {
		printf(": ERROR 0x%02x (%s)\n", err, xyc_e2str(err));
		goto done;
	}
	printf(" drive %d: ready", xa->driveno);

	/*
	 * now set drive parameters (to semi-bogus values) so we can read the
	 * disk label.
	 */
	xy->pcyl = xy->ncyl = 1;
	xy->acyl = 0;
	xy->nhead = 1;
	xy->nsect = 1;
	xy->sectpercyl = 1;
	for (lcv = 0; lcv < NBT_BAD; lcv++)	/* init empty bad144 table */
		xy->dkb.bt_bad[lcv].bt_cyl =
			xy->dkb.bt_bad[lcv].bt_trksec = 0xffff;

	/* read disk label */
	for (xy->drive_type = 0 ; xy->drive_type <= XYC_MAXDT ;
						xy->drive_type++) {
		err = xyc_cmd(xyc, XYCMD_RD, 0, xy->xy_drive, 0, 1,
						xa->dvmabuf, fmode);
		XYC_DONE(xyc, err);
		if (err == XY_ERR_AOK) break;
	}

	if (err != XY_ERR_AOK) {
		printf("\n%s: reading disk label failed: %s\n",
			xy->sc_dev.dv_xname, xyc_e2str(err));
		goto done;
	}
	printf(" (drive type %d)\n", xy->drive_type);

	newstate = XY_DRIVE_NOLABEL;

	xy->hw_spt = spt = 0; /* XXX needed ? */
	/* Attach the disk: must be before getdisklabel to malloc label */
	disk_attach(&xy->sc_dev, &xy->sc_dk);

	xy->xy_labeldata = xa->buf;
	if (xygetdisklabel(MAKEDISKDEV(0, xy->sc_dev.dv_unit, 0), xy,
	    xy->sc_dk.dk_label, 0) != 0) {
		printf("%s: no label, unknown geometry\n", xy->sc_dev.dv_xname);
		goto done;
	}

	/* inform the user of what is up */
	printf("%s: <%s>, pcyl %d\n", xy->sc_dev.dv_xname,
		xa->buf, xy->pcyl);
	mb = xy->ncyl * (xy->nhead * xy->nsect) / (1048576 / XYFM_BPS);
	printf("%s: %dMB, %d cyl, %d head, %d sec, %d bytes/sec\n",
		xy->sc_dev.dv_xname, mb, xy->ncyl, xy->nhead, xy->nsect,
		XYFM_BPS);

	/*
	 * 450/451 stupidity: the drive type is encoded into the format
	 * of the disk.   the drive type in the IOPB must match the drive
	 * type in the format, or you will not be able to do I/O to the
	 * disk (you get header not found errors).  if you have two drives
	 * of different sizes that have the same drive type in their
	 * formatting then you are out of luck.
	 *
	 * this problem was corrected in the 753/7053.
	 */

	for (lcv = 0 ; lcv < XYC_MAXDEV ; lcv++) {
		oxy = xyc->sc_drives[lcv];
		if (oxy == NULL || oxy == xy) continue;
		if (oxy->drive_type != xy->drive_type) continue;
		if (xy->nsect != oxy->nsect || xy->pcyl != oxy->pcyl ||
			xy->nhead != oxy->nhead) {
			printf("%s: %s and %s must be the same size!\n",
				xyc->sc_dev.dv_xname, xy->sc_dev.dv_xname,
				oxy->sc_dev.dv_xname);
			panic("xy drive size mismatch");
		}
	}

	/* now set the real drive parameters! */

	blk = (xy->nsect - 1) +
		((xy->nhead - 1) * xy->nsect) +
		((xy->pcyl - 1) * xy->nsect * xy->nhead);
	err = xyc_cmd(xyc, XYCMD_SDS, 0, xy->xy_drive, blk, 0, 0, fmode);
	XYC_DONE(xyc, err);
	if (err) {
		printf("%s: write drive size failed: %s\n",
			xy->sc_dev.dv_xname, xyc_e2str(err));
		goto done;
	}
	newstate = XY_DRIVE_ONLINE;

	/*
	 * read bad144 table. this table resides on the first sector of the
	 * last track of the disk (i.e. second cyl of "acyl" area).
	 */

	blk = (xy->ncyl + xy->acyl - 1) * (xy->nhead * xy->nsect) +
								/* last cyl */
	    (xy->nhead - 1) * xy->nsect;	/* last head */
	err = xyc_cmd(xyc, XYCMD_RD, 0, xy->xy_drive, blk, 1,
						xa->dvmabuf, fmode);
	XYC_DONE(xyc, err);
	if (err) {
		printf("%s: reading bad144 failed: %s\n",
			xy->sc_dev.dv_xname, xyc_e2str(err));
		goto done;
	}

	/* check dkbad for sanity */
	dkb = (struct dkbad *) xa->buf;
	for (lcv = 0; lcv < NBT_BAD; lcv++) {
		if ((dkb->bt_bad[lcv].bt_cyl == 0xffff ||
				dkb->bt_bad[lcv].bt_cyl == 0) &&
		     dkb->bt_bad[lcv].bt_trksec == 0xffff)
			continue;	/* blank */
		if (dkb->bt_bad[lcv].bt_cyl >= xy->ncyl)
			break;
		if ((dkb->bt_bad[lcv].bt_trksec >> 8) >= xy->nhead)
			break;
		if ((dkb->bt_bad[lcv].bt_trksec & 0xff) >= xy->nsect)
			break;
	}
	if (lcv != NBT_BAD) {
		printf("%s: warning: invalid bad144 sector!\n",
			xy->sc_dev.dv_xname);
	} else {
		bcopy(xa->buf, &xy->dkb, XYFM_BPS);
	}

	if (xa->booting) {
		/* restore bootpath! (do this via attach_args again?)*/
		bp = bootpath_store(0, NULL);
		if (bp && strcmp("xy", bp->name) == 0 &&
					xy->xy_drive == bp->val[0])
			bp->dev = &xy->sc_dev;
	}

done:
	xy->state = newstate;
	if (!xa->booting) {
		wakeup(&xy->state);
		splx(s);
	}
}

/*
 * end of autoconfig functions
 */

/*
 * { b , c } d e v s w   f u n c t i o n s
 */

/*
 * xyclose: close device
 */
int
xyclose(dev, flag, fmt, p)
	dev_t   dev;
	int     flag, fmt;
	struct proc *p;

{
	struct xy_softc *xy = xy_cd.cd_devs[DISKUNIT(dev)];
	int     part = DISKPART(dev);

	/* clear mask bits */

	switch (fmt) {
	case S_IFCHR:
		xy->sc_dk.dk_copenmask &= ~(1 << part);
		break;
	case S_IFBLK:
		xy->sc_dk.dk_bopenmask &= ~(1 << part);
		break;
	}
	xy->sc_dk.dk_openmask = xy->sc_dk.dk_copenmask | xy->sc_dk.dk_bopenmask;

	return 0;
}

/*
 * xydump: crash dump system
 */
int
xydump(dev, blkno, va, size)
	dev_t dev;
	daddr_t blkno;
	caddr_t va;
	size_t size;
{
	int     unit, part;
	struct xy_softc *xy;

	unit = DISKUNIT(dev);
	if (unit >= xy_cd.cd_ndevs)
		return ENXIO;
	part = DISKPART(dev);

	xy = xy_cd.cd_devs[unit];

	printf("%s%c: crash dump not supported (yet)\n", xy->sc_dev.dv_xname,
	    'a' + part);

	return ENXIO;
}

/*
 * xyioctl: ioctls on XY drives.   based on ioctl's of other netbsd disks.
 */
int
xyioctl(dev, command, addr, flag, p)
	dev_t   dev;
	u_long  command;
	caddr_t addr;
	int     flag;
	struct proc *p;

{
	struct xy_softc *xy;
	int     error, s, unit;

	unit = DISKUNIT(dev);

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

	/* switch on ioctl type */

	switch (command) {
	case DIOCSBAD:		/* set bad144 info */
		if ((flag & FWRITE) == 0)
			return EBADF;
		s = splbio();
		bcopy(addr, &xy->dkb, sizeof(xy->dkb));
		splx(s);
		return 0;

	case DIOCGPDINFO:
		xygetdisklabel(dev, xy, (struct disklabel *)addr, 1);
		return 0;

	case DIOCGDINFO:	/* get disk label */
		bcopy(xy->sc_dk.dk_label, addr, sizeof(struct disklabel));
		return 0;

	case DIOCGPART:	/* get partition info */
		((struct partinfo *)addr)->disklab = xy->sc_dk.dk_label;
		((struct partinfo *)addr)->part =
		    &xy->sc_dk.dk_label->d_partitions[DISKPART(dev)];
		return 0;

	case DIOCWDINFO:	/* write disk label */
	case DIOCSDINFO:	/* set disk label */
		if ((flag & FWRITE) == 0)
			return EBADF;
		error = setdisklabel(xy->sc_dk.dk_label,
		    (struct disklabel *)addr, /* xy->sc_dk.dk_openmask : */ 0);
		if (error == 0) {
			if (xy->state == XY_DRIVE_NOLABEL)
				xy->state = XY_DRIVE_ONLINE;

			if (command == DIOCWDINFO) {
				/*
				 * Simulate opening partition 0 so write
				 * succeeds.
				 */
				xy->sc_dk.dk_openmask |= (1 << 0);
				error = writedisklabel(DISKLABELDEV(dev),
				    xystrategy, xy->sc_dk.dk_label);
				xy->sc_dk.dk_openmask = xy->sc_dk.dk_copenmask |
				    xy->sc_dk.dk_bopenmask;
			}
		}
		return error;

	default:
		return ENOTTY;
	}
}

/*
 * xyopen: open drive
 */

int
xyopen(dev, flag, fmt, p)
	dev_t   dev;
	int     flag, fmt;
	struct proc *p;
{
	int     unit, part;
	struct xy_softc *xy;
	struct xyc_attach_args xa;

	/* first, could it be a valid target? */

	unit = DISKUNIT(dev);
	if (unit >= xy_cd.cd_ndevs || (xy = xy_cd.cd_devs[unit]) == NULL)
		return (ENXIO);
	part = DISKPART(dev);

	/* do we need to attach the drive? */

	if (xy->state == XY_DRIVE_UNKNOWN) {
		xa.driveno = xy->xy_drive;
		xa.dvmabuf = (char *)dvma_malloc(XYFM_BPS, &xa.buf, M_NOWAIT);
		xa.fullmode = XY_SUB_WAIT;
		xa.booting = 0;
		xyattach((struct device *) xy->parent,
						(struct device *) xy, &xa);
		dvma_free(xa.dvmabuf, XYFM_BPS, &xa.buf);
		if (xy->state == XY_DRIVE_UNKNOWN) {
			return (EIO);
		}
	}
	/* check for partition */

	if (part != RAW_PART &&
	    (part >= xy->sc_dk.dk_label->d_npartitions ||
		xy->sc_dk.dk_label->d_partitions[part].p_fstype == FS_UNUSED)) {
		return (ENXIO);
	}
	/* set open masks */

	switch (fmt) {
	case S_IFCHR:
		xy->sc_dk.dk_copenmask |= (1 << part);
		break;
	case S_IFBLK:
		xy->sc_dk.dk_bopenmask |= (1 << part);
		break;
	}
	xy->sc_dk.dk_openmask = xy->sc_dk.dk_copenmask | xy->sc_dk.dk_bopenmask;

	return 0;
}

int
xyread(dev, uio, flags)
	dev_t   dev;
	struct uio *uio;
	int flags;
{

	return (physio(xystrategy, dev, B_READ, minphys, uio));
}

int
xywrite(dev, uio, flags)
	dev_t   dev;
	struct uio *uio;
	int flags;
{

	return (physio(xystrategy, dev, B_WRITE, minphys, uio));
}

/*
 * xysize: return size of a partition for a dump
 */

daddr_t
xysize(dev)
	dev_t   dev;

{
	struct xy_softc *xysc;
	int     unit, part, omask;
	daddr_t size;

	/* valid unit? */
	unit = DISKUNIT(dev);
	if (unit >= xy_cd.cd_ndevs || (xysc = xy_cd.cd_devs[unit]) == NULL)
		return (-1);

	part = DISKPART(dev);
	omask = xysc->sc_dk.dk_openmask & (1 << part);

	if (omask == 0 && xyopen(dev, 0, S_IFBLK, NULL) != 0)
		return (-1);

	/* do it */
	if (xysc->sc_dk.dk_label->d_partitions[part].p_fstype != FS_SWAP)
		size = -1;	/* only give valid size for swap partitions */
	else
		size = DL_GETPSIZE(&xysc->sc_dk.dk_label->d_partitions[part]) *
		    (xysc->sc_dk.dk_label->d_secsize / DEV_BSIZE);
	if (omask == 0 && xyclose(dev, 0, S_IFBLK, NULL) != 0)
		return (-1);
	return (size);
}

/*
 * xystrategy: buffering system interface to xy.
 */

void
xystrategy(bp)
	struct buf *bp;

{
	struct xy_softc *xy;
	int     s, unit;
	struct xyc_attach_args xa;

	unit = DISKUNIT(bp->b_dev);

	/* check for live device */

	if (unit >= xy_cd.cd_ndevs || (xy = xy_cd.cd_devs[unit]) == 0) {
		bp->b_error = EINVAL;
		goto bad;
	}
	/* do we need to attach the drive? */

	if (xy->state == XY_DRIVE_UNKNOWN) {
		xa.driveno = xy->xy_drive;
		xa.dvmabuf = (char *)dvma_malloc(XYFM_BPS, &xa.buf, M_NOWAIT);
		xa.fullmode = XY_SUB_WAIT;
		xa.booting = 0;
		xyattach((struct device *)xy->parent, (struct device *)xy, &xa);
		dvma_free(xa.dvmabuf, XYFM_BPS, &xa.buf);
		if (xy->state == XY_DRIVE_UNKNOWN) {
			bp->b_error = EIO;
			goto bad;
		}
	}
	if (xy->state != XY_DRIVE_ONLINE && DISKPART(bp->b_dev) != RAW_PART) {
		/* no I/O to unlabeled disks, unless raw partition */
		bp->b_error = EIO;
		goto bad;
	}

	/* Validate the request. */
	if (bounds_check_with_label(bp, xy->sc_dk.dk_label) == -1)
		goto done;

	bufq_queue(&xy->xy_bufq, bp);

	/*
	 * now we know we have a valid buf structure that we need to do I/O
	 * on.
	 */
	s = splbio();		/* protect the queues */

	/* start 'em up */

	xyc_start(xy->parent, NULL);

	/* done! */

	splx(s);
	return;

 bad:				/* tells upper layers we have an error */
	bp->b_flags |= B_ERROR;
	bp->b_resid = bp->b_bcount;
 done:				/* tells upper layers we are done with this
				 * buf */
	s = splbio();
	biodone(bp);
	splx(s);
}
/*
 * end of {b,c}devsw functions
 */

/*
 * i n t e r r u p t   f u n c t i o n
 *
 * xycintr: hardware interrupt.
 */
int
xycintr(v)
	void   *v;

{
	struct xyc_softc *xycsc = v;

	/* remove as many done IOPBs as possible */

	xyc_remove_iorq(xycsc);

	/* start any iorq's already waiting */

	xyc_start(xycsc, NULL);

	return (1);
}
/*
 * end of interrupt function
 */

/*
 * i n t e r n a l   f u n c t i o n s
 */

/*
 * xyc_rqinit: fill out the fields of an I/O request
 */

inline void
xyc_rqinit(rq, xyc, xy, md, blk, cnt, db, bp)
	struct xy_iorq *rq;
	struct xyc_softc *xyc;
	struct xy_softc *xy;
	int     md;
	u_long  blk;
	int     cnt;
	caddr_t db;
	struct buf *bp;
{
	rq->xyc = xyc;
	rq->xy = xy;
	rq->ttl = XYC_MAXTTL + 10;
	rq->mode = md;
	rq->tries = rq->errno = rq->lasterror = 0;
	rq->blockno = blk;
	rq->sectcnt = cnt;
	rq->dbuf = rq->dbufbase = db;
	rq->buf = bp;
}

/*
 * xyc_rqtopb: load up an IOPB based on an iorq
 */

void
xyc_rqtopb(iorq, iopb, cmd, subfun)
	struct xy_iorq *iorq;
	struct xy_iopb *iopb;
	int     cmd, subfun;

{
	u_long  block, dp;

	/* normal IOPB case, standard stuff */

	/* chain bit handled later */
	iopb->ien = (XY_STATE(iorq->mode) == XY_SUB_POLL) ? 0 : 1;
	iopb->com = cmd;
	iopb->errno = 0;
	iopb->errs = 0;
	iopb->done = 0;
	if (iorq->xy) {
		iopb->unit = iorq->xy->xy_drive;
		iopb->dt = iorq->xy->drive_type;
	} else {
		iopb->unit = 0;
		iopb->dt = 0;
	}
	block = iorq->blockno;
	if (iorq->xy == NULL || block == 0) {
		iopb->sect = iopb->head = iopb->cyl = 0;
	} else {
		iopb->sect = block % iorq->xy->nsect;
		block = block / iorq->xy->nsect;
		iopb->head = block % iorq->xy->nhead;
		block = block / iorq->xy->nhead;
		iopb->cyl = block;
	}
	iopb->scnt = iorq->sectcnt;
	dp = (u_long) iorq->dbuf - DVMA_BASE;
	if (iorq->dbuf == NULL) {
		iopb->dataa = 0;
		iopb->datar = 0;
	} else {
		iopb->dataa = (dp & 0xffff);
		iopb->datar = ((dp & 0xff0000) >> 16);
	}
	iopb->subfn = subfun;
}

/*
 * xyc_unbusy: wait for the xyc to go unbusy, or timeout.
 */

int
xyc_unbusy(xyc, del)

struct xyc *xyc;
int del;

{
	while (del-- > 0) {
		if ((xyc->xyc_csr & XYC_GBSY) == 0)
			break;
		DELAY(1);
	}
	return(del == 0 ? XY_ERR_FAIL : XY_ERR_AOK);
}

/*
 * xyc_cmd: front end for POLL'd and WAIT'd commands.  Returns 0 or error.
 * note that NORM requests are handled separately.
 */
int
xyc_cmd(xycsc, cmd, subfn, unit, block, scnt, dptr, fullmode)
	struct xyc_softc *xycsc;
	int     cmd, subfn, unit, block, scnt;
	char   *dptr;
	int     fullmode;

{
	int     submode = XY_STATE(fullmode);
	struct xy_iorq *iorq = xycsc->ciorq;
	struct xy_iopb *iopb = xycsc->ciopb;

	/*
	 * is someone else using the control iopq wait for it if we can
	 */
start:
	if (submode == XY_SUB_WAIT && XY_STATE(iorq->mode) != XY_SUB_FREE) {
		if (tsleep(iorq, PRIBIO, "xyc_cmd", 0))
                                return(XY_ERR_FAIL);
		goto start;
	}

	if (XY_STATE(iorq->mode) != XY_SUB_FREE) {
		DELAY(1000000);		/* XY_SUB_POLL: steal the iorq */
		iorq->mode = XY_SUB_FREE;
		printf("%s: stole control iopb\n", xycsc->sc_dev.dv_xname);
	}

	/* init iorq/iopb */

	xyc_rqinit(iorq, xycsc,
	    (unit == XYC_NOUNIT) ? NULL : xycsc->sc_drives[unit],
	    fullmode, block, scnt, dptr, NULL);

	/* load IOPB from iorq */

	xyc_rqtopb(iorq, iopb, cmd, subfn);

	/* submit it for processing */

	xyc_submit_iorq(xycsc, iorq, fullmode);	/* error code will be in iorq */

	return(XY_ERR_AOK);
}

/*
 * xyc_startbuf
 * start a buffer for running
 */

int
xyc_startbuf(xycsc, xysc, bp)
	struct xyc_softc *xycsc;
	struct xy_softc *xysc;
	struct buf *bp;

{
	int     partno;
	struct xy_iorq *iorq;
	struct xy_iopb *iopb;
	daddr_t  block;
	caddr_t dbuf;

	iorq = xysc->xyrq;
	iopb = iorq->iopb;

	/* get buf */

	if (bp == NULL)
		panic("xyc_startbuf null buf");

	partno = DISKPART(bp->b_dev);
#ifdef XYC_DEBUG
	printf("xyc_startbuf: %s%c: %s block %lld\n",
	    xysc->sc_dev.dv_xname, 'a' + partno,
	    (bp->b_flags & B_READ) ? "read" : "write", (long long)bp->b_blkno);
	printf("xyc_startbuf: b_bcount %d, b_data 0x%x\n",
	    bp->b_bcount, bp->b_data);
#endif

	/*
	 * load request.  we have to calculate the correct block number based
	 * on partition info.
	 *
	 * note that iorq points to the buffer as mapped into DVMA space,
	 * where as the bp->b_data points to its non-DVMA mapping.
	 */

	block = bp->b_blkno + ((partno == RAW_PART) ? 0 :
	    DL_GETPOFFSET(&xysc->sc_dk.dk_label->d_partitions[partno]));

	dbuf = kdvma_mapin(bp->b_data, bp->b_bcount, 0);
	if (dbuf == NULL) {	/* out of DVMA space */
		printf("%s: warning: out of DVMA space\n",
			xycsc->sc_dev.dv_xname);
		return (XY_ERR_FAIL);	/* XXX: need some sort of
					 * call-back scheme here? */
	}

	/* init iorq and load iopb from it */

	xyc_rqinit(iorq, xycsc, xysc, XY_SUB_NORM | XY_MODE_VERBO, block,
	    bp->b_bcount / XYFM_BPS, dbuf, bp);

	xyc_rqtopb(iorq, iopb, (bp->b_flags & B_READ) ? XYCMD_RD : XYCMD_WR, 0);

	/* Instrumentation. */
	disk_busy(&xysc->sc_dk);

	return (XY_ERR_AOK);
}

/*
 * xyc_submit_iorq: submit an iorq for processing.  returns XY_ERR_AOK
 * if ok.  if it fail returns an error code.  type is XY_SUB_*.
 *
 * note: caller frees iorq in all cases except NORM
 *
 * return value:
 *   NORM: XY_AOK (req pending), XY_FAIL (couldn't submit request)
 *   WAIT: XY_AOK (success), <error-code> (failed)
 *   POLL: <same as WAIT>
 *   NOQ : <same as NORM>
 *
 * there are three sources for i/o requests:
 * [1] xystrategy: normal block I/O, using "struct buf" system.
 * [2] autoconfig/crash dump: these are polled I/O requests, no interrupts.
 * [3] open/ioctl: these are I/O requests done in the context of a process,
 *                 and the process should block until they are done.
 *
 * software state is stored in the iorq structure.  each iorq has an
 * iopb structure.  the hardware understands the iopb structure.
 * every command must go through an iopb.  a 450 handles one iopb at a
 * time, where as a 451 can take them in chains.  [the 450 claims it
 * can handle chains, but is appears to be buggy...]   iopb are allocated
 * in DVMA space at boot up time.  each disk gets one iopb, and the
 * controller gets one (for POLL and WAIT commands).  what happens if
 * the iopb is busy?  for i/o type [1], the buffers are queued at the
 * "buff" layer and * picked up later by the interrupt routine.  for case
 * [2] we can only be blocked if there is a WAIT type I/O request being
 * run.   since this can only happen when we are crashing, we wait a sec
 * and then steal the IOPB.  for case [3] the process can sleep
 * on the iorq free list until some iopbs are available.
 */

int
xyc_submit_iorq(xycsc, iorq, type)
	struct xyc_softc *xycsc;
	struct xy_iorq *iorq;
	int     type;

{
	struct xy_iopb *iopb;
	u_long  iopbaddr;

#ifdef XYC_DEBUG
	printf("xyc_submit_iorq(%s, addr=0x%x, type=%d)\n",
		xycsc->sc_dev.dv_xname, iorq, type);
#endif

	/* first check and see if controller is busy */
	if ((xycsc->xyc->xyc_csr & XYC_GBSY) != 0) {
#ifdef XYC_DEBUG
		printf("xyc_submit_iorq: XYC not ready (BUSY)\n");
#endif
		if (type == XY_SUB_NOQ)
			return (XY_ERR_FAIL);	/* failed */
		switch (type) {
		case XY_SUB_NORM:
			return XY_ERR_AOK;	/* success */
		case XY_SUB_WAIT:
			while (iorq->iopb->done == 0) {
				tsleep(iorq, PRIBIO, "xyiorq", 0);
			}
			return (iorq->errno);
		case XY_SUB_POLL:		/* steal controller */
			iopbaddr = xycsc->xyc->xyc_rsetup; /* RESET */
			if (xyc_unbusy(xycsc->xyc,XYC_RESETUSEC) == XY_ERR_FAIL)
				panic("xyc_submit_iorq: stuck xyc");
			printf("%s: stole controller\n",
				xycsc->sc_dev.dv_xname);
			break;
		default:
			panic("xyc_submit_iorq adding");
		}
	}

	iopb = xyc_chain(xycsc, iorq);	 /* build chain */
	if (iopb == NULL) { /* nothing doing? */
		if (type == XY_SUB_NORM || type == XY_SUB_NOQ)
			return(XY_ERR_AOK);
		panic("xyc_submit_iorq: xyc_chain failed!");
	}
	iopbaddr = (u_long) iopb - DVMA_BASE;

	XYC_GO(xycsc->xyc, iopbaddr);

	/* command now running, wrap it up */
	switch (type) {
	case XY_SUB_NORM:
	case XY_SUB_NOQ:
		return (XY_ERR_AOK);	/* success */
	case XY_SUB_WAIT:
		while (iorq->iopb->done == 0) {
			tsleep(iorq, PRIBIO, "xyiorq", 0);
		}
		return (iorq->errno);
	case XY_SUB_POLL:
		return (xyc_piodriver(xycsc, iorq));
	default:
		panic("xyc_submit_iorq wrap up");
	}
	panic("xyc_submit_iorq");
	return 0;	/* not reached */
}

/*
 * xyc_chain: build a chain.  return dvma address of first element in
 * the chain.   iorq != NULL: means we only want that item on the chain.
 */

struct xy_iopb *
xyc_chain(xycsc, iorq)

struct xyc_softc *xycsc;
struct xy_iorq *iorq;

{
  int togo, chain, hand;
  struct xy_iopb *iopb, *prev_iopb;
  bzero(xycsc->xy_chain, sizeof(xycsc->xy_chain));

  /*
   * promote control IOPB to the top
   */
  if (iorq == NULL) {
    if ((XY_STATE(xycsc->reqs[XYC_CTLIOPB].mode) == XY_SUB_POLL ||
        XY_STATE(xycsc->reqs[XYC_CTLIOPB].mode) == XY_SUB_WAIT) &&
		xycsc->iopbase[XYC_CTLIOPB].done == 0)
    iorq = &xycsc->reqs[XYC_CTLIOPB];
  }
  /*
   * special case: if iorq != NULL then we have a POLL or WAIT request.
   * we let these take priority and do them first.
   */
  if (iorq) {
    xycsc->xy_chain[0] = iorq;
    iorq->iopb->chen = 0;
    return(iorq->iopb);
  }

  /*
   * NORM case: do round robin and maybe chain (if allowed and possible)
   */

  chain = 0;
  hand = xycsc->xy_hand;
  xycsc->xy_hand = (xycsc->xy_hand + 1) % XYC_MAXIOPB;

  for (togo = XYC_MAXIOPB ; togo > 0 ; togo--, hand = (hand + 1) % XYC_MAXIOPB){

    if (XY_STATE(xycsc->reqs[hand].mode) != XY_SUB_NORM ||
		xycsc->iopbase[hand].done)
      continue;   /* not ready-for-i/o */

    xycsc->xy_chain[chain] = &xycsc->reqs[hand];
    iopb = xycsc->xy_chain[chain]->iopb;
    iopb->chen = 0;
    if (chain != 0) {   /* adding a link to a chain? */
      prev_iopb = xycsc->xy_chain[chain-1]->iopb;
      prev_iopb->chen = 1;
      prev_iopb->nxtiopb = ((u_long) iopb - DVMA_BASE) & 0xffff;
    } else {            /* head of chain */
      iorq = xycsc->xy_chain[chain];
    }
    chain++;
    if (xycsc->no_ols) break;   /* quit if chaining dis-allowed */
  }
  return(iorq ? iorq->iopb : NULL);
}

/*
 * xyc_piodriver
 *
 * programmed i/o driver.   this function takes over the computer
 * and drains off the polled i/o request.   it returns the status of the iorq
 * the caller is interesting in.
 */
int
xyc_piodriver(xycsc, iorq)
	struct xyc_softc *xycsc;
	struct xy_iorq  *iorq;

{
	int     nreset = 0;
	int     retval = 0;
	u_long  res;
#ifdef XYC_DEBUG
	printf("xyc_piodriver(%s, 0x%x)\n", xycsc->sc_dev.dv_xname, iorq);
#endif

	while (iorq->iopb->done == 0) {

		res = xyc_unbusy(xycsc->xyc, XYC_MAXTIME);

		/* we expect some progress soon */
		if (res == XY_ERR_FAIL && nreset >= 2) {
			xyc_reset(xycsc, 0, XY_RSET_ALL, XY_ERR_FAIL, 0);
#ifdef XYC_DEBUG
			printf("xyc_piodriver: timeout\n");
#endif
			return (XY_ERR_FAIL);
		}
		if (res == XY_ERR_FAIL) {
			if (xyc_reset(xycsc, 0,
				      (nreset++ == 0) ? XY_RSET_NONE : iorq,
				      XY_ERR_FAIL,
				      0) == XY_ERR_FAIL)
				return (XY_ERR_FAIL);	/* flushes all but POLL
							 * requests, resets */
			continue;
		}

		xyc_remove_iorq(xycsc);	 /* may resubmit request */

		if (iorq->iopb->done == 0)
			xyc_start(xycsc, iorq);
	}

	/* get return value */

	retval = iorq->errno;

#ifdef XYC_DEBUG
	printf("xyc_piodriver: done, retval = 0x%x (%s)\n",
	    iorq->errno, xyc_e2str(iorq->errno));
#endif

	/* start up any bufs that have queued */

	xyc_start(xycsc, NULL);

	return (retval);
}

/*
 * xyc_xyreset: reset one drive.   NOTE: assumes xyc was just reset.
 * we steal iopb[XYC_CTLIOPB] for this, but we put it back when we are done.
 */
void
xyc_xyreset(xycsc, xysc)
	struct xyc_softc *xycsc;
	struct xy_softc *xysc;

{
	struct xy_iopb tmpiopb;
	u_long  addr;
	int     del;
	bcopy(xycsc->ciopb, &tmpiopb, sizeof(tmpiopb));
	xycsc->ciopb->chen = xycsc->ciopb->done = xycsc->ciopb->errs = 0;
	xycsc->ciopb->ien = 0;
	xycsc->ciopb->com = XYCMD_RST;
	xycsc->ciopb->unit = xysc->xy_drive;
	addr = (u_long) xycsc->ciopb - DVMA_BASE;

	XYC_GO(xycsc->xyc, addr);

	del = XYC_RESETUSEC;
	while (del > 0) {
		if ((xycsc->xyc->xyc_csr & XYC_GBSY) == 0) break;
		DELAY(1);
		del--;
	}

	if (del <= 0 || xycsc->ciopb->errs) {
		printf("%s: off-line: %s\n", xycsc->sc_dev.dv_xname,
		    xyc_e2str(xycsc->ciopb->errno));
		del = xycsc->xyc->xyc_rsetup;
		if (xyc_unbusy(xycsc->xyc, XYC_RESETUSEC) == XY_ERR_FAIL)
			panic("xyc_reset");
	} else {
		xycsc->xyc->xyc_csr = XYC_IPND;	/* clear IPND */
	}
	bcopy(&tmpiopb, xycsc->ciopb, sizeof(tmpiopb));
}

/*
 * xyc_reset: reset everything: requests are marked as errors except
 * a polled request (which is resubmitted)
 */
int
xyc_reset(xycsc, quiet, blastmode, error, xysc)
	struct xyc_softc *xycsc;
	int     quiet, error;
	struct xy_iorq *blastmode;
	struct xy_softc *xysc;

{
	int     del = 0, lcv, retval = XY_ERR_AOK;

	/* soft reset hardware */

	if (!quiet)
		printf("%s: soft reset\n", xycsc->sc_dev.dv_xname);
	del = xycsc->xyc->xyc_rsetup;
	del = xyc_unbusy(xycsc->xyc, XYC_RESETUSEC);
	if (del == XY_ERR_FAIL) {
		blastmode = XY_RSET_ALL;	/* dead, flush all requests */
		retval = XY_ERR_FAIL;
	}
	if (xysc)
		xyc_xyreset(xycsc, xysc);

	/* fix queues based on "blast-mode" */

	for (lcv = 0; lcv < XYC_MAXIOPB; lcv++) {
		struct xy_iorq *iorq = &xycsc->reqs[lcv];

		if (XY_STATE(iorq->mode) != XY_SUB_POLL &&
		    XY_STATE(iorq->mode) != XY_SUB_WAIT &&
		    XY_STATE(iorq->mode) != XY_SUB_NORM)
			/* is it active? */
			continue;

		if (blastmode == XY_RSET_ALL ||
				blastmode != iorq) {
			/* failed */
			iorq->errno = error;
			xycsc->iopbase[lcv].done = xycsc->iopbase[lcv].errs = 1;
			switch (XY_STATE(iorq->mode)) {
			case XY_SUB_NORM:
			    iorq->buf->b_error = EIO;
			    iorq->buf->b_flags |= B_ERROR;
			    iorq->buf->b_resid = iorq->sectcnt * XYFM_BPS;
			    dvma_mapout((vaddr_t)iorq->dbufbase,
					(vaddr_t)iorq->buf->b_data,
					iorq->buf->b_bcount);
			    disk_unbusy(&xycsc->reqs[lcv].xy->sc_dk,
				(xycsc->reqs[lcv].buf->b_bcount -
				xycsc->reqs[lcv].buf->b_resid),
				(xycsc->reqs[lcv].buf->b_flags & B_READ));
			    biodone(iorq->buf);
			    iorq->mode = XY_SUB_FREE;
			    break;
			case XY_SUB_WAIT:
			    wakeup(iorq);
			case XY_SUB_POLL:
			    iorq->mode =
				XY_NEWSTATE(iorq->mode, XY_SUB_DONE);
			    break;
			}

		} else {

			/* resubmit, no need to do anything here */
		}
	}

	/*
	 * now, if stuff is waiting, start it.
	 * since we just reset it should go
	 */
	xyc_start(xycsc, NULL);

	return (retval);
}

/*
 * xyc_start: start waiting buffers
 */

void
xyc_start(xycsc, iorq)
	struct xyc_softc *xycsc;
	struct xy_iorq *iorq;

{
	int lcv;
	struct xy_softc *xy;

	if (iorq == NULL) {
		for (lcv = 0; lcv < XYC_MAXDEV ; lcv++) {
			if ((xy = xycsc->sc_drives[lcv]) == NULL) continue;
			if (!bufq_peek(&xy->xy_bufq)) continue;
			if (xy->xyrq->mode != XY_SUB_FREE) continue;
			xyc_startbuf(xycsc, xy, bufq_dequeue(&xy->xy_bufq));
		}
	}
	xyc_submit_iorq(xycsc, iorq, XY_SUB_NOQ);
}

/*
 * xyc_remove_iorq: remove "done" IOPB's.
 */

int
xyc_remove_iorq(xycsc)
	struct xyc_softc *xycsc;

{
	int     errno, rq, comm, errs;
	struct xyc *xyc = xycsc->xyc;
	u_long  addr;
	struct xy_iopb *iopb;
	struct xy_iorq *iorq;
	struct buf *bp;

	if (xyc->xyc_csr & XYC_DERR) {
		/*
		 * DOUBLE ERROR: should never happen under normal use. This
		 * error is so bad, you can't even tell which IOPB is bad, so
		 * we dump them all.
		 */
		errno = XY_ERR_DERR;
		printf("%s: DOUBLE ERROR!\n", xycsc->sc_dev.dv_xname);
		if (xyc_reset(xycsc, 0, XY_RSET_ALL, errno, 0) != XY_ERR_AOK) {
			printf("%s: soft reset failed!\n",
				xycsc->sc_dev.dv_xname);
			panic("xyc_remove_iorq: controller DEAD");
		}
		return (XY_ERR_AOK);
	}

	/*
	 * get iopb that is done, loop down the chain
	 */

	if (xyc->xyc_csr & XYC_ERR) {
		xyc->xyc_csr = XYC_ERR; /* clear error condition */
	}
	if (xyc->xyc_csr & XYC_IPND) {
		xyc->xyc_csr = XYC_IPND; /* clear interrupt */
	}

	for (rq = 0; rq < XYC_MAXIOPB; rq++) {
		iorq = xycsc->xy_chain[rq];
		if (iorq == NULL) break; /* done ! */
		if (iorq->mode == 0 || XY_STATE(iorq->mode) == XY_SUB_DONE)
			continue;	/* free, or done */
		iopb = iorq->iopb;
		if (iopb->done == 0)
			continue;	/* not done yet */

		comm = iopb->com;
		errs = iopb->errs;

		if (errs)
			iorq->errno = iopb->errno;
		else
			iorq->errno = 0;

		/* handle non-fatal errors */

		if (errs &&
		    xyc_error(xycsc, iorq, iopb, comm) == XY_ERR_AOK)
			continue;	/* AOK: we resubmitted it */

		/* this iorq is now done (hasn't been restarted or anything) */

		if ((iorq->mode & XY_MODE_VERBO) && iorq->lasterror)
			xyc_perror(iorq, iopb, 0);

		/* now, if read/write check to make sure we got all the data
		 * we needed. (this may not be the case if we got an error in
		 * the middle of a multisector request).   */

		if ((iorq->mode & XY_MODE_B144) != 0 && errs == 0 &&
		    (comm == XYCMD_RD || comm == XYCMD_WR)) {
			/* we just successfully processed a bad144 sector
			 * note: if we are in bad 144 mode, the pointers have
			 * been advanced already (see above) and are pointing
			 * at the bad144 sector.   to exit bad144 mode, we
			 * must advance the pointers 1 sector and issue a new
			 * request if there are still sectors left to process
			 *
			 */
			XYC_ADVANCE(iorq, 1);	/* advance 1 sector */

			/* exit b144 mode */
			iorq->mode = iorq->mode & (~XY_MODE_B144);

			if (iorq->sectcnt) {	/* more to go! */
				iorq->lasterror = iorq->errno = iopb->errno = 0;
				iopb->errs = iopb->done = 0;
				iorq->tries = 0;
				iopb->scnt = iorq->sectcnt;
				iopb->cyl = iorq->blockno /
						iorq->xy->sectpercyl;
				iopb->head =
					(iorq->blockno / iorq->xy->nhead) %
						iorq->xy->nhead;
				iopb->sect = iorq->blockno % iorq->xy->nsect;
				addr = (u_long) iorq->dbuf - DVMA_BASE;
				iopb->dataa = (addr & 0xffff);
				iopb->datar = ((addr & 0xff0000) >> 16);
				/* will resubmit at end */
				continue;
			}
		}
		/* final cleanup, totally done with this request */

		switch (XY_STATE(iorq->mode)) {
		case XY_SUB_NORM:
			bp = iorq->buf;
			if (errs) {
				bp->b_error = EIO;
				bp->b_flags |= B_ERROR;
				bp->b_resid = iorq->sectcnt * XYFM_BPS;
			} else {
				bp->b_resid = 0;	/* done */
			}
			dvma_mapout((vaddr_t) iorq->dbufbase,
				    (vaddr_t) bp->b_data,
				    bp->b_bcount);
			disk_unbusy(&iorq->xy->sc_dk,
			    (bp->b_bcount - bp->b_resid),
			    (bp->b_flags & B_READ));
			iorq->mode = XY_SUB_FREE;
			biodone(bp);
			break;
		case XY_SUB_WAIT:
			iorq->mode = XY_NEWSTATE(iorq->mode, XY_SUB_DONE);
			wakeup(iorq);
			break;
		case XY_SUB_POLL:
			iorq->mode = XY_NEWSTATE(iorq->mode, XY_SUB_DONE);
			break;
		}
	}

	return (XY_ERR_AOK);
}

/*
 * xyc_perror: print error.
 * - if still_trying is true: we got an error, retried and got a
 *   different error.  in that case lasterror is the old error,
 *   and errno is the new one.
 * - if still_trying is not true, then if we ever had an error it
 *   is in lasterror. also, if iorq->errno == 0, then we recovered
 *   from that error (otherwise iorq->errno == iorq->lasterror).
 */
void
xyc_perror(iorq, iopb, still_trying)
	struct xy_iorq *iorq;
	struct xy_iopb *iopb;
	int     still_trying;

{

	int     error = iorq->lasterror;

	printf("%s", (iorq->xy) ? iorq->xy->sc_dev.dv_xname
	    : iorq->xyc->sc_dev.dv_xname);
	if (iorq->buf)
		printf("%c: ", 'a' + DISKPART(iorq->buf->b_dev));
	if (iopb->com == XYCMD_RD || iopb->com == XYCMD_WR)
		printf("%s %d/%d/%d: ",
			(iopb->com == XYCMD_RD) ? "read" : "write",
			iopb->cyl, iopb->head, iopb->sect);
	printf("%s", xyc_e2str(error));

	if (still_trying)
		printf(" [still trying, new error=%s]", xyc_e2str(iorq->errno));
	else
		if (iorq->errno == 0)
			printf(" [recovered in %d tries]", iorq->tries);

	printf("\n");
}

/*
 * xyc_error: non-fatal error encountered... recover.
 * return AOK if resubmitted, return FAIL if this iopb is done
 */
int
xyc_error(xycsc, iorq, iopb, comm)
	struct xyc_softc *xycsc;
	struct xy_iorq *iorq;
	struct xy_iopb *iopb;
	int     comm;

{
	int     errno = iorq->errno;
	int     erract = xyc_entoact(errno);
	int     oldmode, advance, i;
	u_long  addr;

	if (erract == XY_ERA_RSET) {	/* some errors require a reset */
		oldmode = iorq->mode;
		iorq->mode = XY_SUB_DONE | (~XY_SUB_MASK & oldmode);
		/* make xyc_start ignore us */
		xyc_reset(xycsc, 1, XY_RSET_NONE, errno, iorq->xy);
		iorq->mode = oldmode;
	}
	/* check for read/write to a sector in bad144 table if bad: redirect
	 * request to bad144 area */

	if ((comm == XYCMD_RD || comm == XYCMD_WR) &&
	    (iorq->mode & XY_MODE_B144) == 0) {
		advance = iorq->sectcnt - iopb->scnt;
		XYC_ADVANCE(iorq, advance);
		if ((i = isbad(&iorq->xy->dkb, iorq->blockno / iorq->xy->sectpercyl,
			    (iorq->blockno / iorq->xy->nsect) % iorq->xy->nhead,
			    iorq->blockno % iorq->xy->nsect)) != -1) {
			iorq->mode |= XY_MODE_B144;	/* enter bad144 mode &
							 * redirect */
			iopb->errno = iopb->done = iopb->errs = 0;
			iopb->scnt = 1;
			iopb->cyl = (iorq->xy->ncyl + iorq->xy->acyl) - 2;
			/* second to last acyl */
			i = iorq->xy->sectpercyl - 1 - i;	/* follow bad144
								 * standard */
			iopb->head = i % iorq->xy->nhead;
			iopb->sect = i / iorq->xy->nhead;

			addr = (u_long) iorq->dbuf - DVMA_BASE;
			iopb->dataa = (addr & 0xffff);
			iopb->datar = ((addr & 0xff0000) >> 16);

			/* will resubmit when we come out of remove_iorq */
			return (XY_ERR_AOK);	/* recovered! */
		}
	}

	/*
	 * it isn't a bad144 sector, must be real error! see if we can retry
	 * it?
	 */
	if ((iorq->mode & XY_MODE_VERBO) && iorq->lasterror)
		xyc_perror(iorq, iopb, 1);	/* inform of error state
						 * change */
	iorq->lasterror = errno;

	if ((erract == XY_ERA_RSET || erract == XY_ERA_HARD)
	    && iorq->tries < XYC_MAXTRIES) {	/* retry? */
		iorq->tries++;
		iorq->errno = iopb->errno = iopb->done = iopb->errs = 0;
		/* will resubmit at end of remove_iorq */
		return (XY_ERR_AOK);	/* recovered! */
	}

	/* failed to recover from this error */
	return (XY_ERR_FAIL);
}

/*
 * xyc_tick: make sure xy is still alive and ticking (err, kicking).
 */
void
xyc_tick(arg)
	void   *arg;

{
	struct xyc_softc *xycsc = arg;
	int     lcv, s, reset = 0;

	/* reduce ttl for each request if one goes to zero, reset xyc */
	s = splbio();
	for (lcv = 0; lcv < XYC_MAXIOPB; lcv++) {
		if (xycsc->reqs[lcv].mode == 0 ||
		    XY_STATE(xycsc->reqs[lcv].mode) == XY_SUB_DONE)
			continue;
		xycsc->reqs[lcv].ttl--;
		if (xycsc->reqs[lcv].ttl == 0) {
			reset = 1;
			break;	/* we're going to fail all requests anyway */
		}
	}
	if (reset) {
		printf("%s: watchdog timeout\n", xycsc->sc_dev.dv_xname);
		xyc_reset(xycsc, 0, XY_RSET_NONE, XY_ERR_FAIL, NULL);
	}
	splx(s);

	/* until next time */

	timeout_add(&xycsc->xyc_tick_tmo, XYC_TICKCNT);
}

/*
 * xyc_e2str: convert error code number into an error string
 */
const char *
xyc_e2str(no)
	int     no;
{
	switch (no) {
	case XY_ERR_FAIL:
		return ("Software fatal error");
	case XY_ERR_DERR:
		return ("DOUBLE ERROR");
	case XY_ERR_AOK:
		return ("Successful completion");
	case XY_ERR_IPEN:
		return("Interrupt pending");
	case XY_ERR_BCFL:
		return("Busy conflict");
	case XY_ERR_TIMO:
		return("Operation timeout");
	case XY_ERR_NHDR:
		return("Header not found");
	case XY_ERR_HARD:
		return("Hard ECC error");
	case XY_ERR_ICYL:
		return("Illegal cylinder address");
	case XY_ERR_ISEC:
		return("Illegal sector address");
	case XY_ERR_SMAL:
		return("Last sector too small");
	case XY_ERR_SACK:
		return("Slave ACK error (non-existent memory)");
	case XY_ERR_CHER:
		return("Cylinder and head/header error");
	case XY_ERR_SRTR:
		return("Auto-seek retry successful");
	case XY_ERR_WPRO:
		return("Write-protect error");
	case XY_ERR_UIMP:
		return("Unimplemented command");
	case XY_ERR_DNRY:
		return("Drive not ready");
	case XY_ERR_SZER:
		return("Sector count zero");
	case XY_ERR_DFLT:
		return("Drive faulted");
	case XY_ERR_ISSZ:
		return("Illegal sector size");
	case XY_ERR_SLTA:
		return("Self test A");
	case XY_ERR_SLTB:
		return("Self test B");
	case XY_ERR_SLTC:
		return("Self test C");
	case XY_ERR_SOFT:
		return("Soft ECC error");
	case XY_ERR_SFOK:
		return("Soft ECC error recovered");
	case XY_ERR_IHED:
		return("Illegal head");
	case XY_ERR_DSEQ:
		return("Disk sequencer error");
	case XY_ERR_SEEK:
		return("Seek error");
	default:
		return ("Unknown error");
	}
}

int
xyc_entoact(errno)

int errno;

{
  switch (errno) {
    case XY_ERR_FAIL:	case XY_ERR_DERR:	case XY_ERR_IPEN:
    case XY_ERR_BCFL:	case XY_ERR_ICYL:	case XY_ERR_ISEC:
    case XY_ERR_UIMP:	case XY_ERR_SZER:	case XY_ERR_ISSZ:
    case XY_ERR_SLTA:	case XY_ERR_SLTB:	case XY_ERR_SLTC:
    case XY_ERR_IHED:	case XY_ERR_SACK:	case XY_ERR_SMAL:

	return(XY_ERA_PROG); /* program error ! */

    case XY_ERR_TIMO:	case XY_ERR_NHDR:	case XY_ERR_HARD:
    case XY_ERR_DNRY:	case XY_ERR_CHER:	case XY_ERR_SEEK:
    case XY_ERR_SOFT:

	return(XY_ERA_HARD); /* hard error, retry */

    case XY_ERR_DFLT:	case XY_ERR_DSEQ:

	return(XY_ERA_RSET); /* hard error reset */

    case XY_ERR_SRTR:	case XY_ERR_SFOK:	case XY_ERR_AOK:

	return(XY_ERA_SOFT); /* an FYI error */

    case XY_ERR_WPRO:

	return(XY_ERA_WPRO); /* write protect */
  }

  return(XY_ERA_PROG); /* ??? */
}


code:
/*	$OpenBSD: xyreg.h,v 1.5 2014/07/11 16:35:40 jsg Exp $	*/
/*	$NetBSD: xyreg.h,v 1.3 1996/03/31 22:39:02 pk Exp $	*/

/*
 * Copyright (c) 1995 Charles D. Cranor
 * 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.
 */

/*
 * x y r e g . h
 *
 * this file contains the description of the Xylogics 450/451's hardware
 * data structures.
 *
 * author: Chuck Cranor <chuck@ccrc.wustl.edu>
 */

#define XYC_MAXDEV    2       /* max devices per controller */
#define XYC_CTLIOPB   XYC_MAXDEV /* controller's iopb */
#define XYC_RESETUSEC 1000000 /* max time for xyc reset (same as xdc?) */
#define XYC_MAXIOPB   (XYC_MAXDEV+1)
			      /* max number of iopbs that can be active */
#define XYC_MAXTIME   4*1000000 /* four seconds before we give up and reset */
#define XYC_MAXTRIES  4       /* max number of times to retry an operation */
#define XYC_INTERLEAVE 1      /* interleave (from disk label?) */
#define XYFM_BPS	0x200 /* must be 512! */

/*
 * xyc device interface
 * (lives in VME address space)   [note: bytes are swapped!]
 */

struct xyc {
  volatile u_char xyc_reloc_hi;        /* iopb relocation (low byte) */
  volatile u_char xyc_reloc_lo;        /* iopb relocation (high byte) */
  volatile u_char xyc_addr_hi;         /* iopb address (low byte) */
  volatile u_char xyc_addr_lo;         /* iopb address (high byte) */
  volatile u_char xyc_rsetup;          /* reset/update reg */
  volatile u_char xyc_csr;             /* control and status register */
};

/*
 * xyc_csr
 */

#define XYC_GBSY     0x80     /* go/busy */
#define XYC_ERR	     0x40     /* error */
#define XYC_DERR     0x20     /* double error! */
#define XYC_IPND     0x10     /* interrupt pending */
#define XYC_ADRM     0x08     /* 24-bit addressing */
#define XYC_AREQ     0x04     /* attention request */
#define XYC_AACK     0x02     /* attention ack. */
#define XYC_DRDY     0x01     /* drive ready */

/*
 * Input/Output Parameter Block (iopb)
 *
 * all controller commands are done via iopb's.   to start a command you
 * must do this:
 * [1] allocate space in DVMA space for the iopb
 * [2] fill out all the fields of the iopb
 * [3] if the controller isn't busy, start the iopb by loading the address
 *     and reloc in the xyc's registers and setting the "go" bit [done]
 * [4] controller busy: set AREQ bit, and wait for AACK bit.
 *     add iopb to the chain, and clear AREQ to resume I/O
 *
 * when the controller is done with a command it may interrupt (if you
 * ask it to) and it will set the XYC_IPND bit in the csr.   clear
 * the interrupt by writing one to this bit.
 *
 * the format of the iopb is described in section 2.4 of the manual.
 * note that it is byte-swapped on the sun.
 */

struct xy_iopb {
				 /* section 2.4.2: byte 1 */
  volatile u_char resv1:1;	 /* reserved */
  volatile u_char iei:1;	 /* interrupt on each IOPB done */
  volatile u_char ierr:1;	 /* interrupt on error (no effect on 450) */
  volatile u_char hdp:1;	 /* hold dual port drive */
  volatile u_char asr:1;	 /* autoseek retry */
  volatile u_char eef:1;	 /* enable extended fn. (overlap seek) */
  volatile u_char ecm:2;	 /* ECC correction mode */
#define XY_ECM 2		 /* use mode 2 (see section 2.4.2) */
                                 /* section 2.4.1: byte 0 */
  volatile u_char aud:1;	 /* auto-update iopb */
  volatile u_char relo:1;	 /* enable multibus relocation (>16bit addrs)*/
  volatile u_char chen:1;        /* chain enable, "next iopb" is valid */
  volatile u_char ien:1;	 /* interrupt enable */
  volatile u_char com:4;	 /* command */
#define XYCMD_NOP 0x0            /* no-op */
#define XYCMD_WR  0x1            /* write */
#define XYCMD_RD  0x2            /* read */
#define XYCMD_WTH 0x3		 /* write track headers */
#define XYCMD_RTH 0x4		 /* read track headers */
#define XYCMD_SK  0x5            /* seek */
#define XYCMD_RST 0x6            /* drive reset */
#define XYCMD_WFM 0x7		 /* write format */
#define XYCMD_RDH 0x8		 /* read header, data, and ECC */
#define XYCMD_RDS 0x9		 /* read drive status */
#define XYCMD_WRH 0xa		 /* write header, data, and ECC */
#define XYCMD_SDS 0xb		 /* set drive size */
#define XYCMD_ST  0xc		 /* self test */
#define XYCMD_R   0xd		 /* reserved */
#define XYCMD_MBL 0xe		 /* maint. buffer load */
#define XYCMD_MBD 0xf		 /* main. buffer dump */
                                 /* section 2.4.4: byte 3 */
  volatile u_char errno;	 /* error or completion code */
                                 /* section 2.4.3: byte 2 */
  volatile u_char errs:1;        /* error summary bit */
  volatile u_char resv2:2;	 /* reserved */
  volatile u_char ctyp:3;	 /* controller type */
#define XYCT_450 1		 /* the 450 controller */
  volatile u_char resv3:1;	 /* reserved */
  volatile u_char done:1;	 /* done! */
                                 /* section 2.4.6: byte 5 */
  volatile u_char dt:2;		 /* drive type */
#define XYC_MAXDT 3		 /* largest drive type possible */
  volatile u_char resv4:4;	 /* reserved */
  volatile u_char unit:2;	 /* unit # */
                                 /* section 2.4.5: byte 4 */
  volatile u_char bw:1;		 /* byte(1)/word(0) xfer size */
  volatile u_char intlv:4;	 /* interleave factor (0=1:1, 1=2:1, etc.) */
  volatile u_char thro:3;	 /* dma throttle (0=2,1=4,2=8, etc...) */
#define XY_THRO 4		 /* 4 == 32 dma cycles */
                                 /* section 2.4.8: byte 7 */
  volatile u_char sect;		 /* sector # */
                                 /* section 2.4.7: byte 6 */
  volatile u_char head;		 /* head # */
                                 /* section 2.4.9: byte 8,9 */
  volatile u_short cyl;		 /* cyl # */
                                 /* section 2.4.10: byte a,b */
  volatile u_short scnt;	 /* sector count, also drive status */
#define xy_dr_status scnt
#define XYS_ONCL 0x80		 /* on-cylinder (active LOW) */
#define XYS_DRDY 0x40		 /* drive ready (active LOW) */
#define XYS_WRPT 0x20		 /* write protect */
#define XYS_DPB  0x10		 /* dual-port busy */
#define XYS_SKER 0x08		 /* hard seek error */
#define XYS_DFLT 0x04		 /* disk fault */
                                 /* section 2.4.11: byte c,d */
  volatile u_short dataa;	 /* data address */
                                 /* section 2.4.12: byte e,f */
  volatile u_short datar;	 /* data relocation pointer */
				 /* section 2.4.14: byte 11 */
  volatile u_char subfn;	 /* sub-function */
				 /* section 2.4.13: byte 10 */
  volatile u_char hoff;		 /* head offset for fixed/removable drives */
				 /* section 2.4.15: byte 12,13 */
  volatile u_short nxtiopb;	 /* next iopb address (same relocation) */
				 /* section 2.4.16: byte 14,15 */
  volatile u_short eccpat;	 /* ecc pattern */
				 /* section 2.4.17: byte 16,17 */
  volatile u_short eccaddr;	 /* ecc address */
};

/*
 * errors (section 2.4.4.1)
 */

/* software error codes */
#define XY_ERR_FAIL 0xff         /* general total failure */
#define XY_ERR_DERR 0xfe	 /* double error */
/* no error */
#define XY_ERR_AOK  0x00         /* success */

#define XY_ERR_IPEN 0x01	 /* interrupt pending */
#define XY_ERR_BCFL 0x03	 /* busy conflict */
#define XY_ERR_TIMO 0x04	 /* operation timeout */
#define XY_ERR_NHDR 0x05	 /* header not found */
#define XY_ERR_HARD 0x06	 /* hard ECC error */
#define XY_ERR_ICYL 0x07	 /* illegal cylinder address */
#define XY_ERR_ISEC 0x0a	 /* illegal sector address */
#define XY_ERR_SMAL 0x0d	 /* last sector too small */
#define XY_ERR_SACK 0x0e	 /* slave ACK error (non-existent memory) */
#define XY_ERR_CHER 0x12	 /* cylinder and head/header error */
#define XY_ERR_SRTR 0x13	 /* auto-seek retry successful */
#define XY_ERR_WPRO 0x14	 /* write-protect error */
#define XY_ERR_UIMP 0x15	 /* unimplemented command */
#define XY_ERR_DNRY 0x16	 /* drive not ready */
#define XY_ERR_SZER 0x17	 /* sector count zero */
#define XY_ERR_DFLT 0x18	 /* drive faulted */
#define XY_ERR_ISSZ 0x19	 /* illegal sector size */
#define XY_ERR_SLTA 0x1a	 /* self test a */
#define XY_ERR_SLTB 0x1b	 /* self test b */
#define XY_ERR_SLTC 0x1c	 /* self test c */
#define XY_ERR_SOFT 0x1e	 /* soft ECC error */
#define XY_ERR_SFOK 0x1f	 /* soft ECC error recovered */
#define XY_ERR_IHED 0x20	 /* illegal head */
#define XY_ERR_DSEQ 0x21	 /* disk sequencer error */
#define XY_ERR_SEEK 0x25	 /* seek error */

/* error actions */
#define XY_ERA_PROG 0x10	 /* program error: quit */
#define XY_ERA_SOFT 0x30         /* soft error: we recovered */
#define XY_ERA_HARD 0x40         /* hard error: retry */
#define XY_ERA_RSET 0x60         /* hard error: reset, then retry */
#define XY_ERA_WPRO 0x90         /* write protected */

license: unknown


code:
/*	$OpenBSD: xyvar.h,v 1.10 2015/01/14 21:13:46 miod Exp $	*/
/*	$NetBSD: xyvar.h,v 1.4 1996/03/31 22:39:04 pk Exp $	*/

/*
 * Copyright (c) 1995 Charles D. Cranor
 * 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.
 */

/*
 * x y v a r . h
 *
 * this file defines the software structure we use to control the
 * 450/451.
 *
 * author: Chuck Cranor <chuck@ccrc.wustl.edu>
 */

/*
 * i/o request: wrapper for hardware's iopb data structure
 */

struct xy_iorq {
  struct xy_iopb *iopb;             /* address of matching iopb */
  struct xyc_softc *xyc;            /* who we are working with */
  struct xy_softc *xy;              /* which disk */
  int ttl;                          /* time to live */
  int mode;                         /* current mode (state+other data) */
  int tries;                        /* number of times we have tried it */
  int errno;                        /* error number if we fail */
  int lasterror;		    /* last error we got */
  int blockno;                      /* starting block no for this xfer */
  int sectcnt;                      /* number of sectors in xfer */
  char *dbuf;                       /* KVA of data buffer (advances) */
  char *dbufbase;                   /* base of dbuf */
  struct buf *buf;                  /* for NORM */
};

/*
 * state
 */

#define XY_SUB_MASK 0xf0            /* mask bits for state */
#define XY_SUB_FREE 0x00            /* free */
#define XY_SUB_NORM 0x10            /* normal I/O request */
#define XY_SUB_WAIT 0x20            /* normal I/O request in the
                                             context of a process */
#define XY_SUB_POLL 0x30            /* polled mode */
#define XY_SUB_DONE 0x40            /* not active, but can't be free'd yet */
#define XY_SUB_NOQ  0x50            /* don't queue, just submit (internal) */

#define XY_STATE(X) ((X) & XY_SUB_MASK) /* extract state from mode */
#define XY_NEWSTATE(OLD, NEW) (((OLD) & ~XY_SUB_MASK) |(NEW)) /* new state */

/*
 * other mode data
 */

#define XY_MODE_VERBO 0x08          /* print error messages */
#define XY_MODE_B144  0x04          /* handling a bad144 sector */

/*
 * software timers and flags
 */

#define XYC_SUBWAITLIM 4   /* max number of "done" IOPBs there can be
				where we still allow a SUB_WAIT command */
#define XYC_TICKCNT (5*hz) /* call xyc_tick on this interval (5 sec) */
#define XYC_MAXTTL     2   /* max number of xy ticks to live */
#define XYC_NOUNIT (-1)    /* for xycmd: no unit number */

/*
 * a "xy_softc" structure contains per-disk state info.
 */

struct xy_softc {
  struct device sc_dev;            /* device struct, reqd by autoconf */
  struct disk sc_dk;               /* generic disk info */
  struct xyc_softc *parent;        /* parent */
  u_short flags;                   /* flags */
  u_short state;                   /* device state */
  int xy_drive;                    /* unit number */
  int drive_type;		   /* drive type (as per disk) */
  /* geometry */
  u_short ncyl, acyl, pcyl;        /* number of cyl's */
  u_short sectpercyl;              /* nhead*nsect */
  u_char nhead;                    /* number of heads */
  u_char nsect;                    /* number of sectors per track */
  u_char hw_spt;                   /* as above, but includes spare sectors */
  struct xy_iorq *xyrq;		   /* this disk's ioreq structure */
  void *xy_labeldata;              /* temporary sector buffer */
  struct bufq xy_bufq;		   /* queue'd I/O requests */
  struct dkbad dkb;                /* bad144 sectors */
};

/*
 * flags
 */

/*
 * state
 */

#define XY_DRIVE_UNKNOWN 0         /* never talked to it */
#define XY_DRIVE_ATTACHING 1       /* attach in progress */
#define XY_DRIVE_NOLABEL 2         /* drive on-line, no label */
#define XY_DRIVE_ONLINE  3         /* drive is on-line */

/*
 * a "xyc_softc" structure contains per-disk-controller state info,
 * including a list of active controllers.
 */

struct xyc_softc {
  struct device sc_dev;            /* device struct, reqd by autoconf */
  struct intrhand sc_ih;           /* interrupt info */

  struct xyc *xyc;                 /* vaddr of vme registers */

  struct xy_softc *sc_drives[XYC_MAXDEV];   /* drives on this controller */
  int ipl;                         /* interrupt level */
  int vector;                      /* interrupt vector */

  struct xy_iorq *reqs;            /* i/o requests */
  struct xy_iopb *iopbase;         /* iopb base addr (maps iopb->iorq) */
  struct xy_iopb *dvmaiopb;        /* iopb base in DVMA space, not kvm */

  struct xy_iorq *ciorq;	   /* controller's iorq */
  struct xy_iopb *ciopb;	   /* controller's iopb */

  int xy_hand;			   /* hand */
  struct xy_iorq *xy_chain[XYC_MAXIOPB];
				   /* current chain */
  int no_ols;			   /* disable overlap seek for stupid 450s */
  struct timeout xyc_tick_tmo;	   /* for xyc_tick() */
};

/*
 * reset blast modes
 */

#define XY_RSET_NONE (struct xy_iorq *)(-1)   /* restart all requests */
#define XY_RSET_ALL  (struct xy_iorq *)(-2)   /* don't restart anything */


code:
/*	$OpenBSD: z8530kbd.c,v 1.17 2013/05/10 16:00:08 mikeb Exp $	*/
/*	$NetBSD: z8530tty.c,v 1.77 2001/05/30 15:24:24 lukem Exp $	*/

/*-
 * Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998, 1999
 *	Charles M. Hannum.  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 Charles M. Hannum.
 * 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.
 */

/*
 * Copyright (c) 1994 Gordon W. Ross
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This software was developed by the Computer Systems Engineering group
 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
 * contributed to Berkeley.
 *
 * All advertising materials mentioning features or use of this software
 * must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Lawrence Berkeley Laboratory.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)zs.c	8.1 (Berkeley) 7/19/93
 */

/*
 * Zilog Z8530 Dual UART driver (tty interface)
 *
 * This is the "slave" driver that will be attached to
 * the "zsc" driver for plain "tty" async. serial lines.
 *
 * Credits, history:
 *
 * The original version of this code was the sparc/dev/zs.c driver
 * as distributed with the Berkeley 4.4 Lite release.  Since then,
 * Gordon Ross reorganized the code into the current parent/child
 * driver scheme, separating the Sun keyboard and mouse support
 * into independent child drivers.
 *
 * RTS/CTS flow-control support was a collaboration of:
 *	Gordon Ross <gwr@netbsd.org>,
 *	Bill Studenmund <wrstuden@loki.stanford.edu>
 *	Ian Dall <Ian.Dall@dsto.defence.gov.au>
 *
 * The driver was massively overhauled in November 1997 by Charles Hannum,
 * fixing *many* bugs, and substantially improving performance.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/device.h>
#include <sys/conf.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 <machine/autoconf.h>
#include <machine/conf.h>

#include <dev/wscons/wsconsio.h>
#include <dev/wscons/wskbdvar.h>

#include <dev/sun/sunkbdreg.h>
#include <dev/sun/sunkbdvar.h>

#include <dev/ic/z8530reg.h>
#include <machine/z8530var.h>

#include <dev/cons.h>

/*
 * How many input characters we can buffer.
 * The port-specific var.h may override this.
 * Note: must be a power of two!
 */
#ifndef	ZSKBD_RING_SIZE
#define	ZSKBD_RING_SIZE	2048
#endif

struct cfdriver zskbd_cd = {
	NULL, "zskbd", DV_TTY
};

/*
 * Make this an option variable one can patch.
 * But be warned:  this must be a power of 2!
 */
u_int zskbd_rbuf_size = ZSKBD_RING_SIZE;

/* Stop input when 3/4 of the ring is full; restart when only 1/4 is full. */
u_int zskbd_rbuf_hiwat = (ZSKBD_RING_SIZE * 1) / 4;
u_int zskbd_rbuf_lowat = (ZSKBD_RING_SIZE * 3) / 4;

struct zskbd_softc {
	struct sunkbd_softc	zst_base;

	struct	zs_chanstate *zst_cs;

	struct timeout zst_diag_ch;

	u_int zst_overflows,
	      zst_floods,
	      zst_errors;

	int zst_hwflags,	/* see z8530var.h */
	    zst_swflags;	/* TIOCFLAG_SOFTCAR, ... <ttycom.h> */

	u_int zst_r_hiwat,
	      zst_r_lowat;
	u_char *volatile zst_rbget,
	       *volatile zst_rbput;
	volatile u_int zst_rbavail;
	u_char *zst_rbuf,
	       *zst_ebuf;

	/*
	 * The transmit byte count and address are used for pseudo-DMA
	 * output in the hardware interrupt code.  PDMA can be suspended
	 * to get pending changes done; heldtbc is used for this.  It can
	 * also be stopped for ^S; this sets TS_TTSTOP in tp->t_state.
	 */
	u_char *zst_tba;		/* transmit buffer address */
	u_int zst_tbc,			/* transmit byte count */
	      zst_heldtbc;		/* held tbc while xmission stopped */

	u_char zst_tbuf[ZSKBD_RING_SIZE];
	u_char *zst_tbeg, *zst_tend, *zst_tbp;

	/* Flags to communicate with zskbd_softint() */
	volatile u_char zst_rx_flags,	/* receiver blocked */
#define	RX_TTY_BLOCKED		0x01
#define	RX_TTY_OVERFLOWED	0x02
#define	RX_IBUF_BLOCKED		0x04
#define	RX_IBUF_OVERFLOWED	0x08
#define	RX_ANY_BLOCK		0x0f
			zst_tx_busy,	/* working on an output chunk */
			zst_tx_done,	/* done with one output chunk */
			zst_tx_stopped,	/* H/W level stop (lost CTS) */
			zst_st_check,	/* got a status interrupt */
			zst_rx_ready;

	/* PPS signal on DCD, with or without inkernel clock disciplining */
	u_char  zst_ppsmask;			/* pps signal mask */
	u_char  zst_ppsassert;			/* pps leading edge */
	u_char  zst_ppsclear;			/* pps trailing edge */
};

/* Definition of the driver for autoconfig. */
static int	zskbd_match(struct device *, void *, void *);
static void	zskbd_attach(struct device *, struct device *, void *);

struct cfattach zskbd_ca = {
	sizeof(struct zskbd_softc), zskbd_match, zskbd_attach
};

struct zsops zsops_kbd;

static void zs_modem(struct zskbd_softc *, int);
static void zs_hwiflow(struct zskbd_softc *);
static void zs_maskintr(struct zskbd_softc *);

/* Low-level routines. */
static void zskbd_rxint(struct zs_chanstate *);
static void zskbd_stint(struct zs_chanstate *, int);
static void zskbd_txint(struct zs_chanstate *);
static void zskbd_softint(struct zs_chanstate *);
static void zskbd_diag(void *);

int zskbd_init(struct zskbd_softc *);
void zskbd_putc(struct zskbd_softc *, u_int8_t);
void zskbd_raw(struct zskbd_softc *, u_int8_t);

/* wskbd glue */
void zskbd_cngetc(void *, u_int *, int *);
void zskbd_cnpollc(void *, int);

void zsstart_tx(struct zskbd_softc *);
int zsenqueue_tx(void *, u_int8_t *, u_int);

struct wskbd_consops zskbd_consops = {
	zskbd_cngetc,
	zskbd_cnpollc
};

#define	ZSKBDUNIT(x)	(minor(x) & 0x7ffff)

/*
 * zskbd_match: how is this zs channel configured?
 */
int
zskbd_match(parent, vcf, aux)
	struct device *parent;
	void *vcf;
	void   *aux;
{
	struct cfdata *cf = vcf;
	struct zsc_attach_args *args = aux;
	int ret;

	/* If we're not looking for a keyboard, just exit */
	if (strcmp(args->type, "keyboard") != 0)
		return (0);

	ret = 10;

	/* Exact match is better than wildcard. */
	if (cf->cf_loc[ZSCCF_CHANNEL] == args->channel)
		ret += 2;

	/* This driver accepts wildcard. */
	if (cf->cf_loc[ZSCCF_CHANNEL] == ZSCCF_CHANNEL_DEFAULT)
		ret += 1;

	return (ret);
}

void
zskbd_attach(parent, self, aux)
	struct device *parent, *self;
	void   *aux;

{
	struct zsc_softc *zsc = (void *)parent;
	struct zskbd_softc *zst = (void *)self;
	struct sunkbd_softc *ss = (void *)self;
	struct cfdata *cf = self->dv_cfdata;
	struct zsc_attach_args *args = aux;
	struct wskbddev_attach_args a;
	struct zs_chanstate *cs;
	int channel, s, tty_unit, console = 0;
	dev_t dev;

	ss->sc_sendcmd = zsenqueue_tx;
	timeout_set(&ss->sc_bellto, sunkbd_bellstop, zst);

	timeout_set(&zst->zst_diag_ch, zskbd_diag, zst);

	zst->zst_tbp = zst->zst_tba = zst->zst_tbeg = zst->zst_tbuf;
	zst->zst_tend = zst->zst_tbeg + ZSKBD_RING_SIZE;

	tty_unit = ss->sc_dev.dv_unit;
	channel = args->channel;
	cs = zsc->zsc_cs[channel];
	cs->cs_private = zst;
	cs->cs_ops = &zsops_kbd;

	zst->zst_cs = cs;
	zst->zst_swflags = cf->cf_flags;	/* softcar, etc. */
	zst->zst_hwflags = args->hwflags;
	dev = makedev(zs_major, tty_unit);

	if (zst->zst_swflags)
		printf(", flags 0x%x", zst->zst_swflags);

	/*
	 * Check whether we serve as a console device.
	 * XXX - split console input/output channels aren't
	 *	 supported yet on /dev/console
	 */
	if ((zst->zst_hwflags & ZS_HWFLAG_CONSOLE_INPUT) != 0) {
		if ((args->hwflags & ZS_HWFLAG_USE_CONSDEV) != 0) {
			args->consdev->cn_dev = dev;
			cn_tab->cn_pollc = wskbd_cnpollc;
			cn_tab->cn_getc = wskbd_cngetc;
		}
		cn_tab->cn_dev = dev;
		console = 1;
	}

	zst->zst_rbuf = malloc(zskbd_rbuf_size << 1, M_DEVBUF, M_WAITOK);
	zst->zst_ebuf = zst->zst_rbuf + (zskbd_rbuf_size << 1);
	/* Disable the high water mark. */
	zst->zst_r_hiwat = 0;
	zst->zst_r_lowat = 0;
	zst->zst_rbget = zst->zst_rbput = zst->zst_rbuf;
	zst->zst_rbavail = zskbd_rbuf_size;

	/* if there are no enable/disable functions, assume the device
	   is always enabled */
	if (!cs->enable)
		cs->enabled = 1;

	/*
	 * Hardware init
	 */
	if (ISSET(zst->zst_hwflags, ZS_HWFLAG_CONSOLE)) {
		/* Call zsparam similar to open. */

		/* Wait a while for previous console output to complete */
		DELAY(10000);
	} else if (!ISSET(zst->zst_hwflags, ZS_HWFLAG_NORESET)) {
		/* Not the console; may need reset. */
		int reset;

		reset = (channel == 0) ? ZSWR9_A_RESET : ZSWR9_B_RESET;
		s = splzs();
		zs_write_reg(cs, 9, reset);
		splx(s);
	}

	/*
	 * Probe for a keyboard.
	 * If one is found, turn on receiver and status interrupts.
	 * We defer the actual write of the register to zsparam(),
	 * but we must make sure status interrupts are turned on by
	 * the time zsparam() reads the initial rr0 state.
	 */
	if (zskbd_init(zst)) {
		SET(cs->cs_preg[1], ZSWR1_RIE | ZSWR1_SIE);
		zs_write_reg(cs, 1, cs->cs_creg[1]);

		/* Make sure DTR is on now. */
		s = splzs();
		zs_modem(zst, 1);
		splx(s);
	} else {
		/* Will raise DTR in open. */
		s = splzs();
		zs_modem(zst, 0);
		splx(s);

		return;
	}

	ss->sc_click = 0;
#if defined(SUN4C) || defined(SUN4D) || defined(SUN4E) || defined(SUN4M)
	if (!CPU_ISSUN4) {
		char *cp = getpropstring(optionsnode, "keyboard-click?");

		if (cp != NULL && strcmp(cp, "true") == 0)
			ss->sc_click = 1;
	}
#endif
	sunkbd_setclick(ss, ss->sc_click);

	a.console = console;
	if (ISTYPE5(ss->sc_layout)) {
		printf(": keyboard, type 5, layout 0x%x", ss->sc_layout);
		a.keymap = &sunkbd5_keymapdata;
#ifndef	SUNKBD5_LAYOUT
		if (ss->sc_layout < MAXSUNLAYOUT &&
		    sunkbd_layouts[ss->sc_layout] != -1)
			sunkbd5_keymapdata.layout =
			    sunkbd_layouts[ss->sc_layout];
#endif
	} else {
		printf(": keyboard, type %d", ss->sc_id);
		if (ss->sc_id >= KB_SUN4)
			printf(", layout 0x%x", ss->sc_layout);
		a.keymap = &sunkbd_keymapdata;
#ifndef	SUNKBD_LAYOUT
		if (ss->sc_layout < MAXSUNLAYOUT &&
		    sunkbd_layouts[ss->sc_layout] != -1)
			sunkbd_keymapdata.layout =
			    sunkbd_layouts[ss->sc_layout];
#endif
	}
	a.accessops = &sunkbd_accessops;
	a.accesscookie = zst;

	printf("\n");

	if (console)
		wskbd_cnattach(&zskbd_consops, zst, a.keymap);

	sunkbd_attach(ss, &a);
}

int
zskbd_init(zst)
	struct zskbd_softc *zst;
{
	struct sunkbd_softc *ss = (void *)zst;
	struct zs_chanstate *cs = zst->zst_cs;
	int s, tries;
	u_int8_t v3, v4, v5, rr0;

	/* setup for 1200n81 */
	if (zs_set_speed(cs, 1200)) {			/* set 1200bps */
		printf(": failed to set baudrate\n");
		return 0;
	}
	if (zs_set_modes(cs, CS8 | CLOCAL)) {
		printf(": failed to set modes\n");
		return 0;
	}

	s = splzs();

	zs_maskintr(zst);

	v3 = cs->cs_preg[3];				/* set 8 bit chars */
	v5 = cs->cs_preg[5];
	CLR(v3, ZSWR3_RXSIZE);
	CLR(v5, ZSWR5_TXSIZE);
	SET(v3, ZSWR3_RX_8);
	SET(v5, ZSWR5_TX_8);
	cs->cs_preg[3] = v3;
	cs->cs_preg[5] = v5;

	v4 = cs->cs_preg[4];				/* no parity 1 stop */
	CLR(v4, ZSWR4_SBMASK | ZSWR4_PARMASK);
	SET(v4, ZSWR4_ONESB | ZSWR4_EVENP);
	cs->cs_preg[4] = v4;

	if (!cs->cs_heldchange) {
		if (zst->zst_tx_busy) {
			zst->zst_heldtbc = zst->zst_tbc;
			zst->zst_tbc = 0;
			cs->cs_heldchange = 1;
		} else
			zs_loadchannelregs(cs);
	}

	/*
	 * Hardware flow control is disabled, turn off the buffer water
	 * marks and unblock any soft flow control state.  Otherwise, enable
	 * the water marks.
	 */
	zst->zst_r_hiwat = 0;
	zst->zst_r_lowat = 0;
	if (ISSET(zst->zst_rx_flags, RX_TTY_OVERFLOWED)) {
		CLR(zst->zst_rx_flags, RX_TTY_OVERFLOWED);
		zst->zst_rx_ready = 1;
		cs->cs_softreq = 1;
	}
	if (ISSET(zst->zst_rx_flags, RX_TTY_BLOCKED|RX_IBUF_BLOCKED)) {
		CLR(zst->zst_rx_flags, RX_TTY_BLOCKED|RX_IBUF_BLOCKED);
		zs_hwiflow(zst);
	}

	/*
	 * Force a recheck of the hardware carrier and flow control status,
	 * since we may have changed which bits we're looking at.
	 */
	zskbd_stint(cs, 1);

	splx(s);

	/*
	 * Hardware flow control is disabled, unblock any hard flow control
	 * state.
	 */
	if (zst->zst_tx_stopped) {
		zst->zst_tx_stopped = 0;
		zsstart_tx(zst);
	}

	zskbd_softint(cs);

	/* Ok, start the reset sequence... */

	s = splhigh();

	for (tries = 5; tries != 0; tries--) {
		int ltries;

		ss->sc_leds = 0;
		ss->sc_layout = -1;

		/* Send reset request */
		zskbd_putc(zst, SKBD_CMD_RESET);

		ltries = 1000;
		while (--ltries > 0) {
			rr0 = *cs->cs_reg_csr;
			if (rr0 & ZSRR0_RX_READY) {
				sunkbd_raw(ss, *cs->cs_reg_data);
				if (ss->sc_kbdstate == SKBD_STATE_RESET)
					break;
			}
			DELAY(1000);
		}
		if (ltries == 0)
			continue;

		/* Wait for reset to finish. */
		ltries = 1000;
		while (--ltries > 0) {
			rr0 = *cs->cs_reg_csr;
			if (rr0 & ZSRR0_RX_READY) {
				sunkbd_raw(ss, *cs->cs_reg_data);
				if (ss->sc_kbdstate == SKBD_STATE_GETKEY)
					break;
			}
			DELAY(1000);
		}
		if (ltries == 0)
			continue;

		/* Send layout request */
		if (ss->sc_id == KB_SUN4) {
			/* Some Sun<=>PS/2 converters need some delay here */
			DELAY(5000);

			zskbd_putc(zst, SKBD_CMD_LAYOUT);

			ltries = 1000;
			while (--ltries > 0) {
				rr0 = *cs->cs_reg_csr;
				if (rr0 & ZSRR0_RX_READY) {
					sunkbd_raw(ss, *cs->cs_reg_data);
					if (ss->sc_layout != -1)
						break;
				}
				DELAY(1000);
			}
			if (ltries == 0)
				continue;
			break;
		} else {
			ss->sc_layout = 0;
			break;
		}
	}
	if (tries == 0)
		printf(": no keyboard\n");
	splx(s);

	return tries;
}

void
zskbd_putc(zst, c)
	struct zskbd_softc *zst;
	u_int8_t c;
{
	u_int8_t rr0;
	int s;

	s = splhigh();
	do {
		rr0 = *zst->zst_cs->cs_reg_csr;
	} while ((rr0 & ZSRR0_TX_READY) == 0);
	*zst->zst_cs->cs_reg_data = c;
	delay(2);
	splx(s);
}

int
zsenqueue_tx(v, str, len)
	void *v;
	u_int8_t *str;
	u_int len;
{
	struct zskbd_softc *zst = v;
	int s;
	u_int i;

	s = splzs();
	if (zst->zst_tbc + len > ZSKBD_RING_SIZE)
		return (-1);
	zst->zst_tbc += len;
	for (i = 0; i < len; i++) {
		*zst->zst_tbp = str[i];
		if (++zst->zst_tbp == zst->zst_tend)
			zst->zst_tbp = zst->zst_tbeg;
	}
	splx(s);
	zsstart_tx(zst);
	return (0);
}

void
zsstart_tx(zst)
	struct zskbd_softc *zst;
{
	struct zs_chanstate *cs = zst->zst_cs;
	int s, s1;

	s = spltty();

	if (zst->zst_tx_stopped)
		goto out;
	if (zst->zst_tbc == 0)
		goto out;

	s1 = splzs();

	zst->zst_tx_busy = 1;

	if (!ISSET(cs->cs_preg[1], ZSWR1_TIE)) {
		SET(cs->cs_preg[1], ZSWR1_TIE);
		cs->cs_creg[1] = cs->cs_preg[1];
		zs_write_reg(cs, 1, cs->cs_creg[1]);
	}

	zs_write_data(cs, *zst->zst_tba);

	zst->zst_tbc--;
	if (++zst->zst_tba == zst->zst_tend)
		zst->zst_tba = zst->zst_tbeg;

	splx(s1);

out:
	splx(s);
}

/*
 * Compute interrupt enable bits and set in the pending bits. Called both
 * in zsparam() and when PPS (pulse per second timing) state changes.
 * Must be called at splzs().
 */
static void
zs_maskintr(zst)
	struct zskbd_softc *zst;
{
	struct zs_chanstate *cs = zst->zst_cs;
	int tmp15;

	cs->cs_rr0_mask = cs->cs_rr0_cts | cs->cs_rr0_dcd;
	if (zst->zst_ppsmask != 0)
		cs->cs_rr0_mask |= cs->cs_rr0_pps;
	tmp15 = cs->cs_preg[15];
	if (ISSET(cs->cs_rr0_mask, ZSRR0_DCD))
		SET(tmp15, ZSWR15_DCD_IE);
	else
		CLR(tmp15, ZSWR15_DCD_IE);
	if (ISSET(cs->cs_rr0_mask, ZSRR0_CTS))
		SET(tmp15, ZSWR15_CTS_IE);
	else
		CLR(tmp15, ZSWR15_CTS_IE);
	cs->cs_preg[15] = tmp15;
}

/*
 * Raise or lower modem control (DTR/RTS) signals.  If a character is
 * in transmission, the change is deferred.
 */
static void
zs_modem(zst, onoff)
	struct zskbd_softc *zst;
	int onoff;
{
	struct zs_chanstate *cs = zst->zst_cs;

	if (cs->cs_wr5_dtr == 0)
		return;

	if (onoff)
		SET(cs->cs_preg[5], cs->cs_wr5_dtr);
	else
		CLR(cs->cs_preg[5], cs->cs_wr5_dtr);

	if (!cs->cs_heldchange) {
		if (zst->zst_tx_busy) {
			zst->zst_heldtbc = zst->zst_tbc;
			zst->zst_tbc = 0;
			cs->cs_heldchange = 1;
		} else
			zs_loadchannelregs(cs);
	}
}

/*
 * Internal version of zshwiflow
 * called at splzs
 */
static void
zs_hwiflow(zst)
	struct zskbd_softc *zst;
{
	struct zs_chanstate *cs = zst->zst_cs;

	if (cs->cs_wr5_rts == 0)
		return;

	if (ISSET(zst->zst_rx_flags, RX_ANY_BLOCK)) {
		CLR(cs->cs_preg[5], cs->cs_wr5_rts);
		CLR(cs->cs_creg[5], cs->cs_wr5_rts);
	} else {
		SET(cs->cs_preg[5], cs->cs_wr5_rts);
		SET(cs->cs_creg[5], cs->cs_wr5_rts);
	}
	zs_write_reg(cs, 5, cs->cs_creg[5]);
}

/****************************************************************
 * Interface to the lower layer (zscc)
 ****************************************************************/

#define	integrate
integrate void zskbd_rxsoft(struct zskbd_softc *);
integrate void zskbd_txsoft(struct zskbd_softc *);
integrate void zskbd_stsoft(struct zskbd_softc *);
/*
 * receiver ready interrupt.
 * called at splzs
 */
static void
zskbd_rxint(cs)
	struct zs_chanstate *cs;
{
	struct zskbd_softc *zst = cs->cs_private;
	u_char *put, *end;
	u_int cc;
	u_char rr0, rr1, c;

	end = zst->zst_ebuf;
	put = zst->zst_rbput;
	cc = zst->zst_rbavail;

	while (cc > 0) {
		/*
		 * First read the status, because reading the received char
		 * destroys the status of this char.
		 */
		rr1 = zs_read_reg(cs, 1);
		c = zs_read_data(cs);

		if (ISSET(rr1, ZSRR1_FE | ZSRR1_DO | ZSRR1_PE)) {
			/* Clear the receive error. */
			zs_write_csr(cs, ZSWR0_RESET_ERRORS);
		}

		put[0] = c;
		put[1] = rr1;
		put += 2;
		if (put >= end)
			put = zst->zst_rbuf;
		cc--;

		rr0 = zs_read_csr(cs);
		if (!ISSET(rr0, ZSRR0_RX_READY))
			break;
	}

	/*
	 * Current string of incoming characters ended because
	 * no more data was available or we ran out of space.
	 * Schedule a receive event if any data was received.
	 * If we're out of space, turn off receive interrupts.
	 */
	zst->zst_rbput = put;
	zst->zst_rbavail = cc;
	if (!ISSET(zst->zst_rx_flags, RX_TTY_OVERFLOWED)) {
		zst->zst_rx_ready = 1;
		cs->cs_softreq = 1;
	}

	/*
	 * See if we are in danger of overflowing a buffer. If
	 * so, use hardware flow control to ease the pressure.
	 */
	if (!ISSET(zst->zst_rx_flags, RX_IBUF_BLOCKED) &&
	    cc < zst->zst_r_hiwat) {
		SET(zst->zst_rx_flags, RX_IBUF_BLOCKED);
		zs_hwiflow(zst);
	}

	/*
	 * If we're out of space, disable receive interrupts
	 * until the queue has drained a bit.
	 */
	if (!cc) {
		SET(zst->zst_rx_flags, RX_IBUF_OVERFLOWED);
		CLR(cs->cs_preg[1], ZSWR1_RIE);
		cs->cs_creg[1] = cs->cs_preg[1];
		zs_write_reg(cs, 1, cs->cs_creg[1]);
	}
}

/*
 * transmitter ready interrupt.  (splzs)
 */
static void
zskbd_txint(cs)
	struct zs_chanstate *cs;
{
	struct zskbd_softc *zst = cs->cs_private;

	/*
	 * If we've delayed a parameter change, do it now, and restart
	 * output.
	 */
	if (cs->cs_heldchange) {
		zs_loadchannelregs(cs);
		cs->cs_heldchange = 0;
		zst->zst_tbc = zst->zst_heldtbc;
		zst->zst_heldtbc = 0;
	}

	/* Output the next character in the buffer, if any. */
	if (zst->zst_tbc > 0) {
		zs_write_data(cs, *zst->zst_tba);
		zst->zst_tbc--;
		if (++zst->zst_tba == zst->zst_tend)
			zst->zst_tba = zst->zst_tbeg;
	} else {
		/* Disable transmit completion interrupts if necessary. */
		if (ISSET(cs->cs_preg[1], ZSWR1_TIE)) {
			CLR(cs->cs_preg[1], ZSWR1_TIE);
			cs->cs_creg[1] = cs->cs_preg[1];
			zs_write_reg(cs, 1, cs->cs_creg[1]);
		}
		if (zst->zst_tx_busy) {
			zst->zst_tx_busy = 0;
			zst->zst_tx_done = 1;
			cs->cs_softreq = 1;
		}
	}
}

/*
 * status change interrupt.  (splzs)
 */
static void
zskbd_stint(cs, force)
	struct zs_chanstate *cs;
	int force;
{
	struct zskbd_softc *zst = cs->cs_private;
	u_char rr0, delta;

	rr0 = zs_read_csr(cs);
	zs_write_csr(cs, ZSWR0_RESET_STATUS);

	/*
	 * Check here for console break, so that we can abort
	 * even when interrupts are locking up the machine.
	 */
	if (!force)
		delta = rr0 ^ cs->cs_rr0;
	else
		delta = cs->cs_rr0_mask;
	cs->cs_rr0 = rr0;

	if (ISSET(delta, cs->cs_rr0_mask)) {
		SET(cs->cs_rr0_delta, delta);

		/*
		 * Stop output immediately if we lose the output
		 * flow control signal or carrier detect.
		 */
		if (ISSET(~rr0, cs->cs_rr0_mask)) {
			zst->zst_tbc = 0;
			zst->zst_heldtbc = 0;
		}

		zst->zst_st_check = 1;
		cs->cs_softreq = 1;
	}
}

void
zskbd_diag(arg)
	void *arg;
{
	struct zskbd_softc *zst = arg;
	struct sunkbd_softc *ss = arg;
	int overflows, floods;
	int s;

	s = splzs();
	overflows = zst->zst_overflows;
	zst->zst_overflows = 0;
	floods = zst->zst_floods;
	zst->zst_floods = 0;
	zst->zst_errors = 0;
	splx(s);

	log(LOG_WARNING, "%s: %d silo overflow%s, %d ibuf flood%s\n",
	    ss->sc_dev.dv_xname,
	    overflows, overflows == 1 ? "" : "s",
	    floods, floods == 1 ? "" : "s");
}

integrate void
zskbd_rxsoft(zst)
	struct zskbd_softc *zst;
{
	struct sunkbd_softc *ss = (void *)zst;
	struct zs_chanstate *cs = zst->zst_cs;
	u_char *get, *end;
	u_int cc, scc;
	u_char rr1;
	int code;
	int s;
	u_int8_t cbuf[SUNKBD_MAX_INPUT_SIZE], *c;

	end = zst->zst_ebuf;
	get = zst->zst_rbget;
	scc = cc = zskbd_rbuf_size - zst->zst_rbavail;

	if (cc == zskbd_rbuf_size) {
		zst->zst_floods++;
		if (zst->zst_errors++ == 0)
			timeout_add_sec(&zst->zst_diag_ch, 60);
	}

	c = cbuf;
	while (cc) {
		code = get[0];
		rr1 = get[1];
		if (ISSET(rr1, ZSRR1_DO | ZSRR1_FE | ZSRR1_PE)) {
			if (ISSET(rr1, ZSRR1_DO)) {
				zst->zst_overflows++;
				if (zst->zst_errors++ == 0)
					timeout_add_sec(&zst->zst_diag_ch, 60);
			}
			if (ISSET(rr1, ZSRR1_FE))
				SET(code, TTY_FE);
			if (ISSET(rr1, ZSRR1_PE))
				SET(code, TTY_PE);
		}

		*c++ = code;
		if (c - cbuf == sizeof cbuf) {
			sunkbd_input(ss, cbuf, c - cbuf);
			c = cbuf;
		}

		get += 2;
		if (get >= end)
			get = zst->zst_rbuf;
		cc--;
	}
	if (c != cbuf)
		sunkbd_input(ss, cbuf, c - cbuf);

	if (cc != scc) {
		zst->zst_rbget = get;
		s = splzs();
		cc = zst->zst_rbavail += scc - cc;
		/* Buffers should be ok again, release possible block. */
		if (cc >= zst->zst_r_lowat) {
			if (ISSET(zst->zst_rx_flags, RX_IBUF_OVERFLOWED)) {
				CLR(zst->zst_rx_flags, RX_IBUF_OVERFLOWED);
				SET(cs->cs_preg[1], ZSWR1_RIE);
				cs->cs_creg[1] = cs->cs_preg[1];
				zs_write_reg(cs, 1, cs->cs_creg[1]);
			}
			if (ISSET(zst->zst_rx_flags, RX_IBUF_BLOCKED)) {
				CLR(zst->zst_rx_flags, RX_IBUF_BLOCKED);
				zs_hwiflow(zst);
			}
		}
		splx(s);
	}
}

integrate void
zskbd_txsoft(zst)
	struct zskbd_softc *zst;
{
}

integrate void
zskbd_stsoft(zst)
	struct zskbd_softc *zst;
{
	struct zs_chanstate *cs = zst->zst_cs;
	u_char rr0, delta;
	int s;

	s = splzs();
	rr0 = cs->cs_rr0;
	delta = cs->cs_rr0_delta;
	cs->cs_rr0_delta = 0;
	splx(s);

	if (ISSET(delta, cs->cs_rr0_cts)) {
		/* Block or unblock output according to flow control. */
		if (ISSET(rr0, cs->cs_rr0_cts))
			zst->zst_tx_stopped = 0;
		else
			zst->zst_tx_stopped = 1;
	}
}

/*
 * Software interrupt.  Called at zssoft
 *
 * The main job to be done here is to empty the input ring
 * by passing its contents up to the tty layer.  The ring is
 * always emptied during this operation, therefore the ring
 * must not be larger than the space after "high water" in
 * the tty layer, or the tty layer might drop our input.
 *
 * Note: an "input blockage" condition is assumed to exist if
 * EITHER the TS_TBLOCK flag or zst_rx_blocked flag is set.
 */
static void
zskbd_softint(cs)
	struct zs_chanstate *cs;
{
	struct zskbd_softc *zst = cs->cs_private;
	int s;

	s = spltty();

	if (zst->zst_rx_ready) {
		zst->zst_rx_ready = 0;
		zskbd_rxsoft(zst);
	}

	if (zst->zst_st_check) {
		zst->zst_st_check = 0;
		zskbd_stsoft(zst);
	}

	if (zst->zst_tx_done) {
		zst->zst_tx_done = 0;
		zskbd_txsoft(zst);
	}

	splx(s);
}

struct zsops zsops_kbd = {
	zskbd_rxint,	/* receive char available */
	zskbd_stint,	/* external/status */
	zskbd_txint,	/* xmit buffer empty */
	zskbd_softint,	/* process software interrupt */
};

void
zskbd_cnpollc(v, on)
	void *v;
	int on;
{
	extern int swallow_zsintrs;

	if (on)
		swallow_zsintrs++;
	else
		swallow_zsintrs--;
}

void
zskbd_cngetc(v, type, data)
	void *v;
	u_int *type;
	int *data;
{
	struct zskbd_softc *zst = v;
	int s;
	u_int8_t c, rr0;

	s = splhigh();
	do {
		rr0 = *zst->zst_cs->cs_reg_csr;
	} while ((rr0 & ZSRR0_RX_READY) == 0);

	c = *zst->zst_cs->cs_reg_data;
	splx(s);

	sunkbd_decode(c, type, data);
}