code:
/*	$OpenBSD: fd.c,v 1.90 2014/07/12 18:44:43 tedu Exp $	*/
/*	$NetBSD: fd.c,v 1.51 1997/05/24 20:16:19 pk Exp $	*/

/*-
 * Copyright (c) 2000 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Paul Kranenburg.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/*-
 * Copyright (c) 1993, 1994, 1995 Charles Hannum.
 * Copyright (c) 1990 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Don Ahn.
 *
 * Portions Copyright (c) 1993, 1994 by
 *  jc@irbs.UUCP (John Capo)
 *  vak@zebub.msk.su (Serge Vakulenko)
 *  ache@astral.msk.su (Andrew A. Chernov)
 *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
 *
 * 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.
 *
 *	@(#)fd.c	7.4 (Berkeley) 5/25/91
 */

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

#include <dev/cons.h>

#include <uvm/uvm_extern.h>

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

#include <sparc/sparc/auxioreg.h>
#include <sparc/dev/fdreg.h>
#include <sparc/dev/fdvar.h>

#define FDUNIT(dev)	((dev & 0x80) >> 7)
#define FDTYPE(dev)	((minor(dev) & 0x70) >> 4)
#define FDPART(dev)	(minor(dev) & 0x0f)

/* XXX misuse a flag to identify format operation */
#define B_FORMAT B_XXX

#ifdef FD_DEBUG
int	fdc_debug = 0;
#endif

enum fdc_state {
	DEVIDLE = 0,
	MOTORWAIT,	/*  1 */
	DOSEEK,		/*  2 */
	SEEKWAIT,	/*  3 */
	SEEKTIMEDOUT,	/*  4 */
	SEEKCOMPLETE,	/*  5 */
	DOIO,		/*  6 */
	IOCOMPLETE,	/*  7 */
	IOTIMEDOUT,	/*  8 */
	IOCLEANUPWAIT,	/*  9 */
	IOCLEANUPTIMEDOUT,/*10 */
	DORESET,	/* 11 */
	RESETCOMPLETE,	/* 12 */
	RESETTIMEDOUT,	/* 13 */
	DORECAL,	/* 14 */
	RECALWAIT,	/* 15 */
	RECALTIMEDOUT,	/* 16 */
	RECALCOMPLETE,	/* 17 */
};

/* software state, per controller */
struct fdc_softc {
	struct device	sc_dev;		/* boilerplate */
	caddr_t		sc_reg;
	struct fd_softc *sc_fd[4];	/* pointers to children */
	TAILQ_HEAD(drivehead, fd_softc) sc_drives;
	enum fdc_state	sc_state;
	int		sc_flags;
#define FDC_82077		0x01
#define FDC_NEEDHEADSETTLE	0x02
#define FDC_EIS			0x04
#define FDC_NEEDMOTORWAIT	0x08
	int		sc_errors;		/* number of retries so far */
	int		sc_overruns;		/* number of DMA overruns */
	int		sc_cfg;			/* current configuration */
	struct fdcio	sc_io;
#define sc_reg_msr	sc_io.fdcio_reg_msr
#define sc_reg_fifo	sc_io.fdcio_reg_fifo
#define sc_reg_dor	sc_io.fdcio_reg_dor
#define sc_reg_drs	sc_io.fdcio_reg_msr
#define sc_itask	sc_io.fdcio_itask
#define sc_istatus	sc_io.fdcio_istatus
#define sc_data		sc_io.fdcio_data
#define sc_tc		sc_io.fdcio_tc
#define sc_nstat	sc_io.fdcio_nstat
#define sc_status	sc_io.fdcio_status
#define	sc_hih		sc_io.fdcio_ih
#define	sc_sih		sc_io.fdcio_sih
	struct timeout	fdctimeout_to;
	struct timeout	fdcpseudointr_to;
};

#ifndef FDC_C_HANDLER
extern	struct fdcio *fdciop;
#endif

/* controller driver configuration */
int	fdcmatch(struct device *, void *, void *);
void	fdcattach(struct device *, struct device *, void *);

struct cfattach fdc_ca = {
	sizeof(struct fdc_softc), fdcmatch, fdcattach
};

struct cfdriver fdc_cd = {
	NULL, "fdc", DV_DULL
};

__inline struct fd_type *fd_dev_to_type(struct fd_softc *, dev_t);

/* The order of entries in the following table is important -- BEWARE! */
struct fd_type fd_types[] = {
	{ 18,2,36,2,0xff,0xcf,0x1b,0x6c,80,2880,1,FDC_500KBPS, "1.44MB"    }, /* 1.44MB diskette */
	{  9,2,18,2,0xff,0xdf,0x2a,0x50,80,1440,1,FDC_250KBPS, "720KB"    }, /* 3.5" 720kB diskette */
	{  9,2,18,2,0xff,0xdf,0x2a,0x50,40, 720,2,FDC_250KBPS, "360KB/x"  }, /* 360kB in 720kB drive */
	{  8,2,16,3,0xff,0xdf,0x35,0x74,77,1232,1,FDC_500KBPS, "1.2MB/NEC" } /* 1.2 MB japanese format */
};

/* software state, per disk (with up to 4 disks per ctlr) */
struct fd_softc {
	struct device	sc_dv;		/* generic device info */
	struct disk	sc_dk;		/* generic disk info */

	struct fd_type *sc_deftype;	/* default type descriptor */
	struct fd_type *sc_type;	/* current type descriptor */

	daddr_t sc_blkno;	/* starting block number */
	int sc_bcount;		/* byte count left */
	int sc_skip;		/* bytes already transferred */
	int sc_nblks;		/* number of blocks currently transferring */
	int sc_nbytes;		/* number of bytes currently transferring */

	int sc_drive;		/* physical unit number */
	int sc_flags;
#define	FD_OPEN		0x01		/* it's open */
#define	FD_MOTOR	0x02		/* motor should be on */
#define	FD_MOTOR_WAIT	0x04		/* motor coming up */
	int sc_cylin;		/* where we think the head is */
	int sc_opts;		/* user-set options */

	TAILQ_ENTRY(fd_softc) sc_drivechain;
	int sc_ops;		/* I/O ops since last switch */
	struct bufq sc_bufq;	/* pending I/O requests */
	struct buf *sc_bp;	/* current I/O */

	struct timeout fd_motor_on_to;
	struct timeout fd_motor_off_to;
};

/* floppy driver configuration */
int	fdmatch(struct device *, void *, void *);
void	fdattach(struct device *, struct device *, void *);
int	fdactivate(struct device *, int);

struct cfattach fd_ca = {
	sizeof(struct fd_softc), fdmatch, fdattach,
	NULL, fdactivate
};

struct cfdriver fd_cd = {
	NULL, "fd", DV_DISK
};

int fdgetdisklabel(dev_t, struct fd_softc *, struct disklabel *, int);
int fd_get_parms(struct fd_softc *);
void fdstrategy(struct buf *);
void fdstart(struct fd_softc *);
int fdprint(void *, const char *);

struct	fd_type *fd_nvtotype(char *, int, int);
void	fd_set_motor(struct fdc_softc *fdc);
void	fd_motor_off(void *arg);
void	fd_motor_on(void *arg);
int	fdcresult(struct fdc_softc *fdc);
int	fdc_wrfifo(struct fdc_softc *fdc, u_char x);
void	fdcstart(struct fdc_softc *fdc);
void	fdcstatus(struct fdc_softc *fdc, char *s);
void	fdc_reset(struct fdc_softc *fdc);
void	fdctimeout(void *arg);
void	fdcpseudointr(void *arg);
#ifdef FDC_C_HANDLER
int	fdc_c_hwintr(struct fdc_softc *);
#else
void	fdchwintr(void);
#endif
void	fdcswintr(void *);
int	fdcstate(struct fdc_softc *);
void	fdcretry(struct fdc_softc *fdc);
void	fdfinish(struct fd_softc *fd, struct buf *bp);
int	fdformat(dev_t, struct fd_formb *, struct proc *);
void	fd_do_eject(struct fd_softc *);
static int fdconf(struct fdc_softc *);

#define OBP_FDNAME	(CPU_ISSUN4M ? "SUNW,fdtwo" : "fd")

int
fdcmatch(parent, match, aux)
	struct device *parent;
	void *match, *aux;
{
	register struct confargs *ca = aux;
	register struct romaux *ra = &ca->ca_ra;

	/*
	 * Floppy doesn't exist on sun4 and sun4e.
	 */
	if (CPU_ISSUN4OR4E)
		return (0);

	/*
	 * Floppy controller is on mainbus on sun4c.
	 */
	if ((CPU_ISSUN4C) && (ca->ca_bustype != BUS_MAIN))
		return (0);

	/*
	 * Floppy controller is on obio on sun4m.
	 */
	if ((CPU_ISSUN4M) && (ca->ca_bustype != BUS_OBIO))
		return (0);

	/* Sun PROMs call the controller an "fd" or "SUNW,fdtwo" */
	if (strcmp(OBP_FDNAME, ra->ra_name))
		return (0);

	if (ca->ca_ra.ra_vaddr &&
	    probeget(ca->ca_ra.ra_vaddr, 1) == -1) {
		return (0);
	}

	return (1);
}

/*
 * Arguments passed between fdcattach and fdprobe.
 */
struct fdc_attach_args {
	int fa_drive;
	struct bootpath *fa_bootpath;
	struct fd_type *fa_deftype;
};

/*
 * Print the location of a disk drive (called just before attaching the
 * the drive).  If `fdc' is not NULL, the drive was found but was not
 * in the system config file; print the drive name as well.
 * Return QUIET (config_find ignores this if the device was configured) to
 * avoid printing `fdN not configured' messages.
 */
int
fdprint(aux, fdc)
	void *aux;
	const char *fdc;
{
	register struct fdc_attach_args *fa = aux;

	if (!fdc)
		printf(" drive %d", fa->fa_drive);
	return (QUIET);
}

/*
 * Configure several parameters and features on the FDC.
 * Return 0 on success.
 */
static int
fdconf(fdc)
	struct fdc_softc *fdc;
{
	int	vroom;

	if (fdc_wrfifo(fdc, NE7CMD_DUMPREG) || fdcresult(fdc) != 10)
		return (-1);

	/*
	 * dumpreg[7] seems to be a motor-off timeout; set it to whatever
	 * the PROM thinks is appropriate.
	 */
	if ((vroom = fdc->sc_status[7]) == 0)
		vroom = 0x64;

	/* Configure controller to use FIFO and Implied Seek */
	if (fdc_wrfifo(fdc, NE7CMD_CFG) != 0)
		return (-1);
	if (fdc_wrfifo(fdc, vroom) != 0)
		return (-1);
	if (fdc_wrfifo(fdc, fdc->sc_cfg) != 0)
		return (-1);
	if (fdc_wrfifo(fdc, 0) != 0)	/* PRETRK */
		return (-1);
	/* No result phase for the NE7CMD_CFG command */

	if ((fdc->sc_flags & FDC_82077) != 0) {
		/* Lock configuration across soft resets. */
		if (fdc_wrfifo(fdc, NE7CMD_LOCK | CFG_LOCK) != 0 ||
		    fdcresult(fdc) != 1) {
#ifdef FD_DEBUG
			printf("fdconf: CFGLOCK failed");
#endif
			return (-1);
		}
	}
	return (0);
#if 0
	if (fdc_wrfifo(fdc, NE7CMD_VERSION) == 0 &&
	    fdcresult(fdc) == 1 && fdc->sc_status[0] == 0x90) {
		if (fdc_debug)
			printf("[version cmd]");
	}
#endif

}

void
fdcattach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	register struct confargs *ca = aux;
	struct fdc_softc *fdc = (void *)self;
	struct fdc_attach_args fa;
	struct bootpath *bp;
	int pri;
	char code;

	if (ca->ca_ra.ra_vaddr)
		fdc->sc_reg = (caddr_t)ca->ca_ra.ra_vaddr;
	else
		fdc->sc_reg = (caddr_t)mapiodev(ca->ca_ra.ra_reg, 0,
						ca->ca_ra.ra_len);

	fdc->sc_state = DEVIDLE;
	fdc->sc_itask = FDC_ITASK_NONE;
	fdc->sc_istatus = FDC_ISTATUS_NONE;
	fdc->sc_flags |= FDC_EIS;
	TAILQ_INIT(&fdc->sc_drives);

	pri = ca->ca_ra.ra_intr[0].int_pri;
	printf(" pri %d, softpri %d: ", pri, IPL_FDSOFT);
#ifdef FDC_C_HANDLER
	fdc->sc_hih.ih_fun = (void *)fdc_c_hwintr;
	fdc->sc_hih.ih_arg = fdc;
	intr_establish(pri, &fdc->sc_hih, IPL_FD, self->dv_xname);
#else
	fdciop = &fdc->sc_io;
	fdc->sc_hih.ih_vec = pri;
	if (intr_fasttrap(pri, fdchwintr, NULL, NULL) != 0) {
		printf("unable to register fast trap handler\n");
		return;
	}
	evcount_attach(&fdc->sc_hih.ih_count, self->dv_xname,
	    &fdc->sc_hih.ih_vec);
