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