Home | History | Annotate | Line # | Download | only in dev
fd.c revision 1.18
      1 /*	$NetBSD: fd.c,v 1.18 1996/03/27 10:08:28 leo Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1995 Leo Weppelman.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *      This product includes software developed by Leo Weppelman.
     18  * 4. The name of the author may not be used to endorse or promote products
     19  *    derived from this software without specific prior written permission
     20  *
     21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * This file contains a driver for the Floppy Disk Controller (FDC)
     35  * on the Atari TT. It uses the WD 1772 chip, modified for steprates.
     36  *
     37  * The ST floppy disk controller shares the access to the DMA circuitry
     38  * with other devices. For this reason the floppy disk controller makes
     39  * use of some special DMA accessing code.
     40  *
     41  * Interrupts from the FDC are in fact DMA interrupts which get their
     42  * first level handling in 'dma.c' . If the floppy driver is currently
     43  * using DMA the interrupt is signalled to 'fdcint'.
     44  *
     45  * TODO:
     46  *   - Test it with 2 drives (I don't have them)
     47  *   - Test it with an HD-drive (Don't have that either)
     48  *   - Finish ioctl's
     49  */
     50 
     51 #include <sys/param.h>
     52 #include <sys/systm.h>
     53 #include <sys/kernel.h>
     54 #include <sys/malloc.h>
     55 #include <sys/buf.h>
     56 #include <sys/proc.h>
     57 #include <sys/device.h>
     58 #include <sys/ioctl.h>
     59 #include <sys/fcntl.h>
     60 #include <sys/conf.h>
     61 #include <sys/disklabel.h>
     62 #include <sys/disk.h>
     63 #include <sys/dkbad.h>
     64 #include <atari/atari/device.h>
     65 #include <machine/disklabel.h>
     66 #include <machine/iomap.h>
     67 #include <machine/mfp.h>
     68 #include <machine/dma.h>
     69 #include <machine/video.h>
     70 #include <atari/dev/ym2149reg.h>
     71 #include <atari/dev/fdreg.h>
     72 
     73 /*
     74  * Be verbose for debugging
     75  */
     76 /*#define FLP_DEBUG	1 */
     77 
     78 #define	FDC_MAX_DMA_AD	0x1000000	/* No DMA possible beyond	*/
     79 
     80 /* Parameters for the disk drive. */
     81 #define SECTOR_SIZE	512	/* physical sector size in bytes	*/
     82 #define NR_DRIVES	2	/* maximum number of drives		*/
     83 #define NR_TYPES	3	/* number of diskette/drive combinations*/
     84 #define MAX_ERRORS	10	/* how often to try rd/wt before quitting*/
     85 #define STEP_DELAY	6000	/* 6ms (6000us) delay after stepping	*/
     86 
     87 
     88 #define	INV_TRK		32000	/* Should fit in unsigned short		*/
     89 #define	INV_PART	NR_TYPES
     90 
     91 /*
     92  * Driver states
     93  */
     94 #define	FLP_IDLE	0x00	/* floppy is idle			*/
     95 #define	FLP_MON		0x01	/* idle with motor on			*/
     96 #define	FLP_STAT	0x02	/* determine floppy status		*/
     97 #define	FLP_XFER	0x04	/* read/write data from floppy		*/
     98 
     99 /*
    100  * Timer delay's
    101  */
    102 #define	FLP_MONDELAY	(3 * hz)	/* motor-on delay		*/
    103 #define	FLP_XFERDELAY	(2 * hz)	/* timeout on transfer		*/
    104 
    105 /*
    106  * The density codes
    107  */
    108 #define	FLP_DD		0		/* Double density		*/
    109 #define	FLP_HD		1		/* High density			*/
    110 
    111 
    112 #define	b_block		b_resid		/* FIXME: this is not the place	*/
    113 
    114 /*
    115  * Global data for all physical floppy devices
    116  */
    117 static short	selected = 0;		/* drive/head currently selected*/
    118 static short	motoron  = 0;		/* motor is spinning		*/
    119 static short	nopens   = 0;		/* Number of opens executed	*/
    120 
    121 static short	fd_state = FLP_IDLE;	/* Current driver state		*/
    122 static int	lock_stat= 0;		/* dma locking status		*/
    123 static short	fd_cmd   = 0;		/* command being executed	*/
    124 static char	*fd_error= NULL;	/* error from fd_xfer_ok()	*/
    125 
    126 /*
    127  * Private per device data
    128  */
    129 struct fd_softc {
    130 	struct device	sc_dv;		/* generic device info		*/
    131 	struct disk	dkdev;		/* generic disk info		*/
    132 	struct buf	bufq;		/* queue of buf's		*/
    133 	int		unit;		/* unit for atari controlling hw*/
    134 	int		nheads;		/* number of heads in use	*/
    135 	int		nsectors;	/* number of sectors/track	*/
    136 	int		density;	/* density code			*/
    137 	int		nblocks;	/* number of blocks on disk	*/
    138 	int		curtrk;		/* track head positioned on	*/
    139 	short		flags;		/* misc flags			*/
    140 	short		part;		/* Current open partition	*/
    141 	int		sector;		/* logical sector for I/O	*/
    142 	caddr_t		io_data;	/* KVA for data transfer	*/
    143 	int		io_bytes;	/* bytes left for I/O		*/
    144 	int		io_dir;		/* B_READ/B_WRITE		*/
    145 	int		errcnt;		/* current error count		*/
    146 	u_char		*bounceb;	/* Bounce buffer		*/
    147 
    148 };
    149 
    150 /*
    151  * Flags in fd_softc:
    152  */
    153 #define FLPF_NOTRESP	0x001		/* Unit not responding		*/
    154 #define FLPF_ISOPEN	0x002		/* Unit is open			*/
    155 #define FLPF_SPARE	0x004		/* Not used			*/
    156 #define FLPF_HAVELAB	0x008		/* We have a valid label	*/
    157 #define FLPF_BOUNCE	0x010		/* Now using the bounce buffer	*/
    158 #define FLPF_WRTPROT	0x020		/* Unit is write-protected	*/
    159 #define FLPF_EMPTY	0x040		/* Unit is empty		*/
    160 #define FLPF_INOPEN	0x080		/* Currently being opened	*/
    161 #define FLPF_GETSTAT	0x100		/* Getting unit status		*/
    162 
    163 struct fd_types {
    164 	int		nheads;		/* Heads in use			*/
    165 	int		nsectors;	/* sectors per track		*/
    166 	int		nblocks;	/* number of blocks		*/
    167 	int		density;	/* density code			*/
    168 } fdtypes[NR_TYPES] = {
    169 		{ 1,  9,  720 , FLP_DD },	/* 360  Kb	*/
    170 		{ 2,  9, 1440 , FLP_DD },	/* 720  Kb	*/
    171 		{ 2, 18, 2880 , FLP_HD },	/* 1.44 Mb	*/
    172 };
    173 
    174 typedef void	(*FPV) __P((void *));
    175 
    176 /*
    177  * {b,c}devsw[] function prototypes
    178  */
    179 dev_type_open(Fdopen);
    180 dev_type_close(fdclose);
    181 dev_type_read(fdread);
    182 dev_type_write(fdwrite);
    183 dev_type_ioctl(fdioctl);
    184 dev_type_size(fdsize);
    185 dev_type_dump(fddump);
    186 
    187 /*
    188  * Private drive functions....
    189  */
    190 static void	fdstart __P((struct fd_softc *));
    191 static void	fddone __P((struct fd_softc *));
    192 static void	fdstatus __P((struct fd_softc *));
    193 static void	fd_xfer __P((struct fd_softc *));
    194 static void	fdcint __P((struct fd_softc *));
    195 static int	fd_xfer_ok __P((struct fd_softc *));
    196 static void	fdmotoroff __P((struct fd_softc *));
    197 static void	fdminphys __P((struct buf *));
    198 static void	fdtestdrv __P((struct fd_softc *));
    199 static int	fdgetdisklabel __P((struct fd_softc *, dev_t));
    200 static int	fdselect __P((int, int, int));
    201 static void	fddeselect __P((void));
    202 static void	fdmoff __P((struct fd_softc *));
    203        u_char	read_fdreg __P((u_short));
    204        void	write_fdreg __P((u_short, u_short));
    205        u_char	read_dmastat __P((void));
    206 
    207 extern __inline__ u_char read_fdreg(u_short regno)
    208 {
    209 	DMA->dma_mode = regno;
    210 	return(DMA->dma_data);
    211 }
    212 
    213 extern __inline__ void write_fdreg(u_short regno, u_short val)
    214 {
    215 	DMA->dma_mode = regno;
    216 	DMA->dma_data = val;
    217 }
    218 
    219 extern __inline__ u_char read_dmastat(void)
    220 {
    221 	DMA->dma_mode = FDC_CS | DMA_SCREG;
    222 	return(DMA->dma_stat);
    223 }
    224 
    225 /*
    226  * Autoconfig stuff....
    227  */
    228 static int	fdcmatch __P((struct device *, void *, void *));
    229 static int	fdcprint __P((void *, char *));
    230 static void	fdcattach __P((struct device *, struct device *, void *));
    231 
    232 struct cfattach fdc_ca = {
    233 	sizeof(struct device), fdcmatch, fdcattach
    234 };
    235 
    236 struct cfdriver fdc_cd = {
    237 	NULL, "fdc", DV_DULL, NULL, 0
    238 };
    239 
    240 static int
    241 fdcmatch(pdp, match, auxp)
    242 struct device	*pdp;
    243 void		*match, *auxp;
    244 {
    245 	struct cfdata *cfp = match;
    246 
    247 	if(strcmp("fdc", auxp) || cfp->cf_unit != 0)
    248 		return(0);
    249 	return(1);
    250 }
    251 
    252 static void
    253 fdcattach(pdp, dp, auxp)
    254 struct device	*pdp, *dp;
    255 void		*auxp;
    256 {
    257 	extern struct cfdriver fd_cd;
    258 	struct fd_softc	fdsoftc;
    259 	int		i, nfound, first_found;
    260 
    261 	nfound = first_found = 0;
    262 	printf("\n");
    263 	fddeselect();
    264 	for(i = 0; i < NR_DRIVES; i++) {
    265 
    266 		/*
    267 		 * Test if unit is present
    268 		 */
    269 		fdsoftc.unit  = i;
    270 		fdsoftc.flags = 0;
    271 		st_dmagrab((dma_farg)fdcint, (dma_farg)fdtestdrv, &fdsoftc,
    272 								&lock_stat, 0);
    273 		st_dmafree(&fdsoftc, &lock_stat);
    274 
    275 		if(!(fdsoftc.flags & FLPF_NOTRESP)) {
    276 			if(!nfound)
    277 				first_found = i;
    278 			nfound++;
    279 			config_found(dp, (void*)i, fdcprint);
    280 		}
    281 	}
    282 
    283 	if(nfound) {
    284 
    285 		/*
    286 		 * Make sure motor will be turned of when a floppy is
    287 		 * inserted in the first selected drive.
    288 		 */
    289 		fdselect(first_found, 0, FLP_DD);
    290 		fd_state = FLP_MON;
    291 		timeout((FPV)fdmotoroff, (void*)getsoftc(fd_cd,first_found), 0);
    292 
    293 		/*
    294 		 * enable disk related interrupts
    295 		 */
    296 		MFP->mf_ierb  |= IB_DINT;
    297 		MFP->mf_iprb  &= ~IB_DINT;
    298 		MFP->mf_imrb  |= IB_DINT;
    299 	}
    300 }
    301 
    302 static int
    303 fdcprint(auxp, pnp)
    304 void	*auxp;
    305 char	*pnp;
    306 {
    307 	return(UNCONF);
    308 }
    309 
    310 static int	fdmatch __P((struct device *, void *, void *));
    311 static void	fdattach __P((struct device *, struct device *, void *));
    312 	   void fdstrategy __P((struct buf *));
    313 struct dkdriver fddkdriver = { fdstrategy };
    314 
    315 struct cfattach fd_ca = {
    316 	sizeof(struct fd_softc), fdmatch, fdattach
    317 };
    318 
    319 struct cfdriver fd_cd = {
    320 	NULL, "fd", DV_DISK, NULL, 0
    321 };
    322 
    323 static int
    324 fdmatch(pdp, match, auxp)
    325 struct device	*pdp;
    326 void		*match, *auxp;
    327 {
    328 	return(1);
    329 }
    330 
    331 static void
    332 fdattach(pdp, dp, auxp)
    333 struct device	*pdp, *dp;
    334 void		*auxp;
    335 {
    336 	struct fd_softc	*sc;
    337 
    338 	sc = (struct fd_softc *)dp;
    339 
    340 	printf("\n");
    341 
    342 	/*
    343 	 * Initialize and attach the disk structure.
    344 	 */
    345 	sc->dkdev.dk_name = sc->sc_dv.dv_xname;
    346 	sc->dkdev.dk_driver = &fddkdriver;
    347 	disk_attach(&sc->dkdev);
    348 }
    349 
    350 int
    351 fdioctl(dev, cmd, addr, flag, p)
    352 dev_t		dev;
    353 u_long		cmd;
    354 int		flag;
    355 caddr_t		addr;
    356 struct proc	*p;
    357 {
    358 	struct fd_softc *sc;
    359 
    360 	sc = getsoftc(fd_cd, DISKUNIT(dev));
    361 
    362 	if((sc->flags & FLPF_HAVELAB) == 0)
    363 		return(EBADF);
    364 
    365 	switch(cmd) {
    366 		case DIOCSBAD:
    367 			return(EINVAL);
    368 		case DIOCGDINFO:
    369 			*(struct disklabel *)addr = *(sc->dkdev.dk_label);
    370 			return(0);
    371 		case DIOCGPART:
    372 			((struct partinfo *)addr)->disklab =
    373 				sc->dkdev.dk_label;
    374 			((struct partinfo *)addr)->part =
    375 			      &sc->dkdev.dk_label->d_partitions[DISKPART(dev)];
    376 			return(0);
    377 #ifdef notyet /* XXX LWP */
    378 		case DIOCSRETRIES:
    379 		case DIOCSSTEP:
    380 		case DIOCSDINFO:
    381 		case DIOCWDINFO:
    382 		case DIOCWLABEL:
    383 #endif /* notyet */
    384 	}
    385 	return(ENOTTY);
    386 }
    387 
    388 /*
    389  * Open the device. If this is the first open on both the floppy devices,
    390  * intialize the controller.
    391  * Note that partition info on the floppy device is used to distinguise
    392  * between 780Kb and 360Kb floppy's.
    393  *	partition 0: 360Kb
    394  *	partition 1: 780Kb
    395  */
    396 int
    397 Fdopen(dev, flags, devtype, proc)
    398 dev_t		dev;
    399 int		flags, devtype;
    400 struct proc	*proc;
    401 {
    402 	struct fd_softc	*sc;
    403 	int		sps;
    404 
    405 #ifdef FLP_DEBUG
    406 	printf("Fdopen dev=0x%x\n", dev);
    407 #endif
    408 
    409 	if(DISKPART(dev) >= NR_TYPES)
    410 		return(ENXIO);
    411 
    412 	if((sc = getsoftc(fd_cd, DISKUNIT(dev))) == NULL)
    413 		return(ENXIO);
    414 
    415 	/*
    416 	 * If no floppy currently open, reset the controller and select
    417 	 * floppy type.
    418 	 */
    419 	if(!nopens) {
    420 
    421 #ifdef FLP_DEBUG
    422 		printf("Fdopen device not yet open\n");
    423 #endif
    424 		nopens++;
    425 		write_fdreg(FDC_CS, IRUPT);
    426 		delay(40);
    427 	}
    428 
    429 	/*
    430 	 * Sleep while other process is opening the device
    431 	 */
    432 	sps = splbio();
    433 	while(sc->flags & FLPF_INOPEN)
    434 		tsleep((caddr_t)sc, PRIBIO, "Fdopen", 0);
    435 	splx(sps);
    436 
    437 	if(!(sc->flags & FLPF_ISOPEN)) {
    438 		/*
    439 		 * Initialise some driver values.
    440 		 */
    441 		int	part = DISKPART(dev);
    442 		void	*addr;
    443 
    444 		sc->bufq.b_actf = NULL;
    445 		sc->unit        = DISKUNIT(dev);
    446 		sc->part        = part;
    447 		sc->nheads	= fdtypes[part].nheads;
    448 		sc->nsectors	= fdtypes[part].nsectors;
    449 		sc->nblocks     = fdtypes[part].nblocks;
    450 		sc->density	= fdtypes[part].density;
    451 		sc->curtrk	= INV_TRK;
    452 		sc->sector	= 0;
    453 		sc->errcnt	= 0;
    454 		sc->bounceb	= (u_char*)alloc_stmem(SECTOR_SIZE, &addr);
    455 		if(sc->bounceb == NULL)
    456 			return(ENOMEM); /* XXX */
    457 
    458 		/*
    459 		 * Go get write protect + loaded status
    460 		 */
    461 		sc->flags |= FLPF_INOPEN|FLPF_GETSTAT;
    462 		sps = splbio();
    463 		st_dmagrab((dma_farg)fdcint, (dma_farg)fdstatus, sc,
    464 								&lock_stat, 0);
    465 		while(sc->flags & FLPF_GETSTAT)
    466 			tsleep((caddr_t)sc, PRIBIO, "Fdopen", 0);
    467 		splx(sps);
    468 		wakeup((caddr_t)sc);
    469 
    470 		if((sc->flags & FLPF_WRTPROT) && (flags & FWRITE)) {
    471 			sc->flags = 0;
    472 			return(EPERM);
    473 		}
    474 		if(sc->flags & FLPF_EMPTY) {
    475 			sc->flags = 0;
    476 			return(ENXIO);
    477 		}
    478 		sc->flags &= ~(FLPF_INOPEN|FLPF_GETSTAT);
    479 		sc->flags |= FLPF_ISOPEN;
    480 	}
    481 	else {
    482 		/*
    483 		 * Multiply opens are granted when accessing the same type of
    484 		 * floppy (eq. the same partition).
    485 		 */
    486 		if(sc->part != DISKPART(dev))
    487 			return(ENXIO);	/* XXX temporarely out of business */
    488 	}
    489 	fdgetdisklabel(sc, dev);
    490 #ifdef FLP_DEBUG
    491 	printf("Fdopen open succeeded on type %d\n", sc->part);
    492 #endif
    493 	return (0);
    494 }
    495 
    496 int
    497 fdclose(dev, flags, devtype, proc)
    498 dev_t		dev;
    499 int		flags, devtype;
    500 struct proc	*proc;
    501 {
    502 	struct fd_softc	*sc;
    503 
    504 	sc = getsoftc(fd_cd, DISKUNIT(dev));
    505 	free_stmem(sc->bounceb);
    506 	sc->flags = 0;
    507 	nopens--;
    508 
    509 #ifdef FLP_DEBUG
    510 	printf("Closed floppy device -- nopens: %d\n", nopens);
    511 #endif
    512 	return(0);
    513 }
    514 
    515 void
    516 fdstrategy(bp)
    517 struct buf	*bp;
    518 {
    519 	struct fd_softc	 *sc;
    520 	struct disklabel *lp;
    521 	int		 sps;
    522 
    523 	sc = getsoftc(fd_cd, DISKUNIT(bp->b_dev));
    524 
    525 #ifdef FLP_DEBUG
    526 	printf("fdstrategy: 0x%x\n", bp);
    527 #endif
    528 
    529 	/*
    530 	 * check for valid partition and bounds
    531 	 */
    532 	lp = sc->dkdev.dk_label;
    533 	if ((sc->flags & FLPF_HAVELAB) == 0) {
    534 		bp->b_error = EIO;
    535 		goto bad;
    536 	}
    537 	if (bounds_check_with_label(bp, lp, 0) <= 0)
    538 		goto done;
    539 
    540 	if (bp->b_bcount == 0)
    541 		goto done;
    542 
    543 	/*
    544 	 * queue the buf and kick the low level code
    545 	 */
    546 	sps = splbio();
    547 	disksort(&sc->bufq, bp);
    548 	if (!lock_stat) {
    549 		if (fd_state & FLP_MON)
    550 			untimeout((FPV)fdmotoroff, (void*)sc);
    551 		fd_state = FLP_IDLE;
    552 		st_dmagrab((dma_farg)fdcint, (dma_farg)fdstart, sc,
    553 							&lock_stat, 0);
    554 	}
    555 	splx(sps);
    556 
    557 	return;
    558 bad:
    559 	bp->b_flags |= B_ERROR;
    560 done:
    561 	bp->b_resid = bp->b_bcount;
    562 	biodone(bp);
    563 }
    564 
    565 /*
    566  * no dumps to floppy disks thank you.
    567  */
    568 int
    569 fddump(dev, blkno, va, size)
    570 dev_t	dev;
    571 daddr_t	blkno;
    572 caddr_t	va;
    573 size_t	size;
    574 {
    575 	return(ENXIO);
    576 }
    577 
    578 /*
    579  * no dumps to floppy disks thank you.
    580  */
    581 int
    582 fdsize(dev)
    583 dev_t dev;
    584 {
    585 	return(-1);
    586 }
    587 
    588 int
    589 fdread(dev, uio, flags)
    590 dev_t		dev;
    591 struct uio	*uio;
    592 int		flags;
    593 {
    594 	return(physio(fdstrategy, NULL, dev, B_READ, fdminphys, uio));
    595 }
    596 
    597 int
    598 fdwrite(dev, uio, flags)
    599 dev_t		dev;
    600 struct uio	*uio;
    601 int		flags;
    602 {
    603 	return(physio(fdstrategy, NULL, dev, B_WRITE, fdminphys, uio));
    604 }
    605 
    606 /*
    607  * Called through DMA-dispatcher, get status.
    608  */
    609 static void
    610 fdstatus(sc)
    611 struct fd_softc	*sc;
    612 {
    613 #ifdef FLP_DEBUG
    614 	printf("fdstatus\n");
    615 #endif
    616 	sc->errcnt = 0;
    617 	fd_state   = FLP_STAT;
    618 	fd_xfer(sc);
    619 }
    620 
    621 /*
    622  * Called through the dma-dispatcher. So we know we are the only ones
    623  * messing with the floppy-controler.
    624  * Initialize some fields in the fdsoftc for the state-machine and get
    625  * it going.
    626  */
    627 static void
    628 fdstart(sc)
    629 struct fd_softc	*sc;
    630 {
    631 	struct buf	*bp;
    632 
    633 	bp           = sc->bufq.b_actf;
    634 	sc->sector   = bp->b_blkno;	/* Start sector for I/O		*/
    635 	sc->io_data  = bp->b_data;	/* KVA base for I/O		*/
    636 	sc->io_bytes = bp->b_bcount;	/* Transfer size in bytes	*/
    637 	sc->io_dir   = bp->b_flags & B_READ;/* Direction of transfer	*/
    638 	sc->errcnt   = 0;		/* No errors yet		*/
    639 	fd_state     = FLP_XFER;	/* Yes, we're going to transfer	*/
    640 
    641 	/* Instrumentation. */
    642 	disk_busy(&sc->dkdev);
    643 
    644 	fd_xfer(sc);
    645 }
    646 
    647 /*
    648  * The current transaction is finished (for good or bad). Let go of
    649  * the the dma-resources. Call biodone() to finish the transaction.
    650  * Find a new transaction to work on.
    651  */
    652 static void
    653 fddone(sc)
    654 register struct fd_softc	*sc;
    655 {
    656 	struct buf	*bp, *dp;
    657 	struct fd_softc	*sc1;
    658 	int		i, sps;
    659 
    660 	/*
    661 	 * Give others a chance to use the dma.
    662 	 */
    663 	st_dmafree(sc, &lock_stat);
    664 
    665 
    666 	if(fd_state != FLP_STAT) {
    667 		/*
    668 		 * Finish current transaction.
    669 		 */
    670 		sps = splbio();
    671 		dp = &sc->bufq;
    672 		bp = dp->b_actf;
    673 		if(bp == NULL)
    674 			panic("fddone");
    675 		dp->b_actf = bp->b_actf;
    676 		splx(sps);
    677 
    678 #ifdef FLP_DEBUG
    679 		printf("fddone: unit: %d, buf: %x, resid: %d\n",sc->unit,bp,
    680 								sc->io_bytes);
    681 #endif
    682 		bp->b_resid = sc->io_bytes;
    683 
    684 		disk_unbusy(&sc->dkdev, (bp->b_bcount - bp->b_resid));
    685 
    686 		biodone(bp);
    687 	}
    688 	fd_state = FLP_MON;
    689 
    690 	if(lock_stat)
    691 		return;		/* XXX Is this possible?	*/
    692 
    693 	/*
    694 	 * Find a new transaction on round-robin basis.
    695 	 */
    696 	for(i = sc->unit + 1; ;i++) {
    697 		if(i >= fd_cd.cd_ndevs)
    698 			i = 0;
    699 		if((sc1 = fd_cd.cd_devs[i]) == NULL)
    700 			continue;
    701 		if(sc1->bufq.b_actf)
    702 			break;
    703 		if(i == sc->unit) {
    704 			timeout((FPV)fdmotoroff, (void*)sc, FLP_MONDELAY);
    705 #ifdef FLP_DEBUG
    706 			printf("fddone: Nothing to do\n");
    707 #endif
    708 			return;	/* No work */
    709 		}
    710 	}
    711 	fd_state = FLP_IDLE;
    712 #ifdef FLP_DEBUG
    713 	printf("fddone: Staring job on unit %d\n", sc1->unit);
    714 #endif
    715 	st_dmagrab((dma_farg)fdcint, (dma_farg)fdstart, sc1, &lock_stat, 0);
    716 }
    717 
    718 static int
    719 fdselect(drive, head, dense)
    720 int	drive, head, dense;
    721 {
    722 	int	i, spinning;
    723 #ifdef FLP_DEBUG
    724 	printf("fdselect: drive=%d, head=%d, dense=%d\n", drive, head, dense);
    725 #endif
    726 	i = ((drive == 1) ? PA_FLOP1 : PA_FLOP0) | head;
    727 	spinning = motoron;
    728 	motoron  = 1;
    729 
    730 	switch(dense) {
    731 		case FLP_DD:
    732 			DMA->dma_drvmode = 0;
    733 			break;
    734 		case FLP_HD:
    735 			DMA->dma_drvmode = (FDC_HDSET|FDC_HDSIG);
    736 			break;
    737 		default:
    738 			panic("fdselect: unknown density code\n");
    739 	}
    740 	if(i != selected) {
    741 		selected = i;
    742 		ym2149_fd_select(i ^ PA_FDSEL);
    743 	}
    744 	return(spinning);
    745 }
    746 
    747 static void
    748 fddeselect()
    749 {
    750 	ym2149_fd_select(PA_FDSEL);
    751 	motoron = selected = 0;
    752 	DMA->dma_drvmode   = 0;
    753 }
    754 
    755 /****************************************************************************
    756  * The following functions assume to be running as a result of a            *
    757  * disk-interrupt (e.q. spl = splbio).				            *
    758  * They form the finit-state machine, the actual driver.                    *
    759  *                                                                          *
    760  *	fdstart()/ --> fd_xfer() -> activate hardware                       *
    761  *  fdopen()          ^                                                     *
    762  *                    |                                                     *
    763  *                    +-- not ready -<------------+                         *
    764  *                                                |                         *
    765  *  fdmotoroff()/ --> fdcint() -> fd_xfer_ok() ---+                         *
    766  *  h/w interrupt                 |                                         *
    767  *                               \|/                                        *
    768  *                            finished ---> fdone()                         *
    769  *                                                                          *
    770  ****************************************************************************/
    771 static void
    772 fd_xfer(sc)
    773 struct fd_softc	*sc;
    774 {
    775 	register int	head;
    776 	register int	track, sector, hbit;
    777 		 u_long	phys_addr;
    778 
    779 	head = track = 0;
    780 	switch(fd_state) {
    781 	    case FLP_XFER:
    782 		/*
    783 		 * Calculate head/track values
    784 		 */
    785 		track  = sc->sector / sc->nsectors;
    786 		head   = track % sc->nheads;
    787 		track  = track / sc->nheads;
    788 #ifdef FLP_DEBUG
    789 		printf("fd_xfer: sector:%d,head:%d,track:%d\n", sc->sector,head,
    790 								track);
    791 #endif
    792 		break;
    793 
    794 	    case FLP_STAT:
    795 		/*
    796 		 * FLP_STAT only wants to recalibrate
    797 		 */
    798 		sc->curtrk = INV_TRK;
    799 		break;
    800 	    default:
    801 		panic("fd_xfer: wrong state (0x%x)", fd_state);
    802 	}
    803 
    804 	/*
    805 	 * Select the drive.
    806 	 */
    807 	hbit = fdselect(sc->unit, head, sc->density) ? HBIT : 0;
    808 
    809 	if(sc->curtrk == INV_TRK) {
    810 		/*
    811 		 * Recalibrate, since we lost track of head positioning.
    812 		 * The floppy disk controller has no way of determining its
    813 		 * absolute arm position (track).  Instead, it steps the
    814 		 * arm a track at a time and keeps track of where it
    815 		 * thinks it is (in software).  However, after a SEEK, the
    816 		 * hardware reads information from the diskette telling
    817 		 * where the arm actually is.  If the arm is in the wrong place,
    818 		 * a recalibration is done, which forces the arm to track 0.
    819 		 * This way the controller can get back into sync with reality.
    820 		 */
    821 		fd_cmd = RESTORE;
    822 		write_fdreg(FDC_CS, RESTORE|VBIT|hbit);
    823 		timeout((FPV)fdmotoroff, (void*)sc, FLP_XFERDELAY);
    824 
    825 #ifdef FLP_DEBUG
    826 		printf("fd_xfer:Recalibrating drive %d\n", sc->unit);
    827 #endif
    828 		return;
    829 	}
    830 
    831 	write_fdreg(FDC_TR, sc->curtrk);
    832 
    833 	/*
    834 	 * Issue a SEEK command on the indicated drive unless the arm is
    835 	 * already positioned on the correct track.
    836 	 */
    837 	if(track != sc->curtrk) {
    838 		sc->curtrk = track;	/* be optimistic */
    839 		write_fdreg(FDC_DR, track);
    840 		write_fdreg(FDC_CS, SEEK|RATE6|VBIT|hbit);
    841 		timeout((FPV)fdmotoroff, (void*)sc, FLP_XFERDELAY);
    842 		fd_cmd = SEEK;
    843 #ifdef FLP_DEBUG
    844 		printf("fd_xfer:Seek to track %d on drive %d\n",track,sc->unit);
    845 #endif
    846 		return;
    847 	}
    848 
    849 	/*
    850 	 * The drive is now on the proper track. Read or write 1 block.
    851 	 */
    852 	sector = sc->sector % sc->nsectors;
    853 	sector++;	/* start numbering at 1 */
    854 
    855 	write_fdreg(FDC_SR, sector);
    856 
    857 	phys_addr = (u_long)kvtop(sc->io_data);
    858 	if(phys_addr >= FDC_MAX_DMA_AD) {
    859 		/*
    860 		 * We _must_ bounce this address
    861 		 */
    862 		phys_addr = (u_long)kvtop(sc->bounceb);
    863 		if(sc->io_dir == B_WRITE)
    864 			bcopy(sc->io_data, sc->bounceb, SECTOR_SIZE);
    865 		sc->flags |= FLPF_BOUNCE;
    866 	}
    867 	st_dmaaddr_set((caddr_t)phys_addr);	/* DMA address setup */
    868 
    869 #ifdef FLP_DEBUG
    870 	printf("fd_xfer:Start io (io_addr:%x)\n", kvtop(sc->io_data));
    871 #endif
    872 
    873 	if(sc->io_dir == B_READ) {
    874 		/* Issue the command */
    875 		st_dmacomm(DMA_FDC | DMA_SCREG, 1);
    876 		write_fdreg(FDC_CS, F_READ|hbit);
    877 		fd_cmd = F_READ;
    878 	}
    879 	else {
    880 		/* Issue the command */
    881 		st_dmacomm(DMA_WRBIT | DMA_FDC | DMA_SCREG, 1);
    882 		write_fdreg(DMA_WRBIT | FDC_CS, F_WRITE|hbit|EBIT|PBIT);
    883 		fd_cmd = F_WRITE;
    884 	}
    885 	timeout((FPV)fdmotoroff, (void*)sc, FLP_XFERDELAY);
    886 }
    887 
    888 /* return values of fd_xfer_ok(): */
    889 #define X_OK			0
    890 #define X_AGAIN			1
    891 #define X_ERROR			2
    892 #define X_FAIL			3
    893 
    894 /*
    895  * Hardware interrupt function.
    896  */
    897 static void
    898 fdcint(sc)
    899 struct fd_softc	*sc;
    900 {
    901 	struct	buf	*bp;
    902 
    903 #ifdef FLP_DEBUG
    904 	printf("fdcint: unit = %d\n", sc->unit);
    905 #endif
    906 
    907 	/*
    908 	 * Cancel timeout (we made it, didn't we)
    909 	 */
    910 	untimeout((FPV)fdmotoroff, (void*)sc);
    911 
    912 	switch(fd_xfer_ok(sc)) {
    913 		case X_ERROR :
    914 			if(++(sc->errcnt) < MAX_ERRORS) {
    915 				/*
    916 				 * Command failed but still retries left.
    917 				 */
    918 				break;
    919 			}
    920 			/* FALL THROUGH */
    921 		case X_FAIL  :
    922 			/*
    923 			 * Non recoverable error. Fall back to motor-on
    924 			 * idle-state.
    925 			 */
    926 			if(fd_error != NULL) {
    927 				printf("Floppy error: %s\n", fd_error);
    928 				fd_error = NULL;
    929 			}
    930 
    931 			if(fd_state == FLP_STAT) {
    932 				sc->flags |= FLPF_EMPTY;
    933 				sc->flags &= ~FLPF_GETSTAT;
    934 				wakeup((caddr_t)sc);
    935 				fddone(sc);
    936 				return;
    937 			}
    938 
    939 			bp = sc->bufq.b_actf;
    940 
    941 			bp->b_error  = EIO;
    942 			bp->b_flags |= B_ERROR;
    943 			fd_state     = FLP_MON;
    944 
    945 			break;
    946 		case X_AGAIN:
    947 			/*
    948 			 * Start next part of state machine.
    949 			 */
    950 			break;
    951 		case X_OK:
    952 			/*
    953 			 * Command ok and finished. Reset error-counter.
    954 			 * If there are no more bytes to transfer fall back
    955 			 * to motor-on idle state.
    956 			 */
    957 			sc->errcnt = 0;
    958 
    959 			if(fd_state == FLP_STAT) {
    960 				sc->flags &= ~FLPF_GETSTAT;
    961 				wakeup((caddr_t)sc);
    962 				fddone(sc);
    963 				return;
    964 			}
    965 
    966 			if((sc->flags & FLPF_BOUNCE) && (sc->io_dir == B_READ))
    967 				bcopy(sc->bounceb, sc->io_data, SECTOR_SIZE);
    968 			sc->flags &= ~FLPF_BOUNCE;
    969 
    970 			sc->sector++;
    971 			sc->io_data  += SECTOR_SIZE;
    972 			sc->io_bytes -= SECTOR_SIZE;
    973 			if(sc->io_bytes <= 0)
    974 				fd_state = FLP_MON;
    975 	}
    976 	if(fd_state == FLP_MON)
    977 		fddone(sc);
    978 	else fd_xfer(sc);
    979 }
    980 
    981 /*
    982  * Determine status of last command. Should only be called through
    983  * 'fdcint()'.
    984  * Returns:
    985  *	X_ERROR : Error on command; might succeed next time.
    986  *	X_FAIL  : Error on command; will never succeed.
    987  *	X_AGAIN : Part of a command succeeded, call 'fd_xfer()' to complete.
    988  *	X_OK	: Command succeeded and is complete.
    989  *
    990  * This function only affects sc->curtrk.
    991  */
    992 static int
    993 fd_xfer_ok(sc)
    994 register struct fd_softc	*sc;
    995 {
    996 	register int	status;
    997 
    998 #ifdef FLP_DEBUG
    999 	printf("fd_xfer_ok: cmd: 0x%x, state: 0x%x\n", fd_cmd, fd_state);
   1000 #endif
   1001 	switch(fd_cmd) {
   1002 		case IRUPT:
   1003 			/*
   1004 			 * Timeout. Force a recalibrate before we try again.
   1005 			 */
   1006 			status = read_fdreg(FDC_CS);
   1007 
   1008 			fd_error = "Timeout";
   1009 			sc->curtrk = INV_TRK;
   1010 			return(X_ERROR);
   1011 		case F_READ:
   1012 			/*
   1013 			 * Test for DMA error
   1014 			 */
   1015 			status = read_dmastat();
   1016 			if(!(status & DMAOK)) {
   1017 				fd_error = "Dma error";
   1018 				return(X_ERROR);
   1019 			}
   1020 			/*
   1021 			 * Get controller status and check for errors.
   1022 			 */
   1023 			status = read_fdreg(FDC_CS);
   1024 			if(status & (RNF | CRCERR | LD_T00)) {
   1025 				fd_error = "Read error";
   1026 				if(status & RNF)
   1027 					sc->curtrk = INV_TRK;
   1028 				return(X_ERROR);
   1029 			}
   1030 			break;
   1031 		case F_WRITE:
   1032 			/*
   1033 			 * Test for DMA error
   1034 			 */
   1035 			status = read_dmastat();
   1036 			if(!(status & DMAOK)) {
   1037 				fd_error = "Dma error";
   1038 				return(X_ERROR);
   1039 			}
   1040 			/*
   1041 			 * Get controller status and check for errors.
   1042 			 */
   1043 			status = read_fdreg(FDC_CS);
   1044 			if(status & WRI_PRO) {
   1045 				fd_error = "Write protected";
   1046 				return(X_FAIL);
   1047 			}
   1048 			if(status & (RNF | CRCERR | LD_T00)) {
   1049 				fd_error = "Write error";
   1050 				sc->curtrk = INV_TRK;
   1051 				return(X_ERROR);
   1052 			}
   1053 			break;
   1054 		case SEEK:
   1055 			status = read_fdreg(FDC_CS);
   1056 			if(status & (RNF | CRCERR)) {
   1057 				fd_error = "Seek error";
   1058 				sc->curtrk = INV_TRK;
   1059 				return(X_ERROR);
   1060 			}
   1061 			return(X_AGAIN);
   1062 		case RESTORE:
   1063 			/*
   1064 			 * Determine if the recalibration succeeded.
   1065 			 */
   1066 			status = read_fdreg(FDC_CS);
   1067 			if(status & RNF) {
   1068 				fd_error = "Recalibrate error";
   1069 				/* reset controller */
   1070 				write_fdreg(FDC_CS, IRUPT);
   1071 				sc->curtrk = INV_TRK;
   1072 				return(X_ERROR);
   1073 			}
   1074 			sc->curtrk = 0;
   1075 			if(fd_state == FLP_STAT) {
   1076 				if(status & WRI_PRO)
   1077 					sc->flags |= FLPF_WRTPROT;
   1078 				break;
   1079 			}
   1080 			return(X_AGAIN);
   1081 		default:
   1082 			fd_error = "Driver error: fd_xfer_ok : Unknown state";
   1083 			return(X_FAIL);
   1084 	}
   1085 	return(X_OK);
   1086 }
   1087 
   1088 /*
   1089  * All timeouts will call this function.
   1090  */
   1091 static void
   1092 fdmotoroff(sc)
   1093 struct fd_softc	*sc;
   1094 {
   1095 	int	sps;
   1096 
   1097 	/*
   1098 	 * Get at harware interrupt level
   1099 	 */
   1100 	sps = splbio();
   1101 
   1102 #if FLP_DEBUG
   1103 	printf("fdmotoroff, state = 0x%x\n", fd_state);
   1104 #endif
   1105 
   1106 	switch(fd_state) {
   1107 		case FLP_STAT :
   1108 		case FLP_XFER :
   1109 			/*
   1110 			 * Timeout during a transfer; cancel transaction
   1111 			 * set command to 'IRUPT'.
   1112 			 * A drive-interrupt is simulated to trigger the state
   1113 			 * machine.
   1114 			 */
   1115 			/*
   1116 			 * Cancel current transaction
   1117 			 */
   1118 			fd_cmd = IRUPT;
   1119 			write_fdreg(FDC_CS, IRUPT);
   1120 			delay(20);
   1121 			(void)read_fdreg(FDC_CS);
   1122 			write_fdreg(FDC_CS, RESTORE);
   1123 			break;
   1124 
   1125 		case FLP_MON  :
   1126 			/*
   1127 			 * Turn motor off.
   1128 			 */
   1129 			if(selected) {
   1130 				int tmp;
   1131 
   1132 				st_dmagrab((dma_farg)fdcint, (dma_farg)fdmoff,
   1133 								sc, &tmp, 0);
   1134 			}
   1135 			else  fd_state = FLP_IDLE;
   1136 			break;
   1137 	}
   1138 	splx(sps);
   1139 }
   1140 
   1141 /*
   1142  * min byte count to whats left of the track in question
   1143  */
   1144 static void
   1145 fdminphys(bp)
   1146 struct buf	*bp;
   1147 {
   1148 	struct fd_softc	*sc;
   1149 	int		sec, toff, tsz;
   1150 
   1151 	if((sc = getsoftc(fd_cd, DISKUNIT(bp->b_dev))) == NULL)
   1152 		panic("fdminphys: couldn't get softc");
   1153 
   1154 	sec  = bp->b_blkno % (sc->nsectors * sc->nheads);
   1155 	toff = sec * SECTOR_SIZE;
   1156 	tsz  = sc->nsectors * sc->nheads * SECTOR_SIZE;
   1157 
   1158 #ifdef FLP_DEBUG
   1159 	printf("fdminphys: before %d", bp->b_bcount);
   1160 #endif
   1161 
   1162 	bp->b_bcount = min(bp->b_bcount, tsz - toff);
   1163 
   1164 #ifdef FLP_DEBUG
   1165 	printf(" after %d\n", bp->b_bcount);
   1166 #endif
   1167 
   1168 	minphys(bp);
   1169 }
   1170 
   1171 /*
   1172  * Called from fdmotoroff to turn the motor actually off....
   1173  * This can't be done in fdmotoroff itself, because exclusive access to the
   1174  * DMA controller is needed to read the FDC-status register. The function
   1175  * 'fdmoff()' always runs as the result of a 'dmagrab()'.
   1176  * We need to test the status-register because we want to be sure that the
   1177  * drive motor is really off before deselecting the drive. The FDC only
   1178  * turns off the drive motor after having seen 10 index-pulses. You only
   1179  * get index-pulses when a drive is selected....This means that if the
   1180  * drive is deselected when the motor is still spinning, it will continue
   1181  * to spin _even_ when you insert a floppy later on...
   1182  */
   1183 static void
   1184 fdmoff(fdsoftc)
   1185 struct fd_softc	*fdsoftc;
   1186 {
   1187 	int tmp;
   1188 
   1189 	if ((fd_state == FLP_MON) && selected) {
   1190 		tmp = read_fdreg(FDC_CS);
   1191 		if (!(tmp & MOTORON)) {
   1192 			fddeselect();
   1193 			fd_state = FLP_IDLE;
   1194 		}
   1195 		else timeout((FPV)fdmotoroff, (void*)fdsoftc, 10*FLP_MONDELAY);
   1196 	}
   1197 	st_dmafree(fdsoftc, &tmp);
   1198 }
   1199 
   1200 /*
   1201  * Used to find out wich drives are actually connected. We do this by issueing
   1202  * is 'RESTORE' command and check if the 'track-0' bit is set. This also works
   1203  * if the drive is present but no floppy is inserted.
   1204  */
   1205 static void
   1206 fdtestdrv(fdsoftc)
   1207 struct fd_softc	*fdsoftc;
   1208 {
   1209 	int	status;
   1210 
   1211 	/*
   1212 	 * Select the right unit and head.
   1213 	 */
   1214 	fdselect(fdsoftc->unit, 0, FLP_DD);
   1215 
   1216 	write_fdreg(FDC_CS, RESTORE|HBIT);
   1217 
   1218 	/*
   1219 	 * Wait for about 2 seconds.
   1220 	 */
   1221 	delay(2000000);
   1222 
   1223 	status = read_fdreg(FDC_CS);
   1224 	if(status & (RNF|BUSY)) {
   1225 		write_fdreg(FDC_CS, IRUPT);	/* reset controller */
   1226 		delay(40);
   1227 	}
   1228 
   1229 	if(!(status & LD_T00))
   1230 		fdsoftc->flags |= FLPF_NOTRESP;
   1231 
   1232 	fddeselect();
   1233 }
   1234 
   1235 /*
   1236  * Build disk label. For now we only create a label from what we know
   1237  * from 'sc'.
   1238  */
   1239 static int
   1240 fdgetdisklabel(sc, dev)
   1241 struct fd_softc *sc;
   1242 dev_t			dev;
   1243 {
   1244 	struct disklabel	*lp;
   1245 	int			part;
   1246 
   1247 	/*
   1248 	 * If we already got one, get out.
   1249 	 */
   1250 	if(sc->flags & FLPF_HAVELAB)
   1251 		return(0);
   1252 
   1253 #ifdef FLP_DEBUG
   1254 	printf("fdgetdisklabel()\n");
   1255 #endif
   1256 
   1257 	part = DISKPART(dev);
   1258 	lp   = sc->dkdev.dk_label;
   1259 	bzero(lp, sizeof(struct disklabel));
   1260 
   1261 	lp->d_secsize     = SECTOR_SIZE;
   1262 	lp->d_ntracks     = sc->nheads;
   1263 	lp->d_nsectors    = sc->nsectors;
   1264 	lp->d_secpercyl   = lp->d_ntracks * lp->d_nsectors;
   1265 	lp->d_ncylinders  = sc->nblocks / lp->d_secpercyl;
   1266 	lp->d_secperunit  = sc->nblocks;
   1267 
   1268 	lp->d_type        = DTYPE_FLOPPY;
   1269 	lp->d_rpm         = 300; 	/* good guess I suppose.	*/
   1270 	lp->d_interleave  = 1;		/* FIXME: is this OK?		*/
   1271 	lp->d_bbsize      = 0;
   1272 	lp->d_sbsize      = 0;
   1273 	lp->d_npartitions = part + 1;
   1274 	lp->d_trkseek     = STEP_DELAY;
   1275 	lp->d_magic       = DISKMAGIC;
   1276 	lp->d_magic2      = DISKMAGIC;
   1277 	lp->d_checksum    = dkcksum(lp);
   1278 	lp->d_partitions[part].p_size   = lp->d_secperunit;
   1279 	lp->d_partitions[part].p_fstype = FS_UNUSED;
   1280 	lp->d_partitions[part].p_fsize  = 1024;
   1281 	lp->d_partitions[part].p_frag   = 8;
   1282 	sc->flags        |= FLPF_HAVELAB;
   1283 
   1284 	return(0);
   1285 }
   1286