#endif
	fdc->sc_sih = softintr_establish(IPL_FDSOFT, fdcswintr, fdc);

	/* Assume a 82077 */
	fdc->sc_reg_msr = &((struct fdreg_77 *)fdc->sc_reg)->fd_msr;
	fdc->sc_reg_fifo = &((struct fdreg_77 *)fdc->sc_reg)->fd_fifo;
	fdc->sc_reg_dor = &((struct fdreg_77 *)fdc->sc_reg)->fd_dor;

	code = '7';
	if (*fdc->sc_reg_dor == NE7_RQM) {
		/*
		 * This hack from Chris Torek: apparently DOR really
		 * addresses MSR/DRS on a 82072.
		 * We used to rely on the VERSION command to tell the
		 * difference (which did not work).
		 */
		*fdc->sc_reg_dor = FDC_250KBPS;
		if (*fdc->sc_reg_dor == NE7_RQM)
			code = '2';
	}
	if (code == '7') {
		fdc->sc_flags |= FDC_82077;
		fdc->sc_flags |= FDC_NEEDMOTORWAIT;
	} else {
		fdc->sc_reg_msr = &((struct fdreg_72 *)fdc->sc_reg)->fd_msr;
		fdc->sc_reg_fifo = &((struct fdreg_72 *)fdc->sc_reg)->fd_fifo;
		fdc->sc_reg_dor = 0;
	}

	/*
	 * Configure controller; enable FIFO, Implied seek, no POLL mode?.
	 * Note: CFG_EFIFO is active-low, initial threshold value: 8
	 */
	fdc->sc_cfg = CFG_EIS|/*CFG_EFIFO|*/CFG_POLL|(8 & CFG_THRHLD_MASK);
	if (fdconf(fdc) != 0) {
		printf("%s: no drives attached\n", fdc->sc_dev.dv_xname);
		return;
	}

	if ((fdc->sc_flags & FDC_82077) != 0) {
		/* Lock configuration across soft resets. */
		fdc_wrfifo(fdc, NE7CMD_LOCK | CFG_LOCK);
		if (fdcresult(fdc) != 1)
			printf(" CFGLOCK: unexpected response");
	}

	printf("chip 8207%c\n", code);

	/*
	 * Controller and drives are represented by one and the same
	 * Openprom node, so we can as well check for the floppy boots here.
	 */
	fa.fa_bootpath = 0;
	if ((bp = ca->ca_ra.ra_bp) && strcmp(bp->name, OBP_FDNAME) == 0) {

		switch (ca->ca_bustype) {
		case BUS_MAIN:
			/*
			 * We can get the bootpath in several different
			 * formats! The faked v1 bootpath looks like /fd@0,0.
			 * The v2 bootpath is either just /fd0, in which case
			 * `bp->val[0]' will have been set to -1, or /fd@x,y
			 * where <x,y> is the prom address specifier.
			 */
			if (((bp->val[0] == ca->ca_ra.ra_iospace) &&
			     (bp->val[1] == (int)ca->ca_ra.ra_paddr)) ||

			    ((bp->val[0] == -1) &&	/* v2: /fd0 */
			     (bp->val[1] == 0)) ||

			    ((bp->val[0] == 0) &&	/* v1: /fd@0,0 */
			     (bp->val[1] == 0))
			   )
				fa.fa_bootpath = bp;
			break;

		case BUS_OBIO:
			/*
			 * floppy controller on obio (such as on the sun4m),
			 * e.g.: `/obio0/SUNW,fdtwo@0,700000'.
			 * We use "slot, offset" to determine if this is the
			 * right one.
			 */
			if ((bp->val[0] == ca->ca_slot) &&
			    (bp->val[1] == ca->ca_offset))
				fa.fa_bootpath = bp;
			break;
		}

	}

	timeout_set(&fdc->fdctimeout_to, fdctimeout, fdc);
	timeout_set(&fdc->fdcpseudointr_to, fdcpseudointr, fdc);

	/*
	 * physical limit: four drives per controller, but the dev_t
	 * only has room for 2
	 */
	for (fa.fa_drive = 0; fa.fa_drive < 2; fa.fa_drive++) {
		fa.fa_deftype = NULL;		/* unknown */
		fa.fa_deftype = &fd_types[0];	/* XXX */
		(void)config_found(self, (void *)&fa, fdprint);
	}

	bootpath_store(1, NULL);
}

int
fdmatch(parent, match, aux)
	struct device *parent;
	void *match, *aux;
{
	struct fdc_softc *fdc = (void *)parent;
	struct fdc_attach_args *fa = aux;
	int drive = fa->fa_drive;
	int n, ok;

	if (drive > 0)
		/* XXX - for now, punt on more than one drive */
		return (0);

	if ((fdc->sc_flags & FDC_82077) != 0) {
		/* select drive and turn on motor */
		*fdc->sc_reg_dor = drive | FDO_FRST | FDO_MOEN(drive);
		/* wait for motor to spin up */
		delay(250000);
	} else {
		auxregbisc(AUXIO4C_FDS, 0);
	}

	fdc->sc_nstat = 0;
	fdc_wrfifo(fdc, NE7CMD_RECAL);
	fdc_wrfifo(fdc, drive);

	/* wait for recalibrate */
	for (n = 0; n < 10000; n++) {
		delay(1000);
		if ((*fdc->sc_reg_msr & (NE7_RQM|NE7_DIO|NE7_CB)) == NE7_RQM) {
			/* wait a bit longer till device *really* is ready */
			delay(100000);
			if (fdc_wrfifo(fdc, NE7CMD_SENSEI))
				break;
			if (fdcresult(fdc) == 1 && fdc->sc_status[0] == 0x80)
				/*
				 * Got `invalid command'; we interpret it
				 * to mean that the re-calibrate hasn't in
				 * fact finished yet
				 */
				continue;
			break;
		}
	}
	n = fdc->sc_nstat;
#ifdef FD_DEBUG
	if (fdc_debug) {
		int i;
		printf("fdprobe: %d stati:", n);
		for (i = 0; i < n; i++)
			printf(" 0x%x", fdc->sc_status[i]);
		printf("\n");
	}
#endif
	ok = (n == 2 && (fdc->sc_status[0] & 0xf8) == 0x20) ? 1 : 0;

	/* turn off motor */
	if ((fdc->sc_flags & FDC_82077) != 0) {
		/* deselect drive and turn motor off */
		*fdc->sc_reg_dor = FDO_FRST | FDO_DS;
	} else {
		auxregbisc(0, AUXIO4C_FDS);
	}

	return (ok);
}

/*
 * Controller is working, and drive responded.  Attach it.
 */
void
fdattach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct fdc_softc *fdc = (void *)parent;
	struct fd_softc *fd = (void *)self;
	struct fdc_attach_args *fa = aux;
	struct fd_type *type = fa->fa_deftype;
	int drive = fa->fa_drive;

	/* Setup timeouts */
	timeout_set(&fd->fd_motor_on_to, fd_motor_on, fd);
	timeout_set(&fd->fd_motor_off_to, fd_motor_off, fd);

	/* XXX Allow `flags' to override device type? */

	if (type)
		printf(": %s %d cyl, %d head, %d sec\n", type->name,
		    type->tracks, type->heads, type->sectrac);
	else
		printf(": density unknown\n");

	fd->sc_cylin = -1;
	fd->sc_drive = drive;
	fd->sc_deftype = type;
	fdc->sc_fd[drive] = fd;

	fdc_wrfifo(fdc, NE7CMD_SPECIFY);
	fdc_wrfifo(fdc, type->steprate);
	/* XXX head load time == 6ms */
	fdc_wrfifo(fdc, 6 | NE7_SPECIFY_NODMA);

	/*
	 * Initialize and attach the disk structure.
	 */
	fd->sc_dk.dk_flags = DKF_NOLABELREAD;
	fd->sc_dk.dk_name = fd->sc_dv.dv_xname;
	bufq_init(&fd->sc_bufq, BUFQ_DEFAULT);
	disk_attach(&fd->sc_dv, &fd->sc_dk);

	/*
	 * We're told if we're the boot device in fdcattach().
	 */
	if (fa->fa_bootpath)
		fa->fa_bootpath->dev = &fd->sc_dv;
}

int
fdactivate(struct device *self, int act)
{
	struct fd_softc *sc = (struct fd_softc *)self;
	int ret = 0;

	switch (act) {
	case DVACT_POWERDOWN:
		/* Make sure the drive motor gets turned off at shutdown time. */
		fd_motor_off(sc);
		break;
	}

	return (ret);
}

__inline struct fd_type *
fd_dev_to_type(fd, dev)
	struct fd_softc *fd;
	dev_t dev;
{
	int type = FDTYPE(dev);

	if (type > (sizeof(fd_types) / sizeof(fd_types[0])))
		return (NULL);
	return (type ? &fd_types[type - 1] : fd->sc_deftype);
}

void
fdstrategy(bp)
	register struct buf *bp;	/* IO operation to perform */
{
	struct fd_softc *fd;
	int unit = FDUNIT(bp->b_dev);
	int sz;
 	int s;

	/* Valid unit, controller, and request? */
	if (unit >= fd_cd.cd_ndevs ||
	    (fd = fd_cd.cd_devs[unit]) == 0 ||
	    bp->b_blkno < 0 ||
	    (((bp->b_bcount % FD_BSIZE(fd)) != 0 ||
	      (bp->b_blkno * DEV_BSIZE) % FD_BSIZE(fd) != 0) &&
	     (bp->b_flags & B_FORMAT) == 0)) {
		bp->b_error = EINVAL;
		goto bad;
	}

	/* If it's a null transfer, return immediately. */
	if (bp->b_bcount == 0)
		goto done;

	bp->b_resid = bp->b_bcount;
	sz = howmany(bp->b_bcount, DEV_BSIZE);

	if (bp->b_blkno + sz > (fd->sc_type->size * DEV_BSIZE) / FD_BSIZE(fd)) {
		sz = (fd->sc_type->size * DEV_BSIZE) / FD_BSIZE(fd)
		    - bp->b_blkno;
		if (sz == 0) {
			/* If exactly at end of disk, return EOF. */
			goto done;
		}
		if (sz < 0) {
			/* If past end of disk, return EINVAL. */
			bp->b_error = EINVAL;
			goto bad;
		}
		/* Otherwise, truncate request. */
		bp->b_bcount = sz << DEV_BSHIFT;
	}

#ifdef FD_DEBUG
	if (fdc_debug > 1)
	    printf("fdstrategy: b_blkno %lld b_bcount %ld blkno %lld\n",
		(long long)bp->b_blkno, bp->b_bcount,
		(long long)fd->sc_blkno);
#endif

	/* Queue transfer */
	bufq_queue(&fd->sc_bufq, bp);

	/* Queue transfer on drive, activate drive and controller if idle. */
	s = splbio();
	timeout_del(&fd->fd_motor_off_to); /* a good idea */
	if (fd->sc_bp == NULL)
		fdstart(fd);
#ifdef DIAGNOSTIC
	else {
		struct fdc_softc *fdc = (void *)fd->sc_dv.dv_parent;
		if (fdc->sc_state == DEVIDLE) {
			printf("fdstrategy: controller inactive\n");
			fdcstart(fdc);
		}
	}
#endif
	splx(s);
	return;

bad:
	bp->b_flags |= B_ERROR;
done:
	/* Toss transfer; we're done early. */
	s = splbio();
	biodone(bp);
	splx(s);
}

void
fdstart(fd)
	struct fd_softc *fd;
{
	struct fdc_softc *fdc = (void *)fd->sc_dv.dv_parent;
	int active = !TAILQ_EMPTY(&fdc->sc_drives);

	/* Link into controller queue. */
	fd->sc_bp = bufq_dequeue(&fd->sc_bufq);
	TAILQ_INSERT_TAIL(&fdc->sc_drives, fd, sc_drivechain);

	/* If controller not already active, start it. */
	if (!active)
		fdcstart(fdc);
}

void
fdfinish(fd, bp)
	struct fd_softc *fd;
	struct buf *bp;
{
	struct fdc_softc *fdc = (void *)fd->sc_dv.dv_parent;

	fd->sc_skip = 0;
	fd->sc_bp = bufq_dequeue(&fd->sc_bufq);

	/*
	 * Move this drive to the end of the queue to give others a `fair'
	 * chance.  We only force a switch if N operations are completed while
	 * another drive is waiting to be serviced, since there is a long motor
	 * startup delay whenever we switch.
	 */
	if (TAILQ_NEXT(fd, sc_drivechain) != NULL && ++fd->sc_ops >= 8) {
		fd->sc_ops = 0;
		TAILQ_REMOVE(&fdc->sc_drives, fd, sc_drivechain);
		if (fd->sc_bp != NULL)
			TAILQ_INSERT_TAIL(&fdc->sc_drives, fd, sc_drivechain);
	}

	biodone(bp);
	/* turn off motor 5s from now */
	timeout_add_sec(&fd->fd_motor_off_to, 5);
	fdc->sc_state = DEVIDLE;
}

void
fdc_reset(fdc)
	struct fdc_softc *fdc;
{
	if (fdc->sc_flags & FDC_82077) {
		*fdc->sc_reg_dor = FDO_FDMAEN | FDO_MOEN(0);
	}

	*fdc->sc_reg_drs = DRS_RESET;
	delay(10);
	*fdc->sc_reg_drs = 0;

	if (fdc->sc_flags & FDC_82077) {
		*fdc->sc_reg_dor = FDO_FRST | FDO_FDMAEN | FDO_DS;
	}
#ifdef FD_DEBUG
	if (fdc_debug)
		printf("fdc reset\n");
#endif
}

void
fd_set_motor(fdc)
	struct fdc_softc *fdc;
{
	struct fd_softc *fd;
	u_char status;
	int n;

	if (fdc->sc_flags & FDC_82077) {
		status = FDO_FRST | FDO_FDMAEN;
		if ((fd = TAILQ_FIRST(&fdc->sc_drives)) != NULL)
			status |= fd->sc_drive;

		for (n = 0; n < 4; n++)
			if ((fd = fdc->sc_fd[n]) && (fd->sc_flags & FD_MOTOR))
				status |= FDO_MOEN(n);
		*fdc->sc_reg_dor = status;
	} else {
		for (n = 0; n < 4; n++) {
			if ((fd = fdc->sc_fd[n]) != NULL &&
			    (fd->sc_flags & FD_MOTOR) != 0) {
				auxregbisc(AUXIO4C_FDS, 0);
				return;
			}
		}
		auxregbisc(0, AUXIO4C_FDS);
	}
}

void
fd_motor_off(arg)
	void *arg;
{
	struct fd_softc *fd = arg;
	int s;

	s = splbio();
	fd->sc_flags &= ~(FD_MOTOR | FD_MOTOR_WAIT);
	fd_set_motor((struct fdc_softc *)fd->sc_dv.dv_parent);
	splx(s);
}

void
fd_motor_on(arg)
	void *arg;
{
	struct fd_softc *fd = arg;
	struct fdc_softc *fdc = (void *)fd->sc_dv.dv_parent;
	int s;

	s = splbio();
	fd->sc_flags &= ~FD_MOTOR_WAIT;
	if (fd == TAILQ_FIRST(&fdc->sc_drives) && fdc->sc_state == MOTORWAIT)
		(void) fdcstate(fdc);
	splx(s);
}

/*
 * Get status bytes off the FDC after a command has finished
 * Returns the number of status bytes read; -1 on error.
 * The return value is also stored in `sc_nstat'.
 */
int
fdcresult(fdc)
	struct fdc_softc *fdc;
{
	u_char i;
	int j, n = 0;

	for (j = 100000; j; j--) {
		i = *fdc->sc_reg_msr & (NE7_DIO | NE7_RQM | NE7_CB);
		if (i == NE7_RQM)
			return (fdc->sc_nstat = n);
		if (i == (NE7_DIO | NE7_RQM | NE7_CB)) {
			if (n >= sizeof(fdc->sc_status)) {
				log(LOG_ERR, "fdcresult: overrun\n");
				return (-1);
			}
			fdc->sc_status[n++] = *fdc->sc_reg_fifo;
		} else
			delay(1);
	}

	log(LOG_ERR, "fdcresult: timeout\n");
	return (fdc->sc_nstat = -1);
}

/*
 * Write a command byte to the FDC.
 * Returns 0 on success; -1 on failure (i.e. timeout)
 */
int
fdc_wrfifo(fdc, x)
	struct fdc_softc *fdc;
	u_char x;
{
	int i;

	for (i = 100000; i-- > 0;) {
		if ((*fdc->sc_reg_msr & (NE7_DIO|NE7_RQM)) == NE7_RQM) {
			/* The chip is ready */
			*fdc->sc_reg_fifo = x;
			return (0);
		}
		delay(1);
	}
	return (-1);
}

int
fdopen(dev, flags, fmt, p)
	dev_t dev;
	int flags, fmt;
	struct proc *p;
{
 	int unit, pmask;
	struct fd_softc *fd;
	struct fd_type *type;

