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