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