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