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