xref: /freebsd/sys/dev/fdc/fdc.c (revision a3e8fd0b7f663db7eafff527d5c3ca3bcfa8a537)
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/disk.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 FDBIO_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 FDBIO_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 		free(ivar, M_DEVBUF);
990 		return;
991 	}
992 	device_set_ivars(child, ivar);
993 	if (resource_int_value(name, unit, "flags", &flags) == 0)
994 		 device_set_flags(child, flags);
995 	if (resource_int_value(name, unit, "disabled", &disabled) == 0
996 	    && disabled != 0)
997 		device_disable(child);
998 }
999 
1000 static int
1001 fdc_attach(device_t dev)
1002 {
1003 	struct	fdc_data *fdc;
1004 	const char *name, *dname;
1005 	int	i, error, dunit;
1006 
1007 	fdc = device_get_softc(dev);
1008 	error = fdc_alloc_resources(fdc);
1009 	if (error) {
1010 		device_printf(dev, "cannot re-acquire resources\n");
1011 		return error;
1012 	}
1013 	error = BUS_SETUP_INTR(device_get_parent(dev), dev, fdc->res_irq,
1014 			       INTR_TYPE_BIO | INTR_ENTROPY, fdc_intr, fdc,
1015 			       &fdc->fdc_intr);
1016 	if (error) {
1017 		device_printf(dev, "cannot setup interrupt\n");
1018 		return error;
1019 	}
1020 	fdc->fdcu = device_get_unit(dev);
1021 	fdc->flags |= FDC_ATTACHED | FDC_NEEDS_RESET;
1022 
1023 	if ((fdc->flags & FDC_NODMA) == 0) {
1024 		/*
1025 		 * Acquire the DMA channel forever, the driver will do
1026 		 * the rest
1027 		 * XXX should integrate with rman
1028 		 */
1029 		isa_dma_acquire(fdc->dmachan);
1030 		isa_dmainit(fdc->dmachan, MAX_SEC_SIZE);
1031 	}
1032 	fdc->state = DEVIDLE;
1033 
1034 	/* reset controller, turn motor off, clear fdout mirror reg */
1035 	fdout_wr(fdc, fdc->fdout = 0);
1036 	bioq_init(&fdc->head);
1037 
1038 	/*
1039 	 * Probe and attach any children.  We should probably detect
1040 	 * devices from the BIOS unless overridden.
1041 	 */
1042 	name = device_get_nameunit(dev);
1043 	i = 0;
1044 	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0)
1045 		fdc_add_child(dev, dname, dunit);
1046 
1047 	if ((error = bus_generic_attach(dev)) != 0)
1048 		return (error);
1049 
1050 	return (0);
1051 }
1052 
1053 static int
1054 fdc_print_child(device_t me, device_t child)
1055 {
1056 	int retval = 0, flags;
1057 
1058 	retval += bus_print_child_header(me, child);
1059 	retval += printf(" on %s drive %d", device_get_nameunit(me),
1060 	       fdc_get_fdunit(child));
1061 	if ((flags = device_get_flags(me)) != 0)
1062 		retval += printf(" flags %#x", flags);
1063 	retval += printf("\n");
1064 
1065 	return (retval);
1066 }
1067 
1068 static device_method_t fdc_methods[] = {
1069 	/* Device interface */
1070 	DEVMETHOD(device_probe,		fdc_probe),
1071 	DEVMETHOD(device_attach,	fdc_attach),
1072 	DEVMETHOD(device_detach,	fdc_detach),
1073 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1074 	DEVMETHOD(device_suspend,	bus_generic_suspend),
1075 	DEVMETHOD(device_resume,	bus_generic_resume),
1076 
1077 	/* Bus interface */
1078 	DEVMETHOD(bus_print_child,	fdc_print_child),
1079 	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
1080 	/* Our children never use any other bus interface methods. */
1081 
1082 	{ 0, 0 }
1083 };
1084 
1085 static driver_t fdc_driver = {
1086 	"fdc",
1087 	fdc_methods,
1088 	sizeof(struct fdc_data)
1089 };
1090 
1091 DRIVER_MODULE(fdc, isa, fdc_driver, fdc_devclass, 0, 0);
1092 DRIVER_MODULE(fdc, acpi, fdc_driver, fdc_devclass, 0, 0);
1093 
1094 #if NCARD > 0
1095 
1096 static device_method_t fdc_pccard_methods[] = {
1097 	/* Device interface */
1098 	DEVMETHOD(device_probe,		fdc_pccard_probe),
1099 	DEVMETHOD(device_attach,	fdc_attach),
1100 	DEVMETHOD(device_detach,	fdc_detach),
1101 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1102 	DEVMETHOD(device_suspend,	bus_generic_suspend),
1103 	DEVMETHOD(device_resume,	bus_generic_resume),
1104 
1105 	/* Bus interface */
1106 	DEVMETHOD(bus_print_child,	fdc_print_child),
1107 	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
1108 	/* Our children never use any other bus interface methods. */
1109 
1110 	{ 0, 0 }
1111 };
1112 
1113 static driver_t fdc_pccard_driver = {
1114 	"fdc",
1115 	fdc_pccard_methods,
1116 	sizeof(struct fdc_data)
1117 };
1118 
1119 DRIVER_MODULE(fdc, pccard, fdc_pccard_driver, fdc_devclass, 0, 0);
1120 
1121 #endif /* NCARD > 0 */
1122 
1123 /*
1124  * Create a clone device upon request by devfs.
1125  */
1126 static void
1127 fd_clone(void *arg, char *name, int namelen, dev_t *dev)
1128 {
1129 	struct	fd_data *fd;
1130 	int i, u;
1131 	char *n;
1132 	size_t l;
1133 
1134 	fd = (struct fd_data *)arg;
1135 	if (*dev != NODEV)
1136 		return;
1137 	if (dev_stdclone(name, &n, "fd", &u) != 2)
1138 		return;
1139 	l = strlen(n);
1140 	if (l == 1 && *n >= 'a' && *n <= 'h') {
1141 		/*
1142 		 * Trailing letters a through h denote
1143 		 * pseudo-partitions.  We don't support true
1144 		 * (UFS-style) partitions, so we just implement them
1145 		 * as symlinks if someone asks us nicely.
1146 		 */
1147 		*dev = make_dev_alias(fd->masterdev, name);
1148 		return;
1149 	}
1150 	if (l >= 2 && l <= 5 && *n == '.') {
1151 		/*
1152 		 * Trailing numbers, preceded by a dot, denote
1153 		 * subdevices for different densities.  Historically,
1154 		 * they have been named by density (like fd0.1440),
1155 		 * but we allow arbitrary numbers between 1 and 4
1156 		 * digits, so fd0.1 through fd0.15 are possible as
1157 		 * well.
1158 		 */
1159 		for (i = 1; i < l; i++)
1160 			if (n[i] < '0' || n[i] > '9')
1161 				return;
1162 		for (i = 0; i < NUMDENS - 1; i++)
1163 			if (fd->clonedevs[i] == NODEV) {
1164 				*dev = make_dev(&fd_cdevsw,
1165 						FDNUMTOUNIT(u) + i + 1,
1166 						UID_ROOT, GID_OPERATOR, 0640,
1167 						name);
1168 				fd->clonedevs[i] = *dev;
1169 				return;
1170 			}
1171 	}
1172 }
1173 
1174 /*
1175  * Configuration/initialization, per drive.
1176  */
1177 static int
1178 fd_probe(device_t dev)
1179 {
1180 	int	i;
1181 	u_int	st0, st3;
1182 	struct	fd_data *fd;
1183 	struct	fdc_data *fdc;
1184 	fdsu_t	fdsu;
1185 	int	flags;
1186 
1187 	fdsu = *(int *)device_get_ivars(dev); /* xxx cheat a bit... */
1188 	fd = device_get_softc(dev);
1189 	fdc = device_get_softc(device_get_parent(dev));
1190 	flags = device_get_flags(dev);
1191 
1192 	bzero(fd, sizeof *fd);
1193 	fd->dev = dev;
1194 	fd->fdc = fdc;
1195 	fd->fdsu = fdsu;
1196 	fd->fdu = device_get_unit(dev);
1197 	fd->flags = FD_UA;	/* make sure fdautoselect() will be called */
1198 
1199 	fd->type = FD_DTYPE(flags);
1200 /*
1201  * XXX I think using __i386__ is wrong here since we actually want to probe
1202  * for the machine type, not the CPU type (so non-PC arch's like the PC98 will
1203  * fail the probe).  However, for whatever reason, testing for _MACHINE_ARCH
1204  * == i386 breaks the test on FreeBSD/Alpha.
1205  */
1206 #ifdef __i386__
1207 	if (fd->type == FDT_NONE && (fd->fdu == 0 || fd->fdu == 1)) {
1208 		/* Look up what the BIOS thinks we have. */
1209 		if (fd->fdu == 0) {
1210 			if ((fdc->flags & FDC_ISPCMCIA))
1211 				/*
1212 				 * Somewhat special.  No need to force the
1213 				 * user to set device flags, since the Y-E
1214 				 * Data PCMCIA floppy is always a 1.44 MB
1215 				 * device.
1216 				 */
1217 				fd->type = FDT_144M;
1218 			else
1219 				fd->type = (rtcin(RTC_FDISKETTE) & 0xf0) >> 4;
1220 		} else {
1221 			fd->type = rtcin(RTC_FDISKETTE) & 0x0f;
1222 		}
1223 		if (fd->type == FDT_288M_1)
1224 			fd->type = FDT_288M;
1225 	}
1226 #endif /* __i386__ */
1227 	/* is there a unit? */
1228 	if (fd->type == FDT_NONE)
1229 		return (ENXIO);
1230 
1231 	/* select it */
1232 	set_motor(fdc, fdsu, TURNON);
1233 	fdc_reset(fdc);		/* XXX reset, then unreset, etc. */
1234 	DELAY(1000000);	/* 1 sec */
1235 
1236 	/* XXX This doesn't work before the first set_motor() */
1237 	if ((fdc->flags & FDC_HAS_FIFO) == 0  &&
1238 	    fdc->fdct == FDC_ENHANCED &&
1239 	    (device_get_flags(fdc->fdc_dev) & FDC_NO_FIFO) == 0 &&
1240 	    enable_fifo(fdc) == 0) {
1241 		device_printf(device_get_parent(dev),
1242 		    "FIFO enabled, %d bytes threshold\n", fifo_threshold);
1243 	}
1244 
1245 	if ((flags & FD_NO_PROBE) == 0) {
1246 		/* If we're at track 0 first seek inwards. */
1247 		if ((fd_sense_drive_status(fdc, &st3) == 0) &&
1248 		    (st3 & NE7_ST3_T0)) {
1249 			/* Seek some steps... */
1250 			if (fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1251 				/* ...wait a moment... */
1252 				DELAY(300000);
1253 				/* make ctrlr happy: */
1254 				fd_sense_int(fdc, 0, 0);
1255 			}
1256 		}
1257 
1258 		for (i = 0; i < 2; i++) {
1259 			/*
1260 			 * we must recalibrate twice, just in case the
1261 			 * heads have been beyond cylinder 76, since
1262 			 * most FDCs still barf when attempting to
1263 			 * recalibrate more than 77 steps
1264 			 */
1265 			/* go back to 0: */
1266 			if (fd_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1267 				/* a second being enough for full stroke seek*/
1268 				DELAY(i == 0 ? 1000000 : 300000);
1269 
1270 				/* anything responding? */
1271 				if (fd_sense_int(fdc, &st0, 0) == 0 &&
1272 				    (st0 & NE7_ST0_EC) == 0)
1273 					break; /* already probed succesfully */
1274 			}
1275 		}
1276 	}
1277 
1278 	set_motor(fdc, fdsu, TURNOFF);
1279 
1280 	if ((flags & FD_NO_PROBE) == 0 &&
1281 	    (st0 & NE7_ST0_EC) != 0) /* no track 0 -> no drive present */
1282 		return (ENXIO);
1283 
1284 	switch (fd->type) {
1285 	case FDT_12M:
1286 		device_set_desc(dev, "1200-KB 5.25\" drive");
1287 		fd->type = FDT_12M;
1288 		break;
1289 	case FDT_144M:
1290 		device_set_desc(dev, "1440-KB 3.5\" drive");
1291 		fd->type = FDT_144M;
1292 		break;
1293 	case FDT_288M:
1294 		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1295 		fd->type = FDT_288M;
1296 		break;
1297 	case FDT_360K:
1298 		device_set_desc(dev, "360-KB 5.25\" drive");
1299 		fd->type = FDT_360K;
1300 		break;
1301 	case FDT_720K:
1302 		device_set_desc(dev, "720-KB 3.5\" drive");
1303 		fd->type = FDT_720K;
1304 		break;
1305 	default:
1306 		return (ENXIO);
1307 	}
1308 	fd->track = FD_NO_TRACK;
1309 	fd->fdc = fdc;
1310 	fd->fdsu = fdsu;
1311 	fd->options = 0;
1312 	callout_handle_init(&fd->toffhandle);
1313 	callout_handle_init(&fd->tohandle);
1314 
1315 	/* initialize densities for subdevices */
1316 	for (i = 0; i < NUMDENS; i++)
1317 		memcpy(fd->fts + i, fd_native_types + fd->type,
1318 		       sizeof(struct fd_type));
1319 	return (0);
1320 }
1321 
1322 static int
1323 fd_attach(device_t dev)
1324 {
1325 	struct	fd_data *fd;
1326 	static	int cdevsw_add_done;
1327 	int i;
1328 
1329 	if (!cdevsw_add_done) {
1330 		cdevsw_add(&fd_cdevsw);	/* XXX */
1331 		cdevsw_add_done = 1;
1332 	}
1333 	fd = device_get_softc(dev);
1334 	fd->clonetag = EVENTHANDLER_REGISTER(dev_clone, fd_clone, fd, 1000);
1335 	fd->masterdev = make_dev(&fd_cdevsw, fd->fdu << 6,
1336 				 UID_ROOT, GID_OPERATOR, 0640, "fd%d", fd->fdu);
1337 	for (i = 0; i < NUMDENS - 1; i++)
1338 		fd->clonedevs[i] = NODEV;
1339 	devstat_add_entry(&fd->device_stats, device_get_name(dev),
1340 			  device_get_unit(dev), 0, DEVSTAT_NO_ORDERED_TAGS,
1341 			  DEVSTAT_TYPE_FLOPPY | DEVSTAT_TYPE_IF_OTHER,
1342 			  DEVSTAT_PRIORITY_FD);
1343 	return (0);
1344 }
1345 
1346 static int
1347 fd_detach(device_t dev)
1348 {
1349 	struct	fd_data *fd;
1350 	int i;
1351 
1352 	fd = device_get_softc(dev);
1353 	untimeout(fd_turnoff, fd, fd->toffhandle);
1354 	devstat_remove_entry(&fd->device_stats);
1355 	destroy_dev(fd->masterdev);
1356 	for (i = 0; i < NUMDENS - 1; i++)
1357 		if (fd->clonedevs[i] != NODEV)
1358 			destroy_dev(fd->clonedevs[i]);
1359 	cdevsw_remove(&fd_cdevsw);
1360 	EVENTHANDLER_DEREGISTER(dev_clone, fd->clonetag);
1361 
1362 	return (0);
1363 }
1364 
1365 static device_method_t fd_methods[] = {
1366 	/* Device interface */
1367 	DEVMETHOD(device_probe,		fd_probe),
1368 	DEVMETHOD(device_attach,	fd_attach),
1369 	DEVMETHOD(device_detach,	fd_detach),
1370 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1371 	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
1372 	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
1373 
1374 	{ 0, 0 }
1375 };
1376 
1377 static driver_t fd_driver = {
1378 	"fd",
1379 	fd_methods,
1380 	sizeof(struct fd_data)
1381 };
1382 
1383 DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, 0, 0);
1384 
1385 /*
1386  * More auxiliary functions.
1387  */
1388 /*
1389  * Motor control stuff.
1390  * Remember to not deselect the drive we're working on.
1391  */
1392 static void
1393 set_motor(struct fdc_data *fdc, int fdsu, int turnon)
1394 {
1395 	int fdout;
1396 
1397 	fdout = fdc->fdout;
1398 	if (turnon) {
1399 		fdout &= ~FDO_FDSEL;
1400 		fdout |= (FDO_MOEN0 << fdsu) | FDO_FDMAEN | FDO_FRST | fdsu;
1401 	} else
1402 		fdout &= ~(FDO_MOEN0 << fdsu);
1403 	fdc->fdout = fdout;
1404 	fdout_wr(fdc, fdout);
1405 	TRACE1("[0x%x->FDOUT]", fdout);
1406 }
1407 
1408 static void
1409 fd_turnoff(void *xfd)
1410 {
1411 	int	s;
1412 	fd_p fd = xfd;
1413 
1414 	TRACE1("[fd%d: turnoff]", fd->fdu);
1415 
1416 	s = splbio();
1417 	/*
1418 	 * Don't turn off the motor yet if the drive is active.
1419 	 *
1420 	 * If we got here, this could only mean we missed an interrupt.
1421 	 * This can e. g. happen on the Y-E Date PCMCIA floppy controller
1422 	 * after a controller reset.  Just schedule a pseudo-interrupt
1423 	 * so the state machine gets re-entered.
1424 	 */
1425 	if (fd->fdc->state != DEVIDLE && fd->fdc->fdu == fd->fdu) {
1426 		fdc_intr(fd->fdc);
1427 		splx(s);
1428 		return;
1429 	}
1430 
1431 	fd->flags &= ~FD_MOTOR;
1432 	set_motor(fd->fdc, fd->fdsu, TURNOFF);
1433 	splx(s);
1434 }
1435 
1436 static void
1437 fd_motor_on(void *xfd)
1438 {
1439 	int	s;
1440 	fd_p fd = xfd;
1441 
1442 	s = splbio();
1443 	fd->flags &= ~FD_MOTOR_WAIT;
1444 	if((fd->fdc->fd == fd) && (fd->fdc->state == MOTORWAIT))
1445 	{
1446 		fdc_intr(fd->fdc);
1447 	}
1448 	splx(s);
1449 }
1450 
1451 static void
1452 fd_turnon(fd_p fd)
1453 {
1454 	if(!(fd->flags & FD_MOTOR))
1455 	{
1456 		fd->flags |= (FD_MOTOR + FD_MOTOR_WAIT);
1457 		set_motor(fd->fdc, fd->fdsu, TURNON);
1458 		timeout(fd_motor_on, fd, hz); /* in 1 sec its ok */
1459 	}
1460 }
1461 
1462 static void
1463 fdc_reset(fdc_p fdc)
1464 {
1465 	/* Try a reset, keep motor on */
1466 	fdout_wr(fdc, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1467 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1468 	DELAY(100);
1469 	/* enable FDC, but defer interrupts a moment */
1470 	fdout_wr(fdc, fdc->fdout & ~FDO_FDMAEN);
1471 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~FDO_FDMAEN);
1472 	DELAY(100);
1473 	fdout_wr(fdc, fdc->fdout);
1474 	TRACE1("[0x%x->FDOUT]", fdc->fdout);
1475 
1476 	/* XXX after a reset, silently believe the FDC will accept commands */
1477 	(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1478 		     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1479 		     0);
1480 	if (fdc->flags & FDC_HAS_FIFO)
1481 		(void) enable_fifo(fdc);
1482 }
1483 
1484 /*
1485  * FDC IO functions, take care of the main status register, timeout
1486  * in case the desired status bits are never set.
1487  *
1488  * These PIO loops initially start out with short delays between
1489  * each iteration in the expectation that the required condition
1490  * is usually met quickly, so it can be handled immediately.  After
1491  * about 1 ms, stepping is increased to achieve a better timing
1492  * accuracy in the calls to DELAY().
1493  */
1494 static int
1495 fd_in(struct fdc_data *fdc, int *ptr)
1496 {
1497 	int i, j, step;
1498 
1499 	for (j = 0, step = 1;
1500 	    (i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM)) != (NE7_DIO|NE7_RQM) &&
1501 	    j < FDSTS_TIMEOUT;
1502 	    j += step) {
1503 		if (i == NE7_RQM)
1504 			return (fdc_err(fdc, "ready for output in input\n"));
1505 		if (j == 1000)
1506 			step = 1000;
1507 		DELAY(step);
1508 	}
1509 	if (j >= FDSTS_TIMEOUT)
1510 		return (fdc_err(fdc, bootverbose? "input ready timeout\n": 0));
1511 #ifdef	FDC_DEBUG
1512 	i = fddata_rd(fdc);
1513 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
1514 	*ptr = i;
1515 	return (0);
1516 #else	/* !FDC_DEBUG */
1517 	i = fddata_rd(fdc);
1518 	if (ptr)
1519 		*ptr = i;
1520 	return (0);
1521 #endif	/* FDC_DEBUG */
1522 }
1523 
1524 static int
1525 out_fdc(struct fdc_data *fdc, int x)
1526 {
1527 	int i, j, step;
1528 
1529 	for (j = 0, step = 1;
1530 	    (i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM)) != NE7_RQM &&
1531 	    j < FDSTS_TIMEOUT;
1532 	    j += step) {
1533 		if (i == (NE7_DIO|NE7_RQM))
1534 			return (fdc_err(fdc, "ready for input in output\n"));
1535 		if (j == 1000)
1536 			step = 1000;
1537 		DELAY(step);
1538 	}
1539 	if (j >= FDSTS_TIMEOUT)
1540 		return (fdc_err(fdc, bootverbose? "output ready timeout\n": 0));
1541 
1542 	/* Send the command and return */
1543 	fddata_wr(fdc, x);
1544 	TRACE1("[0x%x->FDDATA]", x);
1545 	return (0);
1546 }
1547 
1548 /*
1549  * Block device driver interface functions (interspersed with even more
1550  * auxiliary functions).
1551  */
1552 static int
1553 Fdopen(dev_t dev, int flags, int mode, struct thread *td)
1554 {
1555  	fdu_t fdu = FDUNIT(minor(dev));
1556 	int type = FDTYPE(minor(dev));
1557 	fd_p	fd;
1558 	fdc_p	fdc;
1559  	int rv, unitattn, dflags;
1560 
1561 	if ((fd = devclass_get_softc(fd_devclass, fdu)) == 0)
1562 		return (ENXIO);
1563 	fdc = fd->fdc;
1564 	if ((fdc == NULL) || (fd->type == FDT_NONE))
1565 		return (ENXIO);
1566 	if (type > NUMDENS)
1567 		return (ENXIO);
1568 	dflags = device_get_flags(fd->dev);
1569 	/*
1570 	 * This is a bit bogus.  It's still possible that e. g. a
1571 	 * descriptor gets inherited to a child, but then it's at
1572 	 * least for the same subdevice.  By checking FD_OPEN here, we
1573 	 * can ensure that a device isn't attempted to be opened with
1574 	 * different densities at the same time where the second open
1575 	 * could clobber the settings from the first one.
1576 	 */
1577 	if (fd->flags & FD_OPEN)
1578 		return (EBUSY);
1579 
1580 	if (type == 0) {
1581 		if (flags & FNONBLOCK) {
1582 			/*
1583 			 * Unfortunately, physio(9) discards its ioflag
1584 			 * argument, thus preventing us from seeing the
1585 			 * IO_NDELAY bit.  So we need to keep track
1586 			 * ourselves.
1587 			 */
1588 			fd->flags |= FD_NONBLOCK;
1589 			fd->ft = 0;
1590 		} else {
1591 			/*
1592 			 * Figure out a unit attention condition.
1593 			 *
1594 			 * If UA has been forced, proceed.
1595 			 *
1596 			 * If motor is off, turn it on for a moment
1597 			 * and select our drive, in order to read the
1598 			 * UA hardware signal.
1599 			 *
1600 			 * If motor is on, and our drive is currently
1601 			 * selected, just read the hardware bit.
1602 			 *
1603 			 * If motor is on, but active for another
1604 			 * drive on that controller, we are lost.  We
1605 			 * cannot risk to deselect the other drive, so
1606 			 * we just assume a forced UA condition to be
1607 			 * on the safe side.
1608 			 */
1609 			unitattn = 0;
1610 			if ((dflags & FD_NO_CHLINE) != 0 ||
1611 			    (fd->flags & FD_UA) != 0) {
1612 				unitattn = 1;
1613 				fd->flags &= ~FD_UA;
1614 			} else if (fdc->fdout & (FDO_MOEN0 | FDO_MOEN1 |
1615 						 FDO_MOEN2 | FDO_MOEN3)) {
1616 				if ((fdc->fdout & FDO_FDSEL) == fd->fdsu)
1617 					unitattn = fdin_rd(fdc) & FDI_DCHG;
1618 				else
1619 					unitattn = 1;
1620 			} else {
1621 				set_motor(fdc, fd->fdsu, TURNON);
1622 				unitattn = fdin_rd(fdc) & FDI_DCHG;
1623 				set_motor(fdc, fd->fdsu, TURNOFF);
1624 			}
1625 			if (unitattn && (rv = fdautoselect(dev)) != 0)
1626 				return (rv);
1627 		}
1628 	} else {
1629 		fd->ft = fd->fts + type;
1630 	}
1631 	fd->flags |= FD_OPEN;
1632 	/*
1633 	 * Clearing the DMA overrun counter at open time is a bit messy.
1634 	 * Since we're only managing one counter per controller, opening
1635 	 * the second drive could mess it up.  Anyway, if the DMA overrun
1636 	 * condition is really persistent, it will eventually time out
1637 	 * still.  OTOH, clearing it here will ensure we'll at least start
1638 	 * trying again after a previous (maybe even long ago) failure.
1639 	 * Also, this is merely a stop-gap measure only that should not
1640 	 * happen during normal operation, so we can tolerate it to be a
1641 	 * bit sloppy about this.
1642 	 */
1643 	fdc->dma_overruns = 0;
1644 
1645 	return 0;
1646 }
1647 
1648 static int
1649 fdclose(dev_t dev, int flags, int mode, struct thread *td)
1650 {
1651  	fdu_t fdu = FDUNIT(minor(dev));
1652 	struct fd_data *fd;
1653 
1654 	fd = devclass_get_softc(fd_devclass, fdu);
1655 	fd->flags &= ~(FD_OPEN | FD_NONBLOCK);
1656 	fd->options &= ~(FDOPT_NORETRY | FDOPT_NOERRLOG | FDOPT_NOERROR);
1657 
1658 	return (0);
1659 }
1660 
1661 static void
1662 fdstrategy(struct bio *bp)
1663 {
1664 	long blknum, nblocks;
1665  	int	s;
1666  	fdu_t	fdu;
1667  	fdc_p	fdc;
1668  	fd_p	fd;
1669 	size_t	fdblk;
1670 
1671  	fdu = FDUNIT(minor(bp->bio_dev));
1672 	fd = devclass_get_softc(fd_devclass, fdu);
1673 	if (fd == 0)
1674 		panic("fdstrategy: buf for nonexistent device (%#lx, %#lx)",
1675 		      (u_long)major(bp->bio_dev), (u_long)minor(bp->bio_dev));
1676 	fdc = fd->fdc;
1677 	if (fd->type == FDT_NONE || fd->ft == 0) {
1678 		bp->bio_error = ENXIO;
1679 		bp->bio_flags |= BIO_ERROR;
1680 		goto bad;
1681 	}
1682 	fdblk = 128 << (fd->ft->secsize);
1683 	if (bp->bio_cmd != FDBIO_FORMAT && bp->bio_cmd != FDBIO_RDSECTID) {
1684 		if (fd->flags & FD_NONBLOCK) {
1685 			bp->bio_error = EAGAIN;
1686 			bp->bio_flags |= BIO_ERROR;
1687 			goto bad;
1688 		}
1689 		if (bp->bio_blkno < 0) {
1690 			printf(
1691 		"fd%d: fdstrat: bad request blkno = %lu, bcount = %ld\n",
1692 			       fdu, (u_long)bp->bio_blkno, bp->bio_bcount);
1693 			bp->bio_error = EINVAL;
1694 			bp->bio_flags |= BIO_ERROR;
1695 			goto bad;
1696 		}
1697 		if ((bp->bio_bcount % fdblk) != 0) {
1698 			bp->bio_error = EINVAL;
1699 			bp->bio_flags |= BIO_ERROR;
1700 			goto bad;
1701 		}
1702 	}
1703 
1704 	/*
1705 	 * Set up block calculations.
1706 	 */
1707 	if (bp->bio_blkno > 20000000) {
1708 		/*
1709 		 * Reject unreasonably high block number, prevent the
1710 		 * multiplication below from overflowing.
1711 		 */
1712 		bp->bio_error = EINVAL;
1713 		bp->bio_flags |= BIO_ERROR;
1714 		goto bad;
1715 	}
1716 	blknum = bp->bio_blkno * DEV_BSIZE / fdblk;
1717  	nblocks = fd->ft->size;
1718 	if (blknum + bp->bio_bcount / fdblk > nblocks) {
1719 		if (blknum >= nblocks) {
1720 			if (bp->bio_cmd == BIO_READ)
1721 				bp->bio_resid = bp->bio_bcount;
1722 			else {
1723 				bp->bio_error = ENOSPC;
1724 				bp->bio_flags |= BIO_ERROR;
1725 			}
1726 			goto bad;	/* not always bad, but EOF */
1727 		}
1728 		bp->bio_bcount = (nblocks - blknum) * fdblk;
1729 	}
1730  	bp->bio_pblkno = blknum;
1731 	s = splbio();
1732 	bioqdisksort(&fdc->head, bp);
1733 	untimeout(fd_turnoff, fd, fd->toffhandle); /* a good idea */
1734 	devstat_start_transaction(&fd->device_stats);
1735 	device_busy(fd->dev);
1736 	fdstart(fdc);
1737 	splx(s);
1738 	return;
1739 
1740 bad:
1741 	biodone(bp);
1742 }
1743 
1744 /*
1745  * fdstart
1746  *
1747  * We have just queued something.  If the controller is not busy
1748  * then simulate the case where it has just finished a command
1749  * So that it (the interrupt routine) looks on the queue for more
1750  * work to do and picks up what we just added.
1751  *
1752  * If the controller is already busy, we need do nothing, as it
1753  * will pick up our work when the present work completes.
1754  */
1755 static void
1756 fdstart(struct fdc_data *fdc)
1757 {
1758 	int s;
1759 
1760 	s = splbio();
1761 	if(fdc->state == DEVIDLE)
1762 	{
1763 		fdc_intr(fdc);
1764 	}
1765 	splx(s);
1766 }
1767 
1768 static void
1769 fd_iotimeout(void *xfdc)
1770 {
1771  	fdc_p fdc;
1772 	int s;
1773 
1774 	fdc = xfdc;
1775 	TRACE1("fd%d[fd_iotimeout()]", fdc->fdu);
1776 
1777 	/*
1778 	 * Due to IBM's brain-dead design, the FDC has a faked ready
1779 	 * signal, hardwired to ready == true. Thus, any command
1780 	 * issued if there's no diskette in the drive will _never_
1781 	 * complete, and must be aborted by resetting the FDC.
1782 	 * Many thanks, Big Blue!
1783 	 * The FDC must not be reset directly, since that would
1784 	 * interfere with the state machine.  Instead, pretend that
1785 	 * the command completed but was invalid.  The state machine
1786 	 * will reset the FDC and retry once.
1787 	 */
1788 	s = splbio();
1789 	fdc->status[0] = NE7_ST0_IC_IV;
1790 	fdc->flags &= ~FDC_STAT_VALID;
1791 	fdc->state = IOTIMEDOUT;
1792 	fdc_intr(fdc);
1793 	splx(s);
1794 }
1795 
1796 /* Just ensure it has the right spl. */
1797 static void
1798 fd_pseudointr(void *xfdc)
1799 {
1800 	int	s;
1801 
1802 	s = splbio();
1803 	fdc_intr(xfdc);
1804 	splx(s);
1805 }
1806 
1807 /*
1808  * fdc_intr
1809  *
1810  * Keep calling the state machine until it returns a 0.
1811  * Always called at splbio.
1812  */
1813 static void
1814 fdc_intr(void *xfdc)
1815 {
1816 	fdc_p fdc = xfdc;
1817 	while(fdstate(fdc))
1818 		;
1819 }
1820 
1821 /*
1822  * Magic pseudo-DMA initialization for YE FDC. Sets count and
1823  * direction.
1824  */
1825 #define SET_BCDR(fdc,wr,cnt,port) \
1826 	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port,	 \
1827 	    ((cnt)-1) & 0xff);						 \
1828 	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port + 1, \
1829 	    ((wr ? 0x80 : 0) | ((((cnt)-1) >> 8) & 0x7f)));
1830 
1831 /*
1832  * fdcpio(): perform programmed IO read/write for YE PCMCIA floppy.
1833  */
1834 static int
1835 fdcpio(fdc_p fdc, long flags, caddr_t addr, u_int count)
1836 {
1837 	u_char *cptr = (u_char *)addr;
1838 
1839 	if (flags == BIO_READ) {
1840 		if (fdc->state != PIOREAD) {
1841 			fdc->state = PIOREAD;
1842 			return(0);
1843 		}
1844 		SET_BCDR(fdc, 0, count, 0);
1845 		bus_space_read_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1846 		    FDC_YE_DATAPORT, cptr, count);
1847 	} else {
1848 		bus_space_write_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1849 		    FDC_YE_DATAPORT, cptr, count);
1850 		SET_BCDR(fdc, 0, count, 0);
1851 	}
1852 	return(1);
1853 }
1854 
1855 /*
1856  * Try figuring out the density of the media present in our device.
1857  */
1858 static int
1859 fdautoselect(dev_t dev)
1860 {
1861 	fdu_t fdu;
1862  	fd_p fd;
1863 	struct fd_type *fdtp;
1864 	struct fdc_readid id;
1865 	int i, n, oopts, rv;
1866 
1867  	fdu = FDUNIT(minor(dev));
1868 	fd = devclass_get_softc(fd_devclass, fdu);
1869 
1870 	switch (fd->type) {
1871 	default:
1872 		return (ENXIO);
1873 
1874 	case FDT_360K:
1875 	case FDT_720K:
1876 		/* no autoselection on those drives */
1877 		fd->ft = fd_native_types + fd->type;
1878 		return (0);
1879 
1880 	case FDT_12M:
1881 		fdtp = fd_searchlist_12m;
1882 		n = sizeof fd_searchlist_12m / sizeof(struct fd_type);
1883 		break;
1884 
1885 	case FDT_144M:
1886 		fdtp = fd_searchlist_144m;
1887 		n = sizeof fd_searchlist_144m / sizeof(struct fd_type);
1888 		break;
1889 
1890 	case FDT_288M:
1891 		fdtp = fd_searchlist_288m;
1892 		n = sizeof fd_searchlist_288m / sizeof(struct fd_type);
1893 		break;
1894 	}
1895 
1896 	/*
1897 	 * Try reading sector ID fields, first at cylinder 0, head 0,
1898 	 * then at cylinder 2, head N.  We don't probe cylinder 1,
1899 	 * since for 5.25in DD media in a HD drive, there are no data
1900 	 * to read (2 step pulses per media cylinder required).  For
1901 	 * two-sided media, the second probe always goes to head 1, so
1902 	 * we can tell them apart from single-sided media.  As a
1903 	 * side-effect this means that single-sided media should be
1904 	 * mentioned in the search list after two-sided media of an
1905 	 * otherwise identical density.  Media with a different number
1906 	 * of sectors per track but otherwise identical parameters
1907 	 * cannot be distinguished at all.
1908 	 *
1909 	 * If we successfully read an ID field on both cylinders where
1910 	 * the recorded values match our expectation, we are done.
1911 	 * Otherwise, we try the next density entry from the table.
1912 	 *
1913 	 * Stepping to cylinder 2 has the side-effect of clearing the
1914 	 * unit attention bit.
1915 	 */
1916 	oopts = fd->options;
1917 	fd->options |= FDOPT_NOERRLOG | FDOPT_NORETRY;
1918 	for (i = 0; i < n; i++, fdtp++) {
1919 		fd->ft = fdtp;
1920 
1921 		id.cyl = id.head = 0;
1922 		rv = fdmisccmd(dev, FDBIO_RDSECTID, &id);
1923 		if (rv != 0)
1924 			continue;
1925 		if (id.cyl != 0 || id.head != 0 ||
1926 		    id.secshift != fdtp->secsize)
1927 			continue;
1928 		id.cyl = 2;
1929 		id.head = fd->ft->heads - 1;
1930 		rv = fdmisccmd(dev, FDBIO_RDSECTID, &id);
1931 		if (id.cyl != 2 || id.head != fdtp->heads - 1 ||
1932 		    id.secshift != fdtp->secsize)
1933 			continue;
1934 		if (rv == 0)
1935 			break;
1936 	}
1937 
1938 	fd->options = oopts;
1939 	if (i == n) {
1940 		if (bootverbose)
1941 			device_printf(fd->dev, "autoselection failed\n");
1942 		fd->ft = 0;
1943 		return (EIO);
1944 	} else {
1945 		if (bootverbose)
1946 			device_printf(fd->dev, "autoselected %d KB medium\n",
1947 				      fd->ft->size / 2);
1948 		return (0);
1949 	}
1950 }
1951 
1952 
1953 /*
1954  * The controller state machine.
1955  *
1956  * If it returns a non zero value, it should be called again immediately.
1957  */
1958 static int
1959 fdstate(fdc_p fdc)
1960 {
1961 	struct fdc_readid *idp;
1962 	int read, format, rdsectid, cylinder, head, i, sec = 0, sectrac;
1963 	int st0, cyl, st3, idf, ne7cmd, mfm, steptrac;
1964 	unsigned long blknum;
1965 	fdu_t fdu = fdc->fdu;
1966 	fd_p fd;
1967 	register struct bio *bp;
1968 	struct fd_formb *finfo = NULL;
1969 	size_t fdblk;
1970 
1971 	bp = fdc->bp;
1972 	if (bp == NULL) {
1973 		bp = bioq_first(&fdc->head);
1974 		if (bp != NULL) {
1975 			bioq_remove(&fdc->head, bp);
1976 			fdc->bp = bp;
1977 		}
1978 	}
1979 	if (bp == NULL) {
1980 		/*
1981 		 * Nothing left for this controller to do,
1982 		 * force into the IDLE state.
1983 		 */
1984 		fdc->state = DEVIDLE;
1985 		if (fdc->fd) {
1986 			device_printf(fdc->fdc_dev,
1987 			    "unexpected valid fd pointer\n");
1988 			fdc->fd = (fd_p) 0;
1989 			fdc->fdu = -1;
1990 		}
1991 		TRACE1("[fdc%d IDLE]", fdc->fdcu);
1992  		return (0);
1993 	}
1994 	fdu = FDUNIT(minor(bp->bio_dev));
1995 	fd = devclass_get_softc(fd_devclass, fdu);
1996 	fdblk = 128 << fd->ft->secsize;
1997 	if (fdc->fd && (fd != fdc->fd))
1998 		device_printf(fd->dev, "confused fd pointers\n");
1999 	read = bp->bio_cmd == BIO_READ;
2000 	mfm = (fd->ft->flags & FL_MFM)? NE7CMD_MFM: 0;
2001 	steptrac = (fd->ft->flags & FL_2STEP)? 2: 1;
2002 	if (read)
2003 		idf = ISADMA_READ;
2004 	else
2005 		idf = ISADMA_WRITE;
2006 	format = bp->bio_cmd == FDBIO_FORMAT;
2007 	rdsectid = bp->bio_cmd == FDBIO_RDSECTID;
2008 	if (format)
2009 		finfo = (struct fd_formb *)bp->bio_data;
2010 	TRACE1("fd%d", fdu);
2011 	TRACE1("[%s]", fdstates[fdc->state]);
2012 	TRACE1("(0x%x)", fd->flags);
2013 	untimeout(fd_turnoff, fd, fd->toffhandle);
2014 	fd->toffhandle = timeout(fd_turnoff, fd, 4 * hz);
2015 	switch (fdc->state)
2016 	{
2017 	case DEVIDLE:
2018 	case FINDWORK:	/* we have found new work */
2019 		fdc->retry = 0;
2020 		fd->skip = 0;
2021 		fdc->fd = fd;
2022 		fdc->fdu = fdu;
2023 		fdc->fdctl_wr(fdc, fd->ft->trans);
2024 		TRACE1("[0x%x->FDCTL]", fd->ft->trans);
2025 		/*
2026 		 * If the next drive has a motor startup pending, then
2027 		 * it will start up in its own good time.
2028 		 */
2029 		if(fd->flags & FD_MOTOR_WAIT) {
2030 			fdc->state = MOTORWAIT;
2031 			return (0); /* will return later */
2032 		}
2033 		/*
2034 		 * Maybe if it's not starting, it SHOULD be starting.
2035 		 */
2036 		if (!(fd->flags & FD_MOTOR))
2037 		{
2038 			fdc->state = MOTORWAIT;
2039 			fd_turnon(fd);
2040 			return (0); /* will return later */
2041 		}
2042 		else	/* at least make sure we are selected */
2043 		{
2044 			set_motor(fdc, fd->fdsu, TURNON);
2045 		}
2046 		if (fdc->flags & FDC_NEEDS_RESET) {
2047 			fdc->state = RESETCTLR;
2048 			fdc->flags &= ~FDC_NEEDS_RESET;
2049 		} else
2050 			fdc->state = DOSEEK;
2051 		return (1);	/* will return immediately */
2052 
2053 	case DOSEEK:
2054 		blknum = bp->bio_pblkno + fd->skip / fdblk;
2055 		cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
2056 		if (cylinder == fd->track)
2057 		{
2058 			fdc->state = SEEKCOMPLETE;
2059 			return (1); /* will return immediately */
2060 		}
2061 		if (fd_cmd(fdc, 3, NE7CMD_SEEK,
2062 			   fd->fdsu, cylinder * steptrac, 0))
2063 		{
2064 			/*
2065 			 * Seek command not accepted, looks like
2066 			 * the FDC went off to the Saints...
2067 			 */
2068 			fdc->retry = 6;	/* try a reset */
2069 			return(retrier(fdc));
2070 		}
2071 		fd->track = FD_NO_TRACK;
2072 		fdc->state = SEEKWAIT;
2073 		return(0);	/* will return later */
2074 
2075 	case SEEKWAIT:
2076 		/* allow heads to settle */
2077 		timeout(fd_pseudointr, fdc, hz / 16);
2078 		fdc->state = SEEKCOMPLETE;
2079 		return(0);	/* will return later */
2080 
2081 	case SEEKCOMPLETE : /* seek done, start DMA */
2082 		blknum = bp->bio_pblkno + fd->skip / fdblk;
2083 		cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
2084 
2085 		/* Make sure seek really happened. */
2086 		if(fd->track == FD_NO_TRACK) {
2087 			int descyl = cylinder * steptrac;
2088 			do {
2089 				/*
2090 				 * This might be a "ready changed" interrupt,
2091 				 * which cannot really happen since the
2092 				 * RDY pin is hardwired to + 5 volts.  This
2093 				 * generally indicates a "bouncing" intr
2094 				 * line, so do one of the following:
2095 				 *
2096 				 * When running on an enhanced FDC that is
2097 				 * known to not go stuck after responding
2098 				 * with INVALID, fetch all interrupt states
2099 				 * until seeing either an INVALID or a
2100 				 * real interrupt condition.
2101 				 *
2102 				 * When running on a dumb old NE765, give
2103 				 * up immediately.  The controller will
2104 				 * provide up to four dummy RC interrupt
2105 				 * conditions right after reset (for the
2106 				 * corresponding four drives), so this is
2107 				 * our only chance to get notice that it
2108 				 * was not the FDC that caused the interrupt.
2109 				 */
2110 				if (fd_sense_int(fdc, &st0, &cyl)
2111 				    == FD_NOT_VALID)
2112 					return (0); /* will return later */
2113 				if(fdc->fdct == FDC_NE765
2114 				   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2115 					return (0); /* hope for a real intr */
2116 			} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2117 
2118 			if (0 == descyl) {
2119 				int failed = 0;
2120 				/*
2121 				 * seek to cyl 0 requested; make sure we are
2122 				 * really there
2123 				 */
2124 				if (fd_sense_drive_status(fdc, &st3))
2125 					failed = 1;
2126 				if ((st3 & NE7_ST3_T0) == 0) {
2127 					printf(
2128 		"fd%d: Seek to cyl 0, but not really there (ST3 = %b)\n",
2129 					       fdu, st3, NE7_ST3BITS);
2130 					failed = 1;
2131 				}
2132 
2133 				if (failed) {
2134 					if(fdc->retry < 3)
2135 						fdc->retry = 3;
2136 					return (retrier(fdc));
2137 				}
2138 			}
2139 
2140 			if (cyl != descyl) {
2141 				printf(
2142 		"fd%d: Seek to cyl %d failed; am at cyl %d (ST0 = 0x%x)\n",
2143 				       fdu, descyl, cyl, st0);
2144 				if (fdc->retry < 3)
2145 					fdc->retry = 3;
2146 				return (retrier(fdc));
2147 			}
2148 		}
2149 
2150 		fd->track = cylinder;
2151 		if (format)
2152 			fd->skip = (char *)&(finfo->fd_formb_cylno(0))
2153 			    - (char *)finfo;
2154 		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2155 			isa_dmastart(idf, bp->bio_data+fd->skip,
2156 				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2157 		blknum = bp->bio_pblkno + fd->skip / fdblk;
2158 		sectrac = fd->ft->sectrac;
2159 		sec = blknum %  (sectrac * fd->ft->heads);
2160 		head = sec / sectrac;
2161 		sec = sec % sectrac + 1;
2162 		if (head != 0 && fd->ft->offset_side2 != 0)
2163 			sec += fd->ft->offset_side2;
2164 		fd->hddrv = ((head&1)<<2)+fdu;
2165 
2166 		if(format || !(read || rdsectid))
2167 		{
2168 			/* make sure the drive is writable */
2169 			if(fd_sense_drive_status(fdc, &st3) != 0)
2170 			{
2171 				/* stuck controller? */
2172 				if (!(fdc->flags & FDC_NODMA))
2173 					isa_dmadone(idf,
2174 						    bp->bio_data + fd->skip,
2175 						    format ? bp->bio_bcount : fdblk,
2176 						    fdc->dmachan);
2177 				fdc->retry = 6;	/* reset the beast */
2178 				return (retrier(fdc));
2179 			}
2180 			if(st3 & NE7_ST3_WP)
2181 			{
2182 				/*
2183 				 * XXX YES! this is ugly.
2184 				 * in order to force the current operation
2185 				 * to fail, we will have to fake an FDC
2186 				 * error - all error handling is done
2187 				 * by the retrier()
2188 				 */
2189 				fdc->status[0] = NE7_ST0_IC_AT;
2190 				fdc->status[1] = NE7_ST1_NW;
2191 				fdc->status[2] = 0;
2192 				fdc->status[3] = fd->track;
2193 				fdc->status[4] = head;
2194 				fdc->status[5] = sec;
2195 				fdc->retry = 8;	/* break out immediately */
2196 				fdc->state = IOTIMEDOUT; /* not really... */
2197 				return (1); /* will return immediately */
2198 			}
2199 		}
2200 
2201 		if (format) {
2202 			ne7cmd = NE7CMD_FORMAT | mfm;
2203 			if (fdc->flags & FDC_NODMA) {
2204 				/*
2205 				 * This seems to be necessary for
2206 				 * whatever obscure reason; if we omit
2207 				 * it, we end up filling the sector ID
2208 				 * fields of the newly formatted track
2209 				 * entirely with garbage, causing
2210 				 * `wrong cylinder' errors all over
2211 				 * the place when trying to read them
2212 				 * back.
2213 				 *
2214 				 * Umpf.
2215 				 */
2216 				SET_BCDR(fdc, 1, bp->bio_bcount, 0);
2217 
2218 				(void)fdcpio(fdc,bp->bio_cmd,
2219 					bp->bio_data+fd->skip,
2220 					bp->bio_bcount);
2221 
2222 			}
2223 			/* formatting */
2224 			if(fd_cmd(fdc, 6,  ne7cmd, head << 2 | fdu,
2225 				  finfo->fd_formb_secshift,
2226 				  finfo->fd_formb_nsecs,
2227 				  finfo->fd_formb_gaplen,
2228 				  finfo->fd_formb_fillbyte, 0)) {
2229 				/* controller fell over */
2230 				if (!(fdc->flags & FDC_NODMA))
2231 					isa_dmadone(idf,
2232 						    bp->bio_data + fd->skip,
2233 						    format ? bp->bio_bcount : fdblk,
2234 						    fdc->dmachan);
2235 				fdc->retry = 6;
2236 				return (retrier(fdc));
2237 			}
2238 		} else if (rdsectid) {
2239 			ne7cmd = NE7CMD_READID | mfm;
2240 			if (fd_cmd(fdc, 2, ne7cmd, head << 2 | fdu, 0)) {
2241 				/* controller jamming */
2242 				fdc->retry = 6;
2243 				return (retrier(fdc));
2244 			}
2245 		} else {
2246 			/* read or write operation */
2247 			ne7cmd = (read ? NE7CMD_READ | NE7CMD_SK : NE7CMD_WRITE) | mfm;
2248 			if (fdc->flags & FDC_NODMA) {
2249 				/*
2250 				 * This seems to be necessary even when
2251 				 * reading data.
2252 				 */
2253 				SET_BCDR(fdc, 1, fdblk, 0);
2254 
2255 				/*
2256 				 * Perform the write pseudo-DMA before
2257 				 * the WRITE command is sent.
2258 				 */
2259 				if (!read)
2260 					(void)fdcpio(fdc,bp->bio_cmd,
2261 					    bp->bio_data+fd->skip,
2262 					    fdblk);
2263 			}
2264 			if (fd_cmd(fdc, 9,
2265 				   ne7cmd,
2266 				   head << 2 | fdu,  /* head & unit */
2267 				   fd->track,        /* track */
2268 				   head,
2269 				   sec,              /* sector + 1 */
2270 				   fd->ft->secsize,  /* sector size */
2271 				   sectrac,          /* sectors/track */
2272 				   fd->ft->gap,      /* gap size */
2273 				   fd->ft->datalen,  /* data length */
2274 				   0)) {
2275 				/* the beast is sleeping again */
2276 				if (!(fdc->flags & FDC_NODMA))
2277 					isa_dmadone(idf,
2278 						    bp->bio_data + fd->skip,
2279 						    format ? bp->bio_bcount : fdblk,
2280 						    fdc->dmachan);
2281 				fdc->retry = 6;
2282 				return (retrier(fdc));
2283 			}
2284 		}
2285 		if (!rdsectid && (fdc->flags & FDC_NODMA))
2286 			/*
2287 			 * If this is a read, then simply await interrupt
2288 			 * before performing PIO.
2289 			 */
2290 			if (read && !fdcpio(fdc,bp->bio_cmd,
2291 			    bp->bio_data+fd->skip,fdblk)) {
2292 				fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2293 				return(0);      /* will return later */
2294 			}
2295 
2296 		/*
2297 		 * Write (or format) operation will fall through and
2298 		 * await completion interrupt.
2299 		 */
2300 		fdc->state = IOCOMPLETE;
2301 		fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2302 		return (0);	/* will return later */
2303 
2304 	case PIOREAD:
2305 		/*
2306 		 * Actually perform the PIO read.  The IOCOMPLETE case
2307 		 * removes the timeout for us.
2308 		 */
2309 		(void)fdcpio(fdc,bp->bio_cmd,bp->bio_data+fd->skip,fdblk);
2310 		fdc->state = IOCOMPLETE;
2311 		/* FALLTHROUGH */
2312 	case IOCOMPLETE: /* IO done, post-analyze */
2313 		untimeout(fd_iotimeout, fdc, fd->tohandle);
2314 
2315 		if (fd_read_status(fdc)) {
2316 			if (!rdsectid && !(fdc->flags & FDC_NODMA))
2317 				isa_dmadone(idf, bp->bio_data + fd->skip,
2318 					    format ? bp->bio_bcount : fdblk,
2319 					    fdc->dmachan);
2320 			if (fdc->retry < 6)
2321 				fdc->retry = 6;	/* force a reset */
2322 			return (retrier(fdc));
2323   		}
2324 
2325 		fdc->state = IOTIMEDOUT;
2326 
2327 		/* FALLTHROUGH */
2328 	case IOTIMEDOUT:
2329 		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2330 			isa_dmadone(idf, bp->bio_data + fd->skip,
2331 				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2332 		if (fdc->status[0] & NE7_ST0_IC) {
2333                         if ((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2334 			    && fdc->status[1] & NE7_ST1_OR) {
2335                                 /*
2336 				 * DMA overrun. Someone hogged the bus and
2337 				 * didn't release it in time for the next
2338 				 * FDC transfer.
2339 				 *
2340 				 * We normally restart this without bumping
2341 				 * the retry counter.  However, in case
2342 				 * something is seriously messed up (like
2343 				 * broken hardware), we rather limit the
2344 				 * number of retries so the IO operation
2345 				 * doesn't block indefinately.
2346 				 */
2347 				if (fdc->dma_overruns++ < FDC_DMAOV_MAX) {
2348 					fdc->state = SEEKCOMPLETE;
2349 					return (1);/* will return immediately */
2350 				} /* else fall through */
2351                         }
2352 			if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_IV
2353 				&& fdc->retry < 6)
2354 				fdc->retry = 6;	/* force a reset */
2355 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2356 				&& fdc->status[2] & NE7_ST2_WC
2357 				&& fdc->retry < 3)
2358 				fdc->retry = 3;	/* force recalibrate */
2359 			return (retrier(fdc));
2360 		}
2361 		/* All OK */
2362 		if (rdsectid) {
2363 			/* copy out ID field contents */
2364 			idp = (struct fdc_readid *)bp->bio_data;
2365 			idp->cyl = fdc->status[3];
2366 			idp->head = fdc->status[4];
2367 			idp->sec = fdc->status[5];
2368 			idp->secshift = fdc->status[6];
2369 		}
2370 		/* Operation successful, retry DMA overruns again next time. */
2371 		fdc->dma_overruns = 0;
2372 		fd->skip += fdblk;
2373 		if (!rdsectid && !format && fd->skip < bp->bio_bcount) {
2374 			/* set up next transfer */
2375 			fdc->state = DOSEEK;
2376 		} else {
2377 			/* ALL DONE */
2378 			fd->skip = 0;
2379 			bp->bio_resid = 0;
2380 			fdc->bp = NULL;
2381 			device_unbusy(fd->dev);
2382 			biofinish(bp, &fd->device_stats, 0);
2383 			fdc->fd = (fd_p) 0;
2384 			fdc->fdu = -1;
2385 			fdc->state = FINDWORK;
2386 		}
2387 		return (1);	/* will return immediately */
2388 
2389 	case RESETCTLR:
2390 		fdc_reset(fdc);
2391 		fdc->retry++;
2392 		fdc->state = RESETCOMPLETE;
2393 		return (0);	/* will return later */
2394 
2395 	case RESETCOMPLETE:
2396 		/*
2397 		 * Discard all the results from the reset so that they
2398 		 * can't cause an unexpected interrupt later.
2399 		 */
2400 		for (i = 0; i < 4; i++)
2401 			(void)fd_sense_int(fdc, &st0, &cyl);
2402 		fdc->state = STARTRECAL;
2403 		/* FALLTHROUGH */
2404 	case STARTRECAL:
2405 		if(fd_cmd(fdc, 2, NE7CMD_RECAL, fdu, 0)) {
2406 			/* arrgl */
2407 			fdc->retry = 6;
2408 			return (retrier(fdc));
2409 		}
2410 		fdc->state = RECALWAIT;
2411 		return (0);	/* will return later */
2412 
2413 	case RECALWAIT:
2414 		/* allow heads to settle */
2415 		timeout(fd_pseudointr, fdc, hz / 8);
2416 		fdc->state = RECALCOMPLETE;
2417 		return (0);	/* will return later */
2418 
2419 	case RECALCOMPLETE:
2420 		do {
2421 			/*
2422 			 * See SEEKCOMPLETE for a comment on this:
2423 			 */
2424 			if (fd_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
2425 				return (0); /* will return later */
2426 			if(fdc->fdct == FDC_NE765
2427 			   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2428 				return (0); /* hope for a real intr */
2429 		} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2430 		if ((st0 & NE7_ST0_IC) != NE7_ST0_IC_NT || cyl != 0)
2431 		{
2432 			if(fdc->retry > 3)
2433 				/*
2434 				 * A recalibrate from beyond cylinder 77
2435 				 * will "fail" due to the FDC limitations;
2436 				 * since people used to complain much about
2437 				 * the failure message, try not logging
2438 				 * this one if it seems to be the first
2439 				 * time in a line.
2440 				 */
2441 				printf("fd%d: recal failed ST0 %b cyl %d\n",
2442 				       fdu, st0, NE7_ST0BITS, cyl);
2443 			if(fdc->retry < 3) fdc->retry = 3;
2444 			return (retrier(fdc));
2445 		}
2446 		fd->track = 0;
2447 		/* Seek (probably) necessary */
2448 		fdc->state = DOSEEK;
2449 		return (1);	/* will return immediately */
2450 
2451 	case MOTORWAIT:
2452 		if(fd->flags & FD_MOTOR_WAIT)
2453 		{
2454 			return (0); /* time's not up yet */
2455 		}
2456 		if (fdc->flags & FDC_NEEDS_RESET) {
2457 			fdc->state = RESETCTLR;
2458 			fdc->flags &= ~FDC_NEEDS_RESET;
2459 		} else
2460 			fdc->state = DOSEEK;
2461 		return (1);	/* will return immediately */
2462 
2463 	default:
2464 		device_printf(fdc->fdc_dev, "unexpected FD int->");
2465 		if (fd_read_status(fdc) == 0)
2466 			printf("FDC status :%x %x %x %x %x %x %x   ",
2467 			       fdc->status[0],
2468 			       fdc->status[1],
2469 			       fdc->status[2],
2470 			       fdc->status[3],
2471 			       fdc->status[4],
2472 			       fdc->status[5],
2473 			       fdc->status[6] );
2474 		else
2475 			printf("No status available   ");
2476 		if (fd_sense_int(fdc, &st0, &cyl) != 0)
2477 		{
2478 			printf("[controller is dead now]\n");
2479 			return (0); /* will return later */
2480 		}
2481 		printf("ST0 = %x, PCN = %x\n", st0, cyl);
2482 		return (0);	/* will return later */
2483 	}
2484 	/* noone should ever get here */
2485 }
2486 
2487 static int
2488 retrier(struct fdc_data *fdc)
2489 {
2490 	struct bio *bp;
2491 	struct fd_data *fd;
2492 	int fdu;
2493 
2494 	bp = fdc->bp;
2495 
2496 	/* XXX shouldn't this be cached somewhere?  */
2497 	fdu = FDUNIT(minor(bp->bio_dev));
2498 	fd = devclass_get_softc(fd_devclass, fdu);
2499 	if (fd->options & FDOPT_NORETRY)
2500 		goto fail;
2501 
2502 	switch (fdc->retry) {
2503 	case 0: case 1: case 2:
2504 		fdc->state = SEEKCOMPLETE;
2505 		break;
2506 	case 3: case 4: case 5:
2507 		fdc->state = STARTRECAL;
2508 		break;
2509 	case 6:
2510 		fdc->state = RESETCTLR;
2511 		break;
2512 	case 7:
2513 		break;
2514 	default:
2515 	fail:
2516 		if ((fd->options & FDOPT_NOERRLOG) == 0) {
2517 			disk_err(bp, "hard error",
2518 			    fdc->fd->skip / DEV_BSIZE, 0);
2519 			if (fdc->flags & FDC_STAT_VALID) {
2520 				printf(
2521 				" (ST0 %b ST1 %b ST2 %b cyl %u hd %u sec %u)\n",
2522 				       fdc->status[0], NE7_ST0BITS,
2523 				       fdc->status[1], NE7_ST1BITS,
2524 				       fdc->status[2], NE7_ST2BITS,
2525 				       fdc->status[3], fdc->status[4],
2526 				       fdc->status[5]);
2527 			}
2528 			else
2529 				printf(" (No status)\n");
2530 		}
2531 		if ((fd->options & FDOPT_NOERROR) == 0) {
2532 			bp->bio_flags |= BIO_ERROR;
2533 			bp->bio_error = EIO;
2534 			bp->bio_resid = bp->bio_bcount - fdc->fd->skip;
2535 		} else
2536 			bp->bio_resid = 0;
2537 		fdc->bp = NULL;
2538 		fdc->fd->skip = 0;
2539 		device_unbusy(fd->dev);
2540 		biofinish(bp, &fdc->fd->device_stats, 0);
2541 		fdc->state = FINDWORK;
2542 		fdc->flags |= FDC_NEEDS_RESET;
2543 		fdc->fd = (fd_p) 0;
2544 		fdc->fdu = -1;
2545 		return (1);
2546 	}
2547 	fdc->retry++;
2548 	return (1);
2549 }
2550 
2551 static void
2552 fdbiodone(struct bio *bp)
2553 {
2554 	wakeup(bp);
2555 }
2556 
2557 static int
2558 fdmisccmd(dev_t dev, u_int cmd, void *data)
2559 {
2560  	fdu_t fdu;
2561  	fd_p fd;
2562 	struct bio *bp;
2563 	struct fd_formb *finfo;
2564 	struct fdc_readid *idfield;
2565 	size_t fdblk;
2566 	int error;
2567 
2568  	fdu = FDUNIT(minor(dev));
2569 	fd = devclass_get_softc(fd_devclass, fdu);
2570 	fdblk = 128 << fd->ft->secsize;
2571 	finfo = (struct fd_formb *)data;
2572 	idfield = (struct fdc_readid *)data;
2573 
2574 	bp = malloc(sizeof(struct bio), M_TEMP, M_ZERO);
2575 
2576 	/*
2577 	 * Set up a bio request for fdstrategy().  bio_blkno is faked
2578 	 * so that fdstrategy() will seek to the the requested
2579 	 * cylinder, and use the desired head.
2580 	 */
2581 	bp->bio_cmd = cmd;
2582 	if (cmd == FDBIO_FORMAT) {
2583 		bp->bio_blkno =
2584 		    (finfo->cyl * (fd->ft->sectrac * fd->ft->heads) +
2585 		     finfo->head * fd->ft->sectrac) *
2586 		    fdblk / DEV_BSIZE;
2587 		bp->bio_bcount = sizeof(struct fd_idfield_data) *
2588 		    finfo->fd_formb_nsecs;
2589 	} else if (cmd == FDBIO_RDSECTID) {
2590 		bp->bio_blkno =
2591 		    (idfield->cyl * (fd->ft->sectrac * fd->ft->heads) +
2592 		     idfield->head * fd->ft->sectrac) *
2593 		    fdblk / DEV_BSIZE;
2594 		bp->bio_bcount = sizeof(struct fdc_readid);
2595 	} else
2596 		panic("wrong cmd in fdmisccmd()");
2597 	bp->bio_data = data;
2598 	bp->bio_dev = dev;
2599 	bp->bio_done = fdbiodone;
2600 	bp->bio_flags = 0;
2601 
2602 	/* Now run the command. */
2603 	fdstrategy(bp);
2604 	error = biowait(bp, "fdcmd");
2605 
2606 	free(bp, M_TEMP);
2607 	return (error);
2608 }
2609 
2610 static int
2611 fdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
2612 {
2613  	fdu_t fdu;
2614  	fd_p fd;
2615 	struct fdc_status *fsp;
2616 	struct fdc_readid *rid;
2617 	size_t fdblk;
2618 	int error, type;
2619 
2620  	fdu = FDUNIT(minor(dev));
2621 	type = FDTYPE(minor(dev));
2622  	fd = devclass_get_softc(fd_devclass, fdu);
2623 
2624 	/*
2625 	 * First, handle everything that could be done with
2626 	 * FD_NONBLOCK still being set.
2627 	 */
2628 	switch (cmd) {
2629 
2630 	case DIOCGMEDIASIZE:
2631 		*(off_t *)addr = (128 << (fd->ft->secsize)) * fd->ft->size;
2632 		return (0);
2633 
2634 	case DIOCGSECTORSIZE:
2635 		*(u_int *)addr = 128 << (fd->ft->secsize);
2636 		return (0);
2637 
2638 	case FIONBIO:
2639 		if (*(int *)addr != 0)
2640 			fd->flags |= FD_NONBLOCK;
2641 		else {
2642 			if (fd->ft == 0) {
2643 				/*
2644 				 * No drive type has been selected yet,
2645 				 * cannot turn FNONBLOCK off.
2646 				 */
2647 				return (EINVAL);
2648 			}
2649 			fd->flags &= ~FD_NONBLOCK;
2650 		}
2651 		return (0);
2652 
2653 	case FIOASYNC:
2654 		/* keep the generic fcntl() code happy */
2655 		return (0);
2656 
2657 	case FD_GTYPE:                  /* get drive type */
2658 		if (fd->ft == 0)
2659 			/* no type known yet, return the native type */
2660 			*(struct fd_type *)addr = fd_native_types[fd->type];
2661 		else
2662 			*(struct fd_type *)addr = *fd->ft;
2663 		return (0);
2664 
2665 	case FD_STYPE:                  /* set drive type */
2666 		if (type == 0) {
2667 			/*
2668 			 * Allow setting drive type temporarily iff
2669 			 * currently unset.  Used for fdformat so any
2670 			 * user can set it, and then start formatting.
2671 			 */
2672 			if (fd->ft)
2673 				return (EINVAL); /* already set */
2674 			fd->ft = fd->fts;
2675 			*fd->ft = *(struct fd_type *)addr;
2676 			fd->flags |= FD_UA;
2677 		} else {
2678 			/*
2679 			 * Set density definition permanently.  Only
2680 			 * allow for superuser.
2681 			 */
2682 			if (suser(td) != 0)
2683 				return (EPERM);
2684 			fd->fts[type] = *(struct fd_type *)addr;
2685 		}
2686 		return (0);
2687 
2688 	case FD_GOPTS:			/* get drive options */
2689 		*(int *)addr = fd->options + (type == 0? FDOPT_AUTOSEL: 0);
2690 		return (0);
2691 
2692 	case FD_SOPTS:			/* set drive options */
2693 		fd->options = *(int *)addr & ~FDOPT_AUTOSEL;
2694 		return (0);
2695 
2696 #ifdef FDC_DEBUG
2697 	case FD_DEBUG:
2698 		if ((fd_debug != 0) != (*(int *)addr != 0)) {
2699 			fd_debug = (*(int *)addr != 0);
2700 			printf("fd%d: debugging turned %s\n",
2701 			    fd->fdu, fd_debug ? "on" : "off");
2702 		}
2703 		return (0);
2704 #endif
2705 
2706 	case FD_CLRERR:
2707 		if (suser(td) != 0)
2708 			return (EPERM);
2709 		fd->fdc->fdc_errs = 0;
2710 		return (0);
2711 
2712 	case FD_GSTAT:
2713 		fsp = (struct fdc_status *)addr;
2714 		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2715 			return (EINVAL);
2716 		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2717 		return (0);
2718 
2719 	case FD_GDTYPE:
2720 		*(enum fd_drivetype *)addr = fd->type;
2721 		return (0);
2722 	}
2723 
2724 	/*
2725 	 * Now handle everything else.  Make sure we have a valid
2726 	 * drive type.
2727 	 */
2728 	if (fd->flags & FD_NONBLOCK)
2729 		return (EAGAIN);
2730 	if (fd->ft == 0)
2731 		return (ENXIO);
2732 	fdblk = 128 << fd->ft->secsize;
2733 	error = 0;
2734 
2735 	switch (cmd) {
2736 
2737 	case FD_FORM:
2738 		if ((flag & FWRITE) == 0)
2739 			return (EBADF);	/* must be opened for writing */
2740 		if (((struct fd_formb *)addr)->format_version !=
2741 		    FD_FORMAT_VERSION)
2742 			return (EINVAL); /* wrong version of formatting prog */
2743 		error = fdmisccmd(dev, FDBIO_FORMAT, addr);
2744 		break;
2745 
2746 	case FD_GTYPE:                  /* get drive type */
2747 		*(struct fd_type *)addr = *fd->ft;
2748 		break;
2749 
2750 	case FD_STYPE:                  /* set drive type */
2751 		/* this is considered harmful; only allow for superuser */
2752 		if (suser(td) != 0)
2753 			return (EPERM);
2754 		*fd->ft = *(struct fd_type *)addr;
2755 		break;
2756 
2757 	case FD_GOPTS:			/* get drive options */
2758 		*(int *)addr = fd->options;
2759 		break;
2760 
2761 	case FD_SOPTS:			/* set drive options */
2762 		fd->options = *(int *)addr;
2763 		break;
2764 
2765 #ifdef FDC_DEBUG
2766 	case FD_DEBUG:
2767 		if ((fd_debug != 0) != (*(int *)addr != 0)) {
2768 			fd_debug = (*(int *)addr != 0);
2769 			printf("fd%d: debugging turned %s\n",
2770 			    fd->fdu, fd_debug ? "on" : "off");
2771 		}
2772 		break;
2773 #endif
2774 
2775 	case FD_CLRERR:
2776 		if (suser(td) != 0)
2777 			return (EPERM);
2778 		fd->fdc->fdc_errs = 0;
2779 		break;
2780 
2781 	case FD_GSTAT:
2782 		fsp = (struct fdc_status *)addr;
2783 		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2784 			return (EINVAL);
2785 		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2786 		break;
2787 
2788 	case FD_READID:
2789 		rid = (struct fdc_readid *)addr;
2790 		if (rid->cyl > MAX_CYLINDER || rid->head > MAX_HEAD)
2791 			return (EINVAL);
2792 		error = fdmisccmd(dev, FDBIO_RDSECTID, addr);
2793 		break;
2794 
2795 	default:
2796 		error = ENOTTY;
2797 		break;
2798 	}
2799 	return (error);
2800 }
2801