xref: /freebsd/sys/dev/fdc/fdc.c (revision f9ce010afdd3136fc73e2b500f2ed916bf9cfa59)
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  * Libretto PCMCIA floppy support by David Horwitt (dhorwitt@ucsd.edu)
9  * aided by the Linux floppy driver modifications from David Bateman
10  * (dbateman@eng.uts.edu.au).
11  *
12  * Copyright (c) 1993, 1994 by
13  *  jc@irbs.UUCP (John Capo)
14  *  vak@zebub.msk.su (Serge Vakulenko)
15  *  ache@astral.msk.su (Andrew A. Chernov)
16  *
17  * Copyright (c) 1993, 1994, 1995 by
18  *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
19  *  dufault@hda.com (Peter Dufault)
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  * 3. All advertising materials mentioning features or use of this software
30  *    must display the following acknowledgement:
31  *	This product includes software developed by the University of
32  *	California, Berkeley and its contributors.
33  * 4. Neither the name of the University nor the names of its contributors
34  *    may be used to endorse or promote products derived from this software
35  *    without specific prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  *
49  *	from:	@(#)fd.c	7.4 (Berkeley) 5/25/91
50  * $FreeBSD$
51  *
52  */
53 
54 #include "fd.h"
55 #include "opt_fdc.h"
56 
57 #if NFDC > 0
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/kernel.h>
62 #include <sys/buf.h>
63 #include <sys/bus.h>
64 #include <sys/conf.h>
65 #include <sys/disklabel.h>
66 #include <sys/devicestat.h>
67 #include <sys/fcntl.h>
68 #include <sys/malloc.h>
69 #include <sys/module.h>
70 #include <sys/proc.h>
71 #include <sys/syslog.h>
72 
73 #include <sys/bus.h>
74 #include <machine/bus.h>
75 #include <sys/rman.h>
76 
77 #include <machine/clock.h>
78 #include <machine/ioctl_fd.h>
79 #include <machine/resource.h>
80 #include <machine/stdarg.h>
81 
82 #include <isa/isavar.h>
83 #include <isa/isareg.h>
84 #include <isa/fdreg.h>
85 #include <isa/fdc.h>
86 #include <isa/rtc.h>
87 
88 #ifdef FDC_YE
89 #undef FDC_YE
90 #warning "fix FDC_YE! - newbus casualty"
91 #endif
92 
93 /* misuse a flag to identify format operation */
94 #define B_FORMAT B_XXX
95 
96 /* configuration flags */
97 #define FDC_PRETEND_D0	(1 << 0)	/* pretend drive 0 to be there */
98 #ifdef FDC_YE
99 #define FDC_IS_PCMCIA  (1 << 1)		/* if successful probe, then it's
100 					   a PCMCIA device */
101 #endif
102 
103 /* internally used only, not really from CMOS: */
104 #define RTCFDT_144M_PRETENDED	0x1000
105 
106 /* error returns for fd_cmd() */
107 #define FD_FAILED -1
108 #define FD_NOT_VALID -2
109 #define FDC_ERRMAX	100	/* do not log more */
110 
111 #define NUMTYPES 14
112 #define NUMDENS  (NUMTYPES - 6)
113 
114 /* These defines (-1) must match index for fd_types */
115 #define F_TAPE_TYPE	0x020	/* bit for fd_types to indicate tape */
116 #define NO_TYPE		0	/* must match NO_TYPE in ft.c */
117 #define FD_1720         1
118 #define FD_1480         2
119 #define FD_1440         3
120 #define FD_1200         4
121 #define FD_820          5
122 #define FD_800          6
123 #define FD_720          7
124 #define FD_360          8
125 
126 #define FD_1480in5_25   9
127 #define FD_1440in5_25   10
128 #define FD_820in5_25    11
129 #define FD_800in5_25    12
130 #define FD_720in5_25    13
131 #define FD_360in5_25    14
132 
133 
134 static struct fd_type fd_types[NUMTYPES] =
135 {
136 { 21,2,0xFF,0x04,82,3444,1,FDC_500KBPS,2,0x0C,2 }, /* 1.72M in HD 3.5in */
137 { 18,2,0xFF,0x1B,82,2952,1,FDC_500KBPS,2,0x6C,1 }, /* 1.48M in HD 3.5in */
138 { 18,2,0xFF,0x1B,80,2880,1,FDC_500KBPS,2,0x6C,1 }, /* 1.44M in HD 3.5in */
139 { 15,2,0xFF,0x1B,80,2400,1,FDC_500KBPS,2,0x54,1 }, /*  1.2M in HD 5.25/3.5 */
140 { 10,2,0xFF,0x10,82,1640,1,FDC_250KBPS,2,0x2E,1 }, /*  820K in HD 3.5in */
141 { 10,2,0xFF,0x10,80,1600,1,FDC_250KBPS,2,0x2E,1 }, /*  800K in HD 3.5in */
142 {  9,2,0xFF,0x20,80,1440,1,FDC_250KBPS,2,0x50,1 }, /*  720K in HD 3.5in */
143 {  9,2,0xFF,0x2A,40, 720,1,FDC_250KBPS,2,0x50,1 }, /*  360K in DD 5.25in */
144 
145 { 18,2,0xFF,0x02,82,2952,1,FDC_500KBPS,2,0x02,2 }, /* 1.48M in HD 5.25in */
146 { 18,2,0xFF,0x02,80,2880,1,FDC_500KBPS,2,0x02,2 }, /* 1.44M in HD 5.25in */
147 { 10,2,0xFF,0x10,82,1640,1,FDC_300KBPS,2,0x2E,1 }, /*  820K in HD 5.25in */
148 { 10,2,0xFF,0x10,80,1600,1,FDC_300KBPS,2,0x2E,1 }, /*  800K in HD 5.25in */
149 {  9,2,0xFF,0x20,80,1440,1,FDC_300KBPS,2,0x50,1 }, /*  720K in HD 5.25in */
150 {  9,2,0xFF,0x23,40, 720,2,FDC_300KBPS,2,0x50,1 }, /*  360K in HD 5.25in */
151 };
152 
153 #define DRVS_PER_CTLR 2		/* 2 floppies */
154 
155 /***********************************************************************\
156 * Per controller structure.						*
157 \***********************************************************************/
158 static devclass_t fdc_devclass;
159 
160 /***********************************************************************\
161 * Per drive structure.							*
162 * N per controller  (DRVS_PER_CTLR)					*
163 \***********************************************************************/
164 struct fd_data {
165 	struct	fdc_data *fdc;	/* pointer to controller structure */
166 	int	fdsu;		/* this units number on this controller */
167 	int	type;		/* Drive type (FD_1440...) */
168 	struct	fd_type *ft;	/* pointer to the type descriptor */
169 	int	flags;
170 #define	FD_OPEN		0x01	/* it's open		*/
171 #define	FD_ACTIVE	0x02	/* it's active		*/
172 #define	FD_MOTOR	0x04	/* motor should be on	*/
173 #define	FD_MOTOR_WAIT	0x08	/* motor coming up	*/
174 	int	skip;
175 	int	hddrv;
176 #define FD_NO_TRACK -2
177 	int	track;		/* where we think the head is */
178 	int	options;	/* user configurable options, see ioctl_fd.h */
179 	struct	callout_handle toffhandle;
180 	struct	callout_handle tohandle;
181 	struct	devstat device_stats;
182 	device_t dev;
183 	fdu_t	fdu;
184 };
185 static devclass_t fd_devclass;
186 
187 /***********************************************************************\
188 * Throughout this file the following conventions will be used:		*
189 * fd is a pointer to the fd_data struct for the drive in question	*
190 * fdc is a pointer to the fdc_data struct for the controller		*
191 * fdu is the floppy drive unit number					*
192 * fdcu is the floppy controller unit number				*
193 * fdsu is the floppy drive unit number on that controller. (sub-unit)	*
194 \***********************************************************************/
195 
196 #ifdef FDC_YE
197 #include "card.h"
198 static int yeattach(struct isa_device *);
199 #endif
200 
201 /* needed for ft driver, thus exported */
202 int in_fdc(struct fdc_data *);
203 int out_fdc(struct fdc_data *, int);
204 
205 /* internal functions */
206 static	void fdc_add_device(device_t, const char *, int);
207 static	void fdc_intr(void *);
208 static void set_motor(struct fdc_data *, int, int);
209 #  define TURNON 1
210 #  define TURNOFF 0
211 static timeout_t fd_turnoff;
212 static timeout_t fd_motor_on;
213 static void fd_turnon(struct fd_data *);
214 static void fdc_reset(fdc_p);
215 static int fd_in(struct fdc_data *, int *);
216 static void fdstart(struct fdc_data *);
217 static timeout_t fd_iotimeout;
218 static timeout_t fd_pseudointr;
219 static int fdstate(struct fdc_data *);
220 static int retrier(struct fdc_data *);
221 static int fdformat(dev_t, struct fd_formb *, struct proc *);
222 
223 static int enable_fifo(fdc_p fdc);
224 
225 static int fifo_threshold = 8;	/* XXX: should be accessible via sysctl */
226 
227 
228 #define DEVIDLE		0
229 #define FINDWORK	1
230 #define	DOSEEK		2
231 #define SEEKCOMPLETE 	3
232 #define	IOCOMPLETE	4
233 #define RECALCOMPLETE	5
234 #define	STARTRECAL	6
235 #define	RESETCTLR	7
236 #define	SEEKWAIT	8
237 #define	RECALWAIT	9
238 #define	MOTORWAIT	10
239 #define	IOTIMEDOUT	11
240 #define	RESETCOMPLETE	12
241 #ifdef FDC_YE
242 #define PIOREAD		13
243 #endif
244 
245 #ifdef	FDC_DEBUG
246 static char const * const fdstates[] =
247 {
248 "DEVIDLE",
249 "FINDWORK",
250 "DOSEEK",
251 "SEEKCOMPLETE",
252 "IOCOMPLETE",
253 "RECALCOMPLETE",
254 "STARTRECAL",
255 "RESETCTLR",
256 "SEEKWAIT",
257 "RECALWAIT",
258 "MOTORWAIT",
259 "IOTIMEDOUT",
260 "RESETCOMPLETE",
261 #ifdef FDC_YE
262 "PIOREAD",
263 #endif
264 };
265 
266 /* CAUTION: fd_debug causes huge amounts of logging output */
267 static int volatile fd_debug = 0;
268 #define TRACE0(arg) if(fd_debug) printf(arg)
269 #define TRACE1(arg1, arg2) if(fd_debug) printf(arg1, arg2)
270 #else /* FDC_DEBUG */
271 #define TRACE0(arg)
272 #define TRACE1(arg1, arg2)
273 #endif /* FDC_DEBUG */
274 
275 #ifdef FDC_YE
276 #if NCARD > 0
277 #include <sys/select.h>
278 #include <sys/module.h>
279 #include <pccard/cardinfo.h>
280 #include <pccard/driver.h>
281 #include <pccard/slot.h>
282 
283 /*
284  *	PC-Card (PCMCIA) specific code.
285  */
286 static int yeinit(struct pccard_devinfo *);		/* init device */
287 static void yeunload(struct pccard_devinfo *); 		/* Disable driver */
288 static int yeintr(struct pccard_devinfo *); 		/* Interrupt handler */
289 
290 PCCARD_MODULE(fdc, yeinit, yeunload, yeintr, 0, bio_imask);
291 
292 /*
293  * this is the secret PIO data port (offset from base)
294  */
295 #define FDC_YE_DATAPORT 6
296 
297 /*
298  *	Initialize the device - called from Slot manager.
299  */
300 static int yeinit(struct pccard_devinfo *devi)
301 {
302 	fdc_p fdc = &fdc_data[devi->isahd.id_unit];
303 
304 	/* validate unit number. */
305 	if (devi->isahd.id_unit >= NFDC)
306 		return(ENODEV);
307 	fdc->baseport = devi->isahd.id_iobase;
308 	/*
309 	 * reset controller
310 	 */
311 	outb(fdc->baseport+FDOUT, 0);
312 	DELAY(100);
313 	outb(fdc->baseport+FDOUT, FDO_FRST);
314 
315 	/*
316 	 * wire into system
317 	 */
318 	if (yeattach(&devi->isahd) == 0)
319 		return(ENXIO);
320 
321 	return(0);
322 }
323 
324 /*
325  *	yeunload - unload the driver and clear the table.
326  *	XXX TODO:
327  *	This is usually called when the card is ejected, but
328  *	can be caused by a modunload of a controller driver.
329  *	The idea is to reset the driver's view of the device
330  *	and ensure that any driver entry points such as
331  *	read and write do not hang.
332  */
333 static void yeunload(struct pccard_devinfo *devi)
334 {
335 	if (fd_data[devi->isahd.id_unit].type == NO_TYPE)
336 		return;
337 
338 	/*
339 	 * this prevents Fdopen() and fdstrategy() from attempting
340 	 * to access unloaded controller
341 	 */
342 	fd_data[devi->isahd.id_unit].type = NO_TYPE;
343 
344 	printf("fdc%d: unload\n", devi->isahd.id_unit);
345 }
346 
347 /*
348  *	yeintr - Shared interrupt called from
349  *	front end of PC-Card handler.
350  */
351 static int yeintr(struct pccard_devinfo *devi)
352 {
353 	fdintr((fdcu_t)devi->isahd.id_unit);
354 	return(1);
355 }
356 #endif /* NCARD > 0 */
357 #endif /* FDC_YE */
358 
359 static	d_open_t	Fdopen;	/* NOTE, not fdopen */
360 static	d_close_t	fdclose;
361 static	d_ioctl_t	fdioctl;
362 static	d_strategy_t	fdstrategy;
363 
364 #define CDEV_MAJOR 9
365 #define BDEV_MAJOR 2
366 
367 static struct cdevsw fd_cdevsw = {
368 	/* open */	Fdopen,
369 	/* close */	fdclose,
370 	/* read */	physread,
371 	/* write */	physwrite,
372 	/* ioctl */	fdioctl,
373 	/* stop */	nostop,
374 	/* reset */	noreset,
375 	/* devtotty */	nodevtotty,
376 	/* poll */	nopoll,
377 	/* mmap */	nommap,
378 	/* strategy */	fdstrategy,
379 	/* name */	"fd",
380 	/* parms */	noparms,
381 	/* maj */	CDEV_MAJOR,
382 	/* dump */	nodump,
383 	/* psize */	nopsize,
384 	/* flags */	D_DISK,
385 	/* maxio */	0,
386 	/* bmaj */	BDEV_MAJOR
387 };
388 
389 static int
390 fdc_err(struct fdc_data *fdc, const char *s)
391 {
392 	fdc->fdc_errs++;
393 	if (s) {
394 		if (fdc->fdc_errs < FDC_ERRMAX) {
395 			device_print_prettyname(fdc->fdc_dev);
396 			printf("%s", s);
397 		} else if (fdc->fdc_errs == FDC_ERRMAX) {
398 			device_print_prettyname(fdc->fdc_dev);
399 			printf("too many errors, not logging any more\n");
400 		}
401 	}
402 
403 	return FD_FAILED;
404 }
405 
406 /*
407  * fd_cmd: Send a command to the chip.  Takes a varargs with this structure:
408  * Unit number,
409  * # of output bytes, output bytes as ints ...,
410  * # of input bytes, input bytes as ints ...
411  */
412 static int
413 fd_cmd(struct fdc_data *fdc, int n_out, ...)
414 {
415 	u_char cmd;
416 	int n_in;
417 	int n;
418 	va_list ap;
419 
420 	va_start(ap, n_out);
421 	cmd = (u_char)(va_arg(ap, int));
422 	va_end(ap);
423 	va_start(ap, n_out);
424 	for (n = 0; n < n_out; n++)
425 	{
426 		if (out_fdc(fdc, va_arg(ap, int)) < 0)
427 		{
428 			char msg[50];
429 			snprintf(msg, sizeof(msg),
430 				"cmd %x failed at out byte %d of %d\n",
431 				cmd, n + 1, n_out);
432 			return fdc_err(fdc, msg);
433 		}
434 	}
435 	n_in = va_arg(ap, int);
436 	for (n = 0; n < n_in; n++)
437 	{
438 		int *ptr = va_arg(ap, int *);
439 		if (fd_in(fdc, ptr) < 0)
440 		{
441 			char msg[50];
442 			snprintf(msg, sizeof(msg),
443 				"cmd %02x failed at in byte %d of %d\n",
444 				cmd, n + 1, n_in);
445 			return fdc_err(fdc, msg);
446 		}
447 	}
448 
449 	return 0;
450 }
451 
452 static int
453 enable_fifo(fdc_p fdc)
454 {
455 	int i, j;
456 
457 	if ((fdc->flags & FDC_HAS_FIFO) == 0) {
458 
459 		/*
460 		 * XXX:
461 		 * Cannot use fd_cmd the normal way here, since
462 		 * this might be an invalid command. Thus we send the
463 		 * first byte, and check for an early turn of data directon.
464 		 */
465 
466 		if (out_fdc(fdc, I8207X_CONFIGURE) < 0)
467 			return fdc_err(fdc, "Enable FIFO failed\n");
468 
469 		/* If command is invalid, return */
470 		j = 100000;
471 		while ((i = inb(fdc->baseport + FDSTS) & (NE7_DIO | NE7_RQM))
472 		       != NE7_RQM && j-- > 0)
473 			if (i == (NE7_DIO | NE7_RQM)) {
474 				fdc_reset(fdc);
475 				return FD_FAILED;
476 			}
477 		if (j<0 ||
478 		    fd_cmd(fdc, 3,
479 			   0, (fifo_threshold - 1) & 0xf, 0, 0) < 0) {
480 			fdc_reset(fdc);
481 			return fdc_err(fdc, "Enable FIFO failed\n");
482 		}
483 		fdc->flags |= FDC_HAS_FIFO;
484 		return 0;
485 	}
486 	if (fd_cmd(fdc, 4,
487 		   I8207X_CONFIGURE, 0, (fifo_threshold - 1) & 0xf, 0, 0) < 0)
488 		return fdc_err(fdc, "Re-enable FIFO failed\n");
489 	return 0;
490 }
491 
492 static int
493 fd_sense_drive_status(fdc_p fdc, int *st3p)
494 {
495 	int st3;
496 
497 	if (fd_cmd(fdc, 2, NE7CMD_SENSED, fdc->fdu, 1, &st3))
498 	{
499 		return fdc_err(fdc, "Sense Drive Status failed\n");
500 	}
501 	if (st3p)
502 		*st3p = st3;
503 
504 	return 0;
505 }
506 
507 static int
508 fd_sense_int(fdc_p fdc, int *st0p, int *cylp)
509 {
510 	int cyl, st0, ret;
511 
512 	ret = fd_cmd(fdc, 1, NE7CMD_SENSEI, 1, &st0);
513 	if (ret) {
514 		(void)fdc_err(fdc,
515 			      "sense intr err reading stat reg 0\n");
516 		return ret;
517 	}
518 
519 	if (st0p)
520 		*st0p = st0;
521 
522 	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV) {
523 		/*
524 		 * There doesn't seem to have been an interrupt.
525 		 */
526 		return FD_NOT_VALID;
527 	}
528 
529 	if (fd_in(fdc, &cyl) < 0) {
530 		return fdc_err(fdc, "can't get cyl num\n");
531 	}
532 
533 	if (cylp)
534 		*cylp = cyl;
535 
536 	return 0;
537 }
538 
539 
540 static int
541 fd_read_status(fdc_p fdc, int fdsu)
542 {
543 	int i, ret;
544 
545 	for (i = 0; i < 7; i++) {
546 		/*
547 		 * XXX types are poorly chosen.  Only bytes can by read
548 		 * from the hardware, but fdc->status[] wants u_ints and
549 		 * fd_in() gives ints.
550 		 */
551 		int status;
552 
553 		ret = fd_in(fdc, &status);
554 		fdc->status[i] = status;
555 		if (ret != 0)
556 			break;
557 	}
558 
559 	if (ret == 0)
560 		fdc->flags |= FDC_STAT_VALID;
561 	else
562 		fdc->flags &= ~FDC_STAT_VALID;
563 
564 	return ret;
565 }
566 
567 /****************************************************************************/
568 /*                      autoconfiguration stuff                             */
569 /****************************************************************************/
570 
571 /*
572  * fdc controller section.
573  */
574 static int
575 fdc_probe(device_t dev)
576 {
577 	int	error, i, ic_type;
578 	struct	fdc_data *fdc;
579 	char	myname[8];	/* better be long enough */
580 
581 	/* No pnp support */
582 	if (isa_get_vendorid(dev))
583 		return (ENXIO);
584 
585 	fdc = device_get_softc(dev);
586 	bzero(fdc, sizeof *fdc);
587 	fdc->fdc_dev = dev;
588 	fdc->rid_ioport = fdc->rid_irq = fdc->rid_drq = 0;
589 	fdc->res_ioport = fdc->res_irq = fdc->res_drq = 0;
590 
591 	fdc->res_ioport = bus_alloc_resource(dev, SYS_RES_IOPORT,
592 					     &fdc->rid_ioport, 0ul, ~0ul,
593 					     IO_FDCSIZE, RF_ACTIVE);
594 	if (fdc->res_ioport == 0) {
595 		device_print_prettyname(dev);
596 		printf("cannot reserve I/O port range\n");
597 		error = ENXIO;
598 		goto out;
599 	}
600 	fdc->baseport = fdc->res_ioport->r_start;
601 
602 	fdc->res_irq = bus_alloc_resource(dev, SYS_RES_IRQ,
603 					  &fdc->rid_irq, 0ul, ~0ul, 1,
604 					  RF_ACTIVE);
605 	if (fdc->res_irq == 0) {
606 		device_print_prettyname(dev);
607 		printf("cannot reserve interrupt line\n");
608 		error = ENXIO;
609 		goto out;
610 	}
611 	fdc->res_drq = bus_alloc_resource(dev, SYS_RES_DRQ,
612 					  &fdc->rid_drq, 0ul, ~0ul, 1,
613 					  RF_ACTIVE);
614 	if (fdc->res_drq == 0) {
615 		device_print_prettyname(dev);
616 		printf("cannot reserve DMA request line\n");
617 		error = ENXIO;
618 		goto out;
619 	}
620 	fdc->dmachan = fdc->res_drq->r_start;
621 	error = BUS_SETUP_INTR(device_get_parent(dev), dev, fdc->res_irq,
622 			       INTR_TYPE_BIO, fdc_intr, fdc, &fdc->fdc_intr);
623 
624 	/* First - lets reset the floppy controller */
625 	outb(fdc->baseport + FDOUT, 0);
626 	DELAY(100);
627 	outb(fdc->baseport + FDOUT, FDO_FRST);
628 
629 	/* see if it can handle a command */
630 	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
631 		   NE7_SPEC_2(2, 0), 0)) {
632 		error = ENXIO;
633 		goto out;
634 	}
635 
636 	if (fd_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type) == 0) {
637 		ic_type = (u_char)ic_type;
638 		switch (ic_type) {
639 		case 0x80:
640 			device_set_desc(dev, "NEC 765 or clone");
641 			fdc->fdct = FDC_NE765;
642 			break;
643 		case 0x81:
644 			device_set_desc(dev, "Intel 82077 or clone");
645 			fdc->fdct = FDC_I82077;
646 			break;
647 		case 0x90:
648 			device_set_desc(dev, "NEC 72065B or clone");
649 			fdc->fdct = FDC_NE72065;
650 			break;
651 		default:
652 			device_set_desc(dev, "generic floppy controller");
653 			fdc->fdct = FDC_UNKNOWN;
654 			break;
655 		}
656 	}
657 
658 	snprintf(myname, sizeof(myname), "%s%d", device_get_name(dev),
659 		 device_get_unit(dev));
660 	for (i = resource_query_string(-1, "at", myname); i != -1;
661 	     i = resource_query_string(i, "at", myname))
662 		fdc_add_device(dev, resource_query_name(i),
663 			       resource_query_unit(i));
664 #ifdef FDC_YE
665 	/*
666 	 * don't succeed on probe; wait
667 	 * for PCCARD subsystem to do it
668 	 */
669 	if (dev->id_flags & FDC_IS_PCMCIA)
670 		return(0);
671 #endif
672 	return (0);
673 
674 out:
675 	if (fdc->fdc_intr)
676 		BUS_TEARDOWN_INTR(device_get_parent(dev), dev, fdc->res_irq,
677 				  fdc->fdc_intr);
678 	if (fdc->res_irq != 0) {
679 		bus_deactivate_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
680 					fdc->res_irq);
681 		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
682 				     fdc->res_irq);
683 	}
684 	if (fdc->res_ioport != 0) {
685 		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
686 					fdc->res_ioport);
687 		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
688 				     fdc->res_ioport);
689 	}
690 	if (fdc->res_drq != 0) {
691 		bus_deactivate_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
692 					fdc->res_drq);
693 		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
694 				     fdc->res_drq);
695 	}
696 	return (error);
697 }
698 
699 /*
700  * Aped dfr@freebsd.org's isa_add_device().
701  */
702 static void
703 fdc_add_device(device_t dev, const char *name, int unit)
704 {
705 	int	disabled, *ivar;
706 	device_t child;
707 
708 	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT);
709 	if (ivar == 0)
710 		return;
711 	if (resource_int_value(name, unit, "drive", ivar) != 0)
712 		*ivar = 0;
713 	child = device_add_child(dev, name, unit, ivar);
714 	if (child == 0)
715 		return;
716 	if (resource_int_value(name, unit, "disabled", &disabled) == 0
717 	    && disabled != 0)
718 		device_disable(child);
719 }
720 
721 static int
722 fdc_attach(device_t dev)
723 {
724 	struct	fdc_data *fdc = device_get_softc(dev);
725 	fdcu_t	fdcu = device_get_unit(dev);
726 
727 	fdc->fdcu = fdcu;
728 	fdc->flags |= FDC_ATTACHED;
729 
730 	/* Acquire the DMA channel forever, The driver will do the rest */
731 				/* XXX should integrate with rman */
732 	isa_dma_acquire(fdc->dmachan);
733 	isa_dmainit(fdc->dmachan, 128 << 3 /* XXX max secsize */);
734 	fdc->state = DEVIDLE;
735 
736 	/* reset controller, turn motor off, clear fdout mirror reg */
737 	outb(fdc->baseport + FDOUT, ((fdc->fdout = 0)));
738 	bufq_init(&fdc->head);
739 
740 #ifdef FIFO_BEFORE_MOTORON
741 	/* Hmm, this doesn't work here - is set_motor() magic? -Peter */
742 	if (fdc->fdct != FDC_NE765 && fdc->fdct != FDC_UNKNOWN
743 	    && enable_fifo(fdc) == 0) {
744 		device_print_prettyname(dev);
745 		printf("FIFO enabled, %d bytes threshold\n", fifo_threshold);
746 	}
747 #endif
748 	/*
749 	 * Probe and attach any children as were configured above.
750 	 */
751 	return (bus_generic_attach(dev));
752 }
753 
754 static int
755 fdc_print_child(device_t me, device_t child)
756 {
757 	int retval = 0;
758 
759 	retval += bus_print_child_header(me, child);
760 	retval += printf(" on %s drive %d\n", device_get_nameunit(me),
761 	       *(int *)device_get_ivars(child));
762 
763 	return (retval);
764 }
765 
766 static device_method_t fdc_methods[] = {
767 	/* Device interface */
768 	DEVMETHOD(device_probe,		fdc_probe),
769 	DEVMETHOD(device_attach,	fdc_attach),
770 	DEVMETHOD(device_detach,	bus_generic_detach),
771 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
772 	DEVMETHOD(device_suspend,	bus_generic_suspend),
773 	DEVMETHOD(device_resume,	bus_generic_resume),
774 
775 	/* Bus interface */
776 	DEVMETHOD(bus_print_child,	fdc_print_child),
777 	/* Our children never use any other bus interface methods. */
778 
779 	{ 0, 0 }
780 };
781 
782 static driver_t fdc_driver = {
783 	"fdc",
784 	fdc_methods,
785 	sizeof(struct fdc_data)
786 };
787 
788 DRIVER_MODULE(fdc, isa, fdc_driver, fdc_devclass, 0, 0);
789 
790 /******************************************************************/
791 /*
792  * devices attached to the controller section.
793  */
794 static int
795 fd_probe(device_t dev)
796 {
797 	int	i;
798 	u_int	fdt, st0, st3;
799 	struct	fd_data *fd;
800 	struct	fdc_data *fdc;
801 	fdsu_t	fdsu;
802 #ifndef FIFO_BEFORE_MOTORON
803 	static int fd_fifo = 0;
804 #endif
805 
806 	fdsu = *(int *)device_get_ivars(dev); /* xxx cheat a bit... */
807 	fd = device_get_softc(dev);
808 	fdc = device_get_softc(device_get_parent(dev));
809 
810 	bzero(fd, sizeof *fd);
811 	fd->dev = dev;
812 	fd->fdc = fdc;
813 	fd->fdsu = fdsu;
814 	fd->fdu = device_get_unit(dev);
815 
816 #ifdef __i386__
817 	/* look up what bios thinks we have */
818 	switch (fd->fdu) {
819 	case 0:
820 		if (isa_get_flags(fdc->fdc_dev) & FDC_PRETEND_D0)
821 			fdt = RTCFDT_144M | RTCFDT_144M_PRETENDED;
822 		else
823 			fdt = (rtcin(RTC_FDISKETTE) & 0xf0);
824 		break;
825 	case 1:
826 		fdt = ((rtcin(RTC_FDISKETTE) << 4) & 0xf0);
827 		break;
828 	default:
829 		fdt = RTCFDT_NONE;
830 		break;
831 	}
832 #else
833 	fdt = RTCFDT_144M;	/* XXX probably */
834 #endif
835 
836 	/* is there a unit? */
837 	if (fdt == RTCFDT_NONE)
838 		return (ENXIO);
839 
840 	/* select it */
841 	set_motor(fdc, fdsu, TURNON);
842 	DELAY(1000000);	/* 1 sec */
843 
844 #ifndef FIFO_BEFORE_MOTORON
845 	if (fd_fifo == 0 && fdc->fdct != FDC_NE765 && fdc->fdct != FDC_UNKNOWN
846 	    && enable_fifo(fdc) == 0) {
847 		device_print_prettyname(device_get_parent(dev));
848 		printf("FIFO enabled, %d bytes threshold\n", fifo_threshold);
849 	}
850 	fd_fifo = 1;
851 #endif
852 
853 	if ((fd_cmd(fdc, 2, NE7CMD_SENSED, fdsu, 1, &st3) == 0)
854 	    && (st3 & NE7_ST3_T0)) {
855 		/* if at track 0, first seek inwards */
856 		/* seek some steps: */
857 		fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0);
858 		DELAY(300000); /* ...wait a moment... */
859 		fd_sense_int(fdc, 0, 0); /* make ctrlr happy */
860 	}
861 
862 	/* If we're at track 0 first seek inwards. */
863 	if ((fd_sense_drive_status(fdc, &st3) == 0) && (st3 & NE7_ST3_T0)) {
864 		/* Seek some steps... */
865 		if (fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
866 			/* ...wait a moment... */
867 			DELAY(300000);
868 			/* make ctrlr happy: */
869 			fd_sense_int(fdc, 0, 0);
870 		}
871 	}
872 
873 	for (i = 0; i < 2; i++) {
874 		/*
875 		 * we must recalibrate twice, just in case the
876 		 * heads have been beyond cylinder 76, since most
877 		 * FDCs still barf when attempting to recalibrate
878 		 * more than 77 steps
879 		 */
880 		/* go back to 0: */
881 		if (fd_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
882 			/* a second being enough for full stroke seek*/
883 			DELAY(i == 0 ? 1000000 : 300000);
884 
885 			/* anything responding? */
886 			if (fd_sense_int(fdc, &st0, 0) == 0 &&
887 			    (st0 & NE7_ST0_EC) == 0)
888 				break; /* already probed succesfully */
889 		}
890 	}
891 
892 	set_motor(fdc, fdsu, TURNOFF);
893 
894 	if (st0 & NE7_ST0_EC) /* no track 0 -> no drive present */
895 		return (ENXIO);
896 
897 	fd->track = FD_NO_TRACK;
898 	fd->fdc = fdc;
899 	fd->fdsu = fdsu;
900 	fd->options = 0;
901 	callout_handle_init(&fd->toffhandle);
902 	callout_handle_init(&fd->tohandle);
903 
904 	switch (fdt) {
905 	case RTCFDT_12M:
906 		device_set_desc(dev, "1200-KB 5.25\" drive");
907 		fd->type = FD_1200;
908 		break;
909 	case RTCFDT_144M | RTCFDT_144M_PRETENDED:
910 		device_set_desc(dev, "config-pretended 1440-MB 3.5\" drive");
911 		fdt = RTCFDT_144M;
912 		fd->type = FD_1440;
913 	case RTCFDT_144M:
914 		device_set_desc(dev, "1440-KB 3.5\" drive");
915 		fd->type = FD_1440;
916 		break;
917 	case RTCFDT_288M:
918 	case RTCFDT_288M_1:
919 		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
920 		fd->type = FD_1440;
921 		break;
922 	case RTCFDT_360K:
923 		device_set_desc(dev, "360-KB 5.25\" drive");
924 		fd->type = FD_360;
925 		break;
926 	case RTCFDT_720K:
927 		printf("720-KB 3.5\" drive");
928 		fd->type = FD_720;
929 		break;
930 	default:
931 		return (ENXIO);
932 	}
933 	return (0);
934 }
935 
936 static int
937 fd_attach(device_t dev)
938 {
939 	struct	fd_data *fd;
940 #if 0
941 	int	i;
942 	int	mynor;
943 	int	typemynor;
944 	int	typesize;
945 #endif
946 
947 	fd = device_get_softc(dev);
948 
949 	make_dev(&fd_cdevsw, (fd->fdu << 6),
950 		UID_ROOT, GID_OPERATOR, 0640, "rfd%d", fd->fdu);
951 
952 #if 0
953 	/* Other make_dev() go here. */
954 #endif
955 
956 	/*
957 	 * Export the drive to the devstat interface.
958 	 */
959 	devstat_add_entry(&fd->device_stats, device_get_name(dev),
960 			  device_get_unit(dev), 512, DEVSTAT_NO_ORDERED_TAGS,
961 			  DEVSTAT_TYPE_FLOPPY | DEVSTAT_TYPE_IF_OTHER,
962 			  DEVSTAT_PRIORITY_FD);
963 	return (0);
964 }
965 
966 static device_method_t fd_methods[] = {
967 	/* Device interface */
968 	DEVMETHOD(device_probe,		fd_probe),
969 	DEVMETHOD(device_attach,	fd_attach),
970 	DEVMETHOD(device_detach,	bus_generic_detach),
971 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
972 	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
973 	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
974 
975 	{ 0, 0 }
976 };
977 
978 static driver_t fd_driver = {
979 	"fd",
980 	fd_methods,
981 	sizeof(struct fd_data)
982 };
983 
984 DEV_DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, fd_cdevsw, 0, 0);
985 
986 /******************************************************************/
987 
988 #ifdef FDC_YE
989 /*
990  * this is a subset of fdattach() optimized for the Y-E Data
991  * PCMCIA floppy drive.
992  */
993 static int yeattach(struct isa_device *dev)
994 {
995 	fdcu_t  fdcu = dev->id_unit;
996 	fdc_p   fdc = fdc_data + fdcu;
997 	fdsu_t  fdsu = 0;               /* assume 1 drive per YE controller */
998 	fdu_t   fdu;
999 	fd_p    fd;
1000 	int     st0, st3, i;
1001 	fdc->fdcu = fdcu;
1002 	/*
1003 	 * the FDC_PCMCIA flag is used to to indicate special PIO is used
1004 	 * instead of DMA
1005 	 */
1006 	fdc->flags = FDC_ATTACHED|FDC_PCMCIA;
1007 	fdc->state = DEVIDLE;
1008 	/* reset controller, turn motor off, clear fdout mirror reg */
1009 	outb(fdc->baseport + FDOUT, ((fdc->fdout = 0)));
1010 	bufq_init(&fdc->head);
1011 	/*
1012 	 * assume 2 drives/ "normal" controller
1013 	 */
1014 	fdu = fdcu * 2;
1015 	if (fdu >= NFD) {
1016 		printf("fdu %d >= NFD\n",fdu);
1017 		return(0);
1018 	};
1019 	fd = &fd_data[fdu];
1020 
1021 	set_motor(fdcu, fdsu, TURNON);
1022 	DELAY(1000000); /* 1 sec */
1023 	fdc->fdct = FDC_NE765;
1024 
1025 	if ((fd_cmd(fdcu, 2, NE7CMD_SENSED, fdsu, 1, &st3) == 0) &&
1026 		(st3 & NE7_ST3_T0)) {
1027 		/* if at track 0, first seek inwards */
1028 		/* seek some steps: */
1029 		(void)fd_cmd(fdcu, 3, NE7CMD_SEEK, fdsu, 10, 0);
1030 		DELAY(300000); /* ...wait a moment... */
1031 		(void)fd_sense_int(fdc, 0, 0); /* make ctrlr happy */
1032 	}
1033 
1034 	/* If we're at track 0 first seek inwards. */
1035 	if ((fd_sense_drive_status(fdc, &st3) == 0) && (st3 & NE7_ST3_T0)) {
1036 		/* Seek some steps... */
1037 		if (fd_cmd(fdcu, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1038 			/* ...wait a moment... */
1039 			DELAY(300000);
1040 			/* make ctrlr happy: */
1041 			(void)fd_sense_int(fdc, 0, 0);
1042 		}
1043 	}
1044 
1045 	for(i = 0; i < 2; i++) {
1046 		/*
1047 		 * we must recalibrate twice, just in case the
1048 		 * heads have been beyond cylinder 76, since most
1049 		 * FDCs still barf when attempting to recalibrate
1050 		 * more than 77 steps
1051 		 */
1052 		/* go back to 0: */
1053 		if (fd_cmd(fdcu, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1054 			/* a second being enough for full stroke seek*/
1055 			DELAY(i == 0? 1000000: 300000);
1056 
1057 			/* anything responding? */
1058 			if (fd_sense_int(fdc, &st0, 0) == 0 &&
1059 				(st0 & NE7_ST0_EC) == 0)
1060 				break; /* already probed succesfully */
1061 		}
1062 	}
1063 
1064 	set_motor(fdcu, fdsu, TURNOFF);
1065 
1066 	if (st0 & NE7_ST0_EC) /* no track 0 -> no drive present */
1067 		return(0);
1068 
1069 	fd->track = FD_NO_TRACK;
1070 	fd->fdc = fdc;
1071 	fd->fdsu = fdsu;
1072 	fd->options = 0;
1073 	printf("fdc%d: 1.44MB 3.5in PCMCIA\n", fdcu);
1074 	fd->type = FD_1440;
1075 
1076 	return (1);
1077 }
1078 #endif
1079 
1080 /****************************************************************************/
1081 /*                            motor control stuff                           */
1082 /*		remember to not deselect the drive we're working on         */
1083 /****************************************************************************/
1084 static void
1085 set_motor(struct fdc_data *fdc, int fdsu, int turnon)
1086 {
1087 	int fdout = fdc->fdout;
1088 	int needspecify = 0;
1089 
1090 	if(turnon) {
1091 		fdout &= ~FDO_FDSEL;
1092 		fdout |= (FDO_MOEN0 << fdsu) + fdsu;
1093 	} else
1094 		fdout &= ~(FDO_MOEN0 << fdsu);
1095 
1096 	if(!turnon
1097 	   && (fdout & (FDO_MOEN0+FDO_MOEN1+FDO_MOEN2+FDO_MOEN3)) == 0)
1098 		/* gonna turn off the last drive, put FDC to bed */
1099 		fdout &= ~ (FDO_FRST|FDO_FDMAEN);
1100 	else {
1101 		/* make sure controller is selected and specified */
1102 		if((fdout & (FDO_FRST|FDO_FDMAEN)) == 0)
1103 			needspecify = 1;
1104 		fdout |= (FDO_FRST|FDO_FDMAEN);
1105 	}
1106 
1107 	outb(fdc->baseport+FDOUT, fdout);
1108 	fdc->fdout = fdout;
1109 	TRACE1("[0x%x->FDOUT]", fdout);
1110 
1111 	if (needspecify) {
1112 		/*
1113 		 * XXX
1114 		 * special case: since we have just woken up the FDC
1115 		 * from its sleep, we silently assume the command will
1116 		 * be accepted, and do not test for a timeout
1117 		 */
1118 		(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1119 			     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1120 			     0);
1121 		if (fdc->flags & FDC_HAS_FIFO)
1122 			(void) enable_fifo(fdc);
1123 	}
1124 }
1125 
1126 static void
1127 fd_turnoff(void *xfd)
1128 {
1129 	int	s;
1130 	fd_p fd = xfd;
1131 
1132 	TRACE1("[fd%d: turnoff]", fd->fdu);
1133 
1134 	/*
1135 	 * Don't turn off the motor yet if the drive is active.
1136 	 * XXX shouldn't even schedule turnoff until drive is inactive
1137 	 * and nothing is queued on it.
1138 	 */
1139 	if (fd->fdc->state != DEVIDLE && fd->fdc->fdu == fd->fdu) {
1140 		fd->toffhandle = timeout(fd_turnoff, fd, 4 * hz);
1141 		return;
1142 	}
1143 
1144 	s = splbio();
1145 	fd->flags &= ~FD_MOTOR;
1146 	set_motor(fd->fdc, fd->fdsu, TURNOFF);
1147 	splx(s);
1148 }
1149 
1150 static void
1151 fd_motor_on(void *xfd)
1152 {
1153 	int	s;
1154 	fd_p fd = xfd;
1155 
1156 	s = splbio();
1157 	fd->flags &= ~FD_MOTOR_WAIT;
1158 	if((fd->fdc->fd == fd) && (fd->fdc->state == MOTORWAIT))
1159 	{
1160 		fdc_intr(fd->fdc);
1161 	}
1162 	splx(s);
1163 }
1164 
1165 static void
1166 fd_turnon(fd_p fd)
1167 {
1168 	if(!(fd->flags & FD_MOTOR))
1169 	{
1170 		fd->flags |= (FD_MOTOR + FD_MOTOR_WAIT);
1171 		set_motor(fd->fdc, fd->fdsu, TURNON);
1172 		timeout(fd_motor_on, fd, hz); /* in 1 sec its ok */
1173 	}
1174 }
1175 
1176 static void
1177 fdc_reset(fdc_p fdc)
1178 {
1179 	/* Try a reset, keep motor on */
1180 	outb(fdc->baseport + FDOUT, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1181 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1182 	DELAY(100);
1183 	/* enable FDC, but defer interrupts a moment */
1184 	outb(fdc->baseport + FDOUT, fdc->fdout & ~FDO_FDMAEN);
1185 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~FDO_FDMAEN);
1186 	DELAY(100);
1187 	outb(fdc->baseport + FDOUT, fdc->fdout);
1188 	TRACE1("[0x%x->FDOUT]", fdc->fdout);
1189 
1190 	/* XXX after a reset, silently believe the FDC will accept commands */
1191 	(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1192 		     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1193 		     0);
1194 	if (fdc->flags & FDC_HAS_FIFO)
1195 		(void) enable_fifo(fdc);
1196 }
1197 
1198 /****************************************************************************/
1199 /*                             fdc in/out                                   */
1200 /****************************************************************************/
1201 int
1202 in_fdc(struct fdc_data *fdc)
1203 {
1204 	int baseport = fdc->baseport;
1205 	int i, j = 100000;
1206 	while ((i = inb(baseport+FDSTS) & (NE7_DIO|NE7_RQM))
1207 		!= (NE7_DIO|NE7_RQM) && j-- > 0)
1208 		if (i == NE7_RQM)
1209 			return fdc_err(fdc, "ready for output in input\n");
1210 	if (j <= 0)
1211 		return fdc_err(fdc, bootverbose? "input ready timeout\n": 0);
1212 #ifdef	FDC_DEBUG
1213 	i = inb(baseport+FDDATA);
1214 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
1215 	return(i);
1216 #else	/* !FDC_DEBUG */
1217 	return inb(baseport+FDDATA);
1218 #endif	/* FDC_DEBUG */
1219 }
1220 
1221 /*
1222  * fd_in: Like in_fdc, but allows you to see if it worked.
1223  */
1224 static int
1225 fd_in(struct fdc_data *fdc, int *ptr)
1226 {
1227 	int baseport = fdc->baseport;
1228 	int i, j = 100000;
1229 	while ((i = inb(baseport+FDSTS) & (NE7_DIO|NE7_RQM))
1230 		!= (NE7_DIO|NE7_RQM) && j-- > 0)
1231 		if (i == NE7_RQM)
1232 			return fdc_err(fdc, "ready for output in input\n");
1233 	if (j <= 0)
1234 		return fdc_err(fdc, bootverbose? "input ready timeout\n": 0);
1235 #ifdef	FDC_DEBUG
1236 	i = inb(baseport+FDDATA);
1237 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
1238 	*ptr = i;
1239 	return 0;
1240 #else	/* !FDC_DEBUG */
1241 	i = inb(baseport+FDDATA);
1242 	if (ptr)
1243 		*ptr = i;
1244 	return 0;
1245 #endif	/* FDC_DEBUG */
1246 }
1247 
1248 int
1249 out_fdc(struct fdc_data *fdc, int x)
1250 {
1251 	int baseport = fdc->baseport;
1252 	int i;
1253 
1254 	/* Check that the direction bit is set */
1255 	i = 100000;
1256 	while ((inb(baseport+FDSTS) & NE7_DIO) && i-- > 0);
1257 	if (i <= 0) return fdc_err(fdc, "direction bit not set\n");
1258 
1259 	/* Check that the floppy controller is ready for a command */
1260 	i = 100000;
1261 	while ((inb(baseport+FDSTS) & NE7_RQM) == 0 && i-- > 0);
1262 	if (i <= 0)
1263 		return fdc_err(fdc, bootverbose? "output ready timeout\n": 0);
1264 
1265 	/* Send the command and return */
1266 	outb(baseport+FDDATA, x);
1267 	TRACE1("[0x%x->FDDATA]", x);
1268 	return (0);
1269 }
1270 
1271 /****************************************************************************/
1272 /*                           fdopen/fdclose                                 */
1273 /****************************************************************************/
1274 int
1275 Fdopen(dev_t dev, int flags, int mode, struct proc *p)
1276 {
1277  	fdu_t fdu = FDUNIT(minor(dev));
1278 	int type = FDTYPE(minor(dev));
1279 	fd_p	fd;
1280 	fdc_p	fdc;
1281 
1282 	dev->si_bsize_phys = DEV_BSIZE;
1283 	dev->si_bsize_best = BLKDEV_IOSIZE;
1284 	dev->si_bsize_max = MAXBSIZE;
1285 	/* check bounds */
1286 	if ((fd = devclass_get_softc(fd_devclass, fdu)) == 0)
1287 		return (ENXIO);
1288 	fdc = fd->fdc;
1289 	if ((fdc == NULL) || (fd->type == NO_TYPE))
1290 		return (ENXIO);
1291 	if (type > NUMDENS)
1292 		return (ENXIO);
1293 	if (type == 0)
1294 		type = fd->type;
1295 	else {
1296 		/*
1297 		 * For each type of basic drive, make sure we are trying
1298 		 * to open a type it can do,
1299 		 */
1300 		if (type != fd->type) {
1301 			switch (fd->type) {
1302 			case FD_360:
1303 				return (ENXIO);
1304 			case FD_720:
1305 				if (   type != FD_820
1306 				    && type != FD_800
1307 				   )
1308 					return (ENXIO);
1309 				break;
1310 			case FD_1200:
1311 				switch (type) {
1312 				case FD_1480:
1313 					type = FD_1480in5_25;
1314 					break;
1315 				case FD_1440:
1316 					type = FD_1440in5_25;
1317 					break;
1318 				case FD_820:
1319 					type = FD_820in5_25;
1320 					break;
1321 				case FD_800:
1322 					type = FD_800in5_25;
1323 					break;
1324 				case FD_720:
1325 					type = FD_720in5_25;
1326 					break;
1327 				case FD_360:
1328 					type = FD_360in5_25;
1329 					break;
1330 				default:
1331 					return(ENXIO);
1332 				}
1333 				break;
1334 			case FD_1440:
1335 				if (   type != FD_1720
1336 				    && type != FD_1480
1337 				    && type != FD_1200
1338 				    && type != FD_820
1339 				    && type != FD_800
1340 				    && type != FD_720
1341 				    )
1342 					return(ENXIO);
1343 				break;
1344 			}
1345 		}
1346 	}
1347 	fd->ft = fd_types + type - 1;
1348 	fd->flags |= FD_OPEN;
1349 	device_busy(fd->dev);
1350 	device_busy(fd->fdc->fdc_dev);
1351 	return 0;
1352 }
1353 
1354 int
1355 fdclose(dev_t dev, int flags, int mode, struct proc *p)
1356 {
1357  	fdu_t fdu = FDUNIT(minor(dev));
1358 	struct fd_data *fd;
1359 
1360 	fd = devclass_get_softc(fd_devclass, fdu);
1361 	fd->flags &= ~FD_OPEN;
1362 	fd->options &= ~FDOPT_NORETRY;
1363 
1364 	return (0);
1365 }
1366 
1367 /****************************************************************************/
1368 /*                               fdstrategy                                 */
1369 /****************************************************************************/
1370 void
1371 fdstrategy(struct buf *bp)
1372 {
1373 	unsigned nblocks, blknum, cando;
1374  	int	s;
1375  	fdu_t	fdu;
1376  	fdc_p	fdc;
1377  	fd_p	fd;
1378 	size_t	fdblk;
1379 
1380  	fdu = FDUNIT(minor(bp->b_dev));
1381 	fd = devclass_get_softc(fd_devclass, fdu);
1382 	if (fd == 0)
1383 		panic("fdstrategy: buf for nonexistent device (%#lx, %#lx)",
1384 		      (u_long)major(bp->b_dev), (u_long)minor(bp->b_dev));
1385 	fdc = fd->fdc;
1386 #ifdef FDC_YE
1387 	if (fd->type == NO_TYPE) {
1388 		bp->b_error = ENXIO;
1389 		bp->b_flags |= B_ERROR;
1390 		/*
1391 		 * I _refuse_ to use a goto
1392 		 */
1393 		biodone(bp);
1394 		return;
1395 	};
1396 #endif
1397 
1398 	fdblk = 128 << (fd->ft->secsize);
1399 	if (!(bp->b_flags & B_FORMAT)) {
1400 		if (bp->b_blkno < 0) {
1401 			printf(
1402 		"fd%d: fdstrat: bad request blkno = %lu, bcount = %ld\n",
1403 			       fdu, (u_long)bp->b_blkno, bp->b_bcount);
1404 			bp->b_error = EINVAL;
1405 			bp->b_flags |= B_ERROR;
1406 			goto bad;
1407 		}
1408 		if ((bp->b_bcount % fdblk) != 0) {
1409 			bp->b_error = EINVAL;
1410 			bp->b_flags |= B_ERROR;
1411 			goto bad;
1412 		}
1413 	}
1414 
1415 	/*
1416 	 * Set up block calculations.
1417 	 */
1418 	if (bp->b_blkno > 20000000) {
1419 		/*
1420 		 * Reject unreasonably high block number, prevent the
1421 		 * multiplication below from overflowing.
1422 		 */
1423 		bp->b_error = EINVAL;
1424 		bp->b_flags |= B_ERROR;
1425 		goto bad;
1426 	}
1427 	blknum = (unsigned) bp->b_blkno * DEV_BSIZE/fdblk;
1428  	nblocks = fd->ft->size;
1429 	bp->b_resid = 0;
1430 	if (blknum + (bp->b_bcount / fdblk) > nblocks) {
1431 		if (blknum <= nblocks) {
1432 			cando = (nblocks - blknum) * fdblk;
1433 			bp->b_resid = bp->b_bcount - cando;
1434 			if (cando == 0)
1435 				goto bad;	/* not actually bad but EOF */
1436 		} else {
1437 			bp->b_error = EINVAL;
1438 			bp->b_flags |= B_ERROR;
1439 			goto bad;
1440 		}
1441 	}
1442  	bp->b_pblkno = bp->b_blkno;
1443 	s = splbio();
1444 	bufqdisksort(&fdc->head, bp);
1445 	untimeout(fd_turnoff, fd, fd->toffhandle); /* a good idea */
1446 
1447 	/* Tell devstat we are starting on the transaction */
1448 	devstat_start_transaction(&fd->device_stats);
1449 
1450 	fdstart(fdc);
1451 	splx(s);
1452 	return;
1453 
1454 bad:
1455 	biodone(bp);
1456 }
1457 
1458 /***************************************************************\
1459 *				fdstart				*
1460 * We have just queued something.. if the controller is not busy	*
1461 * then simulate the case where it has just finished a command	*
1462 * So that it (the interrupt routine) looks on the queue for more*
1463 * work to do and picks up what we just added.			*
1464 * If the controller is already busy, we need do nothing, as it	*
1465 * will pick up our work when the present work completes		*
1466 \***************************************************************/
1467 static void
1468 fdstart(struct fdc_data *fdc)
1469 {
1470 	int s;
1471 
1472 	s = splbio();
1473 	if(fdc->state == DEVIDLE)
1474 	{
1475 		fdc_intr(fdc);
1476 	}
1477 	splx(s);
1478 }
1479 
1480 static void
1481 fd_iotimeout(void *xfdc)
1482 {
1483  	fdc_p fdc;
1484 	int s;
1485 
1486 	fdc = xfdc;
1487 	TRACE1("fd%d[fd_iotimeout()]", fdc->fdu);
1488 
1489 	/*
1490 	 * Due to IBM's brain-dead design, the FDC has a faked ready
1491 	 * signal, hardwired to ready == true. Thus, any command
1492 	 * issued if there's no diskette in the drive will _never_
1493 	 * complete, and must be aborted by resetting the FDC.
1494 	 * Many thanks, Big Blue!
1495 	 * The FDC must not be reset directly, since that would
1496 	 * interfere with the state machine.  Instead, pretend that
1497 	 * the command completed but was invalid.  The state machine
1498 	 * will reset the FDC and retry once.
1499 	 */
1500 	s = splbio();
1501 	fdc->status[0] = NE7_ST0_IC_IV;
1502 	fdc->flags &= ~FDC_STAT_VALID;
1503 	fdc->state = IOTIMEDOUT;
1504 	fdc_intr(fdc);
1505 	splx(s);
1506 }
1507 
1508 /* just ensure it has the right spl */
1509 static void
1510 fd_pseudointr(void *xfdc)
1511 {
1512 	int	s;
1513 
1514 	s = splbio();
1515 	fdc_intr(xfdc);
1516 	splx(s);
1517 }
1518 
1519 /***********************************************************************\
1520 *                                 fdintr				*
1521 * keep calling the state machine until it returns a 0			*
1522 * ALWAYS called at SPLBIO 						*
1523 \***********************************************************************/
1524 static void
1525 fdc_intr(void *xfdc)
1526 {
1527 	fdc_p fdc = xfdc;
1528 	while(fdstate(fdc))
1529 		;
1530 }
1531 
1532 #ifdef FDC_YE
1533 /*
1534  * magic pseudo-DMA initialization for YE FDC. Sets count and
1535  * direction
1536  */
1537 #define SET_BCDR(wr,cnt,port) outb(port,(((cnt)-1) & 0xff)); \
1538 	outb(port+1,((wr ? 0x80 : 0) | ((((cnt)-1) >> 8) & 0x7f)))
1539 
1540 /*
1541  * fdcpio(): perform programmed IO read/write for YE PCMCIA floppy
1542  */
1543 static int fdcpio(fdcu_t fdcu, long flags, caddr_t addr, u_int count)
1544 {
1545 	u_char *cptr = (u_char *)addr;
1546 	fdc_p fdc = &fdc_data[fdcu];
1547 	int io = fdc->baseport;
1548 
1549 	if (flags & B_READ) {
1550 		if (fdc->state != PIOREAD) {
1551 			fdc->state = PIOREAD;
1552 			return(0);
1553 		};
1554 		SET_BCDR(0,count,io);
1555 		insb(io+FDC_YE_DATAPORT,cptr,count);
1556 	} else {
1557 		outsb(io+FDC_YE_DATAPORT,cptr,count);
1558 		SET_BCDR(0,count,io);
1559 	};
1560 	return(1);
1561 }
1562 #endif /* FDC_YE */
1563 
1564 /***********************************************************************\
1565 * The controller state machine.						*
1566 * if it returns a non zero value, it should be called again immediatly	*
1567 \***********************************************************************/
1568 static int
1569 fdstate(fdc_p fdc)
1570 {
1571 	int read, format, head, i, sec = 0, sectrac, st0, cyl, st3;
1572 	unsigned blknum = 0, b_cylinder = 0;
1573 	fdu_t fdu = fdc->fdu;
1574 	fd_p fd;
1575 	register struct buf *bp;
1576 	struct fd_formb *finfo = NULL;
1577 	size_t fdblk;
1578 
1579 	bp = fdc->bp;
1580 	if (bp == NULL) {
1581 		bp = bufq_first(&fdc->head);
1582 		if (bp != NULL) {
1583 			bufq_remove(&fdc->head, bp);
1584 			fdc->bp = bp;
1585 		}
1586 	}
1587 	if (bp == NULL) {
1588 		/***********************************************\
1589 		* nothing left for this controller to do	*
1590 		* Force into the IDLE state,			*
1591 		\***********************************************/
1592 		fdc->state = DEVIDLE;
1593 		if (fdc->fd) {
1594 			device_print_prettyname(fdc->fdc_dev);
1595 			printf("unexpected valid fd pointer\n");
1596 			fdc->fd = (fd_p) 0;
1597 			fdc->fdu = -1;
1598 		}
1599 		TRACE1("[fdc%d IDLE]", fdc->fdcu);
1600  		return (0);
1601 	}
1602 	fdu = FDUNIT(minor(bp->b_dev));
1603 	fd = devclass_get_softc(fd_devclass, fdu);
1604 	fdblk = 128 << fd->ft->secsize;
1605 	if (fdc->fd && (fd != fdc->fd)) {
1606 		device_print_prettyname(fd->dev);
1607 		printf("confused fd pointers\n");
1608 	}
1609 	read = bp->b_flags & B_READ;
1610 	format = bp->b_flags & B_FORMAT;
1611 	if (format) {
1612 		finfo = (struct fd_formb *)bp->b_data;
1613 		fd->skip = (char *)&(finfo->fd_formb_cylno(0))
1614 			- (char *)finfo;
1615 	}
1616 	if (fdc->state == DOSEEK || fdc->state == SEEKCOMPLETE) {
1617 		blknum = (unsigned) bp->b_pblkno * DEV_BSIZE/fdblk +
1618 			fd->skip/fdblk;
1619 		b_cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
1620 	}
1621 	TRACE1("fd%d", fdu);
1622 	TRACE1("[%s]", fdstates[fdc->state]);
1623 	TRACE1("(0x%x)", fd->flags);
1624 	untimeout(fd_turnoff, fd, fd->toffhandle);
1625 	fd->toffhandle = timeout(fd_turnoff, fd, 4 * hz);
1626 	switch (fdc->state)
1627 	{
1628 	case DEVIDLE:
1629 	case FINDWORK:	/* we have found new work */
1630 		fdc->retry = 0;
1631 		fd->skip = 0;
1632 		fdc->fd = fd;
1633 		fdc->fdu = fdu;
1634 		outb(fdc->baseport+FDCTL, fd->ft->trans);
1635 		TRACE1("[0x%x->FDCTL]", fd->ft->trans);
1636 		/*******************************************************\
1637 		* If the next drive has a motor startup pending, then	*
1638 		* it will start up in its own good time		*
1639 		\*******************************************************/
1640 		if(fd->flags & FD_MOTOR_WAIT) {
1641 			fdc->state = MOTORWAIT;
1642 			return (0); /* come back later */
1643 		}
1644 		/*******************************************************\
1645 		* Maybe if it's not starting, it SHOULD be starting	*
1646 		\*******************************************************/
1647 		if (!(fd->flags & FD_MOTOR))
1648 		{
1649 			fdc->state = MOTORWAIT;
1650 			fd_turnon(fd);
1651 			return (0);
1652 		}
1653 		else	/* at least make sure we are selected */
1654 		{
1655 			set_motor(fdc, fd->fdsu, TURNON);
1656 		}
1657 		if (fdc->flags & FDC_NEEDS_RESET) {
1658 			fdc->state = RESETCTLR;
1659 			fdc->flags &= ~FDC_NEEDS_RESET;
1660 		} else
1661 			fdc->state = DOSEEK;
1662 		break;
1663 	case DOSEEK:
1664 		if (b_cylinder == (unsigned)fd->track)
1665 		{
1666 			fdc->state = SEEKCOMPLETE;
1667 			break;
1668 		}
1669 		if (fd_cmd(fdc, 3, NE7CMD_SEEK,
1670 			   fd->fdsu, b_cylinder * fd->ft->steptrac,
1671 			   0))
1672 		{
1673 			/*
1674 			 * seek command not accepted, looks like
1675 			 * the FDC went off to the Saints...
1676 			 */
1677 			fdc->retry = 6;	/* try a reset */
1678 			return(retrier(fdc));
1679 		}
1680 		fd->track = FD_NO_TRACK;
1681 		fdc->state = SEEKWAIT;
1682 		return(0);	/* will return later */
1683 	case SEEKWAIT:
1684 		/* allow heads to settle */
1685 		timeout(fd_pseudointr, fdc, hz / 16);
1686 		fdc->state = SEEKCOMPLETE;
1687 		return(0);	/* will return later */
1688 	case SEEKCOMPLETE : /* SEEK DONE, START DMA */
1689 		/* Make sure seek really happened*/
1690 		if(fd->track == FD_NO_TRACK) {
1691 			int descyl = b_cylinder * fd->ft->steptrac;
1692 			do {
1693 				/*
1694 				 * This might be a "ready changed" interrupt,
1695 				 * which cannot really happen since the
1696 				 * RDY pin is hardwired to + 5 volts.  This
1697 				 * generally indicates a "bouncing" intr
1698 				 * line, so do one of the following:
1699 				 *
1700 				 * When running on an enhanced FDC that is
1701 				 * known to not go stuck after responding
1702 				 * with INVALID, fetch all interrupt states
1703 				 * until seeing either an INVALID or a
1704 				 * real interrupt condition.
1705 				 *
1706 				 * When running on a dumb old NE765, give
1707 				 * up immediately.  The controller will
1708 				 * provide up to four dummy RC interrupt
1709 				 * conditions right after reset (for the
1710 				 * corresponding four drives), so this is
1711 				 * our only chance to get notice that it
1712 				 * was not the FDC that caused the interrupt.
1713 				 */
1714 				if (fd_sense_int(fdc, &st0, &cyl)
1715 				    == FD_NOT_VALID)
1716 					return 0;
1717 				if(fdc->fdct == FDC_NE765
1718 				   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
1719 					return 0; /* hope for a real intr */
1720 			} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
1721 
1722 			if (0 == descyl) {
1723 				int failed = 0;
1724 				/*
1725 				 * seek to cyl 0 requested; make sure we are
1726 				 * really there
1727 				 */
1728 				if (fd_sense_drive_status(fdc, &st3))
1729 					failed = 1;
1730 				if ((st3 & NE7_ST3_T0) == 0) {
1731 					printf(
1732 		"fd%d: Seek to cyl 0, but not really there (ST3 = %b)\n",
1733 					       fdu, st3, NE7_ST3BITS);
1734 					failed = 1;
1735 				}
1736 
1737 				if (failed) {
1738 					if(fdc->retry < 3)
1739 						fdc->retry = 3;
1740 					return (retrier(fdc));
1741 				}
1742 			}
1743 
1744 			if (cyl != descyl) {
1745 				printf(
1746 		"fd%d: Seek to cyl %d failed; am at cyl %d (ST0 = 0x%x)\n",
1747 				       fdu, descyl, cyl, st0);
1748 				if (fdc->retry < 3)
1749 					fdc->retry = 3;
1750 				return (retrier(fdc));
1751 			}
1752 		}
1753 
1754 		fd->track = b_cylinder;
1755 #ifdef FDC_YE
1756 		if (!(fdc->flags & FDC_PCMCIA))
1757 #endif
1758 			isa_dmastart(bp->b_flags, bp->b_data+fd->skip,
1759 				format ? bp->b_bcount : fdblk, fdc->dmachan);
1760 		sectrac = fd->ft->sectrac;
1761 		sec = blknum %  (sectrac * fd->ft->heads);
1762 		head = sec / sectrac;
1763 		sec = sec % sectrac + 1;
1764 		fd->hddrv = ((head&1)<<2)+fdu;
1765 
1766 		if(format || !read)
1767 		{
1768 			/* make sure the drive is writable */
1769 			if(fd_sense_drive_status(fdc, &st3) != 0)
1770 			{
1771 				/* stuck controller? */
1772 				isa_dmadone(bp->b_flags, bp->b_data + fd->skip,
1773 					    format ? bp->b_bcount : fdblk,
1774 					    fdc->dmachan);
1775 				fdc->retry = 6;	/* reset the beast */
1776 				return (retrier(fdc));
1777 			}
1778 			if(st3 & NE7_ST3_WP)
1779 			{
1780 				/*
1781 				 * XXX YES! this is ugly.
1782 				 * in order to force the current operation
1783 				 * to fail, we will have to fake an FDC
1784 				 * error - all error handling is done
1785 				 * by the retrier()
1786 				 */
1787 				fdc->status[0] = NE7_ST0_IC_AT;
1788 				fdc->status[1] = NE7_ST1_NW;
1789 				fdc->status[2] = 0;
1790 				fdc->status[3] = fd->track;
1791 				fdc->status[4] = head;
1792 				fdc->status[5] = sec;
1793 				fdc->retry = 8;	/* break out immediately */
1794 				fdc->state = IOTIMEDOUT; /* not really... */
1795 				return (1);
1796 			}
1797 		}
1798 
1799 		if (format) {
1800 #ifdef FDC_YE
1801 			if (fdc->flags & FDC_PCMCIA)
1802 				(void)fdcpio(fdcu,bp->b_flags,
1803 					bp->b_data+fd->skip,
1804 					bp->b_bcount);
1805 #endif
1806 			/* formatting */
1807 			if(fd_cmd(fdc, 6,  NE7CMD_FORMAT, head << 2 | fdu,
1808 				  finfo->fd_formb_secshift,
1809 				  finfo->fd_formb_nsecs,
1810 				  finfo->fd_formb_gaplen,
1811 				  finfo->fd_formb_fillbyte, 0)) {
1812 				/* controller fell over */
1813 				isa_dmadone(bp->b_flags, bp->b_data + fd->skip,
1814 					    format ? bp->b_bcount : fdblk,
1815 					    fdc->dmachan);
1816 				fdc->retry = 6;
1817 				return (retrier(fdc));
1818 			}
1819 		} else {
1820 #ifdef FDC_YE
1821 			if (fdc->flags & FDC_PCMCIA) {
1822 				/*
1823 				 * this seems to be necessary even when
1824 				 * reading data
1825 				 */
1826 				SET_BCDR(1,fdblk,fdc->baseport);
1827 
1828 				/*
1829 				 * perform the write pseudo-DMA before
1830 				 * the WRITE command is sent
1831 				 */
1832 				if (!read)
1833 					(void)fdcpio(fdcu,bp->b_flags,
1834 					    bp->b_data+fd->skip,
1835 					    fdblk);
1836 			}
1837 #endif
1838 			if (fd_cmd(fdc, 9,
1839 				   (read ? NE7CMD_READ : NE7CMD_WRITE),
1840 				   head << 2 | fdu,  /* head & unit */
1841 				   fd->track,        /* track */
1842 				   head,
1843 				   sec,              /* sector + 1 */
1844 				   fd->ft->secsize,  /* sector size */
1845 				   sectrac,          /* sectors/track */
1846 				   fd->ft->gap,      /* gap size */
1847 				   fd->ft->datalen,  /* data length */
1848 				   0)) {
1849 				/* the beast is sleeping again */
1850 				isa_dmadone(bp->b_flags, bp->b_data + fd->skip,
1851 					    format ? bp->b_bcount : fdblk,
1852 					    fdc->dmachan);
1853 				fdc->retry = 6;
1854 				return (retrier(fdc));
1855 			}
1856 		}
1857 #ifdef FDC_YE
1858 		if (fdc->flags & FDC_PCMCIA)
1859 			/*
1860 			 * if this is a read, then simply await interrupt
1861 			 * before performing PIO
1862 			 */
1863 			if (read && !fdcpio(fdcu,bp->b_flags,
1864 			    bp->b_data+fd->skip,fdblk)) {
1865 				fd->tohandle = timeout(fd_iotimeout,
1866 					(caddr_t)fdcu, hz);
1867 				return(0);      /* will return later */
1868 			};
1869 
1870 		/*
1871 		 * write (or format) operation will fall through and
1872 		 * await completion interrupt
1873 		 */
1874 #endif
1875 		fdc->state = IOCOMPLETE;
1876 		fd->tohandle = timeout(fd_iotimeout, fdc, hz);
1877 		return (0);	/* will return later */
1878 #ifdef FDC_YE
1879 	case PIOREAD:
1880 		/*
1881 		 * actually perform the PIO read.  The IOCOMPLETE case
1882 		 * removes the timeout for us.
1883 		 */
1884 		(void)fdcpio(fdcu,bp->b_flags,bp->b_data+fd->skip,fdblk);
1885 		fdc->state = IOCOMPLETE;
1886 		/* FALLTHROUGH */
1887 #endif
1888 	case IOCOMPLETE: /* IO DONE, post-analyze */
1889 		untimeout(fd_iotimeout, fdc, fd->tohandle);
1890 
1891 		if (fd_read_status(fdc, fd->fdsu)) {
1892 			isa_dmadone(bp->b_flags, bp->b_data + fd->skip,
1893 				    format ? bp->b_bcount : fdblk,
1894 				    fdc->dmachan);
1895 			if (fdc->retry < 6)
1896 				fdc->retry = 6;	/* force a reset */
1897 			return (retrier(fdc));
1898   		}
1899 
1900 		fdc->state = IOTIMEDOUT;
1901 
1902 		/* FALLTHROUGH */
1903 
1904 	case IOTIMEDOUT:
1905 #ifdef FDC_YE
1906 		if (!(fdc->flags & FDC_PCMCIA))
1907 #endif
1908 			isa_dmadone(bp->b_flags, bp->b_data + fd->skip,
1909 				format ? bp->b_bcount : fdblk, fdc->dmachan);
1910 		if (fdc->status[0] & NE7_ST0_IC) {
1911                         if ((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
1912 			    && fdc->status[1] & NE7_ST1_OR) {
1913                                 /*
1914 				 * DMA overrun. Someone hogged the bus
1915 				 * and didn't release it in time for the
1916 				 * next FDC transfer.
1917 				 * Just restart it, don't increment retry
1918 				 * count. (vak)
1919                                  */
1920                                 fdc->state = SEEKCOMPLETE;
1921                                 return (1);
1922                         }
1923 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_IV
1924 				&& fdc->retry < 6)
1925 				fdc->retry = 6;	/* force a reset */
1926 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
1927 				&& fdc->status[2] & NE7_ST2_WC
1928 				&& fdc->retry < 3)
1929 				fdc->retry = 3;	/* force recalibrate */
1930 			return (retrier(fdc));
1931 		}
1932 		/* All OK */
1933 		fd->skip += fdblk;
1934 		if (!format && fd->skip < bp->b_bcount - bp->b_resid) {
1935 			/* set up next transfer */
1936 			fdc->state = DOSEEK;
1937 		} else {
1938 			/* ALL DONE */
1939 			fd->skip = 0;
1940 			fdc->bp = NULL;
1941 			/* Tell devstat we have finished with the transaction */
1942 			devstat_end_transaction(&fd->device_stats,
1943 						bp->b_bcount - bp->b_resid,
1944 						DEVSTAT_TAG_NONE,
1945 						(bp->b_flags & B_READ) ?
1946 						DEVSTAT_READ : DEVSTAT_WRITE);
1947 			biodone(bp);
1948 			fdc->fd = (fd_p) 0;
1949 			fdc->fdu = -1;
1950 			fdc->state = FINDWORK;
1951 		}
1952 		return (1);
1953 	case RESETCTLR:
1954 		fdc_reset(fdc);
1955 		fdc->retry++;
1956 		fdc->state = RESETCOMPLETE;
1957 		return (0);
1958 	case RESETCOMPLETE:
1959 		/*
1960 		 * Discard all the results from the reset so that they
1961 		 * can't cause an unexpected interrupt later.
1962 		 */
1963 		for (i = 0; i < 4; i++)
1964 			(void)fd_sense_int(fdc, &st0, &cyl);
1965 		fdc->state = STARTRECAL;
1966 		/* Fall through. */
1967 	case STARTRECAL:
1968 		if(fd_cmd(fdc, 2, NE7CMD_RECAL, fdu, 0)) {
1969 			/* arrgl */
1970 			fdc->retry = 6;
1971 			return (retrier(fdc));
1972 		}
1973 		fdc->state = RECALWAIT;
1974 		return (0);	/* will return later */
1975 	case RECALWAIT:
1976 		/* allow heads to settle */
1977 		timeout(fd_pseudointr, fdc, hz / 8);
1978 		fdc->state = RECALCOMPLETE;
1979 		return (0);	/* will return later */
1980 	case RECALCOMPLETE:
1981 		do {
1982 			/*
1983 			 * See SEEKCOMPLETE for a comment on this:
1984 			 */
1985 			if (fd_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
1986 				return 0;
1987 			if(fdc->fdct == FDC_NE765
1988 			   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
1989 				return 0; /* hope for a real intr */
1990 		} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
1991 		if ((st0 & NE7_ST0_IC) != NE7_ST0_IC_NT || cyl != 0)
1992 		{
1993 			if(fdc->retry > 3)
1994 				/*
1995 				 * a recalibrate from beyond cylinder 77
1996 				 * will "fail" due to the FDC limitations;
1997 				 * since people used to complain much about
1998 				 * the failure message, try not logging
1999 				 * this one if it seems to be the first
2000 				 * time in a line
2001 				 */
2002 				printf("fd%d: recal failed ST0 %b cyl %d\n",
2003 				       fdu, st0, NE7_ST0BITS, cyl);
2004 			if(fdc->retry < 3) fdc->retry = 3;
2005 			return (retrier(fdc));
2006 		}
2007 		fd->track = 0;
2008 		/* Seek (probably) necessary */
2009 		fdc->state = DOSEEK;
2010 		return (1);	/* will return immediatly */
2011 	case MOTORWAIT:
2012 		if(fd->flags & FD_MOTOR_WAIT)
2013 		{
2014 			return (0); /* time's not up yet */
2015 		}
2016 		if (fdc->flags & FDC_NEEDS_RESET) {
2017 			fdc->state = RESETCTLR;
2018 			fdc->flags &= ~FDC_NEEDS_RESET;
2019 		} else {
2020 			/*
2021 			 * If all motors were off, then the controller was
2022 			 * reset, so it has lost track of the current
2023 			 * cylinder.  Recalibrate to handle this case.
2024 			 * But first, discard the results of the reset.
2025 			 */
2026 			fdc->state = RESETCOMPLETE;
2027 		}
2028 		return (1);	/* will return immediatly */
2029 	default:
2030 		device_print_prettyname(fdc->fdc_dev);
2031 		printf("unexpected FD int->");
2032 		if (fd_read_status(fdc, fd->fdsu) == 0)
2033 			printf("FDC status :%x %x %x %x %x %x %x   ",
2034 			       fdc->status[0],
2035 			       fdc->status[1],
2036 			       fdc->status[2],
2037 			       fdc->status[3],
2038 			       fdc->status[4],
2039 			       fdc->status[5],
2040 			       fdc->status[6] );
2041 		else
2042 			printf("No status available   ");
2043 		if (fd_sense_int(fdc, &st0, &cyl) != 0)
2044 		{
2045 			printf("[controller is dead now]\n");
2046 			return (0);
2047 		}
2048 		printf("ST0 = %x, PCN = %x\n", st0, cyl);
2049 		return (0);
2050 	}
2051 	/*XXX confusing: some branches return immediately, others end up here*/
2052 	return (1); /* Come back immediatly to new state */
2053 }
2054 
2055 static int
2056 retrier(struct fdc_data *fdc)
2057 {
2058 	register struct buf *bp;
2059 	struct fd_data *fd;
2060 	int fdu;
2061 
2062 	bp = fdc->bp;
2063 
2064 	/* XXX shouldn't this be cached somewhere?  */
2065 	fdu = FDUNIT(minor(bp->b_dev));
2066 	fd = devclass_get_softc(fd_devclass, fdu);
2067 	if (fd->options & FDOPT_NORETRY)
2068 		goto fail;
2069 
2070 	switch (fdc->retry) {
2071 	case 0: case 1: case 2:
2072 		fdc->state = SEEKCOMPLETE;
2073 		break;
2074 	case 3: case 4: case 5:
2075 		fdc->state = STARTRECAL;
2076 		break;
2077 	case 6:
2078 		fdc->state = RESETCTLR;
2079 		break;
2080 	case 7:
2081 		break;
2082 	default:
2083 	fail:
2084 		{
2085 			dev_t sav_b_dev = bp->b_dev;
2086 			/* Trick diskerr */
2087 			bp->b_dev = makedev(major(bp->b_dev),
2088 				    (FDUNIT(minor(bp->b_dev))<<3)|RAW_PART);
2089 			diskerr(bp, "fd", "hard error", LOG_PRINTF,
2090 				fdc->fd->skip / DEV_BSIZE,
2091 				(struct disklabel *)NULL);
2092 			bp->b_dev = sav_b_dev;
2093 			if (fdc->flags & FDC_STAT_VALID)
2094 			{
2095 				printf(
2096 			" (ST0 %b ST1 %b ST2 %b cyl %u hd %u sec %u)\n",
2097 				       fdc->status[0], NE7_ST0BITS,
2098 				       fdc->status[1], NE7_ST1BITS,
2099 				       fdc->status[2], NE7_ST2BITS,
2100 				       fdc->status[3], fdc->status[4],
2101 				       fdc->status[5]);
2102 			}
2103 			else
2104 				printf(" (No status)\n");
2105 		}
2106 		bp->b_flags |= B_ERROR;
2107 		bp->b_error = EIO;
2108 		bp->b_resid += bp->b_bcount - fdc->fd->skip;
2109 		fdc->bp = NULL;
2110 
2111 		/* Tell devstat we have finished with the transaction */
2112 		devstat_end_transaction(&fdc->fd->device_stats,
2113 					bp->b_bcount - bp->b_resid,
2114 					DEVSTAT_TAG_NONE,
2115 					(bp->b_flags & B_READ) ? DEVSTAT_READ :
2116 								 DEVSTAT_WRITE);
2117 		fdc->fd->skip = 0;
2118 		biodone(bp);
2119 		fdc->state = FINDWORK;
2120 		fdc->flags |= FDC_NEEDS_RESET;
2121 		fdc->fd = (fd_p) 0;
2122 		fdc->fdu = -1;
2123 		return (1);
2124 	}
2125 	fdc->retry++;
2126 	return (1);
2127 }
2128 
2129 static int
2130 fdformat(dev, finfo, p)
2131 	dev_t dev;
2132 	struct fd_formb *finfo;
2133 	struct proc *p;
2134 {
2135  	fdu_t	fdu;
2136  	fd_p	fd;
2137 
2138 	struct buf *bp;
2139 	int rv = 0, s;
2140 	size_t fdblk;
2141 
2142  	fdu	= FDUNIT(minor(dev));
2143 	fd	= devclass_get_softc(fd_devclass, fdu);
2144 	fdblk = 128 << fd->ft->secsize;
2145 
2146 	/* set up a buffer header for fdstrategy() */
2147 	bp = (struct buf *)malloc(sizeof(struct buf), M_TEMP, M_NOWAIT);
2148 	if(bp == 0)
2149 		return ENOBUFS;
2150 	/*
2151 	 * keep the process from being swapped
2152 	 */
2153 	PHOLD(p);
2154 	bzero((void *)bp, sizeof(struct buf));
2155 	BUF_LOCKINIT(bp);
2156 	BUF_LOCK(bp, LK_EXCLUSIVE);
2157 	bp->b_flags = B_PHYS | B_FORMAT;
2158 
2159 	/*
2160 	 * calculate a fake blkno, so fdstrategy() would initiate a
2161 	 * seek to the requested cylinder
2162 	 */
2163 	bp->b_blkno = (finfo->cyl * (fd->ft->sectrac * fd->ft->heads)
2164 		+ finfo->head * fd->ft->sectrac) * fdblk / DEV_BSIZE;
2165 
2166 	bp->b_bcount = sizeof(struct fd_idfield_data) * finfo->fd_formb_nsecs;
2167 	bp->b_data = (caddr_t)finfo;
2168 
2169 	/* now do the format */
2170 	bp->b_dev = dev;
2171 	BUF_STRATEGY(bp, 0);
2172 
2173 	/* ...and wait for it to complete */
2174 	s = splbio();
2175 	while(!(bp->b_flags & B_DONE)) {
2176 		rv = tsleep((caddr_t)bp, PRIBIO, "fdform", 20 * hz);
2177 		if (rv == EWOULDBLOCK)
2178 			break;
2179 	}
2180 	splx(s);
2181 
2182 	if (rv == EWOULDBLOCK) {
2183 		/* timed out */
2184 		rv = EIO;
2185 		biodone(bp);
2186 	}
2187 	if (bp->b_flags & B_ERROR)
2188 		rv = bp->b_error;
2189 	/*
2190 	 * allow the process to be swapped
2191 	 */
2192 	PRELE(p);
2193 	BUF_UNLOCK(bp);
2194 	BUF_LOCKFREE(bp);
2195 	free(bp, M_TEMP);
2196 	return rv;
2197 }
2198 
2199 /*
2200  * TODO: don't allocate buffer on stack.
2201  */
2202 
2203 static int
2204 fdioctl(dev, cmd, addr, flag, p)
2205 	dev_t dev;
2206 	u_long cmd;
2207 	caddr_t addr;
2208 	int flag;
2209 	struct proc *p;
2210 {
2211  	fdu_t	fdu = FDUNIT(minor(dev));
2212  	fd_p	fd = devclass_get_softc(fd_devclass, fdu);
2213 	size_t fdblk;
2214 
2215 	struct fd_type *fdt;
2216 	struct disklabel *dl;
2217 	char buffer[DEV_BSIZE];
2218 	int error = 0;
2219 
2220 	fdblk = 128 << fd->ft->secsize;
2221 
2222 	switch (cmd) {
2223 	case DIOCGDINFO:
2224 		bzero(buffer, sizeof (buffer));
2225 		dl = (struct disklabel *)buffer;
2226 		dl->d_secsize = fdblk;
2227 		fdt = fd->ft;
2228 		dl->d_secpercyl = fdt->size / fdt->tracks;
2229 		dl->d_type = DTYPE_FLOPPY;
2230 
2231 		if (readdisklabel(dkmodpart(dev, RAW_PART), dl)
2232 		    == NULL)
2233 			error = 0;
2234 		else
2235 			error = EINVAL;
2236 
2237 		*(struct disklabel *)addr = *dl;
2238 		break;
2239 
2240 	case DIOCSDINFO:
2241 		if ((flag & FWRITE) == 0)
2242 			error = EBADF;
2243 		break;
2244 
2245 	case DIOCWLABEL:
2246 		if ((flag & FWRITE) == 0)
2247 			error = EBADF;
2248 		break;
2249 
2250 	case DIOCWDINFO:
2251 		if ((flag & FWRITE) == 0) {
2252 			error = EBADF;
2253 			break;
2254 		}
2255 
2256 		dl = (struct disklabel *)addr;
2257 
2258 		if ((error = setdisklabel((struct disklabel *)buffer, dl,
2259 					  (u_long)0)) != 0)
2260 			break;
2261 
2262 		error = writedisklabel(dev, (struct disklabel *)buffer);
2263 		break;
2264 	case FD_FORM:
2265 		if ((flag & FWRITE) == 0)
2266 			error = EBADF;	/* must be opened for writing */
2267 		else if (((struct fd_formb *)addr)->format_version !=
2268 			FD_FORMAT_VERSION)
2269 			error = EINVAL;	/* wrong version of formatting prog */
2270 		else
2271 			error = fdformat(dev, (struct fd_formb *)addr, p);
2272 		break;
2273 
2274 	case FD_GTYPE:                  /* get drive type */
2275 		*(struct fd_type *)addr = *fd->ft;
2276 		break;
2277 
2278 	case FD_STYPE:                  /* set drive type */
2279 		/* this is considered harmful; only allow for superuser */
2280 		if (suser(p) != 0)
2281 			return EPERM;
2282 		*fd->ft = *(struct fd_type *)addr;
2283 		break;
2284 
2285 	case FD_GOPTS:			/* get drive options */
2286 		*(int *)addr = fd->options;
2287 		break;
2288 
2289 	case FD_SOPTS:			/* set drive options */
2290 		fd->options = *(int *)addr;
2291 		break;
2292 
2293 	default:
2294 		error = ENOTTY;
2295 		break;
2296 	}
2297 	return (error);
2298 }
2299 
2300 #endif /* NFDC > 0 */
2301 
2302 /*
2303  * Hello emacs, these are the
2304  * Local Variables:
2305  *  c-indent-level:               8
2306  *  c-continued-statement-offset: 8
2307  *  c-continued-brace-offset:     0
2308  *  c-brace-offset:              -8
2309  *  c-brace-imaginary-offset:     0
2310  *  c-argdecl-indent:             8
2311  *  c-label-offset:              -8
2312  *  c++-hanging-braces:           1
2313  *  c++-access-specifier-offset: -8
2314  *  c++-empty-arglist-indent:     8
2315  *  c++-friend-offset:            0
2316  * End:
2317  */
2318