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