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