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