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