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