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