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