	unit = FDUNIT(dev);
	if (unit >= fd_cd.cd_ndevs)
		return (ENXIO);
	fd = fd_cd.cd_devs[unit];
	if (fd == NULL)
		return (ENXIO);
	type = fd_dev_to_type(fd, dev);
	if (type == NULL)
		return (ENXIO);

	if ((fd->sc_flags & FD_OPEN) != 0 &&
	    fd->sc_type != type)
		return (EBUSY);

	fd->sc_type = type;
	fd->sc_cylin = -1;
	fd->sc_flags |= FD_OPEN;

	/*
	 * Only update the disklabel if we're not open anywhere else.
	 */
	if (fd->sc_dk.dk_openmask == 0)
		fdgetdisklabel(dev, fd, fd->sc_dk.dk_label, 0);

	pmask = (1 << FDPART(dev));

	switch (fmt) {
	case S_IFCHR:
		fd->sc_dk.dk_copenmask |= pmask;
		break;

	case S_IFBLK:
		fd->sc_dk.dk_bopenmask |= pmask;
		break;
	}
	fd->sc_dk.dk_openmask =
	    fd->sc_dk.dk_copenmask | fd->sc_dk.dk_bopenmask;

	return (0);
}

int
fdclose(dev, flags, fmt, p)
	dev_t dev;
	int flags, fmt;
	struct proc *p;
{
	struct fd_softc *fd = fd_cd.cd_devs[FDUNIT(dev)];
	int pmask = (1 << FDPART(dev));

	fd->sc_flags &= ~FD_OPEN;
	fd->sc_opts &= ~(FDOPT_NORETRY|FDOPT_SILENT);

	switch (fmt) {
	case S_IFCHR:
		fd->sc_dk.dk_copenmask &= ~pmask;
		break;

	case S_IFBLK:
		fd->sc_dk.dk_bopenmask &= ~pmask;
		break;
	}
	fd->sc_dk.dk_openmask =
	    fd->sc_dk.dk_copenmask | fd->sc_dk.dk_bopenmask;

	return (0);
}

