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