xref: /freebsd/sys/dev/fdc/fdc.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Don Ahn.
7  *
8  * Libretto PCMCIA floppy support by David Horwitt (dhorwitt@ucsd.edu)
9  * aided by the Linux floppy driver modifications from David Bateman
10  * (dbateman@eng.uts.edu.au).
11  *
12  * Copyright (c) 1993, 1994 by
13  *  jc@irbs.UUCP (John Capo)
14  *  vak@zebub.msk.su (Serge Vakulenko)
15  *  ache@astral.msk.su (Andrew A. Chernov)
16  *
17  * Copyright (c) 1993, 1994, 1995 by
18  *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
19  *  dufault@hda.com (Peter Dufault)
20  *
21  * Copyright (c) 2001 Joerg Wunsch,
22  *  joerg_wunsch@uriah.heep.sax.de (Joerg Wunsch)
23  *
24  * Redistribution and use in source and binary forms, with or without
25  * modification, are permitted provided that the following conditions
26  * are met:
27  * 1. Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  * 2. Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in the
31  *    documentation and/or other materials provided with the distribution.
32  * 3. All advertising materials mentioning features or use of this software
33  *    must display the following acknowledgement:
34  *	This product includes software developed by the University of
35  *	California, Berkeley and its contributors.
36  * 4. Neither the name of the University nor the names of its contributors
37  *    may be used to endorse or promote products derived from this software
38  *    without specific prior written permission.
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  *	from:	@(#)fd.c	7.4 (Berkeley) 5/25/91
53  * $FreeBSD$
54  */
55 
56 #include "opt_fdc.h"
57 #include "card.h"
58 
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/bus.h>
63 #include <sys/conf.h>
64 #include <sys/devicestat.h>
65 #include <sys/disklabel.h>
66 #include <sys/fcntl.h>
67 #include <sys/fdcio.h>
68 #include <sys/kernel.h>
69 #include <sys/lock.h>
70 #include <sys/malloc.h>
71 #include <sys/module.h>
72 #include <sys/mutex.h>
73 #include <sys/proc.h>
74 #include <sys/syslog.h>
75 
76 #include <machine/bus.h>
77 #include <sys/rman.h>
78 
79 #include <machine/clock.h>
80 #include <machine/resource.h>
81 #include <machine/stdarg.h>
82 
83 #include <isa/isavar.h>
84 #include <isa/isareg.h>
85 #include <isa/fdreg.h>
86 #include <isa/fdc.h>
87 #include <isa/rtc.h>
88 
89 /* configuration flags */
90 #define FDC_PRETEND_D0	(1 << 0)	/* pretend drive 0 to be there */
91 #define FDC_NO_FIFO	(1 << 2)	/* do not enable FIFO  */
92 
93 /* internally used only, not really from CMOS: */
94 #define RTCFDT_144M_PRETENDED	0x1000
95 
96 /* error returns for fd_cmd() */
97 #define FD_FAILED -1
98 #define FD_NOT_VALID -2
99 #define FDC_ERRMAX	100	/* do not log more */
100 
101 #define NUMTYPES 17
102 #define NUMDENS  (NUMTYPES - 7)
103 
104 #define NO_TYPE		0	/* must match NO_TYPE in ft.c */
105 #define FD_1720         1
106 #define FD_1480         2
107 #define FD_1440         3
108 #define FD_1200         4
109 #define FD_820          5
110 #define FD_800          6
111 #define FD_720          7
112 #define FD_360          8
113 #define FD_640          9
114 #define FD_1232         10
115 
116 #define FD_1480in5_25   11
117 #define FD_1440in5_25   12
118 #define FD_820in5_25    13
119 #define FD_800in5_25    14
120 #define FD_720in5_25    15
121 #define FD_360in5_25    16
122 #define FD_640in5_25    17
123 
124 #define BIO_RDSECTID	BIO_CMD1
125 
126 static struct fd_type fd_types[NUMTYPES] =
127 {
128 { 21,2,0xFF,0x04,82,3444,1,FDC_500KBPS,2,0x0C,2 }, /* 1.72M in HD 3.5in */
129 { 18,2,0xFF,0x1B,82,2952,1,FDC_500KBPS,2,0x6C,1 }, /* 1.48M in HD 3.5in */
130 { 18,2,0xFF,0x1B,80,2880,1,FDC_500KBPS,2,0x6C,1 }, /* 1.44M in HD 3.5in */
131 { 15,2,0xFF,0x1B,80,2400,1,FDC_500KBPS,2,0x54,1 }, /*  1.2M in HD 5.25/3.5 */
132 { 10,2,0xFF,0x10,82,1640,1,FDC_250KBPS,2,0x2E,1 }, /*  820K in HD 3.5in */
133 { 10,2,0xFF,0x10,80,1600,1,FDC_250KBPS,2,0x2E,1 }, /*  800K in HD 3.5in */
134 {  9,2,0xFF,0x20,80,1440,1,FDC_250KBPS,2,0x50,1 }, /*  720K in HD 3.5in */
135 {  9,2,0xFF,0x2A,40, 720,1,FDC_250KBPS,2,0x50,1 }, /*  360K in DD 5.25in */
136 {  8,2,0xFF,0x2A,80,1280,1,FDC_250KBPS,2,0x50,1 }, /*  640K in DD 5.25in */
137 {  8,3,0xFF,0x35,77,1232,1,FDC_500KBPS,2,0x74,1 }, /* 1.23M in HD 5.25in */
138 
139 { 18,2,0xFF,0x02,82,2952,1,FDC_500KBPS,2,0x02,2 }, /* 1.48M in HD 5.25in */
140 { 18,2,0xFF,0x02,80,2880,1,FDC_500KBPS,2,0x02,2 }, /* 1.44M in HD 5.25in */
141 { 10,2,0xFF,0x10,82,1640,1,FDC_300KBPS,2,0x2E,1 }, /*  820K in HD 5.25in */
142 { 10,2,0xFF,0x10,80,1600,1,FDC_300KBPS,2,0x2E,1 }, /*  800K in HD 5.25in */
143 {  9,2,0xFF,0x20,80,1440,1,FDC_300KBPS,2,0x50,1 }, /*  720K in HD 5.25in */
144 {  9,2,0xFF,0x23,40, 720,2,FDC_300KBPS,2,0x50,1 }, /*  360K in HD 5.25in */
145 {  8,2,0xFF,0x2A,80,1280,1,FDC_300KBPS,2,0x50,1 }, /*  640K in HD 5.25in */
146 };
147 
148 #define DRVS_PER_CTLR 2		/* 2 floppies */
149 
150 #define MAX_SEC_SIZE	(128 << 3)
151 #define MAX_CYLINDER	85	/* some people really stress their drives
152 				 * up to cyl 82 */
153 #define MAX_HEAD	1
154 
155 /***********************************************************************\
156 * Per controller structure.						*
157 \***********************************************************************/
158 static devclass_t fdc_devclass;
159 
160 /***********************************************************************\
161 * Per drive structure.							*
162 * N per controller  (DRVS_PER_CTLR)					*
163 \***********************************************************************/
164 struct fd_data {
165 	struct	fdc_data *fdc;	/* pointer to controller structure */
166 	int	fdsu;		/* this units number on this controller */
167 	int	type;		/* Drive type (FD_1440...) */
168 	struct	fd_type *ft;	/* pointer to the type descriptor */
169 	int	flags;
170 #define	FD_OPEN		0x01	/* it's open		*/
171 #define	FD_ACTIVE	0x02	/* it's active		*/
172 #define	FD_MOTOR	0x04	/* motor should be on	*/
173 #define	FD_MOTOR_WAIT	0x08	/* motor coming up	*/
174 	int	skip;
175 	int	hddrv;
176 #define FD_NO_TRACK -2
177 	int	track;		/* where we think the head is */
178 	int	options;	/* user configurable options, see ioctl_fd.h */
179 	struct	callout_handle toffhandle;
180 	struct	callout_handle tohandle;
181 	struct	devstat device_stats;
182 	eventhandler_tag clonetag;
183 	dev_t	masterdev;
184 	device_t dev;
185 	fdu_t	fdu;
186 };
187 
188 struct fdc_ivars {
189 	int	fdunit;
190 };
191 static devclass_t fd_devclass;
192 
193 /***********************************************************************\
194 * Throughout this file the following conventions will be used:		*
195 * fd is a pointer to the fd_data struct for the drive in question	*
196 * fdc is a pointer to the fdc_data struct for the controller		*
197 * fdu is the floppy drive unit number					*
198 * fdcu is the floppy controller unit number				*
199 * fdsu is the floppy drive unit number on that controller. (sub-unit)	*
200 \***********************************************************************/
201 
202 /* internal functions */
203 static driver_intr_t fdc_intr;
204 static void set_motor(struct fdc_data *, int, int);
205 #  define TURNON 1
206 #  define TURNOFF 0
207 static timeout_t fd_turnoff;
208 static timeout_t fd_motor_on;
209 static void fd_turnon(struct fd_data *);
210 static void fdc_reset(fdc_p);
211 static int fd_in(struct fdc_data *, int *);
212 static int out_fdc(struct fdc_data *, int);
213 static void fdstart(struct fdc_data *);
214 static timeout_t fd_iotimeout;
215 static timeout_t fd_pseudointr;
216 static int fdstate(struct fdc_data *);
217 static int retrier(struct fdc_data *);
218 static int fdmisccmd(dev_t, u_int, void *);
219 
220 static int enable_fifo(fdc_p fdc);
221 static void fd_clone (void *arg, char *name, int namelen, dev_t *dev);
222 
223 static int fifo_threshold = 8;	/* XXX: should be accessible via sysctl */
224 
225 #ifdef	FDC_DEBUG
226 static char const * const fdstates[] =
227 {
228 "DEVIDLE",
229 "FINDWORK",
230 "DOSEEK",
231 "SEEKCOMPLETE",
232 "IOCOMPLETE",
233 "RECALCOMPLETE",
234 "STARTRECAL",
235 "RESETCTLR",
236 "SEEKWAIT",
237 "RECALWAIT",
238 "MOTORWAIT",
239 "IOTIMEDOUT",
240 "RESETCOMPLETE",
241 "PIOREAD",
242 };
243 
244 /* CAUTION: fd_debug causes huge amounts of logging output */
245 static int volatile fd_debug = 0;
246 #define TRACE0(arg) if(fd_debug) printf(arg)
247 #define TRACE1(arg1, arg2) if(fd_debug) printf(arg1, arg2)
248 #else /* FDC_DEBUG */
249 #define TRACE0(arg)
250 #define TRACE1(arg1, arg2)
251 #endif /* FDC_DEBUG */
252 
253 static void
254 fdout_wr(fdc_p fdc, u_int8_t v)
255 {
256 	bus_space_write_1(fdc->portt, fdc->porth, FDOUT+fdc->port_off, v);
257 }
258 
259 static u_int8_t
260 fdsts_rd(fdc_p fdc)
261 {
262 	return bus_space_read_1(fdc->portt, fdc->porth, FDSTS+fdc->port_off);
263 }
264 
265 static void
266 fddata_wr(fdc_p fdc, u_int8_t v)
267 {
268 	bus_space_write_1(fdc->portt, fdc->porth, FDDATA+fdc->port_off, v);
269 }
270 
271 static u_int8_t
272 fddata_rd(fdc_p fdc)
273 {
274 	return bus_space_read_1(fdc->portt, fdc->porth, FDDATA+fdc->port_off);
275 }
276 
277 static void
278 fdctl_wr_isa(fdc_p fdc, u_int8_t v)
279 {
280 	bus_space_write_1(fdc->ctlt, fdc->ctlh, 0, v);
281 }
282 
283 #if NCARD > 0
284 static void
285 fdctl_wr_pcmcia(fdc_p fdc, u_int8_t v)
286 {
287 	bus_space_write_1(fdc->portt, fdc->porth, FDCTL+fdc->port_off, v);
288 }
289 #endif
290 
291 #if 0
292 
293 static u_int8_t
294 fdin_rd(fdc_p fdc)
295 {
296 	return bus_space_read_1(fdc->portt, fdc->porth, FDIN);
297 }
298 
299 #endif
300 
301 /*
302  * The open function is named Fdopen() to avoid confusion with fdopen()
303  * in fd(4).  The difference is now only meaningful for debuggers.
304  */
305 static	d_open_t	Fdopen;
306 static	d_close_t	fdclose;
307 static	d_ioctl_t	fdioctl;
308 static	d_strategy_t	fdstrategy;
309 
310 #define CDEV_MAJOR 9
311 static struct cdevsw fd_cdevsw = {
312 	/* open */	Fdopen,
313 	/* close */	fdclose,
314 	/* read */	physread,
315 	/* write */	physwrite,
316 	/* ioctl */	fdioctl,
317 	/* poll */	nopoll,
318 	/* mmap */	nommap,
319 	/* strategy */	fdstrategy,
320 	/* name */	"fd",
321 	/* maj */	CDEV_MAJOR,
322 	/* dump */	nodump,
323 	/* psize */	nopsize,
324 	/* flags */	D_DISK,
325 };
326 
327 static int
328 fdc_err(struct fdc_data *fdc, const char *s)
329 {
330 	fdc->fdc_errs++;
331 	if (s) {
332 		if (fdc->fdc_errs < FDC_ERRMAX)
333 			device_printf(fdc->fdc_dev, "%s", s);
334 		else if (fdc->fdc_errs == FDC_ERRMAX)
335 			device_printf(fdc->fdc_dev, "too many errors, not "
336 						    "logging any more\n");
337 	}
338 
339 	return FD_FAILED;
340 }
341 
342 /*
343  * fd_cmd: Send a command to the chip.  Takes a varargs with this structure:
344  * Unit number,
345  * # of output bytes, output bytes as ints ...,
346  * # of input bytes, input bytes as ints ...
347  */
348 static int
349 fd_cmd(struct fdc_data *fdc, int n_out, ...)
350 {
351 	u_char cmd;
352 	int n_in;
353 	int n;
354 	va_list ap;
355 
356 	va_start(ap, n_out);
357 	cmd = (u_char)(va_arg(ap, int));
358 	va_end(ap);
359 	va_start(ap, n_out);
360 	for (n = 0; n < n_out; n++)
361 	{
362 		if (out_fdc(fdc, va_arg(ap, int)) < 0)
363 		{
364 			char msg[50];
365 			snprintf(msg, sizeof(msg),
366 				"cmd %x failed at out byte %d of %d\n",
367 				cmd, n + 1, n_out);
368 			return fdc_err(fdc, msg);
369 		}
370 	}
371 	n_in = va_arg(ap, int);
372 	for (n = 0; n < n_in; n++)
373 	{
374 		int *ptr = va_arg(ap, int *);
375 		if (fd_in(fdc, ptr) < 0)
376 		{
377 			char msg[50];
378 			snprintf(msg, sizeof(msg),
379 				"cmd %02x failed at in byte %d of %d\n",
380 				cmd, n + 1, n_in);
381 			return fdc_err(fdc, msg);
382 		}
383 	}
384 
385 	return 0;
386 }
387 
388 static int
389 enable_fifo(fdc_p fdc)
390 {
391 	int i, j;
392 
393 	if ((fdc->flags & FDC_HAS_FIFO) == 0) {
394 
395 		/*
396 		 * Cannot use fd_cmd the normal way here, since
397 		 * this might be an invalid command. Thus we send the
398 		 * first byte, and check for an early turn of data directon.
399 		 */
400 
401 		if (out_fdc(fdc, I8207X_CONFIGURE) < 0)
402 			return fdc_err(fdc, "Enable FIFO failed\n");
403 
404 		/* If command is invalid, return */
405 		j = 100000;
406 		while ((i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM))
407 		       != NE7_RQM && j-- > 0)
408 			if (i == (NE7_DIO | NE7_RQM)) {
409 				fdc_reset(fdc);
410 				return FD_FAILED;
411 			}
412 		if (j<0 ||
413 		    fd_cmd(fdc, 3,
414 			   0, (fifo_threshold - 1) & 0xf, 0, 0) < 0) {
415 			fdc_reset(fdc);
416 			return fdc_err(fdc, "Enable FIFO failed\n");
417 		}
418 		fdc->flags |= FDC_HAS_FIFO;
419 		return 0;
420 	}
421 	if (fd_cmd(fdc, 4,
422 		   I8207X_CONFIGURE, 0, (fifo_threshold - 1) & 0xf, 0, 0) < 0)
423 		return fdc_err(fdc, "Re-enable FIFO failed\n");
424 	return 0;
425 }
426 
427 static int
428 fd_sense_drive_status(fdc_p fdc, int *st3p)
429 {
430 	int st3;
431 
432 	if (fd_cmd(fdc, 2, NE7CMD_SENSED, fdc->fdu, 1, &st3))
433 	{
434 		return fdc_err(fdc, "Sense Drive Status failed\n");
435 	}
436 	if (st3p)
437 		*st3p = st3;
438 
439 	return 0;
440 }
441 
442 static int
443 fd_sense_int(fdc_p fdc, int *st0p, int *cylp)
444 {
445 	int cyl, st0, ret;
446 
447 	ret = fd_cmd(fdc, 1, NE7CMD_SENSEI, 1, &st0);
448 	if (ret) {
449 		(void)fdc_err(fdc,
450 			      "sense intr err reading stat reg 0\n");
451 		return ret;
452 	}
453 
454 	if (st0p)
455 		*st0p = st0;
456 
457 	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV) {
458 		/*
459 		 * There doesn't seem to have been an interrupt.
460 		 */
461 		return FD_NOT_VALID;
462 	}
463 
464 	if (fd_in(fdc, &cyl) < 0) {
465 		return fdc_err(fdc, "can't get cyl num\n");
466 	}
467 
468 	if (cylp)
469 		*cylp = cyl;
470 
471 	return 0;
472 }
473 
474 
475 static int
476 fd_read_status(fdc_p fdc)
477 {
478 	int i, ret;
479 
480 	for (i = 0; i < 7; i++) {
481 		/*
482 		 * XXX types are poorly chosen.  Only bytes can be read
483 		 * from the hardware, but fdc->status[] wants u_ints and
484 		 * fd_in() gives ints.
485 		 */
486 		int status;
487 
488 		ret = fd_in(fdc, &status);
489 		fdc->status[i] = status;
490 		if (ret != 0)
491 			break;
492 	}
493 
494 	if (ret == 0)
495 		fdc->flags |= FDC_STAT_VALID;
496 	else
497 		fdc->flags &= ~FDC_STAT_VALID;
498 
499 	return ret;
500 }
501 
502 /****************************************************************************/
503 /*                      autoconfiguration stuff                             */
504 /****************************************************************************/
505 
506 static int
507 fdc_alloc_resources(struct fdc_data *fdc)
508 {
509 	device_t dev;
510 	int ispnp, ispcmcia, nports;
511 
512 	dev = fdc->fdc_dev;
513 	ispnp = (fdc->flags & FDC_ISPNP) != 0;
514 	ispcmcia = (fdc->flags & FDC_ISPCMCIA) != 0;
515 	fdc->rid_ioport = fdc->rid_irq = fdc->rid_drq = 0;
516 	fdc->res_ioport = fdc->res_irq = fdc->res_drq = 0;
517 
518 	/*
519 	 * On standard ISA, we don't just use an 8 port range
520 	 * (e.g. 0x3f0-0x3f7) since that covers an IDE control
521 	 * register at 0x3f6.
522 	 *
523 	 * Isn't PC hardware wonderful.
524 	 *
525 	 * The Y-E Data PCMCIA FDC doesn't have this problem, it
526 	 * uses the register with offset 6 for pseudo-DMA, and the
527 	 * one with offset 7 as control register.
528 	 */
529 	nports = ispcmcia ? 8 : (ispnp ? 1 : 6);
530 	fdc->res_ioport = bus_alloc_resource(dev, SYS_RES_IOPORT,
531 					     &fdc->rid_ioport, 0ul, ~0ul,
532 					     nports, RF_ACTIVE);
533 	if (fdc->res_ioport == 0) {
534 		device_printf(dev, "cannot reserve I/O port range (%d ports)\n",
535 			      nports);
536 		return ENXIO;
537 	}
538 	fdc->portt = rman_get_bustag(fdc->res_ioport);
539 	fdc->porth = rman_get_bushandle(fdc->res_ioport);
540 
541 	if (!ispcmcia) {
542 		/*
543 		 * Some BIOSen report the device at 0x3f2-0x3f5,0x3f7
544 		 * and some at 0x3f0-0x3f5,0x3f7. We detect the former
545 		 * by checking the size and adjust the port address
546 		 * accordingly.
547 		 */
548 		if (bus_get_resource_count(dev, SYS_RES_IOPORT, 0) == 4)
549 			fdc->port_off = -2;
550 
551 		/*
552 		 * Register the control port range as rid 1 if it
553 		 * isn't there already. Most PnP BIOSen will have
554 		 * already done this but non-PnP configurations don't.
555 		 *
556 		 * And some (!!) report 0x3f2-0x3f5 and completely
557 		 * leave out the control register!  It seems that some
558 		 * non-antique controller chips have a different
559 		 * method of programming the transfer speed which
560 		 * doesn't require the control register, but it's
561 		 * mighty bogus as the chip still responds to the
562 		 * address for the control register.
563 		 */
564 		if (bus_get_resource_count(dev, SYS_RES_IOPORT, 1) == 0) {
565 			u_long ctlstart;
566 
567 			/* Find the control port, usually 0x3f7 */
568 			ctlstart = rman_get_start(fdc->res_ioport) +
569 				fdc->port_off + 7;
570 
571 			bus_set_resource(dev, SYS_RES_IOPORT, 1, ctlstart, 1);
572 		}
573 
574 		/*
575 		 * Now (finally!) allocate the control port.
576 		 */
577 		fdc->rid_ctl = 1;
578 		fdc->res_ctl = bus_alloc_resource(dev, SYS_RES_IOPORT,
579 						  &fdc->rid_ctl,
580 						  0ul, ~0ul, 1, RF_ACTIVE);
581 		if (fdc->res_ctl == 0) {
582 			device_printf(dev,
583 		"cannot reserve control I/O port range (control port)\n");
584 			return ENXIO;
585 		}
586 		fdc->ctlt = rman_get_bustag(fdc->res_ctl);
587 		fdc->ctlh = rman_get_bushandle(fdc->res_ctl);
588 	}
589 
590 	fdc->res_irq = bus_alloc_resource(dev, SYS_RES_IRQ,
591 					  &fdc->rid_irq, 0ul, ~0ul, 1,
592 					  RF_ACTIVE);
593 	if (fdc->res_irq == 0) {
594 		device_printf(dev, "cannot reserve interrupt line\n");
595 		return ENXIO;
596 	}
597 
598 	if ((fdc->flags & FDC_NODMA) == 0) {
599 		fdc->res_drq = bus_alloc_resource(dev, SYS_RES_DRQ,
600 						  &fdc->rid_drq, 0ul, ~0ul, 1,
601 						  RF_ACTIVE);
602 		if (fdc->res_drq == 0) {
603 			device_printf(dev, "cannot reserve DMA request line\n");
604 			return ENXIO;
605 		}
606 		fdc->dmachan = fdc->res_drq->r_start;
607 	}
608 
609 	return 0;
610 }
611 
612 static void
613 fdc_release_resources(struct fdc_data *fdc)
614 {
615 	device_t dev;
616 
617 	dev = fdc->fdc_dev;
618 	if (fdc->res_irq != 0) {
619 		bus_deactivate_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
620 					fdc->res_irq);
621 		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
622 				     fdc->res_irq);
623 	}
624 	if (fdc->res_ctl != 0) {
625 		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ctl,
626 					fdc->res_ctl);
627 		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ctl,
628 				     fdc->res_ctl);
629 	}
630 	if (fdc->res_ioport != 0) {
631 		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
632 					fdc->res_ioport);
633 		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
634 				     fdc->res_ioport);
635 	}
636 	if (fdc->res_drq != 0) {
637 		bus_deactivate_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
638 					fdc->res_drq);
639 		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
640 				     fdc->res_drq);
641 	}
642 }
643 
644 /****************************************************************************/
645 /*                      autoconfiguration stuff                             */
646 /****************************************************************************/
647 
648 static struct isa_pnp_id fdc_ids[] = {
649 	{0x0007d041, "PC standard floppy disk controller"}, /* PNP0700 */
650 	{0x0107d041, "Standard floppy controller supporting MS Device Bay Spec"}, /* PNP0701 */
651 	{0}
652 };
653 
654 static int
655 fdc_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
656 {
657 	struct fdc_ivars *ivars = device_get_ivars(child);
658 
659 	switch (which) {
660 	case FDC_IVAR_FDUNIT:
661 		*result = ivars->fdunit;
662 		break;
663 	default:
664 		return ENOENT;
665 	}
666 	return 0;
667 }
668 
669 /*
670  * fdc controller section.
671  */
672 static int
673 fdc_probe(device_t dev)
674 {
675 	int	error, ic_type;
676 	struct	fdc_data *fdc;
677 
678 	fdc = device_get_softc(dev);
679 	bzero(fdc, sizeof *fdc);
680 	fdc->fdc_dev = dev;
681 	fdc->fdctl_wr = fdctl_wr_isa;
682 
683 	/* Check pnp ids */
684 	error = ISA_PNP_PROBE(device_get_parent(dev), dev, fdc_ids);
685 	if (error == ENXIO)
686 		return ENXIO;
687 	if (error == 0)
688 		fdc->flags |= FDC_ISPNP;
689 
690 	/* Attempt to allocate our resources for the duration of the probe */
691 	error = fdc_alloc_resources(fdc);
692 	if (error)
693 		goto out;
694 
695 	/* First - lets reset the floppy controller */
696 	fdout_wr(fdc, 0);
697 	DELAY(100);
698 	fdout_wr(fdc, FDO_FRST);
699 
700 	/* see if it can handle a command */
701 	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
702 		   NE7_SPEC_2(2, 0), 0)) {
703 		error = ENXIO;
704 		goto out;
705 	}
706 
707 	if (fd_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type) == 0) {
708 		ic_type = (u_char)ic_type;
709 		switch (ic_type) {
710 		case 0x80:
711 			device_set_desc(dev, "NEC 765 or clone");
712 			fdc->fdct = FDC_NE765;
713 			break;
714 		case 0x81:
715 			device_set_desc(dev, "Intel 82077 or clone");
716 			fdc->fdct = FDC_I82077;
717 			break;
718 		case 0x90:
719 			device_set_desc(dev, "NEC 72065B or clone");
720 			fdc->fdct = FDC_NE72065;
721 			break;
722 		default:
723 			device_set_desc(dev, "generic floppy controller");
724 			fdc->fdct = FDC_UNKNOWN;
725 			break;
726 		}
727 	}
728 
729 out:
730 	fdc_release_resources(fdc);
731 	return (error);
732 }
733 
734 #if NCARD > 0
735 
736 static int
737 fdc_pccard_probe(device_t dev)
738 {
739 	int	error;
740 	struct	fdc_data *fdc;
741 
742 	fdc = device_get_softc(dev);
743 	bzero(fdc, sizeof *fdc);
744 	fdc->fdc_dev = dev;
745 	fdc->fdctl_wr = fdctl_wr_pcmcia;
746 
747 	fdc->flags |= FDC_ISPCMCIA | FDC_NODMA;
748 
749 	/* Attempt to allocate our resources for the duration of the probe */
750 	error = fdc_alloc_resources(fdc);
751 	if (error)
752 		goto out;
753 
754 	/* First - lets reset the floppy controller */
755 	fdout_wr(fdc, 0);
756 	DELAY(100);
757 	fdout_wr(fdc, FDO_FRST);
758 
759 	/* see if it can handle a command */
760 	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
761 		   NE7_SPEC_2(2, 0), 0)) {
762 		error = ENXIO;
763 		goto out;
764 	}
765 
766 	device_set_desc(dev, "Y-E Data PCMCIA floppy");
767 	fdc->fdct = FDC_NE765;
768 
769 out:
770 	fdc_release_resources(fdc);
771 	return (error);
772 }
773 
774 #endif /* NCARD > 0 */
775 
776 static int
777 fdc_detach(device_t dev)
778 {
779 	struct	fdc_data *fdc;
780 	int	error;
781 
782 	fdc = device_get_softc(dev);
783 
784 	/* have our children detached first */
785 	if ((error = bus_generic_detach(dev)))
786 		return (error);
787 
788 	/* reset controller, turn motor off */
789 	fdout_wr(fdc, 0);
790 
791 	if ((fdc->flags & FDC_NODMA) == 0)
792 		isa_dma_release(fdc->dmachan);
793 
794 	if ((fdc->flags & FDC_ATTACHED) == 0) {
795 		device_printf(dev, "already unloaded\n");
796 		return (0);
797 	}
798 	fdc->flags &= ~FDC_ATTACHED;
799 
800 	BUS_TEARDOWN_INTR(device_get_parent(dev), dev, fdc->res_irq,
801 			  fdc->fdc_intr);
802 	fdc_release_resources(fdc);
803 	device_printf(dev, "unload\n");
804 	return (0);
805 }
806 
807 /*
808  * Add a child device to the fdc controller.  It will then be probed etc.
809  */
810 static void
811 fdc_add_child(device_t dev, const char *name, int unit)
812 {
813 	int	disabled;
814 	struct fdc_ivars *ivar;
815 	device_t child;
816 
817 	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT | M_ZERO);
818 	if (ivar == NULL)
819 		return;
820 	if (resource_int_value(name, unit, "drive", &ivar->fdunit) != 0)
821 		ivar->fdunit = 0;
822 	child = device_add_child(dev, name, unit);
823 	if (child == NULL)
824 		return;
825 	device_set_ivars(child, ivar);
826 	if (resource_int_value(name, unit, "disabled", &disabled) == 0
827 	    && disabled != 0)
828 		device_disable(child);
829 }
830 
831 static int
832 fdc_attach(device_t dev)
833 {
834 	struct	fdc_data *fdc;
835 	int	i, error, dunit;
836 	const char *name, *dname;
837 
838 	fdc = device_get_softc(dev);
839 	error = fdc_alloc_resources(fdc);
840 	if (error) {
841 		device_printf(dev, "cannot re-acquire resources\n");
842 		return error;
843 	}
844 	error = BUS_SETUP_INTR(device_get_parent(dev), dev, fdc->res_irq,
845 			       INTR_TYPE_BIO | INTR_ENTROPY, fdc_intr, fdc,
846 			       &fdc->fdc_intr);
847 	if (error) {
848 		device_printf(dev, "cannot setup interrupt\n");
849 		return error;
850 	}
851 	fdc->fdcu = device_get_unit(dev);
852 	fdc->flags |= FDC_ATTACHED;
853 
854 	if ((fdc->flags & FDC_NODMA) == 0) {
855 		/*
856 		 * Acquire the DMA channel forever, the driver will do
857 		 * the rest
858 		 * XXX should integrate with rman
859 		 */
860 		isa_dma_acquire(fdc->dmachan);
861 		isa_dmainit(fdc->dmachan, MAX_SEC_SIZE);
862 	}
863 	fdc->state = DEVIDLE;
864 
865 	/* reset controller, turn motor off, clear fdout mirror reg */
866 	fdout_wr(fdc, fdc->fdout = 0);
867 	bioq_init(&fdc->head);
868 
869 	/*
870 	 * Probe and attach any children.  We should probably detect
871 	 * devices from the BIOS unless overridden.
872 	 */
873 	name = device_get_nameunit(dev);
874 	i = 0;
875 	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0)
876 		fdc_add_child(dev, dname, dunit);
877 
878 	return (bus_generic_attach(dev));
879 }
880 
881 static int
882 fdc_print_child(device_t me, device_t child)
883 {
884 	int retval = 0;
885 
886 	retval += bus_print_child_header(me, child);
887 	retval += printf(" on %s drive %d\n", device_get_nameunit(me),
888 	       fdc_get_fdunit(child));
889 
890 	return (retval);
891 }
892 
893 static device_method_t fdc_methods[] = {
894 	/* Device interface */
895 	DEVMETHOD(device_probe,		fdc_probe),
896 	DEVMETHOD(device_attach,	fdc_attach),
897 	DEVMETHOD(device_detach,	fdc_detach),
898 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
899 	DEVMETHOD(device_suspend,	bus_generic_suspend),
900 	DEVMETHOD(device_resume,	bus_generic_resume),
901 
902 	/* Bus interface */
903 	DEVMETHOD(bus_print_child,	fdc_print_child),
904 	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
905 	/* Our children never use any other bus interface methods. */
906 
907 	{ 0, 0 }
908 };
909 
910 static driver_t fdc_driver = {
911 	"fdc",
912 	fdc_methods,
913 	sizeof(struct fdc_data)
914 };
915 
916 DRIVER_MODULE(fdc, isa, fdc_driver, fdc_devclass, 0, 0);
917 
918 #if NCARD > 0
919 
920 static device_method_t fdc_pccard_methods[] = {
921 	/* Device interface */
922 	DEVMETHOD(device_probe,		fdc_pccard_probe),
923 	DEVMETHOD(device_attach,	fdc_attach),
924 	DEVMETHOD(device_detach,	fdc_detach),
925 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
926 	DEVMETHOD(device_suspend,	bus_generic_suspend),
927 	DEVMETHOD(device_resume,	bus_generic_resume),
928 
929 	/* Bus interface */
930 	DEVMETHOD(bus_print_child,	fdc_print_child),
931 	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
932 	/* Our children never use any other bus interface methods. */
933 
934 	{ 0, 0 }
935 };
936 
937 static driver_t fdc_pccard_driver = {
938 	"fdc",
939 	fdc_pccard_methods,
940 	sizeof(struct fdc_data)
941 };
942 
943 DRIVER_MODULE(fdc, pccard, fdc_pccard_driver, fdc_devclass, 0, 0);
944 
945 #endif /* NCARD > 0 */
946 
947 static struct {
948 	char *match;
949 	int minor;
950 	int link;
951 } fd_suffix[] = {
952 	{ "a",		0,	1 },
953 	{ "b",		0,	1 },
954 	{ "c",		0,	1 },
955 	{ "d",		0,	1 },
956 	{ "e",		0,	1 },
957 	{ "f",		0,	1 },
958 	{ "g",		0,	1 },
959 	{ "h",		0,	1 },
960 	{ ".1720",	1,	0 },
961 	{ ".1480",	2,	0 },
962 	{ ".1440",	3,	0 },
963 	{ ".1200",	4,	0 },
964 	{ ".820",	5,	0 },
965 	{ ".800",	6,	0 },
966 	{ ".720",	7,	0 },
967 	{ ".360",	8,	0 },
968 	{ ".640",	9,	0 },
969 	{ ".1232",	10,	0 },
970 	{ 0, 0 }
971 };
972 static void
973 fd_clone (void *arg, char *name, int namelen, dev_t *dev)
974 {
975 	int u, d, i;
976 	char *n;
977 	dev_t pdev;
978 
979 	if (*dev != NODEV)
980 		return;
981 	if (dev_stdclone(name, &n, "fd", &u) != 2)
982 		return;
983 	for (i = 0; ; i++) {
984 		if (fd_suffix[i].match == NULL)
985 			return;
986 		if (strcmp(n, fd_suffix[i].match))
987 			continue;
988 		d = fd_suffix[i].minor;
989 		break;
990 	}
991 	if (fd_suffix[i].link == 0) {
992 		*dev = make_dev(&fd_cdevsw, (u << 6) + d,
993 			UID_ROOT, GID_OPERATOR, 0640, name);
994 	} else {
995 		pdev = makedev(fd_cdevsw.d_maj, (u << 6) + d);
996 		*dev = make_dev_alias(pdev, name);
997 	}
998 }
999 
1000 /******************************************************************/
1001 /*
1002  * devices attached to the controller section.
1003  */
1004 static int
1005 fd_probe(device_t dev)
1006 {
1007 	int	i;
1008 	u_int	fdt, st0, st3;
1009 	struct	fd_data *fd;
1010 	struct	fdc_data *fdc;
1011 	fdsu_t	fdsu;
1012 	static int fd_fifo = 0;
1013 
1014 	fdsu = *(int *)device_get_ivars(dev); /* xxx cheat a bit... */
1015 	fd = device_get_softc(dev);
1016 	fdc = device_get_softc(device_get_parent(dev));
1017 
1018 	bzero(fd, sizeof *fd);
1019 	fd->dev = dev;
1020 	fd->fdc = fdc;
1021 	fd->fdsu = fdsu;
1022 	fd->fdu = device_get_unit(dev);
1023 
1024 #ifdef __i386__
1025 	/* look up what bios thinks we have */
1026 	switch (fd->fdu) {
1027 	case 0:
1028 		if ((fdc->flags & FDC_ISPCMCIA))
1029 			fdt = RTCFDT_144M;
1030 		else if (device_get_flags(fdc->fdc_dev) & FDC_PRETEND_D0)
1031 			fdt = RTCFDT_144M | RTCFDT_144M_PRETENDED;
1032 		else
1033 			fdt = (rtcin(RTC_FDISKETTE) & 0xf0);
1034 		break;
1035 	case 1:
1036 		fdt = ((rtcin(RTC_FDISKETTE) << 4) & 0xf0);
1037 		break;
1038 	default:
1039 		fdt = RTCFDT_NONE;
1040 		break;
1041 	}
1042 #else
1043 	fdt = RTCFDT_144M;	/* XXX probably */
1044 #endif
1045 
1046 	/* is there a unit? */
1047 	if (fdt == RTCFDT_NONE)
1048 		return (ENXIO);
1049 
1050 	/* select it */
1051 	set_motor(fdc, fdsu, TURNON);
1052 	DELAY(1000000);	/* 1 sec */
1053 
1054 	/* XXX This doesn't work before the first set_motor() */
1055 	if (fd_fifo == 0 && fdc->fdct != FDC_NE765 && fdc->fdct != FDC_UNKNOWN
1056 	    && (device_get_flags(fdc->fdc_dev) & FDC_NO_FIFO) == 0
1057 	    && enable_fifo(fdc) == 0) {
1058 		device_printf(device_get_parent(dev),
1059 		    "FIFO enabled, %d bytes threshold\n", fifo_threshold);
1060 	}
1061 	fd_fifo = 1;
1062 
1063 	if ((fd_cmd(fdc, 2, NE7CMD_SENSED, fdsu, 1, &st3) == 0)
1064 	    && (st3 & NE7_ST3_T0)) {
1065 		/* if at track 0, first seek inwards */
1066 		/* seek some steps: */
1067 		fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0);
1068 		DELAY(300000); /* ...wait a moment... */
1069 		fd_sense_int(fdc, 0, 0); /* make ctrlr happy */
1070 	}
1071 
1072 	/* If we're at track 0 first seek inwards. */
1073 	if ((fd_sense_drive_status(fdc, &st3) == 0) && (st3 & NE7_ST3_T0)) {
1074 		/* Seek some steps... */
1075 		if (fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1076 			/* ...wait a moment... */
1077 			DELAY(300000);
1078 			/* make ctrlr happy: */
1079 			fd_sense_int(fdc, 0, 0);
1080 		}
1081 	}
1082 
1083 	for (i = 0; i < 2; i++) {
1084 		/*
1085 		 * we must recalibrate twice, just in case the
1086 		 * heads have been beyond cylinder 76, since most
1087 		 * FDCs still barf when attempting to recalibrate
1088 		 * more than 77 steps
1089 		 */
1090 		/* go back to 0: */
1091 		if (fd_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1092 			/* a second being enough for full stroke seek*/
1093 			DELAY(i == 0 ? 1000000 : 300000);
1094 
1095 			/* anything responding? */
1096 			if (fd_sense_int(fdc, &st0, 0) == 0 &&
1097 			    (st0 & NE7_ST0_EC) == 0)
1098 				break; /* already probed succesfully */
1099 		}
1100 	}
1101 
1102 	set_motor(fdc, fdsu, TURNOFF);
1103 
1104 	if (st0 & NE7_ST0_EC) /* no track 0 -> no drive present */
1105 		return (ENXIO);
1106 
1107 	fd->track = FD_NO_TRACK;
1108 	fd->fdc = fdc;
1109 	fd->fdsu = fdsu;
1110 	fd->options = 0;
1111 	callout_handle_init(&fd->toffhandle);
1112 	callout_handle_init(&fd->tohandle);
1113 
1114 	switch (fdt) {
1115 	case RTCFDT_12M:
1116 		device_set_desc(dev, "1200-KB 5.25\" drive");
1117 		fd->type = FD_1200;
1118 		break;
1119 	case RTCFDT_144M | RTCFDT_144M_PRETENDED:
1120 		device_set_desc(dev, "config-pretended 1440-MB 3.5\" drive");
1121 		fdt = RTCFDT_144M;
1122 		fd->type = FD_1440;
1123 	case RTCFDT_144M:
1124 		device_set_desc(dev, "1440-KB 3.5\" drive");
1125 		fd->type = FD_1440;
1126 		break;
1127 	case RTCFDT_288M:
1128 	case RTCFDT_288M_1:
1129 		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1130 		fd->type = FD_1440;
1131 		break;
1132 	case RTCFDT_360K:
1133 		device_set_desc(dev, "360-KB 5.25\" drive");
1134 		fd->type = FD_360;
1135 		break;
1136 	case RTCFDT_720K:
1137 		printf("720-KB 3.5\" drive");
1138 		fd->type = FD_720;
1139 		break;
1140 	default:
1141 		return (ENXIO);
1142 	}
1143 	return (0);
1144 }
1145 
1146 static int
1147 fd_attach(device_t dev)
1148 {
1149 	struct	fd_data *fd;
1150 	static	int cdevsw_add_done;
1151 
1152 	if (!cdevsw_add_done) {
1153 		cdevsw_add(&fd_cdevsw);	/* XXX */
1154 		cdevsw_add_done = 1;
1155 	}
1156 	fd = device_get_softc(dev);
1157 	fd->clonetag = EVENTHANDLER_REGISTER(dev_clone, fd_clone, 0, 1000);
1158 	fd->masterdev = make_dev(&fd_cdevsw, fd->fdu << 6,
1159 				 UID_ROOT, GID_OPERATOR, 0640, "fd%d", fd->fdu);
1160 	devstat_add_entry(&fd->device_stats, device_get_name(dev),
1161 			  device_get_unit(dev), 0, DEVSTAT_NO_ORDERED_TAGS,
1162 			  DEVSTAT_TYPE_FLOPPY | DEVSTAT_TYPE_IF_OTHER,
1163 			  DEVSTAT_PRIORITY_FD);
1164 	return (0);
1165 }
1166 
1167 static int
1168 fd_detach(device_t dev)
1169 {
1170 	struct	fd_data *fd;
1171 
1172 	fd = device_get_softc(dev);
1173 	devstat_remove_entry(&fd->device_stats);
1174 	destroy_dev(fd->masterdev);
1175 	cdevsw_remove(&fd_cdevsw);
1176 	/* XXX need to destroy cloned devs as well */
1177 	EVENTHANDLER_DEREGISTER(dev_clone, fd->clonetag);
1178 	untimeout(fd_turnoff, fd, fd->toffhandle);
1179 
1180 	return (0);
1181 }
1182 
1183 static device_method_t fd_methods[] = {
1184 	/* Device interface */
1185 	DEVMETHOD(device_probe,		fd_probe),
1186 	DEVMETHOD(device_attach,	fd_attach),
1187 	DEVMETHOD(device_detach,	fd_detach),
1188 	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1189 	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
1190 	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
1191 
1192 	{ 0, 0 }
1193 };
1194 
1195 static driver_t fd_driver = {
1196 	"fd",
1197 	fd_methods,
1198 	sizeof(struct fd_data)
1199 };
1200 
1201 DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, 0, 0);
1202 
1203 /****************************************************************************/
1204 /*                            motor control stuff                           */
1205 /*		remember to not deselect the drive we're working on         */
1206 /****************************************************************************/
1207 static void
1208 set_motor(struct fdc_data *fdc, int fdsu, int turnon)
1209 {
1210 	int fdout = fdc->fdout;
1211 	int needspecify = 0;
1212 
1213 	if(turnon) {
1214 		fdout &= ~FDO_FDSEL;
1215 		fdout |= (FDO_MOEN0 << fdsu) + fdsu;
1216 	} else
1217 		fdout &= ~(FDO_MOEN0 << fdsu);
1218 
1219 	if(!turnon
1220 	   && (fdout & (FDO_MOEN0+FDO_MOEN1+FDO_MOEN2+FDO_MOEN3)) == 0)
1221 		/* gonna turn off the last drive, put FDC to bed */
1222 		fdout &= ~ (FDO_FRST|FDO_FDMAEN);
1223 	else {
1224 		/* make sure controller is selected and specified */
1225 		if((fdout & (FDO_FRST|FDO_FDMAEN)) == 0)
1226 			needspecify = 1;
1227 		fdout |= (FDO_FRST|FDO_FDMAEN);
1228 	}
1229 
1230 	fdout_wr(fdc, fdout);
1231 	fdc->fdout = fdout;
1232 	TRACE1("[0x%x->FDOUT]", fdout);
1233 
1234 	if (needspecify) {
1235 		/*
1236 		 * we silently assume the command will be accepted
1237 		 * after an FDC reset
1238 		 *
1239 		 * Steinbach's Guideline for Systems Programming:
1240 		 * Never test for an error condition you don't know
1241 		 * how to handle.
1242 		 */
1243 		(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1244 			     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1245 			     0);
1246 		if (fdc->flags & FDC_HAS_FIFO)
1247 			(void) enable_fifo(fdc);
1248 	}
1249 }
1250 
1251 static void
1252 fd_turnoff(void *xfd)
1253 {
1254 	int	s;
1255 	fd_p fd = xfd;
1256 
1257 	TRACE1("[fd%d: turnoff]", fd->fdu);
1258 
1259 	s = splbio();
1260 	/*
1261 	 * Don't turn off the motor yet if the drive is active.
1262 	 *
1263 	 * If we got here, this could only mean we missed an interrupt.
1264 	 * This can e. g. happen on the Y-E Date PCMCIA floppy controller
1265 	 * after a controller reset.  Just schedule a pseudo-interrupt
1266 	 * so the state machine gets re-entered.
1267 	 */
1268 	if (fd->fdc->state != DEVIDLE && fd->fdc->fdu == fd->fdu) {
1269 		fdc_intr(fd->fdc);
1270 		splx(s);
1271 		return;
1272 	}
1273 
1274 	fd->flags &= ~FD_MOTOR;
1275 	set_motor(fd->fdc, fd->fdsu, TURNOFF);
1276 	splx(s);
1277 }
1278 
1279 static void
1280 fd_motor_on(void *xfd)
1281 {
1282 	int	s;
1283 	fd_p fd = xfd;
1284 
1285 	s = splbio();
1286 	fd->flags &= ~FD_MOTOR_WAIT;
1287 	if((fd->fdc->fd == fd) && (fd->fdc->state == MOTORWAIT))
1288 	{
1289 		fdc_intr(fd->fdc);
1290 	}
1291 	splx(s);
1292 }
1293 
1294 static void
1295 fd_turnon(fd_p fd)
1296 {
1297 	if(!(fd->flags & FD_MOTOR))
1298 	{
1299 		fd->flags |= (FD_MOTOR + FD_MOTOR_WAIT);
1300 		set_motor(fd->fdc, fd->fdsu, TURNON);
1301 		timeout(fd_motor_on, fd, hz); /* in 1 sec its ok */
1302 	}
1303 }
1304 
1305 static void
1306 fdc_reset(fdc_p fdc)
1307 {
1308 	/* Try a reset, keep motor on */
1309 	fdout_wr(fdc, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1310 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1311 	DELAY(100);
1312 	/* enable FDC, but defer interrupts a moment */
1313 	fdout_wr(fdc, fdc->fdout & ~FDO_FDMAEN);
1314 	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~FDO_FDMAEN);
1315 	DELAY(100);
1316 	fdout_wr(fdc, fdc->fdout);
1317 	TRACE1("[0x%x->FDOUT]", fdc->fdout);
1318 
1319 	/* XXX after a reset, silently believe the FDC will accept commands */
1320 	(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1321 		     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1322 		     0);
1323 	if (fdc->flags & FDC_HAS_FIFO)
1324 		(void) enable_fifo(fdc);
1325 }
1326 
1327 /****************************************************************************/
1328 /*                             fdc in/out                                   */
1329 /****************************************************************************/
1330 static int
1331 fd_in(struct fdc_data *fdc, int *ptr)
1332 {
1333 	int i, j = 100000;
1334 	while ((i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM))
1335 		!= (NE7_DIO|NE7_RQM) && j-- > 0)
1336 		if (i == NE7_RQM)
1337 			return fdc_err(fdc, "ready for output in input\n");
1338 	if (j <= 0)
1339 		return fdc_err(fdc, bootverbose? "input ready timeout\n": 0);
1340 #ifdef	FDC_DEBUG
1341 	i = fddata_rd(fdc);
1342 	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
1343 	*ptr = i;
1344 	return 0;
1345 #else	/* !FDC_DEBUG */
1346 	i = fddata_rd(fdc);
1347 	if (ptr)
1348 		*ptr = i;
1349 	return 0;
1350 #endif	/* FDC_DEBUG */
1351 }
1352 
1353 int
1354 out_fdc(struct fdc_data *fdc, int x)
1355 {
1356 	int i;
1357 
1358 	/* Check that the direction bit is set */
1359 	i = 100000;
1360 	while ((fdsts_rd(fdc) & NE7_DIO) && i-- > 0);
1361 	if (i <= 0) return fdc_err(fdc, "direction bit not set\n");
1362 
1363 	/* Check that the floppy controller is ready for a command */
1364 	i = 100000;
1365 	while ((fdsts_rd(fdc) & NE7_RQM) == 0 && i-- > 0);
1366 	if (i <= 0)
1367 		return fdc_err(fdc, bootverbose? "output ready timeout\n": 0);
1368 
1369 	/* Send the command and return */
1370 	fddata_wr(fdc, x);
1371 	TRACE1("[0x%x->FDDATA]", x);
1372 	return (0);
1373 }
1374 
1375 /****************************************************************************/
1376 /*                           fdopen/fdclose                                 */
1377 /****************************************************************************/
1378 int
1379 Fdopen(dev_t dev, int flags, int mode, struct proc *p)
1380 {
1381  	fdu_t fdu = FDUNIT(minor(dev));
1382 	int type = FDTYPE(minor(dev));
1383 	fd_p	fd;
1384 	fdc_p	fdc;
1385 
1386 	/* check bounds */
1387 	if ((fd = devclass_get_softc(fd_devclass, fdu)) == 0)
1388 		return (ENXIO);
1389 	fdc = fd->fdc;
1390 	if ((fdc == NULL) || (fd->type == NO_TYPE))
1391 		return (ENXIO);
1392 	if (type > NUMDENS)
1393 		return (ENXIO);
1394 	if (type == 0)
1395 		type = fd->type;
1396 	else {
1397 		/*
1398 		 * For each type of basic drive, make sure we are trying
1399 		 * to open a type it can do,
1400 		 */
1401 		if (type != fd->type) {
1402 			switch (fd->type) {
1403 			case FD_360:
1404 				return (ENXIO);
1405 			case FD_720:
1406 				if (   type != FD_820
1407 				    && type != FD_800
1408 				    && type != FD_640
1409 				   )
1410 					return (ENXIO);
1411 				break;
1412 			case FD_1200:
1413 				switch (type) {
1414 				case FD_1480:
1415 					type = FD_1480in5_25;
1416 					break;
1417 				case FD_1440:
1418 					type = FD_1440in5_25;
1419 					break;
1420 				case FD_1232:
1421 					break;
1422 				case FD_820:
1423 					type = FD_820in5_25;
1424 					break;
1425 				case FD_800:
1426 					type = FD_800in5_25;
1427 					break;
1428 				case FD_720:
1429 					type = FD_720in5_25;
1430 					break;
1431 				case FD_640:
1432 					type = FD_640in5_25;
1433 					break;
1434 				case FD_360:
1435 					type = FD_360in5_25;
1436 					break;
1437 				default:
1438 					return(ENXIO);
1439 				}
1440 				break;
1441 			case FD_1440:
1442 				if (   type != FD_1720
1443 				    && type != FD_1480
1444 				    && type != FD_1200
1445 				    && type != FD_820
1446 				    && type != FD_800
1447 				    && type != FD_720
1448 				    && type != FD_640
1449 				    )
1450 					return(ENXIO);
1451 				break;
1452 			}
1453 		}
1454 	}
1455 	fd->ft = fd_types + type - 1;
1456 	fd->flags |= FD_OPEN;
1457 
1458 	return 0;
1459 }
1460 
1461 int
1462 fdclose(dev_t dev, int flags, int mode, struct proc *p)
1463 {
1464  	fdu_t fdu = FDUNIT(minor(dev));
1465 	struct fd_data *fd;
1466 
1467 	fd = devclass_get_softc(fd_devclass, fdu);
1468 	fd->flags &= ~FD_OPEN;
1469 	fd->options &= ~(FDOPT_NORETRY | FDOPT_NOERRLOG | FDOPT_NOERROR);
1470 
1471 	return (0);
1472 }
1473 
1474 /****************************************************************************/
1475 /*                               fdstrategy                                 */
1476 /****************************************************************************/
1477 void
1478 fdstrategy(struct bio *bp)
1479 {
1480 	unsigned nblocks, blknum, cando;
1481  	int	s;
1482  	fdu_t	fdu;
1483  	fdc_p	fdc;
1484  	fd_p	fd;
1485 	size_t	fdblk;
1486 
1487  	fdu = FDUNIT(minor(bp->bio_dev));
1488 	fd = devclass_get_softc(fd_devclass, fdu);
1489 	if (fd == 0)
1490 		panic("fdstrategy: buf for nonexistent device (%#lx, %#lx)",
1491 		      (u_long)major(bp->bio_dev), (u_long)minor(bp->bio_dev));
1492 	fdc = fd->fdc;
1493 	if (fd->type == NO_TYPE) {
1494 		bp->bio_error = ENXIO;
1495 		bp->bio_flags |= BIO_ERROR;
1496 		goto bad;
1497 	}
1498 	fdblk = 128 << (fd->ft->secsize);
1499 	if (bp->bio_cmd != BIO_FORMAT && bp->bio_cmd != BIO_RDSECTID) {
1500 		if (bp->bio_blkno < 0) {
1501 			printf(
1502 		"fd%d: fdstrat: bad request blkno = %lu, bcount = %ld\n",
1503 			       fdu, (u_long)bp->bio_blkno, bp->bio_bcount);
1504 			bp->bio_error = EINVAL;
1505 			bp->bio_flags |= BIO_ERROR;
1506 			goto bad;
1507 		}
1508 		if ((bp->bio_bcount % fdblk) != 0) {
1509 			bp->bio_error = EINVAL;
1510 			bp->bio_flags |= BIO_ERROR;
1511 			goto bad;
1512 		}
1513 	}
1514 
1515 	/*
1516 	 * Set up block calculations.
1517 	 */
1518 	if (bp->bio_blkno > 20000000) {
1519 		/*
1520 		 * Reject unreasonably high block number, prevent the
1521 		 * multiplication below from overflowing.
1522 		 */
1523 		bp->bio_error = EINVAL;
1524 		bp->bio_flags |= BIO_ERROR;
1525 		goto bad;
1526 	}
1527 	blknum = (unsigned) bp->bio_blkno * DEV_BSIZE/fdblk;
1528  	nblocks = fd->ft->size;
1529 	bp->bio_resid = 0;
1530 	if (blknum + (bp->bio_bcount / fdblk) > nblocks) {
1531 		if (blknum <= nblocks) {
1532 			cando = (nblocks - blknum) * fdblk;
1533 			bp->bio_resid = bp->bio_bcount - cando;
1534 			if (cando == 0)
1535 				goto bad;	/* not actually bad but EOF */
1536 		} else {
1537 			bp->bio_error = EINVAL;
1538 			bp->bio_flags |= BIO_ERROR;
1539 			goto bad;
1540 		}
1541 	}
1542  	bp->bio_pblkno = bp->bio_blkno;
1543 	s = splbio();
1544 	bioqdisksort(&fdc->head, bp);
1545 	untimeout(fd_turnoff, fd, fd->toffhandle); /* a good idea */
1546 	devstat_start_transaction(&fd->device_stats);
1547 	device_busy(fd->dev);
1548 	fdstart(fdc);
1549 	splx(s);
1550 	return;
1551 
1552 bad:
1553 	biodone(bp);
1554 }
1555 
1556 /***************************************************************\
1557 *				fdstart				*
1558 * We have just queued something.. if the controller is not busy	*
1559 * then simulate the case where it has just finished a command	*
1560 * So that it (the interrupt routine) looks on the queue for more*
1561 * work to do and picks up what we just added.			*
1562 * If the controller is already busy, we need do nothing, as it	*
1563 * will pick up our work when the present work completes		*
1564 \***************************************************************/
1565 static void
1566 fdstart(struct fdc_data *fdc)
1567 {
1568 	int s;
1569 
1570 	s = splbio();
1571 	if(fdc->state == DEVIDLE)
1572 	{
1573 		fdc_intr(fdc);
1574 	}
1575 	splx(s);
1576 }
1577 
1578 static void
1579 fd_iotimeout(void *xfdc)
1580 {
1581  	fdc_p fdc;
1582 	int s;
1583 
1584 	fdc = xfdc;
1585 	TRACE1("fd%d[fd_iotimeout()]", fdc->fdu);
1586 
1587 	/*
1588 	 * Due to IBM's brain-dead design, the FDC has a faked ready
1589 	 * signal, hardwired to ready == true. Thus, any command
1590 	 * issued if there's no diskette in the drive will _never_
1591 	 * complete, and must be aborted by resetting the FDC.
1592 	 * Many thanks, Big Blue!
1593 	 * The FDC must not be reset directly, since that would
1594 	 * interfere with the state machine.  Instead, pretend that
1595 	 * the command completed but was invalid.  The state machine
1596 	 * will reset the FDC and retry once.
1597 	 */
1598 	s = splbio();
1599 	fdc->status[0] = NE7_ST0_IC_IV;
1600 	fdc->flags &= ~FDC_STAT_VALID;
1601 	fdc->state = IOTIMEDOUT;
1602 	fdc_intr(fdc);
1603 	splx(s);
1604 }
1605 
1606 /* just ensure it has the right spl */
1607 static void
1608 fd_pseudointr(void *xfdc)
1609 {
1610 	int	s;
1611 
1612 	s = splbio();
1613 	fdc_intr(xfdc);
1614 	splx(s);
1615 }
1616 
1617 /***********************************************************************\
1618 *                                 fdc_intr				*
1619 * keep calling the state machine until it returns a 0			*
1620 * ALWAYS called at SPLBIO 						*
1621 \***********************************************************************/
1622 static void
1623 fdc_intr(void *xfdc)
1624 {
1625 	fdc_p fdc = xfdc;
1626 	while(fdstate(fdc))
1627 		;
1628 }
1629 
1630 /*
1631  * magic pseudo-DMA initialization for YE FDC. Sets count and
1632  * direction
1633  */
1634 #define SET_BCDR(fdc,wr,cnt,port) \
1635 	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port,	 \
1636 	    ((cnt)-1) & 0xff);						 \
1637 	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port + 1, \
1638 	    ((wr ? 0x80 : 0) | ((((cnt)-1) >> 8) & 0x7f)));
1639 
1640 /*
1641  * fdcpio(): perform programmed IO read/write for YE PCMCIA floppy
1642  */
1643 static int
1644 fdcpio(fdc_p fdc, long flags, caddr_t addr, u_int count)
1645 {
1646 	u_char *cptr = (u_char *)addr;
1647 
1648 	if (flags == BIO_READ) {
1649 		if (fdc->state != PIOREAD) {
1650 			fdc->state = PIOREAD;
1651 			return(0);
1652 		}
1653 		SET_BCDR(fdc, 0, count, 0);
1654 		bus_space_read_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1655 		    FDC_YE_DATAPORT, cptr, count);
1656 	} else {
1657 		bus_space_write_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1658 		    FDC_YE_DATAPORT, cptr, count);
1659 		SET_BCDR(fdc, 0, count, 0);
1660 	}
1661 	return(1);
1662 }
1663 
1664 /***********************************************************************\
1665 * The controller state machine.						*
1666 * if it returns a non zero value, it should be called again immediatly	*
1667 \***********************************************************************/
1668 static int
1669 fdstate(fdc_p fdc)
1670 {
1671 	int read, format, rdsectid, head, i, sec = 0, sectrac, st0, cyl, st3, idf;
1672 	unsigned blknum = 0, b_cylinder = 0;
1673 	struct fdc_readid *idp;
1674 	fdu_t fdu = fdc->fdu;
1675 	fd_p fd;
1676 	register struct bio *bp;
1677 	struct fd_formb *finfo = NULL;
1678 	size_t fdblk;
1679 
1680 	bp = fdc->bp;
1681 	if (bp == NULL) {
1682 		bp = bioq_first(&fdc->head);
1683 		if (bp != NULL) {
1684 			bioq_remove(&fdc->head, bp);
1685 			fdc->bp = bp;
1686 		}
1687 	}
1688 	if (bp == NULL) {
1689 		/***********************************************\
1690 		* nothing left for this controller to do	*
1691 		* Force into the IDLE state,			*
1692 		\***********************************************/
1693 		fdc->state = DEVIDLE;
1694 		if (fdc->fd) {
1695 			device_printf(fdc->fdc_dev,
1696 			    "unexpected valid fd pointer\n");
1697 			fdc->fd = (fd_p) 0;
1698 			fdc->fdu = -1;
1699 		}
1700 		TRACE1("[fdc%d IDLE]", fdc->fdcu);
1701  		return (0);
1702 	}
1703 	fdu = FDUNIT(minor(bp->bio_dev));
1704 	fd = devclass_get_softc(fd_devclass, fdu);
1705 	fdblk = 128 << fd->ft->secsize;
1706 	if (fdc->fd && (fd != fdc->fd))
1707 		device_printf(fd->dev, "confused fd pointers\n");
1708 	read = bp->bio_cmd == BIO_READ;
1709 	if (read)
1710 		idf = ISADMA_READ;
1711 	else
1712 		idf = ISADMA_WRITE;
1713 	format = bp->bio_cmd == BIO_FORMAT;
1714 	rdsectid = bp->bio_cmd == BIO_RDSECTID;
1715 	if (format) {
1716 		finfo = (struct fd_formb *)bp->bio_data;
1717 		fd->skip = (char *)&(finfo->fd_formb_cylno(0))
1718 			- (char *)finfo;
1719 	}
1720 	if (fdc->state == DOSEEK || fdc->state == SEEKCOMPLETE) {
1721 		blknum = (unsigned) bp->bio_pblkno * DEV_BSIZE/fdblk +
1722 			fd->skip/fdblk;
1723 		b_cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
1724 	}
1725 	TRACE1("fd%d", fdu);
1726 	TRACE1("[%s]", fdstates[fdc->state]);
1727 	TRACE1("(0x%x)", fd->flags);
1728 	untimeout(fd_turnoff, fd, fd->toffhandle);
1729 	fd->toffhandle = timeout(fd_turnoff, fd, 4 * hz);
1730 	switch (fdc->state)
1731 	{
1732 	case DEVIDLE:
1733 	case FINDWORK:	/* we have found new work */
1734 		fdc->retry = 0;
1735 		fd->skip = 0;
1736 		fdc->fd = fd;
1737 		fdc->fdu = fdu;
1738 		fdc->fdctl_wr(fdc, fd->ft->trans);
1739 		TRACE1("[0x%x->FDCTL]", fd->ft->trans);
1740 		/*******************************************************\
1741 		* If the next drive has a motor startup pending, then	*
1742 		* it will start up in its own good time			*
1743 		\*******************************************************/
1744 		if(fd->flags & FD_MOTOR_WAIT) {
1745 			fdc->state = MOTORWAIT;
1746 			return (0); /* come back later */
1747 		}
1748 		/*******************************************************\
1749 		* Maybe if it's not starting, it SHOULD be starting	*
1750 		\*******************************************************/
1751 		if (!(fd->flags & FD_MOTOR))
1752 		{
1753 			fdc->state = MOTORWAIT;
1754 			fd_turnon(fd);
1755 			return (0);
1756 		}
1757 		else	/* at least make sure we are selected */
1758 		{
1759 			set_motor(fdc, fd->fdsu, TURNON);
1760 		}
1761 		if (fdc->flags & FDC_NEEDS_RESET) {
1762 			fdc->state = RESETCTLR;
1763 			fdc->flags &= ~FDC_NEEDS_RESET;
1764 		} else
1765 			fdc->state = DOSEEK;
1766 		break;
1767 	case DOSEEK:
1768 		if (b_cylinder == (unsigned)fd->track)
1769 		{
1770 			fdc->state = SEEKCOMPLETE;
1771 			break;
1772 		}
1773 		if (fd_cmd(fdc, 3, NE7CMD_SEEK,
1774 			   fd->fdsu, b_cylinder * fd->ft->steptrac,
1775 			   0))
1776 		{
1777 			/*
1778 			 * seek command not accepted, looks like
1779 			 * the FDC went off to the Saints...
1780 			 */
1781 			fdc->retry = 6;	/* try a reset */
1782 			return(retrier(fdc));
1783 		}
1784 		fd->track = FD_NO_TRACK;
1785 		fdc->state = SEEKWAIT;
1786 		return(0);	/* will return later */
1787 	case SEEKWAIT:
1788 		/* allow heads to settle */
1789 		timeout(fd_pseudointr, fdc, hz / 16);
1790 		fdc->state = SEEKCOMPLETE;
1791 		return(0);	/* will return later */
1792 	case SEEKCOMPLETE : /* SEEK DONE, START DMA */
1793 		/* Make sure seek really happened*/
1794 		if(fd->track == FD_NO_TRACK) {
1795 			int descyl = b_cylinder * fd->ft->steptrac;
1796 			do {
1797 				/*
1798 				 * This might be a "ready changed" interrupt,
1799 				 * which cannot really happen since the
1800 				 * RDY pin is hardwired to + 5 volts.  This
1801 				 * generally indicates a "bouncing" intr
1802 				 * line, so do one of the following:
1803 				 *
1804 				 * When running on an enhanced FDC that is
1805 				 * known to not go stuck after responding
1806 				 * with INVALID, fetch all interrupt states
1807 				 * until seeing either an INVALID or a
1808 				 * real interrupt condition.
1809 				 *
1810 				 * When running on a dumb old NE765, give
1811 				 * up immediately.  The controller will
1812 				 * provide up to four dummy RC interrupt
1813 				 * conditions right after reset (for the
1814 				 * corresponding four drives), so this is
1815 				 * our only chance to get notice that it
1816 				 * was not the FDC that caused the interrupt.
1817 				 */
1818 				if (fd_sense_int(fdc, &st0, &cyl)
1819 				    == FD_NOT_VALID)
1820 					return 0;
1821 				if(fdc->fdct == FDC_NE765
1822 				   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
1823 					return 0; /* hope for a real intr */
1824 			} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
1825 
1826 			if (0 == descyl) {
1827 				int failed = 0;
1828 				/*
1829 				 * seek to cyl 0 requested; make sure we are
1830 				 * really there
1831 				 */
1832 				if (fd_sense_drive_status(fdc, &st3))
1833 					failed = 1;
1834 				if ((st3 & NE7_ST3_T0) == 0) {
1835 					printf(
1836 		"fd%d: Seek to cyl 0, but not really there (ST3 = %b)\n",
1837 					       fdu, st3, NE7_ST3BITS);
1838 					failed = 1;
1839 				}
1840 
1841 				if (failed) {
1842 					if(fdc->retry < 3)
1843 						fdc->retry = 3;
1844 					return (retrier(fdc));
1845 				}
1846 			}
1847 
1848 			if (cyl != descyl) {
1849 				printf(
1850 		"fd%d: Seek to cyl %d failed; am at cyl %d (ST0 = 0x%x)\n",
1851 				       fdu, descyl, cyl, st0);
1852 				if (fdc->retry < 3)
1853 					fdc->retry = 3;
1854 				return (retrier(fdc));
1855 			}
1856 		}
1857 
1858 		fd->track = b_cylinder;
1859 		if (!rdsectid && !(fdc->flags & FDC_NODMA))
1860 			isa_dmastart(idf, bp->bio_data+fd->skip,
1861 				format ? bp->bio_bcount : fdblk, fdc->dmachan);
1862 		sectrac = fd->ft->sectrac;
1863 		sec = blknum %  (sectrac * fd->ft->heads);
1864 		head = sec / sectrac;
1865 		sec = sec % sectrac + 1;
1866 		fd->hddrv = ((head&1)<<2)+fdu;
1867 
1868 		if(format || !(read || rdsectid))
1869 		{
1870 			/* make sure the drive is writable */
1871 			if(fd_sense_drive_status(fdc, &st3) != 0)
1872 			{
1873 				/* stuck controller? */
1874 				if (!(fdc->flags & FDC_NODMA))
1875 					isa_dmadone(idf,
1876 						    bp->bio_data + fd->skip,
1877 						    format ? bp->bio_bcount : fdblk,
1878 						    fdc->dmachan);
1879 				fdc->retry = 6;	/* reset the beast */
1880 				return (retrier(fdc));
1881 			}
1882 			if(st3 & NE7_ST3_WP)
1883 			{
1884 				/*
1885 				 * XXX YES! this is ugly.
1886 				 * in order to force the current operation
1887 				 * to fail, we will have to fake an FDC
1888 				 * error - all error handling is done
1889 				 * by the retrier()
1890 				 */
1891 				fdc->status[0] = NE7_ST0_IC_AT;
1892 				fdc->status[1] = NE7_ST1_NW;
1893 				fdc->status[2] = 0;
1894 				fdc->status[3] = fd->track;
1895 				fdc->status[4] = head;
1896 				fdc->status[5] = sec;
1897 				fdc->retry = 8;	/* break out immediately */
1898 				fdc->state = IOTIMEDOUT; /* not really... */
1899 				return (1);
1900 			}
1901 		}
1902 
1903 		if (format) {
1904 			if (fdc->flags & FDC_NODMA) {
1905 				/*
1906 				 * This seems to be necessary for
1907 				 * whatever obscure reason; if we omit
1908 				 * it, we end up filling the sector ID
1909 				 * fields of the newly formatted track
1910 				 * entirely with garbage, causing
1911 				 * `wrong cylinder' errors all over
1912 				 * the place when trying to read them
1913 				 * back.
1914 				 *
1915 				 * Umpf.
1916 				 */
1917 				SET_BCDR(fdc, 1, bp->bio_bcount, 0);
1918 
1919 				(void)fdcpio(fdc,bp->bio_cmd,
1920 					bp->bio_data+fd->skip,
1921 					bp->bio_bcount);
1922 
1923 			}
1924 			/* formatting */
1925 			if(fd_cmd(fdc, 6,  NE7CMD_FORMAT, head << 2 | fdu,
1926 				  finfo->fd_formb_secshift,
1927 				  finfo->fd_formb_nsecs,
1928 				  finfo->fd_formb_gaplen,
1929 				  finfo->fd_formb_fillbyte, 0)) {
1930 				/* controller fell over */
1931 				if (!(fdc->flags & FDC_NODMA))
1932 					isa_dmadone(idf,
1933 						    bp->bio_data + fd->skip,
1934 						    format ? bp->bio_bcount : fdblk,
1935 						    fdc->dmachan);
1936 				fdc->retry = 6;
1937 				return (retrier(fdc));
1938 			}
1939 		} else if (rdsectid) {
1940 			if (fd_cmd(fdc, 2, NE7CMD_READID, head << 2 | fdu, 0)) {
1941 				/* controller jamming */
1942 				fdc->retry = 6;
1943 				return (retrier(fdc));
1944 			}
1945 		} else {
1946 			/* read or write operation */
1947 			if (fdc->flags & FDC_NODMA) {
1948 				/*
1949 				 * this seems to be necessary even when
1950 				 * reading data
1951 				 */
1952 				SET_BCDR(fdc, 1, fdblk, 0);
1953 
1954 				/*
1955 				 * perform the write pseudo-DMA before
1956 				 * the WRITE command is sent
1957 				 */
1958 				if (!read)
1959 					(void)fdcpio(fdc,bp->bio_cmd,
1960 					    bp->bio_data+fd->skip,
1961 					    fdblk);
1962 			}
1963 			if (fd_cmd(fdc, 9,
1964 				   (read ? NE7CMD_READ : NE7CMD_WRITE),
1965 				   head << 2 | fdu,  /* head & unit */
1966 				   fd->track,        /* track */
1967 				   head,
1968 				   sec,              /* sector + 1 */
1969 				   fd->ft->secsize,  /* sector size */
1970 				   sectrac,          /* sectors/track */
1971 				   fd->ft->gap,      /* gap size */
1972 				   fd->ft->datalen,  /* data length */
1973 				   0)) {
1974 				/* the beast is sleeping again */
1975 				if (!(fdc->flags & FDC_NODMA))
1976 					isa_dmadone(idf,
1977 						    bp->bio_data + fd->skip,
1978 						    format ? bp->bio_bcount : fdblk,
1979 						    fdc->dmachan);
1980 				fdc->retry = 6;
1981 				return (retrier(fdc));
1982 			}
1983 		}
1984 		if (!rdsectid && (fdc->flags & FDC_NODMA))
1985 			/*
1986 			 * if this is a read, then simply await interrupt
1987 			 * before performing PIO
1988 			 */
1989 			if (read && !fdcpio(fdc,bp->bio_cmd,
1990 			    bp->bio_data+fd->skip,fdblk)) {
1991 				fd->tohandle = timeout(fd_iotimeout, fdc, hz);
1992 				return(0);      /* will return later */
1993 			}
1994 
1995 		/*
1996 		 * write (or format) operation will fall through and
1997 		 * await completion interrupt
1998 		 */
1999 		fdc->state = IOCOMPLETE;
2000 		fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2001 		return (0);	/* will return later */
2002 	case PIOREAD:
2003 		/*
2004 		 * actually perform the PIO read.  The IOCOMPLETE case
2005 		 * removes the timeout for us.
2006 		 */
2007 		(void)fdcpio(fdc,bp->bio_cmd,bp->bio_data+fd->skip,fdblk);
2008 		fdc->state = IOCOMPLETE;
2009 		/* FALLTHROUGH */
2010 	case IOCOMPLETE: /* IO DONE, post-analyze */
2011 		untimeout(fd_iotimeout, fdc, fd->tohandle);
2012 
2013 		if (fd_read_status(fdc)) {
2014 			if (!rdsectid && !(fdc->flags & FDC_NODMA))
2015 				isa_dmadone(idf, bp->bio_data + fd->skip,
2016 					    format ? bp->bio_bcount : fdblk,
2017 					    fdc->dmachan);
2018 			if (fdc->retry < 6)
2019 				fdc->retry = 6;	/* force a reset */
2020 			return (retrier(fdc));
2021   		}
2022 
2023 		fdc->state = IOTIMEDOUT;
2024 
2025 		/* FALLTHROUGH */
2026 
2027 	case IOTIMEDOUT:
2028 		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2029 			isa_dmadone(idf, bp->bio_data + fd->skip,
2030 				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2031 		if (fdc->status[0] & NE7_ST0_IC) {
2032                         if ((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2033 			    && fdc->status[1] & NE7_ST1_OR) {
2034                                 /*
2035 				 * DMA overrun. Someone hogged the bus
2036 				 * and didn't release it in time for the
2037 				 * next FDC transfer.
2038 				 * Just restart it, don't increment retry
2039 				 * count. (vak)
2040                                  */
2041                                 fdc->state = SEEKCOMPLETE;
2042                                 return (1);
2043                         }
2044 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_IV
2045 				&& fdc->retry < 6)
2046 				fdc->retry = 6;	/* force a reset */
2047 			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2048 				&& fdc->status[2] & NE7_ST2_WC
2049 				&& fdc->retry < 3)
2050 				fdc->retry = 3;	/* force recalibrate */
2051 			return (retrier(fdc));
2052 		}
2053 		/* All OK */
2054 		if (rdsectid) {
2055 			/* copy out ID field contents */
2056 			idp = (struct fdc_readid *)bp->bio_data;
2057 			idp->cyl = fdc->status[3];
2058 			idp->head = fdc->status[4];
2059 			idp->sec = fdc->status[5];
2060 			idp->secshift = fdc->status[6];
2061 		}
2062 		fd->skip += fdblk;
2063 		if (!rdsectid && !format && fd->skip < bp->bio_bcount - bp->bio_resid) {
2064 			/* set up next transfer */
2065 			fdc->state = DOSEEK;
2066 		} else {
2067 			/* ALL DONE */
2068 			fd->skip = 0;
2069 			fdc->bp = NULL;
2070 			device_unbusy(fd->dev);
2071 			biofinish(bp, &fd->device_stats, 0);
2072 			fdc->fd = (fd_p) 0;
2073 			fdc->fdu = -1;
2074 			fdc->state = FINDWORK;
2075 		}
2076 		return (1);
2077 	case RESETCTLR:
2078 		fdc_reset(fdc);
2079 		fdc->retry++;
2080 		fdc->state = RESETCOMPLETE;
2081 		return (0);
2082 	case RESETCOMPLETE:
2083 		/*
2084 		 * Discard all the results from the reset so that they
2085 		 * can't cause an unexpected interrupt later.
2086 		 */
2087 		for (i = 0; i < 4; i++)
2088 			(void)fd_sense_int(fdc, &st0, &cyl);
2089 		fdc->state = STARTRECAL;
2090 		/* Fall through. */
2091 	case STARTRECAL:
2092 		if(fd_cmd(fdc, 2, NE7CMD_RECAL, fdu, 0)) {
2093 			/* arrgl */
2094 			fdc->retry = 6;
2095 			return (retrier(fdc));
2096 		}
2097 		fdc->state = RECALWAIT;
2098 		return (0);	/* will return later */
2099 	case RECALWAIT:
2100 		/* allow heads to settle */
2101 		timeout(fd_pseudointr, fdc, hz / 8);
2102 		fdc->state = RECALCOMPLETE;
2103 		return (0);	/* will return later */
2104 	case RECALCOMPLETE:
2105 		do {
2106 			/*
2107 			 * See SEEKCOMPLETE for a comment on this:
2108 			 */
2109 			if (fd_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
2110 				return 0;
2111 			if(fdc->fdct == FDC_NE765
2112 			   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2113 				return 0; /* hope for a real intr */
2114 		} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2115 		if ((st0 & NE7_ST0_IC) != NE7_ST0_IC_NT || cyl != 0)
2116 		{
2117 			if(fdc->retry > 3)
2118 				/*
2119 				 * a recalibrate from beyond cylinder 77
2120 				 * will "fail" due to the FDC limitations;
2121 				 * since people used to complain much about
2122 				 * the failure message, try not logging
2123 				 * this one if it seems to be the first
2124 				 * time in a line
2125 				 */
2126 				printf("fd%d: recal failed ST0 %b cyl %d\n",
2127 				       fdu, st0, NE7_ST0BITS, cyl);
2128 			if(fdc->retry < 3) fdc->retry = 3;
2129 			return (retrier(fdc));
2130 		}
2131 		fd->track = 0;
2132 		/* Seek (probably) necessary */
2133 		fdc->state = DOSEEK;
2134 		return (1);	/* will return immediatly */
2135 	case MOTORWAIT:
2136 		if(fd->flags & FD_MOTOR_WAIT)
2137 		{
2138 			return (0); /* time's not up yet */
2139 		}
2140 		if (fdc->flags & FDC_NEEDS_RESET) {
2141 			fdc->state = RESETCTLR;
2142 			fdc->flags &= ~FDC_NEEDS_RESET;
2143 		} else {
2144 			/*
2145 			 * If all motors were off, then the controller was
2146 			 * reset, so it has lost track of the current
2147 			 * cylinder.  Recalibrate to handle this case.
2148 			 * But first, discard the results of the reset.
2149 			 */
2150 			fdc->state = RESETCOMPLETE;
2151 		}
2152 		return (1);	/* will return immediatly */
2153 	default:
2154 		device_printf(fdc->fdc_dev, "unexpected FD int->");
2155 		if (fd_read_status(fdc) == 0)
2156 			printf("FDC status :%x %x %x %x %x %x %x   ",
2157 			       fdc->status[0],
2158 			       fdc->status[1],
2159 			       fdc->status[2],
2160 			       fdc->status[3],
2161 			       fdc->status[4],
2162 			       fdc->status[5],
2163 			       fdc->status[6] );
2164 		else
2165 			printf("No status available   ");
2166 		if (fd_sense_int(fdc, &st0, &cyl) != 0)
2167 		{
2168 			printf("[controller is dead now]\n");
2169 			return (0);
2170 		}
2171 		printf("ST0 = %x, PCN = %x\n", st0, cyl);
2172 		return (0);
2173 	}
2174 	/*XXX confusing: some branches return immediately, others end up here*/
2175 	return (1); /* Come back immediatly to new state */
2176 }
2177 
2178 static int
2179 retrier(struct fdc_data *fdc)
2180 {
2181 	struct bio *bp;
2182 	struct fd_data *fd;
2183 	int fdu;
2184 
2185 	bp = fdc->bp;
2186 
2187 	/* XXX shouldn't this be cached somewhere?  */
2188 	fdu = FDUNIT(minor(bp->bio_dev));
2189 	fd = devclass_get_softc(fd_devclass, fdu);
2190 	if (fd->options & FDOPT_NORETRY)
2191 		goto fail;
2192 
2193 	switch (fdc->retry) {
2194 	case 0: case 1: case 2:
2195 		fdc->state = SEEKCOMPLETE;
2196 		break;
2197 	case 3: case 4: case 5:
2198 		fdc->state = STARTRECAL;
2199 		break;
2200 	case 6:
2201 		fdc->state = RESETCTLR;
2202 		break;
2203 	case 7:
2204 		break;
2205 	default:
2206 	fail:
2207 		{
2208 			int printerror = (fd->options & FDOPT_NOERRLOG) == 0;
2209 
2210 			if (printerror)
2211 				diskerr(bp, "hard error",
2212 				    fdc->fd->skip / DEV_BSIZE,
2213 				    (struct disklabel *)NULL);
2214 			if (printerror) {
2215 				if (fdc->flags & FDC_STAT_VALID)
2216 				{
2217 					printf(
2218 				" (ST0 %b ST1 %b ST2 %b cyl %u hd %u sec %u)\n",
2219 					       fdc->status[0], NE7_ST0BITS,
2220 					       fdc->status[1], NE7_ST1BITS,
2221 					       fdc->status[2], NE7_ST2BITS,
2222 					       fdc->status[3], fdc->status[4],
2223 					       fdc->status[5]);
2224 				}
2225 				else
2226 					printf(" (No status)\n");
2227 			}
2228 		}
2229 		if ((fd->options & FDOPT_NOERROR) == 0) {
2230 			bp->bio_flags |= BIO_ERROR;
2231 			bp->bio_error = EIO;
2232 			bp->bio_resid += bp->bio_bcount - fdc->fd->skip;
2233 		}
2234 		fdc->bp = NULL;
2235 		fdc->fd->skip = 0;
2236 		device_unbusy(fd->dev);
2237 		biofinish(bp, &fdc->fd->device_stats, 0);
2238 		fdc->state = FINDWORK;
2239 		fdc->flags |= FDC_NEEDS_RESET;
2240 		fdc->fd = (fd_p) 0;
2241 		fdc->fdu = -1;
2242 		return (1);
2243 	}
2244 	fdc->retry++;
2245 	return (1);
2246 }
2247 
2248 static void
2249 fdbiodone(struct bio *bp)
2250 {
2251 	wakeup(bp);
2252 }
2253 
2254 static int
2255 fdmisccmd(dev_t dev, u_int cmd, void *data)
2256 {
2257  	fdu_t fdu;
2258  	fd_p fd;
2259 	struct bio *bp;
2260 	struct fd_formb *finfo;
2261 	struct fdc_readid *idfield;
2262 	size_t fdblk;
2263 
2264  	fdu = FDUNIT(minor(dev));
2265 	fd = devclass_get_softc(fd_devclass, fdu);
2266 	fdblk = 128 << fd->ft->secsize;
2267 	finfo = (struct fd_formb *)data;
2268 	idfield = (struct fdc_readid *)data;
2269 
2270 	bp = malloc(sizeof(struct bio), M_TEMP, M_ZERO | M_NOWAIT);
2271 	if (bp == 0)
2272 		return (ENOMEM);
2273 
2274 	/*
2275 	 * Set up a bio request for fdstrategy().  bio_blkno is faked
2276 	 * so that fdstrategy() will seek to the the requested
2277 	 * cylinder, and use the desired head.  Since we are not
2278 	 * interested in bioqdisksort() munging with our faked bio
2279 	 * request, we mark it as being an ordered request.
2280 	 */
2281 	bp->bio_cmd = cmd;
2282 	if (cmd == BIO_FORMAT) {
2283 		bp->bio_blkno =
2284 		    (finfo->cyl * (fd->ft->sectrac * fd->ft->heads) +
2285 		     finfo->head * fd->ft->sectrac) *
2286 		    fdblk / DEV_BSIZE;
2287 		bp->bio_bcount = sizeof(struct fd_idfield_data) *
2288 		    finfo->fd_formb_nsecs;
2289 	} else if (cmd == BIO_RDSECTID) {
2290 		bp->bio_blkno =
2291 		    (idfield->cyl * (fd->ft->sectrac * fd->ft->heads) +
2292 		     idfield->head * fd->ft->sectrac) *
2293 		    fdblk / DEV_BSIZE;
2294 		bp->bio_bcount = sizeof(struct fdc_readid);
2295 	} else
2296 		panic("wrong cmd in fdmisccmd()");
2297 	bp->bio_data = data;
2298 	bp->bio_dev = dev;
2299 	bp->bio_done = fdbiodone;
2300 	bp->bio_flags = BIO_ORDERED;
2301 
2302 	/*
2303 	 * Now run the cmd.  The wait loop is a version of bufwait()
2304 	 * adapted for struct bio instead of struct buf and
2305 	 * specialized for the current context.
2306 	 */
2307 	fdstrategy(bp);
2308 	while((bp->bio_flags & BIO_DONE) == 0)
2309 		tsleep(bp, PRIBIO, "fdcmd", 0);
2310 
2311 	free(bp, M_TEMP);
2312 	return (bp->bio_flags & BIO_ERROR ? bp->bio_error : 0);
2313 }
2314 
2315 static int
2316 fdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
2317 {
2318  	fdu_t fdu;
2319  	fd_p fd;
2320 	struct fd_type *fdt;
2321 	struct disklabel *dl;
2322 	struct fdc_status *fsp;
2323 	struct fdc_readid *rid;
2324 	char *buffer;
2325 	size_t fdblk;
2326 	int error = 0;
2327 
2328 	fdu = FDUNIT(minor(dev));
2329 	fd = devclass_get_softc(fd_devclass, fdu);
2330 	fdblk = 128 << fd->ft->secsize;
2331 
2332 	switch (cmd) {
2333 	case DIOCGDINFO:
2334 		buffer = malloc(DEV_BSIZE, M_TEMP, M_ZERO | M_NOWAIT);
2335 		if (buffer == 0) {
2336 			error = ENOMEM;
2337 			break;
2338 		}
2339 		dl = (struct disklabel *)buffer;
2340 		dl->d_secsize = fdblk;
2341 		fdt = fd->ft;
2342 		dl->d_secpercyl = fdt->size / fdt->tracks;
2343 		dl->d_type = DTYPE_FLOPPY;
2344 
2345 		if (readdisklabel(dkmodpart(dev, RAW_PART), dl)
2346 		    == NULL)
2347 			error = 0;
2348 		else
2349 			error = EINVAL;
2350 
2351 		*(struct disklabel *)addr = *dl;
2352 		free(buffer, M_TEMP);
2353 		break;
2354 
2355 	case DIOCSDINFO:
2356 		if ((flag & FWRITE) == 0)
2357 			error = EBADF;
2358 		break;
2359 
2360 	case DIOCWLABEL:
2361 		if ((flag & FWRITE) == 0)
2362 			error = EBADF;
2363 		break;
2364 
2365 	case DIOCWDINFO:
2366 		if ((flag & FWRITE) == 0) {
2367 			error = EBADF;
2368 			break;
2369 		}
2370 
2371 		dl = (struct disklabel *)addr;
2372 
2373 		buffer = malloc(DEV_BSIZE, M_TEMP, M_ZERO | M_NOWAIT);
2374 		if (buffer == 0) {
2375 			error = ENOMEM;
2376 			break;
2377 		}
2378 		if ((error = setdisklabel((struct disklabel *)buffer, dl,
2379 					  (u_long)0)) != 0)
2380 			break;
2381 
2382 		error = writedisklabel(dev, (struct disklabel *)buffer);
2383 		free(buffer, M_TEMP);
2384 		break;
2385 
2386 	case FD_FORM:
2387 		if ((flag & FWRITE) == 0)
2388 			error = EBADF;	/* must be opened for writing */
2389 		else if (((struct fd_formb *)addr)->format_version !=
2390 			FD_FORMAT_VERSION)
2391 			error = EINVAL;	/* wrong version of formatting prog */
2392 		else
2393 			error = fdmisccmd(dev, BIO_FORMAT, addr);
2394 		break;
2395 
2396 	case FD_GTYPE:                  /* get drive type */
2397 		*(struct fd_type *)addr = *fd->ft;
2398 		break;
2399 
2400 	case FD_STYPE:                  /* set drive type */
2401 		/* this is considered harmful; only allow for superuser */
2402 		if (suser(p) != 0)
2403 			return EPERM;
2404 		*fd->ft = *(struct fd_type *)addr;
2405 		break;
2406 
2407 	case FD_GOPTS:			/* get drive options */
2408 		*(int *)addr = fd->options;
2409 		break;
2410 
2411 	case FD_SOPTS:			/* set drive options */
2412 		fd->options = *(int *)addr;
2413 		break;
2414 
2415 #ifdef FDC_DEBUG
2416 	case FD_DEBUG:
2417 		fd_debug = *(int *)addr;
2418 		break;
2419 #endif
2420 
2421 	case FD_CLRERR:
2422 		if (suser(p) != 0)
2423 			return EPERM;
2424 		fd->fdc->fdc_errs = 0;
2425 		break;
2426 
2427 	case FD_GSTAT:
2428 		fsp = (struct fdc_status *)addr;
2429 		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2430 			return EINVAL;
2431 		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2432 		break;
2433 
2434 	case FD_READID:
2435 		rid = (struct fdc_readid *)addr;
2436 		if (rid->cyl > MAX_CYLINDER || rid->head > MAX_HEAD)
2437 			return EINVAL;
2438 		error = fdmisccmd(dev, BIO_RDSECTID, addr);
2439 		break;
2440 
2441 	default:
2442 		error = ENOTTY;
2443 		break;
2444 	}
2445 	return (error);
2446 }
2447