xref: /freebsd/sys/dev/fdc/fdc.c (revision 09e8dea79366f1e5b3a73e8a271b26e4b6bf2e6a)
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.heep.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$
54  */
55 
56 #include "opt_fdc.h"
57 #include "card.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/bus.h>
63 #include <sys/conf.h>
64 #include <sys/devicestat.h>
65 #include <sys/disklabel.h>
66 #include <sys/fcntl.h>
67 #include <sys/fdcio.h>
68 #include <sys/filio.h>
69 #include <sys/kernel.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/module.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/syslog.h>
76 
77 #include <machine/bus.h>
78 #include <sys/rman.h>
79 
80 #include <machine/clock.h>
81 #include <machine/resource.h>
82 #include <machine/stdarg.h>
83 
84 #include <isa/isavar.h>
85 #include <isa/isareg.h>
86 #include <isa/fdreg.h>
87 #include <isa/rtc.h>
88 
89 enum fdc_type
90 {
91 	FDC_NE765, FDC_ENHANCED, FDC_UNKNOWN = -1
92 };
93 
94 enum fdc_states {
95 	DEVIDLE,
96 	FINDWORK,
97 	DOSEEK,
98 	SEEKCOMPLETE ,
99 	IOCOMPLETE,
100 	RECALCOMPLETE,
101 	STARTRECAL,
102 	RESETCTLR,
103 	SEEKWAIT,
104 	RECALWAIT,
105 	MOTORWAIT,
106 	IOTIMEDOUT,
107 	RESETCOMPLETE,
108 	PIOREAD
109 };
110 
111 #ifdef	FDC_DEBUG
112 static char const * const fdstates[] = {
113 	"DEVIDLE",
114 	"FINDWORK",
115 	"DOSEEK",
116 	"SEEKCOMPLETE",
117 	"IOCOMPLETE",
118 	"RECALCOMPLETE",
119 	"STARTRECAL",
120 	"RESETCTLR",
121 	"SEEKWAIT",
122 	"RECALWAIT",
123 	"MOTORWAIT",
124 	"IOTIMEDOUT",
125 	"RESETCOMPLETE",
126 	"PIOREAD"
127 };
128 #endif
129 
130 /*
131  * Per controller structure (softc).
132  */
133 struct fdc_data
134 {
135 	int	fdcu;		/* our unit number */
136 	int	dmachan;
137 	int	flags;
138 #define FDC_ATTACHED	0x01
139 #define FDC_STAT_VALID	0x08
140 #define FDC_HAS_FIFO	0x10
141 #define FDC_NEEDS_RESET	0x20
142 #define FDC_NODMA	0x40
143 #define FDC_ISPNP	0x80
144 #define FDC_ISPCMCIA	0x100
145 	struct	fd_data *fd;
146 	int	fdu;		/* the active drive	*/
147 	enum	fdc_states state;
148 	int	retry;
149 	int	fdout;		/* mirror of the w/o digital output reg */
150 	u_int	status[7];	/* copy of the registers */
151 	enum	fdc_type fdct;	/* chip version of FDC */
152 	int	fdc_errs;	/* number of logged errors */
153 	int	dma_overruns;	/* number of DMA overruns */
154 	struct	bio_queue_head head;
155 	struct	bio *bp;	/* active buffer */
156 	struct	resource *res_ioport, *res_ctl, *res_irq, *res_drq;
157 	int	rid_ioport, rid_ctl, rid_irq, rid_drq;
158 	int	port_off;
159 	bus_space_tag_t portt;
160 	bus_space_handle_t porth;
161 	bus_space_tag_t ctlt;
162 	bus_space_handle_t ctlh;
163 	void	*fdc_intr;
164 	struct	device *fdc_dev;
165 	void	(*fdctl_wr)(struct fdc_data *fdc, u_int8_t v);
166 };
167 
168 #define BIO_FORMAT	BIO_CMD2
169 
170 typedef int	fdu_t;
171 typedef int	fdcu_t;
172 typedef int	fdsu_t;
173 typedef	struct fd_data *fd_p;
174 typedef struct fdc_data *fdc_p;
175 typedef enum fdc_type fdc_t;
176 
177 #define FDUNIT(s)	(((s) >> 6) & 3)
178 #define FDNUMTOUNIT(n)	(((n) & 3) << 6)
179 #define FDTYPE(s)	((s) & 0x3f)
180 
181 /*
182  * fdc maintains a set (1!) of ivars per child of each controller.
183  */
184 enum fdc_device_ivars {
185 	FDC_IVAR_FDUNIT,
186 };
187 
188 /*
189  * Simple access macros for the ivars.
190  */
191 #define FDC_ACCESSOR(A, B, T)						\
192 static __inline T fdc_get_ ## A(device_t dev)				\
193 {									\
194 	uintptr_t v;							\
195 	BUS_READ_IVAR(device_get_parent(dev), dev, FDC_IVAR_ ## B, &v);	\
196 	return (T) v;							\
197 }
198 FDC_ACCESSOR(fdunit,	FDUNIT,	int)
199 
200 /* configuration flags for fdc */
201 #define FDC_NO_FIFO	(1 << 2)	/* do not enable FIFO  */
202 
203 /* error returns for fd_cmd() */
204 #define FD_FAILED -1
205 #define FD_NOT_VALID -2
206 #define FDC_ERRMAX	100	/* do not log more */
207 /*
208  * Stop retrying after this many DMA overruns.  Since each retry takes
209  * one revolution, with 300 rpm., 25 retries take approximately 5
210  * seconds which the read attempt will block in case the DMA overrun
211  * is persistent.
212  */
213 #define FDC_DMAOV_MAX	25
214 
215 /*
216  * Timeout value for the PIO loops to wait until the FDC main status
217  * register matches our expectations (request for master, direction
218  * bit).  This is supposed to be a number of microseconds, although
219  * timing might actually not be very accurate.
220  *
221  * Timeouts of 100 msec are believed to be required for some broken
222  * (old) hardware.
223  */
224 #define	FDSTS_TIMEOUT	100000
225 
226 /*
227  * Number of subdevices that can be used for different density types.
228  * By now, the lower 6 bit of the minor number are reserved for this,
229  * allowing for up to 64 subdevices, but we only use 16 out of this.
230  * Density #0 is used for automatic format detection, the other
231  * densities are available as programmable densities (for assignment
232  * by fdcontrol(8)).
233  * The upper 2 bits of the minor number are reserved for the subunit
234  * (drive #) per controller.
235  */
236 #define NUMDENS		16
237 
238 #define BIO_RDSECTID	BIO_CMD1
239 
240 /*
241  * List of native drive densities.  Order must match enum fd_drivetype
242  * in <sys/fdcio.h>.  Upon attaching the drive, each of the
243  * programmable subdevices is initialized with the native density
244  * definition.
245  */
246 static struct fd_type fd_native_types[] =
247 {
248 { 0 },				/* FDT_NONE */
249 {  9,2,0xFF,0x2A,40, 720,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* FDT_360K */
250 { 15,2,0xFF,0x1B,80,2400,FDC_500KBPS,2,0x54,1,0,FL_MFM }, /* FDT_12M  */
251 {  9,2,0xFF,0x20,80,1440,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* FDT_720K */
252 { 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* FDT_144M */
253 #if 0				/* we currently don't handle 2.88 MB */
254 { 36,2,0xFF,0x1B,80,5760,FDC_1MBPS,  2,0x4C,1,1,FL_MFM|FL_PERPND } /*FDT_288M*/
255 #else
256 { 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* FDT_144M */
257 #endif
258 };
259 
260 /*
261  * 360 KB 5.25" and 720 KB 3.5" drives don't have automatic density
262  * selection, they just start out with their native density (or lose).
263  * So 1.2 MB 5.25", 1.44 MB 3.5", and 2.88 MB 3.5" drives have their
264  * respective lists of densities to search for.
265  */
266 static struct fd_type fd_searchlist_12m[] = {
267 { 15,2,0xFF,0x1B,80,2400,FDC_500KBPS,2,0x54,1,0,FL_MFM }, /* 1.2M */
268 {  9,2,0xFF,0x23,40, 720,FDC_300KBPS,2,0x50,1,0,FL_MFM|FL_2STEP }, /* 360K */
269 {  9,2,0xFF,0x20,80,1440,FDC_300KBPS,2,0x50,1,0,FL_MFM }, /* 720K */
270 };
271 
272 static struct fd_type fd_searchlist_144m[] = {
273 { 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* 1.44M */
274 {  9,2,0xFF,0x20,80,1440,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* 720K */
275 };
276 
277 /* We search for 1.44M first since this is the most common case. */
278 static struct fd_type fd_searchlist_288m[] = {
279 { 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* 1.44M */
280 #if 0
281 { 36,2,0xFF,0x1B,80,5760,FDC_1MBPS,  2,0x4C,1,1,FL_MFM|FL_PERPND } /* 2.88M */
282 #endif
283 {  9,2,0xFF,0x20,80,1440,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* 720K */
284 };
285 
286 #define MAX_SEC_SIZE	(128 << 3)
287 #define MAX_CYLINDER	85	/* some people really stress their drives
288 				 * up to cyl 82 */
289 #define MAX_HEAD	1
290 
291 static devclass_t fdc_devclass;
292 
293 /*
294  * Per drive structure (softc).
295  */
296 struct fd_data {
297 	struct	fdc_data *fdc;	/* pointer to controller structure */
298 	int	fdsu;		/* this units number on this controller */
299 	enum	fd_drivetype type; /* drive type */
300 	struct	fd_type *ft;	/* pointer to current type descriptor */
301 	struct	fd_type fts[NUMDENS]; /* type descriptors */
302 	int	flags;
303 #define	FD_OPEN		0x01	/* it's open		*/
304 #define	FD_NONBLOCK	0x02	/* O_NONBLOCK set	*/
305 #define	FD_ACTIVE	0x04	/* it's active		*/
306 #define	FD_MOTOR	0x08	/* motor should be on	*/
307 #define	FD_MOTOR_WAIT	0x10	/* motor coming up	*/
308 #define	FD_UA		0x20	/* force unit attention */
309 	int	skip;
310 	int	hddrv;
311 #define FD_NO_TRACK -2
312 	int	track;		/* where we think the head is */
313 	int	options;	/* user configurable options, see fdcio.h */
314 	struct	callout_handle toffhandle;
315 	struct	callout_handle tohandle;
316 	struct	devstat device_stats;
317 	eventhandler_tag clonetag;
318 	dev_t	masterdev;
319 	dev_t	clonedevs[NUMDENS - 1];
320 	device_t dev;
321 	fdu_t	fdu;
322 };
323 
324 struct fdc_ivars {
325 	int	fdunit;
326 };
327 static devclass_t fd_devclass;
328 
329 /* configuration flags for fd */
330 #define FD_TYPEMASK	0x0f	/* drive type, matches enum
331 				 * fd_drivetype; on i386 machines, if
332 				 * given as 0, use RTC type for fd0
333 				 * and fd1 */
334 #define FD_DTYPE(flags)	((flags) & FD_TYPEMASK)
335 #define FD_NO_CHLINE	0x10	/* drive does not support changeline
336 				 * aka. unit attention */
337 #define FD_NO_PROBE	0x20	/* don't probe drive (seek test), just
338 				 * assume it is there */
339 
340 /*
341  * Throughout this file the following conventions will be used:
342  *
343  * fd is a pointer to the fd_data struct for the drive in question
344  * fdc is a pointer to the fdc_data struct for the controller
345  * fdu is the floppy drive unit number
346  * fdcu is the floppy controller unit number
347  * fdsu is the floppy drive unit number on that controller. (sub-unit)
348  */
349 
350 /*
351  * Function declarations, same (chaotic) order as they appear in the
352  * file.  Re-ordering is too late now, it would only obfuscate the
353  * diffs against old and offspring versions (like the PC98 one).
354  *
355  * Anyone adding functions here, please keep this sequence the same
356  * as below -- makes locating a particular function in the body much
357  * easier.
358  */
359 static void fdout_wr(fdc_p, u_int8_t);
360 static u_int8_t fdsts_rd(fdc_p);
361 static void fddata_wr(fdc_p, u_int8_t);
362 static u_int8_t fddata_rd(fdc_p);
363 static void fdctl_wr_isa(fdc_p, u_int8_t);
364 #if NCARD > 0
365 static void fdctl_wr_pcmcia(fdc_p, u_int8_t);
366 #endif
367 #if 0
368 static u_int8_t fdin_rd(fdc_p);
369 #endif
370 static int fdc_err(struct fdc_data *, const char *);
371 static int fd_cmd(struct fdc_data *, int, ...);
372 static int enable_fifo(fdc_p fdc);
373 static int fd_sense_drive_status(fdc_p, int *);
374 static int fd_sense_int(fdc_p, int *, int *);
375 static int fd_read_status(fdc_p);
376 static int fdc_alloc_resources(struct fdc_data *);
377 static void fdc_release_resources(struct fdc_data *);
378 static int fdc_read_ivar(device_t, device_t, int, uintptr_t *);
379 static int fdc_probe(device_t);
380 #if NCARD > 0
381 static int fdc_pccard_probe(device_t);
382 #endif
383 static int fdc_detach(device_t dev);
384 static void fdc_add_child(device_t, const char *, int);
385 static int fdc_attach(device_t);
386 static int fdc_print_child(device_t, device_t);
387 static void fd_clone (void *, char *, int, dev_t *);
388 static int fd_probe(device_t);
389 static int fd_attach(device_t);
390 static int fd_detach(device_t);
391 static void set_motor(struct fdc_data *, int, int);
392 #  define TURNON 1
393 #  define TURNOFF 0
394 static timeout_t fd_turnoff;
395 static timeout_t fd_motor_on;
396 static void fd_turnon(struct fd_data *);
397 static void fdc_reset(fdc_p);
398 static int fd_in(struct fdc_data *, int *);
399 static int out_fdc(struct fdc_data *, int);
400 /*
401  * The open function is named Fdopen() to avoid confusion with fdopen()
402  * in fd(4).  The difference is now only meaningful for debuggers.
403  */
404 static	d_open_t	Fdopen;
405 static	d_close_t	fdclose;
406 static	d_strategy_t	fdstrategy;
407 static void fdstart(struct fdc_data *);
408 static timeout_t fd_iotimeout;
409 static timeout_t fd_pseudointr;
410 static driver_intr_t fdc_intr;
411 static int fdcpio(fdc_p, long, caddr_t, u_int);
412 static int fdautoselect(dev_t);
413 static int fdstate(struct fdc_data *);
414 static int retrier(struct fdc_data *);
415 static void fdbiodone(struct bio *);
416 static int fdmisccmd(dev_t, u_int, void *);
417 static	d_ioctl_t	fdioctl;
418 
419 static int fifo_threshold = 8;	/* XXX: should be accessible via sysctl */
420 
421 #ifdef	FDC_DEBUG
422 /* CAUTION: fd_debug causes huge amounts of logging output */
423 static int volatile fd_debug = 0;
424 #define TRACE0(arg) do { if (fd_debug) printf(arg); } while (0)
425 #define TRACE1(arg1, arg2) do { if (fd_debug) printf(arg1, arg2); } while (0)
426 #else /* FDC_DEBUG */
427 #define TRACE0(arg) do { } while (0)
428 #define TRACE1(arg1, arg2) do { } while (0)
429 #endif /* FDC_DEBUG */
430 
431 /*
432  * Bus space handling (access to low-level IO).
433  */
434 static void
435 fdout_wr(fdc_p fdc, u_int8_t v)
436 {
437 	bus_space_write_1(fdc->portt, fdc->porth, FDOUT+fdc->port_off, v);
438 }
439 
440 static u_int8_t
441 fdsts_rd(fdc_p fdc)
442 {
443 	return bus_space_read_1(fdc->portt, fdc->porth, FDSTS+fdc->port_off);
444 }
445 
446 static void
447 fddata_wr(fdc_p fdc, u_int8_t v)
448 {
449 	bus_space_write_1(fdc->portt, fdc->porth, FDDATA+fdc->port_off, v);
450 }
451 
452 static u_int8_t
453 fddata_rd(fdc_p fdc)
454 {
455 	return bus_space_read_1(fdc->portt, fdc->porth, FDDATA+fdc->port_off);
456 }
457 
458 static void
459 fdctl_wr_isa(fdc_p fdc, u_int8_t v)
460 {
461 	bus_space_write_1(fdc->ctlt, fdc->ctlh, 0, v);
462 }
463 
464 #if NCARD > 0
465 static void
466 fdctl_wr_pcmcia(fdc_p fdc, u_int8_t v)
467 {
468 	bus_space_write_1(fdc->portt, fdc->porth, FDCTL+fdc->port_off, v);
469 }
470 #endif
471 
472 static u_int8_t
473 fdin_rd(fdc_p fdc)
474 {
475 	return bus_space_read_1(fdc->portt, fdc->porth, FDIN);
476 }
477 
478 #define CDEV_MAJOR 9
479 static struct cdevsw fd_cdevsw = {
480 	/* open */	Fdopen,
481 	/* close */	fdclose,
482 	/* read */	physread,
483 	/* write */	physwrite,
484 	/* ioctl */	fdioctl,
485 	/* poll */	nopoll,
486 	/* mmap */	nommap,
487 	/* strategy */	fdstrategy,
488 	/* name */	"fd",
489 	/* maj */	CDEV_MAJOR,
490 	/* dump */	nodump,
491 	/* psize */	nopsize,
492 	/* flags */	D_DISK,
493 };
494 
495 /*
496  * Auxiliary functions.  Well, some only.  Others are scattered
497  * throughout the entire file.
498  */
499 static int
500 fdc_err(struct fdc_data *fdc, const char *s)
501 {
502 	fdc->fdc_errs++;
503 	if (s) {
504 		if (fdc->fdc_errs < FDC_ERRMAX)
505 			device_printf(fdc->fdc_dev, "%s", s);
506 		else if (fdc->fdc_errs == FDC_ERRMAX)
507 			device_printf(fdc->fdc_dev, "too many errors, not "
508 						    "logging any more\n");
509 	}
510 
511 	return FD_FAILED;
512 }
513 
514 /*
515  * fd_cmd: Send a command to the chip.  Takes a varargs with this structure:
516  * Unit number,
517  * # of output bytes, output bytes as ints ...,
518  * # of input bytes, input bytes as ints ...
519  */
520 static int
521 fd_cmd(struct fdc_data *fdc, int n_out, ...)
522 {
523 	u_char cmd;
524 	int n_in;
525 	int n;
526 	va_list ap;
527 
528 	va_start(ap, n_out);
529 	cmd = (u_char)(va_arg(ap, int));
530 	va_end(ap);
531 	va_start(ap, n_out);
532 	for (n = 0; n < n_out; n++)
533 	{
534 		if (out_fdc(fdc, va_arg(ap, int)) < 0)
535 		{
536 			char msg[50];
537 			snprintf(msg, sizeof(msg),
538 				"cmd %x failed at out byte %d of %d\n",
539 				cmd, n + 1, n_out);
540 			return fdc_err(fdc, msg);
541 		}
542 	}
543 	n_in = va_arg(ap, int);
544 	for (n = 0; n < n_in; n++)
545 	{
546 		int *ptr = va_arg(ap, int *);
547 		if (fd_in(fdc, ptr) < 0)
548 		{
549 			char msg[50];
550 			snprintf(msg, sizeof(msg),
551 				"cmd %02x failed at in byte %d of %d\n",
552 				cmd, n + 1, n_in);
553 			return fdc_err(fdc, msg);
554 		}
555 	}
556 
557 	return 0;
558 }
559 
560 static int
561 enable_fifo(fdc_p fdc)
562 {
563 	int i, j;
564 
565 	if ((fdc->flags & FDC_HAS_FIFO) == 0) {
566 
567 		/*
568 		 * Cannot use fd_cmd the normal way here, since
569 		 * this might be an invalid command. Thus we send the
570 		 * first byte, and check for an early turn of data directon.
571 		 */
572 
573 		if (out_fdc(fdc, I8207X_CONFIGURE) < 0)
574 			return fdc_err(fdc, "Enable FIFO failed\n");
575 
576 		/* If command is invalid, return */
577 		j = FDSTS_TIMEOUT;
578 		while ((i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM))
579 		       != NE7_RQM && j-- > 0) {
580 			if (i == (NE7_DIO | NE7_RQM)) {
581 				fdc_reset(fdc);
582 				return FD_FAILED;
583 			}
584 			DELAY(1);
585 		}
586 		if (j<0 ||
587 		    fd_cmd(fdc, 3,
588 			   0, (fifo_threshold - 1) & 0xf, 0, 0) < 0) {
589 			fdc_reset(fdc);
590 			return fdc_err(fdc, "Enable FIFO failed\n");
591 		}
592 		fdc->flags |= FDC_HAS_FIFO;
593 		return 0;
594 	}
595 	if (fd_cmd(fdc, 4,
596 		   I8207X_CONFIGURE, 0, (fifo_threshold - 1) & 0xf, 0, 0) < 0)
597 		return fdc_err(fdc, "Re-enable FIFO failed\n");
598 	return 0;
599 }
600 
601 static int
602 fd_sense_drive_status(fdc_p fdc, int *st3p)
603 {
604 	int st3;
605 
606 	if (fd_cmd(fdc, 2, NE7CMD_SENSED, fdc->fdu, 1, &st3))
607 	{
608 		return fdc_err(fdc, "Sense Drive Status failed\n");
609 	}
610 	if (st3p)
611 		*st3p = st3;
612 
613 	return 0;
614 }
615 
616 static int
617 fd_sense_int(fdc_p fdc, int *st0p, int *cylp)
618 {
619 	int cyl, st0, ret;
620 
621 	ret = fd_cmd(fdc, 1, NE7CMD_SENSEI, 1, &st0);
622 	if (ret) {
623 		(void)fdc_err(fdc,
624 			      "sense intr err reading stat reg 0\n");
625 		return ret;
626 	}
627 
628 	if (st0p)
629 		*st0p = st0;
630 
631 	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV) {
632 		/*
633 		 * There doesn't seem to have been an interrupt.
634 		 */
635 		return FD_NOT_VALID;
636 	}
637 
638 	if (fd_in(fdc, &cyl) < 0) {
639 		return fdc_err(fdc, "can't get cyl num\n");
640 	}
641 
642 	if (cylp)
643 		*cylp = cyl;
644 
645 	return 0;
646 }
647 
648 
649 static int
650 fd_read_status(fdc_p fdc)
651 {
652 	int i, ret;
653 
654 	for (i = ret = 0; i < 7; i++) {
655 		/*
656 		 * XXX types are poorly chosen.  Only bytes can be read
657 		 * from the hardware, but fdc->status[] wants u_ints and
658 		 * fd_in() gives ints.
659 		 */
660 		int status;
661 
662 		ret = fd_in(fdc, &status);
663 		fdc->status[i] = status;
664 		if (ret != 0)
665 			break;
666 	}
667 
668 	if (ret == 0)
669 		fdc->flags |= FDC_STAT_VALID;
670 	else
671 		fdc->flags &= ~FDC_STAT_VALID;
672 
673 	return ret;
674 }
675 
676 static int
677 fdc_alloc_resources(struct fdc_data *fdc)
678 {
679 	device_t dev;
680 	int ispnp, ispcmcia, nports;
681 
682 	dev = fdc->fdc_dev;
683 	ispnp = (fdc->flags & FDC_ISPNP) != 0;
684 	ispcmcia = (fdc->flags & FDC_ISPCMCIA) != 0;
685 	fdc->rid_ioport = fdc->rid_irq = fdc->rid_drq = 0;
686 	fdc->res_ioport = fdc->res_irq = fdc->res_drq = 0;
687 
688 	/*
689 	 * On standard ISA, we don't just use an 8 port range
690 	 * (e.g. 0x3f0-0x3f7) since that covers an IDE control
691 	 * register at 0x3f6.
692 	 *
693 	 * Isn't PC hardware wonderful.
694 	 *
695 	 * The Y-E Data PCMCIA FDC doesn't have this problem, it
696 	 * uses the register with offset 6 for pseudo-DMA, and the
697 	 * one with offset 7 as control register.
698 	 */
699 	nports = ispcmcia ? 8 : (ispnp ? 1 : 6);
700 	fdc->res_ioport = bus_alloc_resource(dev, SYS_RES_IOPORT,
701 					     &fdc->rid_ioport, 0ul, ~0ul,
702 					     nports, RF_ACTIVE);
703 	if (fdc->res_ioport == 0) {
704 		device_printf(dev, "cannot reserve I/O port range (%d ports)\n",
705 			      nports);
706 		return ENXIO;
707 	}
708 	fdc->portt = rman_get_bustag(fdc->res_ioport);
709 	fdc->porth = rman_get_bushandle(fdc->res_ioport);
710 
711 	if (!ispcmcia) {
712 		/*
713 		 * Some BIOSen report the device at 0x3f2-0x3f5,0x3f7
714 		 * and some at 0x3f0-0x3f5,0x3f7. We detect the former
715 		 * by checking the size and adjust the port address
716 		 * accordingly.
717 		 */
718 		if (bus_get_resource_count(dev, SYS_RES_IOPORT, 0) == 4)
719 			fdc->port_off = -2;
720 
721 		/*
722 		 * Register the control port range as rid 1 if it
723 		 * isn't there already. Most PnP BIOSen will have
724 		 * already done this but non-PnP configurations don't.
725 		 *
726 		 * And some (!!) report 0x3f2-0x3f5 and completely
727 		 * leave out the control register!  It seems that some
728 		 * non-antique controller chips have a different
729 		 * method of programming the transfer speed which
730 		 * doesn't require the control register, but it's
731 		 * mighty bogus as the chip still responds to the
732 		 * address for the control register.
733 		 */
734 		if (bus_get_resource_count(dev, SYS_RES_IOPORT, 1) == 0) {
735 			u_long ctlstart;
736 
737 			/* Find the control port, usually 0x3f7 */
738 			ctlstart = rman_get_start(fdc->res_ioport) +
739 				fdc->port_off + 7;
740 
741 			bus_set_resource(dev, SYS_RES_IOPORT, 1, ctlstart, 1);
742 		}
743 
744 		/*
745 		 * Now (finally!) allocate the control port.
746 		 */
747 		fdc->rid_ctl = 1;
748 		fdc->res_ctl = bus_alloc_resource(dev, SYS_RES_IOPORT,
749 						  &fdc->rid_ctl,
750 						  0ul, ~0ul, 1, RF_ACTIVE);
751 		if (fdc->res_ctl == 0) {
752 			device_printf(dev,
753 		"cannot reserve control I/O port range (control port)\n");
754 			return ENXIO;
755 		}
756 		fdc->ctlt = rman_get_bustag(fdc->res_ctl);
757 		fdc->ctlh = rman_get_bushandle(fdc->res_ctl);
758 	}
759 
760 	fdc->res_irq = bus_alloc_resource(dev, SYS_RES_IRQ,
761 					  &fdc->rid_irq, 0ul, ~0ul, 1,
762 					  RF_ACTIVE);
763 	if (fdc->res_irq == 0) {
764 		device_printf(dev, "cannot reserve interrupt line\n");
765 		return ENXIO;
766 	}
767 
768 	if ((fdc->flags & FDC_NODMA) == 0) {
769 		fdc->res_drq = bus_alloc_resource(dev, SYS_RES_DRQ,
770 						  &fdc->rid_drq, 0ul, ~0ul, 1,
771 						  RF_ACTIVE);
772 		if (fdc->res_drq == 0) {
773 			device_printf(dev, "cannot reserve DMA request line\n");
774 			return ENXIO;
775 		}
776 		fdc->dmachan = fdc->res_drq->r_start;
777 	}
778 
779 	return 0;
780 }
781 
782 static void
783 fdc_release_resources(struct fdc_data *fdc)
784 {
785 	device_t dev;
786 
787 	dev = fdc->fdc_dev;
788 	if (fdc->res_irq != 0) {
789 		bus_deactivate_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
790 					fdc->res_irq);
791 		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
792 				     fdc->res_irq);
793 	}
794 	if (fdc->res_ctl != 0) {
795 		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ctl,
796 					fdc->res_ctl);
797 		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ctl,
798 				     fdc->res_ctl);
799 	}
800 	if (fdc->res_ioport != 0) {
801 		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
802 					fdc->res_ioport);
803 		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
804 				     fdc->res_ioport);
805 	}
806 	if (fdc->res_drq != 0) {
807 		bus_deactivate_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
808 					fdc->res_drq);
809 		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
810 				     fdc->res_drq);
811 	}
812 }
813 
814 /*
815  * Configuration/initialization stuff, per controller.
816  */
817 
818 static struct isa_pnp_id fdc_ids[] = {
819 	{0x0007d041, "PC standard floppy disk controller"}, /* PNP0700 */
820 	{0x0107d041, "Standard floppy controller supporting MS Device Bay Spec"}, /* PNP0701 */
821 	{0}
822 };
823 
824 static int
825 fdc_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
826 {
827 	struct fdc_ivars *ivars = device_get_ivars(child);
828 
829 	switch (which) {
830 	case FDC_IVAR_FDUNIT:
831 		*result = ivars->fdunit;
832 		break;
833 	default:
834 		return ENOENT;
835 	}
836 	return 0;
837 }
838 
839 static int
840 fdc_probe(device_t dev)
841 {
842 	int	error, ic_type;
843 	struct	fdc_data *fdc;
844 
845 	fdc = device_get_softc(dev);
846 	bzero(fdc, sizeof *fdc);
847 	fdc->fdc_dev = dev;
848 	fdc->fdctl_wr = fdctl_wr_isa;
849 
850 	/* Check pnp ids */
851 	error = ISA_PNP_PROBE(device_get_parent(dev), dev, fdc_ids);
852 	if (error == ENXIO)
853 		return ENXIO;
854 	if (error == 0)
855 		fdc->flags |= FDC_ISPNP;
856 
857 	/* Attempt to allocate our resources for the duration of the probe */
858 	error = fdc_alloc_resources(fdc);
859 	if (error)
860 		goto out;
861 
862 	/* First - lets reset the floppy controller */
863 	fdout_wr(fdc, 0);
864 	DELAY(100);
865 	fdout_wr(fdc, FDO_FRST);
866 
867 	/* see if it can handle a command */
868 	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
869 		   NE7_SPEC_2(2, 0), 0)) {
870 		error = ENXIO;
871 		goto out;
872 	}
873 
874 	if (fd_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type) == 0) {
875 		ic_type = (u_char)ic_type;
876 		switch (ic_type) {
877 		case 0x80:
878 			device_set_desc(dev, "NEC 765 or clone");
879 			fdc->fdct = FDC_NE765;
880 			break;
881 		case 0x81:	/* not mentioned in any hardware doc */
882 		case 0x90:
883 			device_set_desc(dev,
884 		"enhanced floppy controller (i82077, NE72065 or clone)");
885 			fdc->fdct = FDC_ENHANCED;
886 			break;
887 		default:
888 			device_set_desc(dev, "generic floppy controller");
889 			fdc->fdct = FDC_UNKNOWN;
890 			break;
891 		}
892 	}
893 
894 out:
895 	fdc_release_resources(fdc);
896 	return (error);
897 }
898 
899 #if NCARD > 0
900 
901 static int
902 fdc_pccard_probe(device_t dev)
903 {
904 	int	error;
905 	struct	fdc_data *fdc;
906 
907 	fdc = device_get_softc(dev);
908 	bzero(fdc, sizeof *fdc);
909 	fdc->fdc_dev = dev;
910 	fdc->fdctl_wr = fdctl_wr_pcmcia;
911 
912 	fdc->flags |= FDC_ISPCMCIA | FDC_NODMA;
913 
914 	/* Attempt to allocate our resources for the duration of the probe */
915 	error = fdc_alloc_resources(fdc);
916 	if (error)
917 		goto out;
918 
919 	/* First - lets reset the floppy controller */
920 	fdout_wr(fdc, 0);
921 	DELAY(100);
922 	fdout_wr(fdc, FDO_FRST);
923 
924 	/* see if it can handle a command */
925 	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
926 		   NE7_SPEC_2(2, 0), 0)) {
927 		error = ENXIO;
928 		goto out;
929 	}
930 
931 	device_set_desc(dev, "Y-E Data PCMCIA floppy");
932 	fdc->fdct = FDC_NE765;
933 
934 out:
935 	fdc_release_resources(fdc);
936 	return (error);
937 }
938 
939 #endif /* NCARD > 0 */
940 
941 static int
942 fdc_detach(device_t dev)
943 {
944 	struct	fdc_data *fdc;
945 	int	error;
946 
947 	fdc = device_get_softc(dev);
948 
949 	/* have our children detached first */
950 	if ((error = bus_generic_detach(dev)))
951 		return (error);
952 
953 	/* reset controller, turn motor off */
954 	fdout_wr(fdc, 0);
955 
956 	if ((fdc->flags & FDC_NODMA) == 0)
957 		isa_dma_release(fdc->dmachan);
958 
959 	if ((fdc->flags & FDC_ATTACHED) == 0) {
960 		device_printf(dev, "already unloaded\n");
961 		return (0);
962 	}
963 	fdc->flags &= ~FDC_ATTACHED;
964 
965 	BUS_TEARDOWN_INTR(device_get_parent(dev), dev, fdc->res_irq,
966 			  fdc->fdc_intr);
967 	fdc_release_resources(fdc);
968 	device_printf(dev, "unload\n");
969 	return (0);
970 }
971 
972 /*
973  * Add a child device to the fdc controller.  It will then be probed etc.
974  */
975 static void
976 fdc_add_child(device_t dev, const char *name, int unit)
977 {
978 	int	disabled, flags;
979 	struct fdc_ivars *ivar;
980 	device_t child;
981 
982 	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT | M_ZERO);
983 	if (ivar == NULL)
984 		return;
985 	if (resource_int_value(name, unit, "drive", &ivar->fdunit) != 0)
986 		ivar->fdunit = 0;
987 	child = device_add_child(dev, name, unit);
988 	if (child == NULL)
989 		return;
990 	device_set_ivars(child, ivar);
991 	if (resource_int_value(name, unit, "flags", &flags) == 0)
992 		 device_set_flags(child, flags);
993 	if (resource_int_value(name, unit, "disabled", &disabled) == 0
994 	    && disabled != 0)
995 		device_disable(child);
996 }
997 
998 static int
999 fdc_attach(device_t dev)
1000 {
1001 	struct	fdc_data *fdc;
1002 	const char *name, *dname;
1003 	int	i, error, dunit;
1004 
1005 	fdc = device_get_softc(dev);
1006 	error = fdc_alloc_resources(fdc);
1007 	if (error) {
1008 		device_printf(dev, "cannot re-acquire resources\n");
1009 		return error;
1010 	}
1011 	error = BUS_SETUP_INTR(device_get_parent(dev), dev, fdc->res_irq,
1012 			       INTR_TYPE_BIO | INTR_ENTROPY, fdc_intr, fdc,
1013 			       &fdc->fdc_intr);
1014 	if (error) {
1015 		device_printf(dev, "cannot setup interrupt\n");
1016 		return error;
1017 	}
1018 	fdc->fdcu = device_get_unit(dev);
1019 	fdc->flags |= FDC_ATTACHED | FDC_NEEDS_RESET;
1020 
1021 	if ((fdc->flags & FDC_NODMA) == 0) {
1022 		/*
1023 		 * Acquire the DMA channel forever, the driver will do
1024 		 * the rest
1025 		 * XXX should integrate with rman
1026 		 */
1027 		isa_dma_acquire(fdc->dmachan);
1028 		isa_dmainit(fdc->dmachan, MAX_SEC_SIZE);
1029 	}
1030 	fdc->state = DEVIDLE;
1031 
1032 	/* reset controller, turn motor off, clear fdout mirror reg */
1033 	fdout_wr(fdc, fdc->fdout = 0);
1034 	bioq_init(&fdc->head);
1035 
1036 	/*
1037 	 * Probe and attach any children.  We should probably detect
1038 	 * devices from the BIOS unless overridden.
1039 	 */
1040 	name = device_get_nameunit(dev);
1041 	i = 0;
1042 	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0)
1043 		fdc_add_child(dev, dname, dunit);
1044 
1045 	if ((error = bus_generic_attach(dev)) != 0)
1046 		return (error);
1047 
1048 	return (0);
1049 }
1050 
1051 static int
1052 fdc_print_child(device_t me, device_t child)
1053 {
1054 	int retval = 0, flags;
1055 
1056 	retval += bus_print_child_header(me, child);
1057 	retval += printf(" on %s drive %d", device_get_nameunit(me),
1058 	       fdc_get_fdunit(child));
1059 	if ((flags = device_get_flags(me)) != 0)
1060 		retval += printf(" flags %#x", flags);
1061 	retval += printf("\n");
1062 
1063 	return (retval);
1064 }
1065 
1066 static device_method_t fdc_methods[] = {
1067 	/* Device interface */
1068 	DEVMETHOD(device_probe,		fdc_probe),
1069 	DEVMETHOD(device_attach,	fdc_attach),
1070 	DEVMETHOD(device_detach,	fdc_detach),
1071 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1072 	DEVMETHOD(device_suspend,	bus_generic_suspend),
1073 	DEVMETHOD(device_resume,	bus_generic_resume),
1074 
1075 	/* Bus interface */
1076 	DEVMETHOD(bus_print_child,	fdc_print_child),
1077 	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
1078 	/* Our children never use any other bus interface methods. */
1079 
1080 	{ 0, 0 }
1081 };
1082 
1083 static driver_t fdc_driver = {
1084 	"fdc",
1085 	fdc_methods,
1086 	sizeof(struct fdc_data)
1087 };
1088 
1089 DRIVER_MODULE(fdc, isa, fdc_driver, fdc_devclass, 0, 0);
1090 DRIVER_MODULE(fdc, acpi, fdc_driver, fdc_devclass, 0, 0);
1091 
1092 #if NCARD > 0
1093 
1094 static device_method_t fdc_pccard_methods[] = {
1095 	/* Device interface */
1096 	DEVMETHOD(device_probe,		fdc_pccard_probe),
1097 	DEVMETHOD(device_attach,	fdc_attach),
1098 	DEVMETHOD(device_detach,	fdc_detach),
1099 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1100 	DEVMETHOD(device_suspend,	bus_generic_suspend),
1101 	DEVMETHOD(device_resume,	bus_generic_resume),
1102 
1103 	/* Bus interface */
1104 	DEVMETHOD(bus_print_child,	fdc_print_child),
1105 	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
1106 	/* Our children never use any other bus interface methods. */
1107 
1108 	{ 0, 0 }
1109 };
1110 
1111 static driver_t fdc_pccard_driver = {
1112 	"fdc",
1113 	fdc_pccard_methods,
1114 	sizeof(struct fdc_data)
1115 };
1116 
1117 DRIVER_MODULE(fdc, pccard, fdc_pccard_driver, fdc_devclass, 0, 0);
1118 
1119 #endif /* NCARD > 0 */
1120 
1121 /*
1122  * Create a clone device upon request by devfs.
1123  */
1124 static void
1125 fd_clone(void *arg, char *name, int namelen, dev_t *dev)
1126 {
1127 	struct	fd_data *fd;
1128 	int i, u;
1129 	char *n;
1130 	size_t l;
1131 
1132 	fd = (struct fd_data *)arg;
1133 	if (*dev != NODEV)
1134 		return;
1135 	if (dev_stdclone(name, &n, "fd", &u) != 2)
1136 		return;
1137 	l = strlen(n);
1138 	if (l == 1 && *n >= 'a' && *n <= 'h') {
1139 		/*
1140 		 * Trailing letters a through h denote
1141 		 * pseudo-partitions.  We don't support true
1142 		 * (UFS-style) partitions, so we just implement them
1143 		 * as symlinks if someone asks us nicely.
1144 		 */
1145 		*dev = make_dev_alias(fd->masterdev, name);
1146 		return;
1147 	}
1148 	if (l >= 2 && l <= 5 && *n == '.') {
1149 		/*
1150 		 * Trailing numbers, preceded by a dot, denote
1151 		 * subdevices for different densities.  Historically,
1152 		 * they have been named by density (like fd0.1440),
1153 		 * but we allow arbitrary numbers between 1 and 4
1154 		 * digits, so fd0.1 through fd0.15 are possible as
1155 		 * well.
1156 		 */
1157 		for (i = 1; i < l; i++)
1158 			if (n[i] < '0' || n[i] > '9')
1159 				return;
1160 		for (i = 0; i < NUMDENS - 1; i++)
1161 			if (fd->clonedevs[i] == NODEV) {
1162 				*dev = make_dev(&fd_cdevsw,
1163 						FDNUMTOUNIT(u) + i + 1,
1164 						UID_ROOT, GID_OPERATOR, 0640,
1165 						name);
1166 				fd->clonedevs[i] = *dev;
1167 				return;
1168 			}
1169 	}
1170 }
1171 
1172 /*
1173  * Configuration/initialization, per drive.
1174  */
1175 static int
1176 fd_probe(device_t dev)
1177 {
1178 	int	i;
1179 	u_int	st0, st3;
1180 	struct	fd_data *fd;
1181 	struct	fdc_data *fdc;
1182 	fdsu_t	fdsu;
1183 	int	flags;
1184 
1185 	fdsu = *(int *)device_get_ivars(dev); /* xxx cheat a bit... */
1186 	fd = device_get_softc(dev);
1187 	fdc = device_get_softc(device_get_parent(dev));
1188 	flags = device_get_flags(dev);
1189 
1190 	bzero(fd, sizeof *fd);
1191 	fd->dev = dev;
1192 	fd->fdc = fdc;
1193 	fd->fdsu = fdsu;
1194 	fd->fdu = device_get_unit(dev);
1195 	fd->flags = FD_UA;	/* make sure fdautoselect() will be called */
1196 
1197 	fd->type = FD_DTYPE(flags);
1198 /*
1199  * XXX I think using __i386__ is wrong here since we actually want to probe
1200  * for the machine type, not the CPU type (so non-PC arch's like the PC98 will
1201  * fail the probe).  However, for whatever reason, testing for _MACHINE_ARCH
1202  * == i386 breaks the test on FreeBSD/Alpha.
1203  */
1204 #ifdef __i386__
1205 	if (fd->type == FDT_NONE && (fd->fdu == 0 || fd->fdu == 1)) {
1206 		/* Look up what the BIOS thinks we have. */
1207 		if (fd->fdu == 0) {
1208 			if ((fdc->flags & FDC_ISPCMCIA))
1209 				/*
1210 				 * Somewhat special.  No need to force the
1211 				 * user to set device flags, since the Y-E
1212 				 * Data PCMCIA floppy is always a 1.44 MB
1213 				 * device.
1214 				 */
1215 				fd->type = FDT_144M;
1216 			else
1217 				fd->type = (rtcin(RTC_FDISKETTE) & 0xf0) >> 4;
1218 		} else {
1219 			fd->type = rtcin(RTC_FDISKETTE) & 0x0f;
1220 		}
1221 		if (fd->type == FDT_288M_1)
1222 			fd->type = FDT_288M;
1223 	}
1224 #endif /* __i386__ */
1225 	/* is there a unit? */
1226 	if (fd->type == FDT_NONE)
1227 		return (ENXIO);
1228 
1229 	/* select it */
1230 	set_motor(fdc, fdsu, TURNON);
1231 	fdc_reset(fdc);		/* XXX reset, then unreset, etc. */
1232 	DELAY(1000000);	/* 1 sec */
1233 
1234 	/* XXX This doesn't work before the first set_motor() */
1235 	if ((fdc->flags & FDC_HAS_FIFO) == 0  &&
1236 	    fdc->fdct == FDC_ENHANCED &&
1237 	    (device_get_flags(fdc->fdc_dev) & FDC_NO_FIFO) == 0 &&
1238 	    enable_fifo(fdc) == 0) {
1239 		device_printf(device_get_parent(dev),
1240 		    "FIFO enabled, %d bytes threshold\n", fifo_threshold);
1241 	}
1242 
1243 	if ((flags & FD_NO_PROBE) == 0) {
1244 		/* If we're at track 0 first seek inwards. */
1245 		if ((fd_sense_drive_status(fdc, &st3) == 0) &&
1246 		    (st3 & NE7_ST3_T0)) {
1247 			/* Seek some steps... */
1248 			if (fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1249 				/* ...wait a moment... */
1250 				DELAY(300000);
1251 				/* make ctrlr happy: */
1252 				fd_sense_int(fdc, 0, 0);
1253 			}
1254 		}
1255 
1256 		for (i = 0; i < 2; i++) {
1257 			/*
1258 			 * we must recalibrate twice, just in case the
1259 			 * heads have been beyond cylinder 76, since
1260 			 * most FDCs still barf when attempting to
1261 			 * recalibrate more than 77 steps
1262 			 */
1263 			/* go back to 0: */
1264 			if (fd_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1265 				/* a second being enough for full stroke seek*/
1266 				DELAY(i == 0 ? 1000000 : 300000);
1267 
1268 				/* anything responding? */
1269 				if (fd_sense_int(fdc, &st0, 0) == 0 &&
1270 				    (st0 & NE7_ST0_EC) == 0)
1271 					break; /* already probed succesfully */
1272 			}
1273 		}
1274 	}
1275 
1276 	set_motor(fdc, fdsu, TURNOFF);
1277 
1278 	if ((flags & FD_NO_PROBE) == 0 &&
1279 	    (st0 & NE7_ST0_EC) != 0) /* no track 0 -> no drive present */
1280 		return (ENXIO);
1281 
1282 	switch (fd->type) {
1283 	case FDT_12M:
1284 		device_set_desc(dev, "1200-KB 5.25\" drive");
1285 		fd->type = FDT_12M;
1286 		break;
1287 	case FDT_144M:
1288 		device_set_desc(dev, "1440-KB 3.5\" drive");
1289 		fd->type = FDT_144M;
1290 		break;
1291 	case FDT_288M:
1292 		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1293 		fd->type = FDT_288M;
1294 		break;
1295 	case FDT_360K:
1296 		device_set_desc(dev, "360-KB 5.25\" drive");
1297 		fd->type = FDT_360K;
1298 		break;
1299 	case FDT_720K:
1300 		device_set_desc(dev, "720-KB 3.5\" drive");
1301 		fd->type = FDT_720K;
1302 		break;
1303 	default:
1304 		return (ENXIO);
1305 	}
1306 	fd->track = FD_NO_TRACK;
1307 	fd->fdc = fdc;
1308 	fd->fdsu = fdsu;
1309 	fd->options = 0;
1310 	callout_handle_init(&fd->toffhandle);
1311 	callout_handle_init(&fd->tohandle);
1312 
1313 	/* initialize densities for subdevices */
1314 	for (i = 0; i < NUMDENS; i++)
1315 		memcpy(fd->fts + i, fd_native_types + fd->type,
1316 		       sizeof(struct fd_type));
1317 	return (0);
1318 }
1319 
1320 static int
1321 fd_attach(device_t dev)
1322 {
1323 	struct	fd_data *fd;
1324 	static	int cdevsw_add_done;
1325 	int i;
1326 
1327 	if (!cdevsw_add_done) {
1328 		cdevsw_add(&fd_cdevsw);	/* XXX */
1329 		cdevsw_add_done = 1;
1330 	}
1331 	fd = device_get_softc(dev);
1332 	fd->clonetag = EVENTHANDLER_REGISTER(dev_clone, fd_clone, fd, 1000);
1333 	fd->masterdev = make_dev(&fd_cdevsw, fd->fdu << 6,
1334 				 UID_ROOT, GID_OPERATOR, 0640, "fd%d", fd->fdu);
1335 	for (i = 0; i < NUMDENS - 1; i++)
1336 		fd->clonedevs[i] = NODEV;
1337 	devstat_add_entry(&fd->device_stats, device_get_name(dev),
1338 			  device_get_unit(dev), 0, DEVSTAT_NO_ORDERED_TAGS,
1339 			  DEVSTAT_TYPE_FLOPPY | DEVSTAT_TYPE_IF_OTHER,
1340 			  DEVSTAT_PRIORITY_FD);
1341 	return (0);
1342 }
1343 
1344 static int
1345 fd_detach(device_t dev)
1346 {
1347 	struct	fd_data *fd;
1348 	int i;
1349 
1350 	fd = device_get_softc(dev);
1351 	untimeout(fd_turnoff, fd, fd->toffhandle);
1352 	devstat_remove_entry(&fd->device_stats);
1353 	destroy_dev(fd->masterdev);
1354 	for (i = 0; i < NUMDENS - 1; i++)
1355 		if (fd->clonedevs[i] != NODEV)
1356 			destroy_dev(fd->clonedevs[i]);
1357 	cdevsw_remove(&fd_cdevsw);
1358 	EVENTHANDLER_DEREGISTER(dev_clone, fd->clonetag);
1359 
1360 	return (0);
1361 }
1362 
1363 static device_method_t fd_methods[] = {
1364 	/* Device interface */
1365 	DEVMETHOD(device_probe,		fd_probe),
1366 	DEVMETHOD(device_attach,	fd_attach),
1367 	DEVMETHOD(device_detach,	fd_detach),
1368 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1369 	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
1370 	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
1371 
1372 	{ 0, 0 }
1373 };
1374 
1375 static driver_t fd_driver = {
1376 	"fd",
1377 	fd_methods,
1378 	sizeof(struct fd_data)
1379 };
1380 
1381 DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, 0, 0);
1382 
1383 /*
1384  * More auxiliary functions.
1385  */
1386 /*
1387  * Motor control stuff.
1388  * Remember to not deselect the drive we're working on.
1389  */
1390 static void
1391 set_motor(struct fdc_data *fdc, int fdsu, int turnon)
1392 {
1393 	int fdout;
1394 
1395 	fdout = fdc->fdout;
1396 	if (turnon) {
1397 		fdout &= ~FDO_FDSEL;
1398 		fdout |= (FDO_MOEN0 << fdsu) | FDO_FDMAEN | FDO_FRST | fdsu;
1399 	} else
1400 		fdout &= ~(FDO_MOEN0 << fdsu);
1401 	fdc->fdout = fdout;
1402 	fdout_wr(fdc, fdout);
1403 	TRACE1("[0x%x->FDOUT]", fdout);
1404 }
1405 
1406 static void
1407 fd_turnoff(void *xfd)
1408 {
1409 	int	s;
1410 	fd_p fd = xfd;
1411 
1412 	TRACE1("[fd%d: turnoff]", fd->fdu);
1413 
1414 	s = splbio();
1415 	/*
1416 	 * Don't turn off the motor yet if the drive is active.
1417 	 *
1418 	 * If we got here, this could only mean we missed an interrupt.
1419 	 * This can e. g. happen on the Y-E Date PCMCIA floppy controller
1420 	 * after a controller reset.  Just schedule a pseudo-interrupt
1421 	 * so the state machine gets re-entered.
1422 	 */
1423 	if (fd->fdc->state != DEVIDLE && fd->fdc->fdu == fd->fdu) {
1424 		fdc_intr(fd->fdc);
1425 		splx(s);
1426 		return;
1427 	}
1428 
1429 	fd->flags &= ~FD_MOTOR;
1430 	set_motor(fd->fdc, fd->fdsu, TURNOFF);
1431 	splx(s);
1432 }
1433 
1434 static void
1435 fd_motor_on(void *xfd)
1436 {
1437 	int	s;
1438 	fd_p fd = xfd;
1439 
1440 	s = splbio();
1441 	fd->flags &= ~FD_MOTOR_WAIT;
1442 	if((fd->fdc->fd == fd) && (fd->fdc->state == MOTORWAIT))
1443 	{
1444 		fdc_intr(fd->fdc);
1445 	}
1446 	splx(s);
1447 }
1448 
1449 static void
1450 fd_turnon(fd_p fd)
1451 {
1452 	if(!(fd->flags & FD_MOTOR))
1453 	{
1454 		fd->flags |= (FD_MOTOR + FD_MOTOR_WAIT);
1455 		set_motor(fd->fdc, fd->fdsu, TURNON);
1456 		timeout(fd_motor_on, fd, hz); /* in 1 sec its ok */
1457 	}
1458 }
1459 
1460 static void
1461 fdc_reset(fdc_p fdc)
1462 {
1463 	/* Try a reset, keep motor on */
1464 	fdout_wr(fdc, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1465 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1466 	DELAY(100);
1467 	/* enable FDC, but defer interrupts a moment */
1468 	fdout_wr(fdc, fdc->fdout & ~FDO_FDMAEN);
1469 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~FDO_FDMAEN);
1470 	DELAY(100);
1471 	fdout_wr(fdc, fdc->fdout);
1472 	TRACE1("[0x%x->FDOUT]", fdc->fdout);
1473 
1474 	/* XXX after a reset, silently believe the FDC will accept commands */
1475 	(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1476 		     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1477 		     0);
1478 	if (fdc->flags & FDC_HAS_FIFO)
1479 		(void) enable_fifo(fdc);
1480 }
1481 
1482 /*
1483  * FDC IO functions, take care of the main status register, timeout
1484  * in case the desired status bits are never set.
1485  *
1486  * These PIO loops initially start out with short delays between
1487  * each iteration in the expectation that the required condition
1488  * is usually met quickly, so it can be handled immediately.  After
1489  * about 1 ms, stepping is increased to achieve a better timing
1490  * accuracy in the calls to DELAY().
1491  */
1492 static int
1493 fd_in(struct fdc_data *fdc, int *ptr)
1494 {
1495 	int i, j, step;
1496 
1497 	for (j = 0, step = 1;
1498 	    (i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM)) != (NE7_DIO|NE7_RQM) &&
1499 	    j < FDSTS_TIMEOUT;
1500 	    j += step) {
1501 		if (i == NE7_RQM)
1502 			return (fdc_err(fdc, "ready for output in input\n"));
1503 		if (j == 1000)
1504 			step = 1000;
1505 		DELAY(step);
1506 	}
1507 	if (j >= FDSTS_TIMEOUT)
1508 		return (fdc_err(fdc, bootverbose? "input ready timeout\n": 0));
1509 #ifdef	FDC_DEBUG
1510 	i = fddata_rd(fdc);
1511 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
1512 	*ptr = i;
1513 	return (0);
1514 #else	/* !FDC_DEBUG */
1515 	i = fddata_rd(fdc);
1516 	if (ptr)
1517 		*ptr = i;
1518 	return (0);
1519 #endif	/* FDC_DEBUG */
1520 }
1521 
1522 int
1523 out_fdc(struct fdc_data *fdc, int x)
1524 {
1525 	int i, j, step;
1526 
1527 	for (j = 0, step = 1;
1528 	    (i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM)) != NE7_RQM &&
1529 	    j < FDSTS_TIMEOUT;
1530 	    j += step) {
1531 		if (i == (NE7_DIO|NE7_RQM))
1532 			return (fdc_err(fdc, "ready for input in output\n"));
1533 		if (j == 1000)
1534 			step = 1000;
1535 		DELAY(step);
1536 	}
1537 	if (j >= FDSTS_TIMEOUT)
1538 		return (fdc_err(fdc, bootverbose? "output ready timeout\n": 0));
1539 
1540 	/* Send the command and return */
1541 	fddata_wr(fdc, x);
1542 	TRACE1("[0x%x->FDDATA]", x);
1543 	return (0);
1544 }
1545 
1546 /*
1547  * Block device driver interface functions (interspersed with even more
1548  * auxiliary functions).
1549  */
1550 int
1551 Fdopen(dev_t dev, int flags, int mode, struct thread *td)
1552 {
1553  	fdu_t fdu = FDUNIT(minor(dev));
1554 	int type = FDTYPE(minor(dev));
1555 	fd_p	fd;
1556 	fdc_p	fdc;
1557  	int rv, unitattn, dflags;
1558 
1559 	if ((fd = devclass_get_softc(fd_devclass, fdu)) == 0)
1560 		return (ENXIO);
1561 	fdc = fd->fdc;
1562 	if ((fdc == NULL) || (fd->type == FDT_NONE))
1563 		return (ENXIO);
1564 	if (type > NUMDENS)
1565 		return (ENXIO);
1566 	dflags = device_get_flags(fd->dev);
1567 	/*
1568 	 * This is a bit bogus.  It's still possible that e. g. a
1569 	 * descriptor gets inherited to a child, but then it's at
1570 	 * least for the same subdevice.  By checking FD_OPEN here, we
1571 	 * can ensure that a device isn't attempted to be opened with
1572 	 * different densities at the same time where the second open
1573 	 * could clobber the settings from the first one.
1574 	 */
1575 	if (fd->flags & FD_OPEN)
1576 		return (EBUSY);
1577 
1578 	if (type == 0) {
1579 		if (flags & FNONBLOCK) {
1580 			/*
1581 			 * Unfortunately, physio(9) discards its ioflag
1582 			 * argument, thus preventing us from seeing the
1583 			 * IO_NDELAY bit.  So we need to keep track
1584 			 * ourselves.
1585 			 */
1586 			fd->flags |= FD_NONBLOCK;
1587 			fd->ft = 0;
1588 		} else {
1589 			/*
1590 			 * Figure out a unit attention condition.
1591 			 *
1592 			 * If UA has been forced, proceed.
1593 			 *
1594 			 * If motor is off, turn it on for a moment
1595 			 * and select our drive, in order to read the
1596 			 * UA hardware signal.
1597 			 *
1598 			 * If motor is on, and our drive is currently
1599 			 * selected, just read the hardware bit.
1600 			 *
1601 			 * If motor is on, but active for another
1602 			 * drive on that controller, we are lost.  We
1603 			 * cannot risk to deselect the other drive, so
1604 			 * we just assume a forced UA condition to be
1605 			 * on the safe side.
1606 			 */
1607 			unitattn = 0;
1608 			if ((dflags & FD_NO_CHLINE) != 0 ||
1609 			    (fd->flags & FD_UA) != 0) {
1610 				unitattn = 1;
1611 				fd->flags &= ~FD_UA;
1612 			} else if (fdc->fdout & (FDO_MOEN0 | FDO_MOEN1 |
1613 						 FDO_MOEN2 | FDO_MOEN3)) {
1614 				if ((fdc->fdout & FDO_FDSEL) == fd->fdsu)
1615 					unitattn = fdin_rd(fdc) & FDI_DCHG;
1616 				else
1617 					unitattn = 1;
1618 			} else {
1619 				set_motor(fdc, fd->fdsu, TURNON);
1620 				unitattn = fdin_rd(fdc) & FDI_DCHG;
1621 				set_motor(fdc, fd->fdsu, TURNOFF);
1622 			}
1623 			if (unitattn && (rv = fdautoselect(dev)) != 0)
1624 				return (rv);
1625 		}
1626 	} else {
1627 		fd->ft = fd->fts + type;
1628 	}
1629 	fd->flags |= FD_OPEN;
1630 	/*
1631 	 * Clearing the DMA overrun counter at open time is a bit messy.
1632 	 * Since we're only managing one counter per controller, opening
1633 	 * the second drive could mess it up.  Anyway, if the DMA overrun
1634 	 * condition is really persistent, it will eventually time out
1635 	 * still.  OTOH, clearing it here will ensure we'll at least start
1636 	 * trying again after a previous (maybe even long ago) failure.
1637 	 * Also, this is merely a stop-gap measure only that should not
1638 	 * happen during normal operation, so we can tolerate it to be a
1639 	 * bit sloppy about this.
1640 	 */
1641 	fdc->dma_overruns = 0;
1642 
1643 	return 0;
1644 }
1645 
1646 int
1647 fdclose(dev_t dev, int flags, int mode, struct thread *td)
1648 {
1649  	fdu_t fdu = FDUNIT(minor(dev));
1650 	struct fd_data *fd;
1651 
1652 	fd = devclass_get_softc(fd_devclass, fdu);
1653 	fd->flags &= ~(FD_OPEN | FD_NONBLOCK);
1654 	fd->options &= ~(FDOPT_NORETRY | FDOPT_NOERRLOG | FDOPT_NOERROR);
1655 
1656 	return (0);
1657 }
1658 
1659 void
1660 fdstrategy(struct bio *bp)
1661 {
1662 	long blknum, nblocks;
1663  	int	s;
1664  	fdu_t	fdu;
1665  	fdc_p	fdc;
1666  	fd_p	fd;
1667 	size_t	fdblk;
1668 
1669  	fdu = FDUNIT(minor(bp->bio_dev));
1670 	fd = devclass_get_softc(fd_devclass, fdu);
1671 	if (fd == 0)
1672 		panic("fdstrategy: buf for nonexistent device (%#lx, %#lx)",
1673 		      (u_long)major(bp->bio_dev), (u_long)minor(bp->bio_dev));
1674 	fdc = fd->fdc;
1675 	if (fd->type == FDT_NONE || fd->ft == 0) {
1676 		bp->bio_error = ENXIO;
1677 		bp->bio_flags |= BIO_ERROR;
1678 		goto bad;
1679 	}
1680 	fdblk = 128 << (fd->ft->secsize);
1681 	if (bp->bio_cmd != BIO_FORMAT && bp->bio_cmd != BIO_RDSECTID) {
1682 		if (fd->flags & FD_NONBLOCK) {
1683 			bp->bio_error = EAGAIN;
1684 			bp->bio_flags |= BIO_ERROR;
1685 			goto bad;
1686 		}
1687 		if (bp->bio_blkno < 0) {
1688 			printf(
1689 		"fd%d: fdstrat: bad request blkno = %lu, bcount = %ld\n",
1690 			       fdu, (u_long)bp->bio_blkno, bp->bio_bcount);
1691 			bp->bio_error = EINVAL;
1692 			bp->bio_flags |= BIO_ERROR;
1693 			goto bad;
1694 		}
1695 		if ((bp->bio_bcount % fdblk) != 0) {
1696 			bp->bio_error = EINVAL;
1697 			bp->bio_flags |= BIO_ERROR;
1698 			goto bad;
1699 		}
1700 	}
1701 
1702 	/*
1703 	 * Set up block calculations.
1704 	 */
1705 	if (bp->bio_blkno > 20000000) {
1706 		/*
1707 		 * Reject unreasonably high block number, prevent the
1708 		 * multiplication below from overflowing.
1709 		 */
1710 		bp->bio_error = EINVAL;
1711 		bp->bio_flags |= BIO_ERROR;
1712 		goto bad;
1713 	}
1714 	blknum = bp->bio_blkno * DEV_BSIZE / fdblk;
1715  	nblocks = fd->ft->size;
1716 	if (blknum + bp->bio_bcount / fdblk > nblocks) {
1717 		if (blknum >= nblocks) {
1718 			if (bp->bio_cmd == BIO_READ)
1719 				bp->bio_resid = bp->bio_bcount;
1720 			else {
1721 				bp->bio_error = ENOSPC;
1722 				bp->bio_flags |= BIO_ERROR;
1723 			}
1724 			goto bad;	/* not always bad, but EOF */
1725 		}
1726 		bp->bio_bcount = (nblocks - blknum) * fdblk;
1727 	}
1728  	bp->bio_pblkno = bp->bio_blkno;
1729 	s = splbio();
1730 	bioqdisksort(&fdc->head, bp);
1731 	untimeout(fd_turnoff, fd, fd->toffhandle); /* a good idea */
1732 	devstat_start_transaction(&fd->device_stats);
1733 	device_busy(fd->dev);
1734 	fdstart(fdc);
1735 	splx(s);
1736 	return;
1737 
1738 bad:
1739 	biodone(bp);
1740 }
1741 
1742 /*
1743  * fdstart
1744  *
1745  * We have just queued something.  If the controller is not busy
1746  * then simulate the case where it has just finished a command
1747  * So that it (the interrupt routine) looks on the queue for more
1748  * work to do and picks up what we just added.
1749  *
1750  * If the controller is already busy, we need do nothing, as it
1751  * will pick up our work when the present work completes.
1752  */
1753 static void
1754 fdstart(struct fdc_data *fdc)
1755 {
1756 	int s;
1757 
1758 	s = splbio();
1759 	if(fdc->state == DEVIDLE)
1760 	{
1761 		fdc_intr(fdc);
1762 	}
1763 	splx(s);
1764 }
1765 
1766 static void
1767 fd_iotimeout(void *xfdc)
1768 {
1769  	fdc_p fdc;
1770 	int s;
1771 
1772 	fdc = xfdc;
1773 	TRACE1("fd%d[fd_iotimeout()]", fdc->fdu);
1774 
1775 	/*
1776 	 * Due to IBM's brain-dead design, the FDC has a faked ready
1777 	 * signal, hardwired to ready == true. Thus, any command
1778 	 * issued if there's no diskette in the drive will _never_
1779 	 * complete, and must be aborted by resetting the FDC.
1780 	 * Many thanks, Big Blue!
1781 	 * The FDC must not be reset directly, since that would
1782 	 * interfere with the state machine.  Instead, pretend that
1783 	 * the command completed but was invalid.  The state machine
1784 	 * will reset the FDC and retry once.
1785 	 */
1786 	s = splbio();
1787 	fdc->status[0] = NE7_ST0_IC_IV;
1788 	fdc->flags &= ~FDC_STAT_VALID;
1789 	fdc->state = IOTIMEDOUT;
1790 	fdc_intr(fdc);
1791 	splx(s);
1792 }
1793 
1794 /* Just ensure it has the right spl. */
1795 static void
1796 fd_pseudointr(void *xfdc)
1797 {
1798 	int	s;
1799 
1800 	s = splbio();
1801 	fdc_intr(xfdc);
1802 	splx(s);
1803 }
1804 
1805 /*
1806  * fdc_intr
1807  *
1808  * Keep calling the state machine until it returns a 0.
1809  * Always called at splbio.
1810  */
1811 static void
1812 fdc_intr(void *xfdc)
1813 {
1814 	fdc_p fdc = xfdc;
1815 	while(fdstate(fdc))
1816 		;
1817 }
1818 
1819 /*
1820  * Magic pseudo-DMA initialization for YE FDC. Sets count and
1821  * direction.
1822  */
1823 #define SET_BCDR(fdc,wr,cnt,port) \
1824 	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port,	 \
1825 	    ((cnt)-1) & 0xff);						 \
1826 	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port + 1, \
1827 	    ((wr ? 0x80 : 0) | ((((cnt)-1) >> 8) & 0x7f)));
1828 
1829 /*
1830  * fdcpio(): perform programmed IO read/write for YE PCMCIA floppy.
1831  */
1832 static int
1833 fdcpio(fdc_p fdc, long flags, caddr_t addr, u_int count)
1834 {
1835 	u_char *cptr = (u_char *)addr;
1836 
1837 	if (flags == BIO_READ) {
1838 		if (fdc->state != PIOREAD) {
1839 			fdc->state = PIOREAD;
1840 			return(0);
1841 		}
1842 		SET_BCDR(fdc, 0, count, 0);
1843 		bus_space_read_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1844 		    FDC_YE_DATAPORT, cptr, count);
1845 	} else {
1846 		bus_space_write_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1847 		    FDC_YE_DATAPORT, cptr, count);
1848 		SET_BCDR(fdc, 0, count, 0);
1849 	}
1850 	return(1);
1851 }
1852 
1853 /*
1854  * Try figuring out the density of the media present in our device.
1855  */
1856 static int
1857 fdautoselect(dev_t dev)
1858 {
1859 	fdu_t fdu;
1860  	fd_p fd;
1861 	struct fd_type *fdtp;
1862 	struct fdc_readid id;
1863 	int i, n, oopts, rv;
1864 
1865  	fdu = FDUNIT(minor(dev));
1866 	fd = devclass_get_softc(fd_devclass, fdu);
1867 
1868 	switch (fd->type) {
1869 	default:
1870 		return (ENXIO);
1871 
1872 	case FDT_360K:
1873 	case FDT_720K:
1874 		/* no autoselection on those drives */
1875 		fd->ft = fd_native_types + fd->type;
1876 		return (0);
1877 
1878 	case FDT_12M:
1879 		fdtp = fd_searchlist_12m;
1880 		n = sizeof fd_searchlist_12m / sizeof(struct fd_type);
1881 		break;
1882 
1883 	case FDT_144M:
1884 		fdtp = fd_searchlist_144m;
1885 		n = sizeof fd_searchlist_144m / sizeof(struct fd_type);
1886 		break;
1887 
1888 	case FDT_288M:
1889 		fdtp = fd_searchlist_288m;
1890 		n = sizeof fd_searchlist_288m / sizeof(struct fd_type);
1891 		break;
1892 	}
1893 
1894 	/*
1895 	 * Try reading sector ID fields, first at cylinder 0, head 0,
1896 	 * then at cylinder 2, head N.  We don't probe cylinder 1,
1897 	 * since for 5.25in DD media in a HD drive, there are no data
1898 	 * to read (2 step pulses per media cylinder required).  For
1899 	 * two-sided media, the second probe always goes to head 1, so
1900 	 * we can tell them apart from single-sided media.  As a
1901 	 * side-effect this means that single-sided media should be
1902 	 * mentioned in the search list after two-sided media of an
1903 	 * otherwise identical density.  Media with a different number
1904 	 * of sectors per track but otherwise identical parameters
1905 	 * cannot be distinguished at all.
1906 	 *
1907 	 * If we successfully read an ID field on both cylinders where
1908 	 * the recorded values match our expectation, we are done.
1909 	 * Otherwise, we try the next density entry from the table.
1910 	 *
1911 	 * Stepping to cylinder 2 has the side-effect of clearing the
1912 	 * unit attention bit.
1913 	 */
1914 	oopts = fd->options;
1915 	fd->options |= FDOPT_NOERRLOG | FDOPT_NORETRY;
1916 	for (i = 0; i < n; i++, fdtp++) {
1917 		fd->ft = fdtp;
1918 
1919 		id.cyl = id.head = 0;
1920 		rv = fdmisccmd(dev, BIO_RDSECTID, &id);
1921 		if (rv != 0)
1922 			continue;
1923 		if (id.cyl != 0 || id.head != 0 ||
1924 		    id.secshift != fdtp->secsize)
1925 			continue;
1926 		id.cyl = 2;
1927 		id.head = fd->ft->heads - 1;
1928 		rv = fdmisccmd(dev, BIO_RDSECTID, &id);
1929 		if (id.cyl != 2 || id.head != fdtp->heads - 1 ||
1930 		    id.secshift != fdtp->secsize)
1931 			continue;
1932 		if (rv == 0)
1933 			break;
1934 	}
1935 
1936 	fd->options = oopts;
1937 	if (i == n) {
1938 		if (bootverbose)
1939 			device_printf(fd->dev, "autoselection failed\n");
1940 		fd->ft = 0;
1941 		return (EIO);
1942 	} else {
1943 		if (bootverbose)
1944 			device_printf(fd->dev, "autoselected %d KB medium\n",
1945 				      fd->ft->size / 2);
1946 		return (0);
1947 	}
1948 }
1949 
1950 
1951 /*
1952  * The controller state machine.
1953  *
1954  * If it returns a non zero value, it should be called again immediately.
1955  */
1956 static int
1957 fdstate(fdc_p fdc)
1958 {
1959 	struct fdc_readid *idp;
1960 	int read, format, rdsectid, cylinder, head, i, sec = 0, sectrac;
1961 	int st0, cyl, st3, idf, ne7cmd, mfm, steptrac;
1962 	unsigned long blknum;
1963 	fdu_t fdu = fdc->fdu;
1964 	fd_p fd;
1965 	register struct bio *bp;
1966 	struct fd_formb *finfo = NULL;
1967 	size_t fdblk;
1968 
1969 	bp = fdc->bp;
1970 	if (bp == NULL) {
1971 		bp = bioq_first(&fdc->head);
1972 		if (bp != NULL) {
1973 			bioq_remove(&fdc->head, bp);
1974 			fdc->bp = bp;
1975 		}
1976 	}
1977 	if (bp == NULL) {
1978 		/*
1979 		 * Nothing left for this controller to do,
1980 		 * force into the IDLE state.
1981 		 */
1982 		fdc->state = DEVIDLE;
1983 		if (fdc->fd) {
1984 			device_printf(fdc->fdc_dev,
1985 			    "unexpected valid fd pointer\n");
1986 			fdc->fd = (fd_p) 0;
1987 			fdc->fdu = -1;
1988 		}
1989 		TRACE1("[fdc%d IDLE]", fdc->fdcu);
1990  		return (0);
1991 	}
1992 	fdu = FDUNIT(minor(bp->bio_dev));
1993 	fd = devclass_get_softc(fd_devclass, fdu);
1994 	fdblk = 128 << fd->ft->secsize;
1995 	if (fdc->fd && (fd != fdc->fd))
1996 		device_printf(fd->dev, "confused fd pointers\n");
1997 	read = bp->bio_cmd == BIO_READ;
1998 	mfm = (fd->ft->flags & FL_MFM)? NE7CMD_MFM: 0;
1999 	steptrac = (fd->ft->flags & FL_2STEP)? 2: 1;
2000 	if (read)
2001 		idf = ISADMA_READ;
2002 	else
2003 		idf = ISADMA_WRITE;
2004 	format = bp->bio_cmd == BIO_FORMAT;
2005 	rdsectid = bp->bio_cmd == BIO_RDSECTID;
2006 	if (format)
2007 		finfo = (struct fd_formb *)bp->bio_data;
2008 	TRACE1("fd%d", fdu);
2009 	TRACE1("[%s]", fdstates[fdc->state]);
2010 	TRACE1("(0x%x)", fd->flags);
2011 	untimeout(fd_turnoff, fd, fd->toffhandle);
2012 	fd->toffhandle = timeout(fd_turnoff, fd, 4 * hz);
2013 	switch (fdc->state)
2014 	{
2015 	case DEVIDLE:
2016 	case FINDWORK:	/* we have found new work */
2017 		fdc->retry = 0;
2018 		fd->skip = 0;
2019 		fdc->fd = fd;
2020 		fdc->fdu = fdu;
2021 		fdc->fdctl_wr(fdc, fd->ft->trans);
2022 		TRACE1("[0x%x->FDCTL]", fd->ft->trans);
2023 		/*
2024 		 * If the next drive has a motor startup pending, then
2025 		 * it will start up in its own good time.
2026 		 */
2027 		if(fd->flags & FD_MOTOR_WAIT) {
2028 			fdc->state = MOTORWAIT;
2029 			return (0); /* will return later */
2030 		}
2031 		/*
2032 		 * Maybe if it's not starting, it SHOULD be starting.
2033 		 */
2034 		if (!(fd->flags & FD_MOTOR))
2035 		{
2036 			fdc->state = MOTORWAIT;
2037 			fd_turnon(fd);
2038 			return (0); /* will return later */
2039 		}
2040 		else	/* at least make sure we are selected */
2041 		{
2042 			set_motor(fdc, fd->fdsu, TURNON);
2043 		}
2044 		if (fdc->flags & FDC_NEEDS_RESET) {
2045 			fdc->state = RESETCTLR;
2046 			fdc->flags &= ~FDC_NEEDS_RESET;
2047 		} else
2048 			fdc->state = DOSEEK;
2049 		return (1);	/* will return immediately */
2050 
2051 	case DOSEEK:
2052 		blknum = bp->bio_pblkno + fd->skip / fdblk;
2053 		cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
2054 		if (cylinder == fd->track)
2055 		{
2056 			fdc->state = SEEKCOMPLETE;
2057 			return (1); /* will return immediately */
2058 		}
2059 		if (fd_cmd(fdc, 3, NE7CMD_SEEK,
2060 			   fd->fdsu, cylinder * steptrac, 0))
2061 		{
2062 			/*
2063 			 * Seek command not accepted, looks like
2064 			 * the FDC went off to the Saints...
2065 			 */
2066 			fdc->retry = 6;	/* try a reset */
2067 			return(retrier(fdc));
2068 		}
2069 		fd->track = FD_NO_TRACK;
2070 		fdc->state = SEEKWAIT;
2071 		return(0);	/* will return later */
2072 
2073 	case SEEKWAIT:
2074 		/* allow heads to settle */
2075 		timeout(fd_pseudointr, fdc, hz / 16);
2076 		fdc->state = SEEKCOMPLETE;
2077 		return(0);	/* will return later */
2078 
2079 	case SEEKCOMPLETE : /* seek done, start DMA */
2080 		blknum = bp->bio_pblkno + fd->skip / fdblk;
2081 		cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
2082 
2083 		/* Make sure seek really happened. */
2084 		if(fd->track == FD_NO_TRACK) {
2085 			int descyl = cylinder * steptrac;
2086 			do {
2087 				/*
2088 				 * This might be a "ready changed" interrupt,
2089 				 * which cannot really happen since the
2090 				 * RDY pin is hardwired to + 5 volts.  This
2091 				 * generally indicates a "bouncing" intr
2092 				 * line, so do one of the following:
2093 				 *
2094 				 * When running on an enhanced FDC that is
2095 				 * known to not go stuck after responding
2096 				 * with INVALID, fetch all interrupt states
2097 				 * until seeing either an INVALID or a
2098 				 * real interrupt condition.
2099 				 *
2100 				 * When running on a dumb old NE765, give
2101 				 * up immediately.  The controller will
2102 				 * provide up to four dummy RC interrupt
2103 				 * conditions right after reset (for the
2104 				 * corresponding four drives), so this is
2105 				 * our only chance to get notice that it
2106 				 * was not the FDC that caused the interrupt.
2107 				 */
2108 				if (fd_sense_int(fdc, &st0, &cyl)
2109 				    == FD_NOT_VALID)
2110 					return (0); /* will return later */
2111 				if(fdc->fdct == FDC_NE765
2112 				   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2113 					return (0); /* hope for a real intr */
2114 			} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2115 
2116 			if (0 == descyl) {
2117 				int failed = 0;
2118 				/*
2119 				 * seek to cyl 0 requested; make sure we are
2120 				 * really there
2121 				 */
2122 				if (fd_sense_drive_status(fdc, &st3))
2123 					failed = 1;
2124 				if ((st3 & NE7_ST3_T0) == 0) {
2125 					printf(
2126 		"fd%d: Seek to cyl 0, but not really there (ST3 = %b)\n",
2127 					       fdu, st3, NE7_ST3BITS);
2128 					failed = 1;
2129 				}
2130 
2131 				if (failed) {
2132 					if(fdc->retry < 3)
2133 						fdc->retry = 3;
2134 					return (retrier(fdc));
2135 				}
2136 			}
2137 
2138 			if (cyl != descyl) {
2139 				printf(
2140 		"fd%d: Seek to cyl %d failed; am at cyl %d (ST0 = 0x%x)\n",
2141 				       fdu, descyl, cyl, st0);
2142 				if (fdc->retry < 3)
2143 					fdc->retry = 3;
2144 				return (retrier(fdc));
2145 			}
2146 		}
2147 
2148 		fd->track = cylinder;
2149 		if (format)
2150 			fd->skip = (char *)&(finfo->fd_formb_cylno(0))
2151 			    - (char *)finfo;
2152 		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2153 			isa_dmastart(idf, bp->bio_data+fd->skip,
2154 				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2155 		blknum = bp->bio_pblkno + fd->skip / fdblk;
2156 		sectrac = fd->ft->sectrac;
2157 		sec = blknum %  (sectrac * fd->ft->heads);
2158 		head = sec / sectrac;
2159 		sec = sec % sectrac + 1;
2160 		if (head != 0 && fd->ft->offset_side2 != 0)
2161 			sec += fd->ft->offset_side2;
2162 		fd->hddrv = ((head&1)<<2)+fdu;
2163 
2164 		if(format || !(read || rdsectid))
2165 		{
2166 			/* make sure the drive is writable */
2167 			if(fd_sense_drive_status(fdc, &st3) != 0)
2168 			{
2169 				/* stuck controller? */
2170 				if (!(fdc->flags & FDC_NODMA))
2171 					isa_dmadone(idf,
2172 						    bp->bio_data + fd->skip,
2173 						    format ? bp->bio_bcount : fdblk,
2174 						    fdc->dmachan);
2175 				fdc->retry = 6;	/* reset the beast */
2176 				return (retrier(fdc));
2177 			}
2178 			if(st3 & NE7_ST3_WP)
2179 			{
2180 				/*
2181 				 * XXX YES! this is ugly.
2182 				 * in order to force the current operation
2183 				 * to fail, we will have to fake an FDC
2184 				 * error - all error handling is done
2185 				 * by the retrier()
2186 				 */
2187 				fdc->status[0] = NE7_ST0_IC_AT;
2188 				fdc->status[1] = NE7_ST1_NW;
2189 				fdc->status[2] = 0;
2190 				fdc->status[3] = fd->track;
2191 				fdc->status[4] = head;
2192 				fdc->status[5] = sec;
2193 				fdc->retry = 8;	/* break out immediately */
2194 				fdc->state = IOTIMEDOUT; /* not really... */
2195 				return (1); /* will return immediately */
2196 			}
2197 		}
2198 
2199 		if (format) {
2200 			ne7cmd = NE7CMD_FORMAT | mfm;
2201 			if (fdc->flags & FDC_NODMA) {
2202 				/*
2203 				 * This seems to be necessary for
2204 				 * whatever obscure reason; if we omit
2205 				 * it, we end up filling the sector ID
2206 				 * fields of the newly formatted track
2207 				 * entirely with garbage, causing
2208 				 * `wrong cylinder' errors all over
2209 				 * the place when trying to read them
2210 				 * back.
2211 				 *
2212 				 * Umpf.
2213 				 */
2214 				SET_BCDR(fdc, 1, bp->bio_bcount, 0);
2215 
2216 				(void)fdcpio(fdc,bp->bio_cmd,
2217 					bp->bio_data+fd->skip,
2218 					bp->bio_bcount);
2219 
2220 			}
2221 			/* formatting */
2222 			if(fd_cmd(fdc, 6,  ne7cmd, head << 2 | fdu,
2223 				  finfo->fd_formb_secshift,
2224 				  finfo->fd_formb_nsecs,
2225 				  finfo->fd_formb_gaplen,
2226 				  finfo->fd_formb_fillbyte, 0)) {
2227 				/* controller fell over */
2228 				if (!(fdc->flags & FDC_NODMA))
2229 					isa_dmadone(idf,
2230 						    bp->bio_data + fd->skip,
2231 						    format ? bp->bio_bcount : fdblk,
2232 						    fdc->dmachan);
2233 				fdc->retry = 6;
2234 				return (retrier(fdc));
2235 			}
2236 		} else if (rdsectid) {
2237 			ne7cmd = NE7CMD_READID | mfm;
2238 			if (fd_cmd(fdc, 2, ne7cmd, head << 2 | fdu, 0)) {
2239 				/* controller jamming */
2240 				fdc->retry = 6;
2241 				return (retrier(fdc));
2242 			}
2243 		} else {
2244 			/* read or write operation */
2245 			ne7cmd = (read ? NE7CMD_READ | NE7CMD_SK : NE7CMD_WRITE) | mfm;
2246 			if (fdc->flags & FDC_NODMA) {
2247 				/*
2248 				 * This seems to be necessary even when
2249 				 * reading data.
2250 				 */
2251 				SET_BCDR(fdc, 1, fdblk, 0);
2252 
2253 				/*
2254 				 * Perform the write pseudo-DMA before
2255 				 * the WRITE command is sent.
2256 				 */
2257 				if (!read)
2258 					(void)fdcpio(fdc,bp->bio_cmd,
2259 					    bp->bio_data+fd->skip,
2260 					    fdblk);
2261 			}
2262 			if (fd_cmd(fdc, 9,
2263 				   ne7cmd,
2264 				   head << 2 | fdu,  /* head & unit */
2265 				   fd->track,        /* track */
2266 				   head,
2267 				   sec,              /* sector + 1 */
2268 				   fd->ft->secsize,  /* sector size */
2269 				   sectrac,          /* sectors/track */
2270 				   fd->ft->gap,      /* gap size */
2271 				   fd->ft->datalen,  /* data length */
2272 				   0)) {
2273 				/* the beast is sleeping again */
2274 				if (!(fdc->flags & FDC_NODMA))
2275 					isa_dmadone(idf,
2276 						    bp->bio_data + fd->skip,
2277 						    format ? bp->bio_bcount : fdblk,
2278 						    fdc->dmachan);
2279 				fdc->retry = 6;
2280 				return (retrier(fdc));
2281 			}
2282 		}
2283 		if (!rdsectid && (fdc->flags & FDC_NODMA))
2284 			/*
2285 			 * If this is a read, then simply await interrupt
2286 			 * before performing PIO.
2287 			 */
2288 			if (read && !fdcpio(fdc,bp->bio_cmd,
2289 			    bp->bio_data+fd->skip,fdblk)) {
2290 				fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2291 				return(0);      /* will return later */
2292 			}
2293 
2294 		/*
2295 		 * Write (or format) operation will fall through and
2296 		 * await completion interrupt.
2297 		 */
2298 		fdc->state = IOCOMPLETE;
2299 		fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2300 		return (0);	/* will return later */
2301 
2302 	case PIOREAD:
2303 		/*
2304 		 * Actually perform the PIO read.  The IOCOMPLETE case
2305 		 * removes the timeout for us.
2306 		 */
2307 		(void)fdcpio(fdc,bp->bio_cmd,bp->bio_data+fd->skip,fdblk);
2308 		fdc->state = IOCOMPLETE;
2309 		/* FALLTHROUGH */
2310 	case IOCOMPLETE: /* IO done, post-analyze */
2311 		untimeout(fd_iotimeout, fdc, fd->tohandle);
2312 
2313 		if (fd_read_status(fdc)) {
2314 			if (!rdsectid && !(fdc->flags & FDC_NODMA))
2315 				isa_dmadone(idf, bp->bio_data + fd->skip,
2316 					    format ? bp->bio_bcount : fdblk,
2317 					    fdc->dmachan);
2318 			if (fdc->retry < 6)
2319 				fdc->retry = 6;	/* force a reset */
2320 			return (retrier(fdc));
2321   		}
2322 
2323 		fdc->state = IOTIMEDOUT;
2324 
2325 		/* FALLTHROUGH */
2326 	case IOTIMEDOUT:
2327 		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2328 			isa_dmadone(idf, bp->bio_data + fd->skip,
2329 				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2330 		if (fdc->status[0] & NE7_ST0_IC) {
2331                         if ((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2332 			    && fdc->status[1] & NE7_ST1_OR) {
2333                                 /*
2334 				 * DMA overrun. Someone hogged the bus and
2335 				 * didn't release it in time for the next
2336 				 * FDC transfer.
2337 				 *
2338 				 * We normally restart this without bumping
2339 				 * the retry counter.  However, in case
2340 				 * something is seriously messed up (like
2341 				 * broken hardware), we rather limit the
2342 				 * number of retries so the IO operation
2343 				 * doesn't block indefinately.
2344 				 */
2345 				if (fdc->dma_overruns++ < FDC_DMAOV_MAX) {
2346 					fdc->state = SEEKCOMPLETE;
2347 					return (1);/* will return immediately */
2348 				} /* else fall through */
2349                         }
2350 			if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_IV
2351 				&& fdc->retry < 6)
2352 				fdc->retry = 6;	/* force a reset */
2353 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2354 				&& fdc->status[2] & NE7_ST2_WC
2355 				&& fdc->retry < 3)
2356 				fdc->retry = 3;	/* force recalibrate */
2357 			return (retrier(fdc));
2358 		}
2359 		/* All OK */
2360 		if (rdsectid) {
2361 			/* copy out ID field contents */
2362 			idp = (struct fdc_readid *)bp->bio_data;
2363 			idp->cyl = fdc->status[3];
2364 			idp->head = fdc->status[4];
2365 			idp->sec = fdc->status[5];
2366 			idp->secshift = fdc->status[6];
2367 		}
2368 		/* Operation successful, retry DMA overruns again next time. */
2369 		fdc->dma_overruns = 0;
2370 		fd->skip += fdblk;
2371 		if (!rdsectid && !format && fd->skip < bp->bio_bcount) {
2372 			/* set up next transfer */
2373 			fdc->state = DOSEEK;
2374 		} else {
2375 			/* ALL DONE */
2376 			fd->skip = 0;
2377 			bp->bio_resid = 0;
2378 			fdc->bp = NULL;
2379 			device_unbusy(fd->dev);
2380 			biofinish(bp, &fd->device_stats, 0);
2381 			fdc->fd = (fd_p) 0;
2382 			fdc->fdu = -1;
2383 			fdc->state = FINDWORK;
2384 		}
2385 		return (1);	/* will return immediately */
2386 
2387 	case RESETCTLR:
2388 		fdc_reset(fdc);
2389 		fdc->retry++;
2390 		fdc->state = RESETCOMPLETE;
2391 		return (0);	/* will return later */
2392 
2393 	case RESETCOMPLETE:
2394 		/*
2395 		 * Discard all the results from the reset so that they
2396 		 * can't cause an unexpected interrupt later.
2397 		 */
2398 		for (i = 0; i < 4; i++)
2399 			(void)fd_sense_int(fdc, &st0, &cyl);
2400 		fdc->state = STARTRECAL;
2401 		/* FALLTHROUGH */
2402 	case STARTRECAL:
2403 		if(fd_cmd(fdc, 2, NE7CMD_RECAL, fdu, 0)) {
2404 			/* arrgl */
2405 			fdc->retry = 6;
2406 			return (retrier(fdc));
2407 		}
2408 		fdc->state = RECALWAIT;
2409 		return (0);	/* will return later */
2410 
2411 	case RECALWAIT:
2412 		/* allow heads to settle */
2413 		timeout(fd_pseudointr, fdc, hz / 8);
2414 		fdc->state = RECALCOMPLETE;
2415 		return (0);	/* will return later */
2416 
2417 	case RECALCOMPLETE:
2418 		do {
2419 			/*
2420 			 * See SEEKCOMPLETE for a comment on this:
2421 			 */
2422 			if (fd_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
2423 				return (0); /* will return later */
2424 			if(fdc->fdct == FDC_NE765
2425 			   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2426 				return (0); /* hope for a real intr */
2427 		} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2428 		if ((st0 & NE7_ST0_IC) != NE7_ST0_IC_NT || cyl != 0)
2429 		{
2430 			if(fdc->retry > 3)
2431 				/*
2432 				 * A recalibrate from beyond cylinder 77
2433 				 * will "fail" due to the FDC limitations;
2434 				 * since people used to complain much about
2435 				 * the failure message, try not logging
2436 				 * this one if it seems to be the first
2437 				 * time in a line.
2438 				 */
2439 				printf("fd%d: recal failed ST0 %b cyl %d\n",
2440 				       fdu, st0, NE7_ST0BITS, cyl);
2441 			if(fdc->retry < 3) fdc->retry = 3;
2442 			return (retrier(fdc));
2443 		}
2444 		fd->track = 0;
2445 		/* Seek (probably) necessary */
2446 		fdc->state = DOSEEK;
2447 		return (1);	/* will return immediately */
2448 
2449 	case MOTORWAIT:
2450 		if(fd->flags & FD_MOTOR_WAIT)
2451 		{
2452 			return (0); /* time's not up yet */
2453 		}
2454 		if (fdc->flags & FDC_NEEDS_RESET) {
2455 			fdc->state = RESETCTLR;
2456 			fdc->flags &= ~FDC_NEEDS_RESET;
2457 		} else
2458 			fdc->state = DOSEEK;
2459 		return (1);	/* will return immediately */
2460 
2461 	default:
2462 		device_printf(fdc->fdc_dev, "unexpected FD int->");
2463 		if (fd_read_status(fdc) == 0)
2464 			printf("FDC status :%x %x %x %x %x %x %x   ",
2465 			       fdc->status[0],
2466 			       fdc->status[1],
2467 			       fdc->status[2],
2468 			       fdc->status[3],
2469 			       fdc->status[4],
2470 			       fdc->status[5],
2471 			       fdc->status[6] );
2472 		else
2473 			printf("No status available   ");
2474 		if (fd_sense_int(fdc, &st0, &cyl) != 0)
2475 		{
2476 			printf("[controller is dead now]\n");
2477 			return (0); /* will return later */
2478 		}
2479 		printf("ST0 = %x, PCN = %x\n", st0, cyl);
2480 		return (0);	/* will return later */
2481 	}
2482 	/* noone should ever get here */
2483 }
2484 
2485 static int
2486 retrier(struct fdc_data *fdc)
2487 {
2488 	struct bio *bp;
2489 	struct fd_data *fd;
2490 	int fdu;
2491 
2492 	bp = fdc->bp;
2493 
2494 	/* XXX shouldn't this be cached somewhere?  */
2495 	fdu = FDUNIT(minor(bp->bio_dev));
2496 	fd = devclass_get_softc(fd_devclass, fdu);
2497 	if (fd->options & FDOPT_NORETRY)
2498 		goto fail;
2499 
2500 	switch (fdc->retry) {
2501 	case 0: case 1: case 2:
2502 		fdc->state = SEEKCOMPLETE;
2503 		break;
2504 	case 3: case 4: case 5:
2505 		fdc->state = STARTRECAL;
2506 		break;
2507 	case 6:
2508 		fdc->state = RESETCTLR;
2509 		break;
2510 	case 7:
2511 		break;
2512 	default:
2513 	fail:
2514 		if ((fd->options & FDOPT_NOERRLOG) == 0) {
2515 			diskerr(bp, "hard error", fdc->fd->skip / DEV_BSIZE,
2516 				(struct disklabel *)NULL);
2517 			if (fdc->flags & FDC_STAT_VALID) {
2518 				printf(
2519 				" (ST0 %b ST1 %b ST2 %b cyl %u hd %u sec %u)\n",
2520 				       fdc->status[0], NE7_ST0BITS,
2521 				       fdc->status[1], NE7_ST1BITS,
2522 				       fdc->status[2], NE7_ST2BITS,
2523 				       fdc->status[3], fdc->status[4],
2524 				       fdc->status[5]);
2525 			}
2526 			else
2527 				printf(" (No status)\n");
2528 		}
2529 		if ((fd->options & FDOPT_NOERROR) == 0) {
2530 			bp->bio_flags |= BIO_ERROR;
2531 			bp->bio_error = EIO;
2532 			bp->bio_resid = bp->bio_bcount - fdc->fd->skip;
2533 		} else
2534 			bp->bio_resid = 0;
2535 		fdc->bp = NULL;
2536 		fdc->fd->skip = 0;
2537 		device_unbusy(fd->dev);
2538 		biofinish(bp, &fdc->fd->device_stats, 0);
2539 		fdc->state = FINDWORK;
2540 		fdc->flags |= FDC_NEEDS_RESET;
2541 		fdc->fd = (fd_p) 0;
2542 		fdc->fdu = -1;
2543 		return (1);
2544 	}
2545 	fdc->retry++;
2546 	return (1);
2547 }
2548 
2549 static void
2550 fdbiodone(struct bio *bp)
2551 {
2552 	wakeup(bp);
2553 }
2554 
2555 static int
2556 fdmisccmd(dev_t dev, u_int cmd, void *data)
2557 {
2558  	fdu_t fdu;
2559  	fd_p fd;
2560 	struct bio *bp;
2561 	struct fd_formb *finfo;
2562 	struct fdc_readid *idfield;
2563 	size_t fdblk;
2564 
2565  	fdu = FDUNIT(minor(dev));
2566 	fd = devclass_get_softc(fd_devclass, fdu);
2567 	fdblk = 128 << fd->ft->secsize;
2568 	finfo = (struct fd_formb *)data;
2569 	idfield = (struct fdc_readid *)data;
2570 
2571 	bp = malloc(sizeof(struct bio), M_TEMP, M_ZERO);
2572 
2573 	/*
2574 	 * Set up a bio request for fdstrategy().  bio_blkno is faked
2575 	 * so that fdstrategy() will seek to the the requested
2576 	 * cylinder, and use the desired head.
2577 	 */
2578 	bp->bio_cmd = cmd;
2579 	if (cmd == BIO_FORMAT) {
2580 		bp->bio_blkno =
2581 		    (finfo->cyl * (fd->ft->sectrac * fd->ft->heads) +
2582 		     finfo->head * fd->ft->sectrac) *
2583 		    fdblk / DEV_BSIZE;
2584 		bp->bio_bcount = sizeof(struct fd_idfield_data) *
2585 		    finfo->fd_formb_nsecs;
2586 	} else if (cmd == BIO_RDSECTID) {
2587 		bp->bio_blkno =
2588 		    (idfield->cyl * (fd->ft->sectrac * fd->ft->heads) +
2589 		     idfield->head * fd->ft->sectrac) *
2590 		    fdblk / DEV_BSIZE;
2591 		bp->bio_bcount = sizeof(struct fdc_readid);
2592 	} else
2593 		panic("wrong cmd in fdmisccmd()");
2594 	bp->bio_data = data;
2595 	bp->bio_dev = dev;
2596 	bp->bio_done = fdbiodone;
2597 	bp->bio_flags = 0;
2598 
2599 	/*
2600 	 * Now run the command.  The wait loop is a version of bufwait()
2601 	 * adapted for struct bio instead of struct buf and specialized
2602 	 * for the current context.
2603 	 */
2604 	fdstrategy(bp);
2605 	while ((bp->bio_flags & BIO_DONE) == 0)
2606 		tsleep(bp, PRIBIO, "fdcmd", 0);
2607 
2608 	free(bp, M_TEMP);
2609 	return (bp->bio_flags & BIO_ERROR ? bp->bio_error : 0);
2610 }
2611 
2612 static int
2613 fdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
2614 {
2615  	fdu_t fdu;
2616  	fd_p fd;
2617 	struct fd_type *fdt;
2618 	struct disklabel *lp;
2619 	struct fdc_status *fsp;
2620 	struct fdc_readid *rid;
2621 	size_t fdblk;
2622 	int error, type;
2623 
2624  	fdu = FDUNIT(minor(dev));
2625 	type = FDTYPE(minor(dev));
2626  	fd = devclass_get_softc(fd_devclass, fdu);
2627 
2628 	/*
2629 	 * First, handle everything that could be done with
2630 	 * FD_NONBLOCK still being set.
2631 	 */
2632 	switch (cmd) {
2633 	case FIONBIO:
2634 		if (*(int *)addr != 0)
2635 			fd->flags |= FD_NONBLOCK;
2636 		else {
2637 			if (fd->ft == 0) {
2638 				/*
2639 				 * No drive type has been selected yet,
2640 				 * cannot turn FNONBLOCK off.
2641 				 */
2642 				return (EINVAL);
2643 			}
2644 			fd->flags &= ~FD_NONBLOCK;
2645 		}
2646 		return (0);
2647 
2648 	case FIOASYNC:
2649 		/* keep the generic fcntl() code happy */
2650 		return (0);
2651 
2652 	case FD_GTYPE:                  /* get drive type */
2653 		if (fd->ft == 0)
2654 			/* no type known yet, return the native type */
2655 			*(struct fd_type *)addr = fd_native_types[fd->type];
2656 		else
2657 			*(struct fd_type *)addr = *fd->ft;
2658 		return (0);
2659 
2660 	case FD_STYPE:                  /* set drive type */
2661 		if (type == 0) {
2662 			/*
2663 			 * Allow setting drive type temporarily iff
2664 			 * currently unset.  Used for fdformat so any
2665 			 * user can set it, and then start formatting.
2666 			 */
2667 			if (fd->ft)
2668 				return (EINVAL); /* already set */
2669 			fd->ft = fd->fts;
2670 			*fd->ft = *(struct fd_type *)addr;
2671 			fd->flags |= FD_UA;
2672 		} else {
2673 			/*
2674 			 * Set density definition permanently.  Only
2675 			 * allow for superuser.
2676 			 */
2677 			if (suser(td) != 0)
2678 				return (EPERM);
2679 			fd->fts[type] = *(struct fd_type *)addr;
2680 		}
2681 		return (0);
2682 
2683 	case FD_GOPTS:			/* get drive options */
2684 		*(int *)addr = fd->options + (type == 0? FDOPT_AUTOSEL: 0);
2685 		return (0);
2686 
2687 	case FD_SOPTS:			/* set drive options */
2688 		fd->options = *(int *)addr & ~FDOPT_AUTOSEL;
2689 		return (0);
2690 
2691 #ifdef FDC_DEBUG
2692 	case FD_DEBUG:
2693 		if ((fd_debug != 0) != (*(int *)addr != 0)) {
2694 			fd_debug = (*(int *)addr != 0);
2695 			printf("fd%d: debugging turned %s\n",
2696 			    fd->fdu, fd_debug ? "on" : "off");
2697 		}
2698 		return (0);
2699 #endif
2700 
2701 	case FD_CLRERR:
2702 		if (suser(td) != 0)
2703 			return (EPERM);
2704 		fd->fdc->fdc_errs = 0;
2705 		return (0);
2706 
2707 	case FD_GSTAT:
2708 		fsp = (struct fdc_status *)addr;
2709 		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2710 			return (EINVAL);
2711 		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2712 		return (0);
2713 
2714 	case FD_GDTYPE:
2715 		*(enum fd_drivetype *)addr = fd->type;
2716 		return (0);
2717 	}
2718 
2719 	/*
2720 	 * Now handle everything else.  Make sure we have a valid
2721 	 * drive type.
2722 	 */
2723 	if (fd->flags & FD_NONBLOCK)
2724 		return (EAGAIN);
2725 	if (fd->ft == 0)
2726 		return (ENXIO);
2727 	fdblk = 128 << fd->ft->secsize;
2728 	error = 0;
2729 
2730 	switch (cmd) {
2731 	case DIOCGDINFO:
2732 		lp = malloc(sizeof(*lp), M_TEMP, M_ZERO);
2733 		lp->d_secsize = fdblk;
2734 		fdt = fd->ft;
2735 		lp->d_secpercyl = fdt->size / fdt->tracks;
2736 		lp->d_type = DTYPE_FLOPPY;
2737 		if (readdisklabel(dev, lp) != NULL)
2738 			error = EINVAL;
2739 		else
2740 			*(struct disklabel *)addr = *lp;
2741 		free(lp, M_TEMP);
2742 		break;
2743 
2744 	case DIOCSDINFO:
2745 		if ((flag & FWRITE) == 0)
2746 			return (EBADF);
2747 		/*
2748 		 * XXX perhaps should call setdisklabel() to do error checking
2749 		 * although there is nowhere to "set" the result.  Perhaps
2750 		 * should always just fail.
2751 		 */
2752 		break;
2753 
2754 	case DIOCWLABEL:
2755 		if ((flag & FWRITE) == 0)
2756 			return (EBADF);
2757 		break;
2758 
2759 	case DIOCWDINFO:
2760 		if ((flag & FWRITE) == 0)
2761 			return (EBADF);
2762 		lp = malloc(DEV_BSIZE, M_TEMP, M_ZERO);
2763 		error = setdisklabel(lp, (struct disklabel *)addr, (u_long)0);
2764 		if (error != 0)
2765 			error = writedisklabel(dev, lp);
2766 		free(lp, M_TEMP);
2767 		break;
2768 
2769 	case FD_FORM:
2770 		if ((flag & FWRITE) == 0)
2771 			return (EBADF);	/* must be opened for writing */
2772 		if (((struct fd_formb *)addr)->format_version !=
2773 		    FD_FORMAT_VERSION)
2774 			return (EINVAL); /* wrong version of formatting prog */
2775 		error = fdmisccmd(dev, BIO_FORMAT, addr);
2776 		break;
2777 
2778 	case FD_GTYPE:                  /* get drive type */
2779 		*(struct fd_type *)addr = *fd->ft;
2780 		break;
2781 
2782 	case FD_STYPE:                  /* set drive type */
2783 		/* this is considered harmful; only allow for superuser */
2784 		if (suser(td) != 0)
2785 			return (EPERM);
2786 		*fd->ft = *(struct fd_type *)addr;
2787 		break;
2788 
2789 	case FD_GOPTS:			/* get drive options */
2790 		*(int *)addr = fd->options;
2791 		break;
2792 
2793 	case FD_SOPTS:			/* set drive options */
2794 		fd->options = *(int *)addr;
2795 		break;
2796 
2797 #ifdef FDC_DEBUG
2798 	case FD_DEBUG:
2799 		if ((fd_debug != 0) != (*(int *)addr != 0)) {
2800 			fd_debug = (*(int *)addr != 0);
2801 			printf("fd%d: debugging turned %s\n",
2802 			    fd->fdu, fd_debug ? "on" : "off");
2803 		}
2804 		break;
2805 #endif
2806 
2807 	case FD_CLRERR:
2808 		if (suser(td) != 0)
2809 			return (EPERM);
2810 		fd->fdc->fdc_errs = 0;
2811 		break;
2812 
2813 	case FD_GSTAT:
2814 		fsp = (struct fdc_status *)addr;
2815 		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2816 			return (EINVAL);
2817 		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2818 		break;
2819 
2820 	case FD_READID:
2821 		rid = (struct fdc_readid *)addr;
2822 		if (rid->cyl > MAX_CYLINDER || rid->head > MAX_HEAD)
2823 			return (EINVAL);
2824 		error = fdmisccmd(dev, BIO_RDSECTID, addr);
2825 		break;
2826 
2827 	default:
2828 		error = ENOTTY;
2829 		break;
2830 	}
2831 	return (error);
2832 }
2833