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