int
fdread(dev, uio, flag)
        dev_t dev;
        struct uio *uio;
	int flag;
{

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

int
fdwrite(dev, uio, flag)
        dev_t dev;
        struct uio *uio;
	int flag;
{

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

void
fdcstart(fdc)
	struct fdc_softc *fdc;
{

#ifdef DIAGNOSTIC
	/* only got here if controller's drive queue was inactive; should
	   be in idle state */
	if (fdc->sc_state != DEVIDLE) {
		printf("fdcstart: not idle\n");
		return;
	}
#endif
	(void) fdcstate(fdc);
}

void
fdcstatus(fdc, s)
	struct fdc_softc *fdc;
	char *s;
{
	struct fd_softc *fd = TAILQ_FIRST(&fdc->sc_drives);
	int n;

	/* Just print last status */
	n = fdc->sc_nstat;

#if 0
	/*
	 * A 82072 seems to return <invalid command> on
	 * gratuitous Sense Interrupt commands.
	 */
	if (n == 0 && (fdc->sc_flags & FDC_82077) != 0) {
		fdc_wrfifo(fdc, NE7CMD_SENSEI);
		(void) fdcresult(fdc);
		n = 2;
	}
#endif

	printf("%s: %s: state %d",
	    fd ? fd->sc_dv.dv_xname : "fdc", s, fdc->sc_state);

	switch (n) {
	case 0:
		printf("\n");
		break;
	case 2:
		printf(" (st0 %b cyl %d)\n",
		    fdc->sc_status[0], NE7_ST0BITS,
		    fdc->sc_status[1]);
		break;
	case 7:
		printf(" (st0 %b st1 %b st2 %b cyl %d head %d sec %d)\n",
		    fdc->sc_status[0], NE7_ST0BITS,
		    fdc->sc_status[1], NE7_ST1BITS,
		    fdc->sc_status[2], NE7_ST2BITS,
		    fdc->sc_status[3], fdc->sc_status[4], fdc->sc_status[5]);
		break;
#ifdef DIAGNOSTIC
	default:
		printf(" fdcstatus: weird size: %d\n", n);
		break;
#endif
	}
}

void
fdctimeout(arg)
	void *arg;
{
	struct fdc_softc *fdc = arg;
	struct fd_softc *fd;
	int s;

	s = splbio();
	fd = TAILQ_FIRST(&fdc->sc_drives);
	if (fd == NULL) {
		printf("%s: timeout but no I/O pending: statu %d, istatus=%d\n",
		    fdc->sc_dev.dv_xname, fdc->sc_state, fdc->sc_istatus);
		fdc->sc_state = DEVIDLE;
		goto out;
	}

	if (fd->sc_bp != NULL)
		fdc->sc_state++;
	else
		fdc->sc_state = DEVIDLE;

	(void) fdcstate(fdc);
out:
	splx(s);
}

void
fdcpseudointr(arg)
	void *arg;
{
	struct fdc_softc *fdc = arg;
	int s;

	/* Just ensure it has the right spl. */
	s = splbio();
	(void) fdcstate(fdc);
	splx(s);
}

#ifdef FDC_C_HANDLER
/*
 * hardware interrupt entry point: must be converted to `fast'
 * (in-window) handler.
 */
int
fdc_c_hwintr(fdc)
	struct fdc_softc *fdc;
{

	switch (fdc->sc_itask) {
	case FDC_ITASK_NONE:
		return (0);
	case FDC_ITASK_SENSEI:
		if (fdc_wrfifo(fdc, NE7CMD_SENSEI) != 0 || fdcresult(fdc) == -1)
			fdc->sc_istatus = FDC_ISTATUS_ERROR;
		else
			fdc->sc_istatus = FDC_ISTATUS_DONE;
		softintr_schedule(fdc->sc_sih);
		goto done;
	case FDC_ITASK_RESULT:
		if (fdcresult(fdc) == -1)
			fdc->sc_istatus = FDC_ISTATUS_ERROR;
		else
			fdc->sc_istatus = FDC_ISTATUS_DONE;
		softintr_schedule(fdc->sc_sih);
		goto done;
	case FDC_ITASK_DMA:
		/* Proceed with pseudo-DMA below */
		break;
	default:
		printf("fdc: stray hard interrupt: itask=%d\n", fdc->sc_itask);
		fdc->sc_istatus = FDC_ISTATUS_SPURIOUS;
		softintr_schedule(fdc->sc_sih);
		goto done;
	}

	/*
	 * Pseudo DMA in progress
	 */
	for (;;) {
		register int msr;

		msr = *fdc->sc_reg_msr;

		if ((msr & NE7_RQM) == 0)
			/* That's all this round */
			break;

		if ((msr & NE7_NDM) == 0) {
			fdcresult(fdc);
			fdc->sc_istatus = FDC_ISTATUS_DONE;
			softintr_schedule(fdc->sc_sih);
#ifdef FD_DEBUG
			if (fdc_debug > 1)
				printf("fdc: overrun: tc = %d\n", fdc->sc_tc);
#endif
			break;
		}

		/* Another byte can be transferred */
		if ((msr & NE7_DIO) != 0)
			*fdc->sc_data++ = *fdc->sc_reg_fifo;
		else
			*fdc->sc_reg_fifo = *fdc->sc_data++;
		if (--fdc->sc_tc == 0) {
			fdc->sc_istatus = FDC_ISTATUS_DONE;
			FTC_FLIP;
			fdcresult(fdc);
			softintr_schedule(fdc->sc_sih);
			break;
		}
	}
done:
	return (1);
}
#endif

void
fdcswintr(void *arg)
{
	struct fdc_softc *fdc = (struct fdc_softc *)arg;
	int s;

	if (fdc->sc_istatus == FDC_ISTATUS_NONE)
		/* This (software) interrupt is not for us */
		return;

	switch (fdc->sc_istatus) {
	case FDC_ISTATUS_ERROR:
		printf("fdc: ierror status: state %d\n", fdc->sc_state);
		break;
	case FDC_ISTATUS_SPURIOUS:
		printf("fdc: spurious interrupt: state %d\n", fdc->sc_state);
		break;
	}

	s = splbio();
	fdcstate(fdc);
	splx(s);
}

int
fdcstate(fdc)
	struct fdc_softc *fdc;
{
#define	st0	fdc->sc_status[0]
#define	st1	fdc->sc_status[1]
#define	cyl	fdc->sc_status[1]
#define FDC_WRFIFO(fdc, c) \
	do { \
		if (fdc_wrfifo(fdc, (c))) { \
			goto xxx; \
		} \
	} while (0)

	struct fd_softc *fd;
	struct buf *bp;
	int read, head, sec, nblks, cylin;
	struct fd_type *type;
	struct fd_formb *finfo = NULL;

	if (fdc->sc_istatus == FDC_ISTATUS_ERROR) {
		/* Prevent loop if the reset sequence produces errors */
		if (fdc->sc_state != RESETCOMPLETE &&
		    fdc->sc_state != RECALWAIT &&
		    fdc->sc_state != RECALCOMPLETE)
			fdc->sc_state = DORESET;
	}

	/* Clear I task/status field */
	fdc->sc_istatus = FDC_ISTATUS_NONE;
	fdc->sc_itask = FDC_ITASK_NONE;

loop:
	/* Is there a drive for the controller to do a transfer with? */
	fd = TAILQ_FIRST(&fdc->sc_drives);
	if (fd == NULL) {
		fdc->sc_state = DEVIDLE;
 		return (0);
	}

	/* Is there a transfer to this drive?  If not, deactivate drive. */
	bp = fd->sc_bp;
	if (bp == NULL) {
		fd->sc_ops = 0;
		TAILQ_REMOVE(&fdc->sc_drives, fd, sc_drivechain);
		goto loop;
	}

	cylin = ((bp->b_blkno * DEV_BSIZE) + (bp->b_bcount - bp->b_resid)) /
	    (FD_BSIZE(fd) * fd->sc_type->seccyl);

	if (bp->b_flags & B_FORMAT)
		finfo = (struct fd_formb *)bp->b_data;

	switch (fdc->sc_state) {
	case DEVIDLE:
		fdc->sc_errors = 0;
		fd->sc_skip = 0;
		fd->sc_bcount = bp->b_bcount;
		fd->sc_blkno = (bp->b_blkno * DEV_BSIZE) / FD_BSIZE(fd);
		timeout_del(&fd->fd_motor_off_to);
		if ((fd->sc_flags & FD_MOTOR_WAIT) != 0) {
			fdc->sc_state = MOTORWAIT;
			return (1);
		}
		if ((fd->sc_flags & FD_MOTOR) == 0) {
			/* Turn on the motor, being careful about pairing. */
			struct fd_softc *ofd = fdc->sc_fd[fd->sc_drive ^ 1];
			if (ofd && ofd->sc_flags & FD_MOTOR) {
				timeout_del(&ofd->fd_motor_off_to);
				ofd->sc_flags &= ~(FD_MOTOR | FD_MOTOR_WAIT);
			}
			fd->sc_flags |= FD_MOTOR | FD_MOTOR_WAIT;
			fd_set_motor(fdc);
			fdc->sc_state = MOTORWAIT;
			if ((fdc->sc_flags & FDC_NEEDMOTORWAIT) != 0) { /* XXX */
				/* Allow .25s for motor to stabilize. */
				timeout_add_msec(&fd->fd_motor_on_to, 250);
			} else {
				fd->sc_flags &= ~FD_MOTOR_WAIT;
				goto loop;
			}
			return (1);
		}
		/* Make sure the right drive is selected. */
		fd_set_motor(fdc);

		/*FALLTHROUGH*/
	case DOSEEK:
	doseek:
		if ((fdc->sc_flags & FDC_EIS) &&
		    (bp->b_flags & B_FORMAT) == 0) {
			fd->sc_cylin = cylin;
			/* We use implied seek */
			goto doio;
		}

		if (fd->sc_cylin == cylin)
			goto doio;

		fd->sc_cylin = -1;
		fdc->sc_state = SEEKWAIT;
		fdc->sc_nstat = 0;

		fd->sc_dk.dk_seek++;

		disk_busy(&fd->sc_dk);
		timeout_add_sec(&fdc->fdctimeout_to, 4);

		/* specify command */
		FDC_WRFIFO(fdc, NE7CMD_SPECIFY);
		FDC_WRFIFO(fdc, fd->sc_type->steprate);
		/* XXX head load time == 6ms */
		FDC_WRFIFO(fdc, 6 | NE7_SPECIFY_NODMA);

		fdc->sc_itask = FDC_ITASK_SENSEI;
		/* seek function */
		FDC_WRFIFO(fdc, NE7CMD_SEEK);
		FDC_WRFIFO(fdc, fd->sc_drive); /* drive number */
		FDC_WRFIFO(fdc, cylin * fd->sc_type->step);

		return (1);

	case DOIO:
	doio:
		if (finfo != NULL)
			fd->sc_skip = (char *)&(finfo->fd_formb_cylno(0)) -
				      (char *)finfo;
		type = fd->sc_type;
		sec = fd->sc_blkno % type->seccyl;
		nblks = type->seccyl - sec;
		nblks = min(nblks, fd->sc_bcount / FD_BSIZE(fd));
		nblks = min(nblks, FDC_MAXIOSIZE / FD_BSIZE(fd));
		fd->sc_nblks = nblks;
		fd->sc_nbytes = finfo ? bp->b_bcount : nblks * FD_BSIZE(fd);
		head = sec / type->sectrac;
		sec -= head * type->sectrac;
#ifdef DIAGNOSTIC
		{
			daddr_t block;

			block = (fd->sc_cylin * type->heads + head) *
			    type->sectrac + sec;
			if (block != fd->sc_blkno) {
				printf("fdcintr: block %lld != blkno %lld\n",
				    (long long)block, (long long)fd->sc_blkno);
#if defined(FD_DEBUG) && defined(DDB)
				Debugger();
#endif
			}
		}
#endif
		read = bp->b_flags & B_READ;

		/* Setup for pseudo DMA */
		fdc->sc_data = bp->b_data + fd->sc_skip;
		fdc->sc_tc = fd->sc_nbytes;

		*fdc->sc_reg_drs = type->rate;
#ifdef FD_DEBUG
		if (fdc_debug > 1)
			printf("fdcstate: doio: %s drive %d "
			       "track %d head %d sec %d nblks %d\n",
				finfo ? "format" :
					(read ? "read" : "write"),
				fd->sc_drive, fd->sc_cylin, head, sec, nblks);
#endif
		fdc->sc_state = IOCOMPLETE;
		fdc->sc_itask = FDC_ITASK_DMA;
		fdc->sc_nstat = 0;

		disk_busy(&fd->sc_dk);

		/* allow 3 seconds for operation */
		timeout_add_sec(&fdc->fdctimeout_to, 3);

		if (finfo != NULL) {
			/* formatting */
			FDC_WRFIFO(fdc, NE7CMD_FORMAT);
			FDC_WRFIFO(fdc, (head << 2) | fd->sc_drive);
			FDC_WRFIFO(fdc, finfo->fd_formb_secshift);
			FDC_WRFIFO(fdc, finfo->fd_formb_nsecs);
			FDC_WRFIFO(fdc, finfo->fd_formb_gaplen);
			FDC_WRFIFO(fdc, finfo->fd_formb_fillbyte);
		} else {
			if (read)
				FDC_WRFIFO(fdc, NE7CMD_READ);
			else
				FDC_WRFIFO(fdc, NE7CMD_WRITE);
			FDC_WRFIFO(fdc, (head << 2) | fd->sc_drive);
			FDC_WRFIFO(fdc, fd->sc_cylin);	/*track*/
			FDC_WRFIFO(fdc, head);
			FDC_WRFIFO(fdc, sec + 1);	/*sector+1*/
			FDC_WRFIFO(fdc, type->secsize);	/*sector size*/
			FDC_WRFIFO(fdc, type->sectrac);	/*secs/track*/
			FDC_WRFIFO(fdc, type->gap1);	/*gap1 size*/
			FDC_WRFIFO(fdc, type->datalen);	/*data length*/
		}

		return (1);				/* will return later */

	case SEEKWAIT:
		timeout_del(&fdc->fdctimeout_to);
		fdc->sc_state = SEEKCOMPLETE;
		if (fdc->sc_flags & FDC_NEEDHEADSETTLE) {
			/* allow 1/50 second for heads to settle */
			timeout_add_msec(&fdc->fdcpseudointr_to, 20);
			return (1);		/* will return later */
		}
		/*FALLTHROUGH*/
	case SEEKCOMPLETE:
		disk_unbusy(&fd->sc_dk, 0, 0);	/* no data on seek */

		/* Make sure seek really happened. */
		if (fdc->sc_nstat != 2 || (st0 & 0xf8) != 0x20 ||
		    cyl != cylin * fd->sc_type->step) {
#ifdef FD_DEBUG
			if (fdc_debug)
				fdcstatus(fdc, "seek failed");
#endif
			fdcretry(fdc);
			goto loop;
		}
		fd->sc_cylin = cylin;
		goto doio;

	case IOTIMEDOUT:
		/*
		 * Try to abort the I/O operation without resetting
		 * the chip first.  Poke TC and arrange to pick up
		 * the timed out I/O command's status.
		 */
		fdc->sc_itask = FDC_ITASK_RESULT;
		fdc->sc_state = IOCLEANUPWAIT;
		fdc->sc_nstat = 0;
		/* 1/10 second should be enough */
		timeout_add_msec(&fdc->fdctimeout_to, 100);
		return (1);

	case IOCLEANUPTIMEDOUT:
	case SEEKTIMEDOUT:
	case RECALTIMEDOUT:
	case RESETTIMEDOUT:
		fdcstatus(fdc, "timeout");

		/* All other timeouts always roll through a chip reset */
		fdcretry(fdc);

		/* Force reset, no matter what fdcretry() says */
		fdc->sc_state = DORESET;
		goto loop;

	case IOCLEANUPWAIT: /* IO FAILED, cleanup succeeded */
		timeout_del(&fdc->fdctimeout_to);
		disk_unbusy(&fd->sc_dk, (bp->b_bcount - bp->b_resid),
		    (bp->b_flags & B_READ));
		fdcretry(fdc);
		goto loop;

	case IOCOMPLETE: /* IO DONE, post-analyze */
		timeout_del(&fdc->fdctimeout_to);

		disk_unbusy(&fd->sc_dk, (bp->b_bcount - bp->b_resid),
		    (bp->b_flags & B_READ));

		if (fdc->sc_nstat != 7 || st1 != 0 ||
		    ((st0 & 0xf8) != 0 &&
		     ((st0 & 0xf8) != 0x20 || (fdc->sc_cfg & CFG_EIS) == 0))) {
#ifdef FD_DEBUG
			if (fdc_debug) {
				fdcstatus(fdc,
					bp->b_flags & B_READ
					? "read failed" : "write failed");
				printf("blkno %lld nblks %d nstat %d tc %d\n",
				       (long long)fd->sc_blkno, fd->sc_nblks,
				       fdc->sc_nstat, fdc->sc_tc);
			}
#endif
			if (fdc->sc_nstat == 7 &&
			    (st1 & ST1_OVERRUN) == ST1_OVERRUN) {

				/*
				 * Silently retry overruns if no other
				 * error bit is set. Adjust threshold.
				 */
				int thr = fdc->sc_cfg & CFG_THRHLD_MASK;
				if (thr < 15) {
					thr++;
					fdc->sc_cfg &= ~CFG_THRHLD_MASK;
					fdc->sc_cfg |= (thr & CFG_THRHLD_MASK);
#ifdef FD_DEBUG
					if (fdc_debug)
						printf("fdc: %d -> threshold\n", thr);
#endif
					fdconf(fdc);
					fdc->sc_overruns = 0;
				}
				if (++fdc->sc_overruns < 3) {
					fdc->sc_state = DOIO;
					goto loop;
				}
			}
			fdcretry(fdc);
			goto loop;
		}
		if (fdc->sc_errors) {
			diskerr(bp, "fd", "soft error", LOG_PRINTF,
			    fd->sc_skip / FD_BSIZE(fd),
			    (struct disklabel *)NULL);
			printf("\n");
			fdc->sc_errors = 0;
		} else {
			if (--fdc->sc_overruns < -20) {
				int thr = fdc->sc_cfg & CFG_THRHLD_MASK;
				if (thr > 0) {
					thr--;
					fdc->sc_cfg &= ~CFG_THRHLD_MASK;
					fdc->sc_cfg |= (thr & CFG_THRHLD_MASK);
#ifdef FD_DEBUG
					if (fdc_debug)
						printf("fdc: %d -> threshold\n", thr);
#endif
					fdconf(fdc);
				}
				fdc->sc_overruns = 0;
			}
		}
		fd->sc_blkno += fd->sc_nblks;
		fd->sc_skip += fd->sc_nbytes;
		fd->sc_bcount -= fd->sc_nbytes;
		bp->b_resid -= fd->sc_nbytes;
		if (finfo == NULL && fd->sc_bcount > 0) {
			cylin = fd->sc_blkno / fd->sc_type->seccyl;
			goto doseek;
		}
		fdfinish(fd, bp);
		goto loop;

	case DORESET:
		/* try a reset, keep motor on */
		fd_set_motor(fdc);
		delay(100);
		fdc->sc_nstat = 0;
		fdc->sc_itask = FDC_ITASK_SENSEI;
		fdc->sc_state = RESETCOMPLETE;
		timeout_add_msec(&fdc->fdctimeout_to, 500);
		fdc_reset(fdc);
		return (1);			/* will return later */

	case RESETCOMPLETE:
		timeout_del(&fdc->fdctimeout_to);
		fdconf(fdc);

		/* FALLTHROUGH */
	case DORECAL:
		fdc->sc_state = RECALWAIT;
		fdc->sc_itask = FDC_ITASK_SENSEI;
		fdc->sc_nstat = 0;
		timeout_add_sec(&fdc->fdctimeout_to, 5);
		/* recalibrate function */
		FDC_WRFIFO(fdc, NE7CMD_RECAL);
		FDC_WRFIFO(fdc, fd->sc_drive);
		return (1);			/* will return later */

	case RECALWAIT:
		timeout_del(&fdc->fdctimeout_to);
		fdc->sc_state = RECALCOMPLETE;
		if (fdc->sc_flags & FDC_NEEDHEADSETTLE) {
			/* allow 1/30 second for heads to settle */
			timeout_add(&fdc->fdcpseudointr_to, hz / 30);
			return (1);		/* will return later */
		}

	case RECALCOMPLETE:
		if (fdc->sc_nstat != 2 || (st0 & 0xf8) != 0x20 || cyl != 0) {
#ifdef FD_DEBUG
			if (fdc_debug)
				fdcstatus(fdc, "recalibrate failed");
#endif
			fdcretry(fdc);
			goto loop;
		}
		fd->sc_cylin = 0;
		goto doseek;

	case MOTORWAIT:
		if (fd->sc_flags & FD_MOTOR_WAIT)
			return (1);		/* time's not up yet */
		goto doseek;

	default:
		fdcstatus(fdc, "stray interrupt");
		return (1);
	}
#ifdef DIAGNOSTIC
	panic("fdcintr: impossible");
#endif

xxx:
	/*
	 * We get here if the chip locks up in FDC_WRFIFO()
	 * Cancel any operation and schedule a reset.
	 */
	timeout_del(&fdc->fdctimeout_to);
	fdcretry(fdc);
	fdc->sc_state = DORESET;
	goto loop;

#undef	st0
#undef	st1
#undef	cyl
}

void
fdcretry(fdc)
	struct fdc_softc *fdc;
{
	struct fd_softc *fd;
	struct buf *bp;
	int error = EIO;

	fd = TAILQ_FIRST(&fdc->sc_drives);
	bp = fd->sc_bp;

	fdc->sc_overruns = 0;
	if (fd->sc_opts & FDOPT_NORETRY)
		goto fail;

	switch (fdc->sc_errors) {
	case 0:
		if (fdc->sc_nstat == 7 &&
		    (fdc->sc_status[0] & 0xd8) == 0x40 &&
		    (fdc->sc_status[1] & 0x2) == 0x2) {
			printf("%s: read-only medium\n", fd->sc_dv.dv_xname);
			error = EROFS;
			goto failsilent;
		}
		/* try again */
		fdc->sc_state =
			(fdc->sc_flags & FDC_EIS) ? DOIO : DOSEEK;
		break;

	case 1: case 2: case 3:
		/* didn't work; try recalibrating */
		fdc->sc_state = DORECAL;
		break;

	case 4:
		if (fdc->sc_nstat == 7 &&
		    fdc->sc_status[0] == 0 &&
		    fdc->sc_status[1] == 0 &&
		    fdc->sc_status[2] == 0) {
			/*
			 * We've retried a few times and we've got
			 * valid status and all three status bytes
			 * are zero.  Assume this condition is the
			 * result of no disk loaded into the drive.
			 */
			printf("%s: no medium?\n", fd->sc_dv.dv_xname);
			error = ENODEV;
			goto failsilent;
		}

		/* still no go; reset the bastard */
		fdc->sc_state = DORESET;
		break;

	default:
	fail:
		if ((fd->sc_opts & FDOPT_SILENT) == 0) {
			diskerr(bp, "fd", "hard error", LOG_PRINTF,
				fd->sc_skip / FD_BSIZE(fd),
				(struct disklabel *)NULL);
			printf("\n");
			fdcstatus(fdc, "controller status");
		}

	failsilent:
		bp->b_flags |= B_ERROR;
		bp->b_error = error;
		bp->b_resid = bp->b_bcount;
		fdfinish(fd, bp);
	}
	fdc->sc_errors++;
}

daddr_t
fdsize(dev)
	dev_t dev;
{

	/* Swapping to floppies would not make sense. */
	return (-1);
}

int
fddump(dev, blkno, va, size)
	dev_t dev;
	daddr_t blkno;
	caddr_t va;
	size_t size;
{

	/* Not implemented. */
	return (EINVAL);
}

int
fdioctl(dev, cmd, addr, flag, p)
	dev_t dev;
	u_long cmd;
	caddr_t addr;
	int flag;
	struct proc *p;
{
	struct fd_softc *fd = fd_cd.cd_devs[FDUNIT(dev)];
	struct disklabel *lp;
	int error;

	switch (cmd) {
	case DIOCRLDINFO:
		lp = malloc(sizeof(*lp), M_TEMP, M_WAITOK);
		fdgetdisklabel(dev, fd, lp, 0);
		bcopy(lp, fd->sc_dk.dk_label, sizeof(*lp));
		free(lp, M_TEMP, 0);
		return 0;

	case DIOCGPDINFO:
		fdgetdisklabel(dev, fd, (struct disklabel *)addr, 1);
		return 0;

	case DIOCGDINFO:
		*(struct disklabel *)addr = *(fd->sc_dk.dk_label);
		return 0;

	case DIOCGPART:
		((struct partinfo *)addr)->disklab = fd->sc_dk.dk_label;
		((struct partinfo *)addr)->part =
		    &fd->sc_dk.dk_label->d_partitions[FDPART(dev)];
		return 0;

	case DIOCWDINFO:
	case DIOCSDINFO:
		if ((flag & FWRITE) == 0)
			return (EBADF);

		error = setdisklabel(fd->sc_dk.dk_label,
		    (struct disklabel *)addr, 0);
		if (error == 0) {
			if (cmd == DIOCWDINFO)
				error = writedisklabel(DISKLABELDEV(dev),
				    fdstrategy, fd->sc_dk.dk_label);
		}
		return (error);

	case DIOCLOCK:
		/*
		 * Nothing to do here, really.
		 */
		return (0);

	case MTIOCTOP:
		if (((struct mtop *)addr)->mt_op != MTOFFL)
			return EIO;

	case DIOCEJECT:
		fd_do_eject(fd);
		return (0);

	case FD_FORM:
		if((flag & FWRITE) == 0)
			return EBADF;	/* must be opened for writing */
		else if(((struct fd_formb *)addr)->format_version !=
		    FD_FORMAT_VERSION)
			return EINVAL;	/* wrong version of formatting prog */
		else
			return fdformat(dev, (struct fd_formb *)addr, p);
		break;

	case FD_GTYPE:			/* get drive type */
		*(struct fd_type *)addr = *fd->sc_type;
		return (0);

	case FD_GOPTS:			/* get drive options */
		*(int *)addr = fd->sc_opts;
		return (0);

	case FD_SOPTS:			/* set drive options */
		fd->sc_opts = *(int *)addr;
		return (0);

#ifdef FD_DEBUG
	case _IO('f', 100):
		{
		int i;
		struct fdc_softc *fdc = (struct fdc_softc *)
					fd->sc_dv.dv_parent;

		fdc_wrfifo(fdc, NE7CMD_DUMPREG);
		fdcresult(fdc);
		printf("dumpreg(%d regs): <", fdc->sc_nstat);
		for (i = 0; i < fdc->sc_nstat; i++)
			printf(" 0x%x", fdc->sc_status[i]);
		printf(">\n");
		}

		return (0);
	case _IOW('f', 101, int):
		{
		struct fdc_softc *fdc = (struct fdc_softc *)
					fd->sc_dv.dv_parent;
		fdc->sc_cfg &= ~CFG_THRHLD_MASK;
		fdc->sc_cfg |= (*(int *)addr & CFG_THRHLD_MASK);
		fdconf(fdc);
		}
		return (0);
	case _IO('f', 102):
		{
		int i;
		struct fdc_softc *fdc = (struct fdc_softc *)
					fd->sc_dv.dv_parent;
		fdc_wrfifo(fdc, NE7CMD_SENSEI);
		fdcresult(fdc);
		printf("sensei(%d regs): <", fdc->sc_nstat);
		for (i = 0; i < fdc->sc_nstat; i++)
			printf(" 0x%x", fdc->sc_status[i]);
		}
		printf(">\n");
		return (0);
#endif
	default:
		return (ENOTTY);
	}
}

int
fdformat(dev, finfo, p)
	dev_t dev;
	struct fd_formb *finfo;
	struct proc *p;
{
	int rv = 0;
	struct fd_softc *fd = fd_cd.cd_devs[FDUNIT(dev)];
	struct fd_type *type = fd->sc_type;
	struct buf *bp;

	/* set up a buffer header for fdstrategy() */
	bp = malloc(sizeof(*bp), M_TEMP, M_NOWAIT | M_ZERO);
	if (bp == 0)
		return (ENOBUFS);

	bp->b_flags = B_BUSY | B_PHYS | B_FORMAT | B_RAW;
	bp->b_proc = p;
	bp->b_dev = dev;

	/*
	 * Calculate a fake blkno, so fdstrategy() would initiate a
	 * seek to the requested cylinder.
	 */
	bp->b_blkno = ((finfo->cyl * (type->sectrac * type->heads)
		       + finfo->head * type->sectrac) * FD_BSIZE(fd))
		       / DEV_BSIZE;

	bp->b_bcount = sizeof(struct fd_idfield_data) * finfo->fd_formb_nsecs;
	bp->b_data = (caddr_t)finfo;

#ifdef FD_DEBUG
	if (fdc_debug) {
		int i;

		printf("fdformat: blkno 0x%x count %ld\n",
			bp->b_blkno, bp->b_bcount);

		printf("\tcyl:\t%d\n", finfo->cyl);
		printf("\thead:\t%d\n", finfo->head);
		printf("\tnsecs:\t%d\n", finfo->fd_formb_nsecs);
		printf("\tsshft:\t%d\n", finfo->fd_formb_secshift);
		printf("\tgaplen:\t%d\n", finfo->fd_formb_gaplen);
		printf("\ttrack data:");
		for (i = 0; i < finfo->fd_formb_nsecs; i++) {
			printf(" [c%d h%d s%d]",
					finfo->fd_formb_cylno(i),
					finfo->fd_formb_headno(i),
					finfo->fd_formb_secno(i) );
			if (finfo->fd_formb_secsize(i) != 2)
				printf("<sz:%d>", finfo->fd_formb_secsize(i));
		}
		printf("\n");
	}
#endif

	/* now do the format */
	fdstrategy(bp);

	/* ...and wait for it to complete */
	rv = biowait(bp);
	free(bp, M_TEMP, 0);
	return (rv);
}

int
fdgetdisklabel(dev_t dev, struct fd_softc *fd, struct disklabel *lp,
    int spoofonly)
{
	bzero(lp, sizeof(struct disklabel));

	lp->d_type = DTYPE_FLOPPY;
	lp->d_secsize = FD_BSIZE(fd);
	lp->d_secpercyl = fd->sc_type->seccyl;
	lp->d_nsectors = fd->sc_type->sectrac;
	lp->d_ncylinders = fd->sc_type->tracks;
	lp->d_ntracks = fd->sc_type->heads;	/* Go figure... */
	DL_SETDSIZE(lp, fd->sc_type->size);

	strncpy(lp->d_typename, "floppy disk", sizeof(lp->d_typename));
	strncpy(lp->d_packname, "fictitious", sizeof(lp->d_packname));
	lp->d_version = 1;

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

	/*
	 * Call the generic disklabel extraction routine.
	 */
	return readdisklabel(DISKLABELDEV(dev), fdstrategy, lp, spoofonly);
}

void
fd_do_eject(fd)
	struct fd_softc *fd;
{
	struct fdc_softc *fdc = (void *)fd->sc_dv.dv_parent;

	if (CPU_ISSUN4C) {
		auxregbisc(AUXIO4C_FDS, AUXIO4C_FEJ);
		delay(10);
		auxregbisc(AUXIO4C_FEJ, AUXIO4C_FDS);
		return;
	}
	if (CPU_ISSUN4M && (fdc->sc_flags & FDC_82077) != 0) {
		int dor = FDO_FRST | FDO_FDMAEN | FDO_MOEN(0);
		*fdc->sc_reg_dor = dor | FDO_EJ;
		delay(10);
		*fdc->sc_reg_dor = FDO_FRST | FDO_DS;
		return;
	}
}


code:
/*	$OpenBSD: fdreg.h,v 1.5 2004/09/22 22:12:58 miod Exp $	*/
/*	$NetBSD: fdreg.h,v 1.6 1997/05/02 13:03:44 pk Exp $	*/

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

/*
 * AT floppy controller registers and bitfields
 */

/* uses NEC765 controller */
#include <dev/ic/nec765reg.h>

#ifndef _LOCORE
struct fdreg_77 {
	u_int8_t	fd_statusA;
	u_int8_t	fd_statusB;
	u_int8_t	fd_dor;		/* Digital Output Register (R/W) */
	u_int8_t	fd_tdr;		/* Tape Control Register (R/W) */
	u_int8_t	fd_msr;		/* Main Status Register (R) */
#define fd_drs		fd_msr		/* Data Rate Select Register (W) */
	u_int8_t	fd_fifo;	/* Data (FIFO) register (R/W) */
	u_int8_t	fd_reserved;
	u_int8_t	fd_dir;		/* Digital Input Register (R) */
#define fd_ccr		fd_dir		/* Configuration Control (W) */
};

struct fdreg_72 {
	u_int8_t	fd_msr;		/* Main Status Register (R) */
#if already_a_define
#define fd_drs	fd_msr			/* Data Rate Select Register (W) */
#endif
	u_int8_t	fd_fifo;	/* Data (FIFO) register (R/W) */
};

union fdreg {
	struct fdreg_72 fun72;
	struct fdreg_77 fun77;
};
#endif

/* Data Select Register bits */
#define DRS_RESET	0x80
#define DRS_POWER	0x40
#define DRS_PLL		0x20
#define	FDC_500KBPS	0x00		/*   500KBPS MFM drive transfer rate */
#define	FDC_300KBPS	0x01		/*   300KBPS MFM drive transfer rate */
#define	FDC_250KBPS	0x02		/*   250KBPS MFM drive transfer rate */
#define	FDC_125KBPS	0x03		/*   125KBPS  FM drive transfer rate */

/* Digital Output Register bits (modified on suns) */
#define	FDO_DS		0x01		/*  floppy device select (neg) */
#define	FDO_FRST	0x04		/*  floppy controller reset (neg) */
#define	FDO_FDMAEN	0x08		/*  enable floppy DMA and Interrupt */
#define	FDO_MOEN(n)	((1 << n) << 4)	/* motor enable */
#define FDO_DEN		0x40		/* Density select */
#define FDO_EJ		0x80		/* Eject disk */

/* Digital Input Register bits */
#define	FDI_DCHG	0x80		/*   diskette has been changed */

/* XXX - find a place for these... */
#define NE7CMD_CFG		0x13
#define CFG_EIS			0x40
#define CFG_EFIFO		0x20
#define CFG_POLL		0x10
#define CFG_THRHLD_MASK		0x0f

#define NE7CMD_LOCK		0x14
#define CFG_LOCK		0x80

#define NE7CMD_MOTOR		0x0b
#define MOTOR_ON		0x80

#define NE7CMD_DUMPREG		0x0e
#define NE7CMD_VERSION		0x10

#define ST1_OVERRUN		0x10

#define NE7_SPECIFY_NODMA	0x01

license: unknown


code:
/*	$OpenBSD: fdvar.h,v 1.9 2010/08/17 20:05:06 miod Exp $	*/
/*
 *	$NetBSD: fdvar.h,v 1.5 1996/12/08 23:40:34 pk Exp $
 *
 * Copyright (c) 1995 Paul Kranenburg
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Paul Kranenburg.
 * 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.
 *
 */

#define	FD_BSIZE(fd)	(128 << fd->sc_type->secsize)
#define	FDC_MAXIOSIZE	NBPG	/* XXX should be MAXBSIZE */

#define FDC_NSTATUS	10

#ifndef _LOCORE
struct fdcio {
	/*
	 * 82072 (sun4c) and 82077 (sun4m) controllers have different
	 * register layout; so we cache some here.
	 */
	volatile u_int8_t	*fdcio_reg_msr;
	volatile u_int8_t	*fdcio_reg_fifo;
	volatile u_int8_t	*fdcio_reg_dor;	/* 82077 only */

	/*
	 * Interrupt state.
	 */
	int	fdcio_itask;
	int	fdcio_istatus;

	/*
	 * IO state.
	 */
	char	*fdcio_data;		/* pseudo-dma data */
	int	fdcio_tc;		/* pseudo-dma Terminal Count */
	u_char	fdcio_status[FDC_NSTATUS];	/* copy of registers */
	int	fdcio_nstat;		/* # of valid status bytes */

	struct	intrhand fdcio_ih;
	void		*fdcio_sih;	/* softintr cookie */
};
#endif /* _LOCORE */

/* itask values */
#define FDC_ITASK_NONE		0	/* No HW interrupt expected */
#define FDC_ITASK_SENSEI	1	/* Do SENSEI on next HW interrupt */
#define FDC_ITASK_DMA		2	/* Do Pseudo-DMA */
#define FDC_ITASK_RESULT	3	/* Pick up command results */

/* istatus values */
#define FDC_ISTATUS_NONE	0	/* No status available */
#define FDC_ISTATUS_SPURIOUS	1	/* Spurious HW interrupt detected */
#define FDC_ISTATUS_ERROR	2	/* Operation completed abnormally */
#define FDC_ISTATUS_DONE	3	/* Operation completed normally */

#define SUNOS_FDIOCEJECT	_IO('f', 24)


code:
/*	$OpenBSD: fga.c,v 1.18 2015/03/30 20:30:22 miod Exp $	*/

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

/*
 * Driver for the Force Gate Array 5000 (VME/SBus bridge) found
 * on FORCE CPU-5V boards.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/syslog.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <uvm/uvm_extern.h>

#include <machine/autoconf.h>
#include <machine/bus.h>
#include <sparc/cpu.h>
#include <sparc/sparc/cpuvar.h>

#include <sparc/dev/fgareg.h>
#include <sparc/dev/fgavar.h>
#include <machine/fgaio.h>

int	fgamatch(struct device *, void *, void *);
void	fgaattach(struct device *, struct device *, void *);
int	fvmematch(struct device *, void *, void *);
void	fvmeattach(struct device *, struct device *, void *);
int	fgaprint(void *, const char *);
int	fvmeprint(void *, const char *);
int	fvmescan(struct device *parent, void *, void *);

struct fga_softc {
	struct		device sc_dev;		/* base device */
	int		sc_node;		/* prom node */
	struct		fga_regs *sc_regs;	/* registers */
	struct		intrhand sc_ih1;	/* level 1 handler */
	struct		intrhand sc_ih2;	/* level 2 handler */
	struct		intrhand sc_ih3;	/* level 3 handler */
	struct		intrhand sc_ih4;	/* level 4 handler */
	struct		intrhand sc_ih5;	/* level 5 handler */
	struct		intrhand sc_ih6;	/* level 6 handler */
	struct		intrhand sc_ih7;	/* level 7 handler */
	struct		intrhand **sc_vmevec;	/* vectored handlers */
#ifdef DDB
	int		sc_abort;		/* abort switch enabled? */
#endif
	int		sc_nrange;		/* number of sbus ranges */
	struct		rom_range *sc_range;	/* sbus range data */
	u_int8_t	sc_established;		/* which hw intrs installed */
	bus_dma_tag_t	sc_dmat;
};

int	fgaopen(dev_t, int, int, struct proc *);
int	fgaclose(dev_t, int, int, struct proc *);
int	fgaioctl(dev_t, u_long, caddr_t, int, struct proc *);

int	fga_vmerangemap(struct fga_softc *, u_int32_t, u_int32_t,
    int, int, u_int32_t, struct confargs *);
int	fga_intr_establish(struct fga_softc *, int, int,
    struct intrhand *, const char *);
int	fga_hwintr_establish(struct fga_softc *, u_int8_t);

int	fga_hwintr1(void *);
int	fga_hwintr2(void *);
int	fga_hwintr3(void *);
int	fga_hwintr4(void *);
int	fga_hwintr5(void *);
int	fga_hwintr6(void *);
int	fga_hwintr7(void *);
int	fga_intrvec(struct fga_softc *, int);

struct cfattach fga_ca = {
	sizeof (struct fga_softc), fgamatch, fgaattach
};

struct cfdriver fga_cd = {
	NULL, "fga", DV_DULL
};

struct fvme_softc {
	struct		device sc_dv;
	u_int32_t	sc_vmeoffset;		/* vme range offset */
	u_int32_t	sc_len;			/* length of range */
	u_int32_t	sc_sbusoffset;		/* sbus phys address */
	u_int32_t	sc_type;		/* amcode type */
};

struct cfattach fvme_ca = {
	sizeof (struct fvme_softc), fvmematch, fvmeattach
};

struct cfdriver fvme_cd = {
	NULL, "fvme", DV_DULL
};

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

	if (strcmp("VME", ra->ra_name))
		return (0);
	return (1);
}

