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