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