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