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