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