xref: /freebsd/sys/dev/fdc/fdc.c (revision 9768746b)
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 struct fdc_ivars {
1587 	int	fdunit;
1588 	int	fdtype;
1589 };
1590 
1591 void
1592 fdc_release_resources(struct fdc_data *fdc)
1593 {
1594 	device_t dev;
1595 	struct resource *last;
1596 	int i;
1597 
1598 	dev = fdc->fdc_dev;
1599 	if (fdc->fdc_intr)
1600 		bus_teardown_intr(dev, fdc->res_irq, fdc->fdc_intr);
1601 	fdc->fdc_intr = NULL;
1602 	if (fdc->res_irq != NULL)
1603 		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
1604 		    fdc->res_irq);
1605 	fdc->res_irq = NULL;
1606 	last = NULL;
1607 	for (i = 0; i < FDC_MAXREG; i++) {
1608 		if (fdc->resio[i] != NULL && fdc->resio[i] != last) {
1609 			bus_release_resource(dev, SYS_RES_IOPORT,
1610 			    fdc->ridio[i], fdc->resio[i]);
1611 			last = fdc->resio[i];
1612 			fdc->resio[i] = NULL;
1613 		}
1614 	}
1615 	if (fdc->res_drq != NULL)
1616 		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
1617 		    fdc->res_drq);
1618 	fdc->res_drq = NULL;
1619 }
1620 
1621 int
1622 fdc_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1623 {
1624 	struct fdc_ivars *ivars = device_get_ivars(child);
1625 
1626 	switch (which) {
1627 	case FDC_IVAR_FDUNIT:
1628 		*result = ivars->fdunit;
1629 		break;
1630 	case FDC_IVAR_FDTYPE:
1631 		*result = ivars->fdtype;
1632 		break;
1633 	default:
1634 		return (ENOENT);
1635 	}
1636 	return (0);
1637 }
1638 
1639 int
1640 fdc_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1641 {
1642 	struct fdc_ivars *ivars = device_get_ivars(child);
1643 
1644 	switch (which) {
1645 	case FDC_IVAR_FDUNIT:
1646 		ivars->fdunit = value;
1647 		break;
1648 	case FDC_IVAR_FDTYPE:
1649 		ivars->fdtype = value;
1650 		break;
1651 	default:
1652 		return (ENOENT);
1653 	}
1654 	return (0);
1655 }
1656 
1657 int
1658 fdc_initial_reset(device_t dev, struct fdc_data *fdc)
1659 {
1660 	int ic_type, part_id;
1661 
1662 	/*
1663 	 * A status value of 0xff is very unlikely, but not theoretically
1664 	 * impossible, but it is far more likely to indicate an empty bus.
1665 	 */
1666 	if (fdsts_rd(fdc) == 0xff)
1667 		return (ENXIO);
1668 
1669 	/*
1670 	 * Assert a reset to the floppy controller and check that the status
1671 	 * register goes to zero.
1672 	 */
1673 	fdout_wr(fdc, 0);
1674 	fdout_wr(fdc, 0);
1675 	if (fdsts_rd(fdc) != 0)
1676 		return (ENXIO);
1677 
1678 	/*
1679 	 * Clear the reset and see it come ready.
1680 	 */
1681 	fdout_wr(fdc, FDO_FRST);
1682 	DELAY(100);
1683 	if (fdsts_rd(fdc) != 0x80)
1684 		return (ENXIO);
1685 
1686 	/* Then, see if it can handle a command. */
1687 	if (fdc_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(6, 240),
1688 	    NE7_SPEC_2(31, 0), 0))
1689 		return (ENXIO);
1690 
1691 	/*
1692 	 * Try to identify the chip.
1693 	 *
1694 	 * The i8272 datasheet documents that unknown commands
1695 	 * will return ST0 as 0x80.  The i8272 is supposedly identical
1696 	 * to the NEC765.
1697 	 * The i82077SL datasheet says 0x90 for the VERSION command,
1698 	 * and several "superio" chips emulate this.
1699 	 */
1700 	if (fdc_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type))
1701 		return (ENXIO);
1702 	if (fdc_cmd(fdc, 1, 0x18, 1, &part_id))
1703 		return (ENXIO);
1704 	if (bootverbose)
1705 		device_printf(dev,
1706 		    "ic_type %02x part_id %02x\n", ic_type, part_id);
1707 	switch (ic_type & 0xff) {
1708 	case 0x80:
1709 		device_set_desc(dev, "NEC 765 or clone");
1710 		fdc->fdct = FDC_NE765;
1711 		break;
1712 	case 0x81:
1713 	case 0x90:
1714 		device_set_desc(dev,
1715 		    "Enhanced floppy controller");
1716 		fdc->fdct = FDC_ENHANCED;
1717 		break;
1718 	default:
1719 		device_set_desc(dev, "Generic floppy controller");
1720 		fdc->fdct = FDC_UNKNOWN;
1721 		break;
1722 	}
1723 	return (0);
1724 }
1725 
1726 int
1727 fdc_detach(device_t dev)
1728 {
1729 	struct	fdc_data *fdc;
1730 	int	error;
1731 
1732 	fdc = device_get_softc(dev);
1733 
1734 	/* have our children detached first */
1735 	if ((error = bus_generic_detach(dev)))
1736 		return (error);
1737 
1738 	if (fdc->fdc_intr)
1739 		bus_teardown_intr(dev, fdc->res_irq, fdc->fdc_intr);
1740 	fdc->fdc_intr = NULL;
1741 
1742 	/* kill worker thread */
1743 	mtx_lock(&fdc->fdc_mtx);
1744 	fdc->flags |= FDC_KTHREAD_EXIT;
1745 	wakeup(&fdc->head);
1746 	while ((fdc->flags & FDC_KTHREAD_ALIVE) != 0)
1747 		msleep(fdc->fdc_thread, &fdc->fdc_mtx, PRIBIO, "fdcdet", 0);
1748 	mtx_unlock(&fdc->fdc_mtx);
1749 
1750 	/* reset controller, turn motor off */
1751 	fdout_wr(fdc, 0);
1752 
1753 	if (!(fdc->flags & FDC_NODMA))
1754 		isa_dma_release(fdc->dmachan);
1755 	fdc_release_resources(fdc);
1756 	mtx_destroy(&fdc->fdc_mtx);
1757 	return (0);
1758 }
1759 
1760 /*
1761  * Add a child device to the fdc controller.  It will then be probed etc.
1762  */
1763 device_t
1764 fdc_add_child(device_t dev, const char *name, int unit)
1765 {
1766 	struct fdc_ivars *ivar;
1767 	device_t child;
1768 
1769 	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT | M_ZERO);
1770 	if (ivar == NULL)
1771 		return (NULL);
1772 	child = device_add_child(dev, name, unit);
1773 	if (child == NULL) {
1774 		free(ivar, M_DEVBUF);
1775 		return (NULL);
1776 	}
1777 	device_set_ivars(child, ivar);
1778 	ivar->fdunit = unit;
1779 	ivar->fdtype = FDT_NONE;
1780 	if (resource_disabled(name, unit))
1781 		device_disable(child);
1782 	return (child);
1783 }
1784 
1785 int
1786 fdc_attach(device_t dev)
1787 {
1788 	struct	fdc_data *fdc;
1789 	int	error;
1790 
1791 	fdc = device_get_softc(dev);
1792 	fdc->fdc_dev = dev;
1793 	error = fdc_initial_reset(dev, fdc);
1794 	if (error) {
1795 		device_printf(dev, "does not respond\n");
1796 		return (error);
1797 	}
1798 	error = bus_setup_intr(dev, fdc->res_irq,
1799 	    INTR_TYPE_BIO | INTR_ENTROPY |
1800 	    ((fdc->flags & FDC_NOFAST) ? INTR_MPSAFE : 0),
1801             ((fdc->flags & FDC_NOFAST) ? NULL : fdc_intr_fast),
1802 	    ((fdc->flags & FDC_NOFAST) ? fdc_intr : NULL),
1803 			       fdc, &fdc->fdc_intr);
1804 	if (error) {
1805 		device_printf(dev, "cannot setup interrupt\n");
1806 		return (error);
1807 	}
1808 	if (!(fdc->flags & FDC_NODMA)) {
1809 		error = isa_dma_acquire(fdc->dmachan);
1810 		if (!error) {
1811 			error = isa_dma_init(fdc->dmachan,
1812 			    MAX_BYTES_PER_CYL, M_WAITOK);
1813 			if (error)
1814 				isa_dma_release(fdc->dmachan);
1815 		}
1816 		if (error)
1817 			return (error);
1818 	}
1819 	fdc->fdcu = device_get_unit(dev);
1820 	fdc->flags |= FDC_NEEDS_RESET;
1821 
1822 	mtx_init(&fdc->fdc_mtx, "fdc lock", NULL, MTX_DEF);
1823 
1824 	/* reset controller, turn motor off, clear fdout mirror reg */
1825 	fdout_wr(fdc, fdc->fdout = 0);
1826 	bioq_init(&fdc->head);
1827 
1828 	settle = hz / 8;
1829 
1830 	return (0);
1831 }
1832 
1833 void
1834 fdc_start_worker(device_t dev)
1835 {
1836 	struct	fdc_data *fdc;
1837 
1838 	fdc = device_get_softc(dev);
1839 	kproc_create(fdc_thread, fdc, &fdc->fdc_thread, 0, 0,
1840 	    "fdc%d", device_get_unit(dev));
1841 }
1842 
1843 int
1844 fdc_hints_probe(device_t dev)
1845 {
1846 	const char *name, *dname;
1847 	int i, error, dunit;
1848 
1849 	/*
1850 	 * Probe and attach any children.  We should probably detect
1851 	 * devices from the BIOS unless overridden.
1852 	 */
1853 	name = device_get_nameunit(dev);
1854 	i = 0;
1855 	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0) {
1856 		resource_int_value(dname, dunit, "drive", &dunit);
1857 		fdc_add_child(dev, dname, dunit);
1858 	}
1859 
1860 	if ((error = bus_generic_attach(dev)) != 0)
1861 		return (error);
1862 	return (0);
1863 }
1864 
1865 int
1866 fdc_print_child(device_t me, device_t child)
1867 {
1868 	int retval = 0, flags;
1869 
1870 	retval += bus_print_child_header(me, child);
1871 	retval += printf(" on %s drive %d", device_get_nameunit(me),
1872 	       fdc_get_fdunit(child));
1873 	if ((flags = device_get_flags(me)) != 0)
1874 		retval += printf(" flags %#x", flags);
1875 	retval += printf("\n");
1876 
1877 	return (retval);
1878 }
1879 
1880 /*
1881  * Configuration/initialization, per drive.
1882  */
1883 static int
1884 fd_probe(device_t dev)
1885 {
1886 #if defined(__i386__) || defined(__amd64__)
1887 	int	unit;
1888 #endif
1889 	int	i;
1890 	u_int	st0, st3;
1891 	struct	fd_data *fd;
1892 	struct	fdc_data *fdc;
1893 	int	fdsu;
1894 	int	flags, type;
1895 
1896 	fdsu = fdc_get_fdunit(dev);
1897 	fd = device_get_softc(dev);
1898 	fdc = device_get_softc(device_get_parent(dev));
1899 	flags = device_get_flags(dev);
1900 
1901 	fd->dev = dev;
1902 	fd->fdc = fdc;
1903 	fd->fdsu = fdsu;
1904 
1905 	/* Auto-probe if fdinfo is present, but always allow override. */
1906 	type = flags & FD_TYPEMASK;
1907 	if (type == FDT_NONE && (type = fdc_get_fdtype(dev)) != FDT_NONE) {
1908 		fd->type = type;
1909 		goto done;
1910 	} else {
1911 		/* make sure fdautoselect() will be called */
1912 		fd->flags = FD_EMPTY;
1913 		fd->type = type;
1914 	}
1915 
1916 #if defined(__i386__) || defined(__amd64__)
1917 	unit = device_get_unit(dev);
1918 	if (fd->type == FDT_NONE && (unit == 0 || unit == 1)) {
1919 		/* Look up what the BIOS thinks we have. */
1920 		if (unit == 0)
1921 			fd->type = (rtcin(RTC_FDISKETTE) & 0xf0) >> 4;
1922 		else
1923 			fd->type = rtcin(RTC_FDISKETTE) & 0x0f;
1924 		if (fd->type == FDT_288M_1)
1925 			fd->type = FDT_288M;
1926 	}
1927 #endif /* __i386__ || __amd64__ */
1928 	/* is there a unit? */
1929 	if (fd->type == FDT_NONE)
1930 		return (ENXIO);
1931 
1932 	mtx_lock(&fdc->fdc_mtx);
1933 
1934 	/* select it */
1935 	fd_select(fd);
1936 	fd_motor(fd, 1);
1937 	fdc->fd = fd;
1938 	fdc_reset(fdc);		/* XXX reset, then unreset, etc. */
1939 	DELAY(1000000);	/* 1 sec */
1940 
1941 	if ((flags & FD_NO_PROBE) == 0) {
1942 		/* If we're at track 0 first seek inwards. */
1943 		if ((fdc_sense_drive(fdc, &st3) == 0) &&
1944 		    (st3 & NE7_ST3_T0)) {
1945 			/* Seek some steps... */
1946 			if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1947 				/* ...wait a moment... */
1948 				DELAY(300000);
1949 				/* make ctrlr happy: */
1950 				fdc_sense_int(fdc, NULL, NULL);
1951 			}
1952 		}
1953 
1954 		for (i = 0; i < 2; i++) {
1955 			/*
1956 			 * we must recalibrate twice, just in case the
1957 			 * heads have been beyond cylinder 76, since
1958 			 * most FDCs still barf when attempting to
1959 			 * recalibrate more than 77 steps
1960 			 */
1961 			/* go back to 0: */
1962 			if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1963 				/* a second being enough for full stroke seek*/
1964 				DELAY(i == 0 ? 1000000 : 300000);
1965 
1966 				/* anything responding? */
1967 				if (fdc_sense_int(fdc, &st0, NULL) == 0 &&
1968 				    (st0 & NE7_ST0_EC) == 0)
1969 					break; /* already probed successfully */
1970 			}
1971 		}
1972 	}
1973 
1974 	fd_motor(fd, 0);
1975 	fdc->fd = NULL;
1976 	mtx_unlock(&fdc->fdc_mtx);
1977 
1978 	if ((flags & FD_NO_PROBE) == 0 &&
1979 	    (st0 & NE7_ST0_EC) != 0) /* no track 0 -> no drive present */
1980 		return (ENXIO);
1981 
1982 done:
1983 
1984 	switch (fd->type) {
1985 	case FDT_12M:
1986 		device_set_desc(dev, "1200-KB 5.25\" drive");
1987 		break;
1988 	case FDT_144M:
1989 		device_set_desc(dev, "1440-KB 3.5\" drive");
1990 		break;
1991 	case FDT_288M:
1992 		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1993 		break;
1994 	case FDT_360K:
1995 		device_set_desc(dev, "360-KB 5.25\" drive");
1996 		break;
1997 	case FDT_720K:
1998 		device_set_desc(dev, "720-KB 3.5\" drive");
1999 		break;
2000 	default:
2001 		return (ENXIO);
2002 	}
2003 	fd->track = FD_NO_TRACK;
2004 	fd->fdc = fdc;
2005 	fd->fdsu = fdsu;
2006 	fd->options = 0;
2007 	callout_init_mtx(&fd->toffhandle, &fd->fdc->fdc_mtx, 0);
2008 
2009 	/* initialize densities for subdevices */
2010 	fdsettype(fd, fd_native_types[fd->type]);
2011 	return (0);
2012 }
2013 
2014 /*
2015  * We have to do this in a geom event because GEOM is not running
2016  * when fd_attach() is.
2017  * XXX: move fd_attach after geom like ata/scsi disks
2018  */
2019 static void
2020 fd_attach2(void *arg, int flag)
2021 {
2022 	struct	fd_data *fd;
2023 
2024 	fd = arg;
2025 
2026 	fd->fd_geom = g_new_geomf(&g_fd_class,
2027 	    "fd%d", device_get_unit(fd->dev));
2028 	fd->fd_provider = g_new_providerf(fd->fd_geom, "%s", fd->fd_geom->name);
2029 	fd->fd_geom->softc = fd;
2030 	g_error_provider(fd->fd_provider, 0);
2031 }
2032 
2033 static int
2034 fd_attach(device_t dev)
2035 {
2036 	struct	fd_data *fd;
2037 
2038 	fd = device_get_softc(dev);
2039 	g_post_event(fd_attach2, fd, M_WAITOK, NULL);
2040 	fd->flags |= FD_EMPTY;
2041 	bioq_init(&fd->fd_bq);
2042 
2043 	return (0);
2044 }
2045 
2046 static void
2047 fd_providergone(struct g_provider *pp)
2048 {
2049 	struct fd_data *fd;
2050 
2051 	fd = pp->geom->softc;
2052 	fd->gone = true;
2053 	wakeup(fd);
2054 }
2055 
2056 static void
2057 fd_detach_geom(void *arg, int flag)
2058 {
2059 	struct	fd_data *fd = arg;
2060 
2061 	g_topology_assert();
2062 	g_wither_geom(fd->fd_geom, ENXIO);
2063 }
2064 
2065 static int
2066 fd_detach(device_t dev)
2067 {
2068 	struct	fd_data *fd;
2069 
2070 	fd = device_get_softc(dev);
2071 
2072 	g_waitfor_event(fd_detach_geom, fd, M_WAITOK, NULL);
2073 	while (!fd->gone) {
2074 		tsleep(fd, PZERO, "fdgone", hz/10);
2075 	}
2076 
2077 	/*
2078 	 * There may be accesses to the floppy while we're waitng, so drain the
2079 	 * motor callback here. fdc_detach turns off motor if it's still on when
2080 	 * we get to this point.
2081 	 */
2082 	callout_drain(&fd->toffhandle);
2083 
2084 	return (0);
2085 }
2086 
2087 static device_method_t fd_methods[] = {
2088 	/* Device interface */
2089 	DEVMETHOD(device_probe,		fd_probe),
2090 	DEVMETHOD(device_attach,	fd_attach),
2091 	DEVMETHOD(device_detach,	fd_detach),
2092 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
2093 	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
2094 	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
2095 	{ 0, 0 }
2096 };
2097 
2098 static driver_t fd_driver = {
2099 	"fd",
2100 	fd_methods,
2101 	sizeof(struct fd_data)
2102 };
2103 
2104 static int
2105 fdc_modevent(module_t mod, int type, void *data)
2106 {
2107 
2108 	return (g_modevent(NULL, type, &g_fd_class));
2109 }
2110 
2111 DRIVER_MODULE(fd, fdc, fd_driver, fdc_modevent, 0);
2112