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