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