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