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