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