Home | History | Annotate | Line # | Download | only in dev
fd.c revision 1.12
      1 /*	$NetBSD: fd.c,v 1.12 1995/12/10 14:25:12 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/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 static void	fdmoff __P((struct fd_softc *));
    189 
    190 extern __inline__ u_char read_fdreg(u_short regno)
    191 {
    192 	DMA->dma_mode = regno;
    193 	return(DMA->dma_data);
    194 }
    195 
    196 extern __inline__ void write_fdreg(u_short regno, u_short val)
    197 {
    198 	DMA->dma_mode = regno;
    199 	DMA->dma_data = val;
    200 }
    201 
    202 extern __inline__ u_char read_dmastat(void)
    203 {
    204 	DMA->dma_mode = FDC_CS | DMA_SCREG;
    205 	return(DMA->dma_stat);
    206 }
    207 
    208 /*
    209  * Autoconfig stuff....
    210  */
    211 static int	fdcmatch __P((struct device *, struct cfdata *, void *));
    212 static int	fdcprint __P((void *, char *));
    213 static void	fdcattach __P((struct device *, struct device *, void *));
    214 
    215 struct cfdriver fdccd = {
    216 	NULL, "fdc", (cfmatch_t)fdcmatch, fdcattach, DV_DULL,
    217 	sizeof(struct device), NULL, 0 };
    218 
    219 static int
    220 fdcmatch(pdp, cfp, auxp)
    221 struct device	*pdp;
    222 struct cfdata	*cfp;
    223 void		*auxp;
    224 {
    225 	if(strcmp("fdc", auxp) || cfp->cf_unit != 0)
    226 		return(0);
    227 	return(1);
    228 }
    229 
    230 static void
    231 fdcattach(pdp, dp, auxp)
    232 struct device	*pdp, *dp;
    233 void		*auxp;
    234 {
    235 	extern struct cfdriver fdcd;
    236 
    237 	struct fd_softc	fdsoftc;
    238 	int		i, nfound, first_found = 0;
    239 
    240 	printf("\n");
    241 	fddeselect();
    242 	for(i = 0; i < NR_DRIVES; i++) {
    243 
    244 		/*
    245 		 * Test if unit is present
    246 		 */
    247 		fdsoftc.unit  = i;
    248 		fdsoftc.flags = 0;
    249 		st_dmagrab(fdcint, fdtestdrv, &fdsoftc, &lock_stat, 0);
    250 		st_dmafree(&fdsoftc, &lock_stat);
    251 
    252 		if(!(fdsoftc.flags & FLPF_NOTRESP)) {
    253 			if(!nfound)
    254 				first_found = i;
    255 			nfound++;
    256 			config_found(dp, (void*)i, fdcprint);
    257 		}
    258 	}
    259 
    260 	if(nfound) {
    261 
    262 		/*
    263 		 * Make sure motor will be turned of when a floppy is
    264 		 * inserted in the first selected drive.
    265 		 */
    266 		fdselect(first_found, 0, FLP_DD);
    267 		fd_state = FLP_MON;
    268 		timeout((FPV)fdmotoroff, (void*)getsoftc(fdcd, first_found),
    269 					 			FLP_MONDELAY);
    270 
    271 		/*
    272 		 * enable disk related interrupts
    273 		 */
    274 		MFP->mf_ierb  |= IB_DINT;
    275 		MFP->mf_iprb  &= ~IB_DINT;
    276 		MFP->mf_imrb  |= IB_DINT;
    277 	}
    278 }
    279 
    280 static int
    281 fdcprint(auxp, pnp)
    282 void	*auxp;
    283 char	*pnp;
    284 {
    285 	return(UNCONF);
    286 }
    287 
    288 static int	fdmatch __P((struct device *, struct cfdata *, void *));
    289 static void	fdattach __P((struct device *, struct device *, void *));
    290 	   void fdstrategy __P((struct buf *));
    291 struct dkdriver fddkdriver = { fdstrategy };
    292 
    293 struct cfdriver fdcd = {
    294 	NULL, "fd", (cfmatch_t)fdmatch, fdattach, DV_DISK,
    295 	sizeof(struct fd_softc), NULL, 0 };
    296 
    297 static int
    298 fdmatch(pdp, cfp, auxp)
    299 struct device	*pdp;
    300 struct cfdata	*cfp;
    301 void		*auxp;
    302 {
    303 	int	unit = (int)auxp;
    304 	return(1);
    305 }
    306 
    307 static void
    308 fdattach(pdp, dp, auxp)
    309 struct device	*pdp, *dp;
    310 void		*auxp;
    311 {
    312 	struct fd_softc	*sc;
    313 
    314 	sc = (struct fd_softc *)dp;
    315 
    316 	printf("\n");
    317 
    318 	sc->dkdev.dk_driver = &fddkdriver;
    319 }
    320 
    321 fdioctl(dev, cmd, addr, flag, p)
    322 dev_t		dev;
    323 u_long		cmd;
    324 int		flag;
    325 caddr_t		addr;
    326 struct proc	*p;
    327 {
    328 	struct fd_softc *sc;
    329 	void		*data;
    330 
    331 	sc = getsoftc(fdcd, DISKUNIT(dev));
    332 
    333 	if((sc->flags & FLPF_HAVELAB) == 0)
    334 		return(EBADF);
    335 
    336 	switch(cmd) {
    337 		case DIOCSBAD:
    338 			return(EINVAL);
    339 		case DIOCGDINFO:
    340 			*(struct disklabel *)addr = sc->dkdev.dk_label;
    341 			return(0);
    342 		case DIOCGPART:
    343 			((struct partinfo *)addr)->disklab =
    344 				&sc->dkdev.dk_label;
    345 			((struct partinfo *)addr)->part =
    346 				&sc->dkdev.dk_label.d_partitions[DISKPART(dev)];
    347 			return(0);
    348 #ifdef notyet /* XXX LWP */
    349 		case DIOCSRETRIES:
    350 		case DIOCSSTEP:
    351 		case DIOCSDINFO:
    352 		case DIOCWDINFO:
    353 		case DIOCWLABEL:
    354 #endif /* notyet */
    355 		default:
    356 			return(ENOTTY);
    357 	}
    358 }
    359 
    360 /*
    361  * Open the device. If this is the first open on both the floppy devices,
    362  * intialize the controller.
    363  * Note that partition info on the floppy device is used to distinguise
    364  * between 780Kb and 360Kb floppy's.
    365  *	partition 0: 360Kb
    366  *	partition 1: 780Kb
    367  */
    368 Fdopen(dev, flags, devtype, proc)
    369 dev_t		dev;
    370 int		flags, devtype;
    371 struct proc	*proc;
    372 {
    373 	struct fd_softc	*sc;
    374 	int		sps;
    375 
    376 #ifdef FLP_DEBUG
    377 	printf("Fdopen dev=0x%x\n", dev);
    378 #endif
    379 
    380 	if(DISKPART(dev) >= NR_TYPES)
    381 		return(ENXIO);
    382 
    383 	if((sc = getsoftc(fdcd, DISKUNIT(dev))) == NULL)
    384 		return(ENXIO);
    385 
    386 	/*
    387 	 * If no floppy currently open, reset the controller and select
    388 	 * floppy type.
    389 	 */
    390 	if(!nopens) {
    391 
    392 #ifdef FLP_DEBUG
    393 		printf("Fdopen device not yet open\n");
    394 #endif
    395 		nopens++;
    396 		write_fdreg(FDC_CS, IRUPT);
    397 		delay(40);
    398 	}
    399 
    400 	/*
    401 	 * Sleep while other process is opening the device
    402 	 */
    403 	sps = splbio();
    404 	while(sc->flags & FLPF_INOPEN)
    405 		tsleep((caddr_t)sc, PRIBIO, "Fdopen", 0);
    406 	splx(sps);
    407 
    408 	if(!(sc->flags & FLPF_ISOPEN)) {
    409 		/*
    410 		 * Initialise some driver values.
    411 		 */
    412 		int	part = DISKPART(dev);
    413 		void	*addr;
    414 
    415 		sc->bufq.b_actf = NULL;
    416 		sc->unit        = DISKUNIT(dev);
    417 		sc->part        = part;
    418 		sc->nheads	= fdtypes[part].nheads;
    419 		sc->nsectors	= fdtypes[part].nsectors;
    420 		sc->nblocks     = fdtypes[part].nblocks;
    421 		sc->density	= fdtypes[part].density;
    422 		sc->curtrk	= INV_TRK;
    423 		sc->sector	= 0;
    424 		sc->errcnt	= 0;
    425 		sc->bounceb	= (u_char*)alloc_stmem(SECTOR_SIZE, &addr);
    426 		if(sc->bounceb == NULL)
    427 			return(ENOMEM); /* XXX */
    428 
    429 		/*
    430 		 * Go get write protect + loaded status
    431 		 */
    432 		sc->flags |= FLPF_INOPEN|FLPF_GETSTAT;
    433 		sps = splbio();
    434 		st_dmagrab(fdcint, fdstatus, sc, &lock_stat, 0);
    435 		while(sc->flags & FLPF_GETSTAT)
    436 			tsleep((caddr_t)sc, PRIBIO, "Fdopen", 0);
    437 		splx(sps);
    438 		wakeup((caddr_t)sc);
    439 
    440 		if((sc->flags & FLPF_WRTPROT) && (flags & FWRITE)) {
    441 			sc->flags = 0;
    442 			return(EPERM);
    443 		}
    444 		if(sc->flags & FLPF_EMPTY) {
    445 			sc->flags = 0;
    446 			return(ENXIO);
    447 		}
    448 		sc->flags &= ~(FLPF_INOPEN|FLPF_GETSTAT);
    449 		sc->flags |= FLPF_ISOPEN;
    450 	}
    451 	else {
    452 		/*
    453 		 * Multiply opens are granted when accessing the same type of
    454 		 * floppy (eq. the same partition).
    455 		 */
    456 		if(sc->part != DISKPART(dev))
    457 			return(ENXIO);	/* XXX temporarely out of business */
    458 	}
    459 	fdgetdisklabel(sc, dev);
    460 #ifdef FLP_DEBUG
    461 	printf("Fdopen open succeeded on type %d\n", sc->part);
    462 #endif
    463 }
    464 
    465 fdclose(dev, flags, devtype, proc)
    466 dev_t		dev;
    467 int		flags, devtype;
    468 struct proc	*proc;
    469 {
    470 	struct fd_softc	*sc;
    471 
    472 	sc = getsoftc(fdcd, DISKUNIT(dev));
    473 	free_stmem(sc->bounceb);
    474 	sc->flags = 0;
    475 	nopens--;
    476 
    477 #ifdef FLP_DEBUG
    478 	printf("Closed floppy device -- nopens: %d\n", nopens);
    479 #endif
    480 	return(0);
    481 }
    482 
    483 void
    484 fdstrategy(bp)
    485 struct buf	*bp;
    486 {
    487 	struct fd_softc	 *sc;
    488 	struct disklabel *lp;
    489 	int		 sps, nblocks;
    490 
    491 	sc = getsoftc(fdcd, DISKUNIT(bp->b_dev));
    492 
    493 #ifdef FLP_DEBUG
    494 	printf("fdstrategy: 0x%x\n", bp);
    495 #endif
    496 
    497 	/*
    498 	 * check for valid partition and bounds
    499 	 */
    500 	lp = &sc->dkdev.dk_label;
    501 	if ((sc->flags & FLPF_HAVELAB) == 0) {
    502 		bp->b_error = EIO;
    503 		goto bad;
    504 	}
    505 	if (bounds_check_with_label(bp, lp, 0) <= 0)
    506 		goto done;
    507 
    508 	if (bp->b_bcount == 0)
    509 		goto done;
    510 
    511 	/*
    512 	 * queue the buf and kick the low level code
    513 	 */
    514 	sps = splbio();
    515 	disksort(&sc->bufq, bp);
    516 	if (!lock_stat) {
    517 		if (fd_state & FLP_MON)
    518 			untimeout((FPV)fdmotoroff, (void*)sc);
    519 		fd_state = FLP_IDLE;
    520 		st_dmagrab(fdcint, fdstart, sc, &lock_stat, 0);
    521 	}
    522 	splx(sps);
    523 
    524 	return;
    525 bad:
    526 	bp->b_flags |= B_ERROR;
    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 				int tmp;
   1096 
   1097 				st_dmagrab(fdcint, fdmoff, sc, &tmp, 0);
   1098 			}
   1099 			else  fd_state = FLP_IDLE;
   1100 			break;
   1101 	}
   1102 	splx(sps);
   1103 }
   1104 
   1105 /*
   1106  * min byte count to whats left of the track in question
   1107  */
   1108 static void
   1109 fdminphys(bp)
   1110 struct buf	*bp;
   1111 {
   1112 	struct fd_softc	*sc;
   1113 	int		sec, toff, tsz;
   1114 
   1115 	if((sc = getsoftc(fdcd, DISKUNIT(bp->b_dev))) == NULL)
   1116 		panic("fdminphys: couldn't get softc");
   1117 
   1118 	sec  = bp->b_blkno % (sc->nsectors * sc->nheads);
   1119 	toff = sec * SECTOR_SIZE;
   1120 	tsz  = sc->nsectors * sc->nheads * SECTOR_SIZE;
   1121 
   1122 #ifdef FLP_DEBUG
   1123 	printf("fdminphys: before %d", bp->b_bcount);
   1124 #endif
   1125 
   1126 	bp->b_bcount = min(bp->b_bcount, tsz - toff);
   1127 
   1128 #ifdef FLP_DEBUG
   1129 	printf(" after %d\n", bp->b_bcount);
   1130 #endif
   1131 
   1132 	minphys(bp);
   1133 }
   1134 
   1135 /*
   1136  * Called from fdmotoroff to turn the motor actually off....
   1137  * This can't be done in fdmotoroff itself, because exclusive access to the
   1138  * DMA controller is needed to read the FDC-status register. The function
   1139  * 'fdmoff()' always runs as the result of a 'dmagrab()'.
   1140  * We need to test the status-register because we want to be sure that the
   1141  * drive motor is really off before deselecting the drive. The FDC only
   1142  * turns off the drive motor after having seen 10 index-pulses. You only
   1143  * get index-pulses when a drive is selected....This means that if the
   1144  * drive is deselected when the motor is still spinning, it will continue
   1145  * to spin _even_ when you insert a floppy later on...
   1146  */
   1147 static void
   1148 fdmoff(fdsoftc)
   1149 struct fd_softc	*fdsoftc;
   1150 {
   1151 	int tmp;
   1152 
   1153 	if ((fd_state == FLP_MON) && selected) {
   1154 		tmp = read_fdreg(FDC_CS);
   1155 		if (!(tmp & MOTORON)) {
   1156 			fddeselect();
   1157 			fd_state = FLP_IDLE;
   1158 		}
   1159 		else timeout((FPV)fdmotoroff, (void*)fdsoftc, 10*FLP_MONDELAY);
   1160 	}
   1161 	st_dmafree(fdsoftc, &tmp);
   1162 }
   1163 
   1164 /*
   1165  * Used to find out wich drives are actually connected. We do this by issueing
   1166  * is 'RESTORE' command and check if the 'track-0' bit is set. This also works
   1167  * if the drive is present but no floppy is inserted.
   1168  */
   1169 static void
   1170 fdtestdrv(fdsoftc)
   1171 struct fd_softc	*fdsoftc;
   1172 {
   1173 	int	i, status;
   1174 
   1175 	/*
   1176 	 * Select the right unit and head.
   1177 	 */
   1178 	fdselect(fdsoftc->unit, 0, FLP_DD);
   1179 
   1180 	write_fdreg(FDC_CS, RESTORE|HBIT);
   1181 
   1182 	/*
   1183 	 * Wait for about 2 seconds.
   1184 	 */
   1185 	delay(2000000);
   1186 
   1187 	status = read_fdreg(FDC_CS);
   1188 	if(status & (RNF|BUSY)) {
   1189 		write_fdreg(FDC_CS, IRUPT);	/* reset controller */
   1190 		delay(40);
   1191 	}
   1192 
   1193 	if(!(status & LD_T00))
   1194 		fdsoftc->flags |= FLPF_NOTRESP;
   1195 
   1196 	fddeselect();
   1197 }
   1198 
   1199 /*
   1200  * Build disk label. For now we only create a label from what we know
   1201  * from 'sc'.
   1202  */
   1203 static int
   1204 fdgetdisklabel(sc, dev)
   1205 struct fd_softc *sc;
   1206 dev_t			dev;
   1207 {
   1208 	struct disklabel	*lp, *dlp;
   1209 	int			part;
   1210 
   1211 	/*
   1212 	 * If we already got one, get out.
   1213 	 */
   1214 	if(sc->flags & FLPF_HAVELAB)
   1215 		return(0);
   1216 
   1217 #ifdef FLP_DEBUG
   1218 	printf("fdgetdisklabel()\n");
   1219 #endif
   1220 
   1221 	part = DISKPART(dev);
   1222 	lp   = &sc->dkdev.dk_label;
   1223 	bzero(lp, sizeof(struct disklabel));
   1224 
   1225 	lp->d_secsize     = SECTOR_SIZE;
   1226 	lp->d_ntracks     = sc->nheads;
   1227 	lp->d_nsectors    = sc->nsectors;
   1228 	lp->d_secpercyl   = lp->d_ntracks * lp->d_nsectors;
   1229 	lp->d_ncylinders  = sc->nblocks / lp->d_secpercyl;
   1230 	lp->d_secperunit  = sc->nblocks;
   1231 
   1232 	lp->d_type        = DTYPE_FLOPPY;
   1233 	lp->d_rpm         = 300; 	/* good guess I suppose.	*/
   1234 	lp->d_interleave  = 1;		/* FIXME: is this OK?		*/
   1235 	lp->d_bbsize      = 0;
   1236 	lp->d_sbsize      = 0;
   1237 	lp->d_npartitions = part + 1;
   1238 	lp->d_trkseek     = STEP_DELAY;
   1239 	lp->d_magic       = DISKMAGIC;
   1240 	lp->d_magic2      = DISKMAGIC;
   1241 	lp->d_checksum    = dkcksum(lp);
   1242 	lp->d_partitions[part].p_size   = lp->d_secperunit;
   1243 	lp->d_partitions[part].p_fstype = FS_UNUSED;
   1244 	lp->d_partitions[part].p_fsize  = 1024;
   1245 	lp->d_partitions[part].p_frag   = 8;
   1246 	sc->flags        |= FLPF_HAVELAB;
   1247 
   1248 	return(0);
   1249 }
   1250