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