void
fgaattach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct confargs *ca = aux, oca;
	struct fga_softc *sc = (struct fga_softc *)self;
	char *s;
	int i, rlen;

	if (sc->sc_dev.dv_unit > 0) {
		printf(" unsupported\n");
		return;
	}

	/* map registers */
	if (ca->ca_ra.ra_nreg != 1) {
		printf(": expected 1 register, got %d\n", ca->ca_ra.ra_nreg);
		return;
	}
	sc->sc_regs = mapiodev(&(ca->ca_ra.ra_reg[0]), 0,
	    ca->ca_ra.ra_reg[0].rr_len);

	sc->sc_node = ca->ca_ra.ra_node;
	sc->sc_dmat = ca->ca_dmat;

	i = opennode("/iommu/sbus");
	if (i == 0) {
		printf(": no iommu or sbus found, unconfigured\n");
		return;
	}
	rlen = getproplen(i, "ranges");
	sc->sc_range =
	    (struct rom_range *)malloc(rlen, M_DEVBUF, M_NOWAIT);
	if (sc->sc_range == NULL) {
		printf(": PROM ranges too large: %d\n", rlen);
		return;
	}
	sc->sc_nrange = rlen / sizeof(struct rom_range);
	(void)getprop(i, "ranges", sc->sc_range, rlen);

	s = getpropstring(sc->sc_node, "model");
	printf(": model %s id %c%c%c\n", s,
	    sc->sc_regs->id[0], sc->sc_regs->id[1], sc->sc_regs->id[2]);

	/*
	 * The prom leaves at least one of the ranges "on", so make sure
	 * they are all off.
	 */
	for (i = 0; i < 16; i++)
		sc->sc_regs->vme_range[i] |= VME_RANGE_DECEN;

	sc->sc_regs->sbus_ssel[0] &= ~(SBUS_SSEL_Y);
	sc->sc_regs->sbus_ssel[0] |= SBUS_SSEL_Y_SLOT4;
	sc->sc_regs->sbus_ssel[1] &= ~(SBUS_SSEL_X | SBUS_SSEL_Y);
	sc->sc_regs->sbus_ssel[1] |= SBUS_SSEL_X_SLOT5 | SBUS_SSEL_Y_SLOT5;
	sc->sc_regs->sbus_ssel[2] &= ~(SBUS_SSEL_X | SBUS_SSEL_Y);
	sc->sc_regs->sbus_ssel[2] |= SBUS_SSEL_X_SLOT5 | SBUS_SSEL_Y_SLOT1;
	sc->sc_regs->sbus_ssel[3] &= ~(SBUS_SSEL_X | SBUS_SSEL_Y);
	sc->sc_regs->sbus_ssel[3] |= SBUS_SSEL_X_SLOT1 | SBUS_SSEL_Y_SLOT1;

	/*
	 * Map and attach vme<->sbus master ranges
	 */
	fga_vmerangemap(sc, 0xf0000000, 0x10000000,
	    VME_MASTER_CAP_D32 | VME_MASTER_CAP_A32, 1, 0, &oca);
	fga_vmerangemap(sc, 0xf0000000, 0x10000000,
	    VME_MASTER_CAP_D16 | VME_MASTER_CAP_A32, 4, 0, &oca);
	fga_vmerangemap(sc, 0x00000000, 0x01000000,
	    VME_MASTER_CAP_D16 | VME_MASTER_CAP_A24, 5, 0xe000000, &oca);
	fga_vmerangemap(sc, 0x00000000, 0x00010000,
	    VME_MASTER_CAP_D8 | VME_MASTER_CAP_A16, 5, 0x0ffc0000, &oca);
	fga_vmerangemap(sc, 0x00000000, 0x00010000,
	    VME_MASTER_CAP_D16 | VME_MASTER_CAP_A16, 5, 0x0ffd0000, &oca);
	fga_vmerangemap(sc, 0x00000000, 0x00010000,
	    VME_MASTER_CAP_D32 | VME_MASTER_CAP_A16, 5, 0x0ffe0000, &oca);

