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