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