#ifdef DDB
	s = getpropstring(optionsnode, "abort-ena?");
	if (s && strcmp(s, "true") == 0) {
		sc->sc_abort = 1;
		fga_hwintr_establish(sc, IRQ_MAP_SINT7);
		sc->sc_regs->abort_irq_map &= ~IRQ_MAP_INT_MASK;
		sc->sc_regs->abort_irq_map |= IRQ_MAP_SINT7;
		sc->sc_regs->abort_irq_map &= ~IRQ_MAP_ENABLE;
	}
#endif
}

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

	if (name)
		printf("%s at %s", ca->ca_ra.ra_name, name);
	printf(" slot %d addr 0x%x", ca->ca_slot, ca->ca_offset);
	return (UNCONF);
}

/*
 * Map a region of VME space to a sbus slot/offset.
 */
int
fga_vmerangemap(sc, vmebase, vmelen, vmecap, sbusslot, sbusoffset, oca)
	struct fga_softc *sc;
	u_int32_t vmebase, vmelen;
	int vmecap;
	int sbusslot;
	u_int32_t sbusoffset;
	struct confargs *oca;
{
	struct fga_regs *regs = sc->sc_regs;
	u_int32_t rval;
	u_int8_t sval;
	int range, i, srange;

	for (i = 0; i < FVME_MAX_RANGES; i++) {
		if (regs->vme_range[i] & VME_RANGE_DECEN)
			break;
	}
	if (i == FVME_MAX_RANGES)
		return (-1);
	range = i;

	for (srange = 0; srange < sc->sc_nrange; srange++) {
		if (sbusslot == sc->sc_range[srange].cspace)
			break;
	}
	if (srange == sc->sc_nrange)
		return (-1);

	bzero(oca, sizeof(*oca));
	oca->ca_bustype = BUS_FGA;
	oca->ca_slot = sbusslot;
	oca->ca_offset = sc->sc_range[srange].poffset | sbusoffset;
	oca->ca_ra.ra_name = "fvme";
	oca->ca_ra.ra_nreg = 2;
	oca->ca_ra.ra_reg[0].rr_len = vmelen;
	oca->ca_ra.ra_reg[0].rr_paddr =
	    (void *)(sc->sc_range[srange].poffset | sbusoffset);
	oca->ca_ra.ra_reg[0].rr_iospace = sbusslot;
	oca->ca_ra.ra_reg[1].rr_iospace = vmecap;
	oca->ca_ra.ra_reg[1].rr_paddr = (void *)vmebase;
	oca->ca_ra.ra_reg[1].rr_len = vmelen;
	oca->ca_dmat = sc->sc_dmat;

	/* 1. Setup slot select register for this range. */
	switch (sbusslot) {
	case 1:
		sval = SBUS_SSEL_Y_SLOT1;
		break;
	case 2:
		sval = SBUS_SSEL_Y_SLOT2;
		break;
	case 3:
		sval = SBUS_SSEL_Y_SLOT3;
		break;
	case 4:
		sval = SBUS_SSEL_Y_SLOT4;
		break;
	case 5:
		sval = SBUS_SSEL_Y_SLOT5;
		break;
	default:
		return (-1);
	}

	if (range & 1) {
		regs->sbus_ssel[range >> 1] &= ~SBUS_SSEL_Y;
		regs->sbus_ssel[range >> 1] |= sval;
	} else {
		regs->sbus_ssel[range >> 1] &= ~SBUS_SSEL_X;
		regs->sbus_ssel[range >> 1] |= sval << 4;
	}

	/* 2. Setup and enable the VME master range. */
	rval = regs->vme_range[range];
	rval &= ~(VME_RANGE_VMAE | VME_RANGE_VMAT);
	rval |= (vmebase >> 13) & (VME_RANGE_VMAE | VME_RANGE_VMAT);
	rval &= ~VME_RANGE_VMRCC;
	rval |= ((sbusoffset << 4) | (vmelen << 3)) & VME_RANGE_VMRCC;
	rval &= ~VME_RANGE_DECEN;
	regs->vme_range[range] = rval;

	/* 3. Setup addr/data capabilities for the range. */
	regs->vme_master_cap[range] &=
	    ~(VME_MASTER_CAP_DATA | VME_MASTER_CAP_ADDR);
	regs->vme_master_cap[range] |= vmecap;

	config_found(&sc->sc_dev, oca, fgaprint);

	return (0);
}

int
fga_hwintr1(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	u_int32_t bits = 0, stat;
	int r = 0, s;

	s = splhigh();
	stat = regs->intr_stat;
	splx(s);

	if ((stat & INTR_STAT_VMEIRQ1) == 0) {
		bits |= INTR_STAT_VMEIRQ1;
		r |= fga_intrvec(sc, regs->viack_emu1);
	}

	s = splhigh();
	regs->intr_stat &= ~bits;
	splx(s);

	return (r);
}

int
fga_hwintr2(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	int r = 0;

	if ((regs->intr_stat & INTR_STAT_VMEIRQ2) == 0)
		r |= fga_intrvec(sc, regs->viack_emu2);

	return (r);
}

int
fga_hwintr3(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	int r = 0;

	/* vme irq 3 */
	if ((regs->intr_stat & INTR_STAT_VMEIRQ3) == 0)
		r |= fga_intrvec(sc, regs->viack_emu3);

	return (r);
}

int
fga_hwintr4(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	int r = 0;

	if ((regs->intr_stat & INTR_STAT_VMEIRQ4) == 0)
		r |= fga_intrvec(sc, regs->viack_emu4);

	return (r);
}

int
fga_hwintr5(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	int r = 0;

	if ((regs->intr_stat & INTR_STAT_VMEIRQ5) == 0)
		r |= fga_intrvec(sc, regs->viack_emu5);

	return (r);
}

int
fga_hwintr6(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	int r = 0;

	if ((regs->intr_stat & INTR_STAT_VMEIRQ6) == 0)
		r |= fga_intrvec(sc, regs->viack_emu6);

	return (r);
}

int
fga_hwintr7(v)
	void *v;
{
	struct fga_softc *sc = v;
	struct fga_regs *regs = sc->sc_regs;
	int r = 0, s;
	u_int32_t bits = 0, stat;

	s = splhigh();
	stat = regs->intr_stat;
	splx(s);

#ifdef DDB
	if (sc->sc_abort && (stat & INTR_STAT_ABORT) == 0) {
		bits |= INTR_STAT_ABORT;
		r |= 1;
		Debugger();
	}
#endif

	if ((regs->intr_stat & INTR_STAT_VMEIRQ7) == 0) {
		bits |= INTR_STAT_VMEIRQ7;
		r |= fga_intrvec(sc, regs->viack_emu7);
	}

	s = splhigh();
	regs->intr_stat &= ~bits;
	splx(s);

	return (r);
}

/*
 * Handle a VME vectored interrupt.
 */
int
fga_intrvec(sc, vec)
	struct fga_softc *sc;
	u_int8_t vec;
{
	struct intrhand *ih;
	int r, s = 0;

	if (sc->sc_vmevec == NULL)
		return (0);

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

	return (s);
}

/*
 * Establish a VME level/vector interrupt.
 */
int
fga_intr_establish(sc, vec, level, ih, name)
	struct fga_softc *sc;
	int vec, level;
	struct intrhand *ih;
	const char *name;
{
	struct intrhand *ihs;
	const u_int8_t level_to_sint[] = {
		IRQ_MAP_INT,
		IRQ_MAP_SINT1,
		IRQ_MAP_SINT2,
		IRQ_MAP_SINT3,
		IRQ_MAP_SINT4,
		IRQ_MAP_SINT5,
		IRQ_MAP_SINT6,
		IRQ_MAP_SINT7
	};
	const u_int8_t level_to_irqmap[] = {0xff, 6, 5, 4, 3, 2, 1, 0};

#ifdef DIAGNOSTIC
	if (level < 1 || level > 7)
		panic("fga_level");
#endif

	/* setup vector handler */
	if (sc->sc_vmevec == NULL) {
		sc->sc_vmevec = (struct intrhand **)malloc(256 *
		    sizeof(struct intrhand *), M_DEVBUF, M_NOWAIT | M_ZERO);
		if (sc->sc_vmevec == NULL)
			panic("fga_addirq");
	}
	if (sc->sc_vmevec[vec] == NULL)
		sc->sc_vmevec[vec] = ih;
	else {
		ihs = sc->sc_vmevec[vec];
		while (ihs->ih_next)
			ihs = ihs->ih_next;
		ih->ih_next = ih;
	}

	ih->ih_vec = level;
	evcount_attach(&ih->ih_count, name, &ih->ih_vec);

	/* setup hardware handler */
	fga_hwintr_establish(sc, level_to_sint[level]);

	/* setup/enable vme -> sbus irq mapping */
	sc->sc_regs->virq_map[level_to_irqmap[level]] &= ~IRQ_MAP_INT_MASK;
	sc->sc_regs->virq_map[level_to_irqmap[level]] |= level_to_sint[level];
	sc->sc_regs->virq_map[level_to_irqmap[level]] &= ~IRQ_MAP_ENABLE;

	return (0);
}

/*
 * Establish a hardware interrupt, making sure we're not there already.
 */
int
fga_hwintr_establish(sc, sint)
	struct fga_softc *sc;
	u_int8_t sint;
{
	const int sint_to_pri[] = {0, 2, 3, 5, 6, 7, 8, 9};

	if (sc->sc_established & (1 << sint))
		return (0);

	switch (sint) {
	case 1:
		sc->sc_ih1.ih_fun = fga_hwintr1;
		sc->sc_ih1.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih1, -1, NULL);
		break;
	case 2:
		sc->sc_ih2.ih_fun = fga_hwintr2;
		sc->sc_ih2.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih2, -1, NULL);
		break;
	case 3:
		sc->sc_ih3.ih_fun = fga_hwintr3;
		sc->sc_ih3.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih3, -1, NULL);
		break;
	case 4:
		sc->sc_ih4.ih_fun = fga_hwintr4;
		sc->sc_ih4.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih4, -1, NULL);
		break;
	case 5:
		sc->sc_ih5.ih_fun = fga_hwintr5;
		sc->sc_ih5.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih5, -1, NULL);
		break;
	case 6:
		sc->sc_ih6.ih_fun = fga_hwintr6;
		sc->sc_ih6.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih6, -1, NULL);
		break;
	case 7:
		sc->sc_ih7.ih_fun = fga_hwintr7;
		sc->sc_ih7.ih_arg = sc;
		intr_establish(sint_to_pri[sint], &sc->sc_ih7, -1, NULL);
		break;
#ifdef DIAGNOSTIC
	default:
		panic("fga_sint");
#endif
	}

	sc->sc_established |= 1 << sint;
	return (0);
}

int
fgaopen(dev, flags, mode, p)
	dev_t dev;
	int flags, mode;
	struct proc *p;
{
	struct fga_softc *sc;

	if (fga_cd.cd_ndevs == 0)
		return (ENXIO);
	sc = fga_cd.cd_devs[0];
	if (sc == NULL)
		return (ENXIO);
	return (0);
}

int
fgaclose(dev, flags, mode, p)
	dev_t dev;
	int flags, mode;
	struct proc *p;
{
	return (0);
}

int
fgaioctl(dev, cmd, data, flags, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flags;
	struct proc *p;
{
	struct fga_softc *sc = fga_cd.cd_devs[0];
	struct fga_sem *fsem = (struct fga_sem *)data;
	int error = 0;

	switch (cmd) {
	case FGAIOCSEM:
		if (fsem->fgasem_num >= 48) {
			error = ENOENT;
			break;
		}
		sc->sc_regs->sem[fsem->fgasem_num] = 0xff;
		break;
	case FGAIOGSEM:
		if (fsem->fgasem_num >= 48) {
			error = ENOENT;
			break;
		}
		fsem->fgasem_val =
		    (sc->sc_regs->sem[fsem->fgasem_num] & MBOX_SEM) ? 0 : 1;
		break;
	case FGAIOCMBX:
		if (fsem->fgasem_num >= 16) {
			error = ENOENT;
			break;
		}
		sc->sc_regs->mbox[fsem->fgasem_num] = 0xff;
		break;
	case FGAIOGMBX:
		if (fsem->fgasem_num >= 16) {
			error = ENOENT;
			break;
		}
		fsem->fgasem_val =
		    sc->sc_regs->mbox[fsem->fgasem_num] ? 0 : 1;
		break;
	default:
		error = EINVAL;
	}

	return (error);
}

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

	if (strcmp("fvme", ra->ra_name) || ca->ca_bustype != BUS_FGA)
		return (0);

	return (1);
}

const struct fvme_types {
	int data_cap;
	int addr_cap;
	const char *name;
	int bustype;
} fvme_types[] = {
	{0, 0, "a16d8", BUS_FGA_A16D8},
	{0, 1, "a24d8", BUS_FGA_A24D8},
	{0, 2, "a32d8", BUS_FGA_A32D8},
	{1, 0, "a16d16", BUS_FGA_A16D16},
	{1, 1, "a24d16", BUS_FGA_A24D16},
	{1, 2, "a32d16", BUS_FGA_A32D16},
	{2, 0, "a16d32", BUS_FGA_A16D32},
	{2, 1, "a24d32", BUS_FGA_A24D32},
	{2, 2, "a32d32", BUS_FGA_A32D32},
	{3, 0, "a16blt", -1},
	{3, 1, "a24blt", -1},
	{3, 2, "a32blt", -1},
	{4, 0, "a16mblt", -1},
	{4, 1, "a24mblt", -1},
	{4, 2, "a32mblt", -1},
	{-1, -1, "", -1},
};

