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