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