xref: /freebsd/sys/dev/fdc/fdc.c (revision bb6382fa)
1 /*
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Don Ahn.
7  *
8  * Copyright (c) 1993, 1994 by
9  *  jc@irbs.UUCP (John Capo)
10  *  vak@zebub.msk.su (Serge Vakulenko)
11  *  ache@astral.msk.su (Andrew A. Chernov)
12  *
13  * Copyright (c) 1993, 1994, 1995 by
14  *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
15  *  dufault@hda.com (Peter Dufault)
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  * 3. All advertising materials mentioning features or use of this software
26  *    must display the following acknowledgement:
27  *	This product includes software developed by the University of
28  *	California, Berkeley and its contributors.
29  * 4. Neither the name of the University nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
34  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
37  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43  * SUCH DAMAGE.
44  *
45  *	from:	@(#)fd.c	7.4 (Berkeley) 5/25/91
46  *	$Id: fd.c,v 1.92 1996/09/06 23:07:18 phk Exp $
47  *
48  */
49 
50 #include "ft.h"
51 #if NFT < 1
52 #undef NFDC
53 #endif
54 #include "fd.h"
55 
56 #if NFDC > 0
57 
58 #include <sys/param.h>
59 #include <sys/systm.h>
60 #include <sys/kernel.h>
61 #include <sys/conf.h>
62 #include <sys/file.h>
63 #include <sys/ioctl.h>
64 #include <machine/clock.h>
65 #include <machine/ioctl_fd.h>
66 #include <sys/disklabel.h>
67 #include <sys/buf.h>
68 #include <sys/uio.h>
69 #include <sys/malloc.h>
70 #include <sys/proc.h>
71 #include <sys/syslog.h>
72 #include <sys/dkstat.h>
73 #include <i386/isa/isa.h>
74 #include <i386/isa/isa_device.h>
75 #include <i386/isa/fdreg.h>
76 #include <i386/isa/fdc.h>
77 #include <i386/isa/rtc.h>
78 #include <machine/stdarg.h>
79 #if NFT > 0
80 #include <sys/ftape.h>
81 #include <i386/isa/ftreg.h>
82 #endif
83 #ifdef DEVFS
84 #include <sys/devfsext.h>
85 #endif
86 
87 /* misuse a flag to identify format operation */
88 #define B_FORMAT B_XXX
89 
90 /*
91  * this biotab field doubles as a field for the physical unit number
92  * on the controller
93  */
94 #define id_physid id_scsiid
95 
96 /* error returns for fd_cmd() */
97 #define FD_FAILED -1
98 #define FD_NOT_VALID -2
99 #define FDC_ERRMAX	100	/* do not log more */
100 
101 #define NUMTYPES 14
102 #define NUMDENS  (NUMTYPES - 6)
103 
104 /* These defines (-1) must match index for fd_types */
105 #define F_TAPE_TYPE	0x020	/* bit for fd_types to indicate tape */
106 #define NO_TYPE		0	/* must match NO_TYPE in ft.c */
107 #define FD_1720         1
108 #define FD_1480         2
109 #define FD_1440         3
110 #define FD_1200         4
111 #define FD_820          5
112 #define FD_800          6
113 #define FD_720          7
114 #define FD_360          8
115 
116 #define FD_1480in5_25   9
117 #define FD_1440in5_25   10
118 #define FD_820in5_25    11
119 #define FD_800in5_25    12
120 #define FD_720in5_25    13
121 #define FD_360in5_25    14
122 
123 
124 static struct fd_type fd_types[NUMTYPES] =
125 {
126 { 21,2,0xFF,0x04,82,3444,1,FDC_500KBPS,2,0x0C,2 }, /* 1.72M in HD 3.5in */
127 { 18,2,0xFF,0x1B,82,2952,1,FDC_500KBPS,2,0x6C,1 }, /* 1.48M in HD 3.5in */
128 { 18,2,0xFF,0x1B,80,2880,1,FDC_500KBPS,2,0x6C,1 }, /* 1.44M in HD 3.5in */
129 { 15,2,0xFF,0x1B,80,2400,1,FDC_500KBPS,2,0x54,1 }, /*  1.2M in HD 5.25/3.5 */
130 { 10,2,0xFF,0x10,82,1640,1,FDC_250KBPS,2,0x2E,1 }, /*  820K in HD 3.5in */
131 { 10,2,0xFF,0x10,80,1600,1,FDC_250KBPS,2,0x2E,1 }, /*  800K in HD 3.5in */
132 {  9,2,0xFF,0x20,80,1440,1,FDC_250KBPS,2,0x50,1 }, /*  720K in HD 3.5in */
133 {  9,2,0xFF,0x2A,40, 720,1,FDC_250KBPS,2,0x50,1 }, /*  360K in DD 5.25in */
134 
135 { 18,2,0xFF,0x02,82,2952,1,FDC_500KBPS,2,0x02,2 }, /* 1.48M in HD 5.25in */
136 { 18,2,0xFF,0x02,80,2880,1,FDC_500KBPS,2,0x02,2 }, /* 1.44M in HD 5.25in */
137 { 10,2,0xFF,0x10,82,1640,1,FDC_300KBPS,2,0x2E,1 }, /*  820K in HD 5.25in */
138 { 10,2,0xFF,0x10,80,1600,1,FDC_300KBPS,2,0x2E,1 }, /*  800K in HD 5.25in */
139 {  9,2,0xFF,0x20,80,1440,1,FDC_300KBPS,2,0x50,1 }, /*  720K in HD 5.25in */
140 {  9,2,0xFF,0x23,40, 720,2,FDC_300KBPS,2,0x50,1 }, /*  360K in HD 5.25in */
141 };
142 
143 #define DRVS_PER_CTLR 2		/* 2 floppies */
144 
145 /***********************************************************************\
146 * Per controller structure.						*
147 \***********************************************************************/
148 struct fdc_data fdc_data[NFDC];
149 
150 /***********************************************************************\
151 * Per drive structure.							*
152 * N per controller  (DRVS_PER_CTLR)					*
153 \***********************************************************************/
154 static struct fd_data {
155 	struct	fdc_data *fdc;	/* pointer to controller structure */
156 	int	fdsu;		/* this units number on this controller */
157 	int	type;		/* Drive type (FD_1440...) */
158 	struct	fd_type *ft;	/* pointer to the type descriptor */
159 	int	flags;
160 #define	FD_OPEN		0x01	/* it's open		*/
161 #define	FD_ACTIVE	0x02	/* it's active		*/
162 #define	FD_MOTOR	0x04	/* motor should be on	*/
163 #define	FD_MOTOR_WAIT	0x08	/* motor coming up	*/
164 	int	skip;
165 	int	hddrv;
166 #define FD_NO_TRACK -2
167 	int	track;		/* where we think the head is */
168 	int	options;	/* user configurable options, see ioctl_fd.h */
169 	int	dkunit;		/* disk stats unit number */
170 #ifdef DEVFS
171 	void	*bdevs[1 + NUMDENS + MAXPARTITIONS];
172 	void	*cdevs[1 + NUMDENS + MAXPARTITIONS];
173 #endif
174 } fd_data[NFD];
175 
176 /***********************************************************************\
177 * Throughout this file the following conventions will be used:		*
178 * fd is a pointer to the fd_data struct for the drive in question	*
179 * fdc is a pointer to the fdc_data struct for the controller		*
180 * fdu is the floppy drive unit number					*
181 * fdcu is the floppy controller unit number				*
182 * fdsu is the floppy drive unit number on that controller. (sub-unit)	*
183 \***********************************************************************/
184 
185 #if NFT > 0
186 int ftopen(dev_t, int);
187 int ftintr(ftu_t ftu);
188 int ftclose(dev_t, int);
189 void ftstrategy(struct buf *);
190 int ftioctl(dev_t, int, caddr_t, int, struct proc *);
191 int ftdump(dev_t);
192 int ftsize(dev_t);
193 int ftattach(struct isa_device *, struct isa_device *, int);
194 #endif
195 
196 /* autoconfig functions */
197 static int fdprobe(struct isa_device *);
198 static int fdattach(struct isa_device *);
199 
200 /* needed for ft driver, thus exported */
201 int in_fdc(fdcu_t);
202 int out_fdc(fdcu_t, int);
203 
204 /* internal functions */
205 static void set_motor(fdcu_t, int, int);
206 #  define TURNON 1
207 #  define TURNOFF 0
208 static timeout_t fd_turnoff;
209 static timeout_t fd_motor_on;
210 static void fd_turnon(fdu_t);
211 static void fdc_reset(fdc_p);
212 static int fd_in(fdcu_t, int *);
213 static void fdstart(fdcu_t);
214 static timeout_t fd_timeout;
215 static timeout_t fd_pseudointr;
216 static int fdstate(fdcu_t, fdc_p);
217 static int retrier(fdcu_t);
218 static int fdformat(dev_t, struct fd_formb *, struct proc *);
219 
220 
221 #define DEVIDLE		0
222 #define FINDWORK	1
223 #define	DOSEEK		2
224 #define SEEKCOMPLETE 	3
225 #define	IOCOMPLETE	4
226 #define RECALCOMPLETE	5
227 #define	STARTRECAL	6
228 #define	RESETCTLR	7
229 #define	SEEKWAIT	8
230 #define	RECALWAIT	9
231 #define	MOTORWAIT	10
232 #define	IOTIMEDOUT	11
233 
234 #ifdef	DEBUG
235 static char const * const fdstates[] =
236 {
237 "DEVIDLE",
238 "FINDWORK",
239 "DOSEEK",
240 "SEEKCOMPLETE",
241 "IOCOMPLETE",
242 "RECALCOMPLETE",
243 "STARTRECAL",
244 "RESETCTLR",
245 "SEEKWAIT",
246 "RECALWAIT",
247 "MOTORWAIT",
248 "IOTIMEDOUT"
249 };
250 
251 /* CAUTION: fd_debug causes huge amounts of logging output */
252 static int volatile fd_debug = 0;
253 #define TRACE0(arg) if(fd_debug) printf(arg)
254 #define TRACE1(arg1, arg2) if(fd_debug) printf(arg1, arg2)
255 #else /* DEBUG */
256 #define TRACE0(arg)
257 #define TRACE1(arg1, arg2)
258 #endif /* DEBUG */
259 
260 /* autoconfig structure */
261 
262 struct	isa_driver fdcdriver = {
263 	fdprobe, fdattach, "fdc",
264 };
265 
266 static	d_open_t	Fdopen;	/* NOTE, not fdopen */
267 static	d_close_t	fdclose;
268 static	d_ioctl_t	fdioctl;
269 static	d_strategy_t	fdstrategy;
270 
271 #define CDEV_MAJOR 9
272 #define BDEV_MAJOR 2
273 static struct cdevsw fd_cdevsw;
274 static struct bdevsw fd_bdevsw =
275 	{ Fdopen,	fdclose,	fdstrategy,	fdioctl,	/*2*/
276 	  nodump,	nopsize,	0,	"fd",	&fd_cdevsw,	-1 };
277 
278 
279 static struct isa_device *fdcdevs[NFDC];
280 
281 static int
282 fdc_err(fdcu_t fdcu, const char *s)
283 {
284 	fdc_data[fdcu].fdc_errs++;
285 	if(s) {
286 		if(fdc_data[fdcu].fdc_errs < FDC_ERRMAX)
287 			printf("fdc%d: %s", fdcu, s);
288 		else if(fdc_data[fdcu].fdc_errs == FDC_ERRMAX)
289 			printf("fdc%d: too many errors, not logging any more\n",
290 			       fdcu);
291 	}
292 
293 	return FD_FAILED;
294 }
295 
296 /*
297  * fd_cmd: Send a command to the chip.  Takes a varargs with this structure:
298  * Unit number,
299  * # of output bytes, output bytes as ints ...,
300  * # of input bytes, input bytes as ints ...
301  */
302 
303 static int
304 fd_cmd(fdcu_t fdcu, int n_out, ...)
305 {
306 	u_char cmd;
307 	int n_in;
308 	int n;
309 	va_list ap;
310 
311 	va_start(ap, n_out);
312 	cmd = (u_char)(va_arg(ap, int));
313 	va_end(ap);
314 	va_start(ap, n_out);
315 	for (n = 0; n < n_out; n++)
316 	{
317 		if (out_fdc(fdcu, va_arg(ap, int)) < 0)
318 		{
319 			char msg[50];
320 			sprintf(msg,
321 				"cmd %x failed at out byte %d of %d\n",
322 				cmd, n + 1, n_out);
323 			return fdc_err(fdcu, msg);
324 		}
325 	}
326 	n_in = va_arg(ap, int);
327 	for (n = 0; n < n_in; n++)
328 	{
329 		int *ptr = va_arg(ap, int *);
330 		if (fd_in(fdcu, ptr) < 0)
331 		{
332 			char msg[50];
333 			sprintf(msg,
334 				"cmd %02x failed at in byte %d of %d\n",
335 				cmd, n + 1, n_in);
336 			return fdc_err(fdcu, msg);
337 		}
338 	}
339 
340 	return 0;
341 }
342 
343 static int
344 fd_sense_drive_status(fdc_p fdc, int *st3p)
345 {
346 	int st3;
347 
348 	if (fd_cmd(fdc->fdcu, 2, NE7CMD_SENSED, fdc->fdu, 1, &st3))
349 	{
350 		return fdc_err(fdc->fdcu, "Sense Drive Status failed\n");
351 	}
352 	if (st3p)
353 		*st3p = st3;
354 
355 	return 0;
356 }
357 
358 static int
359 fd_sense_int(fdc_p fdc, int *st0p, int *cylp)
360 {
361 	int st0, cyl;
362 
363 	int ret = fd_cmd(fdc->fdcu, 1, NE7CMD_SENSEI, 1, &st0);
364 
365 	if (ret)
366 	{
367 		(void)fdc_err(fdc->fdcu,
368 			      "sense intr err reading stat reg 0\n");
369 		return ret;
370 	}
371 
372 	if (st0p)
373 		*st0p = st0;
374 
375 	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV)
376 	{
377 		/*
378 		 * There doesn't seem to have been an interrupt.
379 		 */
380 		return FD_NOT_VALID;
381 	}
382 
383 	if (fd_in(fdc->fdcu, &cyl) < 0)
384 	{
385 		return fdc_err(fdc->fdcu, "can't get cyl num\n");
386 	}
387 
388 	if (cylp)
389 		*cylp = cyl;
390 
391 	return 0;
392 }
393 
394 
395 static int
396 fd_read_status(fdc_p fdc, int fdsu)
397 {
398 	int i, ret;
399 
400 	for (i = 0; i < 7; i++)
401 	{
402 		/*
403 		 * XXX types are poorly chosen.  Only bytes can by read
404 		 * from the hardware, but fdc_status wants u_longs and
405 		 * fd_in() gives ints.
406 		 */
407 		int status;
408 
409 		ret = fd_in(fdc->fdcu, &status);
410 		fdc->status[i] = status;
411 		if (ret != 0)
412 			break;
413 	}
414 
415 	if (ret == 0)
416 		fdc->flags |= FDC_STAT_VALID;
417 	else
418 		fdc->flags &= ~FDC_STAT_VALID;
419 
420 	return ret;
421 }
422 
423 /****************************************************************************/
424 /*                      autoconfiguration stuff                             */
425 /****************************************************************************/
426 
427 /*
428  * probe for existance of controller
429  */
430 static int
431 fdprobe(struct isa_device *dev)
432 {
433 	fdcu_t	fdcu = dev->id_unit;
434 	if(fdc_data[fdcu].flags & FDC_ATTACHED)
435 	{
436 		printf("fdc%d: unit used multiple times\n", fdcu);
437 		return 0;
438 	}
439 
440 	fdcdevs[fdcu] = dev;
441 	fdc_data[fdcu].baseport = dev->id_iobase;
442 
443 	/* First - lets reset the floppy controller */
444 	outb(dev->id_iobase+FDOUT, 0);
445 	DELAY(100);
446 	outb(dev->id_iobase+FDOUT, FDO_FRST);
447 
448 	/* see if it can handle a command */
449 	if (fd_cmd(fdcu,
450 		   3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
451 		   0))
452 	{
453 		return(0);
454 	}
455 	return (IO_FDCSIZE);
456 }
457 
458 /*
459  * wire controller into system, look for floppy units
460  */
461 static int
462 fdattach(struct isa_device *dev)
463 {
464 	unsigned fdt;
465 	fdu_t	fdu;
466 	fdcu_t	fdcu = dev->id_unit;
467 	fdc_p	fdc = fdc_data + fdcu;
468 	fd_p	fd;
469 	int	fdsu, st0, st3, i;
470 #if NFT > 0
471 	int	unithasfd;
472 #endif
473 	struct isa_device *fdup;
474 	int ic_type = 0;
475 #ifdef DEVFS
476 	int	mynor;
477 	int	typemynor;
478 	int	typesize;
479 #endif
480 
481 	fdc->fdcu = fdcu;
482 	fdc->flags |= FDC_ATTACHED;
483 	fdc->dmachan = dev->id_drq;
484 	/* Acquire the DMA channel forever, The driver will do the rest */
485 	isa_dma_acquire(fdc->dmachan);
486 	isa_dmainit(fdc->dmachan, 128 << 3 /* XXX max secsize */);
487 	fdc->state = DEVIDLE;
488 	/* reset controller, turn motor off, clear fdout mirror reg */
489 	outb(fdc->baseport + FDOUT, ((fdc->fdout = 0)));
490 	TAILQ_INIT(&fdc->head);
491 
492 	/* check for each floppy drive */
493 	for (fdup = isa_biotab_fdc; fdup->id_driver != 0; fdup++) {
494 		if (fdup->id_iobase != dev->id_iobase)
495 			continue;
496 		fdu = fdup->id_unit;
497 		fd = &fd_data[fdu];
498 		if (fdu >= (NFD+NFT))
499 			continue;
500 		fdsu = fdup->id_physid;
501 		/* look up what bios thinks we have */
502 		switch (fdu) {
503 			case 0: fdt = (rtcin(RTC_FDISKETTE) & 0xf0);
504 				break;
505 			case 1: fdt = ((rtcin(RTC_FDISKETTE) << 4) & 0xf0);
506 				break;
507 			default: fdt = RTCFDT_NONE;
508 				break;
509 		}
510 		/* is there a unit? */
511 		if ((fdt == RTCFDT_NONE)
512 #if NFT > 0
513 		    || (fdsu >= DRVS_PER_CTLR)) {
514 #else
515 		) {
516 			fd->type = NO_TYPE;
517 #endif
518 #if NFT > 0
519 			/* If BIOS says no floppy, or > 2nd device */
520 			/* Probe for and attach a floppy tape.     */
521 			/* Tell FT if there was already a disk     */
522 			/* with this unit number found.            */
523 
524 			unithasfd = 0;
525 			if (fdu < NFD && fd->type != NO_TYPE)
526 				unithasfd = 1;
527 			if (ftattach(dev, fdup, unithasfd))
528 				continue;
529 			if (fdsu < DRVS_PER_CTLR)
530 				fd->type = NO_TYPE;
531 #endif
532 			continue;
533 		}
534 
535 		/* select it */
536 		set_motor(fdcu, fdsu, TURNON);
537 		DELAY(1000000);	/* 1 sec */
538 
539 		if (ic_type == 0 &&
540 		    fd_cmd(fdcu, 1, NE7CMD_VERSION, 1, &ic_type) == 0)
541 		{
542 			printf("fdc%d: ", fdcu);
543 			ic_type = (u_char)ic_type;
544 			switch( ic_type ) {
545 			case 0x80:
546 				printf("NEC 765\n");
547 				fdc->fdct = FDC_NE765;
548 				break;
549 			case 0x81:
550 				printf("Intel 82077\n");
551 				fdc->fdct = FDC_I82077;
552 				break;
553 			case 0x90:
554 				printf("NEC 72065B\n");
555 				fdc->fdct = FDC_NE72065;
556 				break;
557 			default:
558 				printf("unknown IC type %02x\n", ic_type);
559 				fdc->fdct = FDC_UNKNOWN;
560 				break;
561 			}
562 		}
563 		if ((fd_cmd(fdcu, 2, NE7CMD_SENSED, fdsu, 1, &st3) == 0) &&
564 		    (st3 & NE7_ST3_T0)) {
565 			/* if at track 0, first seek inwards */
566 			/* seek some steps: */
567 			(void)fd_cmd(fdcu, 3, NE7CMD_SEEK, fdsu, 10, 0);
568 			DELAY(300000); /* ...wait a moment... */
569 			(void)fd_sense_int(fdc, 0, 0); /* make ctrlr happy */
570 		}
571 
572 		/* If we're at track 0 first seek inwards. */
573 		if ((fd_sense_drive_status(fdc, &st3) == 0) &&
574 		    (st3 & NE7_ST3_T0)) {
575 			/* Seek some steps... */
576 			if (fd_cmd(fdcu, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
577 				/* ...wait a moment... */
578 				DELAY(300000);
579 				/* make ctrlr happy: */
580 				(void)fd_sense_int(fdc, 0, 0);
581 			}
582 		}
583 
584 		for(i = 0; i < 2; i++) {
585 			/*
586 			 * we must recalibrate twice, just in case the
587 			 * heads have been beyond cylinder 76, since most
588 			 * FDCs still barf when attempting to recalibrate
589 			 * more than 77 steps
590 			 */
591 			/* go back to 0: */
592 			if (fd_cmd(fdcu, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
593 				/* a second being enough for full stroke seek*/
594 				DELAY(i == 0? 1000000: 300000);
595 
596 				/* anything responding? */
597 				if (fd_sense_int(fdc, &st0, 0) == 0 &&
598 				(st0 & NE7_ST0_EC) == 0)
599 					break; /* already probed succesfully */
600 			}
601 		}
602 
603 		set_motor(fdcu, fdsu, TURNOFF);
604 
605 		if (st0 & NE7_ST0_EC) /* no track 0 -> no drive present */
606 			continue;
607 
608 		fd->track = FD_NO_TRACK;
609 		fd->fdc = fdc;
610 		fd->fdsu = fdsu;
611 		fd->options = 0;
612 		printf("fd%d: ", fdu);
613 
614 		switch (fdt) {
615 		case RTCFDT_12M:
616 			printf("1.2MB 5.25in\n");
617 			fd->type = FD_1200;
618 			break;
619 		case RTCFDT_144M:
620 			printf("1.44MB 3.5in\n");
621 			fd->type = FD_1440;
622 			break;
623 		case RTCFDT_288M:
624 		case RTCFDT_288M_1:
625 			printf("2.88MB 3.5in - 1.44MB mode\n");
626 			fd->type = FD_1440;
627 			break;
628 		case RTCFDT_360K:
629 			printf("360KB 5.25in\n");
630 			fd->type = FD_360;
631 			break;
632 		case RTCFDT_720K:
633 			printf("720KB 3.5in\n");
634 			fd->type = FD_720;
635 			break;
636 		default:
637 			printf("unknown\n");
638 			fd->type = NO_TYPE;
639 			continue;
640 		}
641 #ifdef DEVFS
642 		mynor = fdu << 6;
643 		fd->bdevs[0] = devfs_add_devswf(&fd_bdevsw, mynor, DV_BLK,
644 						UID_ROOT, GID_OPERATOR, 0640,
645 						"fd%d", fdu);
646 		fd->cdevs[0] = devfs_add_devswf(&fd_cdevsw, mynor, DV_CHR,
647 						UID_ROOT, GID_OPERATOR, 0640,
648 						"rfd%d", fdu);
649 		for (i = 1; i < 1 + NUMDENS; i++) {
650 			/*
651 			 * XXX this and the lookup in Fdopen() should be
652 			 * data driven.
653 			 */
654 			switch (fd->type) {
655 			case FD_360:
656 				if (i != FD_360)
657 					continue;
658 				break;
659 			case FD_720:
660 				if (i != FD_720 && i != FD_800 && i != FD_820)
661 					continue;
662 				break;
663 			case FD_1200:
664 				if (i != FD_360 && i != FD_720 && i != FD_800
665 				    && i != FD_820 && i != FD_1200
666 				    && i != FD_1440 && i != FD_1480)
667 					continue;
668 				break;
669 			case FD_1440:
670 				if (i != FD_720 && i != FD_800 && i != FD_820
671 				    && i != FD_1200 && i != FD_1440
672 				    && i != FD_1480 && i != FD_1720)
673 					continue;
674 				break;
675 			}
676 			typemynor = mynor | i;
677 			typesize = fd_types[i - 1].size / 2;
678 			/*
679 			 * XXX all these conversions give bloated code and
680 			 * confusing names.
681 			 */
682 			if (typesize == 1476)
683 				typesize = 1480;
684 			if (typesize == 1722)
685 				typesize = 1720;
686 			fd->bdevs[i] =
687 				devfs_add_devswf(&fd_bdevsw, typemynor, DV_BLK,
688 						 UID_ROOT, GID_OPERATOR, 0640,
689 						 "fd%d.%d", fdu, typesize);
690 			fd->cdevs[i] =
691 				devfs_add_devswf(&fd_cdevsw, typemynor, DV_CHR,
692 						 UID_ROOT, GID_OPERATOR, 0640,
693 						 "rfd%d.%d", fdu, typesize);
694 		}
695 		for (i = 0; i < MAXPARTITIONS; i++) {
696 			fd->bdevs[1 + NUMDENS + i] =
697 				devfs_link(fd->bdevs[0],
698 					   "fd%d%c", fdu, 'a' + i);
699 			fd->cdevs[1 + NUMDENS + i] =
700 				devfs_link(fd->cdevs[0],
701 					   "rfd%d%c", fdu, 'a' + i);
702 		}
703 #endif /* DEVFS */
704 		if (dk_ndrive < DK_NDRIVE) {
705 			sprintf(dk_names[dk_ndrive], "fd%d", fdu);
706 			fd->dkunit = dk_ndrive++;
707 			/*
708 			 * XXX assume rate is FDC_500KBPS.
709 			 */
710 			dk_wpms[dk_ndrive] = 500000 / 8 / 2;
711 		} else {
712 			fd->dkunit = -1;
713 		}
714 	}
715 
716 	return (1);
717 }
718 
719 /****************************************************************************/
720 /*                            motor control stuff                           */
721 /*		remember to not deselect the drive we're working on         */
722 /****************************************************************************/
723 static void
724 set_motor(fdcu_t fdcu, int fdsu, int turnon)
725 {
726 	int fdout = fdc_data[fdcu].fdout;
727 	int needspecify = 0;
728 
729 	if(turnon) {
730 		fdout &= ~FDO_FDSEL;
731 		fdout |= (FDO_MOEN0 << fdsu) + fdsu;
732 	} else
733 		fdout &= ~(FDO_MOEN0 << fdsu);
734 
735 	if(!turnon
736 	   && (fdout & (FDO_MOEN0+FDO_MOEN1+FDO_MOEN2+FDO_MOEN3)) == 0)
737 		/* gonna turn off the last drive, put FDC to bed */
738 		fdout &= ~ (FDO_FRST|FDO_FDMAEN);
739 	else {
740 		/* make sure controller is selected and specified */
741 		if((fdout & (FDO_FRST|FDO_FDMAEN)) == 0)
742 			needspecify = 1;
743 		fdout |= (FDO_FRST|FDO_FDMAEN);
744 	}
745 
746 	outb(fdc_data[fdcu].baseport+FDOUT, fdout);
747 	fdc_data[fdcu].fdout = fdout;
748 	TRACE1("[0x%x->FDOUT]", fdout);
749 
750 	if(needspecify) {
751 		/*
752 		 * XXX
753 		 * special case: since we have just woken up the FDC
754 		 * from its sleep, we silently assume the command will
755 		 * be accepted, and do not test for a timeout
756 		 */
757 		(void)fd_cmd(fdcu, 3, NE7CMD_SPECIFY,
758 			     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
759 			     0);
760 	}
761 }
762 
763 static void
764 fd_turnoff(void *arg1)
765 {
766 	fdu_t fdu = (fdu_t)arg1;
767 	int	s;
768 	fd_p fd = fd_data + fdu;
769 
770 	TRACE1("[fd%d: turnoff]", fdu);
771 
772 	/*
773 	 * Don't turn off the motor yet if the drive is active.
774 	 * XXX shouldn't even schedule turnoff until drive is inactive
775 	 * and nothing is queued on it.
776 	 */
777 	if (fd->fdc->state != DEVIDLE && fd->fdc->fdu == fdu) {
778 		timeout(fd_turnoff, arg1, 4 * hz);
779 		return;
780 	}
781 
782 	s = splbio();
783 	fd->flags &= ~FD_MOTOR;
784 	set_motor(fd->fdc->fdcu, fd->fdsu, TURNOFF);
785 	splx(s);
786 }
787 
788 static void
789 fd_motor_on(void *arg1)
790 {
791 	fdu_t fdu = (fdu_t)arg1;
792 	int	s;
793 
794 	fd_p fd = fd_data + fdu;
795 	s = splbio();
796 	fd->flags &= ~FD_MOTOR_WAIT;
797 	if((fd->fdc->fd == fd) && (fd->fdc->state == MOTORWAIT))
798 	{
799 		fdintr(fd->fdc->fdcu);
800 	}
801 	splx(s);
802 }
803 
804 static void
805 fd_turnon(fdu_t fdu)
806 {
807 	fd_p fd = fd_data + fdu;
808 	if(!(fd->flags & FD_MOTOR))
809 	{
810 		fd->flags |= (FD_MOTOR + FD_MOTOR_WAIT);
811 		set_motor(fd->fdc->fdcu, fd->fdsu, TURNON);
812 		timeout(fd_motor_on, (caddr_t)fdu, hz); /* in 1 sec its ok */
813 	}
814 }
815 
816 static void
817 fdc_reset(fdc_p fdc)
818 {
819 	fdcu_t fdcu = fdc->fdcu;
820 
821 	/* Try a reset, keep motor on */
822 	outb(fdc->baseport + FDOUT, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
823 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
824 	DELAY(100);
825 	/* enable FDC, but defer interrupts a moment */
826 	outb(fdc->baseport + FDOUT, fdc->fdout & ~FDO_FDMAEN);
827 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~FDO_FDMAEN);
828 	DELAY(100);
829 	outb(fdc->baseport + FDOUT, fdc->fdout);
830 	TRACE1("[0x%x->FDOUT]", fdc->fdout);
831 
832 	/* XXX after a reset, silently believe the FDC will accept commands */
833 	(void)fd_cmd(fdcu, 3, NE7CMD_SPECIFY,
834 		     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
835 		     0);
836 }
837 
838 /****************************************************************************/
839 /*                             fdc in/out                                   */
840 /****************************************************************************/
841 int
842 in_fdc(fdcu_t fdcu)
843 {
844 	int baseport = fdc_data[fdcu].baseport;
845 	int i, j = 100000;
846 	while ((i = inb(baseport+FDSTS) & (NE7_DIO|NE7_RQM))
847 		!= (NE7_DIO|NE7_RQM) && j-- > 0)
848 		if (i == NE7_RQM)
849 			return fdc_err(fdcu, "ready for output in input\n");
850 	if (j <= 0)
851 		return fdc_err(fdcu, bootverbose? "input ready timeout\n": 0);
852 #ifdef	DEBUG
853 	i = inb(baseport+FDDATA);
854 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
855 	return(i);
856 #else
857 	return inb(baseport+FDDATA);
858 #endif
859 }
860 
861 /*
862  * fd_in: Like in_fdc, but allows you to see if it worked.
863  */
864 static int
865 fd_in(fdcu_t fdcu, int *ptr)
866 {
867 	int baseport = fdc_data[fdcu].baseport;
868 	int i, j = 100000;
869 	while ((i = inb(baseport+FDSTS) & (NE7_DIO|NE7_RQM))
870 		!= (NE7_DIO|NE7_RQM) && j-- > 0)
871 		if (i == NE7_RQM)
872 			return fdc_err(fdcu, "ready for output in input\n");
873 	if (j <= 0)
874 		return fdc_err(fdcu, bootverbose? "input ready timeout\n": 0);
875 #ifdef	DEBUG
876 	i = inb(baseport+FDDATA);
877 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
878 	*ptr = i;
879 	return 0;
880 #else
881 	i = inb(baseport+FDDATA);
882 	if (ptr)
883 		*ptr = i;
884 	return 0;
885 #endif
886 }
887 
888 int
889 out_fdc(fdcu_t fdcu, int x)
890 {
891 	int baseport = fdc_data[fdcu].baseport;
892 	int i;
893 
894 	/* Check that the direction bit is set */
895 	i = 100000;
896 	while ((inb(baseport+FDSTS) & NE7_DIO) && i-- > 0);
897 	if (i <= 0) return fdc_err(fdcu, "direction bit not set\n");
898 
899 	/* Check that the floppy controller is ready for a command */
900 	i = 100000;
901 	while ((inb(baseport+FDSTS) & NE7_RQM) == 0 && i-- > 0);
902 	if (i <= 0)
903 		return fdc_err(fdcu, bootverbose? "output ready timeout\n": 0);
904 
905 	/* Send the command and return */
906 	outb(baseport+FDDATA, x);
907 	TRACE1("[0x%x->FDDATA]", x);
908 	return (0);
909 }
910 
911 /****************************************************************************/
912 /*                           fdopen/fdclose                                 */
913 /****************************************************************************/
914 int
915 Fdopen(dev_t dev, int flags, int mode, struct proc *p)
916 {
917  	fdu_t fdu = FDUNIT(minor(dev));
918 	int type = FDTYPE(minor(dev));
919 	fdc_p	fdc;
920 
921 #if NFT > 0
922 	/* check for a tape open */
923 	if (type & F_TAPE_TYPE)
924 		return(ftopen(dev, flags));
925 #endif
926 	/* check bounds */
927 	if (fdu >= NFD)
928 		return(ENXIO);
929 	fdc = fd_data[fdu].fdc;
930 	if ((fdc == NULL) || (fd_data[fdu].type == NO_TYPE))
931 		return(ENXIO);
932 	if (type > NUMDENS)
933 		return(ENXIO);
934 	if (type == 0)
935 		type = fd_data[fdu].type;
936 	else {
937 		if (type != fd_data[fdu].type) {
938 			switch (fd_data[fdu].type) {
939 			case FD_360:
940 				return(ENXIO);
941 			case FD_720:
942 				if (   type != FD_820
943 				    && type != FD_800
944 				   )
945 					return(ENXIO);
946 				break;
947 			case FD_1200:
948 				switch (type) {
949 				case FD_1480:
950 					type = FD_1480in5_25;
951 					break;
952 				case FD_1440:
953 					type = FD_1440in5_25;
954 					break;
955 				case FD_820:
956 					type = FD_820in5_25;
957 					break;
958 				case FD_800:
959 					type = FD_800in5_25;
960 					break;
961 				case FD_720:
962 					type = FD_720in5_25;
963 					break;
964 				case FD_360:
965 					type = FD_360in5_25;
966 					break;
967 				default:
968 					return(ENXIO);
969 				}
970 				break;
971 			case FD_1440:
972 				if (   type != FD_1720
973 				    && type != FD_1480
974 				    && type != FD_1200
975 				    && type != FD_820
976 				    && type != FD_800
977 				    && type != FD_720
978 				    )
979 					return(ENXIO);
980 				break;
981 			}
982 		}
983 	}
984 	fd_data[fdu].ft = fd_types + type - 1;
985 	fd_data[fdu].flags |= FD_OPEN;
986 
987 	return 0;
988 }
989 
990 int
991 fdclose(dev_t dev, int flags, int mode, struct proc *p)
992 {
993  	fdu_t fdu = FDUNIT(minor(dev));
994 
995 #if NFT > 0
996 	int type = FDTYPE(minor(dev));
997 
998 	if (type & F_TAPE_TYPE)
999 		return ftclose(dev, flags);
1000 #endif
1001 	fd_data[fdu].flags &= ~FD_OPEN;
1002 	fd_data[fdu].options &= ~FDOPT_NORETRY;
1003 
1004 	return(0);
1005 }
1006 
1007 
1008 /****************************************************************************/
1009 /*                               fdstrategy                                 */
1010 /****************************************************************************/
1011 void
1012 fdstrategy(struct buf *bp)
1013 {
1014 	unsigned nblocks, blknum, cando;
1015  	int	s;
1016  	fdcu_t	fdcu;
1017  	fdu_t	fdu;
1018  	fdc_p	fdc;
1019  	fd_p	fd;
1020 	size_t	fdblk;
1021 
1022  	fdu = FDUNIT(minor(bp->b_dev));
1023 	fd = &fd_data[fdu];
1024 	fdc = fd->fdc;
1025 	fdcu = fdc->fdcu;
1026 
1027 #if NFT > 0
1028 	if (FDTYPE(minor(bp->b_dev)) & F_TAPE_TYPE) {
1029 		/* ft tapes do not (yet) support strategy i/o */
1030 		bp->b_error = ENODEV;
1031 		bp->b_flags |= B_ERROR;
1032 		goto bad;
1033 	}
1034 	/* check for controller already busy with tape */
1035 	if (fdc->flags & FDC_TAPE_BUSY) {
1036 		bp->b_error = EBUSY;
1037 		bp->b_flags |= B_ERROR;
1038 		goto bad;
1039 	}
1040 #endif
1041 	fdblk = 128 << (fd->ft->secsize);
1042 	if (!(bp->b_flags & B_FORMAT)) {
1043 		if ((fdu >= NFD) || (bp->b_blkno < 0)) {
1044 			printf(
1045 		"fd%d: fdstrat: bad request blkno = %lu, bcount = %ld\n",
1046 			       fdu, (u_long)bp->b_blkno, bp->b_bcount);
1047 			bp->b_error = EINVAL;
1048 			bp->b_flags |= B_ERROR;
1049 			goto bad;
1050 		}
1051 		if ((bp->b_bcount % fdblk) != 0) {
1052 			bp->b_error = EINVAL;
1053 			bp->b_flags |= B_ERROR;
1054 			goto bad;
1055 		}
1056 	}
1057 
1058 	/*
1059 	 * Set up block calculations.
1060 	 */
1061 	if (bp->b_blkno > 20000000) {
1062 		/*
1063 		 * Reject unreasonably high block number, prevent the
1064 		 * multiplication below from overflowing.
1065 		 */
1066 		bp->b_error = EINVAL;
1067 		bp->b_flags |= B_ERROR;
1068 		goto bad;
1069 	}
1070 	blknum = (unsigned) bp->b_blkno * DEV_BSIZE/fdblk;
1071  	nblocks = fd->ft->size;
1072 	bp->b_resid = 0;
1073 	if (blknum + (bp->b_bcount / fdblk) > nblocks) {
1074 		if (blknum <= nblocks) {
1075 			cando = (nblocks - blknum) * fdblk;
1076 			bp->b_resid = bp->b_bcount - cando;
1077 			if (cando == 0)
1078 				goto bad;	/* not actually bad but EOF */
1079 		} else {
1080 			bp->b_error = EINVAL;
1081 			bp->b_flags |= B_ERROR;
1082 			goto bad;
1083 		}
1084 	}
1085  	bp->b_pblkno = bp->b_blkno;
1086 	s = splbio();
1087 	tqdisksort(&fdc->head, bp);
1088 	untimeout(fd_turnoff, (caddr_t)fdu); /* a good idea */
1089 	fdstart(fdcu);
1090 	splx(s);
1091 	return;
1092 
1093 bad:
1094 	biodone(bp);
1095 }
1096 
1097 /***************************************************************\
1098 *				fdstart				*
1099 * We have just queued something.. if the controller is not busy	*
1100 * then simulate the case where it has just finished a command	*
1101 * So that it (the interrupt routine) looks on the queue for more*
1102 * work to do and picks up what we just added.			*
1103 * If the controller is already busy, we need do nothing, as it	*
1104 * will pick up our work when the present work completes		*
1105 \***************************************************************/
1106 static void
1107 fdstart(fdcu_t fdcu)
1108 {
1109 	int s;
1110 
1111 	s = splbio();
1112 	if(fdc_data[fdcu].state == DEVIDLE)
1113 	{
1114 		fdintr(fdcu);
1115 	}
1116 	splx(s);
1117 }
1118 
1119 static void
1120 fd_timeout(void *arg1)
1121 {
1122 	fdcu_t fdcu = (fdcu_t)arg1;
1123 	fdu_t fdu = fdc_data[fdcu].fdu;
1124 	int baseport = fdc_data[fdcu].baseport;
1125 	struct buf *bp;
1126 	int s;
1127 
1128 	bp = TAILQ_FIRST(&fdc_data[fdcu].head);
1129 
1130 	/*
1131 	 * Due to IBM's brain-dead design, the FDC has a faked ready
1132 	 * signal, hardwired to ready == true. Thus, any command
1133 	 * issued if there's no diskette in the drive will _never_
1134 	 * complete, and must be aborted by resetting the FDC.
1135 	 * Many thanks, Big Blue!
1136 	 */
1137 
1138 	s = splbio();
1139 
1140 	TRACE1("fd%d[fd_timeout()]", fdu);
1141 	/* See if the controller is still busy (patiently awaiting data) */
1142 	if(((inb(baseport + FDSTS)) & (NE7_CB|NE7_RQM)) == NE7_CB)
1143 	{
1144 		TRACE1("[FDSTS->0x%x]", inb(baseport + FDSTS));
1145 		/* yup, it is; kill it now */
1146 		fdc_reset(&fdc_data[fdcu]);
1147 		printf("fd%d: Operation timeout\n", fdu);
1148 	}
1149 
1150 	if (bp)
1151 	{
1152 		retrier(fdcu);
1153 		fdc_data[fdcu].status[0] = NE7_ST0_IC_RC;
1154 		fdc_data[fdcu].state = IOTIMEDOUT;
1155 		if( fdc_data[fdcu].retry < 6)
1156 			fdc_data[fdcu].retry = 6;
1157 	}
1158 	else
1159 	{
1160 		fdc_data[fdcu].fd = (fd_p) 0;
1161 		fdc_data[fdcu].fdu = -1;
1162 		fdc_data[fdcu].state = DEVIDLE;
1163 	}
1164 	fdintr(fdcu);
1165 	splx(s);
1166 }
1167 
1168 /* just ensure it has the right spl */
1169 static void
1170 fd_pseudointr(void *arg1)
1171 {
1172 	fdcu_t fdcu = (fdcu_t)arg1;
1173 	int	s;
1174 
1175 	s = splbio();
1176 	fdintr(fdcu);
1177 	splx(s);
1178 }
1179 
1180 /***********************************************************************\
1181 *                                 fdintr				*
1182 * keep calling the state machine until it returns a 0			*
1183 * ALWAYS called at SPLBIO 						*
1184 \***********************************************************************/
1185 void
1186 fdintr(fdcu_t fdcu)
1187 {
1188 	fdc_p fdc = fdc_data + fdcu;
1189 #if NFT > 0
1190 	fdu_t fdu = fdc->fdu;
1191 
1192 	if (fdc->flags & FDC_TAPE_BUSY)
1193 		(ftintr(fdu));
1194 	else
1195 #endif
1196 		while(fdstate(fdcu, fdc))
1197 			;
1198 }
1199 
1200 /***********************************************************************\
1201 * The controller state machine.						*
1202 * if it returns a non zero value, it should be called again immediatly	*
1203 \***********************************************************************/
1204 static int
1205 fdstate(fdcu_t fdcu, fdc_p fdc)
1206 {
1207 	int read, format, head, sec = 0, sectrac, st0, cyl, st3;
1208 	unsigned blknum = 0, b_cylinder = 0;
1209 	fdu_t fdu = fdc->fdu;
1210 	fd_p fd;
1211 	register struct buf *bp;
1212 	struct fd_formb *finfo = NULL;
1213 	size_t fdblk;
1214 
1215 	bp = TAILQ_FIRST(&fdc->head);
1216 	if(!bp) {
1217 		/***********************************************\
1218 		* nothing left for this controller to do	*
1219 		* Force into the IDLE state,			*
1220 		\***********************************************/
1221 		fdc->state = DEVIDLE;
1222 		if(fdc->fd)
1223 		{
1224 			printf("fd%d: unexpected valid fd pointer\n",
1225 			       fdc->fdu);
1226 			fdc->fd = (fd_p) 0;
1227 			fdc->fdu = -1;
1228 		}
1229 		TRACE1("[fdc%d IDLE]", fdcu);
1230  		return(0);
1231 	}
1232 	fdu = FDUNIT(minor(bp->b_dev));
1233 	fd = fd_data + fdu;
1234 	fdblk = 128 << fd->ft->secsize;
1235 	if (fdc->fd && (fd != fdc->fd))
1236 	{
1237 		printf("fd%d: confused fd pointers\n", fdu);
1238 	}
1239 	read = bp->b_flags & B_READ;
1240 	format = bp->b_flags & B_FORMAT;
1241 	if(format) {
1242 		finfo = (struct fd_formb *)bp->b_un.b_addr;
1243 		fd->skip = (char *)&(finfo->fd_formb_cylno(0))
1244 			- (char *)finfo;
1245 	}
1246 	if (fdc->state == DOSEEK || fdc->state == SEEKCOMPLETE) {
1247 		blknum = (unsigned) bp->b_blkno * DEV_BSIZE/fdblk +
1248 			fd->skip/fdblk;
1249 		b_cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
1250 	}
1251 	TRACE1("fd%d", fdu);
1252 	TRACE1("[%s]", fdstates[fdc->state]);
1253 	TRACE1("(0x%x)", fd->flags);
1254 	untimeout(fd_turnoff, (caddr_t)fdu);
1255 	timeout(fd_turnoff, (caddr_t)fdu, 4 * hz);
1256 	switch (fdc->state)
1257 	{
1258 	case DEVIDLE:
1259 	case FINDWORK:	/* we have found new work */
1260 		fdc->retry = 0;
1261 		fd->skip = 0;
1262 		fdc->fd = fd;
1263 		fdc->fdu = fdu;
1264 		outb(fdc->baseport+FDCTL, fd->ft->trans);
1265 		TRACE1("[0x%x->FDCTL]", fd->ft->trans);
1266 		/*******************************************************\
1267 		* If the next drive has a motor startup pending, then	*
1268 		* it will start up in it's own good time		*
1269 		\*******************************************************/
1270 		if(fd->flags & FD_MOTOR_WAIT)
1271 		{
1272 			fdc->state = MOTORWAIT;
1273 			return(0); /* come back later */
1274 		}
1275 		/*******************************************************\
1276 		* Maybe if it's not starting, it SHOULD be starting	*
1277 		\*******************************************************/
1278 		if (!(fd->flags & FD_MOTOR))
1279 		{
1280 			fdc->state = MOTORWAIT;
1281 			fd_turnon(fdu);
1282 			return(0);
1283 		}
1284 		else	/* at least make sure we are selected */
1285 		{
1286 			set_motor(fdcu, fd->fdsu, TURNON);
1287 		}
1288 		fdc->state = DOSEEK;
1289 		break;
1290 	case DOSEEK:
1291 		if (b_cylinder == (unsigned)fd->track)
1292 		{
1293 			fdc->state = SEEKCOMPLETE;
1294 			break;
1295 		}
1296 		if (fd_cmd(fdcu, 3, NE7CMD_SEEK,
1297 			   fd->fdsu, b_cylinder * fd->ft->steptrac,
1298 			   0))
1299 		{
1300 			/*
1301 			 * seek command not accepted, looks like
1302 			 * the FDC went off to the Saints...
1303 			 */
1304 			fdc->retry = 6;	/* try a reset */
1305 			return(retrier(fdcu));
1306 		}
1307 		fd->track = FD_NO_TRACK;
1308 		fdc->state = SEEKWAIT;
1309 		return(0);	/* will return later */
1310 	case SEEKWAIT:
1311 		/* allow heads to settle */
1312 		timeout(fd_pseudointr, (caddr_t)fdcu, hz / 16);
1313 		fdc->state = SEEKCOMPLETE;
1314 		return(0);	/* will return later */
1315 	case SEEKCOMPLETE : /* SEEK DONE, START DMA */
1316 		/* Make sure seek really happened*/
1317 		if(fd->track == FD_NO_TRACK)
1318 		{
1319 			int descyl = b_cylinder * fd->ft->steptrac;
1320 			do {
1321 				/*
1322 				 * This might be a "ready changed" interrupt,
1323 				 * which cannot really happen since the
1324 				 * RDY pin is hardwired to + 5 volts.  This
1325 				 * generally indicates a "bouncing" intr
1326 				 * line, so do one of the following:
1327 				 *
1328 				 * When running on an enhanced FDC that is
1329 				 * known to not go stuck after responding
1330 				 * with INVALID, fetch all interrupt states
1331 				 * until seeing either an INVALID or a
1332 				 * real interrupt condition.
1333 				 *
1334 				 * When running on a dumb old NE765, give
1335 				 * up immediately.  The controller will
1336 				 * provide up to four dummy RC interrupt
1337 				 * conditions right after reset (for the
1338 				 * corresponding four drives), so this is
1339 				 * our only chance to get notice that it
1340 				 * was not the FDC that caused the interrupt.
1341 				 */
1342 				if (fd_sense_int(fdc, &st0, &cyl)
1343 				    == FD_NOT_VALID)
1344 					return 0;
1345 				if(fdc->fdct == FDC_NE765
1346 				   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
1347 					return 0; /* hope for a real intr */
1348 			} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
1349 
1350 			if (0 == descyl)
1351 			{
1352 				int failed = 0;
1353 				/*
1354 				 * seek to cyl 0 requested; make sure we are
1355 				 * really there
1356 				 */
1357 				if (fd_sense_drive_status(fdc, &st3))
1358 					failed = 1;
1359 				if ((st3 & NE7_ST3_T0) == 0) {
1360 					printf(
1361 		"fd%d: Seek to cyl 0, but not really there (ST3 = %b)\n",
1362 					       fdu, st3, NE7_ST3BITS);
1363 					failed = 1;
1364 				}
1365 
1366 				if (failed)
1367 				{
1368 					if(fdc->retry < 3)
1369 						fdc->retry = 3;
1370 					return(retrier(fdcu));
1371 				}
1372 			}
1373 
1374 			if (cyl != descyl)
1375 			{
1376 				printf(
1377 		"fd%d: Seek to cyl %d failed; am at cyl %d (ST0 = 0x%x)\n",
1378 				       fdu, descyl, cyl, st0);
1379 				return(retrier(fdcu));
1380 			}
1381 		}
1382 
1383 		fd->track = b_cylinder;
1384 		isa_dmastart(bp->b_flags, bp->b_un.b_addr+fd->skip,
1385 			format ? bp->b_bcount : fdblk, fdc->dmachan);
1386 		sectrac = fd->ft->sectrac;
1387 		sec = blknum %  (sectrac * fd->ft->heads);
1388 		head = sec / sectrac;
1389 		sec = sec % sectrac + 1;
1390 		fd->hddrv = ((head&1)<<2)+fdu;
1391 
1392 		if(format || !read)
1393 		{
1394 			/* make sure the drive is writable */
1395 			if(fd_sense_drive_status(fdc, &st3) != 0)
1396 			{
1397 				/* stuck controller? */
1398 				fdc->retry = 6;	/* reset the beast */
1399 				return(retrier(fdcu));
1400 			}
1401 			if(st3 & NE7_ST3_WP)
1402 			{
1403 				/*
1404 				 * XXX YES! this is ugly.
1405 				 * in order to force the current operation
1406 				 * to fail, we will have to fake an FDC
1407 				 * error - all error handling is done
1408 				 * by the retrier()
1409 				 */
1410 				fdc->status[0] = NE7_ST0_IC_AT;
1411 				fdc->status[1] = NE7_ST1_NW;
1412 				fdc->status[2] = 0;
1413 				fdc->status[3] = fd->track;
1414 				fdc->status[4] = head;
1415 				fdc->status[5] = sec;
1416 				fdc->retry = 8;	/* break out immediately */
1417 				fdc->state = IOTIMEDOUT; /* not really... */
1418 				return (1);
1419 			}
1420 		}
1421 
1422 		if(format)
1423 		{
1424 			/* formatting */
1425 			if(fd_cmd(fdcu, 6,
1426 				  NE7CMD_FORMAT,
1427 				  head << 2 | fdu,
1428 				  finfo->fd_formb_secshift,
1429 				  finfo->fd_formb_nsecs,
1430 				  finfo->fd_formb_gaplen,
1431 				  finfo->fd_formb_fillbyte,
1432 				  0))
1433 			{
1434 				/* controller fell over */
1435 				fdc->retry = 6;
1436 				return(retrier(fdcu));
1437 			}
1438 		}
1439 		else
1440 		{
1441 			if (fd_cmd(fdcu, 9,
1442 				   (read ? NE7CMD_READ : NE7CMD_WRITE),
1443 				   head << 2 | fdu,  /* head & unit */
1444 				   fd->track,        /* track */
1445 				   head,
1446 				   sec,              /* sector + 1 */
1447 				   fd->ft->secsize,  /* sector size */
1448 				   sectrac,          /* sectors/track */
1449 				   fd->ft->gap,      /* gap size */
1450 				   fd->ft->datalen,  /* data length */
1451 				   0))
1452 			{
1453 				/* the beast is sleeping again */
1454 				fdc->retry = 6;
1455 				return(retrier(fdcu));
1456 			}
1457 		}
1458 		fdc->state = IOCOMPLETE;
1459 		timeout(fd_timeout, (caddr_t)fdcu, hz);
1460 		return(0);	/* will return later */
1461 	case IOCOMPLETE: /* IO DONE, post-analyze */
1462 		untimeout(fd_timeout, (caddr_t)fdcu);
1463 
1464 		if (fd_read_status(fdc, fd->fdsu))
1465 		{
1466 			if (fdc->retry < 6)
1467 				fdc->retry = 6;	/* force a reset */
1468 			return retrier(fdcu);
1469   		}
1470 
1471 		fdc->state = IOTIMEDOUT;
1472 
1473 		/* FALLTHROUGH */
1474 
1475 	case IOTIMEDOUT:
1476 		isa_dmadone(bp->b_flags, bp->b_un.b_addr+fd->skip,
1477 			    format ? bp->b_bcount : fdblk, fdc->dmachan);
1478 		if (fdc->status[0] & NE7_ST0_IC)
1479 		{
1480                         if ((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
1481 			    && fdc->status[1] & NE7_ST1_OR) {
1482                                 /*
1483 				 * DMA overrun. Someone hogged the bus
1484 				 * and didn't release it in time for the
1485 				 * next FDC transfer.
1486 				 * Just restart it, don't increment retry
1487 				 * count. (vak)
1488                                  */
1489                                 fdc->state = SEEKCOMPLETE;
1490                                 return (1);
1491                         }
1492 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_IV
1493 				&& fdc->retry < 6)
1494 				fdc->retry = 6;	/* force a reset */
1495 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
1496 				&& fdc->status[2] & NE7_ST2_WC
1497 				&& fdc->retry < 3)
1498 				fdc->retry = 3;	/* force recalibrate */
1499 			return(retrier(fdcu));
1500 		}
1501 		/* All OK */
1502 		fd->skip += fdblk;
1503 		if (!format && fd->skip < bp->b_bcount - bp->b_resid)
1504 		{
1505 			/* set up next transfer */
1506 			fdc->state = DOSEEK;
1507 		}
1508 		else
1509 		{
1510 			/* ALL DONE */
1511 			fd->skip = 0;
1512 			TAILQ_REMOVE(&fdc->head, bp, b_act);
1513 			biodone(bp);
1514 			fdc->fd = (fd_p) 0;
1515 			fdc->fdu = -1;
1516 			fdc->state = FINDWORK;
1517 		}
1518 		return(1);
1519 	case RESETCTLR:
1520 		fdc_reset(fdc);
1521 		fdc->retry++;
1522 		fdc->state = STARTRECAL;
1523 		break;
1524 	case STARTRECAL:
1525 		/* XXX clear the fdc results from the last reset, if any. */
1526 		{
1527 			int i;
1528 			for (i = 0; i < 4; i++)
1529 				(void)fd_sense_int(fdc, &st0, &cyl);
1530 		}
1531 
1532 		if(fd_cmd(fdcu,
1533 			  2, NE7CMD_RECAL, fdu,
1534 			  0)) /* Recalibrate Function */
1535 		{
1536 			/* arrgl */
1537 			fdc->retry = 6;
1538 			return(retrier(fdcu));
1539 		}
1540 		fdc->state = RECALWAIT;
1541 		return(0);	/* will return later */
1542 	case RECALWAIT:
1543 		/* allow heads to settle */
1544 		timeout(fd_pseudointr, (caddr_t)fdcu, hz / 8);
1545 		fdc->state = RECALCOMPLETE;
1546 		return(0);	/* will return later */
1547 	case RECALCOMPLETE:
1548 		do {
1549 			/*
1550 			 * See SEEKCOMPLETE for a comment on this:
1551 			 */
1552 			if (fd_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
1553 				return 0;
1554 			if(fdc->fdct == FDC_NE765
1555 			   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
1556 				return 0; /* hope for a real intr */
1557 		} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
1558 		if ((st0 & NE7_ST0_IC) != NE7_ST0_IC_NT || cyl != 0)
1559 		{
1560 			if(fdc->retry > 3)
1561 				/*
1562 				 * a recalibrate from beyond cylinder 77
1563 				 * will "fail" due to the FDC limitations;
1564 				 * since people used to complain much about
1565 				 * the failure message, try not logging
1566 				 * this one if it seems to be the first
1567 				 * time in a line
1568 				 */
1569 				printf("fd%d: recal failed ST0 %b cyl %d\n",
1570 				       fdu, st0, NE7_ST0BITS, cyl);
1571 			if(fdc->retry < 3) fdc->retry = 3;
1572 			return(retrier(fdcu));
1573 		}
1574 		fd->track = 0;
1575 		/* Seek (probably) necessary */
1576 		fdc->state = DOSEEK;
1577 		return(1);	/* will return immediatly */
1578 	case MOTORWAIT:
1579 		if(fd->flags & FD_MOTOR_WAIT)
1580 		{
1581 			return(0); /* time's not up yet */
1582 		}
1583 		/*
1584 		 * since the controller was off, it has lost its
1585 		 * idea about the current track it were; thus,
1586 		 * recalibrate the bastard
1587 		 */
1588 		fdc->state = STARTRECAL;
1589 		return(1);	/* will return immediatly */
1590 	default:
1591 		printf("fdc%d: Unexpected FD int->", fdcu);
1592 		if (fd_read_status(fdc, fd->fdsu) == 0)
1593 			printf("FDC status :%lx %lx %lx %lx %lx %lx %lx   ",
1594 			       fdc->status[0],
1595 			       fdc->status[1],
1596 			       fdc->status[2],
1597 			       fdc->status[3],
1598 			       fdc->status[4],
1599 			       fdc->status[5],
1600 			       fdc->status[6] );
1601 		else
1602 			printf("No status available   ");
1603 		if (fd_sense_int(fdc, &st0, &cyl) != 0)
1604 		{
1605 			printf("[controller is dead now]\n");
1606 			return(0);
1607 		}
1608 		printf("ST0 = %x, PCN = %x\n", st0, cyl);
1609 		return(0);
1610 	}
1611 	/*XXX confusing: some branches return immediately, others end up here*/
1612 	return(1); /* Come back immediatly to new state */
1613 }
1614 
1615 static int
1616 retrier(fdcu)
1617 	fdcu_t fdcu;
1618 {
1619 	fdc_p fdc = fdc_data + fdcu;
1620 	register struct buf *bp;
1621 
1622 	bp = TAILQ_FIRST(&fdc->head);
1623 
1624 	if(fd_data[FDUNIT(minor(bp->b_dev))].options & FDOPT_NORETRY)
1625 		goto fail;
1626 	switch(fdc->retry)
1627 	{
1628 	case 0: case 1: case 2:
1629 		fdc->state = SEEKCOMPLETE;
1630 		break;
1631 	case 3: case 4: case 5:
1632 		fdc->state = STARTRECAL;
1633 		break;
1634 	case 6:
1635 		fdc->state = RESETCTLR;
1636 		break;
1637 	case 7:
1638 		break;
1639 	default:
1640 	fail:
1641 		{
1642 			dev_t sav_b_dev = bp->b_dev;
1643 			/* Trick diskerr */
1644 			bp->b_dev = makedev(major(bp->b_dev),
1645 					    (FDUNIT(minor(bp->b_dev))<<3)|RAW_PART);
1646 			diskerr(bp, "fd", "hard error", LOG_PRINTF,
1647 				fdc->fd->skip / DEV_BSIZE,
1648 				(struct disklabel *)NULL);
1649 			bp->b_dev = sav_b_dev;
1650 			if (fdc->flags & FDC_STAT_VALID)
1651 			{
1652 				printf(
1653 			" (ST0 %b ST1 %b ST2 %b cyl %ld hd %ld sec %ld)\n",
1654 				       fdc->status[0], NE7_ST0BITS,
1655 				       fdc->status[1], NE7_ST1BITS,
1656 				       fdc->status[2], NE7_ST2BITS,
1657 				       fdc->status[3], fdc->status[4],
1658 				       fdc->status[5]);
1659 			}
1660 			else
1661 				printf(" (No status)\n");
1662 		}
1663 		bp->b_flags |= B_ERROR;
1664 		bp->b_error = EIO;
1665 		bp->b_resid += bp->b_bcount - fdc->fd->skip;
1666 		TAILQ_REMOVE(&fdc->head, bp, b_act);
1667 		fdc->fd->skip = 0;
1668 		biodone(bp);
1669 		fdc->state = FINDWORK;
1670 		fdc->fd = (fd_p) 0;
1671 		fdc->fdu = -1;
1672 		/* XXX abort current command, if any.  */
1673 		return(1);
1674 	}
1675 	fdc->retry++;
1676 	return(1);
1677 }
1678 
1679 static int
1680 fdformat(dev, finfo, p)
1681 	dev_t dev;
1682 	struct fd_formb *finfo;
1683 	struct proc *p;
1684 {
1685  	fdu_t	fdu;
1686  	fd_p	fd;
1687 
1688 	struct buf *bp;
1689 	int rv = 0, s;
1690 	size_t fdblk;
1691 
1692  	fdu = FDUNIT(minor(dev));
1693 	fd = &fd_data[fdu];
1694 	fdblk = 128 << fd->ft->secsize;
1695 
1696 	/* set up a buffer header for fdstrategy() */
1697 	bp = (struct buf *)malloc(sizeof(struct buf), M_TEMP, M_NOWAIT);
1698 	if(bp == 0)
1699 		return ENOBUFS;
1700 	/*
1701 	 * keep the process from being swapped
1702 	 */
1703 	p->p_flag |= P_PHYSIO;
1704 	bzero((void *)bp, sizeof(struct buf));
1705 	bp->b_flags = B_BUSY | B_PHYS | B_FORMAT;
1706 	bp->b_proc = p;
1707 	bp->b_dev = dev;
1708 
1709 	/*
1710 	 * calculate a fake blkno, so fdstrategy() would initiate a
1711 	 * seek to the requested cylinder
1712 	 */
1713 	bp->b_blkno = (finfo->cyl * (fd->ft->sectrac * fd->ft->heads)
1714 		+ finfo->head * fd->ft->sectrac) * fdblk / DEV_BSIZE;
1715 
1716 	bp->b_bcount = sizeof(struct fd_idfield_data) * finfo->fd_formb_nsecs;
1717 	bp->b_un.b_addr = (caddr_t)finfo;
1718 
1719 	/* now do the format */
1720 	fdstrategy(bp);
1721 
1722 	/* ...and wait for it to complete */
1723 	s = splbio();
1724 	while(!(bp->b_flags & B_DONE))
1725 	{
1726 		rv = tsleep((caddr_t)bp, PRIBIO, "fdform", 20 * hz);
1727 		if(rv == EWOULDBLOCK)
1728 			break;
1729 	}
1730 	splx(s);
1731 
1732 	if(rv == EWOULDBLOCK) {
1733 		/* timed out */
1734 		rv = EIO;
1735 		biodone(bp);
1736 	}
1737 	if(bp->b_flags & B_ERROR)
1738 		rv = bp->b_error;
1739 	/*
1740 	 * allow the process to be swapped
1741 	 */
1742 	p->p_flag &= ~P_PHYSIO;
1743 	free(bp, M_TEMP);
1744 	return rv;
1745 }
1746 
1747 /*
1748  * TODO: don't allocate buffer on stack.
1749  */
1750 
1751 int
1752 fdioctl(dev, cmd, addr, flag, p)
1753 	dev_t dev;
1754 	int cmd;
1755 	caddr_t addr;
1756 	int flag;
1757 	struct proc *p;
1758 {
1759  	fdu_t	fdu = FDUNIT(minor(dev));
1760  	fd_p	fd = &fd_data[fdu];
1761 	size_t fdblk;
1762 
1763 	struct fd_type *fdt;
1764 	struct disklabel *dl;
1765 	char buffer[DEV_BSIZE];
1766 	int error = 0;
1767 
1768 #if NFT > 0
1769 	int type = FDTYPE(minor(dev));
1770 
1771 	/* check for a tape ioctl */
1772 	if (type & F_TAPE_TYPE)
1773 		return ftioctl(dev, cmd, addr, flag, p);
1774 #endif
1775 
1776 	fdblk = 128 << fd->ft->secsize;
1777 
1778 	switch (cmd)
1779 	{
1780 	case DIOCGDINFO:
1781 		bzero(buffer, sizeof (buffer));
1782 		dl = (struct disklabel *)buffer;
1783 		dl->d_secsize = fdblk;
1784 		fdt = fd_data[FDUNIT(minor(dev))].ft;
1785 		dl->d_secpercyl = fdt->size / fdt->tracks;
1786 		dl->d_type = DTYPE_FLOPPY;
1787 
1788 		if (readdisklabel(dkmodpart(dev, RAW_PART), fdstrategy, dl)
1789 		    == NULL)
1790 			error = 0;
1791 		else
1792 			error = EINVAL;
1793 
1794 		*(struct disklabel *)addr = *dl;
1795 		break;
1796 
1797 	case DIOCSDINFO:
1798 		if ((flag & FWRITE) == 0)
1799 			error = EBADF;
1800 		break;
1801 
1802 	case DIOCWLABEL:
1803 		if ((flag & FWRITE) == 0)
1804 			error = EBADF;
1805 		break;
1806 
1807 	case DIOCWDINFO:
1808 		if ((flag & FWRITE) == 0)
1809 		{
1810 			error = EBADF;
1811 			break;
1812 		}
1813 
1814 		dl = (struct disklabel *)addr;
1815 
1816 		if ((error = setdisklabel((struct disklabel *)buffer, dl,
1817 					  (u_long)0)) != 0)
1818 			break;
1819 
1820 		error = writedisklabel(dev, fdstrategy,
1821 				       (struct disklabel *)buffer);
1822 		break;
1823 
1824 	case FD_FORM:
1825 		if((flag & FWRITE) == 0)
1826 			error = EBADF;	/* must be opened for writing */
1827 		else if(((struct fd_formb *)addr)->format_version !=
1828 			FD_FORMAT_VERSION)
1829 			error = EINVAL;	/* wrong version of formatting prog */
1830 		else
1831 			error = fdformat(dev, (struct fd_formb *)addr, p);
1832 		break;
1833 
1834 	case FD_GTYPE:                  /* get drive type */
1835 		*(struct fd_type *)addr = *fd_data[FDUNIT(minor(dev))].ft;
1836 		break;
1837 
1838 	case FD_STYPE:                  /* set drive type */
1839 		/* this is considered harmful; only allow for superuser */
1840 		if(suser(p->p_ucred, &p->p_acflag) != 0)
1841 			return EPERM;
1842 		*fd_data[FDUNIT(minor(dev))].ft = *(struct fd_type *)addr;
1843 		break;
1844 
1845 	case FD_GOPTS:			/* get drive options */
1846 		*(int *)addr = fd_data[FDUNIT(minor(dev))].options;
1847 		break;
1848 
1849 	case FD_SOPTS:			/* set drive options */
1850 		fd_data[FDUNIT(minor(dev))].options = *(int *)addr;
1851 		break;
1852 
1853 	default:
1854 		error = ENOTTY;
1855 		break;
1856 	}
1857 	return (error);
1858 }
1859 
1860 
1861 static fd_devsw_installed = 0;
1862 
1863 static void 	fd_drvinit(void *notused )
1864 {
1865 
1866 	if( ! fd_devsw_installed ) {
1867 		bdevsw_add_generic(BDEV_MAJOR,CDEV_MAJOR, &fd_bdevsw);
1868 		fd_devsw_installed = 1;
1869 	}
1870 }
1871 
1872 SYSINIT(fddev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,fd_drvinit,NULL)
1873 
1874 #endif
1875 /*
1876  * Hello emacs, these are the
1877  * Local Variables:
1878  *  c-indent-level:               8
1879  *  c-continued-statement-offset: 8
1880  *  c-continued-brace-offset:     0
1881  *  c-brace-offset:              -8
1882  *  c-brace-imaginary-offset:     0
1883  *  c-argdecl-indent:             8
1884  *  c-label-offset:              -8
1885  *  c++-hanging-braces:           1
1886  *  c++-access-specifier-offset: -8
1887  *  c++-empty-arglist-indent:     8
1888  *  c++-friend-offset:            0
1889  * End:
1890  */
1891