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