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