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