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