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