void
fvmeattach(parent, self, aux)
	struct device *parent, *self;
	void *aux;
{
	struct confargs *ca = aux;
	const struct fvme_types *p;
	int dtype, atype;

	atype = (ca->ca_ra.ra_reg[1].rr_iospace & VME_MASTER_CAP_ADDR) >> 2;
	dtype = (ca->ca_ra.ra_reg[1].rr_iospace & VME_MASTER_CAP_DATA) >> 5;
	for (p = fvme_types; p->data_cap != -1; p++) {
		if (p->data_cap == dtype && p->addr_cap == atype)
			break;
	}
	if (p->data_cap == -1) {
		printf(" unknown addr/data capability\n");
		return;
	}
	printf(": %s", p->name);
	if (p->bustype == -1) {
		printf(" unsupported\n");
		return;
	}
	ca->ca_ra.ra_reg[1].rr_iospace = p->bustype;

	printf(" offset 0x%x len 0x%x\n", ca->ca_ra.ra_reg[1].rr_paddr,
	   ca->ca_ra.ra_reg[1].rr_len);

	(void)config_search(fvmescan, self, aux);
}

int
fvmescan(parent, child, aux)
	struct device *parent;
	void *child, *aux;
{
	struct cfdata *cf = child;
	struct confargs *ca = aux, oca;
	int plen, paddr;

	if (cf->cf_loc[0] == -1)
		return (0);

	if ((unsigned)cf->cf_loc[0] < (unsigned)ca->ca_ra.ra_reg[1].rr_paddr)
		return (0);

	paddr = cf->cf_loc[0] - (int)ca->ca_ra.ra_reg[1].rr_paddr;
	paddr = (int)ca->ca_ra.ra_reg[0].rr_paddr + paddr;
	plen = cf->cf_loc[0] - (int)ca->ca_ra.ra_reg[1].rr_paddr;
	plen = ca->ca_ra.ra_reg[1].rr_len - plen;

	oca.ca_bustype = ca->ca_ra.ra_reg[1].rr_iospace;
	oca.ca_offset = cf->cf_loc[0];

	oca.ca_ra.ra_nintr = 1;
	oca.ca_ra.ra_intr[0].int_pri = cf->cf_loc[1];
	oca.ca_ra.ra_intr[0].int_vec = cf->cf_loc[2];
	oca.ca_ra.ra_name = cf->cf_driver->cd_name;

	oca.ca_ra.ra_nreg = 1;
	oca.ca_ra.ra_reg[0].rr_paddr = (void *)paddr;
	oca.ca_ra.ra_reg[0].rr_iospace = ca->ca_ra.ra_reg[0].rr_iospace;
	oca.ca_ra.ra_reg[0].rr_len = plen;
	oca.ca_ra.ra_reg[0].rr_paddr =
	    mapdev(&oca.ca_ra.ra_reg[0], TMPMAP_VA, 0, NBPG);

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

	oca.ca_ra.ra_reg[0].rr_paddr = (void *)paddr;
	config_attach(parent, cf, &oca, fvmeprint);
	return (1);
}

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

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

int
fvmeintrestablish(dsc, vec, level, ih, name)
	struct device *dsc;
	int vec, level;
	struct intrhand *ih;
	const char *name;
{
	struct fga_softc *fsc = (struct fga_softc *)dsc->dv_parent;

	return (fga_intr_establish(fsc, vec, level, ih, name));
}


code:
/*	$OpenBSD: fgareg.h,v 1.2 2003/06/02 18:40:59 jason Exp $	*/

/*
 * Copyright (c) 1999 Jason L. Wright (jason@thought.net)
 * All rights reserved.
 *
 * This software was developed by Jason L. Wright under contract with
 * RTMX Incorporated (http://www.rtmx.com).
 *
 * 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.
 */

/*
 * Register definitions for Force Gate Array 5000
 * Definitions from: "Force Gate Array-5000 Technical Reference Manual"
 * revision 1, April 1995, Force Computers, Inc./GmbH.
 */

/*
 * FGA Register structure.
 * The register set takes up 512 bytes and is found in to sbus slot 5's
 * address space (you can change that).
 * Most of the bit registers use a negative logic sense: ie. writing
 * a zero means "setting the bit" and writing a one means "clearing"
 * the bit.
 */
struct fga_regs {
	volatile u_int32_t	sbus_base;	/* sbus base address reg */
	volatile u_int32_t	vme_range[16];	/* master range registers */
	volatile u_int8_t	_unused0[32];
	volatile u_int8_t	vme_master_cap[16];/* master capability */
	volatile u_int8_t	_unused1[8];
	volatile u_int8_t	sbus_ssel[8];	/* sbus slot select */
	volatile u_int8_t	_unused2[15];
	volatile u_int8_t	viack_emu1;	/* vme intr ack emulation */
	volatile u_int8_t	_unused3[1];
	volatile u_int8_t	viack_emu2;
	volatile u_int8_t	_unused4[1];
	volatile u_int8_t	viack_emu3;
	volatile u_int8_t	_unused5[1];
	volatile u_int8_t	viack_emu4;
	volatile u_int8_t	_unused6[1];
	volatile u_int8_t	viack_emu5;
	volatile u_int8_t	_unused7[1];
	volatile u_int8_t	viack_emu6;
	volatile u_int8_t	_unused8[1];
	volatile u_int8_t	viack_emu7;
	volatile u_int8_t	_unused9[16];
	volatile u_int8_t	sbus_cap;	/* sbus capabilities */
	volatile u_int8_t	sbus_retry_ctrl; /* sbus retry control */
	volatile u_int8_t	sbus_rerun_ctrl; /* sbus rerun control */
	volatile u_int8_t	sbus_cap2;	/* sbus capabilities 2 */
	volatile u_int32_t	swpar;		/* sbus write post err addr */
	volatile u_int32_t	slerr;		/* sbus late err addr */
	volatile u_int32_t	_unused10;
	volatile u_int8_t	vme_base;	/* vme slave base addr */
	volatile u_int8_t	vme_ext[3];	/* vme slave addr extension */
	volatile u_int32_t	sbus_range[3];	/* vme->sbus slave addr */
	volatile u_int16_t	ibox_addr;	/* ibox address */
	volatile u_int16_t	ibox_ctrl;	/* ibox control */
	volatile u_int8_t	fmb_ctrl;	/* FMB control reg */
	volatile u_int8_t	fmb_addr;	/* FMB addresss reg */
	volatile u_int8_t	_unused11[10];
	volatile u_int8_t	vme_cap;	/* vme capabilities */
	volatile u_int8_t	vmebus_handshake; /* vme handshake mode */
	volatile u_int8_t	_unused12[2];
	volatile u_int32_t	vwpar;		/* vme write post addr */
	volatile u_int8_t	_unused13[8];
	volatile u_int16_t	dma_ctrl;	/* dma control */
	volatile u_int8_t	dma_mode;	/* dma mode */
	volatile u_int8_t	dma_stat;	/* dma status */
	volatile u_int32_t	dma_src;	/* dma source address */
	volatile u_int32_t	dma_dst;	/* dma destination address */
	volatile u_int32_t	dma_captl;	/* dma capabilities/length */
	volatile u_int8_t	_unused14[32];
	volatile u_int8_t	mbox[16];	/* mailboxes */
	volatile u_int8_t	sem[48];	/* semaphores */
	volatile u_int8_t	_unused15[32];
	volatile u_int8_t	id[4];		/* revision/id register */
	volatile u_int8_t	gcsr;		/* global control/status */
	volatile u_int8_t	_unused16[3];
	volatile u_int8_t	reset_stat;	/* reset status */
	volatile u_int8_t	_unused17[24];
	volatile u_int8_t	virq_map[7];	/* vme->sbus irq mapping */
	volatile u_int8_t	mbox_irq_map[16];
	volatile u_int8_t	acfail_irq_map;
	volatile u_int8_t	sysfail_irq_map[2];
	volatile u_int8_t	abort_irq_map;
	volatile u_int8_t	dma_irq_map;
	volatile u_int8_t	wpe_irq_map;
	volatile u_int8_t	arb_irq_map;
	volatile u_int8_t	wdt_irq_map;
	volatile u_int8_t	slerr_irq_map;
	volatile u_int8_t	fmb_irq_map[2];
	volatile u_int8_t	ibox_irq_map;
	volatile u_int8_t	_unused18[20];
	volatile u_int16_t	mbox_stat;	/* mailbox status */
	volatile u_int8_t	_unused19[2];
	volatile u_int8_t	arb_ctrl;	/* arbitration control */
	volatile u_int8_t	req_ctrl;	/* vme request control */
	volatile u_int8_t	bus_ctrl;	/* vme bus control */
	volatile u_int8_t	_unused20[1];
	volatile u_int8_t	mcsr0;		/* misc control/status */
	volatile u_int8_t	_unused21[3];
	volatile u_int8_t	mcsr1;		/* misc control/status */
	volatile u_int8_t	wdt_restart;	/* watchdog restart */
	volatile u_int8_t	_unused22[2];
	volatile u_int32_t	intr_stat;	/* interrupt status */
	volatile u_int8_t	_unused23[20];
};

/* sbus_base: sbus base address register */
#define	SBUS_BASE_RMBA		0xffffe000	/* reg map base address */
#define	SBUS_BASE_RMSS		0x00000007	/* reg map slot select bits */

/* vme_range0..15: master range registers */
#define	VME_RANGE_VMRCC		0xfff80000	/* master range compare code */
#define	VME_RANGE_VMAE		0x00078000	/* master adr extension bits */
#define	VME_RANGE_VMAT		0x00007ff8	/* master adr xlation bits */
#define	VME_RANGE_WPEN		0x00000002	/* write posting enable */
#define	VME_RANGE_DECEN		0x00000001	/* range decoding enable */

/* vme_master_map0..15: master capability registers */
#define	VME_MASTER_CAP_DATA	0xe0		/* data capabilities */
#define	VME_MASTER_CAP_D8	0x00		/* vmebus D8 */
#define	VME_MASTER_CAP_D16	0x20		/* vmebus D16 */
#define	VME_MASTER_CAP_D32	0x40		/* vmebus D32 */
#define	VME_MASTER_CAP_DBLT	0x60		/* vmebus BLT */
#define	VME_MASTER_CAP_DMBLT	0x80		/* vmebus MBLT */
#define	VME_MASTER_CAP_ADDR	0x1c		/* addr capabilities */
#define	VME_MASTER_CAP_A16	0x00		/* vmebus A16 */
#define	VME_MASTER_CAP_A24	0x04		/* vmebus A24 */
#define	VME_MASTER_CAP_A32	0x08		/* vmebus A32 */
#define	FVME_MAX_RANGES		16		/* number of ranges avail */

/* sbus_ssel0..15: sbus slot select registers */
#define	SBUS_SSEL_X		0x70		/* slot select pins range X */
#define	SBUS_SSEL_X_SLOT1	0x00		/* sbus slot 1 */
#define	SBUS_SSEL_X_SLOT2	0x10		/* sbus slot 2 */
#define	SBUS_SSEL_X_SLOT3	0x20		/* sbus slot 3 */
#define	SBUS_SSEL_X_SLOT4	0x30		/* sbus slot 4 */
#define	SBUS_SSEL_X_SLOT5x	0x40		/* sbus slot 5? */
#define	SBUS_SSEL_X_SLOT5	0x50		/* sbus slot 5 */
#define	SBUS_SSEL_Y		0x07		/* slot select pins range X+1*/
#define	SBUS_SSEL_Y_SLOT1	0x00		/* sbus slot 1 */
#define	SBUS_SSEL_Y_SLOT2	0x01		/* sbus slot 2 */
#define	SBUS_SSEL_Y_SLOT3	0x02		/* sbus slot 3 */
#define	SBUS_SSEL_Y_SLOT4	0x03		/* sbus slot 4 */
#define	SBUS_SSEL_Y_SLOT5x	0x04		/* sbus slot 5? */
#define	SBUS_SSEL_Y_SLOT5	0x05		/* sbus slot 5 */

/* viack_emu1..7: iack emulation registers */
/* bits contain d00-d07 from VMEbus interrupter */

/* sbus_cap: sbus capability register */
#define	SBUS_CAP_BURSTMASK	0xc0		/* dma burst size mask */
#define	SBUS_CAP_BURST_64	0xc0		/* 64 byte burst */
#define	SBUS_CAP_BURST_32	0x80		/* 32 byte burst */
#define	SBUS_CAP_BURST_16	0x40		/* 16 byte burst */
#define	SBUS_CAP_BURST_8	0x00		/* 8 byte burst */
#define	SBUS_CAP_READSTOPMASK	0x30		/* master read stop point */
#define	SBUS_CAP_READSTOP_64	0x30		/* stop at 64 byte boundary */
#define	SBUS_CAP_READSTOP_32	0x20		/* stop at 32 byte boundary */
#define	SBUS_CAP_READSTOP_16	0x10		/* stop at 16 byte boundary */
#define	SBUS_CAP_READSTOP_8	0x00		/* stop at 8 byte boundary */
#define	SBUS_CAP_BURSTDIS	0x08		/* disable sbus bursts */
#define	SBUS_CAP_HIDDENARBDIS	0x04		/* disable sbus hidden arb */
#define	SBUS_CAP_SPLITFLOW	0x02		/* disable flow through */

/* sbus_retry_ctrl: sbus retry register */
/* clock cycles with no acknowledge */

/* sbus_rerun_ctrl: sbus rerun limit register */
/* number of times to reruns to try on the bus */

/* swpar: sbus write posting error address register */
/* virtual sbus transfer address that was ack'd with an error */

/* slerr: sbus late error address register */
/* virtual sbus address that resulted in a late transfer */

/* vme_base: VMEbus base address register */
#define VME_BASE_RMVBA		0xfe		/* reg map base address */
#define	VME_BASE_RMACCEN	0x01		/* reg remote access enable */

/* vme_ext0..2: slave address extension registers */
/* extensions of A24 VMEbus address to 32bit sbus address (msb) */

/* sbus_range0..2: slave range registers */
#define	SBUS_RANGE_VSRCC	0xfff00000	/* slave range compare code */
#define	SBUS_RANGE_VSAT		0x000ffe00	/* slave address translation */
#define	SBUS_RANGE_A32DIS	0x00000004	/* disable A32 (enable A24) */
#define	SBUS_RANGE_WPDIS	0x00000002	/* disable write posting */
#define	SBUS_RANGE_DECDIS	0x00000001	/* disable encoding */

/* ibox_addr: IBOX address register */
/* address within VME A16 space where the IBOX is accessed */

/* ibox_ctrl: IBOX control register */
#define	IBOX_CTRL_DIS		0x01		/* disable ibox */

/* fmb_ctrl: force message broadcast control register */
#define	FMB_CTRL_SELAM		0x80		/* supervisor/user access */
#define	FMB_CTRL_DISCH1		0x40		/* disable channel 1 */
#define	FMB_CTRL_DISCH2		0x20		/* disable channel 2 */
#define	FMB_CTRL_SLOTID		0x1f		/* slot id: 1-15 */

/* vme_cap: global master capability register */
#define	VME_CAP_NPRV		0x80		/* supervisor access */

