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