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