/* vmebus_handshake: VMEbus handshake configuration register */
#define	VME_HANDSHAKE_DISSGLE	0x80		/* disable glitch filter */
#define	VME_HANDSHAKE_DISASFAST	0x40		/* disable fast AS handshake */
#define	VME_HANDSHAKE_DISDS	0x20		/* disable fast data strobe */

/* vwpar: VMEbus write posting address register */
/* contains address ack'd with a BERR from the VME bus */

/* dma_ctrl: dma control register */
#define	DMA_CTRL_DMAEN		0x80		/* enable (start) dma */
#define	DMA_CTRL_DMADIS		0x40		/* disable dma transaction */
#define	DMA_CTRL_DMAHLT		0x20		/* stop dma transaction */
#define	DMA_CTRL_DMARESU	0x10		/* resume dma transaction */

/* dma_mode: dma mode register */
#define	DMA_MODE_DMASB		0x80		/* single buffer mode */
#define	DMA_MODE_DMANRTRY	0x40		/* error on retry */

/* dma_stat: dma status register */
#define	DMA_STAT_DMARUN		0x80		/* dma task is running */
#define	DMA_STAT_DMAWT		0x40		/* dma task is halted */
#define	DMA_STAT_DMANT		0x20		/* dma task successful */
#define	DMA_STAT_ERRMASK	0x18		/* dma error mask */
#define	DMA_STAT_ERR_SRC	0x00		/* error on source bus */
#define	DMA_STAT_ERR_DST	0x08		/* error on destination bus */
#define	DMA_STAT_ERR_NONE	0x10		/* no error termination */
#define	DMA_STAT_ERR_NOERROR	0x18		/* no error termination */

/* dma_src: dma source address register */
#define	DMA_SRC_ADDR		0xfffffffc	/* source address */
#define	DMA_SRC_VME		0x00000002	/* 0=vme, 1=sbus */

/* dma_dst: dma destination address register */
#define	DMA_DST_ADDR		0xfffffffc	/* destination address */
#define	DMA_DST_VME		0x00000002	/* 0=vme, 1=sbus */

/* dma_captl: dma capability/transfer length */
#define	DMA_CAPTL_SCAPD_MASK	0xe0000000	/* src data capability */
#define	DMA_CAPTL_SCAPD_D8	0x00000000	/* D8 slave */
#define	DMA_CAPTL_SCAPD_D16	0x20000000	/* D16 slave */
#define	DMA_CAPTL_SCAPD_D32	0x40000000	/* D32 slave */
#define	DMA_CAPTL_SCAPD_BLT	0x60000000	/* BLT slave */
#define	DMA_CAPTL_SCAPD_MBLT	0x80000000	/* MBLT slave */
#define	DMA_CAPTL_SCAPA_MASK	0x1c000000	/* src addr capability */
#define	DMA_CAPTL_SCAPA_A16	0x00000000	/* A16 slave */
#define	DMA_CAPTL_SCAPA_A24	0x04000000	/* A24 slave */
#define	DMA_CAPTL_SCAPA_A32	0x08000000	/* A32 slave */
#define	DMA_CAPTL_DCAPD_MASK	0x03800000	/* dst data capability */

/* mbox0..15: mailbox registers */
#define	MBOX_SEM		0x80		/* semaphore bit */

/* sem0..47: semaphore registers */
#define	SEM_SEM			0x80		/* semaphore bit */

/* gcsr: global control and status register */
#define	GCSR_SETSYSFAIL		0x80		/* assert SYSFAIL* signal */
#define	GCSR_ENSYSFAIL		0x40		/* enable SYSFAIL* output */
#define	GCSR_SYSFAIL		0x20		/* SYSFAIL* input status */
#define	GCSR_RESET		0x10		/* software reset */
#define	GCSR_ACFAIL		0x08		/* ACFAIL input status */
#define	GCSR_DISVDR		0x04		/* disable VME DTB drivers */
#define	GCSR_ENSYSCON		0x02		/* enable system controller */

/* reset_stat: reset status register */
#define	RESET_STAT_SBUS_RESET	0x80		/* sbus has been reset */
#define	RESET_STAT_VME_SYSRES	0x40		/* vmebus has been reset */
#define	RESET_STAT_WDT_RESET	0x20		/* watchdog has triggered */
#define	RESET_STAT_SYSRES_CALL	0x04		/* sysreset in mcsr0 set */
#define	RESET_STAT_RESET_CALL	0x02		/* reset in mcsr0 set */
#define	RESET_STAT_LOCRES_CALL	0x01		/* reset in ccsr set */

/* *irq_map: interrupt request mapping registers */
#define	IRQ_MAP_ENABLE		0x08		/* enable irq */
#define	IRQ_MAP_INT_MASK	0x07		/* irq mapping mask */
#define	IRQ_MAP_INT		0x00		/* NMI */
#define	IRQ_MAP_SINT1		0x01		/* sbus pri 1 */
#define	IRQ_MAP_SINT2		0x02		/* sbus pri 2 */
#define	IRQ_MAP_SINT3		0x03		/* sbus pri 3 */
#define	IRQ_MAP_SINT4		0x04		/* sbus pri 4 */
#define	IRQ_MAP_SINT5		0x05		/* sbus pri 5 */
#define	IRQ_MAP_SINT6		0x06		/* sbus pri 6 */
#define	IRQ_MAP_SINT7		0x07		/* sbus pri 7 */

/* mbox_stat: mailbox status interrupt status register */
/* 1 bit for each mailbox, 0 = interrupt pending, 1 = no interrupt pending */

/* arb_ctrl: arbitration control register */
#define	ARB_CTRL_MASK		0xc0		/* control mask */
#define	ARB_CTRL_PRIORITY	0xc0		/* priority mode */
#define	ARB_CTRL_ROBIN		0x40		/* round robin mode */
#define	ARB_CTRL_PRIROBIN	0x80		/* priority round robin mode */

/* req_ctrl: VMEbus request control register */
#define	REQ_CTRL_FM		0x80		/* 0=fair,1=demand mode */
#define	REQ_CTRL_RM_MASK	0x70		/* release mode mask */
#define	REQ_CTRL_RM_ROR		0x30		/* release on request */
#define	REQ_CTRL_RM_ROC		0x40		/* release on bus clear */
#define	REQ_CTRL_RM_RAT		0x60		/* release after timeout */
#define	REQ_CTRL_RM_RWD		0x70		/* release when done */
#define	REQ_CTRL_REC		0x08		/* 0=begin,1=end of cycle */
#define	REQ_CTRL_RL_MASK	0x06		/* request level mask */
#define	REQ_CTRL_RL_BR3		0x06		/* br3 priority */
#define	REQ_CTRL_RL_BR2		0x04		/* br2 priority */
#define	REQ_CTRL_RL_BR1		0x02		/* br1 priority */
#define	REQ_CTRL_RL_BR0		0x00		/* br0 priority */
#define	REQ_CTRL_GLFI		0x01		/* enable bbsy glitch filter */

/* bus_ctrl: VMEbus capture register */
#define	BUS_CTRL_BCAP		0x80		/* request and keep bus */
#define	BUS_CTRL_OWN		0x40		/* do we own the bus? */

/* mcsr0: miscellaneous control and status register 0 */
#define	MCSR0_ABORTSW		0x80		/* status of abort switch */
#define	MCSR0_SCON		0x40		/* status of SCON input */
#define	MCSR0_SYSRESET		0x20		/* assert SYSRESET* */
#define	MCSR0_RESET		0x10		/* software reset fga5000 */
#define	MCSR0_ENA_VME_TIMEOUT	0x08		/* enable VME timeout */
#define	MCSR0_VME_TIMEOUT_MASK	0x06		/* VME transaction timeout */
#define	MCSR0_VME_TIMEOUT_32	0x02		/* 32 usec */
#define	MCSR0_VME_TIMEOUT_128	0x04		/* 128 usec */
#define	MCSR0_VME_TIMEOUT_512	0x06		/* 512 usec */
#define	MCSR0_SYSRESET_IN	0x01		/* enable SYSRESET input */

/* mcsr1: miscellaneous control and status register 1 */
#define	MCSR1_ENAWDT		0x80		/* enable watchdog timer */
#define	MCSR1_TIMEOUT_MASK	0x70		/* watchdog timeout mask */
#define	MCSR1_TIMEOUT_408MS	0x00		/* 408 msec */
#define	MCSR1_TIMEOUT_168S	0x10		/* 1.68 sec */
#define	MCSR1_TIMEOUT_67S	0x20		/* 6.7 sec */
#define	MCSR1_TIMEOUT_268S	0x30		/* 26.8 sec */
#define	MCSR1_TIMEOUT_1M48S	0x40		/* 1 min 48 sec */
#define	MCSR1_TIMEOUT_7M9S	0x50		/* 7 min 9 sec */
#define	MCSR1_TIMEOUT_28M38S	0x60		/* 28 min 38 sec */
#define	MCSR1_TIMEOUT_1H54M	0x70		/* 1 hour 54 min */
#define	MCSR1_IRQ_FREEZE	0x08		/* freeze irq map regs */

/* wdt_restart: watchdog timer restart register */
/* any read/write resets the watchdog timer */

/* intr_stat: interrupt status register */
#define	INTR_STAT_ACFAIL	0x80000000	/* acfail pending */
#define	INTR_STAT_SYSFAILASSERT	0x40000000	/* sysfail assert pending */
#define	INTR_STAT_SYSFAILNEGATE	0x20000000	/* sysfail negate pending */
#define	INTR_STAT_ABORT		0x10000000	/* abort pending */
#define	INTR_STAT_ARBTIMEOUT	0x08000000	/* arbitration timeout */
#define	INTR_STAT_MAILBOX	0x04000000	/* mailbox intr pending */
#define	INTR_STAT_SBUS_WPERR	0x02000000	/* sbus wperr pending */
#define	INTR_STAT_VME_WPERR	0x01000000	/* vme wperr pending */
#define	INTR_STAT_DMATERM	0x00800000	/* dma finished */
#define	INTR_STAT_WDT		0x00400000	/* watchdog half timeout */
#define	INTR_STAT_SLERR		0x00200000	/* sbus late error pending */
#define	INTR_STAT_IBOX		0x00100000	/* ibox pending */
#define	INTR_STAT_FMB0		0x00080000	/* fmb channel 0 pending */
#define	INTR_STAT_FMB1		0x00040000	/* fmb channel 1 pending */
#define	INTR_STAT_VMEIRQ7	0x00000080	/* vme irq 7 pending */
#define	INTR_STAT_VMEIRQ6	0x00000040	/* vme irq 6 pending */
#define	INTR_STAT_VMEIRQ5	0x00000020	/* vme irq 5 pending */
#define	INTR_STAT_VMEIRQ4	0x00000010	/* vme irq 4 pending */
#define	INTR_STAT_VMEIRQ3	0x00000008	/* vme irq 3 pending */
#define	INTR_STAT_VMEIRQ2	0x00000004	/* vme irq 2 pending */
#define	INTR_STAT_VMEIRQ1	0x00000002	/* vme irq 1 pending */


code:
/*	$OpenBSD: fgavar.h,v 1.4 2004/09/29 07:35:11 miod Exp $	*/

/*
 * Copyright (c) 1999 Jason L. Wright (jason@thought.net)
 * All rights reserved.
 *
 * This software was developed by Jason L. Wright under contract with
 * RTMX Incorporated (http://www.rtmx.com).
 *
 * 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.
 */

int fvmeintrestablish(struct device *, int, int, struct intrhand *,
	    const char *);


code:
/*	$OpenBSD: flash.c,v 1.7 2015/02/10 23:50:29 miod Exp $	*/

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

/*
 * Driver for the flash memory found on FORCE CPU-5V boards.
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/errno.h>
#include <sys/ioctl.h>
#include <sys/syslog.h>
#include <sys/device.h>
#include <sys/malloc.h>

#include <machine/autoconf.h>
#include <sparc/cpu.h>
#include <sparc/sparc/cpuvar.h>

int	flashmatch(struct device *, void *, void *);
void	flashattach(struct device *, struct device *, void *);

int	flashopen(dev_t, int, int, struct proc *p);
int	flashclose(dev_t, int, int, struct proc *p);
int	flashread(dev_t, struct uio *, int);
int	flashwrite(dev_t, struct uio *, int);
int	flashrw(dev_t, struct uio *, int);
int	flashioctl(dev_t, u_long, caddr_t, int, struct proc *);

/*
 * We see the flash-memory in 512k windows.  The current window is
 * changed in the sysconfig registers (FMPCR1), see scf.c.
 */
#define	FLASH_REGS_SIZE		0x80000

struct flash_regs {
	u_int8_t		regs[0x80000];
};

struct flash_softc {
	struct device		sc_dv;
	struct flash_regs	*sc_regs;
	int			sc_node;
	int			sc_open;
};

struct cfattach flash_ca = {
	sizeof (struct flash_softc), flashmatch, flashattach
};

struct cfdriver flash_cd = {
	NULL, "flash", DV_DULL
};

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

	if (strcmp("flash-memory", ra->ra_name))
		return (0);
	return (1);
}

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

	/* map registers */
	if (ca->ca_ra.ra_nreg != 1) {
		printf(": expected 1 register, got %d\n", ca->ca_ra.ra_nreg);
		return;
	}
	sc->sc_regs = mapiodev(&(ca->ca_ra.ra_reg[0]), 0,
			ca->ca_ra.ra_reg[0].rr_len);

	sc->sc_node = ca->ca_ra.ra_node;

	printf(": window 0x%x\n", ca->ca_ra.ra_reg[0].rr_len);
}

int
flashopen(dev, flags, mode, p)
	dev_t dev;
	int flags;
	int mode;
	struct proc *p;
{
	struct flash_softc *sc;
	int card = 0;

	if (card >= flash_cd.cd_ndevs)
		return (ENXIO);
	sc = flash_cd.cd_devs[card];
	if (sc == NULL)
		return (ENXIO);
	if (sc->sc_open)
		return (EBUSY);
	sc->sc_open = 1;
	return (0);
}

int
flashclose(dev, flags, mode, p)
	dev_t dev;
	int flags;
	int mode;
	struct proc *p;
{
	struct flash_softc *sc = flash_cd.cd_devs[0];
	sc->sc_open = 0;
	return (0);
}

int
flashwrite(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	return (flashrw(dev, uio, flags));
}

int
flashread(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	return (flashrw(dev, uio, flags));
}

int
flashrw(dev, uio, flags)
	dev_t dev;
	struct uio *uio;
	int flags;
{
	struct flash_softc *sc = flash_cd.cd_devs[0];
	size_t cnt;
	off_t off;

	off = uio->uio_offset;
	if (off < 0 || off >= FLASH_REGS_SIZE)
		return (EFAULT);

	cnt = uio->uio_resid;
	if (cnt > (FLASH_REGS_SIZE - off))
		cnt = FLASH_REGS_SIZE - off;

	return (uiomove(&sc->sc_regs->regs[0] + off, cnt, uio));
}

int
flashioctl(dev, cmd, data, flags, p)
	dev_t dev;
	u_long cmd;
	caddr_t data;
	int flags;
	struct proc *p;
{
	return (EINVAL);
}