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