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