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