xref: /freebsd/sys/dev/fdc/fdc.c (revision 43a5ec4eb41567cc92586503212743d89686d78f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2004 Poul-Henning Kamp
5  * Copyright (c) 1990 The Regents of the University of California.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Don Ahn.
10  *
11  * Libretto PCMCIA floppy support by David Horwitt (dhorwitt@ucsd.edu)
12  * aided by the Linux floppy driver modifications from David Bateman
13  * (dbateman@eng.uts.edu.au).
14  *
15  * Copyright (c) 1993, 1994 by
16  *  jc@irbs.UUCP (John Capo)
17  *  vak@zebub.msk.su (Serge Vakulenko)
18  *  ache@astral.msk.su (Andrew A. Chernov)
19  *
20  * Copyright (c) 1993, 1994, 1995 by
21  *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
22  *  dufault@hda.com (Peter Dufault)
23  *
24  * Copyright (c) 2001 Joerg Wunsch,
25  *  joerg_wunsch@uriah.heep.sax.de (Joerg Wunsch)
26  *
27  * Redistribution and use in source and binary forms, with or without
28  * modification, are permitted provided that the following conditions
29  * are met:
30  * 1. Redistributions of source code must retain the above copyright
31  *    notice, this list of conditions and the following disclaimer.
32  * 2. Redistributions in binary form must reproduce the above copyright
33  *    notice, this list of conditions and the following disclaimer in the
34  *    documentation and/or other materials provided with the distribution.
35  * 3. Neither the name of the University nor the names of its contributors
36  *    may be used to endorse or promote products derived from this software
37  *    without specific prior written permission.
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
40  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
43  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49  * SUCH DAMAGE.
50  *
51  *	from:	@(#)fd.c	7.4 (Berkeley) 5/25/91
52  *
53  */
54 
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57 
58 #include "opt_fdc.h"
59 
60 #include <sys/param.h>
61 #include <sys/bio.h>
62 #include <sys/bus.h>
63 #include <sys/devicestat.h>
64 #include <sys/disk.h>
65 #include <sys/fcntl.h>
66 #include <sys/fdcio.h>
67 #include <sys/filio.h>
68 #include <sys/kernel.h>
69 #include <sys/kthread.h>
70 #include <sys/lock.h>
71 #include <sys/malloc.h>
72 #include <sys/module.h>
73 #include <sys/mutex.h>
74 #include <sys/priv.h>
75 #include <sys/proc.h>
76 #include <sys/rman.h>
77 #include <sys/sysctl.h>
78 #include <sys/systm.h>
79 
80 #include <geom/geom.h>
81 
82 #include <machine/bus.h>
83 #include <machine/clock.h>
84 #include <machine/stdarg.h>
85 
86 #include <isa/isavar.h>
87 #include <isa/isareg.h>
88 #include <isa/rtc.h>
89 #include <dev/fdc/fdcvar.h>
90 
91 #include <dev/ic/nec765.h>
92 
93 /*
94  * Runtime configuration hints/flags
95  */
96 
97 /* configuration flags for fd */
98 #define FD_TYPEMASK	0x0f	/* drive type, matches enum
99 				 * fd_drivetype; on i386 machines, if
100 				 * given as 0, use RTC type for fd0
101 				 * and fd1 */
102 #define	FD_NO_CHLINE	0x10	/* drive does not support changeline
103 				 * aka. unit attention */
104 #define FD_NO_PROBE	0x20	/* don't probe drive (seek test), just
105 				 * assume it is there */
106 
107 /*
108  * Things that could conceiveably considered parameters or tweakables
109  */
110 
111 /*
112  * Maximal number of bytes in a cylinder.
113  * This is used for ISADMA bouncebuffer allocation and sets the max
114  * xfersize we support.
115  *
116  * 2.88M format has 2 x 36 x 512, allow for hacked up density.
117  */
118 #define MAX_BYTES_PER_CYL	(2 * 40 * 512)
119 
120 /*
121  * Timeout value for the PIO loops to wait until the FDC main status
122  * register matches our expectations (request for master, direction
123  * bit).  This is supposed to be a number of microseconds, although
124  * timing might actually not be very accurate.
125  *
126  * Timeouts of 100 msec are believed to be required for some broken
127  * (old) hardware.
128  */
129 #define	FDSTS_TIMEOUT	100000
130 
131 /*
132  * After this many errors, stop whining.  Close will reset this count.
133  */
134 #define FDC_ERRMAX	100
135 
136 /*
137  * AutoDensity search lists for each drive type.
138  */
139 
140 static struct fd_type fd_searchlist_360k[] = {
141 	{ FDF_5_360 },
142 	{ 0 }
143 };
144 
145 static struct fd_type fd_searchlist_12m[] = {
146 	{ FDF_5_1200 | FL_AUTO },
147 	{ FDF_5_400 | FL_AUTO },
148 	{ FDF_5_360 | FL_2STEP | FL_AUTO},
149 	{ 0 }
150 };
151 
152 static struct fd_type fd_searchlist_720k[] = {
153 	{ FDF_3_720 },
154 	{ 0 }
155 };
156 
157 static struct fd_type fd_searchlist_144m[] = {
158 	{ FDF_3_1440 | FL_AUTO},
159 	{ FDF_3_720 | FL_AUTO},
160 	{ 0 }
161 };
162 
163 static struct fd_type fd_searchlist_288m[] = {
164 	{ FDF_3_1440 | FL_AUTO },
165 #if 0
166 	{ FDF_3_2880 | FL_AUTO }, /* XXX: probably doesn't work */
167 #endif
168 	{ FDF_3_720 | FL_AUTO},
169 	{ 0 }
170 };
171 
172 /*
173  * Order must match enum fd_drivetype in <sys/fdcio.h>.
174  */
175 static struct fd_type *fd_native_types[] = {
176 	NULL,				/* FDT_NONE */
177 	fd_searchlist_360k, 		/* FDT_360K */
178 	fd_searchlist_12m, 		/* FDT_12M */
179 	fd_searchlist_720k, 		/* FDT_720K */
180 	fd_searchlist_144m, 		/* FDT_144M */
181 	fd_searchlist_288m,		/* FDT_288M_1 (mapped to FDT_288M) */
182 	fd_searchlist_288m, 		/* FDT_288M */
183 };
184 
185 /*
186  * Internals start here
187  */
188 
189 /* registers */
190 #define	FDOUT	2	/* Digital Output Register (W) */
191 #define	FDO_FDSEL	0x03	/*  floppy device select */
192 #define	FDO_FRST	0x04	/*  floppy controller reset */
193 #define	FDO_FDMAEN	0x08	/*  enable floppy DMA and Interrupt */
194 #define	FDO_MOEN0	0x10	/*  motor enable drive 0 */
195 #define	FDO_MOEN1	0x20	/*  motor enable drive 1 */
196 #define	FDO_MOEN2	0x40	/*  motor enable drive 2 */
197 #define	FDO_MOEN3	0x80	/*  motor enable drive 3 */
198 
199 #define	FDSTS	4	/* NEC 765 Main Status Register (R) */
200 #define FDDSR	4	/* Data Rate Select Register (W) */
201 #define	FDDATA	5	/* NEC 765 Data Register (R/W) */
202 #define	FDCTL	7	/* Control Register (W) */
203 
204 /*
205  * The YE-DATA PC Card floppies use PIO to read in the data rather
206  * than DMA due to the wild variability of DMA for the PC Card
207  * devices.  DMA was deleted from the PC Card specification in version
208  * 7.2 of the standard, but that post-dates the YE-DATA devices by many
209  * years.
210  *
211  * In addition, if we cannot setup the DMA resources for the ISA
212  * attachment, we'll use this same offset for data transfer.  However,
213  * that almost certainly won't work.
214  *
215  * For this mode, offset 0 and 1 must be used to setup the transfer
216  * for this floppy.  This is OK for PC Card YE Data devices, but for
217  * ISA this is likely wrong.  These registers are only available on
218  * those systems that map them to the floppy drive.  Newer systems do
219  * not do this, and we should likely prohibit access to them (or
220  * disallow NODMA to be set).
221  */
222 #define FDBCDR		0	/* And 1 */
223 #define FD_YE_DATAPORT	6	/* Drive Data port */
224 
225 #define	FDI_DCHG	0x80	/* diskette has been changed */
226 				/* requires drive and motor being selected */
227 				/* is cleared by any step pulse to drive */
228 
229 /*
230  * We have three private BIO commands.
231  */
232 #define BIO_PROBE	BIO_CMD0
233 #define BIO_RDID	BIO_CMD1
234 #define BIO_FMT		BIO_CMD2
235 
236 /*
237  * Per drive structure (softc).
238  */
239 struct fd_data {
240 	u_char 	*fd_ioptr;	/* IO pointer */
241 	u_int	fd_iosize;	/* Size of IO chunks */
242 	u_int	fd_iocount;	/* Outstanding requests */
243 	struct	fdc_data *fdc;	/* pointer to controller structure */
244 	int	fdsu;		/* this units number on this controller */
245 	enum	fd_drivetype type; /* drive type */
246 	struct	fd_type *ft;	/* pointer to current type descriptor */
247 	struct	fd_type fts;	/* type descriptors */
248 	int	sectorsize;
249 	int	flags;
250 #define	FD_WP		(1<<0)	/* Write protected	*/
251 #define	FD_MOTOR	(1<<1)	/* motor should be on	*/
252 #define	FD_MOTORWAIT	(1<<2)	/* motor should be on	*/
253 #define	FD_EMPTY	(1<<3)	/* no media		*/
254 #define	FD_NEWDISK	(1<<4)	/* media changed	*/
255 #define	FD_ISADMA	(1<<5)	/* isa dma started 	*/
256 	int	track;		/* where we think the head is */
257 #define FD_NO_TRACK	 -2
258 	int	options;	/* FDOPT_* */
259 	struct	callout toffhandle;
260 	struct g_geom *fd_geom;
261 	struct g_provider *fd_provider;
262 	device_t dev;
263 	struct bio_queue_head fd_bq;
264 	bool	gone;
265 };
266 
267 #define FD_NOT_VALID -2
268 
269 static driver_intr_t fdc_intr;
270 static driver_filter_t fdc_intr_fast;
271 static void fdc_reset(struct fdc_data *);
272 static int fd_probe_disk(struct fd_data *, int *);
273 
274 static SYSCTL_NODE(_debug, OID_AUTO, fdc, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
275     "fdc driver");
276 
277 static int fifo_threshold = 8;
278 SYSCTL_INT(_debug_fdc, OID_AUTO, fifo, CTLFLAG_RW, &fifo_threshold, 0,
279 	"FIFO threshold setting");
280 
281 static int debugflags = 0;
282 SYSCTL_INT(_debug_fdc, OID_AUTO, debugflags, CTLFLAG_RW, &debugflags, 0,
283 	"Debug flags");
284 
285 static int retries = 10;
286 SYSCTL_INT(_debug_fdc, OID_AUTO, retries, CTLFLAG_RW, &retries, 0,
287 	"Number of retries to attempt");
288 
289 static int spec1 = NE7_SPEC_1(6, 240);
290 SYSCTL_INT(_debug_fdc, OID_AUTO, spec1, CTLFLAG_RW, &spec1, 0,
291 	"Specification byte one (step-rate + head unload)");
292 
293 static int spec2 = NE7_SPEC_2(16, 0);
294 SYSCTL_INT(_debug_fdc, OID_AUTO, spec2, CTLFLAG_RW, &spec2, 0,
295 	"Specification byte two (head load time + no-dma)");
296 
297 static int settle;
298 SYSCTL_INT(_debug_fdc, OID_AUTO, settle, CTLFLAG_RW, &settle, 0,
299 	"Head settling time in sec/hz");
300 
301 static void
302 fdprinttype(struct fd_type *ft)
303 {
304 
305 	printf("(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,0x%x)",
306 	    ft->sectrac, ft->secsize, ft->datalen, ft->gap, ft->tracks,
307 	    ft->size, ft->trans, ft->heads, ft->f_gap, ft->f_inter,
308 	    ft->offset_side2, ft->flags);
309 }
310 
311 static void
312 fdsettype(struct fd_data *fd, struct fd_type *ft)
313 {
314 	fd->ft = ft;
315 	ft->size = ft->sectrac * ft->heads * ft->tracks;
316 	fd->sectorsize = 128 << fd->ft->secsize;
317 }
318 
319 /*
320  * Bus space handling (access to low-level IO).
321  */
322 static inline void
323 fdregwr(struct fdc_data *fdc, int reg, uint8_t v)
324 {
325 
326 	bus_space_write_1(fdc->iot, fdc->ioh[reg], fdc->ioff[reg], v);
327 }
328 
329 static inline uint8_t
330 fdregrd(struct fdc_data *fdc, int reg)
331 {
332 
333 	return bus_space_read_1(fdc->iot, fdc->ioh[reg], fdc->ioff[reg]);
334 }
335 
336 static void
337 fdctl_wr(struct fdc_data *fdc, u_int8_t v)
338 {
339 
340 	fdregwr(fdc, FDCTL, v);
341 }
342 
343 static void
344 fdout_wr(struct fdc_data *fdc, u_int8_t v)
345 {
346 
347 	fdregwr(fdc, FDOUT, v);
348 }
349 
350 static u_int8_t
351 fdsts_rd(struct fdc_data *fdc)
352 {
353 
354 	return fdregrd(fdc, FDSTS);
355 }
356 
357 static void
358 fddsr_wr(struct fdc_data *fdc, u_int8_t v)
359 {
360 
361 	fdregwr(fdc, FDDSR, v);
362 }
363 
364 static void
365 fddata_wr(struct fdc_data *fdc, u_int8_t v)
366 {
367 
368 	fdregwr(fdc, FDDATA, v);
369 }
370 
371 static u_int8_t
372 fddata_rd(struct fdc_data *fdc)
373 {
374 
375 	return fdregrd(fdc, FDDATA);
376 }
377 
378 static u_int8_t
379 fdin_rd(struct fdc_data *fdc)
380 {
381 
382 	return fdregrd(fdc, FDCTL);
383 }
384 
385 /*
386  * Magic pseudo-DMA initialization for YE FDC. Sets count and
387  * direction.
388  */
389 static void
390 fdbcdr_wr(struct fdc_data *fdc, int iswrite, uint16_t count)
391 {
392 	fdregwr(fdc, FDBCDR, (count - 1) & 0xff);
393 	fdregwr(fdc, FDBCDR + 1,
394 	    (iswrite ? 0x80 : 0) | (((count - 1) >> 8) & 0x7f));
395 }
396 
397 static int
398 fdc_err(struct fdc_data *fdc, const char *s)
399 {
400 	fdc->fdc_errs++;
401 	if (s) {
402 		if (fdc->fdc_errs < FDC_ERRMAX)
403 			device_printf(fdc->fdc_dev, "%s", s);
404 		else if (fdc->fdc_errs == FDC_ERRMAX)
405 			device_printf(fdc->fdc_dev, "too many errors, not "
406 						    "logging any more\n");
407 	}
408 
409 	return (1);
410 }
411 
412 /*
413  * FDC IO functions, take care of the main status register, timeout
414  * in case the desired status bits are never set.
415  *
416  * These PIO loops initially start out with short delays between
417  * each iteration in the expectation that the required condition
418  * is usually met quickly, so it can be handled immediately.
419  */
420 static int
421 fdc_in(struct fdc_data *fdc, int *ptr)
422 {
423 	int i, j, step;
424 
425 	step = 1;
426 	for (j = 0; j < FDSTS_TIMEOUT; j += step) {
427 	        i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM);
428 	        if (i == (NE7_DIO|NE7_RQM)) {
429 			i = fddata_rd(fdc);
430 			if (ptr)
431 				*ptr = i;
432 			return (0);
433 		}
434 		if (i == NE7_RQM)
435 			return (fdc_err(fdc, "ready for output in input\n"));
436 		step += step;
437 		DELAY(step);
438 	}
439 	return (fdc_err(fdc, bootverbose? "input ready timeout\n": 0));
440 }
441 
442 static int
443 fdc_out(struct fdc_data *fdc, int x)
444 {
445 	int i, j, step;
446 
447 	step = 1;
448 	for (j = 0; j < FDSTS_TIMEOUT; j += step) {
449 	        i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM);
450 	        if (i == NE7_RQM) {
451 			fddata_wr(fdc, x);
452 			return (0);
453 		}
454 		if (i == (NE7_DIO|NE7_RQM))
455 			return (fdc_err(fdc, "ready for input in output\n"));
456 		step += step;
457 		DELAY(step);
458 	}
459 	return (fdc_err(fdc, bootverbose? "output ready timeout\n": 0));
460 }
461 
462 /*
463  * fdc_cmd: Send a command to the chip.
464  * Takes a varargs with this structure:
465  *	# of output bytes
466  *	output bytes as int [...]
467  *	# of input bytes
468  *	input bytes as int* [...]
469  */
470 static int
471 fdc_cmd(struct fdc_data *fdc, int n_out, ...)
472 {
473 	u_char cmd = 0;
474 	int n_in;
475 	int n, i;
476 	va_list ap;
477 
478 	va_start(ap, n_out);
479 	for (n = 0; n < n_out; n++) {
480 		i = va_arg(ap, int);
481 		if (n == 0)
482 			cmd = i;
483 		if (fdc_out(fdc, i) < 0) {
484 			char msg[50];
485 			snprintf(msg, sizeof(msg),
486 				"cmd %x failed at out byte %d of %d\n",
487 				cmd, n + 1, n_out);
488 			fdc->flags |= FDC_NEEDS_RESET;
489 			va_end(ap);
490 			return fdc_err(fdc, msg);
491 		}
492 	}
493 	n_in = va_arg(ap, int);
494 	for (n = 0; n < n_in; n++) {
495 		int *ptr = va_arg(ap, int *);
496 		if (fdc_in(fdc, ptr) != 0) {
497 			char msg[50];
498 			snprintf(msg, sizeof(msg),
499 				"cmd %02x failed at in byte %d of %d\n",
500 				cmd, n + 1, n_in);
501 			fdc->flags |= FDC_NEEDS_RESET;
502 			va_end(ap);
503 			return fdc_err(fdc, msg);
504 		}
505 	}
506 	va_end(ap);
507 	return (0);
508 }
509 
510 static void
511 fdc_reset(struct fdc_data *fdc)
512 {
513 	int i, r[10];
514 
515 	if (fdc->fdct == FDC_ENHANCED) {
516 		/* Try a software reset, default precomp, and 500 kb/s */
517 		fddsr_wr(fdc, I8207X_DSR_SR);
518 	} else {
519 		/* Try a hardware reset, keep motor on */
520 		fdout_wr(fdc, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
521 		DELAY(100);
522 		/* enable FDC, but defer interrupts a moment */
523 		fdout_wr(fdc, fdc->fdout & ~FDO_FDMAEN);
524 	}
525 	DELAY(100);
526 	fdout_wr(fdc, fdc->fdout);
527 
528 	/* XXX after a reset, silently believe the FDC will accept commands */
529 	if (fdc_cmd(fdc, 3, NE7CMD_SPECIFY, spec1, spec2, 0))
530 		device_printf(fdc->fdc_dev, " SPECIFY failed in reset\n");
531 
532 	if (fdc->fdct == FDC_ENHANCED) {
533 		if (fdc_cmd(fdc, 4,
534 		    I8207X_CONFIG,
535 		    0,
536 		    /* 0x40 | */		/* Enable Implied Seek -
537 						 * breaks 2step! */
538 		    0x10 |			/* Polling disabled */
539 		    (fifo_threshold - 1),	/* Fifo threshold */
540 		    0x00,			/* Precomp track */
541 		    0))
542 			device_printf(fdc->fdc_dev,
543 			    " CONFIGURE failed in reset\n");
544 		if (debugflags & 1) {
545 			if (fdc_cmd(fdc, 1,
546 			    I8207X_DUMPREG,
547 			    10, &r[0], &r[1], &r[2], &r[3], &r[4],
548 			    &r[5], &r[6], &r[7], &r[8], &r[9]))
549 				device_printf(fdc->fdc_dev,
550 				    " DUMPREG failed in reset\n");
551 			for (i = 0; i < 10; i++)
552 				printf(" %02x", r[i]);
553 			printf("\n");
554 		}
555 	}
556 }
557 
558 static int
559 fdc_sense_drive(struct fdc_data *fdc, int *st3p)
560 {
561 	int st3;
562 
563 	if (fdc_cmd(fdc, 2, NE7CMD_SENSED, fdc->fd->fdsu, 1, &st3))
564 		return (fdc_err(fdc, "Sense Drive Status failed\n"));
565 	if (st3p)
566 		*st3p = st3;
567 	return (0);
568 }
569 
570 static int
571 fdc_sense_int(struct fdc_data *fdc, int *st0p, int *cylp)
572 {
573 	int cyl, st0, ret;
574 
575 	ret = fdc_cmd(fdc, 1, NE7CMD_SENSEI, 1, &st0);
576 	if (ret) {
577 		(void)fdc_err(fdc, "sense intr err reading stat reg 0\n");
578 		return (ret);
579 	}
580 
581 	if (st0p)
582 		*st0p = st0;
583 
584 	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV) {
585 		/*
586 		 * There doesn't seem to have been an interrupt.
587 		 */
588 		return (FD_NOT_VALID);
589 	}
590 
591 	if (fdc_in(fdc, &cyl) != 0)
592 		return fdc_err(fdc, "can't get cyl num\n");
593 
594 	if (cylp)
595 		*cylp = cyl;
596 
597 	return (0);
598 }
599 
600 static int
601 fdc_read_status(struct fdc_data *fdc)
602 {
603 	int i, ret, status;
604 
605 	for (i = ret = 0; i < 7; i++) {
606 		ret = fdc_in(fdc, &status);
607 		fdc->status[i] = status;
608 		if (ret != 0)
609 			break;
610 	}
611 
612 	if (ret == 0)
613 		fdc->flags |= FDC_STAT_VALID;
614 	else
615 		fdc->flags &= ~FDC_STAT_VALID;
616 
617 	return ret;
618 }
619 
620 /*
621  * Select this drive
622  */
623 static void
624 fd_select(struct fd_data *fd)
625 {
626 	struct fdc_data *fdc;
627 
628 	/* XXX: lock controller */
629 	fdc = fd->fdc;
630 	fdc->fdout &= ~FDO_FDSEL;
631 	fdc->fdout |= FDO_FDMAEN | FDO_FRST | fd->fdsu;
632 	fdout_wr(fdc, fdc->fdout);
633 }
634 
635 static void
636 fd_turnon(void *arg)
637 {
638 	struct fd_data *fd;
639 	struct bio *bp;
640 	int once;
641 
642 	fd = arg;
643 	mtx_assert(&fd->fdc->fdc_mtx, MA_OWNED);
644 	fd->flags &= ~FD_MOTORWAIT;
645 	fd->flags |= FD_MOTOR;
646 	once = 0;
647 	for (;;) {
648 		bp = bioq_takefirst(&fd->fd_bq);
649 		if (bp == NULL)
650 			break;
651 		bioq_disksort(&fd->fdc->head, bp);
652 		once = 1;
653 	}
654 	if (once)
655 		wakeup(&fd->fdc->head);
656 }
657 
658 static void
659 fd_motor(struct fd_data *fd, int turnon)
660 {
661 	struct fdc_data *fdc;
662 
663 	fdc = fd->fdc;
664 /*
665 	mtx_assert(&fdc->fdc_mtx, MA_OWNED);
666 */
667 	if (turnon) {
668 		fd->flags |= FD_MOTORWAIT;
669 		fdc->fdout |= (FDO_MOEN0 << fd->fdsu);
670 		callout_reset(&fd->toffhandle, hz, fd_turnon, fd);
671 	} else {
672 		callout_stop(&fd->toffhandle);
673 		fd->flags &= ~(FD_MOTOR|FD_MOTORWAIT);
674 		fdc->fdout &= ~(FDO_MOEN0 << fd->fdsu);
675 	}
676 	fdout_wr(fdc, fdc->fdout);
677 }
678 
679 static void
680 fd_turnoff(void *xfd)
681 {
682 	struct fd_data *fd = xfd;
683 
684 	mtx_assert(&fd->fdc->fdc_mtx, MA_OWNED);
685 	fd_motor(fd, 0);
686 }
687 
688 /*
689  * fdc_intr - wake up the worker thread.
690  */
691 
692 static void
693 fdc_intr(void *arg)
694 {
695 
696 	wakeup(arg);
697 }
698 
699 static int
700 fdc_intr_fast(void *arg)
701 {
702 
703 	wakeup(arg);
704 	return(FILTER_HANDLED);
705 }
706 
707 /*
708  * fdc_pio(): perform programmed IO read/write for YE PCMCIA floppy.
709  */
710 static void
711 fdc_pio(struct fdc_data *fdc)
712 {
713 	u_char *cptr;
714 	struct bio *bp;
715 	u_int count;
716 
717 	bp = fdc->bp;
718 	cptr = fdc->fd->fd_ioptr;
719 	count = fdc->fd->fd_iosize;
720 
721 	if (bp->bio_cmd == BIO_READ) {
722 		fdbcdr_wr(fdc, 0, count);
723 		bus_space_read_multi_1(fdc->iot, fdc->ioh[FD_YE_DATAPORT],
724 		    fdc->ioff[FD_YE_DATAPORT], cptr, count);
725 	} else {
726 		bus_space_write_multi_1(fdc->iot, fdc->ioh[FD_YE_DATAPORT],
727 		    fdc->ioff[FD_YE_DATAPORT], cptr, count);
728 		fdbcdr_wr(fdc, 0, count);	/* needed? */
729 	}
730 }
731 
732 static int
733 fdc_biodone(struct fdc_data *fdc, int error)
734 {
735 	struct fd_data *fd;
736 	struct bio *bp;
737 
738 	fd = fdc->fd;
739 	bp = fdc->bp;
740 
741 	mtx_lock(&fdc->fdc_mtx);
742 	if (--fd->fd_iocount == 0)
743 		callout_reset(&fd->toffhandle, 4 * hz, fd_turnoff, fd);
744 	fdc->bp = NULL;
745 	fdc->fd = NULL;
746 	mtx_unlock(&fdc->fdc_mtx);
747 	if (bp->bio_to != NULL) {
748 		if ((debugflags & 2) && fd->fdc->retry > 0)
749 			printf("retries: %d\n", fd->fdc->retry);
750 		g_io_deliver(bp, error);
751 		return (0);
752 	}
753 	bp->bio_error = error;
754 	bp->bio_flags |= BIO_DONE;
755 	wakeup(bp);
756 	return (0);
757 }
758 
759 static int retry_line;
760 
761 static int
762 fdc_worker(struct fdc_data *fdc)
763 {
764 	struct fd_data *fd;
765 	struct bio *bp;
766 	int i, nsect;
767 	int st0, st3, cyl, mfm, steptrac, cylinder, descyl, sec;
768 	int head;
769 	int override_error;
770 	static int need_recal;
771 	struct fdc_readid *idp;
772 	struct fd_formb *finfo;
773 
774 	override_error = 0;
775 
776 	/* Have we exhausted our retries ? */
777 	bp = fdc->bp;
778 	fd = fdc->fd;
779 	if (bp != NULL &&
780 		(fdc->retry >= retries || (fd->options & FDOPT_NORETRY))) {
781 		if ((debugflags & 4))
782 			printf("Too many retries (EIO)\n");
783 		if (fdc->flags & FDC_NEEDS_RESET) {
784 			mtx_lock(&fdc->fdc_mtx);
785 			fd->flags |= FD_EMPTY;
786 			mtx_unlock(&fdc->fdc_mtx);
787 		}
788 		return (fdc_biodone(fdc, EIO));
789 	}
790 
791 	/* Disable ISADMA if we bailed while it was active */
792 	if (fd != NULL && (fd->flags & FD_ISADMA)) {
793 		isa_dmadone(
794 		    bp->bio_cmd == BIO_READ ? ISADMA_READ : ISADMA_WRITE,
795 		    fd->fd_ioptr, fd->fd_iosize, fdc->dmachan);
796 		mtx_lock(&fdc->fdc_mtx);
797 		fd->flags &= ~FD_ISADMA;
798 		mtx_unlock(&fdc->fdc_mtx);
799 	}
800 
801 	/* Unwedge the controller ? */
802 	if (fdc->flags & FDC_NEEDS_RESET) {
803 		fdc->flags &= ~FDC_NEEDS_RESET;
804 		fdc_reset(fdc);
805 		if (cold)
806 			DELAY(1000000);
807 		else
808 			tsleep(fdc, PRIBIO, "fdcrst", hz);
809 		/* Discard results */
810 		for (i = 0; i < 4; i++)
811 			fdc_sense_int(fdc, &st0, &cyl);
812 		/* All drives must recal */
813 		need_recal = 0xf;
814 	}
815 
816 	/* Pick up a request, if need be wait for it */
817 	if (fdc->bp == NULL) {
818 		mtx_lock(&fdc->fdc_mtx);
819 		do {
820 			fdc->bp = bioq_takefirst(&fdc->head);
821 			if (fdc->bp == NULL)
822 				msleep(&fdc->head, &fdc->fdc_mtx,
823 				    PRIBIO, "-", 0);
824 		} while (fdc->bp == NULL &&
825 		    (fdc->flags & FDC_KTHREAD_EXIT) == 0);
826 		mtx_unlock(&fdc->fdc_mtx);
827 
828 		if (fdc->bp == NULL)
829 			/*
830 			 * Nothing to do, worker thread has been
831 			 * requested to stop.
832 			 */
833 			return (0);
834 
835 		bp = fdc->bp;
836 		fd = fdc->fd = bp->bio_driver1;
837 		fdc->retry = 0;
838 		fd->fd_ioptr = bp->bio_data;
839 		if (bp->bio_cmd == BIO_FMT) {
840 			i = offsetof(struct fd_formb, fd_formb_cylno(0));
841 			fd->fd_ioptr += i;
842 			fd->fd_iosize = bp->bio_length - i;
843 		}
844 	}
845 
846 	/* Select drive, setup params */
847 	fd_select(fd);
848 	if (fdc->fdct == FDC_ENHANCED)
849 		fddsr_wr(fdc, fd->ft->trans);
850 	else
851 		fdctl_wr(fdc, fd->ft->trans);
852 
853 	if (bp->bio_cmd == BIO_PROBE) {
854 		if ((!(device_get_flags(fd->dev) & FD_NO_CHLINE) &&
855 		    !(fdin_rd(fdc) & FDI_DCHG) &&
856 		    !(fd->flags & FD_EMPTY)) ||
857 		    fd_probe_disk(fd, &need_recal) == 0)
858 			return (fdc_biodone(fdc, 0));
859 		return (1);
860 	}
861 
862 	/*
863 	 * If we are dead just flush the requests
864 	 */
865 	if (fd->flags & FD_EMPTY)
866 		return (fdc_biodone(fdc, ENXIO));
867 
868 	/* Check if we lost our media */
869 	if (fdin_rd(fdc) & FDI_DCHG) {
870 		if (debugflags & 0x40)
871 			printf("Lost disk\n");
872 		mtx_lock(&fdc->fdc_mtx);
873 		fd->flags |= FD_EMPTY;
874 		fd->flags |= FD_NEWDISK;
875 		mtx_unlock(&fdc->fdc_mtx);
876 		g_topology_lock();
877 		g_orphan_provider(fd->fd_provider, ENXIO);
878 		fd->fd_provider->flags |= G_PF_WITHER;
879 		fd->fd_provider =
880 		    g_new_providerf(fd->fd_geom, "%s", fd->fd_geom->name);
881 		g_error_provider(fd->fd_provider, 0);
882 		g_topology_unlock();
883 		return (fdc_biodone(fdc, ENXIO));
884 	}
885 
886 	/* Check if the floppy is write-protected */
887 	if (bp->bio_cmd == BIO_FMT || bp->bio_cmd == BIO_WRITE) {
888 		retry_line = __LINE__;
889 		if(fdc_sense_drive(fdc, &st3) != 0)
890 			return (1);
891 		if(st3 & NE7_ST3_WP)
892 			return (fdc_biodone(fdc, EROFS));
893 	}
894 
895 	mfm = (fd->ft->flags & FL_MFM)? NE7CMD_MFM: 0;
896 	steptrac = (fd->ft->flags & FL_2STEP)? 2: 1;
897 	i = fd->ft->sectrac * fd->ft->heads;
898 	cylinder = bp->bio_pblkno / i;
899 	descyl = cylinder * steptrac;
900 	sec = bp->bio_pblkno % i;
901 	nsect = i - sec;
902 	head = sec / fd->ft->sectrac;
903 	sec = sec % fd->ft->sectrac + 1;
904 
905 	/* If everything is going swimmingly, use multisector xfer */
906 	if (fdc->retry == 0 &&
907 	    (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE)) {
908 		fd->fd_iosize = imin(nsect * fd->sectorsize, bp->bio_resid);
909 		nsect = fd->fd_iosize / fd->sectorsize;
910 	} else if (bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE) {
911 		fd->fd_iosize = fd->sectorsize;
912 		nsect = 1;
913 	}
914 
915 	/* Do RECAL if we need to or are going to track zero anyway */
916 	if ((need_recal & (1 << fd->fdsu)) ||
917 	    (cylinder == 0 && fd->track != 0) ||
918 	    fdc->retry > 2) {
919 		retry_line = __LINE__;
920 		if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fd->fdsu, 0))
921 			return (1);
922 		tsleep(fdc, PRIBIO, "fdrecal", hz);
923 		retry_line = __LINE__;
924 		if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
925 			return (1); /* XXX */
926 		retry_line = __LINE__;
927 		if ((st0 & 0xc0) || cyl != 0)
928 			return (1);
929 		need_recal &= ~(1 << fd->fdsu);
930 		fd->track = 0;
931 		/* let the heads settle */
932 		if (settle)
933 			tsleep(fdc->fd, PRIBIO, "fdhdstl", settle);
934 	}
935 
936 	/*
937 	 * SEEK to where we want to be
938 	 */
939 	if (cylinder != fd->track) {
940 		retry_line = __LINE__;
941 		if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fd->fdsu, descyl, 0))
942 			return (1);
943 		tsleep(fdc, PRIBIO, "fdseek", hz);
944 		retry_line = __LINE__;
945 		if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
946 			return (1); /* XXX */
947 		retry_line = __LINE__;
948 		if ((st0 & 0xc0) || cyl != descyl) {
949 			need_recal |= (1 << fd->fdsu);
950 			return (1);
951 		}
952 		/* let the heads settle */
953 		if (settle)
954 			tsleep(fdc->fd, PRIBIO, "fdhdstl", settle);
955 	}
956 	fd->track = cylinder;
957 
958 	if (debugflags & 8)
959 		printf("op %x bn %ju siz %u ptr %p retry %d\n",
960 		    bp->bio_cmd, bp->bio_pblkno, fd->fd_iosize,
961 		    fd->fd_ioptr, fdc->retry);
962 
963 	/* Setup ISADMA if we need it and have it */
964 	if ((bp->bio_cmd == BIO_READ ||
965 		bp->bio_cmd == BIO_WRITE ||
966 		bp->bio_cmd == BIO_FMT)
967 	     && !(fdc->flags & FDC_NODMA)) {
968 		isa_dmastart(
969 		    bp->bio_cmd == BIO_READ ? ISADMA_READ : ISADMA_WRITE,
970 		    fd->fd_ioptr, fd->fd_iosize, fdc->dmachan);
971 		mtx_lock(&fdc->fdc_mtx);
972 		fd->flags |= FD_ISADMA;
973 		mtx_unlock(&fdc->fdc_mtx);
974 	}
975 
976 	/* Do PIO if we have to */
977 	if (fdc->flags & FDC_NODMA) {
978 		if (bp->bio_cmd == BIO_READ ||
979 		    bp->bio_cmd == BIO_WRITE ||
980 		    bp->bio_cmd == BIO_FMT)
981 			fdbcdr_wr(fdc, 1, fd->fd_iosize);
982 		if (bp->bio_cmd == BIO_WRITE ||
983 		    bp->bio_cmd == BIO_FMT)
984 			fdc_pio(fdc);
985 	}
986 
987 	switch(bp->bio_cmd) {
988 	case BIO_FMT:
989 		/* formatting */
990 		finfo = (struct fd_formb *)bp->bio_data;
991 		retry_line = __LINE__;
992 		if (fdc_cmd(fdc, 6,
993 		    NE7CMD_FORMAT | mfm,
994 		    head << 2 | fd->fdsu,
995 		    finfo->fd_formb_secshift,
996 		    finfo->fd_formb_nsecs,
997 		    finfo->fd_formb_gaplen,
998 		    finfo->fd_formb_fillbyte, 0))
999 			return (1);
1000 		break;
1001 	case BIO_RDID:
1002 		retry_line = __LINE__;
1003 		if (fdc_cmd(fdc, 2,
1004 		    NE7CMD_READID | mfm,
1005 		    head << 2 | fd->fdsu, 0))
1006 			return (1);
1007 		break;
1008 	case BIO_READ:
1009 		retry_line = __LINE__;
1010 		if (fdc_cmd(fdc, 9,
1011 		    NE7CMD_READ | NE7CMD_SK | mfm | NE7CMD_MT,
1012 		    head << 2 | fd->fdsu,	/* head & unit */
1013 		    fd->track,			/* track */
1014 		    head,			/* head */
1015 		    sec,			/* sector + 1 */
1016 		    fd->ft->secsize,		/* sector size */
1017 		    fd->ft->sectrac,		/* sectors/track */
1018 		    fd->ft->gap,		/* gap size */
1019 		    fd->ft->datalen,		/* data length */
1020 		    0))
1021 			return (1);
1022 		break;
1023 	case BIO_WRITE:
1024 		retry_line = __LINE__;
1025 		if (fdc_cmd(fdc, 9,
1026 		    NE7CMD_WRITE | mfm | NE7CMD_MT,
1027 		    head << 2 | fd->fdsu,	/* head & unit */
1028 		    fd->track,			/* track */
1029 		    head,			/* head */
1030 		    sec,			/* sector + 1 */
1031 		    fd->ft->secsize,		/* sector size */
1032 		    fd->ft->sectrac,		/* sectors/track */
1033 		    fd->ft->gap,		/* gap size */
1034 		    fd->ft->datalen,		/* data length */
1035 		    0))
1036 			return (1);
1037 		break;
1038 	default:
1039 		KASSERT(0 == 1, ("Wrong bio_cmd %x\n", bp->bio_cmd));
1040 	}
1041 
1042 	/* Wait for interrupt */
1043 	i = tsleep(fdc, PRIBIO, "fddata", hz);
1044 
1045 	/* PIO if the read looks good */
1046 	if (i == 0 && (fdc->flags & FDC_NODMA) && (bp->bio_cmd == BIO_READ))
1047 		fdc_pio(fdc);
1048 
1049 	/* Finish DMA */
1050 	if (fd->flags & FD_ISADMA) {
1051 		isa_dmadone(
1052 		    bp->bio_cmd == BIO_READ ? ISADMA_READ : ISADMA_WRITE,
1053 		    fd->fd_ioptr, fd->fd_iosize, fdc->dmachan);
1054 		mtx_lock(&fdc->fdc_mtx);
1055 		fd->flags &= ~FD_ISADMA;
1056 		mtx_unlock(&fdc->fdc_mtx);
1057 	}
1058 
1059 	if (i != 0) {
1060 		/*
1061 		 * Timeout.
1062 		 *
1063 		 * Due to IBM's brain-dead design, the FDC has a faked ready
1064 		 * signal, hardwired to ready == true. Thus, any command
1065 		 * issued if there's no diskette in the drive will _never_
1066 		 * complete, and must be aborted by resetting the FDC.
1067 		 * Many thanks, Big Blue!
1068 		 */
1069 		retry_line = __LINE__;
1070 		fdc->flags |= FDC_NEEDS_RESET;
1071 		return (1);
1072 	}
1073 
1074 	retry_line = __LINE__;
1075 	if (fdc_read_status(fdc))
1076 		return (1);
1077 
1078 	if (debugflags & 0x10)
1079 		printf("  -> %x %x %x %x\n",
1080 		    fdc->status[0], fdc->status[1],
1081 		    fdc->status[2], fdc->status[3]);
1082 
1083 	st0 = fdc->status[0] & NE7_ST0_IC;
1084 	if (st0 != 0) {
1085 		retry_line = __LINE__;
1086 		if (st0 == NE7_ST0_IC_AT && fdc->status[1] & NE7_ST1_OR) {
1087 			/*
1088 			 * DMA overrun. Someone hogged the bus and
1089 			 * didn't release it in time for the next
1090 			 * FDC transfer.
1091 			 */
1092 			return (1);
1093 		}
1094 		retry_line = __LINE__;
1095 		if(st0 == NE7_ST0_IC_IV) {
1096 			fdc->flags |= FDC_NEEDS_RESET;
1097 			return (1);
1098 		}
1099 		retry_line = __LINE__;
1100 		if(st0 == NE7_ST0_IC_AT && fdc->status[2] & NE7_ST2_WC) {
1101 			need_recal |= (1 << fd->fdsu);
1102 			return (1);
1103 		}
1104 		if (debugflags & 0x20) {
1105 			printf("status %02x %02x %02x %02x %02x %02x\n",
1106 			    fdc->status[0], fdc->status[1], fdc->status[2],
1107 			    fdc->status[3], fdc->status[4], fdc->status[5]);
1108 		}
1109 		retry_line = __LINE__;
1110 		if (fd->options & FDOPT_NOERROR)
1111 			override_error = 1;
1112 		else
1113 			return (1);
1114 	}
1115 	/* All OK */
1116 	switch(bp->bio_cmd) {
1117 	case BIO_RDID:
1118 		/* copy out ID field contents */
1119 		idp = (struct fdc_readid *)bp->bio_data;
1120 		idp->cyl = fdc->status[3];
1121 		idp->head = fdc->status[4];
1122 		idp->sec = fdc->status[5];
1123 		idp->secshift = fdc->status[6];
1124 		if (debugflags & 0x40)
1125 			printf("c %d h %d s %d z %d\n",
1126 			    idp->cyl, idp->head, idp->sec, idp->secshift);
1127 		break;
1128 	case BIO_READ:
1129 	case BIO_WRITE:
1130 		bp->bio_pblkno += nsect;
1131 		bp->bio_resid -= fd->fd_iosize;
1132 		bp->bio_completed += fd->fd_iosize;
1133 		fd->fd_ioptr += fd->fd_iosize;
1134 		if (override_error) {
1135 			if ((debugflags & 4))
1136 				printf("FDOPT_NOERROR: returning bad data\n");
1137 		} else {
1138 			/* Since we managed to get something done,
1139 			 * reset the retry */
1140 			fdc->retry = 0;
1141 			if (bp->bio_resid > 0)
1142 				return (0);
1143 		}
1144 		break;
1145 	case BIO_FMT:
1146 		break;
1147 	}
1148 	return (fdc_biodone(fdc, 0));
1149 }
1150 
1151 static void
1152 fdc_thread(void *arg)
1153 {
1154 	struct fdc_data *fdc;
1155 
1156 	fdc = arg;
1157 	int i;
1158 
1159 	mtx_lock(&fdc->fdc_mtx);
1160 	fdc->flags |= FDC_KTHREAD_ALIVE;
1161 	while ((fdc->flags & FDC_KTHREAD_EXIT) == 0) {
1162 		mtx_unlock(&fdc->fdc_mtx);
1163 		i = fdc_worker(fdc);
1164 		if (i && debugflags & 0x20) {
1165 			if (fdc->bp != NULL)
1166 				g_print_bio("", fdc->bp, "");
1167 			printf("Retry line %d\n", retry_line);
1168 		}
1169 		fdc->retry += i;
1170 		mtx_lock(&fdc->fdc_mtx);
1171 	}
1172 	fdc->flags &= ~(FDC_KTHREAD_EXIT | FDC_KTHREAD_ALIVE);
1173 	mtx_unlock(&fdc->fdc_mtx);
1174 
1175 	kproc_exit(0);
1176 }
1177 
1178 /*
1179  * Enqueue a request.
1180  */
1181 static void
1182 fd_enqueue(struct fd_data *fd, struct bio *bp)
1183 {
1184 	struct fdc_data *fdc;
1185 
1186 	fdc = fd->fdc;
1187 	mtx_lock(&fdc->fdc_mtx);
1188 	/* If we go from idle, cancel motor turnoff */
1189 	if (fd->fd_iocount++ == 0)
1190 		callout_stop(&fd->toffhandle);
1191 	if (fd->flags & FD_MOTOR) {
1192 		/* The motor is on, send it directly to the controller */
1193 		bioq_disksort(&fdc->head, bp);
1194 		wakeup(&fdc->head);
1195 	} else {
1196 		/* Queue it on the drive until the motor has started */
1197 		bioq_insert_tail(&fd->fd_bq, bp);
1198 		if (!(fd->flags & FD_MOTORWAIT))
1199 			fd_motor(fd, 1);
1200 	}
1201 	mtx_unlock(&fdc->fdc_mtx);
1202 }
1203 
1204 /*
1205  * Try to find out if we have a disk in the drive.
1206  */
1207 static int
1208 fd_probe_disk(struct fd_data *fd, int *recal)
1209 {
1210 	struct fdc_data *fdc;
1211 	int st0, st3, cyl;
1212 	int oopts, ret;
1213 
1214 	fdc = fd->fdc;
1215 	oopts = fd->options;
1216 	fd->options |= FDOPT_NOERRLOG | FDOPT_NORETRY;
1217 	ret = 1;
1218 
1219 	/*
1220 	 * First recal, then seek to cyl#1, this clears the old condition on
1221 	 * the disk change line so we can examine it for current status.
1222 	 */
1223 	if (debugflags & 0x40)
1224 		printf("New disk in probe\n");
1225 	mtx_lock(&fdc->fdc_mtx);
1226 	fd->flags |= FD_NEWDISK;
1227 	mtx_unlock(&fdc->fdc_mtx);
1228 	if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fd->fdsu, 0))
1229 		goto done;
1230 	tsleep(fdc, PRIBIO, "fdrecal", hz);
1231 	if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
1232 		goto done;	/* XXX */
1233 	if ((st0 & 0xc0) || cyl != 0)
1234 		goto done;
1235 
1236 	/* Seek to track 1 */
1237 	if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fd->fdsu, 1, 0))
1238 		goto done;
1239 	tsleep(fdc, PRIBIO, "fdseek", hz);
1240 	if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
1241 		goto done;	/* XXX */
1242 	*recal |= (1 << fd->fdsu);
1243 	if (fdin_rd(fdc) & FDI_DCHG) {
1244 		if (debugflags & 0x40)
1245 			printf("Empty in probe\n");
1246 		mtx_lock(&fdc->fdc_mtx);
1247 		fd->flags |= FD_EMPTY;
1248 		mtx_unlock(&fdc->fdc_mtx);
1249 	} else {
1250 		if (fdc_sense_drive(fdc, &st3) != 0)
1251 			goto done;
1252 		if (debugflags & 0x40)
1253 			printf("Got disk in probe\n");
1254 		mtx_lock(&fdc->fdc_mtx);
1255 		fd->flags &= ~FD_EMPTY;
1256 		if (st3 & NE7_ST3_WP)
1257 			fd->flags |= FD_WP;
1258 		else
1259 			fd->flags &= ~FD_WP;
1260 		mtx_unlock(&fdc->fdc_mtx);
1261 	}
1262 	ret = 0;
1263 
1264 done:
1265 	fd->options = oopts;
1266 	return (ret);
1267 }
1268 
1269 static int
1270 fdmisccmd(struct fd_data *fd, u_int cmd, void *data)
1271 {
1272 	struct bio *bp;
1273 	struct fd_formb *finfo;
1274 	struct fdc_readid *idfield;
1275 	int error;
1276 
1277 	bp = malloc(sizeof(struct bio), M_TEMP, M_WAITOK | M_ZERO);
1278 
1279 	/*
1280 	 * Set up a bio request for fdstrategy().  bio_offset is faked
1281 	 * so that fdstrategy() will seek to the requested
1282 	 * cylinder, and use the desired head.
1283 	 */
1284 	bp->bio_cmd = cmd;
1285 	if (cmd == BIO_FMT) {
1286 		finfo = (struct fd_formb *)data;
1287 		bp->bio_pblkno =
1288 		    (finfo->cyl * fd->ft->heads + finfo->head) *
1289 		    fd->ft->sectrac;
1290 		bp->bio_length = sizeof *finfo;
1291 	} else if (cmd == BIO_RDID) {
1292 		idfield = (struct fdc_readid *)data;
1293 		bp->bio_pblkno =
1294 		    (idfield->cyl * fd->ft->heads + idfield->head) *
1295 		    fd->ft->sectrac;
1296 		bp->bio_length = sizeof(struct fdc_readid);
1297 	} else if (cmd == BIO_PROBE) {
1298 		/* nothing */
1299 	} else
1300 		panic("wrong cmd in fdmisccmd()");
1301 	bp->bio_offset = bp->bio_pblkno * fd->sectorsize;
1302 	bp->bio_data = data;
1303 	bp->bio_driver1 = fd;
1304 	bp->bio_flags = 0;
1305 
1306 	fd_enqueue(fd, bp);
1307 
1308 	do {
1309 		tsleep(bp, PRIBIO, "fdwait", hz);
1310 	} while (!(bp->bio_flags & BIO_DONE));
1311 	error = bp->bio_error;
1312 
1313 	free(bp, M_TEMP);
1314 	return (error);
1315 }
1316 
1317 /*
1318  * Try figuring out the density of the media present in our device.
1319  */
1320 static int
1321 fdautoselect(struct fd_data *fd)
1322 {
1323 	struct fd_type *fdtp;
1324 	struct fdc_readid id;
1325 	int oopts, rv;
1326 
1327 	if (!(fd->ft->flags & FL_AUTO))
1328 		return (0);
1329 
1330 	fdtp = fd_native_types[fd->type];
1331 	fdsettype(fd, fdtp);
1332 	if (!(fd->ft->flags & FL_AUTO))
1333 		return (0);
1334 
1335 	/*
1336 	 * Try reading sector ID fields, first at cylinder 0, head 0,
1337 	 * then at cylinder 2, head N.  We don't probe cylinder 1,
1338 	 * since for 5.25in DD media in a HD drive, there are no data
1339 	 * to read (2 step pulses per media cylinder required).  For
1340 	 * two-sided media, the second probe always goes to head 1, so
1341 	 * we can tell them apart from single-sided media.  As a
1342 	 * side-effect this means that single-sided media should be
1343 	 * mentioned in the search list after two-sided media of an
1344 	 * otherwise identical density.  Media with a different number
1345 	 * of sectors per track but otherwise identical parameters
1346 	 * cannot be distinguished at all.
1347 	 *
1348 	 * If we successfully read an ID field on both cylinders where
1349 	 * the recorded values match our expectation, we are done.
1350 	 * Otherwise, we try the next density entry from the table.
1351 	 *
1352 	 * Stepping to cylinder 2 has the side-effect of clearing the
1353 	 * unit attention bit.
1354 	 */
1355 	oopts = fd->options;
1356 	fd->options |= FDOPT_NOERRLOG | FDOPT_NORETRY;
1357 	for (; fdtp->heads; fdtp++) {
1358 		fdsettype(fd, fdtp);
1359 
1360 		id.cyl = id.head = 0;
1361 		rv = fdmisccmd(fd, BIO_RDID, &id);
1362 		if (rv != 0)
1363 			continue;
1364 		if (id.cyl != 0 || id.head != 0 || id.secshift != fdtp->secsize)
1365 			continue;
1366 		id.cyl = 2;
1367 		id.head = fd->ft->heads - 1;
1368 		rv = fdmisccmd(fd, BIO_RDID, &id);
1369 		if (id.cyl != 2 || id.head != fdtp->heads - 1 ||
1370 		    id.secshift != fdtp->secsize)
1371 			continue;
1372 		if (rv == 0)
1373 			break;
1374 	}
1375 
1376 	fd->options = oopts;
1377 	if (fdtp->heads == 0) {
1378 		if (debugflags & 0x40)
1379 			device_printf(fd->dev, "autoselection failed\n");
1380 		fdsettype(fd, fd_native_types[fd->type]);
1381 		return (-1);
1382 	} else {
1383 		if (debugflags & 0x40) {
1384 			device_printf(fd->dev,
1385 			    "autoselected %d KB medium\n",
1386 			    fd->ft->size / 2);
1387 			fdprinttype(fd->ft);
1388 		}
1389 		return (0);
1390 	}
1391 }
1392 
1393 /*
1394  * GEOM class implementation
1395  */
1396 
1397 static g_access_t	fd_access;
1398 static g_start_t	fd_start;
1399 static g_ioctl_t	fd_ioctl;
1400 static g_provgone_t	fd_providergone;
1401 
1402 struct g_class g_fd_class = {
1403 	.name =		"FD",
1404 	.version =	G_VERSION,
1405 	.start =	fd_start,
1406 	.access =	fd_access,
1407 	.ioctl =	fd_ioctl,
1408 	.providergone = fd_providergone,
1409 };
1410 
1411 static int
1412 fd_access(struct g_provider *pp, int r, int w, int e)
1413 {
1414 	struct fd_data *fd;
1415 	struct fdc_data *fdc;
1416 	int ar, aw, ae;
1417 
1418 	fd = pp->geom->softc;
1419 	fdc = fd->fdc;
1420 
1421 	/*
1422 	 * If our provider is withering, we can only get negative requests
1423 	 * and we don't want to even see them
1424 	 */
1425 	if (pp->flags & G_PF_WITHER)
1426 		return (0);
1427 
1428 	ar = r + pp->acr;
1429 	aw = w + pp->acw;
1430 	ae = e + pp->ace;
1431 
1432 	if (ar == 0 && aw == 0 && ae == 0) {
1433 		fd->options &= ~(FDOPT_NORETRY | FDOPT_NOERRLOG | FDOPT_NOERROR);
1434 		return (0);
1435 	}
1436 
1437 	if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0) {
1438 		if (fdmisccmd(fd, BIO_PROBE, NULL))
1439 			return (ENXIO);
1440 		if (fd->flags & FD_EMPTY)
1441 			return (ENXIO);
1442 		if (fd->flags & FD_NEWDISK) {
1443 			if (fdautoselect(fd) != 0 &&
1444 			    (device_get_flags(fd->dev) & FD_NO_CHLINE)) {
1445 				mtx_lock(&fdc->fdc_mtx);
1446 				fd->flags |= FD_EMPTY;
1447 				mtx_unlock(&fdc->fdc_mtx);
1448 				return (ENXIO);
1449 			}
1450 			mtx_lock(&fdc->fdc_mtx);
1451 			fd->flags &= ~FD_NEWDISK;
1452 			mtx_unlock(&fdc->fdc_mtx);
1453 		}
1454 	}
1455 
1456 	if (w > 0 && (fd->flags & FD_WP)) {
1457 		return (EROFS);
1458 	}
1459 
1460 	pp->sectorsize = fd->sectorsize;
1461 	pp->stripesize = fd->ft->heads * fd->ft->sectrac * fd->sectorsize;
1462 	pp->mediasize = pp->stripesize * fd->ft->tracks;
1463 	return (0);
1464 }
1465 
1466 static void
1467 fd_start(struct bio *bp)
1468 {
1469  	struct fd_data *	fd;
1470 
1471 	fd = bp->bio_to->geom->softc;
1472 	bp->bio_driver1 = fd;
1473 	if (bp->bio_cmd == BIO_GETATTR) {
1474 		if (g_handleattr_int(bp, "GEOM::fwsectors", fd->ft->sectrac))
1475 			return;
1476 		if (g_handleattr_int(bp, "GEOM::fwheads", fd->ft->heads))
1477 			return;
1478 		g_io_deliver(bp, ENOIOCTL);
1479 		return;
1480 	}
1481 	if (!(bp->bio_cmd == BIO_READ || bp->bio_cmd == BIO_WRITE)) {
1482 		g_io_deliver(bp, EOPNOTSUPP);
1483 		return;
1484 	}
1485 	bp->bio_pblkno = bp->bio_offset / fd->sectorsize;
1486 	bp->bio_resid = bp->bio_length;
1487 	fd_enqueue(fd, bp);
1488 	return;
1489 }
1490 
1491 static int
1492 fd_ioctl(struct g_provider *pp, u_long cmd, void *data, int fflag, struct thread *td)
1493 {
1494 	struct fd_data *fd;
1495 	struct fdc_status *fsp;
1496 	struct fdc_readid *rid;
1497 	int error;
1498 
1499 	fd = pp->geom->softc;
1500 
1501 	switch (cmd) {
1502 	case FD_GTYPE:                  /* get drive type */
1503 		*(struct fd_type *)data = *fd->ft;
1504 		return (0);
1505 
1506 	case FD_STYPE:                  /* set drive type */
1507 		/*
1508 		 * Allow setting drive type temporarily iff
1509 		 * currently unset.  Used for fdformat so any
1510 		 * user can set it, and then start formatting.
1511 		 */
1512 		fd->fts = *(struct fd_type *)data;
1513 		if (fd->fts.sectrac) {
1514 			/* XXX: check for rubbish */
1515 			fdsettype(fd, &fd->fts);
1516 		} else {
1517 			fdsettype(fd, fd_native_types[fd->type]);
1518 		}
1519 		if (debugflags & 0x40)
1520 			fdprinttype(fd->ft);
1521 		return (0);
1522 
1523 	case FD_GOPTS:			/* get drive options */
1524 		*(int *)data = fd->options;
1525 		return (0);
1526 
1527 	case FD_SOPTS:			/* set drive options */
1528 		fd->options = *(int *)data;
1529 		return (0);
1530 
1531 	case FD_CLRERR:
1532 		error = priv_check(td, PRIV_DRIVER);
1533 		if (error)
1534 			return (error);
1535 		fd->fdc->fdc_errs = 0;
1536 		return (0);
1537 
1538 	case FD_GSTAT:
1539 		fsp = (struct fdc_status *)data;
1540 		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
1541 			return (EINVAL);
1542 		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
1543 		return (0);
1544 
1545 	case FD_GDTYPE:
1546 		*(enum fd_drivetype *)data = fd->type;
1547 		return (0);
1548 
1549 	case FD_FORM:
1550 		if (!(fflag & FWRITE))
1551 			return (EPERM);
1552 		if (((struct fd_formb *)data)->format_version !=
1553 		    FD_FORMAT_VERSION)
1554 			return (EINVAL); /* wrong version of formatting prog */
1555 		error = fdmisccmd(fd, BIO_FMT, data);
1556 		mtx_lock(&fd->fdc->fdc_mtx);
1557 		fd->flags |= FD_NEWDISK;
1558 		mtx_unlock(&fd->fdc->fdc_mtx);
1559 		break;
1560 
1561 	case FD_READID:
1562 		rid = (struct fdc_readid *)data;
1563 		if (rid->cyl > 85 || rid->head > 1)
1564 			return (EINVAL);
1565 		error = fdmisccmd(fd, BIO_RDID, data);
1566 		break;
1567 
1568 	case FIONBIO:
1569 	case FIOASYNC:
1570 		/* For backwards compat with old fd*(8) tools */
1571 		error = 0;
1572 		break;
1573 
1574 	default:
1575 		if (debugflags & 0x80)
1576 			printf("Unknown ioctl %lx\n", cmd);
1577 		error = ENOIOCTL;
1578 		break;
1579 	}
1580 	return (error);
1581 };
1582 
1583 /*
1584  * Configuration/initialization stuff, per controller.
1585  */
1586 
1587 devclass_t fdc_devclass;
1588 static devclass_t fd_devclass;
1589 
1590 struct fdc_ivars {
1591 	int	fdunit;
1592 	int	fdtype;
1593 };
1594 
1595 void
1596 fdc_release_resources(struct fdc_data *fdc)
1597 {
1598 	device_t dev;
1599 	struct resource *last;
1600 	int i;
1601 
1602 	dev = fdc->fdc_dev;
1603 	if (fdc->fdc_intr)
1604 		bus_teardown_intr(dev, fdc->res_irq, fdc->fdc_intr);
1605 	fdc->fdc_intr = NULL;
1606 	if (fdc->res_irq != NULL)
1607 		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
1608 		    fdc->res_irq);
1609 	fdc->res_irq = NULL;
1610 	last = NULL;
1611 	for (i = 0; i < FDC_MAXREG; i++) {
1612 		if (fdc->resio[i] != NULL && fdc->resio[i] != last) {
1613 			bus_release_resource(dev, SYS_RES_IOPORT,
1614 			    fdc->ridio[i], fdc->resio[i]);
1615 			last = fdc->resio[i];
1616 			fdc->resio[i] = NULL;
1617 		}
1618 	}
1619 	if (fdc->res_drq != NULL)
1620 		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
1621 		    fdc->res_drq);
1622 	fdc->res_drq = NULL;
1623 }
1624 
1625 int
1626 fdc_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1627 {
1628 	struct fdc_ivars *ivars = device_get_ivars(child);
1629 
1630 	switch (which) {
1631 	case FDC_IVAR_FDUNIT:
1632 		*result = ivars->fdunit;
1633 		break;
1634 	case FDC_IVAR_FDTYPE:
1635 		*result = ivars->fdtype;
1636 		break;
1637 	default:
1638 		return (ENOENT);
1639 	}
1640 	return (0);
1641 }
1642 
1643 int
1644 fdc_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1645 {
1646 	struct fdc_ivars *ivars = device_get_ivars(child);
1647 
1648 	switch (which) {
1649 	case FDC_IVAR_FDUNIT:
1650 		ivars->fdunit = value;
1651 		break;
1652 	case FDC_IVAR_FDTYPE:
1653 		ivars->fdtype = value;
1654 		break;
1655 	default:
1656 		return (ENOENT);
1657 	}
1658 	return (0);
1659 }
1660 
1661 int
1662 fdc_initial_reset(device_t dev, struct fdc_data *fdc)
1663 {
1664 	int ic_type, part_id;
1665 
1666 	/*
1667 	 * A status value of 0xff is very unlikely, but not theoretically
1668 	 * impossible, but it is far more likely to indicate an empty bus.
1669 	 */
1670 	if (fdsts_rd(fdc) == 0xff)
1671 		return (ENXIO);
1672 
1673 	/*
1674 	 * Assert a reset to the floppy controller and check that the status
1675 	 * register goes to zero.
1676 	 */
1677 	fdout_wr(fdc, 0);
1678 	fdout_wr(fdc, 0);
1679 	if (fdsts_rd(fdc) != 0)
1680 		return (ENXIO);
1681 
1682 	/*
1683 	 * Clear the reset and see it come ready.
1684 	 */
1685 	fdout_wr(fdc, FDO_FRST);
1686 	DELAY(100);
1687 	if (fdsts_rd(fdc) != 0x80)
1688 		return (ENXIO);
1689 
1690 	/* Then, see if it can handle a command. */
1691 	if (fdc_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(6, 240),
1692 	    NE7_SPEC_2(31, 0), 0))
1693 		return (ENXIO);
1694 
1695 	/*
1696 	 * Try to identify the chip.
1697 	 *
1698 	 * The i8272 datasheet documents that unknown commands
1699 	 * will return ST0 as 0x80.  The i8272 is supposedly identical
1700 	 * to the NEC765.
1701 	 * The i82077SL datasheet says 0x90 for the VERSION command,
1702 	 * and several "superio" chips emulate this.
1703 	 */
1704 	if (fdc_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type))
1705 		return (ENXIO);
1706 	if (fdc_cmd(fdc, 1, 0x18, 1, &part_id))
1707 		return (ENXIO);
1708 	if (bootverbose)
1709 		device_printf(dev,
1710 		    "ic_type %02x part_id %02x\n", ic_type, part_id);
1711 	switch (ic_type & 0xff) {
1712 	case 0x80:
1713 		device_set_desc(dev, "NEC 765 or clone");
1714 		fdc->fdct = FDC_NE765;
1715 		break;
1716 	case 0x81:
1717 	case 0x90:
1718 		device_set_desc(dev,
1719 		    "Enhanced floppy controller");
1720 		fdc->fdct = FDC_ENHANCED;
1721 		break;
1722 	default:
1723 		device_set_desc(dev, "Generic floppy controller");
1724 		fdc->fdct = FDC_UNKNOWN;
1725 		break;
1726 	}
1727 	return (0);
1728 }
1729 
1730 int
1731 fdc_detach(device_t dev)
1732 {
1733 	struct	fdc_data *fdc;
1734 	int	error;
1735 
1736 	fdc = device_get_softc(dev);
1737 
1738 	/* have our children detached first */
1739 	if ((error = bus_generic_detach(dev)))
1740 		return (error);
1741 
1742 	if (fdc->fdc_intr)
1743 		bus_teardown_intr(dev, fdc->res_irq, fdc->fdc_intr);
1744 	fdc->fdc_intr = NULL;
1745 
1746 	/* kill worker thread */
1747 	mtx_lock(&fdc->fdc_mtx);
1748 	fdc->flags |= FDC_KTHREAD_EXIT;
1749 	wakeup(&fdc->head);
1750 	while ((fdc->flags & FDC_KTHREAD_ALIVE) != 0)
1751 		msleep(fdc->fdc_thread, &fdc->fdc_mtx, PRIBIO, "fdcdet", 0);
1752 	mtx_unlock(&fdc->fdc_mtx);
1753 
1754 	/* reset controller, turn motor off */
1755 	fdout_wr(fdc, 0);
1756 
1757 	if (!(fdc->flags & FDC_NODMA))
1758 		isa_dma_release(fdc->dmachan);
1759 	fdc_release_resources(fdc);
1760 	mtx_destroy(&fdc->fdc_mtx);
1761 	return (0);
1762 }
1763 
1764 /*
1765  * Add a child device to the fdc controller.  It will then be probed etc.
1766  */
1767 device_t
1768 fdc_add_child(device_t dev, const char *name, int unit)
1769 {
1770 	struct fdc_ivars *ivar;
1771 	device_t child;
1772 
1773 	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT | M_ZERO);
1774 	if (ivar == NULL)
1775 		return (NULL);
1776 	child = device_add_child(dev, name, unit);
1777 	if (child == NULL) {
1778 		free(ivar, M_DEVBUF);
1779 		return (NULL);
1780 	}
1781 	device_set_ivars(child, ivar);
1782 	ivar->fdunit = unit;
1783 	ivar->fdtype = FDT_NONE;
1784 	if (resource_disabled(name, unit))
1785 		device_disable(child);
1786 	return (child);
1787 }
1788 
1789 int
1790 fdc_attach(device_t dev)
1791 {
1792 	struct	fdc_data *fdc;
1793 	int	error;
1794 
1795 	fdc = device_get_softc(dev);
1796 	fdc->fdc_dev = dev;
1797 	error = fdc_initial_reset(dev, fdc);
1798 	if (error) {
1799 		device_printf(dev, "does not respond\n");
1800 		return (error);
1801 	}
1802 	error = bus_setup_intr(dev, fdc->res_irq,
1803 	    INTR_TYPE_BIO | INTR_ENTROPY |
1804 	    ((fdc->flags & FDC_NOFAST) ? INTR_MPSAFE : 0),
1805             ((fdc->flags & FDC_NOFAST) ? NULL : fdc_intr_fast),
1806 	    ((fdc->flags & FDC_NOFAST) ? fdc_intr : NULL),
1807 			       fdc, &fdc->fdc_intr);
1808 	if (error) {
1809 		device_printf(dev, "cannot setup interrupt\n");
1810 		return (error);
1811 	}
1812 	if (!(fdc->flags & FDC_NODMA)) {
1813 		error = isa_dma_acquire(fdc->dmachan);
1814 		if (!error) {
1815 			error = isa_dma_init(fdc->dmachan,
1816 			    MAX_BYTES_PER_CYL, M_WAITOK);
1817 			if (error)
1818 				isa_dma_release(fdc->dmachan);
1819 		}
1820 		if (error)
1821 			return (error);
1822 	}
1823 	fdc->fdcu = device_get_unit(dev);
1824 	fdc->flags |= FDC_NEEDS_RESET;
1825 
1826 	mtx_init(&fdc->fdc_mtx, "fdc lock", NULL, MTX_DEF);
1827 
1828 	/* reset controller, turn motor off, clear fdout mirror reg */
1829 	fdout_wr(fdc, fdc->fdout = 0);
1830 	bioq_init(&fdc->head);
1831 
1832 	settle = hz / 8;
1833 
1834 	return (0);
1835 }
1836 
1837 void
1838 fdc_start_worker(device_t dev)
1839 {
1840 	struct	fdc_data *fdc;
1841 
1842 	fdc = device_get_softc(dev);
1843 	kproc_create(fdc_thread, fdc, &fdc->fdc_thread, 0, 0,
1844 	    "fdc%d", device_get_unit(dev));
1845 }
1846 
1847 int
1848 fdc_hints_probe(device_t dev)
1849 {
1850 	const char *name, *dname;
1851 	int i, error, dunit;
1852 
1853 	/*
1854 	 * Probe and attach any children.  We should probably detect
1855 	 * devices from the BIOS unless overridden.
1856 	 */
1857 	name = device_get_nameunit(dev);
1858 	i = 0;
1859 	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0) {
1860 		resource_int_value(dname, dunit, "drive", &dunit);
1861 		fdc_add_child(dev, dname, dunit);
1862 	}
1863 
1864 	if ((error = bus_generic_attach(dev)) != 0)
1865 		return (error);
1866 	return (0);
1867 }
1868 
1869 int
1870 fdc_print_child(device_t me, device_t child)
1871 {
1872 	int retval = 0, flags;
1873 
1874 	retval += bus_print_child_header(me, child);
1875 	retval += printf(" on %s drive %d", device_get_nameunit(me),
1876 	       fdc_get_fdunit(child));
1877 	if ((flags = device_get_flags(me)) != 0)
1878 		retval += printf(" flags %#x", flags);
1879 	retval += printf("\n");
1880 
1881 	return (retval);
1882 }
1883 
1884 /*
1885  * Configuration/initialization, per drive.
1886  */
1887 static int
1888 fd_probe(device_t dev)
1889 {
1890 	int	unit;
1891 	int	i;
1892 	u_int	st0, st3;
1893 	struct	fd_data *fd;
1894 	struct	fdc_data *fdc;
1895 	int	fdsu;
1896 	int	flags, type;
1897 
1898 	fdsu = fdc_get_fdunit(dev);
1899 	fd = device_get_softc(dev);
1900 	fdc = device_get_softc(device_get_parent(dev));
1901 	flags = device_get_flags(dev);
1902 
1903 	fd->dev = dev;
1904 	fd->fdc = fdc;
1905 	fd->fdsu = fdsu;
1906 	unit = device_get_unit(dev);
1907 
1908 	/* Auto-probe if fdinfo is present, but always allow override. */
1909 	type = flags & FD_TYPEMASK;
1910 	if (type == FDT_NONE && (type = fdc_get_fdtype(dev)) != FDT_NONE) {
1911 		fd->type = type;
1912 		goto done;
1913 	} else {
1914 		/* make sure fdautoselect() will be called */
1915 		fd->flags = FD_EMPTY;
1916 		fd->type = type;
1917 	}
1918 
1919 #if defined(__i386__) || defined(__amd64__)
1920 	if (fd->type == FDT_NONE && (unit == 0 || unit == 1)) {
1921 		/* Look up what the BIOS thinks we have. */
1922 		if (unit == 0)
1923 			fd->type = (rtcin(RTC_FDISKETTE) & 0xf0) >> 4;
1924 		else
1925 			fd->type = rtcin(RTC_FDISKETTE) & 0x0f;
1926 		if (fd->type == FDT_288M_1)
1927 			fd->type = FDT_288M;
1928 	}
1929 #endif /* __i386__ || __amd64__ */
1930 	/* is there a unit? */
1931 	if (fd->type == FDT_NONE)
1932 		return (ENXIO);
1933 
1934 	mtx_lock(&fdc->fdc_mtx);
1935 
1936 	/* select it */
1937 	fd_select(fd);
1938 	fd_motor(fd, 1);
1939 	fdc->fd = fd;
1940 	fdc_reset(fdc);		/* XXX reset, then unreset, etc. */
1941 	DELAY(1000000);	/* 1 sec */
1942 
1943 	if ((flags & FD_NO_PROBE) == 0) {
1944 		/* If we're at track 0 first seek inwards. */
1945 		if ((fdc_sense_drive(fdc, &st3) == 0) &&
1946 		    (st3 & NE7_ST3_T0)) {
1947 			/* Seek some steps... */
1948 			if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1949 				/* ...wait a moment... */
1950 				DELAY(300000);
1951 				/* make ctrlr happy: */
1952 				fdc_sense_int(fdc, NULL, NULL);
1953 			}
1954 		}
1955 
1956 		for (i = 0; i < 2; i++) {
1957 			/*
1958 			 * we must recalibrate twice, just in case the
1959 			 * heads have been beyond cylinder 76, since
1960 			 * most FDCs still barf when attempting to
1961 			 * recalibrate more than 77 steps
1962 			 */
1963 			/* go back to 0: */
1964 			if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1965 				/* a second being enough for full stroke seek*/
1966 				DELAY(i == 0 ? 1000000 : 300000);
1967 
1968 				/* anything responding? */
1969 				if (fdc_sense_int(fdc, &st0, NULL) == 0 &&
1970 				    (st0 & NE7_ST0_EC) == 0)
1971 					break; /* already probed successfully */
1972 			}
1973 		}
1974 	}
1975 
1976 	fd_motor(fd, 0);
1977 	fdc->fd = NULL;
1978 	mtx_unlock(&fdc->fdc_mtx);
1979 
1980 	if ((flags & FD_NO_PROBE) == 0 &&
1981 	    (st0 & NE7_ST0_EC) != 0) /* no track 0 -> no drive present */
1982 		return (ENXIO);
1983 
1984 done:
1985 
1986 	switch (fd->type) {
1987 	case FDT_12M:
1988 		device_set_desc(dev, "1200-KB 5.25\" drive");
1989 		break;
1990 	case FDT_144M:
1991 		device_set_desc(dev, "1440-KB 3.5\" drive");
1992 		break;
1993 	case FDT_288M:
1994 		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1995 		break;
1996 	case FDT_360K:
1997 		device_set_desc(dev, "360-KB 5.25\" drive");
1998 		break;
1999 	case FDT_720K:
2000 		device_set_desc(dev, "720-KB 3.5\" drive");
2001 		break;
2002 	default:
2003 		return (ENXIO);
2004 	}
2005 	fd->track = FD_NO_TRACK;
2006 	fd->fdc = fdc;
2007 	fd->fdsu = fdsu;
2008 	fd->options = 0;
2009 	callout_init_mtx(&fd->toffhandle, &fd->fdc->fdc_mtx, 0);
2010 
2011 	/* initialize densities for subdevices */
2012 	fdsettype(fd, fd_native_types[fd->type]);
2013 	return (0);
2014 }
2015 
2016 /*
2017  * We have to do this in a geom event because GEOM is not running
2018  * when fd_attach() is.
2019  * XXX: move fd_attach after geom like ata/scsi disks
2020  */
2021 static void
2022 fd_attach2(void *arg, int flag)
2023 {
2024 	struct	fd_data *fd;
2025 
2026 	fd = arg;
2027 
2028 	fd->fd_geom = g_new_geomf(&g_fd_class,
2029 	    "fd%d", device_get_unit(fd->dev));
2030 	fd->fd_provider = g_new_providerf(fd->fd_geom, "%s", fd->fd_geom->name);
2031 	fd->fd_geom->softc = fd;
2032 	g_error_provider(fd->fd_provider, 0);
2033 }
2034 
2035 static int
2036 fd_attach(device_t dev)
2037 {
2038 	struct	fd_data *fd;
2039 
2040 	fd = device_get_softc(dev);
2041 	g_post_event(fd_attach2, fd, M_WAITOK, NULL);
2042 	fd->flags |= FD_EMPTY;
2043 	bioq_init(&fd->fd_bq);
2044 
2045 	return (0);
2046 }
2047 
2048 static void
2049 fd_providergone(struct g_provider *pp)
2050 {
2051 	struct fd_data *fd;
2052 
2053 	fd = pp->geom->softc;
2054 	fd->gone = true;
2055 	wakeup(fd);
2056 }
2057 
2058 static void
2059 fd_detach_geom(void *arg, int flag)
2060 {
2061 	struct	fd_data *fd = arg;
2062 
2063 	g_topology_assert();
2064 	g_wither_geom(fd->fd_geom, ENXIO);
2065 }
2066 
2067 static int
2068 fd_detach(device_t dev)
2069 {
2070 	struct	fd_data *fd;
2071 
2072 	fd = device_get_softc(dev);
2073 
2074 	g_waitfor_event(fd_detach_geom, fd, M_WAITOK, NULL);
2075 	while (!fd->gone) {
2076 		tsleep(fd, PZERO, "fdgone", hz/10);
2077 	}
2078 
2079 	/*
2080 	 * There may be accesses to the floppy while we're waitng, so drain the
2081 	 * motor callback here. fdc_detach turns off motor if it's still on when
2082 	 * we get to this point.
2083 	 */
2084 	callout_drain(&fd->toffhandle);
2085 
2086 	return (0);
2087 }
2088 
2089 static device_method_t fd_methods[] = {
2090 	/* Device interface */
2091 	DEVMETHOD(device_probe,		fd_probe),
2092 	DEVMETHOD(device_attach,	fd_attach),
2093 	DEVMETHOD(device_detach,	fd_detach),
2094 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
2095 	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
2096 	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
2097 	{ 0, 0 }
2098 };
2099 
2100 static driver_t fd_driver = {
2101 	"fd",
2102 	fd_methods,
2103 	sizeof(struct fd_data)
2104 };
2105 
2106 static int
2107 fdc_modevent(module_t mod, int type, void *data)
2108 {
2109 
2110 	return (g_modevent(NULL, type, &g_fd_class));
2111 }
2112 
2113 DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, fdc_modevent, 0);
2114