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