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