Home | History | Annotate | Line # | Download | only in dev
fd.c revision 1.17
      1 /*	$NetBSD: fd.c,v 1.17 1996/03/20 12:41:48 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/fdreg.h>
     71 
     72 /*
     73  * Be verbose for debugging
     74  */
     75 /*#define FLP_DEBUG	1 */
     76 
     77 #define	FDC_MAX_DMA_AD	0x1000000	/* No DMA possible beyond	*/
     78 
     79 /* Parameters for the disk drive. */
     80 #define SECTOR_SIZE	512	/* physical sector size in bytes	*/
     81 #define NR_DRIVES	2	/* maximum number of drives		*/
     82 #define NR_TYPES	3	/* number of diskette/drive combinations*/
     83 #define MAX_ERRORS	10	/* how often to try rd/wt before quitting*/
     84 #define STEP_DELAY	6000	/* 6ms (6000us) delay after stepping	*/
     85 
     86 
     87 #define	INV_TRK		32000	/* Should fit in unsigned short		*/
     88 #define	INV_PART	NR_TYPES
     89 
     90 /*
     91  * Driver states
     92  */
     93 #define	FLP_IDLE	0x00	/* floppy is idle			*/
     94 #define	FLP_MON		0x01	/* idle with motor on			*/
     95 #define	FLP_STAT	0x02	/* determine floppy status		*/
     96 #define	FLP_XFER	0x04	/* read/write data from floppy		*/
     97 
     98 /*
     99  * Timer delay's
    100  */
    101 #define	FLP_MONDELAY	(3 * hz)	/* motor-on delay		*/
    102 #define	FLP_XFERDELAY	(2 * hz)	/* timeout on transfer		*/
    103 
    104 /*
    105  * The density codes
    106  */
    107 #define	FLP_DD		0		/* Double density		*/
    108 #define	FLP_HD		1		/* High density			*/
    109 
    110 
    111 #define	b_block		b_resid		/* FIXME: this is not the place	*/
    112 
    113 /*
    114  * Global data for all physical floppy devices
    115  */
    116 static short	selected = 0;		/* drive/head currently selected*/
    117 static short	motoron  = 0;		/* motor is spinning		*/
    118 static short	nopens   = 0;		/* Number of opens executed	*/
    119 
    120 static short	fd_state = FLP_IDLE;	/* Current driver state		*/
    121 static int	lock_stat= 0;		/* dma locking status		*/
    122 static short	fd_cmd   = 0;		/* command being executed	*/
    123 static char	*fd_error= NULL;	/* error from fd_xfer_ok()	*/
    124 
    125 /*
    126  * Private per device data
    127  */
    128 struct fd_softc {
    129 	struct device	sc_dv;		/* generic device info		*/
    130 	struct disk	dkdev;		/* generic disk info		*/
    131 	struct buf	bufq;		/* queue of buf's		*/
    132 	int		unit;		/* unit for atari controlling hw*/
    133 	int		nheads;		/* number of heads in use	*/
    134 	int		nsectors;	/* number of sectors/track	*/
    135 	int		density;	/* density code			*/
    136 	int		nblocks;	/* number of blocks on disk	*/
    137 	int		curtrk;		/* track head positioned on	*/
    138 	short		flags;		/* misc flags			*/
    139 	short		part;		/* Current open partition	*/
    140 	int		sector;		/* logical sector for I/O	*/
    141 	caddr_t		io_data;	/* KVA for data transfer	*/
    142 	int		io_bytes;	/* bytes left for I/O		*/
    143 	int		io_dir;		/* B_READ/B_WRITE		*/
    144 	int		errcnt;		/* current error count		*/
    145 	u_char		*bounceb;	/* Bounce buffer		*/
    146 
    147 };
    148 
    149 /*
    150  * Flags in fd_softc:
    151  */
    152 #define FLPF_NOTRESP	0x001		/* Unit not responding		*/
    153 #define FLPF_ISOPEN	0x002		/* Unit is open			*/
    154 #define FLPF_SPARE	0x004		/* Not used			*/
    155 #define FLPF_HAVELAB	0x008		/* We have a valid label	*/
    156 #define FLPF_BOUNCE	0x010		/* Now using the bounce buffer	*/
    157 #define FLPF_WRTPROT	0x020		/* Unit is write-protected	*/
    158 #define FLPF_EMPTY	0x040		/* Unit is empty		*/
    159 #define FLPF_INOPEN	0x080		/* Currently being opened	*/
    160 #define FLPF_GETSTAT	0x100		/* Getting unit status		*/
    161 
    162 struct fd_types {
    163 	int		nheads;		/* Heads in use			*/
    164 	int		nsectors;	/* sectors per track		*/
    165 	int		nblocks;	/* number of blocks		*/
    166 	int		density;	/* density code			*/
    167 } fdtypes[NR_TYPES] = {
    168 		{ 1,  9,  720 , FLP_DD },	/* 360  Kb	*/
    169 		{ 2,  9, 1440 , FLP_DD },	/* 720  Kb	*/
    170 		{ 2, 18, 2880 , FLP_HD },	/* 1.44 Mb	*/
    171 };
    172 
    173 typedef void	(*FPV) __P((void *));
    174 
    175 /*
    176  * {b,c}devsw[] function prototypes
    177  */
    178 dev_type_open(Fdopen);
    179 dev_type_close(fdclose);
    180 dev_type_read(fdread);
    181 dev_type_write(fdwrite);
    182 dev_type_ioctl(fdioctl);
    183 dev_type_size(fdsize);
    184 dev_type_dump(fddump);
    185 
    186 /*
    187  * Private drive functions....
    188  */
    189 static void	fdstart __P((struct fd_softc *));
    190 static void	fddone __P((struct fd_softc *));
    191 static void	fdstatus __P((struct fd_softc *));
    192 static void	fd_xfer __P((struct fd_softc *));
    193 static void	fdcint __P((struct fd_softc *));
    194 static int	fd_xfer_ok __P((struct fd_softc *));
    195 static void	fdmotoroff __P((struct fd_softc *));
    196 static void	fdminphys __P((struct buf *));
    197 static void	fdtestdrv __P((struct fd_softc *));
    198 static int	fdgetdisklabel __P((struct fd_softc *, dev_t));
    199 static int	fdselect __P((int, int, int));
    200 static void	fddeselect __P((void));
    201 static void	fdmoff __P((struct fd_softc *));
    202        u_char	read_fdreg __P((u_short));
    203        void	write_fdreg __P((u_short, u_short));
    204        u_char	read_dmastat __P((void));
    205 
    206 extern __inline__ u_char read_fdreg(u_short regno)
    207 {
    208 	DMA->dma_mode = regno;
    209 	return(DMA->dma_data);
    210 }
    211 
    212 extern __inline__ void write_fdreg(u_short regno, u_short val)
    213 {
    214 	DMA->dma_mode = regno;
    215 	DMA->dma_data = val;
    216 }
    217 
    218 extern __inline__ u_char read_dmastat(void)
    219 {
    220 	DMA->dma_mode = FDC_CS | DMA_SCREG;
    221 	return(DMA->dma_stat);
    222 }
    223 
    224 /*
    225  * Autoconfig stuff....
    226  */
    227 static int	fdcmatch __P((struct device *, void *, void *));
    228 static int	fdcprint __P((void *, char *));
    229 static void	fdcattach __P((struct device *, struct device *, void *));
    230 
    231 struct cfattach fdc_ca = {
    232 	sizeof(struct device), fdcmatch, fdcattach
    233 };
    234 
    235 struct cfdriver fdc_cd = {
    236 	NULL, "fdc", DV_DULL, NULL, 0
    237 };
    238 
    239 static int
    240 fdcmatch(pdp, match, auxp)
    241 struct device	*pdp;
    242 void		*match, *auxp;
    243 {
    244 	struct cfdata *cfp = match;
    245 
    246 	if(strcmp("fdc", auxp) || cfp->cf_unit != 0)
    247 		return(0);
    248 	return(1);
    249 }
    250 
    251 static void
    252 fdcattach(pdp, dp, auxp)
    253 struct device	*pdp, *dp;
    254 void		*auxp;
    255 {
    256 	extern struct cfdriver fd_cd;
    257 	struct fd_softc	fdsoftc;
    258 	int		i, nfound, first_found;
    259 
    260 	nfound = first_found = 0;
    261 	printf("\n");
    262 	fddeselect();
    263 	for(i = 0; i < NR_DRIVES; i++) {
    264 
    265 		/*
    266 		 * Test if unit is present
    267 		 */
    268 		fdsoftc.unit  = i;
    269 		fdsoftc.flags = 0;
    270 		st_dmagrab((dma_farg)fdcint, (dma_farg)fdtestdrv, &fdsoftc,
    271 								&lock_stat, 0);
    272 		st_dmafree(&fdsoftc, &lock_stat);
    273 
    274 		if(!(fdsoftc.flags & FLPF_NOTRESP)) {
    275 			if(!nfound)
    276 				first_found = i;
    277 			nfound++;
    278 			config_found(dp, (void*)i, fdcprint);
    279 		}
    280 	}
    281 
    282 	if(nfound) {
    283 
    284 		/*
    285 		 * Make sure motor will be turned of when a floppy is
    286 		 * inserted in the first selected drive.
    287 		 */
    288 		fdselect(first_found, 0, FLP_DD);
    289 		fd_state = FLP_MON;
    290 		timeout((FPV)fdmotoroff, (void*)getsoftc(fd_cd, first_found),
    291 					 			FLP_MONDELAY);
    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, sps, 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 		sps = splhigh();
    742 
    743 		selected = i;
    744 		SOUND->sd_selr = YM_IOA;
    745 		SOUND->sd_wdat = (SOUND->sd_rdat & 0x78) | (i ^ 0x07);
    746 		splx(sps);
    747 	}
    748 	return(spinning);
    749 }
    750 
    751 static void
    752 fddeselect()
    753 {
    754 	int	sps;
    755 
    756 	sps = splhigh();
    757 	SOUND->sd_selr = YM_IOA;
    758 	SOUND->sd_wdat = SOUND->sd_rdat | 0x07;
    759 	splx(sps);
    760 
    761 	motoron = selected = 0;
    762 	DMA->dma_drvmode   = 0;
    763 }
    764 
    765 /****************************************************************************
    766  * The following functions assume to be running as a result of a            *
    767  * disk-interrupt (e.q. spl = splbio).				            *
    768  * They form the finit-state machine, the actual driver.                    *
    769  *                                                                          *
    770  *	fdstart()/ --> fd_xfer() -> activate hardware                       *
    771  *  fdopen()          ^                                                     *
    772  *                    |                                                     *
    773  *                    +-- not ready -<------------+                         *
    774  *                                                |                         *
    775  *  fdmotoroff()/ --> fdcint() -> fd_xfer_ok() ---+                         *
    776  *  h/w interrupt                 |                                         *
    777  *                               \|/                                        *
    778  *                            finished ---> fdone()                         *
    779  *                                                                          *
    780  ****************************************************************************/
    781 static void
    782 fd_xfer(sc)
    783 struct fd_softc	*sc;
    784 {
    785 	register int	head;
    786 	register int	track, sector, hbit;
    787 		 u_long	phys_addr;
    788 
    789 	head = track = 0;
    790 	switch(fd_state) {
    791 	    case FLP_XFER:
    792 		/*
    793 		 * Calculate head/track values
    794 		 */
    795 		track  = sc->sector / sc->nsectors;
    796 		head   = track % sc->nheads;
    797 		track  = track / sc->nheads;
    798 #ifdef FLP_DEBUG
    799 		printf("fd_xfer: sector:%d,head:%d,track:%d\n", sc->sector,head,
    800 								track);
    801 #endif
    802 		break;
    803 
    804 	    case FLP_STAT:
    805 		/*
    806 		 * FLP_STAT only wants to recalibrate
    807 		 */
    808 		sc->curtrk = INV_TRK;
    809 		break;
    810 	    default:
    811 		panic("fd_xfer: wrong state (0x%x)", fd_state);
    812 	}
    813 
    814 	/*
    815 	 * Select the drive.
    816 	 */
    817 	hbit = fdselect(sc->unit, head, sc->density) ? HBIT : 0;
    818 
    819 	if(sc->curtrk == INV_TRK) {
    820 		/*
    821 		 * Recalibrate, since we lost track of head positioning.
    822 		 * The floppy disk controller has no way of determining its
    823 		 * absolute arm position (track).  Instead, it steps the
    824 		 * arm a track at a time and keeps track of where it
    825 		 * thinks it is (in software).  However, after a SEEK, the
    826 		 * hardware reads information from the diskette telling
    827 		 * where the arm actually is.  If the arm is in the wrong place,
    828 		 * a recalibration is done, which forces the arm to track 0.
    829 		 * This way the controller can get back into sync with reality.
    830 		 */
    831 		fd_cmd = RESTORE;
    832 		write_fdreg(FDC_CS, RESTORE|VBIT|hbit);
    833 		timeout((FPV)fdmotoroff, (void*)sc, FLP_XFERDELAY);
    834 
    835 #ifdef FLP_DEBUG
    836 		printf("fd_xfer:Recalibrating drive %d\n", sc->unit);
    837 #endif
    838 		return;
    839 	}
    840 
    841 	write_fdreg(FDC_TR, sc->curtrk);
    842 
    843 	/*
    844 	 * Issue a SEEK command on the indicated drive unless the arm is
    845 	 * already positioned on the correct track.
    846 	 */
    847 	if(track != sc->curtrk) {
    848 		sc->curtrk = track;	/* be optimistic */
    849 		write_fdreg(FDC_DR, track);
    850 		write_fdreg(FDC_CS, SEEK|RATE6|VBIT|hbit);
    851 		timeout((FPV)fdmotoroff, (void*)sc, FLP_XFERDELAY);
    852 		fd_cmd = SEEK;
    853 #ifdef FLP_DEBUG
    854 		printf("fd_xfer:Seek to track %d on drive %d\n",track,sc->unit);
    855 #endif
    856 		return;
    857 	}
    858 
    859 	/*
    860 	 * The drive is now on the proper track. Read or write 1 block.
    861 	 */
    862 	sector = sc->sector % sc->nsectors;
    863 	sector++;	/* start numbering at 1 */
    864 
    865 	write_fdreg(FDC_SR, sector);
    866 
    867 	phys_addr = (u_long)kvtop(sc->io_data);
    868 	if(phys_addr >= FDC_MAX_DMA_AD) {
    869 		/*
    870 		 * We _must_ bounce this address
    871 		 */
    872 		phys_addr = (u_long)kvtop(sc->bounceb);
    873 		if(sc->io_dir == B_WRITE)
    874 			bcopy(sc->io_data, sc->bounceb, SECTOR_SIZE);
    875 		sc->flags |= FLPF_BOUNCE;
    876 	}
    877 	st_dmaaddr_set((caddr_t)phys_addr);	/* DMA address setup */
    878 
    879 #ifdef FLP_DEBUG
    880 	printf("fd_xfer:Start io (io_addr:%x)\n", kvtop(sc->io_data));
    881 #endif
    882 
    883 	if(sc->io_dir == B_READ) {
    884 		/* Issue the command */
    885 		st_dmacomm(DMA_FDC | DMA_SCREG, 1);
    886 		write_fdreg(FDC_CS, F_READ|hbit);
    887 		fd_cmd = F_READ;
    888 	}
    889 	else {
    890 		/* Issue the command */
    891 		st_dmacomm(DMA_WRBIT | DMA_FDC | DMA_SCREG, 1);
    892 		write_fdreg(DMA_WRBIT | FDC_CS, F_WRITE|hbit|EBIT|PBIT);
    893 		fd_cmd = F_WRITE;
    894 	}
    895 	timeout((FPV)fdmotoroff, (void*)sc, FLP_XFERDELAY);
    896 }
    897 
    898 /* return values of fd_xfer_ok(): */
    899 #define X_OK			0
    900 #define X_AGAIN			1
    901 #define X_ERROR			2
    902 #define X_FAIL			3
    903 
    904 /*
    905  * Hardware interrupt function.
    906  */
    907 static void
    908 fdcint(sc)
    909 struct fd_softc	*sc;
    910 {
    911 	struct	buf	*bp;
    912 
    913 #ifdef FLP_DEBUG
    914 	printf("fdcint: unit = %d\n", sc->unit);
    915 #endif
    916 
    917 	/*
    918 	 * Cancel timeout (we made it, didn't we)
    919 	 */
    920 	untimeout((FPV)fdmotoroff, (void*)sc);
    921 
    922 	switch(fd_xfer_ok(sc)) {
    923 		case X_ERROR :
    924 			if(++(sc->errcnt) < MAX_ERRORS) {
    925 				/*
    926 				 * Command failed but still retries left.
    927 				 */
    928 				break;
    929 			}
    930 			/* FALL THROUGH */
    931 		case X_FAIL  :
    932 			/*
    933 			 * Non recoverable error. Fall back to motor-on
    934 			 * idle-state.
    935 			 */
    936 			if(fd_error != NULL) {
    937 				printf("Floppy error: %s\n", fd_error);
    938 				fd_error = NULL;
    939 			}
    940 
    941 			if(fd_state == FLP_STAT) {
    942 				sc->flags |= FLPF_EMPTY;
    943 				sc->flags &= ~FLPF_GETSTAT;
    944 				wakeup((caddr_t)sc);
    945 				fddone(sc);
    946 				return;
    947 			}
    948 
    949 			bp = sc->bufq.b_actf;
    950 
    951 			bp->b_error  = EIO;
    952 			bp->b_flags |= B_ERROR;
    953 			fd_state     = FLP_MON;
    954 
    955 			break;
    956 		case X_AGAIN:
    957 			/*
    958 			 * Start next part of state machine.
    959 			 */
    960 			break;
    961 		case X_OK:
    962 			/*
    963 			 * Command ok and finished. Reset error-counter.
    964 			 * If there are no more bytes to transfer fall back
    965 			 * to motor-on idle state.
    966 			 */
    967 			sc->errcnt = 0;
    968 
    969 			if(fd_state == FLP_STAT) {
    970 				sc->flags &= ~FLPF_GETSTAT;
    971 				wakeup((caddr_t)sc);
    972 				fddone(sc);
    973 				return;
    974 			}
    975 
    976 			if((sc->flags & FLPF_BOUNCE) && (sc->io_dir == B_READ))
    977 				bcopy(sc->bounceb, sc->io_data, SECTOR_SIZE);
    978 			sc->flags &= ~FLPF_BOUNCE;
    979 
    980 			sc->sector++;
    981 			sc->io_data  += SECTOR_SIZE;
    982 			sc->io_bytes -= SECTOR_SIZE;
    983 			if(sc->io_bytes <= 0)
    984 				fd_state = FLP_MON;
    985 	}
    986 	if(fd_state == FLP_MON)
    987 		fddone(sc);
    988 	else fd_xfer(sc);
    989 }
    990 
    991 /*
    992  * Determine status of last command. Should only be called through
    993  * 'fdcint()'.
    994  * Returns:
    995  *	X_ERROR : Error on command; might succeed next time.
    996  *	X_FAIL  : Error on command; will never succeed.
    997  *	X_AGAIN : Part of a command succeeded, call 'fd_xfer()' to complete.
    998  *	X_OK	: Command succeeded and is complete.
    999  *
   1000  * This function only affects sc->curtrk.
   1001  */
   1002 static int
   1003 fd_xfer_ok(sc)
   1004 register struct fd_softc	*sc;
   1005 {
   1006 	register int	status;
   1007 
   1008 #ifdef FLP_DEBUG
   1009 	printf("fd_xfer_ok: cmd: 0x%x, state: 0x%x\n", fd_cmd, fd_state);
   1010 #endif
   1011 	switch(fd_cmd) {
   1012 		case IRUPT:
   1013 			/*
   1014 			 * Timeout. Force a recalibrate before we try again.
   1015 			 */
   1016 			status = read_fdreg(FDC_CS);
   1017 
   1018 			fd_error = "Timeout";
   1019 			sc->curtrk = INV_TRK;
   1020 			return(X_ERROR);
   1021 		case F_READ:
   1022 			/*
   1023 			 * Test for DMA error
   1024 			 */
   1025 			status = read_dmastat();
   1026 			if(!(status & DMAOK)) {
   1027 				fd_error = "Dma error";
   1028 				return(X_ERROR);
   1029 			}
   1030 			/*
   1031 			 * Get controller status and check for errors.
   1032 			 */
   1033 			status = read_fdreg(FDC_CS);
   1034 			if(status & (RNF | CRCERR | LD_T00)) {
   1035 				fd_error = "Read error";
   1036 				if(status & RNF)
   1037 					sc->curtrk = INV_TRK;
   1038 				return(X_ERROR);
   1039 			}
   1040 			break;
   1041 		case F_WRITE:
   1042 			/*
   1043 			 * Test for DMA error
   1044 			 */
   1045 			status = read_dmastat();
   1046 			if(!(status & DMAOK)) {
   1047 				fd_error = "Dma error";
   1048 				return(X_ERROR);
   1049 			}
   1050 			/*
   1051 			 * Get controller status and check for errors.
   1052 			 */
   1053 			status = read_fdreg(FDC_CS);
   1054 			if(status & WRI_PRO) {
   1055 				fd_error = "Write protected";
   1056 				return(X_FAIL);
   1057 			}
   1058 			if(status & (RNF | CRCERR | LD_T00)) {
   1059 				fd_error = "Write error";
   1060 				sc->curtrk = INV_TRK;
   1061 				return(X_ERROR);
   1062 			}
   1063 			break;
   1064 		case SEEK:
   1065 			status = read_fdreg(FDC_CS);
   1066 			if(status & (RNF | CRCERR)) {
   1067 				fd_error = "Seek error";
   1068 				sc->curtrk = INV_TRK;
   1069 				return(X_ERROR);
   1070 			}
   1071 			return(X_AGAIN);
   1072 		case RESTORE:
   1073 			/*
   1074 			 * Determine if the recalibration succeeded.
   1075 			 */
   1076 			status = read_fdreg(FDC_CS);
   1077 			if(status & RNF) {
   1078 				fd_error = "Recalibrate error";
   1079 				/* reset controller */
   1080 				write_fdreg(FDC_CS, IRUPT);
   1081 				sc->curtrk = INV_TRK;
   1082 				return(X_ERROR);
   1083 			}
   1084 			sc->curtrk = 0;
   1085 			if(fd_state == FLP_STAT) {
   1086 				if(status & WRI_PRO)
   1087 					sc->flags |= FLPF_WRTPROT;
   1088 				break;
   1089 			}
   1090 			return(X_AGAIN);
   1091 		default:
   1092 			fd_error = "Driver error: fd_xfer_ok : Unknown state";
   1093 			return(X_FAIL);
   1094 	}
   1095 	return(X_OK);
   1096 }
   1097 
   1098 /*
   1099  * All timeouts will call this function.
   1100  */
   1101 static void
   1102 fdmotoroff(sc)
   1103 struct fd_softc	*sc;
   1104 {
   1105 	int	sps;
   1106 
   1107 	/*
   1108 	 * Get at harware interrupt level
   1109 	 */
   1110 	sps = splbio();
   1111 
   1112 #if FLP_DEBUG
   1113 	printf("fdmotoroff, state = 0x%x\n", fd_state);
   1114 #endif
   1115 
   1116 	switch(fd_state) {
   1117 		case FLP_STAT :
   1118 		case FLP_XFER :
   1119 			/*
   1120 			 * Timeout during a transfer; cancel transaction
   1121 			 * set command to 'IRUPT'.
   1122 			 * A drive-interrupt is simulated to trigger the state
   1123 			 * machine.
   1124 			 */
   1125 			/*
   1126 			 * Cancel current transaction
   1127 			 */
   1128 			fd_cmd = IRUPT;
   1129 			write_fdreg(FDC_CS, IRUPT);
   1130 			delay(20);
   1131 			(void)read_fdreg(FDC_CS);
   1132 			write_fdreg(FDC_CS, RESTORE);
   1133 			break;
   1134 
   1135 		case FLP_MON  :
   1136 			/*
   1137 			 * Turn motor off.
   1138 			 */
   1139 			if(selected) {
   1140 				int tmp;
   1141 
   1142 				st_dmagrab((dma_farg)fdcint, (dma_farg)fdmoff,
   1143 								sc, &tmp, 0);
   1144 			}
   1145 			else  fd_state = FLP_IDLE;
   1146 			break;
   1147 	}
   1148 	splx(sps);
   1149 }
   1150 
   1151 /*
   1152  * min byte count to whats left of the track in question
   1153  */
   1154 static void
   1155 fdminphys(bp)
   1156 struct buf	*bp;
   1157 {
   1158 	struct fd_softc	*sc;
   1159 	int		sec, toff, tsz;
   1160 
   1161 	if((sc = getsoftc(fd_cd, DISKUNIT(bp->b_dev))) == NULL)
   1162 		panic("fdminphys: couldn't get softc");
   1163 
   1164 	sec  = bp->b_blkno % (sc->nsectors * sc->nheads);
   1165 	toff = sec * SECTOR_SIZE;
   1166 	tsz  = sc->nsectors * sc->nheads * SECTOR_SIZE;
   1167 
   1168 #ifdef FLP_DEBUG
   1169 	printf("fdminphys: before %d", bp->b_bcount);
   1170 #endif
   1171 
   1172 	bp->b_bcount = min(bp->b_bcount, tsz - toff);
   1173 
   1174 #ifdef FLP_DEBUG
   1175 	printf(" after %d\n", bp->b_bcount);
   1176 #endif
   1177 
   1178 	minphys(bp);
   1179 }
   1180 
   1181 /*
   1182  * Called from fdmotoroff to turn the motor actually off....
   1183  * This can't be done in fdmotoroff itself, because exclusive access to the
   1184  * DMA controller is needed to read the FDC-status register. The function
   1185  * 'fdmoff()' always runs as the result of a 'dmagrab()'.
   1186  * We need to test the status-register because we want to be sure that the
   1187  * drive motor is really off before deselecting the drive. The FDC only
   1188  * turns off the drive motor after having seen 10 index-pulses. You only
   1189  * get index-pulses when a drive is selected....This means that if the
   1190  * drive is deselected when the motor is still spinning, it will continue
   1191  * to spin _even_ when you insert a floppy later on...
   1192  */
   1193 static void
   1194 fdmoff(fdsoftc)
   1195 struct fd_softc	*fdsoftc;
   1196 {
   1197 	int tmp;
   1198 
   1199 	if ((fd_state == FLP_MON) && selected) {
   1200 		tmp = read_fdreg(FDC_CS);
   1201 		if (!(tmp & MOTORON)) {
   1202 			fddeselect();
   1203 			fd_state = FLP_IDLE;
   1204 		}
   1205 		else timeout((FPV)fdmotoroff, (void*)fdsoftc, 10*FLP_MONDELAY);
   1206 	}
   1207 	st_dmafree(fdsoftc, &tmp);
   1208 }
   1209 
   1210 /*
   1211  * Used to find out wich drives are actually connected. We do this by issueing
   1212  * is 'RESTORE' command and check if the 'track-0' bit is set. This also works
   1213  * if the drive is present but no floppy is inserted.
   1214  */
   1215 static void
   1216 fdtestdrv(fdsoftc)
   1217 struct fd_softc	*fdsoftc;
   1218 {
   1219 	int	status;
   1220 
   1221 	/*
   1222 	 * Select the right unit and head.
   1223 	 */
   1224 	fdselect(fdsoftc->unit, 0, FLP_DD);
   1225 
   1226 	write_fdreg(FDC_CS, RESTORE|HBIT);
   1227 
   1228 	/*
   1229 	 * Wait for about 2 seconds.
   1230 	 */
   1231 	delay(2000000);
   1232 
   1233 	status = read_fdreg(FDC_CS);
   1234 	if(status & (RNF|BUSY)) {
   1235 		write_fdreg(FDC_CS, IRUPT);	/* reset controller */
   1236 		delay(40);
   1237 	}
   1238 
   1239 	if(!(status & LD_T00))
   1240 		fdsoftc->flags |= FLPF_NOTRESP;
   1241 
   1242 	fddeselect();
   1243 }
   1244 
   1245 /*
   1246  * Build disk label. For now we only create a label from what we know
   1247  * from 'sc'.
   1248  */
   1249 static int
   1250 fdgetdisklabel(sc, dev)
   1251 struct fd_softc *sc;
   1252 dev_t			dev;
   1253 {
   1254 	struct disklabel	*lp;
   1255 	int			part;
   1256 
   1257 	/*
   1258 	 * If we already got one, get out.
   1259 	 */
   1260 	if(sc->flags & FLPF_HAVELAB)
   1261 		return(0);
   1262 
   1263 #ifdef FLP_DEBUG
   1264 	printf("fdgetdisklabel()\n");
   1265 #endif
   1266 
   1267 	part = DISKPART(dev);
   1268 	lp   = sc->dkdev.dk_label;
   1269 	bzero(lp, sizeof(struct disklabel));
   1270 
   1271 	lp->d_secsize     = SECTOR_SIZE;
   1272 	lp->d_ntracks     = sc->nheads;
   1273 	lp->d_nsectors    = sc->nsectors;
   1274 	lp->d_secpercyl   = lp->d_ntracks * lp->d_nsectors;
   1275 	lp->d_ncylinders  = sc->nblocks / lp->d_secpercyl;
   1276 	lp->d_secperunit  = sc->nblocks;
   1277 
   1278 	lp->d_type        = DTYPE_FLOPPY;
   1279 	lp->d_rpm         = 300; 	/* good guess I suppose.	*/
   1280 	lp->d_interleave  = 1;		/* FIXME: is this OK?		*/
   1281 	lp->d_bbsize      = 0;
   1282 	lp->d_sbsize      = 0;
   1283 	lp->d_npartitions = part + 1;
   1284 	lp->d_trkseek     = STEP_DELAY;
   1285 	lp->d_magic       = DISKMAGIC;
   1286 	lp->d_magic2      = DISKMAGIC;
   1287 	lp->d_checksum    = dkcksum(lp);
   1288 	lp->d_partitions[part].p_size   = lp->d_secperunit;
   1289 	lp->d_partitions[part].p_fstype = FS_UNUSED;
   1290 	lp->d_partitions[part].p_fsize  = 1024;
   1291 	lp->d_partitions[part].p_frag   = 8;
   1292 	sc->flags        |= FLPF_HAVELAB;
   1293 
   1294 	return(0);
   1295 }
   1296