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