ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / block / floppy98.c
1 /*
2  *  linux/drivers/block/floppy.c
3  *
4  *  Copyright (C) 1991, 1992  Linus Torvalds
5  *  Copyright (C) 1993, 1994  Alain Knaff
6  *  Copyright (C) 1998 Alan Cox
7  */
8 /*
9  * 02.12.91 - Changed to static variables to indicate need for reset
10  * and recalibrate. This makes some things easier (output_byte reset
11  * checking etc), and means less interrupt jumping in case of errors,
12  * so the code is hopefully easier to understand.
13  */
14
15 /*
16  * This file is certainly a mess. I've tried my best to get it working,
17  * but I don't like programming floppies, and I have only one anyway.
18  * Urgel. I should check for more errors, and do more graceful error
19  * recovery. Seems there are problems with several drives. I've tried to
20  * correct them. No promises.
21  */
22
23 /*
24  * As with hd.c, all routines within this file can (and will) be called
25  * by interrupts, so extreme caution is needed. A hardware interrupt
26  * handler may not sleep, or a kernel panic will happen. Thus I cannot
27  * call "floppy-on" directly, but have to set a special timer interrupt
28  * etc.
29  */
30
31 /*
32  * 28.02.92 - made track-buffering routines, based on the routines written
33  * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus.
34  */
35
36 /*
37  * Automatic floppy-detection and formatting written by Werner Almesberger
38  * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with
39  * the floppy-change signal detection.
40  */
41
42 /*
43  * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed
44  * FDC data overrun bug, added some preliminary stuff for vertical
45  * recording support.
46  *
47  * 1992/9/17: Added DMA allocation & DMA functions. -- hhb.
48  *
49  * TODO: Errors are still not counted properly.
50  */
51
52 /* 1992/9/20
53  * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl)
54  * modeled after the freeware MS-DOS program fdformat/88 V1.8 by
55  * Christoph H. Hochst\"atter.
56  * I have fixed the shift values to the ones I always use. Maybe a new
57  * ioctl() should be created to be able to modify them.
58  * There is a bug in the driver that makes it impossible to format a
59  * floppy as the first thing after bootup.
60  */
61
62 /*
63  * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and
64  * this helped the floppy driver as well. Much cleaner, and still seems to
65  * work.
66  */
67
68 /* 1994/6/24 --bbroad-- added the floppy table entries and made
69  * minor modifications to allow 2.88 floppies to be run.
70  */
71
72 /* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more
73  * disk types.
74  */
75
76 /*
77  * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger
78  * format bug fixes, but unfortunately some new bugs too...
79  */
80
81 /* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write
82  * errors to allow safe writing by specialized programs.
83  */
84
85 /* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks
86  * by defining bit 1 of the "stretch" parameter to mean put sectors on the
87  * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's
88  * drives are "upside-down").
89  */
90
91 /*
92  * 1995/8/26 -- Andreas Busse -- added Mips support.
93  */
94
95 /*
96  * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent
97  * features to asm/floppy.h.
98  */
99
100 /*
101  * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of
102  * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting &
103  * use of '0' for NULL.
104  */
105  
106 /*
107  * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation
108  * failures.
109  */
110
111 /*
112  * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives.
113  */
114
115 /*
116  * 1999/01/19 -- N.Fujita & Linux/98 Project -- Added code for NEC PC-9800
117  * series.
118  */
119
120 /*
121  * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24
122  * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were
123  * being used to store jiffies, which are unsigned longs).
124  */
125
126 /*
127  * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br>
128  * - get rid of check_region
129  * - s/suser/capable/
130  */
131
132 /*
133  * 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no
134  * floppy controller (lingering task on list after module is gone... boom.)
135  */
136
137 /*
138  * 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range
139  * (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix
140  * requires many non-obvious changes in arch dependent code.
141  */
142
143 /*
144  * 2002/10/12 -- Osamu Tomita <tomita@cinet.co.jp>
145  * split code from floppy.c
146  * support NEC PC-9800 only
147  */
148
149 #define FLOPPY_SANITY_CHECK
150 #undef  FLOPPY_SILENT_DCL_CLEAR
151
152 /*
153 #define PC9800_DEBUG_FLOPPY
154 #define PC9800_DEBUG_FLOPPY2
155 */
156
157 #define REALLY_SLOW_IO
158
159 #define DEBUGT 2
160 #define DCL_DEBUG /* debug disk change line */
161
162 /* do print messages for unexpected interrupts */
163 static int print_unex=1;
164 #include <linux/module.h>
165 #include <linux/sched.h>
166 #include <linux/fs.h>
167 #include <linux/kernel.h>
168 #include <linux/timer.h>
169 #include <linux/workqueue.h>
170 #include <linux/version.h>
171 #include <linux/fdreg.h>
172 #include <linux/blkdev.h>
173 #include <linux/blkpg.h>
174 #include <linux/cdrom.h>        /* for the compatibility eject ioctl */
175 #include <linux/completion.h>
176
177 /*
178  * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support
179  */
180
181
182 #include <linux/fd.h>
183 #define FLOPPY98_MOTOR_MASK 0x08
184
185 #include <linux/hdreg.h>
186 #define FD98_STATUS     (0 + FD_IOPORT )
187 #define FD98_DATA       (2 + FD_IOPORT )
188 #define FD_MODE         (4 + FD_IOPORT )
189 #define FD_MODE_CHANGE  0xbe
190 #define FD_EMODE_CHANGE 0x4be
191
192 #include <linux/errno.h>
193 #include <linux/slab.h>
194 #include <linux/mm.h>
195 #include <linux/bio.h>
196 #include <linux/string.h>
197 #include <linux/fcntl.h>
198 #include <linux/delay.h>
199 #include <linux/mc146818rtc.h> /* CMOS defines */
200 #include <linux/ioport.h>
201 #include <linux/interrupt.h>
202 #include <linux/init.h>
203 #include <linux/devfs_fs_kernel.h>
204 #include <linux/device.h>
205 #include <linux/buffer_head.h>          /* for invalidate_buffers() */
206
207 /*
208  * PS/2 floppies have much slower step rates than regular floppies.
209  * It's been recommended that take about 1/4 of the default speed
210  * in some more extreme cases.
211  */
212 static int slow_floppy;
213
214 #include <asm/dma.h>
215 #include <asm/irq.h>
216 #include <asm/system.h>
217 #include <asm/io.h>
218 #include <asm/uaccess.h>
219
220 #ifndef DEFAULT_FLOPPY_IRQ
221 # define DEFAULT_FLOPPY_IRQ     11
222 #endif
223 #ifndef DEFAULT_FLOPPY_DMA
224 # define DEFAULT_FLOPPY_DMA     2
225 #endif
226
227 static int FLOPPY_IRQ=DEFAULT_FLOPPY_IRQ;
228 static int FLOPPY_DMA=DEFAULT_FLOPPY_DMA;
229 static int can_use_virtual_dma=2;
230 static int auto_detect_mode = 0;
231 static int retry_auto_detect = 0;
232 #define FD_AFTER_RESET_DELAY 1000
233
234 /* =======
235  * can use virtual DMA:
236  * 0 = use of virtual DMA disallowed by config
237  * 1 = use of virtual DMA prescribed by config
238  * 2 = no virtual DMA preference configured.  By default try hard DMA,
239  * but fall back on virtual DMA when not enough memory available
240  */
241
242 static int use_virtual_dma;
243 /* =======
244  * use virtual DMA
245  * 0 using hard DMA
246  * 1 using virtual DMA
247  * This variable is set to virtual when a DMA mem problem arises, and
248  * reset back in floppy_grab_irq_and_dma.
249  * It is not safe to reset it in other circumstances, because the floppy
250  * driver may have several buffers in use at once, and we do currently not
251  * record each buffers capabilities
252  */
253
254 static spinlock_t floppy_lock = SPIN_LOCK_UNLOCKED;
255 static struct completion device_release;
256
257 static unsigned short virtual_dma_port=0x3f0;
258 irqreturn_t floppy_interrupt(int irq, void *dev_id, struct pt_regs * regs);
259 static int set_mode(char mask, char data);
260 static void register_devfs_entries (int drive) __init;
261
262 #define K_64    0x10000         /* 64KB */
263
264 /* the following is the mask of allowed drives. By default units 2 and
265  * 3 of both floppy controllers are disabled, because switching on the
266  * motor of these drives causes system hangs on some PCI computers. drive
267  * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if
268  * a drive is allowed.
269  *
270  * NOTE: This must come before we include the arch floppy header because
271  *       some ports reference this variable from there. -DaveM
272  */
273
274 static int allowed_drive_mask = 0x0f;
275
276 #include <asm/floppy.h>
277
278 static int irqdma_allocated;
279
280 #define LOCAL_END_REQUEST
281 #define DEVICE_NAME "floppy"
282
283 #include <linux/blkpg.h>
284 #include <linux/cdrom.h> /* for the compatibility eject ioctl */
285 #include <linux/completion.h>
286
287 static struct request *current_req;
288 static struct request_queue *floppy_queue;
289
290 #ifndef fd_get_dma_residue
291 #define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)
292 #endif
293
294 /* Dma Memory related stuff */
295
296 #ifndef fd_dma_mem_free
297 #define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))
298 #endif
299
300 #ifndef fd_dma_mem_alloc
301 #define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL,get_order(size))
302 #endif
303
304 static inline void fallback_on_nodma_alloc(char **addr, size_t l)
305 {
306 #ifdef FLOPPY_CAN_FALLBACK_ON_NODMA
307         if (*addr)
308                 return; /* we have the memory */
309         if (can_use_virtual_dma != 2)
310                 return; /* no fallback allowed */
311         printk("DMA memory shortage. Temporarily falling back on virtual DMA\n");
312         *addr = (char *) nodma_mem_alloc(l);
313 #else
314         return;
315 #endif
316 }
317
318 /* End dma memory related stuff */
319
320 static unsigned long fake_change;
321 static int initialising=1;
322
323 #define ITYPE(x) (((x)>>2) & 0x1f)
324 #define TOMINOR(x) ((x & 3) | ((x & 4) << 5))
325 #define UNIT(x) ((x) & 0x03)            /* drive on fdc */
326 #define FDC(x) (((x) & 0x04) >> 2)  /* fdc of drive */
327 #define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))
328                                 /* reverse mapping from unit and fdc to drive */
329 #define DP (&drive_params[current_drive])
330 #define DRS (&drive_state[current_drive])
331 #define DRWE (&write_errors[current_drive])
332 #define FDCS (&fdc_state[fdc])
333 #define CLEARF(x) (clear_bit(x##_BIT, &DRS->flags))
334 #define SETF(x) (set_bit(x##_BIT, &DRS->flags))
335 #define TESTF(x) (test_bit(x##_BIT, &DRS->flags))
336
337 #define UDP (&drive_params[drive])
338 #define UDRS (&drive_state[drive])
339 #define UDRWE (&write_errors[drive])
340 #define UFDCS (&fdc_state[FDC(drive)])
341 #define UCLEARF(x) (clear_bit(x##_BIT, &UDRS->flags))
342 #define USETF(x) (set_bit(x##_BIT, &UDRS->flags))
343 #define UTESTF(x) (test_bit(x##_BIT, &UDRS->flags))
344
345 #define DPRINT(format, args...) printk(DEVICE_NAME "%d: " format, current_drive , ## args)
346
347 #define PH_HEAD(floppy,head) (((((floppy)->stretch & 2) >>1) ^ head) << 2)
348 #define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH)
349
350 #define CLEARSTRUCT(x) memset((x), 0, sizeof(*(x)))
351
352 /* read/write */
353 #define COMMAND raw_cmd->cmd[0]
354 #define DR_SELECT raw_cmd->cmd[1]
355 #define TRACK raw_cmd->cmd[2]
356 #define HEAD raw_cmd->cmd[3]
357 #define SECTOR raw_cmd->cmd[4]
358 #define SIZECODE raw_cmd->cmd[5]
359 #define SECT_PER_TRACK raw_cmd->cmd[6]
360 #define GAP raw_cmd->cmd[7]
361 #define SIZECODE2 raw_cmd->cmd[8]
362 #define NR_RW 9
363
364 /* format */
365 #define F_SIZECODE raw_cmd->cmd[2]
366 #define F_SECT_PER_TRACK raw_cmd->cmd[3]
367 #define F_GAP raw_cmd->cmd[4]
368 #define F_FILL raw_cmd->cmd[5]
369 #define NR_F 6
370
371 /*
372  * Maximum disk size (in kilobytes). This default is used whenever the
373  * current disk size is unknown.
374  * [Now it is rather a minimum]
375  */
376 #define MAX_DISK_SIZE 4 /* 3984*/
377
378
379 /*
380  * globals used by 'result()'
381  */
382 #define MAX_REPLIES 16
383 static unsigned char reply_buffer[MAX_REPLIES];
384 static int inr; /* size of reply buffer, when called from interrupt */
385 #define ST0 (reply_buffer[0])
386 #define ST1 (reply_buffer[1])
387 #define ST2 (reply_buffer[2])
388 #define ST3 (reply_buffer[0]) /* result of GETSTATUS */
389 #define R_TRACK (reply_buffer[3])
390 #define R_HEAD (reply_buffer[4])
391 #define R_SECTOR (reply_buffer[5])
392 #define R_SIZECODE (reply_buffer[6])
393
394 #define SEL_DLY (2*HZ/100)
395
396 /*
397  * this struct defines the different floppy drive types.
398  */
399 static struct {
400         struct floppy_drive_params params;
401         const char *name; /* name printed while booting */
402 } default_drive_params[]= {
403 /* NOTE: the time values in jiffies should be in msec!
404  CMOS drive type
405   |     Maximum data rate supported by drive type
406   |     |   Head load time, msec
407   |     |   |   Head unload time, msec (not used)
408   |     |   |   |     Step rate interval, usec
409   |     |   |   |     |       Time needed for spinup time (jiffies)
410   |     |   |   |     |       |      Timeout for spinning down (jiffies)
411   |     |   |   |     |       |      |   Spindown offset (where disk stops)
412   |     |   |   |     |       |      |   |     Select delay
413   |     |   |   |     |       |      |   |     |     RPS
414   |     |   |   |     |       |      |   |     |     |    Max number of tracks
415   |     |   |   |     |       |      |   |     |     |    |     Interrupt timeout
416   |     |   |   |     |       |      |   |     |     |    |     |   Max nonintlv. sectors
417   |     |   |   |     |       |      |   |     |     |    |     |   | -Max Errors- flags */
418 {{0,  500, 16, 16, 8000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  80, 3*HZ, 20, {3,1,2,0,2}, 0,
419       0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" },
420
421 {{1,  300, 16, 16, 8000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  40, 3*HZ, 17, {3,1,2,0,2}, 0,
422       0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/
423
424 {{2,  500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6,  83, 3*HZ, 17, {3,1,2,0,2}, 0,
425       0, { 2, 6, 4, 0, 0, 0, 0, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/
426
427 {{3,  250, 16, 16, 3000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  83, 3*HZ, 20, {3,1,2,0,2}, 0,
428       0, { 4, 6, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/
429
430 {{4,  500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 20, {3,1,2,0,2}, 0,
431       0, { 7,10, 2, 4, 6, 0, 0, 0}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/
432
433 {{5, 1000, 15,  8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 40, {3,1,2,0,2}, 0,
434       0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/
435
436 {{6, 1000, 15,  8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 40, {3,1,2,0,2}, 0,
437       0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/
438 /*    |  --autodetected formats---    |      |      |
439  *    read_track                      |      |    Name printed when booting
440  *                                    |     Native format
441  *                  Frequency of disk change checks */
442 };
443
444 static struct floppy_drive_params drive_params[N_DRIVE];
445 static struct floppy_drive_struct drive_state[N_DRIVE];
446 static struct floppy_write_errors write_errors[N_DRIVE];
447 static struct timer_list motor_off_timer[N_DRIVE];
448 static struct gendisk *disks[N_DRIVE];
449 static struct block_device *opened_bdev[N_DRIVE];
450 static DECLARE_MUTEX(open_lock);
451 static struct floppy_raw_cmd *raw_cmd, default_raw_cmd;
452
453 /*
454  * This struct defines the different floppy types.
455  *
456  * Bit 0 of 'stretch' tells if the tracks need to be doubled for some
457  * types (e.g. 360kB diskette in 1.2MB drive, etc.).  Bit 1 of 'stretch'
458  * tells if the disk is in Commodore 1581 format, which means side 0 sectors
459  * are located on side 1 of the disk but with a side 0 ID, and vice-versa.
460  * This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the
461  * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical
462  * side 0 is on physical side 0 (but with the misnamed sector IDs).
463  * 'stretch' should probably be renamed to something more general, like
464  * 'options'.  Other parameters should be self-explanatory (see also
465  * setfdprm(8)).
466  */
467 /*
468             Size
469              |  Sectors per track
470              |  | Head
471              |  | |  Tracks
472              |  | |  | Stretch
473              |  | |  | |  Gap 1 size
474              |  | |  | |    |  Data rate, | 0x40 for perp
475              |  | |  | |    |    |  Spec1 (stepping rate, head unload
476              |  | |  | |    |    |    |    /fmt gap (gap2) */
477 static struct floppy_struct floppy_type[32] = {
478         {    0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL    }, /*  0 no testing    */
479 #if 0
480         {  720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360"  }, /*  1 360KB PC      */
481 #else
482         { 2464,16,2,77,0,0x35,0x48,0xDF,0x74,"d360"  }, /*  1 1.25MB 98     */
483 #endif
484         { 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /*  2 1.2MB AT      */
485         {  720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360"  }, /*  3 360KB SS 3.5" */
486         { 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720"  }, /*  4 720KB 3.5"    */
487         {  720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360"  }, /*  5 360KB AT      */
488         { 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720"  }, /*  6 720KB AT      */
489         { 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /*  7 1.44MB 3.5"   */
490         { 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /*  8 2.88MB 3.5"   */
491         { 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /*  9 3.12MB 3.5"   */
492
493         { 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25"  */
494         { 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5"   */
495         {  820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410"  }, /* 12 410KB 5.25"   */
496         { 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820"  }, /* 13 820KB 3.5"    */
497         { 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25"  */
498         { 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5"   */
499         {  840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420"  }, /* 16 420KB 5.25"   */
500         { 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830"  }, /* 17 830KB 3.5"    */
501         { 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25"  */
502         { 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5"  */
503
504         { 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880"  }, /* 20 880KB 5.25"   */
505         { 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5"   */
506         { 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5"   */
507         { 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25"   */
508         { 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5"   */
509         { 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5"   */
510         { 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5"   */
511         { 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5"   */
512         { 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5"   */
513
514         { 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5"   */
515         { 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800"  }, /* 30 800KB 3.5"    */
516         { 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5"    */
517 };
518
519 #define NUMBER(x)       (sizeof(x) / sizeof(*(x)))
520 #define SECTSIZE (_FD_SECTSIZE(*floppy))
521
522 /* Auto-detection: Disk type used until the next media change occurs. */
523 static struct floppy_struct *current_type[N_DRIVE];
524
525 /*
526  * User-provided type information. current_type points to
527  * the respective entry of this array.
528  */
529 static struct floppy_struct user_params[N_DRIVE];
530
531 static sector_t floppy_sizes[256];
532
533 /*
534  * The driver is trying to determine the correct media format
535  * while probing is set. rw_interrupt() clears it after a
536  * successful access.
537  */
538 static int probing;
539
540 /* Synchronization of FDC access. */
541 #define FD_COMMAND_NONE -1
542 #define FD_COMMAND_ERROR 2
543 #define FD_COMMAND_OKAY 3
544
545 static volatile int command_status = FD_COMMAND_NONE;
546 static unsigned long fdc_busy;
547 static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
548 static DECLARE_WAIT_QUEUE_HEAD(command_done);
549
550 #define NO_SIGNAL (!interruptible || !signal_pending(current))
551 #define CALL(x) if ((x) == -EINTR) return -EINTR
552 #define ECALL(x) if ((ret = (x))) return ret;
553 #define _WAIT(x,i) CALL(ret=wait_til_done((x),i))
554 #define WAIT(x) _WAIT((x),interruptible)
555 #define IWAIT(x) _WAIT((x),1)
556
557 /* Errors during formatting are counted here. */
558 static int format_errors;
559
560 /* Format request descriptor. */
561 static struct format_descr format_req;
562
563 /*
564  * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps
565  * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),
566  * H is head unload time (1=16ms, 2=32ms, etc)
567  */
568
569 /*
570  * Track buffer
571  * Because these are written to by the DMA controller, they must
572  * not contain a 64k byte boundary crossing, or data will be
573  * corrupted/lost.
574  */
575 static char *floppy_track_buffer;
576 static int max_buffer_sectors;
577
578 static int *errors;
579 typedef void (*done_f)(int);
580 static struct cont_t {
581         void (*interrupt)(void); /* this is called after the interrupt of the
582                                   * main command */
583         void (*redo)(void); /* this is called to retry the operation */
584         void (*error)(void); /* this is called to tally an error */
585         done_f done; /* this is called to say if the operation has 
586                       * succeeded/failed */
587 } *cont;
588
589 static void floppy_ready(void);
590 static void floppy_start(void);
591 static void process_fd_request(void);
592 static void recalibrate_floppy(void);
593 static void floppy_shutdown(unsigned long);
594
595 static int floppy_grab_irq_and_dma(void);
596 static void floppy_release_irq_and_dma(void);
597
598 /*
599  * The "reset" variable should be tested whenever an interrupt is scheduled,
600  * after the commands have been sent. This is to ensure that the driver doesn't
601  * get wedged when the interrupt doesn't come because of a failed command.
602  * reset doesn't need to be tested before sending commands, because
603  * output_byte is automatically disabled when reset is set.
604  */
605 #define CHECK_RESET { if (FDCS->reset){ reset_fdc(); return; } }
606 static void reset_fdc(void);
607
608 /*
609  * These are global variables, as that's the easiest way to give
610  * information to interrupts. They are the data used for the current
611  * request.
612  */
613 #define NO_TRACK -1
614 #define NEED_1_RECAL -2
615 #define NEED_2_RECAL -3
616
617 static int usage_count;
618
619 /* buffer related variables */
620 static int buffer_track = -1;
621 static int buffer_drive = -1;
622 static int buffer_min = -1;
623 static int buffer_max = -1;
624
625 /* fdc related variables, should end up in a struct */
626 static struct floppy_fdc_state fdc_state[N_FDC];
627 static int fdc; /* current fdc */
628
629 static struct floppy_struct *_floppy = floppy_type;
630 static unsigned char current_drive;
631 static long current_count_sectors;
632 static unsigned char fsector_t; /* sector in track */
633 static unsigned char in_sector_offset;  /* offset within physical sector,
634                                          * expressed in units of 512 bytes */
635
636 #ifndef fd_eject
637 static inline int fd_eject(int drive)
638 {
639         return -EINVAL;
640 }
641 #endif
642
643 #ifdef DEBUGT
644 static long unsigned debugtimer;
645 #endif
646
647 /*
648  * Debugging
649  * =========
650  */
651 static inline void set_debugt(void)
652 {
653 #ifdef DEBUGT
654         debugtimer = jiffies;
655 #endif
656 }
657
658 static inline void debugt(const char *message)
659 {
660 #ifdef DEBUGT
661         if (DP->flags & DEBUGT)
662                 printk("%s dtime=%lu\n", message, jiffies-debugtimer);
663 #endif
664 }
665
666 typedef void (*timeout_fn)(unsigned long);
667 static struct timer_list fd_timeout = TIMER_INITIALIZER(floppy_shutdown, 0, 0);
668
669 static const char *timeout_message;
670
671 #ifdef FLOPPY_SANITY_CHECK
672 static void is_alive(const char *message)
673 {
674         /* this routine checks whether the floppy driver is "alive" */
675         if (fdc_busy && command_status < 2 && !timer_pending(&fd_timeout)){
676                 DPRINT("timeout handler died: %s\n",message);
677         }
678 }
679 #endif
680
681 static void (*do_floppy)(void) = NULL;
682
683 #ifdef FLOPPY_SANITY_CHECK
684
685 #define OLOGSIZE 20
686
687 static void (*lasthandler)(void);
688 static unsigned long interruptjiffies;
689 static unsigned long resultjiffies;
690 static int resultsize;
691 static unsigned long lastredo;
692
693 static struct output_log {
694         unsigned char data;
695         unsigned char status;
696         unsigned long jiffies;
697 } output_log[OLOGSIZE];
698
699 static int output_log_pos;
700 #endif
701
702 #define current_reqD -1
703 #define MAXTIMEOUT -2
704
705 static void reschedule_timeout(int drive, const char *message, int marg)
706 {
707         if (drive == current_reqD)
708                 drive = current_drive;
709         del_timer(&fd_timeout);
710         if (drive < 0 || drive > N_DRIVE) {
711                 fd_timeout.expires = jiffies + 20UL*HZ;
712                 drive=0;
713         } else
714                 fd_timeout.expires = jiffies + UDP->timeout;
715         add_timer(&fd_timeout);
716         if (UDP->flags & FD_DEBUG){
717                 DPRINT("reschedule timeout ");
718                 printk(message, marg);
719                 printk("\n");
720         }
721         timeout_message = message;
722 }
723
724 static int maximum(int a, int b)
725 {
726         if (a > b)
727                 return a;
728         else
729                 return b;
730 }
731 #define INFBOUND(a,b) (a)=maximum((a),(b));
732
733 static int minimum(int a, int b)
734 {
735         if (a < b)
736                 return a;
737         else
738                 return b;
739 }
740 #define SUPBOUND(a,b) (a)=minimum((a),(b));
741
742
743 /*
744  * Bottom half floppy driver.
745  * ==========================
746  *
747  * This part of the file contains the code talking directly to the hardware,
748  * and also the main service loop (seek-configure-spinup-command)
749  */
750
751 /*
752  * disk change.
753  * This routine is responsible for maintaining the FD_DISK_CHANGE flag,
754  * and the last_checked date.
755  *
756  * last_checked is the date of the last check which showed 'no disk change'
757  * FD_DISK_CHANGE is set under two conditions:
758  * 1. The floppy has been changed after some i/o to that floppy already
759  *    took place.
760  * 2. No floppy disk is in the drive. This is done in order to ensure that
761  *    requests are quickly flushed in case there is no disk in the drive. It
762  *    follows that FD_DISK_CHANGE can only be cleared if there is a disk in
763  *    the drive.
764  *
765  * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.
766  * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on
767  *  each seek. If a disk is present, the disk change line should also be
768  *  cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk
769  *  change line is set, this means either that no disk is in the drive, or
770  *  that it has been removed since the last seek.
771  *
772  * This means that we really have a third possibility too:
773  *  The floppy has been changed after the last seek.
774  */
775
776 static int disk_change(int drive)
777 {
778         return UTESTF(FD_DISK_CHANGED);
779 }
780
781 static int set_mode(char mask, char data)
782 {
783         register unsigned char newdor, olddor;
784
785         olddor = FDCS->dor;
786         newdor = (olddor & mask) | data;
787         if (newdor != olddor) {
788                 FDCS->dor = newdor;
789                 fd_outb(newdor, FD_MODE);
790         }
791
792         if (newdor & FLOPPY98_MOTOR_MASK)
793                 floppy_grab_irq_and_dma();
794
795         if (olddor & FLOPPY98_MOTOR_MASK)
796                 floppy_release_irq_and_dma();
797
798         return olddor;
799 }
800
801 static void twaddle(void)
802 {
803         if (DP->select_delay)
804                 return;
805
806         fd_outb(FDCS->dor & 0xf7, FD_MODE);
807         fd_outb(FDCS->dor, FD_MODE);
808         DRS->select_date = jiffies;
809 }
810
811 /* reset all driver information about the current fdc. This is needed after
812  * a reset, and after a raw command. */
813 static void reset_fdc_info(int mode)
814 {
815         int drive;
816
817         FDCS->spec1 = FDCS->spec2 = -1;
818         FDCS->need_configure = 1;
819         FDCS->perp_mode = 1;
820         FDCS->rawcmd = 0;
821         for (drive = 0; drive < N_DRIVE; drive++)
822                 if (FDC(drive) == fdc &&
823                     (mode || UDRS->track != NEED_1_RECAL))
824                         UDRS->track = NEED_2_RECAL;
825 }
826
827 /* selects the fdc and drive, and enables the fdc's input/dma. */
828 static void set_fdc(int drive)
829 {
830         fdc = 0;
831         current_drive = drive;
832         set_mode(~0, 0x10);
833         if (FDCS->rawcmd == 2)
834                 reset_fdc_info(1);
835
836         if (fd_inb(FD98_STATUS) != STATUS_READY)
837                 FDCS->reset = 1;
838 }
839
840 /* locks the driver */
841 static int _lock_fdc(int drive, int interruptible, int line)
842 {
843         if (!usage_count){
844                 printk(KERN_ERR "Trying to lock fdc while usage count=0 at line %d\n", line);
845                 return -1;
846         }
847         if(floppy_grab_irq_and_dma()==-1)
848                 return -EBUSY;
849
850         if (test_and_set_bit(0, &fdc_busy)) {
851                 DECLARE_WAITQUEUE(wait, current);
852                 add_wait_queue(&fdc_wait, &wait);
853
854                 for (;;) {
855                         set_current_state(TASK_INTERRUPTIBLE);
856
857                         if (!test_and_set_bit(0, &fdc_busy))
858                                 break;
859
860                         schedule();
861
862                         if (!NO_SIGNAL) {
863                                 remove_wait_queue(&fdc_wait, &wait);
864                                 return -EINTR;
865                         }
866                 }
867
868                 set_current_state(TASK_RUNNING);
869                 remove_wait_queue(&fdc_wait, &wait);
870         }
871         command_status = FD_COMMAND_NONE;
872
873         reschedule_timeout(drive, "lock fdc", 0);
874         set_fdc(drive);
875         return 0;
876 }
877
878 #define lock_fdc(drive,interruptible) _lock_fdc(drive,interruptible, __LINE__)
879
880 #define LOCK_FDC(drive,interruptible) \
881 if (lock_fdc(drive,interruptible)) return -EINTR;
882
883
884 /* unlocks the driver */
885 static inline void unlock_fdc(void)
886 {
887         raw_cmd = 0;
888         if (!fdc_busy)
889                 DPRINT("FDC access conflict!\n");
890
891         if (do_floppy)
892                 DPRINT("device interrupt still active at FDC release: %p!\n",
893                         do_floppy);
894         command_status = FD_COMMAND_NONE;
895         del_timer(&fd_timeout);
896         cont = NULL;
897         clear_bit(0, &fdc_busy);
898         floppy_release_irq_and_dma();
899         wake_up(&fdc_wait);
900 }
901
902 #ifndef CONFIG_PC9800_MOTOR_OFF /* tomita */
903
904 /* switches the motor off after a given timeout */
905 static void motor_off_callback(unsigned long nr)
906 {
907         printk(KERN_DEBUG "fdc%lu: turn off motor\n", nr);
908 }
909
910 /* schedules motor off */
911 static void floppy_off(unsigned int drive)
912 {
913 }
914
915 #else /* CONFIG_PC9800_MOTOR_OFF */
916
917 /* switches the motor off after a given timeout */
918 static void motor_off_callback(unsigned long fdc)
919 {
920         printk(KERN_DEBUG "fdc%u: turn off motor\n", (unsigned int) fdc);
921
922         fd_outb(0, FD_MODE);    /* MTON = 0 */
923 }
924
925 static struct timer_list motor_off_timer[N_FDC] = {
926         { data: 0, function: motor_off_callback },
927 #if N_FDC > 1
928         { data: 1, function: motor_off_callback },
929 #endif
930 #if N_FDC > 2
931 # error "N_FDC > 2; please fix initializer for motor_off_timer[]"
932 #endif
933 };
934
935 /* schedules motor off */
936 static void floppy_off(unsigned int drive)
937 {
938         unsigned long volatile delta;
939         register int fdc = FDC(drive);
940
941         if (!(FDCS->dor & (0x10 << UNIT(drive))))
942                 return;
943
944         del_timer(motor_off_timer + fdc);
945
946 #if 0
947         /* make spindle stop in a position which minimizes spinup time
948          * next time */
949         if (UDP->rps){
950                 delta = jiffies - UDRS->first_read_date + HZ -
951                         UDP->spindown_offset;
952                 delta = ((delta * UDP->rps) % HZ) / UDP->rps;
953                 motor_off_timer[drive].expires = jiffies + UDP->spindown - delta;
954         }
955 #else
956         if (UDP->rps)
957                 motor_off_timer[drive].expires = jiffies + UDP->spindown;
958 #endif
959
960         add_timer(motor_off_timer + fdc);
961 }
962
963 #endif /* CONFIG_PC9800_MOTOR_OFF */
964
965 /*
966  * cycle through all N_DRIVE floppy drives, for disk change testing.
967  * stopping at current drive. This is done before any long operation, to
968  * be sure to have up to date disk change information.
969  */
970 static void scandrives(void)
971 {
972         int i, drive, saved_drive;
973
974         if (DP->select_delay)
975                 return;
976
977         saved_drive = current_drive;
978         for (i=0; i < N_DRIVE; i++){
979                 drive = (saved_drive + i + 1) % N_DRIVE;
980                 if (UDRS->fd_ref == 0 || UDP->select_delay != 0)
981                         continue; /* skip closed drives */
982                 set_fdc(drive);
983         }
984         set_fdc(saved_drive);
985 }
986
987 static void empty(void)
988 {
989 }
990
991 static DECLARE_WORK(floppy_work, NULL, NULL);
992
993 static void schedule_bh(void (*handler) (void))
994 {
995         PREPARE_WORK(&floppy_work, (void (*)(void *))handler, NULL);
996         schedule_work(&floppy_work);
997 }
998
999 static struct timer_list fd_timer = TIMER_INITIALIZER(NULL, 0, 0);
1000
1001 static void cancel_activity(void)
1002 {
1003         do_floppy = NULL;
1004         PREPARE_WORK(&floppy_work, (void*)(void*)empty, NULL);
1005         del_timer(&fd_timer);
1006 }
1007
1008 /* this function makes sure that the disk stays in the drive during the
1009  * transfer */
1010 static void fd_watchdog(void)
1011 {
1012 #ifdef DCL_DEBUG
1013         if (DP->flags & FD_DEBUG){
1014                 DPRINT("calling disk change from watchdog\n");
1015         }
1016 #endif
1017
1018         if (disk_change(current_drive)){
1019                 DPRINT("disk removed during i/o\n");
1020                 cancel_activity();
1021                 cont->done(0);
1022                 reset_fdc();
1023         } else {
1024                 del_timer(&fd_timer);
1025                 fd_timer.function = (timeout_fn) fd_watchdog;
1026                 fd_timer.expires = jiffies + HZ / 10;
1027                 add_timer(&fd_timer);
1028         }
1029 }
1030
1031 static void main_command_interrupt(void)
1032 {
1033         del_timer(&fd_timer);
1034         cont->interrupt();
1035 }
1036
1037 /* waits for a delay (spinup or select) to pass */
1038 static int fd_wait_for_completion(unsigned long delay, timeout_fn function)
1039 {
1040         if (FDCS->reset){
1041                 reset_fdc(); /* do the reset during sleep to win time
1042                               * if we don't need to sleep, it's a good
1043                               * occasion anyways */
1044                 return 1;
1045         }
1046
1047         if ((signed) (jiffies - delay) < 0){
1048                 del_timer(&fd_timer);
1049                 fd_timer.function = function;
1050                 fd_timer.expires = delay;
1051                 add_timer(&fd_timer);
1052                 return 1;
1053         }
1054         return 0;
1055 }
1056
1057 static spinlock_t floppy_hlt_lock = SPIN_LOCK_UNLOCKED;
1058 static int hlt_disabled;
1059 static void floppy_disable_hlt(void)
1060 {
1061         unsigned long flags;
1062
1063         spin_lock_irqsave(&floppy_hlt_lock, flags);
1064         if (!hlt_disabled) {
1065                 hlt_disabled=1;
1066 #ifdef HAVE_DISABLE_HLT
1067                 disable_hlt();
1068 #endif
1069         }
1070         spin_unlock_irqrestore(&floppy_hlt_lock, flags);
1071 }
1072
1073 static void floppy_enable_hlt(void)
1074 {
1075         unsigned long flags;
1076
1077         spin_lock_irqsave(&floppy_hlt_lock, flags);
1078         if (hlt_disabled){
1079                 hlt_disabled=0;
1080 #ifdef HAVE_DISABLE_HLT
1081                 enable_hlt();
1082 #endif
1083         }
1084         spin_unlock_irqrestore(&floppy_hlt_lock, flags);
1085 }
1086
1087
1088 static void setup_DMA(void)
1089 {
1090         unsigned long f;
1091
1092 #ifdef FLOPPY_SANITY_CHECK
1093         if (raw_cmd->length == 0){
1094                 int i;
1095
1096                 printk("zero dma transfer size:");
1097                 for (i=0; i < raw_cmd->cmd_count; i++)
1098                         printk("%x,", raw_cmd->cmd[i]);
1099                 printk("\n");
1100                 cont->done(0);
1101                 FDCS->reset = 1;
1102                 return;
1103         }
1104         if (((unsigned long) raw_cmd->kernel_data) % 512){
1105                 printk("non aligned address: %p\n", raw_cmd->kernel_data);
1106                 cont->done(0);
1107                 FDCS->reset=1;
1108                 return;
1109         }
1110 #endif
1111         f=claim_dma_lock();
1112         fd_disable_dma();
1113 #ifdef fd_dma_setup
1114         if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length, 
1115                         (raw_cmd->flags & FD_RAW_READ)?
1116                         DMA_MODE_READ : DMA_MODE_WRITE,
1117                         FDCS->address) < 0) {
1118                 release_dma_lock(f);
1119                 cont->done(0);
1120                 FDCS->reset=1;
1121                 return;
1122         }
1123         release_dma_lock(f);
1124 #else   
1125         fd_clear_dma_ff();
1126         fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length);
1127         fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ)?
1128                         DMA_MODE_READ : DMA_MODE_WRITE);
1129         fd_set_dma_addr(raw_cmd->kernel_data);
1130         fd_set_dma_count(raw_cmd->length);
1131         virtual_dma_port = FDCS->address;
1132         fd_enable_dma();
1133         release_dma_lock(f);
1134 #endif
1135         floppy_disable_hlt();
1136 }
1137
1138 static void show_floppy(void);
1139
1140 /* waits until the fdc becomes ready */
1141
1142 #ifdef PC9800_DEBUG_FLOPPY
1143 #define READY_DELAY 10000000
1144 #else
1145 #define READY_DELAY 100000
1146 #endif
1147
1148 static int wait_til_ready(void)
1149 {
1150         int counter, status;
1151         if (FDCS->reset)
1152                 return -1;
1153         for (counter = 0; counter < READY_DELAY; counter++) {
1154                 status = fd_inb(FD98_STATUS);           
1155                 if (status & STATUS_READY)
1156                         return status;
1157         }
1158         if (!initialising) {
1159                 DPRINT("Getstatus times out (%x) on fdc %d\n",
1160                         status, fdc);
1161                 show_floppy();
1162         }
1163         FDCS->reset = 1;
1164         return -1;
1165 }
1166
1167 /* sends a command byte to the fdc */
1168 static int output_byte(char byte)
1169 {
1170         int status;
1171
1172         if ((status = wait_til_ready()) < 0)
1173                 return -1;
1174         if ((status & (STATUS_READY|STATUS_DIR|STATUS_DMA)) == STATUS_READY){
1175                 fd_outb(byte,FD98_DATA);
1176 #ifdef FLOPPY_SANITY_CHECK
1177                 output_log[output_log_pos].data = byte;
1178                 output_log[output_log_pos].status = status;
1179                 output_log[output_log_pos].jiffies = jiffies;
1180                 output_log_pos = (output_log_pos + 1) % OLOGSIZE;
1181 #endif
1182                 return 0;
1183         }
1184         FDCS->reset = 1;
1185         if (!initialising) {
1186                 DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n",
1187                        byte, fdc, status);
1188                 show_floppy();
1189         }
1190         return -1;
1191 }
1192 #define LAST_OUT(x) if (output_byte(x)<0){ reset_fdc();return;}
1193
1194 /* gets the response from the fdc */
1195 static int result(void)
1196 {
1197         int i, status=0;
1198
1199         for(i=0; i < MAX_REPLIES; i++) {
1200                 if ((status = wait_til_ready()) < 0)
1201                         break;
1202                 status &= STATUS_DIR|STATUS_READY|STATUS_BUSY|STATUS_DMA;
1203                 if ((status & ~STATUS_BUSY) == STATUS_READY){
1204 #ifdef FLOPPY_SANITY_CHECK
1205                         resultjiffies = jiffies;
1206                         resultsize = i;
1207 #endif
1208                         return i;
1209                 }
1210                 if (status == (STATUS_DIR|STATUS_READY|STATUS_BUSY))
1211                         reply_buffer[i] = fd_inb(FD98_DATA);
1212                 else
1213                         break;
1214         }
1215         if (!initialising) {
1216                 DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n",
1217                        fdc, status, i);
1218                 show_floppy();
1219         }
1220         FDCS->reset = 1;
1221         return -1;
1222 }
1223
1224 static int fifo_depth = 0xa;
1225 static int no_fifo;
1226
1227 #define NOMINAL_DTR 500
1228
1229 /* Issue a "SPECIFY" command to set the step rate time, head unload time,
1230  * head load time, and DMA disable flag to values needed by floppy.
1231  *
1232  * The value "dtr" is the data transfer rate in Kbps.  It is needed
1233  * to account for the data rate-based scaling done by the 82072 and 82077
1234  * FDC types.  This parameter is ignored for other types of FDCs (i.e.
1235  * 8272a).
1236  *
1237  * Note that changing the data transfer rate has a (probably deleterious)
1238  * effect on the parameters subject to scaling for 82072/82077 FDCs, so
1239  * fdc_specify is called again after each data transfer rate
1240  * change.
1241  *
1242  * srt: 1000 to 16000 in microseconds
1243  * hut: 16 to 240 milliseconds
1244  * hlt: 2 to 254 milliseconds
1245  *
1246  * These values are rounded up to the next highest available delay time.
1247  */
1248 static void fdc_specify(void)
1249 {
1250         output_byte(FD_SPECIFY);
1251         output_byte(FDCS->spec1 = 0xdf);
1252         output_byte(FDCS->spec2 = 0x24);
1253 }
1254
1255 static void tell_sector(void)
1256 {
1257         printk(": track %d, head %d, sector %d, size %d",
1258                R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE);
1259 } /* tell_sector */
1260
1261 static int auto_detect_mode_pc9800(void)
1262 {
1263 #ifdef PC9800_DEBUG_FLOPPY
1264         printk("auto_detect_mode_pc9800: retry_auto_detect=%d\n",
1265                 retry_auto_detect);
1266 #endif
1267         if (retry_auto_detect > 4) {
1268                 retry_auto_detect = 0;     
1269                 return 1;
1270         }
1271
1272         switch ((int)(_floppy - floppy_type)) {
1273                 case 2:
1274                         _floppy = floppy_type + 4;
1275                         break;
1276
1277                 case 4:
1278                 case 6:
1279                         _floppy = floppy_type + 7;
1280                         break;
1281
1282                 case 7:
1283                 case 10:
1284                         _floppy = floppy_type + 2;
1285                         break;
1286
1287                 default:
1288                         _floppy = floppy_type + 7;
1289         }
1290
1291         retry_auto_detect++;
1292         return 0;
1293 }
1294
1295 static void access_mode_change_pc9800(void);
1296
1297 /*
1298  * OK, this error interpreting routine is called after a
1299  * DMA read/write has succeeded
1300  * or failed, so we check the results, and copy any buffers.
1301  * hhb: Added better error reporting.
1302  * ak: Made this into a separate routine.
1303  */
1304 static int interpret_errors(void)
1305 {
1306         char bad;
1307
1308         if (inr!=7) {
1309                 DPRINT("-- FDC reply error");
1310                 FDCS->reset = 1;
1311                 return 1;
1312         }
1313
1314         /* check IC to find cause of interrupt */
1315         switch (ST0 & ST0_INTR) {
1316                 case 0x40:      /* error occurred during command execution */
1317                         if (ST1 & ST1_EOC)
1318                                 return 0; /* occurs with pseudo-DMA */
1319                         bad = 1;
1320                         if (ST1 & ST1_WP) {
1321                                 DPRINT("Drive is write protected\n");
1322                                 CLEARF(FD_DISK_WRITABLE);
1323                                 cont->done(0);
1324                                 bad = 2;
1325                         } else if (ST1 & ST1_ND) {
1326                                 SETF(FD_NEED_TWADDLE);
1327                         } else if (ST1 & ST1_OR) {
1328                                 if (DP->flags & FTD_MSG)
1329                                         DPRINT("Over/Underrun - retrying\n");
1330                                 bad = 0;
1331                         }else if (*errors >= DP->max_errors.reporting){
1332                                 if (ST0 & ST0_ECE) {
1333                                         printk("Recalibrate failed!");
1334                                 } else if (ST2 & ST2_CRC) {
1335                                         printk("data CRC error");
1336                                         tell_sector();
1337                                 } else if (ST1 & ST1_CRC) {
1338                                         printk("CRC error");
1339                                         tell_sector();
1340                                 } else if ((ST1 & (ST1_MAM|ST1_ND)) || (ST2 & ST2_MAM)) {
1341                                         if (auto_detect_mode) {
1342                                                 bad = (char)auto_detect_mode_pc9800();
1343                                                 access_mode_change_pc9800();
1344                                         }
1345
1346                                         if (bad) {
1347                                                 printk("floppy error: MA: _floppy - floppy_type=%d\n", (int)(_floppy - floppy_type));
1348                                                 printk("bad=%d\n", (int)bad);
1349                                                 if (!probing) {
1350                                                         printk("sector not found");
1351                                                         tell_sector();
1352                                                 } else
1353                                                         printk("probe failed...");
1354                                         }
1355                                 } else if (ST2 & ST2_WC) {      /* seek error */
1356                                         printk("wrong cylinder");
1357                                 } else if (ST2 & ST2_BC) {      /* cylinder marked as bad */
1358                                         printk("bad cylinder");
1359                                 } else {
1360                                         printk("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x", ST0, ST1, ST2);
1361                                         tell_sector();
1362                                 }
1363                                 printk("\n");
1364
1365                         }
1366                         if (ST2 & ST2_WC || ST2 & ST2_BC)
1367                                 /* wrong cylinder => recal */
1368                                 DRS->track = NEED_2_RECAL;
1369                         return bad;
1370                 case 0x80: /* invalid command given */
1371                         DPRINT("Invalid FDC command given!\n");
1372                         cont->done(0);
1373                         return 2;
1374                 case 0xc0:
1375                         SETF(FD_DISK_CHANGED);
1376                         SETF(FD_DISK_WRITABLE);
1377                         DPRINT("Abnormal termination caused by polling\n");
1378                         cont->error();
1379                         return 2;
1380                 default: /* (0) Normal command termination */
1381                         auto_detect_mode = 0;
1382                         return 0;
1383         }
1384 }
1385
1386 /*
1387  * This routine is called when everything should be correctly set up
1388  * for the transfer (i.e. floppy motor is on, the correct floppy is
1389  * selected, and the head is sitting on the right track).
1390  */
1391 static void setup_rw_floppy(void)
1392 {
1393         int i,r, flags,dflags;
1394         unsigned long ready_date;
1395         timeout_fn function;
1396
1397         access_mode_change_pc9800();
1398         flags = raw_cmd->flags;
1399         if (flags & (FD_RAW_READ | FD_RAW_WRITE))
1400                 flags |= FD_RAW_INTR;
1401
1402         if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)){
1403                 ready_date = DRS->spinup_date + DP->spinup;
1404                 /* If spinup will take a long time, rerun scandrives
1405                  * again just before spinup completion. Beware that
1406                  * after scandrives, we must again wait for selection.
1407                  */
1408                 if ((signed) (ready_date - jiffies) > DP->select_delay){
1409                         ready_date -= DP->select_delay;
1410                         function = (timeout_fn) floppy_start;
1411                 } else
1412                         function = (timeout_fn) setup_rw_floppy;
1413
1414                 /* wait until the floppy is spinning fast enough */
1415                 if (fd_wait_for_completion(ready_date,function))
1416                         return;
1417         }
1418         dflags = DRS->flags;
1419
1420         if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE))
1421                 setup_DMA();
1422
1423         if (flags & FD_RAW_INTR)
1424                 do_floppy = main_command_interrupt;
1425
1426         r=0;
1427         for (i=0; i< raw_cmd->cmd_count; i++)
1428                 r|=output_byte(raw_cmd->cmd[i]);
1429
1430 #ifdef DEBUGT
1431         debugt("rw_command: ");
1432 #endif
1433         if (r){
1434                 cont->error();
1435                 reset_fdc();
1436                 return;
1437         }
1438
1439         if (!(flags & FD_RAW_INTR)){
1440                 inr = result();
1441                 cont->interrupt();
1442         } else if (flags & FD_RAW_NEED_DISK)
1443                 fd_watchdog();
1444 }
1445
1446 static int blind_seek;
1447
1448 /*
1449  * This is the routine called after every seek (or recalibrate) interrupt
1450  * from the floppy controller.
1451  */
1452 static void seek_interrupt(void)
1453 {
1454 #ifdef DEBUGT
1455         debugt("seek interrupt:");
1456 #endif
1457         if (inr != 2 || (ST0 & 0xF8) != 0x20) {
1458                 DRS->track = NEED_2_RECAL;
1459                 cont->error();
1460                 cont->redo();
1461                 return;
1462         }
1463         if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek){
1464 #ifdef DCL_DEBUG
1465                 if (DP->flags & FD_DEBUG){
1466                         DPRINT("clearing NEWCHANGE flag because of effective seek\n");
1467                         DPRINT("jiffies=%lu\n", jiffies);
1468                 }
1469 #endif
1470                 CLEARF(FD_DISK_NEWCHANGE); /* effective seek */
1471                 CLEARF(FD_DISK_CHANGED); /* effective seek */
1472                 DRS->select_date = jiffies;
1473         }
1474         DRS->track = ST1;
1475         floppy_ready();
1476 }
1477
1478 static void check_wp(void)
1479 {
1480         if (TESTF(FD_VERIFY)) {
1481                 /* check write protection */
1482                 output_byte(FD_GETSTATUS);
1483                 output_byte(UNIT(current_drive));
1484                 if (result() != 1){
1485                         FDCS->reset = 1;
1486                         return;
1487                 }
1488                 CLEARF(FD_VERIFY);
1489                 CLEARF(FD_NEED_TWADDLE);
1490 #ifdef DCL_DEBUG
1491                 if (DP->flags & FD_DEBUG){
1492                         DPRINT("checking whether disk is write protected\n");
1493                         DPRINT("wp=%x\n",ST3 & 0x40);
1494                 }
1495 #endif
1496                 if (!(ST3  & 0x40))
1497                         SETF(FD_DISK_WRITABLE);
1498                 else
1499                         CLEARF(FD_DISK_WRITABLE);
1500         }
1501 }
1502
1503 static void seek_floppy(void)
1504 {
1505         int track;
1506
1507         blind_seek=0;
1508
1509 #ifdef DCL_DEBUG
1510         if (DP->flags & FD_DEBUG){
1511                 DPRINT("calling disk change from seek\n");
1512         }
1513 #endif
1514
1515         if (!TESTF(FD_DISK_NEWCHANGE) &&
1516             disk_change(current_drive) &&
1517             (raw_cmd->flags & FD_RAW_NEED_DISK)){
1518                 /* the media changed flag should be cleared after the seek.
1519                  * If it isn't, this means that there is really no disk in
1520                  * the drive.
1521                  */
1522                 SETF(FD_DISK_CHANGED);
1523                 cont->done(0);
1524                 cont->redo();
1525                 return;
1526         }
1527         if (DRS->track <= NEED_1_RECAL){
1528                 recalibrate_floppy();
1529                 return;
1530         } else if (TESTF(FD_DISK_NEWCHANGE) &&
1531                    (raw_cmd->flags & FD_RAW_NEED_DISK) &&
1532                    (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) {
1533                 /* we seek to clear the media-changed condition. Does anybody
1534                  * know a more elegant way, which works on all drives? */
1535                 if (raw_cmd->track)
1536                         track = raw_cmd->track - 1;
1537                 else {
1538                         if (DP->flags & FD_SILENT_DCL_CLEAR){
1539                                 blind_seek = 1;
1540                                 raw_cmd->flags |= FD_RAW_NEED_SEEK;
1541                         }
1542                         track = 1;
1543                 }
1544         } else {
1545                 check_wp();
1546                 if (raw_cmd->track != DRS->track &&
1547                     (raw_cmd->flags & FD_RAW_NEED_SEEK))
1548                         track = raw_cmd->track;
1549                 else {
1550                         setup_rw_floppy();
1551                         return;
1552                 }
1553         }
1554
1555         do_floppy = seek_interrupt;
1556         output_byte(FD_SEEK);
1557         output_byte(UNIT(current_drive));
1558         LAST_OUT(track);
1559 #ifdef DEBUGT
1560         debugt("seek command:");
1561 #endif
1562 }
1563
1564 static void recal_interrupt(void)
1565 {
1566 #ifdef DEBUGT
1567         debugt("recal interrupt:");
1568 #endif
1569         if (inr !=2)
1570                 FDCS->reset = 1;
1571         else if (ST0 & ST0_ECE) {
1572                 switch(DRS->track){
1573                         case NEED_1_RECAL:
1574 #ifdef DEBUGT
1575                                 debugt("recal interrupt need 1 recal:");
1576 #endif
1577                                 /* after a second recalibrate, we still haven't
1578                                  * reached track 0. Probably no drive. Raise an
1579                                  * error, as failing immediately might upset
1580                                  * computers possessed by the Devil :-) */
1581                                 cont->error();
1582                                 cont->redo();
1583                                 return;
1584                         case NEED_2_RECAL:
1585 #ifdef DEBUGT
1586                                 debugt("recal interrupt need 2 recal:");
1587 #endif
1588                                 /* If we already did a recalibrate,
1589                                  * and we are not at track 0, this
1590                                  * means we have moved. (The only way
1591                                  * not to move at recalibration is to
1592                                  * be already at track 0.) Clear the
1593                                  * new change flag */
1594 #ifdef DCL_DEBUG
1595                                 if (DP->flags & FD_DEBUG){
1596                                         DPRINT("clearing NEWCHANGE flag because of second recalibrate\n");
1597                                 }
1598 #endif
1599
1600                                 CLEARF(FD_DISK_NEWCHANGE);
1601                                 DRS->select_date = jiffies;
1602                                 /* fall through */
1603                         default:
1604 #ifdef DEBUGT
1605                                 debugt("recal interrupt default:");
1606 #endif
1607                                 /* Recalibrate moves the head by at
1608                                  * most 80 steps. If after one
1609                                  * recalibrate we don't have reached
1610                                  * track 0, this might mean that we
1611                                  * started beyond track 80.  Try
1612                                  * again.  */
1613                                 DRS->track = NEED_1_RECAL;
1614                                 break;
1615                 }
1616         } else
1617                 DRS->track = ST1;
1618         floppy_ready();
1619 }
1620
1621 static void print_result(char *message, int inr)
1622 {
1623         int i;
1624
1625         DPRINT("%s ", message);
1626         if (inr >= 0)
1627                 for (i=0; i<inr; i++)
1628                         printk("repl[%d]=%x ", i, reply_buffer[i]);
1629         printk("\n");
1630 }
1631
1632 /* interrupt handler. Note that this can be called externally on the Sparc */
1633 irqreturn_t floppy_interrupt(int irq, void *dev_id, struct pt_regs * regs)
1634 {
1635         void (*handler)(void) = do_floppy;
1636         int do_print;
1637         unsigned long f;
1638
1639         lasthandler = handler;
1640         interruptjiffies = jiffies;
1641
1642         f=claim_dma_lock();
1643         fd_disable_dma();
1644         release_dma_lock(f);
1645
1646         floppy_enable_hlt();
1647         do_floppy = NULL;
1648         if (fdc >= N_FDC || FDCS->address == -1){
1649                 /* we don't even know which FDC is the culprit */
1650                 printk("DOR0=%x\n", fdc_state[0].dor);
1651                 printk("floppy interrupt on bizarre fdc %d\n",fdc);
1652                 printk("handler=%p\n", handler);
1653                 is_alive("bizarre fdc");
1654                 return IRQ_NONE;
1655         }
1656
1657         FDCS->reset = 0;
1658         /* We have to clear the reset flag here, because apparently on boxes
1659          * with level triggered interrupts (PS/2, Sparc, ...), it is needed to
1660          * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the
1661          * emission of the SENSEI's.
1662          * It is OK to emit floppy commands because we are in an interrupt
1663          * handler here, and thus we have to fear no interference of other
1664          * activity.
1665          */
1666
1667         do_print = !handler && print_unex && !initialising;
1668
1669         inr = result();
1670         if (inr && do_print)
1671                 print_result("unexpected interrupt", inr);
1672         if (inr == 0){
1673                 do {
1674                         output_byte(FD_SENSEI);
1675                         inr = result();
1676                         if ((ST0 & ST0_INTR) == 0xC0) {
1677                                 int drive = ST0 & ST0_DS;
1678
1679                                 /* Attention Interrupt. */
1680                                 if (ST0 & ST0_NR) {
1681 #ifdef PC9800_DEBUG_FLOPPY
1682                                         if (do_print)
1683                                                 printk(KERN_DEBUG
1684                                                         "floppy debug: floppy ejected (drive %d)\n",
1685                                                         drive);
1686 #endif
1687                                         USETF(FD_DISK_CHANGED);
1688                                         USETF(FD_VERIFY);
1689                                 } else {
1690 #ifdef PC9800_DEBUG_FLOPPY
1691                                         if (do_print)
1692                                                 printk(KERN_DEBUG
1693                                                         "floppy debug: floppy inserted (drive %d)\n",
1694                                                         drive);
1695 #endif
1696                                 }
1697                         } /* Attention Interrupt */
1698 #ifdef PC9800_DEBUG_FLOPPY
1699                         else {
1700                                 printk(KERN_DEBUG
1701                                         "floppy debug : unknown interrupt\n");
1702                         }
1703 #endif
1704                 } while ((ST0 & 0x83) != UNIT(current_drive) && inr == 2);
1705         }
1706         if (handler) {
1707                 schedule_bh(handler);
1708         } else {
1709 #if 0
1710                 FDCS->reset = 1;
1711 #endif
1712         }
1713         is_alive("normal interrupt end");
1714
1715         /* FIXME! Was it really for us? */
1716         return IRQ_HANDLED;
1717 }
1718
1719 static void recalibrate_floppy(void)
1720 {
1721 #ifdef DEBUGT
1722         debugt("recalibrate floppy:");
1723 #endif
1724         do_floppy = recal_interrupt;
1725         output_byte(FD_RECALIBRATE);
1726         LAST_OUT(UNIT(current_drive));
1727 }
1728
1729 /*
1730  * Must do 4 FD_SENSEIs after reset because of ``drive polling''.
1731  */
1732 static void reset_interrupt(void)
1733 {
1734 #ifdef PC9800_DEBUG_FLOPPY
1735         printk("floppy debug: reset interrupt\n");
1736 #endif
1737 #ifdef DEBUGT
1738         debugt("reset interrupt:");
1739 #endif
1740         result();               /* get the status ready for set_fdc */
1741         if (FDCS->reset) {
1742                 printk("reset set in interrupt, calling %p\n", cont->error);
1743                 cont->error(); /* a reset just after a reset. BAD! */
1744         }
1745         cont->redo();
1746 }
1747
1748 /*
1749  * reset is done by pulling bit 2 of DOR low for a while (old FDCs),
1750  * or by setting the self clearing bit 7 of STATUS (newer FDCs)
1751  */
1752 static void reset_fdc(void)
1753 {
1754         unsigned long flags;
1755
1756 #ifdef PC9800_DEBUG_FLOPPY
1757         printk("floppy debug: reset_fdc\n");
1758 #endif
1759
1760         do_floppy = reset_interrupt;
1761         FDCS->reset = 0;
1762         reset_fdc_info(0);
1763
1764         /* Pseudo-DMA may intercept 'reset finished' interrupt.  */
1765         /* Irrelevant for systems with true DMA (i386).          */
1766
1767         flags=claim_dma_lock();
1768         fd_disable_dma();
1769         release_dma_lock(flags);
1770
1771         fd_outb(FDCS->dor | 0x80, FD_MODE);
1772         udelay(FD_RESET_DELAY);
1773         fd_outb(FDCS->dor, FD_MODE);
1774         udelay(FD_AFTER_RESET_DELAY);
1775 }
1776
1777 static void show_floppy(void)
1778 {
1779         int i;
1780
1781         printk("\n");
1782         printk("floppy driver state\n");
1783         printk("-------------------\n");
1784         printk("now=%lu last interrupt=%lu diff=%lu last called handler=%p\n",
1785                jiffies, interruptjiffies, jiffies-interruptjiffies, lasthandler);
1786
1787
1788 #ifdef FLOPPY_SANITY_CHECK
1789         printk("timeout_message=%s\n", timeout_message);
1790         printk("last output bytes:\n");
1791         for (i=0; i < OLOGSIZE; i++)
1792                 printk("%2x %2x %lu\n",
1793                        output_log[(i+output_log_pos) % OLOGSIZE].data,
1794                        output_log[(i+output_log_pos) % OLOGSIZE].status,
1795                        output_log[(i+output_log_pos) % OLOGSIZE].jiffies);
1796         printk("last result at %lu\n", resultjiffies);
1797         printk("last redo_fd_request at %lu\n", lastredo);
1798         for (i=0; i<resultsize; i++){
1799                 printk("%2x ", reply_buffer[i]);
1800         }
1801         printk("\n");
1802 #endif
1803
1804         printk("status=%x\n", fd_inb(FD98_STATUS));
1805         printk("fdc_busy=%lu\n", fdc_busy);
1806         if (do_floppy)
1807                 printk("do_floppy=%p\n", do_floppy);
1808         if (floppy_work.pending)
1809                 printk("floppy_work.func=%p\n", floppy_work.func);
1810         if (timer_pending(&fd_timer))
1811                 printk("fd_timer.function=%p\n", fd_timer.function);
1812         if (timer_pending(&fd_timeout)){
1813                 printk("timer_function=%p\n",fd_timeout.function);
1814                 printk("expires=%lu\n",fd_timeout.expires-jiffies);
1815                 printk("now=%lu\n",jiffies);
1816         }
1817         printk("cont=%p\n", cont);
1818         printk("current_req=%p\n", current_req);
1819         printk("command_status=%d\n", command_status);
1820         printk("\n");
1821 }
1822
1823 static void floppy_shutdown(unsigned long data)
1824 {
1825         unsigned long flags;
1826         
1827         if (!initialising)
1828                 show_floppy();
1829         cancel_activity();
1830
1831         floppy_enable_hlt();
1832         
1833         flags=claim_dma_lock();
1834         fd_disable_dma();
1835         release_dma_lock(flags);
1836         
1837         /* avoid dma going to a random drive after shutdown */
1838
1839         if (!initialising)
1840                 DPRINT("floppy timeout called\n");
1841         FDCS->reset = 1;
1842         if (cont){
1843                 cont->done(0);
1844                 cont->redo(); /* this will recall reset when needed */
1845         } else {
1846                 printk("no cont in shutdown!\n");
1847                 process_fd_request();
1848         }
1849         is_alive("floppy shutdown");
1850 }
1851 /*typedef void (*timeout_fn)(unsigned long);*/
1852
1853 static void access_mode_change_pc9800(void)
1854 {
1855         static int access_mode, mode_change_now, old_mode, new_set = 1;
1856 #ifdef PC9800_DEBUG_FLOPPY2
1857         printk("enter access_mode_change\n");
1858 #endif
1859         access_mode = mode_change_now = 0;
1860         if (DP->cmos==4) {
1861                 switch ((int)(_floppy - &floppy_type[0])) {
1862                 case 1:
1863                 case 2:
1864                         new_set = 1;
1865                         access_mode = 2;
1866                         break;
1867
1868                 case 4:
1869                 case 6:
1870                         new_set = 1;
1871                         access_mode = 3;
1872                         break;
1873
1874                 case 7:
1875                 case 10:
1876                         new_set = 1;
1877                         access_mode = 1;
1878                         break;
1879
1880                 default:
1881                         access_mode = 1;
1882                         break;
1883                 }
1884
1885                 old_mode = fd_inb(FD_MODE_CHANGE) & 3;
1886
1887                 switch (access_mode) {
1888                 case 1:
1889                         if ((old_mode & 2) == 0) {
1890                                 fd_outb(old_mode | 2, FD_MODE_CHANGE);
1891                                 mode_change_now = 1;
1892                         } else {
1893                                 fd_outb(current_drive << 5, FD_EMODE_CHANGE);
1894                                 if (fd_inb(FD_EMODE_CHANGE) == 0xff)
1895                                         return;
1896                         }
1897
1898                         fd_outb((current_drive << 5) | 0x11, FD_EMODE_CHANGE);
1899                         mode_change_now = 1;
1900                         break;
1901
1902                 case 2:
1903                         if ((old_mode & 2) == 0) {
1904                                 fd_outb(old_mode | 2, FD_MODE_CHANGE);
1905                                 mode_change_now = 1;
1906                         } else {
1907                                 fd_outb(current_drive << 5, FD_EMODE_CHANGE);
1908                                 if ((fd_inb(FD_EMODE_CHANGE) & 1) == 0)
1909                                         return;
1910                                 fd_outb((current_drive << 5) | 0x10, FD_EMODE_CHANGE);
1911                                 mode_change_now = 1;
1912                         }
1913
1914                         break;
1915
1916                 case 3:
1917                         if ((old_mode & 2) == 0)
1918                                 return;
1919                         fd_outb(current_drive << 5, FD_EMODE_CHANGE);
1920                         if (fd_inb(FD_EMODE_CHANGE) & 1)
1921                                 fd_outb((current_drive << 5) | 0x10, FD_EMODE_CHANGE);
1922                         fd_outb(old_mode & 0xfd, FD_MODE_CHANGE);
1923                         mode_change_now = 1;
1924                         break;
1925
1926                 default:
1927                         break;
1928                 }
1929         } else {
1930                 switch ((int)(_floppy - &floppy_type[0])) {
1931                 case 1:
1932                 case 2:
1933                         new_set = 1;
1934                         access_mode = 2;
1935                         break;
1936
1937                 case 4:
1938                 case 6:
1939                         new_set = 1;
1940                         access_mode = 3;
1941                         break;
1942
1943                 default:
1944                         switch (DP->cmos) {
1945                         case 2:
1946                                 access_mode = 2;
1947                                 break;
1948
1949                         case 3:
1950                                 access_mode = 3;
1951                                 break;
1952
1953                         default:
1954                                 break;
1955                         }
1956
1957                         break;
1958                 }
1959
1960                 old_mode = fd_inb(FD_MODE_CHANGE) & 3;
1961
1962                 switch (access_mode) {
1963                 case 2:
1964                         if ((old_mode & 2) == 0) {
1965                                 fd_outb(old_mode | 2, FD_MODE_CHANGE);
1966                                 mode_change_now = 1;
1967                         }
1968
1969                         break;
1970
1971                 case 3:
1972                         if (old_mode & 2) {
1973                                 fd_outb(old_mode & 0xfd, FD_MODE_CHANGE);
1974                                 mode_change_now = 1;
1975                         }
1976
1977                         break;
1978
1979                 default:
1980                         break;
1981                 }
1982         }
1983 #ifdef PC9800_DEBUG_FLOPPY2
1984         printk("floppy debug: DP->cmos=%d\n", DP->cmos);
1985         printk("floppy debug: mode_change_now=%d\n", mode_change_now);
1986         printk("floppy debug: access_mode=%d\n", access_mode);
1987         printk("floppy debug: old_mode=%d\n", old_mode);
1988         printk("floppy debug: _floppy - &floppy_type[0]=%d\n", (int)(_floppy - &floppy_type[0]));
1989 #endif /* PC9800_DEBUG_FLOPPY2 */
1990         if(mode_change_now)
1991                 reset_fdc();
1992 }
1993
1994 /* start motor, check media-changed condition and write protection */
1995 static int start_motor(void (*function)(void) )
1996 {
1997         access_mode_change_pc9800();
1998         set_mode(~0, 0x8);
1999
2000         /* wait_for_completion also schedules reset if needed. */
2001         return(fd_wait_for_completion(DRS->select_date+DP->select_delay,
2002                                    (timeout_fn) function));
2003 }
2004
2005 static void floppy_ready(void)
2006 {
2007         CHECK_RESET;
2008         if (start_motor(floppy_ready)) return;
2009
2010 #ifdef DCL_DEBUG
2011         if (DP->flags & FD_DEBUG){
2012                 DPRINT("calling disk change from floppy_ready\n");
2013         }
2014 #endif
2015         if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) &&
2016            disk_change(current_drive) &&
2017            !DP->select_delay)
2018                 twaddle(); /* this clears the dcl on certain drive/controller
2019                             * combinations */
2020
2021 #ifdef fd_chose_dma_mode
2022         if ((raw_cmd->flags & FD_RAW_READ) || 
2023             (raw_cmd->flags & FD_RAW_WRITE))
2024         {
2025                 unsigned long flags = claim_dma_lock();
2026                 fd_chose_dma_mode(raw_cmd->kernel_data,
2027                                   raw_cmd->length);
2028                 release_dma_lock(flags);
2029         }
2030 #endif
2031
2032 #if 0
2033         access_mode_change_pc9800();
2034 #endif
2035         if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)){
2036                 fdc_specify(); /* must be done here because of hut, hlt ... */
2037                 seek_floppy();
2038         } else {
2039                 if ((raw_cmd->flags & FD_RAW_READ) || 
2040                     (raw_cmd->flags & FD_RAW_WRITE))
2041                         fdc_specify();
2042                 setup_rw_floppy();
2043         }
2044 }
2045
2046 static void floppy_start(void)
2047 {
2048         reschedule_timeout(current_reqD, "floppy start", 0);
2049
2050         scandrives();
2051 #ifdef DCL_DEBUG
2052         if (DP->flags & FD_DEBUG){
2053                 DPRINT("setting NEWCHANGE in floppy_start\n");
2054         }
2055 #endif
2056         SETF(FD_DISK_NEWCHANGE);
2057         floppy_ready();
2058 }
2059
2060 /*
2061  * ========================================================================
2062  * here ends the bottom half. Exported routines are:
2063  * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc,
2064  * start_motor, reset_fdc, reset_fdc_info, interpret_errors.
2065  * Initialization also uses output_byte, result, set_dor, floppy_interrupt
2066  * and set_dor.
2067  * ========================================================================
2068  */
2069 /*
2070  * General purpose continuations.
2071  * ==============================
2072  */
2073
2074 static void do_wakeup(void)
2075 {
2076         reschedule_timeout(MAXTIMEOUT, "do wakeup", 0);
2077         cont = 0;
2078         command_status += 2;
2079         wake_up(&command_done);
2080 }
2081
2082 static struct cont_t wakeup_cont={
2083         empty,
2084         do_wakeup,
2085         empty,
2086         (done_f)empty
2087 };
2088
2089
2090 static struct cont_t intr_cont={
2091         empty,
2092         process_fd_request,
2093         empty,
2094         (done_f) empty
2095 };
2096
2097 static int wait_til_done(void (*handler)(void), int interruptible)
2098 {
2099         int ret;
2100
2101         schedule_bh((void *)(void *)handler);
2102
2103         if (command_status < 2 && NO_SIGNAL) {
2104                 DECLARE_WAITQUEUE(wait, current);
2105
2106                 add_wait_queue(&command_done, &wait);
2107                 for (;;) {
2108                         set_current_state(interruptible?
2109                                           TASK_INTERRUPTIBLE:
2110                                           TASK_UNINTERRUPTIBLE);
2111
2112                         if (command_status >= 2 || !NO_SIGNAL)
2113                                 break;
2114
2115                         is_alive("wait_til_done");
2116
2117                         schedule();
2118                 }
2119
2120                 set_current_state(TASK_RUNNING);
2121                 remove_wait_queue(&command_done, &wait);
2122         }
2123
2124         if (command_status < 2){
2125                 cancel_activity();
2126                 cont = &intr_cont;
2127                 reset_fdc();
2128                 return -EINTR;
2129         }
2130
2131 #ifdef PC9800_DEBUG_FLOPPY
2132         if (command_status != FD_COMMAND_OKAY)
2133                 printk("floppy check: wait_til_done out:%d\n", command_status);
2134 #endif
2135         if (FDCS->reset)
2136                 command_status = FD_COMMAND_ERROR;
2137         if (command_status == FD_COMMAND_OKAY)
2138                 ret=0;
2139         else
2140                 ret=-EIO;
2141         command_status = FD_COMMAND_NONE;
2142         return ret;
2143 }
2144
2145 static void generic_done(int result)
2146 {
2147         command_status = result;
2148         cont = &wakeup_cont;
2149 }
2150
2151 static void generic_success(void)
2152 {
2153         cont->done(1);
2154 }
2155
2156 static void generic_failure(void)
2157 {
2158         cont->done(0);
2159 }
2160
2161 static void success_and_wakeup(void)
2162 {
2163         generic_success();
2164         cont->redo();
2165 }
2166
2167
2168 /*
2169  * formatting and rw support.
2170  * ==========================
2171  */
2172
2173 static int next_valid_format(void)
2174 {
2175         int probed_format;
2176
2177         probed_format = DRS->probed_format;
2178         while(1){
2179                 if (probed_format >= 8 ||
2180                      !DP->autodetect[probed_format]){
2181                         DRS->probed_format = 0;
2182                         return 1;
2183                 }
2184                 if (floppy_type[DP->autodetect[probed_format]].sect){
2185                         DRS->probed_format = probed_format;
2186                         return 0;
2187                 }
2188                 probed_format++;
2189         }
2190 }
2191
2192 static void bad_flp_intr(void)
2193 {
2194         if (probing){
2195                 DRS->probed_format++;
2196                 if (!next_valid_format())
2197                         return;
2198         }
2199         (*errors)++;
2200         INFBOUND(DRWE->badness, *errors);
2201         if (*errors > DP->max_errors.abort)
2202                 cont->done(0);
2203         if (*errors > DP->max_errors.reset)
2204                 FDCS->reset = 1;
2205         else if (*errors > DP->max_errors.recal)
2206                 DRS->track = NEED_2_RECAL;
2207 }
2208
2209 static void set_floppy(int drive)
2210 {
2211         int type = ITYPE(UDRS->fd_device);
2212         if (type) {
2213                 auto_detect_mode = 0;
2214                 _floppy = floppy_type + type;
2215         } else if (auto_detect_mode == 0) {
2216                 auto_detect_mode = 1;
2217                 retry_auto_detect = 0;
2218                 _floppy = current_type[drive];
2219         }
2220 #ifdef PC9800_DEBUG_FLOPPY2
2221         printk("set_floppy: set floppy type=%d\n", (int)(_floppy - floppy_type));
2222 #endif
2223 }
2224
2225 /*
2226  * formatting support.
2227  * ===================
2228  */
2229 static void format_interrupt(void)
2230 {
2231         switch (interpret_errors()){
2232                 case 1:
2233                         cont->error();
2234                 case 2:
2235                         break;
2236                 case 0:
2237                         cont->done(1);
2238         }
2239         cont->redo();
2240 }
2241
2242 #define CODE2SIZE (ssize = ((1 << SIZECODE) + 3) >> 2)
2243 #define FM_MODE(x,y) ((y) & ~(((x)->rate & 0x80) >>1))
2244 #define CT(x) ((x) | 0xc0)
2245 static void setup_format_params(int track)
2246 {
2247         struct fparm {
2248                 unsigned char track,head,sect,size;
2249         } *here = (struct fparm *)floppy_track_buffer;
2250         int il,n;
2251         int count,head_shift,track_shift;
2252
2253         raw_cmd = &default_raw_cmd;
2254         raw_cmd->track = track;
2255
2256         raw_cmd->flags = FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |
2257                 FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK;
2258         raw_cmd->rate = _floppy->rate & 0x43;
2259         raw_cmd->cmd_count = NR_F;
2260         COMMAND = FM_MODE(_floppy,FD_FORMAT);
2261         DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy,format_req.head);
2262         F_SIZECODE = FD_SIZECODE(_floppy);
2263         F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;
2264         F_GAP = _floppy->fmt_gap;
2265         F_FILL = FD_FILL_BYTE;
2266
2267         raw_cmd->kernel_data = floppy_track_buffer;
2268         raw_cmd->length = 4 * F_SECT_PER_TRACK;
2269
2270         /* allow for about 30ms for data transport per track */
2271         head_shift  = (F_SECT_PER_TRACK + 5) / 6;
2272
2273         /* a ``cylinder'' is two tracks plus a little stepping time */
2274         track_shift = 2 * head_shift + 3;
2275
2276         /* position of logical sector 1 on this track */
2277         n = (track_shift * format_req.track + head_shift * format_req.head)
2278                 % F_SECT_PER_TRACK;
2279
2280         /* determine interleave */
2281         il = 1;
2282         if (_floppy->fmt_gap < 0x22)
2283                 il++;
2284
2285         /* initialize field */
2286         for (count = 0; count < F_SECT_PER_TRACK; ++count) {
2287                 here[count].track = format_req.track;
2288                 here[count].head = format_req.head;
2289                 here[count].sect = 0;
2290                 here[count].size = F_SIZECODE;
2291         }
2292         /* place logical sectors */
2293         for (count = 1; count <= F_SECT_PER_TRACK; ++count) {
2294                 here[n].sect = count;
2295                 n = (n+il) % F_SECT_PER_TRACK;
2296                 if (here[n].sect) { /* sector busy, find next free sector */
2297                         ++n;
2298                         if (n>= F_SECT_PER_TRACK) {
2299                                 n-=F_SECT_PER_TRACK;
2300                                 while (here[n].sect) ++n;
2301                         }
2302                 }
2303         }
2304 }
2305
2306 static void redo_format(void)
2307 {
2308         buffer_track = -1;
2309         setup_format_params(format_req.track << STRETCH(_floppy));
2310         floppy_start();
2311 #ifdef DEBUGT
2312         debugt("queue format request");
2313 #endif
2314 }
2315
2316 static struct cont_t format_cont={
2317         format_interrupt,
2318         redo_format,
2319         bad_flp_intr,
2320         generic_done };
2321
2322 static int do_format(int drive, struct format_descr *tmp_format_req)
2323 {
2324         int ret;
2325
2326         LOCK_FDC(drive,1);
2327         set_floppy(drive);
2328         if (!_floppy ||
2329             _floppy->track > DP->tracks ||
2330             tmp_format_req->track >= _floppy->track ||
2331             tmp_format_req->head >= _floppy->head ||
2332             (_floppy->sect << 2) % (1 <<  FD_SIZECODE(_floppy)) ||
2333             !_floppy->fmt_gap) {
2334                 process_fd_request();
2335                 return -EINVAL;
2336         }
2337         format_req = *tmp_format_req;
2338         format_errors = 0;
2339         cont = &format_cont;
2340         errors = &format_errors;
2341         IWAIT(redo_format);
2342         process_fd_request();
2343         return ret;
2344 }
2345
2346 /*
2347  * Buffer read/write and support
2348  * =============================
2349  */
2350
2351 static void floppy_end_request(struct request *req, int uptodate)
2352 {
2353         if (end_that_request_first(req, uptodate, current_count_sectors))
2354                 return;
2355         add_disk_randomness(req->rq_disk);
2356         floppy_off((long)req->rq_disk->private_data);
2357         blkdev_dequeue_request(req);
2358         end_that_request_last(req);
2359
2360         /* We're done with the request */
2361         current_req = NULL;
2362 }
2363
2364
2365 /* new request_done. Can handle physical sectors which are smaller than a
2366  * logical buffer */
2367 static void request_done(int uptodate)
2368 {
2369         struct request_queue *q = floppy_queue;
2370         struct request *req = current_req;
2371         unsigned long flags;
2372         int block;
2373
2374         probing = 0;
2375         reschedule_timeout(MAXTIMEOUT, "request done %d", uptodate);
2376
2377         if (!req) {
2378                 printk("floppy.c: no request in request_done\n");
2379                 return;
2380         }
2381
2382         if (uptodate){
2383                 /* maintain values for invalidation on geometry
2384                  * change */
2385                 block = current_count_sectors + req->sector;
2386                 INFBOUND(DRS->maxblock, block);
2387                 if (block > _floppy->sect)
2388                         DRS->maxtrack = 1;
2389
2390                 /* unlock chained buffers */
2391                 spin_lock_irqsave(q->queue_lock, flags);
2392                 floppy_end_request(req, 1);
2393                 spin_unlock_irqrestore(q->queue_lock, flags);
2394         } else {
2395                 if (rq_data_dir(req) == WRITE) {
2396                         /* record write error information */
2397                         DRWE->write_errors++;
2398                         if (DRWE->write_errors == 1) {
2399                                 DRWE->first_error_sector = req->sector;
2400                                 DRWE->first_error_generation = DRS->generation;
2401                         }
2402                         DRWE->last_error_sector = req->sector;
2403                         DRWE->last_error_generation = DRS->generation;
2404                 }
2405                 spin_lock_irqsave(q->queue_lock, flags);
2406                 floppy_end_request(req, 0);
2407                 spin_unlock_irqrestore(q->queue_lock, flags);
2408         }
2409 }
2410
2411 /* Interrupt handler evaluating the result of the r/w operation */
2412 static void rw_interrupt(void)
2413 {
2414         int nr_sectors, ssize, eoc, heads;
2415
2416         if (R_HEAD >= 2) {
2417             /* some Toshiba floppy controllers occasionnally seem to
2418              * return bogus interrupts after read/write operations, which
2419              * can be recognized by a bad head number (>= 2) */
2420              return;
2421         }  
2422
2423         if (!DRS->first_read_date)
2424                 DRS->first_read_date = jiffies;
2425
2426         nr_sectors = 0;
2427         CODE2SIZE;
2428
2429         if (ST1 & ST1_EOC)
2430                 eoc = 1;
2431         else
2432                 eoc = 0;
2433
2434         if (COMMAND & 0x80)
2435                 heads = 2;
2436         else
2437                 heads = 1;
2438
2439         nr_sectors = (((R_TRACK-TRACK) * heads +
2440                                    R_HEAD-HEAD) * SECT_PER_TRACK +
2441                                    R_SECTOR-SECTOR + eoc) << SIZECODE >> 2;
2442
2443 #ifdef FLOPPY_SANITY_CHECK
2444         if (nr_sectors / ssize > 
2445                 (in_sector_offset + current_count_sectors + ssize - 1) / ssize) {
2446                 DPRINT("long rw: %x instead of %lx\n",
2447                         nr_sectors, current_count_sectors);
2448                 printk("rs=%d s=%d\n", R_SECTOR, SECTOR);
2449                 printk("rh=%d h=%d\n", R_HEAD, HEAD);
2450                 printk("rt=%d t=%d\n", R_TRACK, TRACK);
2451                 printk("heads=%d eoc=%d\n", heads, eoc);
2452                 printk("spt=%d st=%d ss=%d\n", SECT_PER_TRACK,
2453                        fsector_t, ssize);
2454                 printk("in_sector_offset=%d\n", in_sector_offset);
2455         }
2456 #endif
2457
2458         nr_sectors -= in_sector_offset;
2459         INFBOUND(nr_sectors,0);
2460         SUPBOUND(current_count_sectors, nr_sectors);
2461
2462         switch (interpret_errors()){
2463                 case 2:
2464                         cont->redo();
2465                         return;
2466                 case 1:
2467                         if (!current_count_sectors){
2468                                 cont->error();
2469                                 cont->redo();
2470                                 return;
2471                         }
2472                         break;
2473                 case 0:
2474                         if (!current_count_sectors){
2475                                 cont->redo();
2476                                 return;
2477                         }
2478                         current_type[current_drive] = _floppy;
2479                         floppy_sizes[TOMINOR(current_drive) ]= _floppy->size;
2480                         break;
2481         }
2482
2483         if (probing) {
2484                 if (DP->flags & FTD_MSG)
2485                         DPRINT("Auto-detected floppy type %s in fd%d\n",
2486                                 _floppy->name,current_drive);
2487                 current_type[current_drive] = _floppy;
2488                 floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
2489                 probing = 0;
2490         }
2491
2492         if (CT(COMMAND) != FD_READ || 
2493              raw_cmd->kernel_data == current_req->buffer){
2494                 /* transfer directly from buffer */
2495                 cont->done(1);
2496         } else if (CT(COMMAND) == FD_READ){
2497                 buffer_track = raw_cmd->track;
2498                 buffer_drive = current_drive;
2499                 INFBOUND(buffer_max, nr_sectors + fsector_t);
2500         }
2501         cont->redo();
2502 }
2503
2504 /* Compute maximal contiguous buffer size. */
2505 static int buffer_chain_size(void)
2506 {
2507         struct bio *bio;
2508         struct bio_vec *bv;
2509         int size, i;
2510         char *base;
2511
2512         base = bio_data(current_req->bio);
2513         size = 0;
2514
2515         rq_for_each_bio(bio, current_req) {
2516                 bio_for_each_segment(bv, bio, i) {
2517                         if (page_address(bv->bv_page) + bv->bv_offset != base + size)
2518                                 break;
2519
2520                         size += bv->bv_len;
2521                 }
2522         }
2523
2524         return size >> 9;
2525 }
2526
2527 /* Compute the maximal transfer size */
2528 static int transfer_size(int ssize, int max_sector, int max_size)
2529 {
2530         SUPBOUND(max_sector, fsector_t + max_size);
2531
2532         /* alignment */
2533         max_sector -= (max_sector % _floppy->sect) % ssize;
2534
2535         /* transfer size, beginning not aligned */
2536         current_count_sectors = max_sector - fsector_t ;
2537
2538         return max_sector;
2539 }
2540
2541 /*
2542  * Move data from/to the track buffer to/from the buffer cache.
2543  */
2544 static void copy_buffer(int ssize, int max_sector, int max_sector_2)
2545 {
2546         int remaining; /* number of transferred 512-byte sectors */
2547         struct bio_vec *bv;
2548         struct bio *bio;
2549         char *buffer, *dma_buffer;
2550         int size, i;
2551
2552         max_sector = transfer_size(ssize,
2553                                    minimum(max_sector, max_sector_2),
2554                                    current_req->nr_sectors);
2555
2556         if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&
2557             buffer_max > fsector_t + current_req->nr_sectors)
2558                 current_count_sectors = minimum(buffer_max - fsector_t,
2559                                                 current_req->nr_sectors);
2560
2561         remaining = current_count_sectors << 9;
2562 #ifdef FLOPPY_SANITY_CHECK
2563         if ((remaining >> 9) > current_req->nr_sectors  &&
2564             CT(COMMAND) == FD_WRITE){
2565                 DPRINT("in copy buffer\n");
2566                 printk("current_count_sectors=%ld\n", current_count_sectors);
2567                 printk("remaining=%d\n", remaining >> 9);
2568                 printk("current_req->nr_sectors=%ld\n",current_req->nr_sectors);
2569                 printk("current_req->current_nr_sectors=%u\n",
2570                        current_req->current_nr_sectors);
2571                 printk("max_sector=%d\n", max_sector);
2572                 printk("ssize=%d\n", ssize);
2573         }
2574 #endif
2575
2576         buffer_max = maximum(max_sector, buffer_max);
2577
2578         dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9);
2579
2580         size = current_req->current_nr_sectors << 9;
2581
2582         rq_for_each_bio(bio, current_req) {
2583                 bio_for_each_segment(bv, bio, i) {
2584                         if (!remaining)
2585                                 break;
2586
2587                         size = bv->bv_len;
2588                         SUPBOUND(size, remaining);
2589
2590                         buffer = page_address(bv->bv_page) + bv->bv_offset;
2591 #ifdef FLOPPY_SANITY_CHECK
2592                 if (dma_buffer + size >
2593                     floppy_track_buffer + (max_buffer_sectors << 10) ||
2594                     dma_buffer < floppy_track_buffer){
2595                         DPRINT("buffer overrun in copy buffer %d\n",
2596                                 (int) ((floppy_track_buffer - dma_buffer) >>9));
2597                         printk("fsector_t=%d buffer_min=%d\n",
2598                                fsector_t, buffer_min);
2599                         printk("current_count_sectors=%ld\n",
2600                                current_count_sectors);
2601                         if (CT(COMMAND) == FD_READ)
2602                                 printk("read\n");
2603                         if (CT(COMMAND) == FD_WRITE)
2604                                 printk("write\n");
2605                         break;
2606                 }
2607                 if (((unsigned long)buffer) % 512)
2608                         DPRINT("%p buffer not aligned\n", buffer);
2609 #endif
2610                         if (CT(COMMAND) == FD_READ)
2611                                 memcpy(buffer, dma_buffer, size);
2612                         else
2613                                 memcpy(dma_buffer, buffer, size);
2614
2615                         remaining -= size;
2616                         dma_buffer += size;
2617                 }
2618         }
2619 #ifdef FLOPPY_SANITY_CHECK
2620         if (remaining){
2621                 if (remaining > 0)
2622                         max_sector -= remaining >> 9;
2623                 DPRINT("weirdness: remaining %d\n", remaining>>9);
2624         }
2625 #endif
2626 }
2627
2628 #if 0
2629 static inline int check_dma_crossing(char *start, 
2630                                      unsigned long length, char *message)
2631 {
2632         if (CROSS_64KB(start, length)) {
2633                 printk("DMA xfer crosses 64KB boundary in %s %p-%p\n", 
2634                        message, start, start+length);
2635                 return 1;
2636         } else
2637                 return 0;
2638 }
2639 #endif
2640
2641 /* work around a bug in pseudo DMA
2642  * (on some FDCs) pseudo DMA does not stop when the CPU stops
2643  * sending data.  Hence we need a different way to signal the
2644  * transfer length:  We use SECT_PER_TRACK.  Unfortunately, this
2645  * does not work with MT, hence we can only transfer one head at
2646  * a time
2647  */
2648 static void virtualdmabug_workaround(void)
2649 {
2650         int hard_sectors, end_sector;
2651
2652         if(CT(COMMAND) == FD_WRITE) {
2653                 COMMAND &= ~0x80; /* switch off multiple track mode */
2654
2655                 hard_sectors = raw_cmd->length >> (7 + SIZECODE);
2656                 end_sector = SECTOR + hard_sectors - 1;
2657 #ifdef FLOPPY_SANITY_CHECK
2658                 if(end_sector > SECT_PER_TRACK) {
2659                         printk("too many sectors %d > %d\n",
2660                                end_sector, SECT_PER_TRACK);
2661                         return;
2662                 }
2663 #endif
2664                 SECT_PER_TRACK = end_sector; /* make sure SECT_PER_TRACK points
2665                                               * to end of transfer */
2666         }
2667 }
2668
2669 /*
2670  * Formulate a read/write request.
2671  * this routine decides where to load the data (directly to buffer, or to
2672  * tmp floppy area), how much data to load (the size of the buffer, the whole
2673  * track, or a single sector)
2674  * All floppy_track_buffer handling goes in here. If we ever add track buffer
2675  * allocation on the fly, it should be done here. No other part should need
2676  * modification.
2677  */
2678
2679 static int make_raw_rw_request(void)
2680 {
2681         int aligned_sector_t;
2682         int max_sector, max_size, tracksize, ssize;
2683
2684         if(max_buffer_sectors == 0) {
2685                 printk("VFS: Block I/O scheduled on unopened device\n");
2686                 return 0;
2687         }
2688
2689         set_fdc((long)current_req->rq_disk->private_data);
2690
2691         raw_cmd = &default_raw_cmd;
2692         raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_DISK |
2693                 FD_RAW_NEED_SEEK;
2694         raw_cmd->cmd_count = NR_RW;
2695         if (rq_data_dir(current_req) == READ) {
2696                 raw_cmd->flags |= FD_RAW_READ;
2697                 COMMAND = FM_MODE(_floppy,FD_READ);
2698         } else if (rq_data_dir(current_req) == WRITE){
2699                 raw_cmd->flags |= FD_RAW_WRITE;
2700                 COMMAND = FM_MODE(_floppy,FD_WRITE);
2701         } else {
2702                 DPRINT("make_raw_rw_request: unknown command\n");
2703                 return 0;
2704         }
2705
2706         max_sector = _floppy->sect * _floppy->head;
2707
2708         TRACK = (int)current_req->sector / max_sector;
2709         fsector_t = (int)current_req->sector % max_sector;
2710         if (_floppy->track && TRACK >= _floppy->track) {
2711                 if (current_req->current_nr_sectors & 1) {
2712                         current_count_sectors = 1;
2713                         return 1;
2714                 } else
2715                         return 0;
2716         }
2717         HEAD = fsector_t / _floppy->sect;
2718
2719         if (((_floppy->stretch & FD_SWAPSIDES) || TESTF(FD_NEED_TWADDLE)) &&
2720             fsector_t < _floppy->sect)
2721                 max_sector = _floppy->sect;
2722
2723         /* 2M disks have phantom sectors on the first track */
2724         if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)){
2725                 max_sector = 2 * _floppy->sect / 3;
2726                 if (fsector_t >= max_sector){
2727                         current_count_sectors = minimum(_floppy->sect - fsector_t,
2728                                                         current_req->nr_sectors);
2729                         return 1;
2730                 }
2731                 SIZECODE = 2;
2732         } else
2733                 SIZECODE = FD_SIZECODE(_floppy);
2734         raw_cmd->rate = _floppy->rate & 0x43;
2735         if ((_floppy->rate & FD_2M) &&
2736             (TRACK || HEAD) &&
2737             raw_cmd->rate == 2)
2738                 raw_cmd->rate = 1;
2739
2740         if (SIZECODE)
2741                 SIZECODE2 = 0xff;
2742         else
2743                 SIZECODE2 = 0x80;
2744         raw_cmd->track = TRACK << STRETCH(_floppy);
2745         DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy,HEAD);
2746         GAP = _floppy->gap;
2747         CODE2SIZE;
2748         SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;
2749         SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) + 1;
2750
2751         /* tracksize describes the size which can be filled up with sectors
2752          * of size ssize.
2753          */
2754         tracksize = _floppy->sect - _floppy->sect % ssize;
2755         if (tracksize < _floppy->sect){
2756                 SECT_PER_TRACK ++;
2757                 if (tracksize <= fsector_t % _floppy->sect)
2758                         SECTOR--;
2759
2760                 /* if we are beyond tracksize, fill up using smaller sectors */
2761                 while (tracksize <= fsector_t % _floppy->sect){
2762                         while(tracksize + ssize > _floppy->sect){
2763                                 SIZECODE--;
2764                                 ssize >>= 1;
2765                         }
2766                         SECTOR++; SECT_PER_TRACK ++;
2767                         tracksize += ssize;
2768                 }
2769                 max_sector = HEAD * _floppy->sect + tracksize;
2770         } else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {
2771                 max_sector = _floppy->sect;
2772         } else if (!HEAD && CT(COMMAND) == FD_WRITE) {
2773                 /* for virtual DMA bug workaround */
2774                 max_sector = _floppy->sect;
2775         }
2776
2777         in_sector_offset = (fsector_t % _floppy->sect) % ssize;
2778         aligned_sector_t = fsector_t - in_sector_offset;
2779         max_size = current_req->nr_sectors;
2780         if ((raw_cmd->track == buffer_track) && 
2781             (current_drive == buffer_drive) &&
2782             (fsector_t >= buffer_min) && (fsector_t < buffer_max)) {
2783                 /* data already in track buffer */
2784                 if (CT(COMMAND) == FD_READ) {
2785                         copy_buffer(1, max_sector, buffer_max);
2786                         return 1;
2787                 }
2788         } else if (in_sector_offset || current_req->nr_sectors < ssize){
2789                 if (CT(COMMAND) == FD_WRITE){
2790                         if (fsector_t + current_req->nr_sectors > ssize &&
2791                             fsector_t + current_req->nr_sectors < ssize + ssize)
2792                                 max_size = ssize + ssize;
2793                         else
2794                                 max_size = ssize;
2795                 }
2796                 raw_cmd->flags &= ~FD_RAW_WRITE;
2797                 raw_cmd->flags |= FD_RAW_READ;
2798                 COMMAND = FM_MODE(_floppy,FD_READ);
2799         } else if ((unsigned long)current_req->buffer < MAX_DMA_ADDRESS) {
2800                 unsigned long dma_limit;
2801                 int direct, indirect;
2802
2803                 indirect= transfer_size(ssize,max_sector,max_buffer_sectors*2) -
2804                         fsector_t;
2805
2806                 /*
2807                  * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide
2808                  * on a 64 bit machine!
2809                  */
2810                 max_size = buffer_chain_size();
2811                 dma_limit = (MAX_DMA_ADDRESS - ((unsigned long) current_req->buffer)) >> 9;
2812                 if ((unsigned long) max_size > dma_limit) {
2813                         max_size = dma_limit;
2814                 }
2815                 /* 64 kb boundaries */
2816                 if (CROSS_64KB(current_req->buffer, max_size << 9))
2817                         max_size = (K_64 - 
2818                                     ((unsigned long)current_req->buffer) % K_64)>>9;
2819                 direct = transfer_size(ssize,max_sector,max_size) - fsector_t;
2820                 /*
2821                  * We try to read tracks, but if we get too many errors, we
2822                  * go back to reading just one sector at a time.
2823                  *
2824                  * This means we should be able to read a sector even if there
2825                  * are other bad sectors on this track.
2826                  */
2827                 if (!direct ||
2828                     (indirect * 2 > direct * 3 &&
2829                      *errors < DP->max_errors.read_track &&
2830                      /*!TESTF(FD_NEED_TWADDLE) &&*/
2831                      ((!probing || (DP->read_track&(1<<DRS->probed_format)))))){
2832                         max_size = current_req->nr_sectors;
2833                 } else {
2834                         raw_cmd->kernel_data = current_req->buffer;
2835                         raw_cmd->length = current_count_sectors << 9;
2836                         if (raw_cmd->length == 0){
2837                                 DPRINT("zero dma transfer attempted from make_raw_request\n");
2838                                 DPRINT("indirect=%d direct=%d fsector_t=%d",
2839                                         indirect, direct, fsector_t);
2840                                 return 0;
2841                         }
2842 /*                      check_dma_crossing(raw_cmd->kernel_data, 
2843                                            raw_cmd->length, 
2844                                            "end of make_raw_request [1]");*/
2845
2846                         virtualdmabug_workaround();
2847                         return 2;
2848                 }
2849         }
2850
2851         if (CT(COMMAND) == FD_READ)
2852                 max_size = max_sector; /* unbounded */
2853
2854         /* claim buffer track if needed */
2855         if (buffer_track != raw_cmd->track ||  /* bad track */
2856             buffer_drive !=current_drive || /* bad drive */
2857             fsector_t > buffer_max ||
2858             fsector_t < buffer_min ||
2859             ((CT(COMMAND) == FD_READ ||
2860               (!in_sector_offset && current_req->nr_sectors >= ssize))&&
2861              max_sector > 2 * max_buffer_sectors + buffer_min &&
2862              max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)
2863             /* not enough space */){
2864                 buffer_track = -1;
2865                 buffer_drive = current_drive;
2866                 buffer_max = buffer_min = aligned_sector_t;
2867         }
2868         raw_cmd->kernel_data = floppy_track_buffer + 
2869                 ((aligned_sector_t-buffer_min)<<9);
2870
2871         if (CT(COMMAND) == FD_WRITE){
2872                 /* copy write buffer to track buffer.
2873                  * if we get here, we know that the write
2874                  * is either aligned or the data already in the buffer
2875                  * (buffer will be overwritten) */
2876 #ifdef FLOPPY_SANITY_CHECK
2877                 if (in_sector_offset && buffer_track == -1)
2878                         DPRINT("internal error offset !=0 on write\n");
2879 #endif
2880                 buffer_track = raw_cmd->track;
2881                 buffer_drive = current_drive;
2882                 copy_buffer(ssize, max_sector, 2*max_buffer_sectors+buffer_min);
2883         } else
2884                 transfer_size(ssize, max_sector,
2885                               2*max_buffer_sectors+buffer_min-aligned_sector_t);
2886
2887         /* round up current_count_sectors to get dma xfer size */
2888         raw_cmd->length = in_sector_offset+current_count_sectors;
2889         raw_cmd->length = ((raw_cmd->length -1)|(ssize-1))+1;
2890         raw_cmd->length <<= 9;
2891 #ifdef FLOPPY_SANITY_CHECK
2892         /*check_dma_crossing(raw_cmd->kernel_data, raw_cmd->length, 
2893           "end of make_raw_request");*/
2894         if ((raw_cmd->length < current_count_sectors << 9) ||
2895             (raw_cmd->kernel_data != current_req->buffer &&
2896              CT(COMMAND) == FD_WRITE &&
2897              (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||
2898               aligned_sector_t < buffer_min)) ||
2899             raw_cmd->length % (128 << SIZECODE) ||
2900             raw_cmd->length <= 0 || current_count_sectors <= 0){
2901                 DPRINT("fractionary current count b=%lx s=%lx\n",
2902                         raw_cmd->length, current_count_sectors);
2903                 if (raw_cmd->kernel_data != current_req->buffer)
2904                         printk("addr=%d, length=%ld\n",
2905                                (int) ((raw_cmd->kernel_data - 
2906                                        floppy_track_buffer) >> 9),
2907                                current_count_sectors);
2908                 printk("st=%d ast=%d mse=%d msi=%d\n",
2909                        fsector_t, aligned_sector_t, max_sector, max_size);
2910                 printk("ssize=%x SIZECODE=%d\n", ssize, SIZECODE);
2911                 printk("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n",
2912                        COMMAND, SECTOR, HEAD, TRACK);
2913                 printk("buffer drive=%d\n", buffer_drive);
2914                 printk("buffer track=%d\n", buffer_track);
2915                 printk("buffer_min=%d\n", buffer_min);
2916                 printk("buffer_max=%d\n", buffer_max);
2917                 return 0;
2918         }
2919
2920         if (raw_cmd->kernel_data != current_req->buffer){
2921                 if (raw_cmd->kernel_data < floppy_track_buffer ||
2922                     current_count_sectors < 0 ||
2923                     raw_cmd->length < 0 ||
2924                     raw_cmd->kernel_data + raw_cmd->length >
2925                     floppy_track_buffer + (max_buffer_sectors  << 10)){
2926                         DPRINT("buffer overrun in schedule dma\n");
2927                         printk("fsector_t=%d buffer_min=%d current_count=%ld\n",
2928                                fsector_t, buffer_min,
2929                                raw_cmd->length >> 9);
2930                         printk("current_count_sectors=%ld\n",
2931                                current_count_sectors);
2932                         if (CT(COMMAND) == FD_READ)
2933                                 printk("read\n");
2934                         if (CT(COMMAND) == FD_WRITE)
2935                                 printk("write\n");
2936                         return 0;
2937                 }
2938         } else if (raw_cmd->length > current_req->nr_sectors << 9 ||
2939                    current_count_sectors > current_req->nr_sectors){
2940                 DPRINT("buffer overrun in direct transfer\n");
2941                 return 0;
2942         } else if (raw_cmd->length < current_count_sectors << 9){
2943                 DPRINT("more sectors than bytes\n");
2944                 printk("bytes=%ld\n", raw_cmd->length >> 9);
2945                 printk("sectors=%ld\n", current_count_sectors);
2946         }
2947         if (raw_cmd->length == 0){
2948                 DPRINT("zero dma transfer attempted from make_raw_request\n");
2949                 return 0;
2950         }
2951 #endif
2952
2953         virtualdmabug_workaround();
2954         return 2;
2955 }
2956
2957 static void redo_fd_request(void)
2958 {
2959 #define REPEAT {request_done(0); continue; }
2960         int drive;
2961         int tmp;
2962
2963         lastredo = jiffies;
2964         if (current_drive < N_DRIVE)
2965                 floppy_off(current_drive);
2966
2967         for (;;) {
2968                 if (!current_req) {
2969                         struct request *req;
2970
2971                         spin_lock_irq(floppy_queue->queue_lock);
2972                         req = elv_next_request(floppy_queue);
2973                         spin_unlock_irq(floppy_queue->queue_lock);
2974                         if (!req) {
2975                                 do_floppy = NULL;
2976                                 unlock_fdc();
2977                                 return;
2978                         }
2979                         current_req = req;
2980                 }
2981                 drive = (long)current_req->rq_disk->private_data;
2982                 set_fdc(drive);
2983                 reschedule_timeout(current_reqD, "redo fd request", 0);
2984
2985                 set_floppy(drive);
2986                 raw_cmd = & default_raw_cmd;
2987                 raw_cmd->flags = 0;
2988                 if (start_motor(redo_fd_request)) return;
2989                 disk_change(current_drive);
2990                 if (test_bit(current_drive, &fake_change) ||
2991                    TESTF(FD_DISK_CHANGED)){
2992                         DPRINT("disk absent or changed during operation\n");
2993                         REPEAT;
2994                 }
2995                 if (!_floppy) { /* Autodetection */
2996                         if (!probing){
2997                                 DRS->probed_format = 0;
2998                                 if (next_valid_format()){
2999                                         DPRINT("no autodetectable formats\n");
3000                                         _floppy = NULL;
3001                                         REPEAT;
3002                                 }
3003                         }
3004                         probing = 1;
3005                         _floppy = floppy_type+DP->autodetect[DRS->probed_format];
3006                 } else
3007                         probing = 0;
3008                 errors = & (current_req->errors);
3009                 tmp = make_raw_rw_request();
3010                 if (tmp < 2){
3011                         request_done(tmp);
3012                         continue;
3013                 }
3014
3015                 if (TESTF(FD_NEED_TWADDLE))
3016                         twaddle();
3017                 schedule_bh( (void *)(void *) floppy_start);
3018 #ifdef DEBUGT
3019                 debugt("queue fd request");
3020 #endif
3021                 return;
3022         }
3023 #undef REPEAT
3024 }
3025
3026 static struct cont_t rw_cont={
3027         rw_interrupt,
3028         redo_fd_request,
3029         bad_flp_intr,
3030         request_done };
3031
3032 static void process_fd_request(void)
3033 {
3034         cont = &rw_cont;
3035         schedule_bh( (void *)(void *) redo_fd_request);
3036 }
3037
3038 static void do_fd_request(request_queue_t * q)
3039 {
3040         if(max_buffer_sectors == 0) {
3041                 printk("VFS: do_fd_request called on non-open device\n");
3042                 return;
3043         }
3044
3045         if (usage_count == 0) {
3046                 printk("warning: usage count=0, current_req=%p exiting\n", current_req);
3047                 printk("sect=%ld flags=%lx\n", (long)current_req->sector, current_req->flags);
3048                 return;
3049         }
3050         if (fdc_busy){
3051                 /* fdc busy, this new request will be treated when the
3052                    current one is done */
3053                 is_alive("do fd request, old request running");
3054                 return;
3055         }
3056         lock_fdc(MAXTIMEOUT,0);
3057         process_fd_request();
3058         is_alive("do fd request");
3059 }
3060
3061 static struct cont_t poll_cont={
3062         success_and_wakeup,
3063         floppy_ready,
3064         generic_failure,
3065         generic_done };
3066
3067 static int poll_drive(int interruptible, int flag)
3068 {
3069         int ret;
3070         /* no auto-sense, just clear dcl */
3071         raw_cmd = &default_raw_cmd;
3072         raw_cmd->flags= flag;
3073         raw_cmd->track=0;
3074         raw_cmd->cmd_count=0;
3075         cont = &poll_cont;
3076 #ifdef DCL_DEBUG
3077         if (DP->flags & FD_DEBUG){
3078                 DPRINT("setting NEWCHANGE in poll_drive\n");
3079         }
3080 #endif
3081         SETF(FD_DISK_NEWCHANGE);
3082         WAIT(floppy_ready);
3083         return ret;
3084 }
3085
3086 /*
3087  * User triggered reset
3088  * ====================
3089  */
3090
3091 static void reset_intr(void)
3092 {
3093         printk("weird, reset interrupt called\n");
3094 }
3095
3096 static struct cont_t reset_cont={
3097         reset_intr,
3098         success_and_wakeup,
3099         generic_failure,
3100         generic_done };
3101
3102 static int user_reset_fdc(int drive, int arg, int interruptible)
3103 {
3104         int ret;
3105
3106         ret=0;
3107         LOCK_FDC(drive,interruptible);
3108         if (arg == FD_RESET_ALWAYS)
3109                 FDCS->reset=1;
3110         if (FDCS->reset){
3111                 cont = &reset_cont;
3112                 WAIT(reset_fdc);
3113         }
3114         process_fd_request();
3115         return ret;
3116 }
3117
3118 /*
3119  * Misc Ioctl's and support
3120  * ========================
3121  */
3122 static inline int fd_copyout(void *param, const void *address, unsigned long size)
3123 {
3124         return copy_to_user(param,address, size) ? -EFAULT : 0;
3125 }
3126
3127 static inline int fd_copyin(void *param, void *address, unsigned long size)
3128 {
3129         return copy_from_user(address, param, size) ? -EFAULT : 0;
3130 }
3131
3132 #define _COPYOUT(x) (copy_to_user((void *)param, &(x), sizeof(x)) ? -EFAULT : 0)
3133 #define _COPYIN(x) (copy_from_user(&(x), (void *)param, sizeof(x)) ? -EFAULT : 0)
3134
3135 #define COPYOUT(x) ECALL(_COPYOUT(x))
3136 #define COPYIN(x) ECALL(_COPYIN(x))
3137
3138 static inline const char *drive_name(int type, int drive)
3139 {
3140         struct floppy_struct *floppy;
3141
3142         if (type)
3143                 floppy = floppy_type + type;
3144         else {
3145                 if (UDP->native_format)
3146                         floppy = floppy_type + UDP->native_format;
3147                 else
3148                         return "(null)";
3149         }
3150         if (floppy->name)
3151                 return floppy->name;
3152         else
3153                 return "(null)";
3154 }
3155
3156
3157 /* raw commands */
3158 static void raw_cmd_done(int flag)
3159 {
3160         int i;
3161
3162         if (!flag) {
3163                 raw_cmd->flags |= FD_RAW_FAILURE;
3164                 raw_cmd->flags |= FD_RAW_HARDFAILURE;
3165         } else {
3166                 raw_cmd->reply_count = inr;
3167                 if (raw_cmd->reply_count > MAX_REPLIES)
3168                         raw_cmd->reply_count=0;
3169                 for (i=0; i< raw_cmd->reply_count; i++)
3170                         raw_cmd->reply[i] = reply_buffer[i];
3171
3172                 if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE))
3173                 {
3174                         unsigned long flags;
3175                         flags=claim_dma_lock();
3176                         raw_cmd->length = fd_get_dma_residue();
3177                         release_dma_lock(flags);
3178                 }
3179                 
3180                 if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&
3181                     (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))
3182                         raw_cmd->flags |= FD_RAW_FAILURE;
3183
3184                 if (disk_change(current_drive))
3185                         raw_cmd->flags |= FD_RAW_DISK_CHANGE;
3186                 else
3187                         raw_cmd->flags &= ~FD_RAW_DISK_CHANGE;
3188                 if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)
3189                         motor_off_callback(current_drive);
3190
3191                 if (raw_cmd->next &&
3192                    (!(raw_cmd->flags & FD_RAW_FAILURE) ||
3193                     !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&
3194                    ((raw_cmd->flags & FD_RAW_FAILURE) ||
3195                     !(raw_cmd->flags &FD_RAW_STOP_IF_SUCCESS))) {
3196                         raw_cmd = raw_cmd->next;
3197                         return;
3198                 }
3199         }
3200         generic_done(flag);
3201 }
3202
3203
3204 static struct cont_t raw_cmd_cont={
3205         success_and_wakeup,
3206         floppy_start,
3207         generic_failure,
3208         raw_cmd_done
3209 };
3210
3211 static inline int raw_cmd_copyout(int cmd, char *param,
3212                                   struct floppy_raw_cmd *ptr)
3213 {
3214         int ret;
3215
3216         while(ptr) {
3217                 COPYOUT(*ptr);
3218                 param += sizeof(struct floppy_raw_cmd);
3219                 if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length){
3220                         if (ptr->length>=0 && ptr->length<=ptr->buffer_length)
3221                                 ECALL(fd_copyout(ptr->data, 
3222                                                  ptr->kernel_data, 
3223                                                  ptr->buffer_length - 
3224                                                  ptr->length));
3225                 }
3226                 ptr = ptr->next;
3227         }
3228         return 0;
3229 }
3230
3231
3232 static void raw_cmd_free(struct floppy_raw_cmd **ptr)
3233 {
3234         struct floppy_raw_cmd *next,*this;
3235
3236         this = *ptr;
3237         *ptr = 0;
3238         while(this) {
3239                 if (this->buffer_length) {
3240                         fd_dma_mem_free((unsigned long)this->kernel_data,
3241                                         this->buffer_length);
3242                         this->buffer_length = 0;
3243                 }
3244                 next = this->next;
3245                 kfree(this);
3246                 this = next;
3247         }
3248 }
3249
3250
3251 static inline int raw_cmd_copyin(int cmd, char *param,
3252                                  struct floppy_raw_cmd **rcmd)
3253 {
3254         struct floppy_raw_cmd *ptr;
3255         int ret;
3256         int i;
3257         
3258         *rcmd = 0;
3259         while(1) {
3260                 ptr = (struct floppy_raw_cmd *) 
3261                         kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);
3262                 if (!ptr)
3263                         return -ENOMEM;
3264                 *rcmd = ptr;
3265                 COPYIN(*ptr);
3266                 ptr->next = 0;
3267                 ptr->buffer_length = 0;
3268                 param += sizeof(struct floppy_raw_cmd);
3269                 if (ptr->cmd_count > 33)
3270                         /* the command may now also take up the space
3271                          * initially intended for the reply & the
3272                          * reply count. Needed for long 82078 commands
3273                          * such as RESTORE, which takes ... 17 command
3274                          * bytes. Murphy's law #137: When you reserve
3275                          * 16 bytes for a structure, you'll one day
3276                          * discover that you really need 17...
3277                          */
3278                         return -EINVAL;
3279
3280                 for (i=0; i< 16; i++)
3281                         ptr->reply[i] = 0;
3282                 ptr->resultcode = 0;
3283                 ptr->kernel_data = 0;
3284
3285                 if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
3286                         if (ptr->length <= 0)
3287                                 return -EINVAL;
3288                         ptr->kernel_data =(char*)fd_dma_mem_alloc(ptr->length);
3289                         fallback_on_nodma_alloc(&ptr->kernel_data,
3290                                                 ptr->length);
3291                         if (!ptr->kernel_data)
3292                                 return -ENOMEM;
3293                         ptr->buffer_length = ptr->length;
3294                 }
3295                 if (ptr->flags & FD_RAW_WRITE)
3296                         ECALL(fd_copyin(ptr->data, ptr->kernel_data, 
3297                                         ptr->length));
3298                 rcmd = & (ptr->next);
3299                 if (!(ptr->flags & FD_RAW_MORE))
3300                         return 0;
3301                 ptr->rate &= 0x43;
3302         }
3303 }
3304
3305
3306 static int raw_cmd_ioctl(int cmd, void *param)
3307 {
3308         int drive, ret, ret2;
3309         struct floppy_raw_cmd *my_raw_cmd;
3310
3311         if (FDCS->rawcmd <= 1)
3312                 FDCS->rawcmd = 1;
3313         for (drive= 0; drive < N_DRIVE; drive++){
3314                 if (FDC(drive) != fdc)
3315                         continue;
3316                 if (drive == current_drive){
3317                         if (UDRS->fd_ref > 1){
3318                                 FDCS->rawcmd = 2;
3319                                 break;
3320                         }
3321                 } else if (UDRS->fd_ref){
3322                         FDCS->rawcmd = 2;
3323                         break;
3324                 }
3325         }
3326
3327         if (FDCS->reset)
3328                 return -EIO;
3329
3330         ret = raw_cmd_copyin(cmd, param, &my_raw_cmd);
3331         if (ret) {
3332                 raw_cmd_free(&my_raw_cmd);
3333                 return ret;
3334         }
3335
3336         raw_cmd = my_raw_cmd;
3337         cont = &raw_cmd_cont;
3338         ret=wait_til_done(floppy_start,1);
3339 #ifdef DCL_DEBUG
3340         if (DP->flags & FD_DEBUG){
3341                 DPRINT("calling disk change from raw_cmd ioctl\n");
3342         }
3343 #endif
3344
3345         if (ret != -EINTR && FDCS->reset)
3346                 ret = -EIO;
3347
3348         DRS->track = NO_TRACK;
3349
3350         ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);
3351         if (!ret)
3352                 ret = ret2;
3353         raw_cmd_free(&my_raw_cmd);
3354         return ret;
3355 }
3356
3357 static int invalidate_drive(struct block_device *bdev)
3358 {
3359         /* invalidate the buffer track to force a reread */
3360         set_bit((long)bdev->bd_disk->private_data, &fake_change);
3361         process_fd_request();
3362         check_disk_change(bdev);
3363         return 0;
3364 }
3365
3366
3367 static inline void clear_write_error(int drive)
3368 {
3369         CLEARSTRUCT(UDRWE);
3370 }
3371
3372 static inline int set_geometry(unsigned int cmd, struct floppy_struct *g,
3373                                int drive, int type, struct block_device *bdev)
3374 {
3375         int cnt;
3376
3377         /* sanity checking for parameters.*/
3378         if (g->sect <= 0 ||
3379             g->head <= 0 ||
3380             g->track <= 0 ||
3381             g->track > UDP->tracks>>STRETCH(g) ||
3382             /* check if reserved bits are set */
3383             (g->stretch&~(FD_STRETCH|FD_SWAPSIDES)) != 0)
3384                 return -EINVAL;
3385         if (type){
3386                 if (!capable(CAP_SYS_ADMIN))
3387                         return -EPERM;
3388                 down(&open_lock);
3389                 LOCK_FDC(drive,1);
3390                 floppy_type[type] = *g;
3391                 floppy_type[type].name="user format";
3392                 for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
3393                         floppy_sizes[cnt]= floppy_sizes[cnt+0x80]=
3394                                 floppy_type[type].size+1;
3395                 process_fd_request();
3396                 for (cnt = 0; cnt < N_DRIVE; cnt++) {
3397                         struct block_device *bdev = opened_bdev[cnt];
3398                         if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
3399                                 continue;
3400                         __invalidate_device(bdev, 0);
3401                 }
3402                 up(&open_lock);
3403         } else {
3404                 LOCK_FDC(drive,1);
3405                 if (cmd != FDDEFPRM)
3406                         /* notice a disk change immediately, else
3407                          * we lose our settings immediately*/
3408                         CALL(poll_drive(1, FD_RAW_NEED_DISK));
3409                 user_params[drive] = *g;
3410                 if (buffer_drive == drive)
3411                         SUPBOUND(buffer_max, user_params[drive].sect);
3412                 current_type[drive] = &user_params[drive];
3413                 floppy_sizes[drive] = user_params[drive].size;
3414                 if (cmd == FDDEFPRM)
3415                         DRS->keep_data = -1;
3416                 else
3417                         DRS->keep_data = 1;
3418                 /* invalidation. Invalidate only when needed, i.e.
3419                  * when there are already sectors in the buffer cache
3420                  * whose number will change. This is useful, because
3421                  * mtools often changes the geometry of the disk after
3422                  * looking at the boot block */
3423                 if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack)
3424                         invalidate_drive(bdev);
3425                 else
3426                         process_fd_request();
3427         }
3428         return 0;
3429 }
3430
3431 /* handle obsolete ioctl's */
3432 static int ioctl_table[]= {
3433         FDCLRPRM,
3434         FDSETPRM,
3435         FDDEFPRM,
3436         FDGETPRM,
3437         FDMSGON,
3438         FDMSGOFF,
3439         FDFMTBEG,
3440         FDFMTTRK,
3441         FDFMTEND,
3442         FDSETEMSGTRESH,
3443         FDFLUSH,
3444         FDSETMAXERRS,
3445         FDGETMAXERRS,
3446         FDGETDRVTYP,
3447         FDSETDRVPRM,
3448         FDGETDRVPRM,
3449         FDGETDRVSTAT,
3450         FDPOLLDRVSTAT,
3451         FDRESET,
3452         FDGETFDCSTAT,
3453         FDWERRORCLR,
3454         FDWERRORGET,
3455         FDRAWCMD,
3456         FDEJECT,
3457         FDTWADDLE
3458 };
3459
3460 static inline int normalize_ioctl(int *cmd, int *size)
3461 {
3462         int i;
3463
3464         for (i=0; i < ARRAY_SIZE(ioctl_table); i++) {
3465                 if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)){
3466                         *size = _IOC_SIZE(*cmd);
3467                         *cmd = ioctl_table[i];
3468                         if (*size > _IOC_SIZE(*cmd)) {
3469                                 printk("ioctl not yet supported\n");
3470                                 return -EFAULT;
3471                         }
3472                         return 0;
3473                 }
3474         }
3475         return -EINVAL;
3476 }
3477
3478 static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)
3479 {
3480         if (type)
3481                 *g = &floppy_type[type];
3482         else {
3483                 LOCK_FDC(drive,0);
3484                 CALL(poll_drive(0,0));
3485                 process_fd_request();           
3486                 *g = current_type[drive];
3487         }
3488         if (!*g)
3489                 return -ENODEV;
3490         return 0;
3491 }
3492
3493 static int fd_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
3494                     unsigned long param)
3495 {
3496 #define FD_IOCTL_ALLOWED ((filp) && (filp)->private_data)
3497 #define OUT(c,x) case c: outparam = (const char *) (x); break
3498 #define IN(c,x,tag) case c: *(x) = inparam. tag ; return 0
3499
3500         int drive = (long)inode->i_bdev->bd_disk->private_data;
3501         int i, type = ITYPE(UDRS->fd_device);
3502         int ret;
3503         int size;
3504         union inparam {
3505                 struct floppy_struct g; /* geometry */
3506                 struct format_descr f;
3507                 struct floppy_max_errors max_errors;
3508                 struct floppy_drive_params dp;
3509         } inparam; /* parameters coming from user space */
3510         const char *outparam; /* parameters passed back to user space */
3511
3512         /* convert compatibility eject ioctls into floppy eject ioctl.
3513          * We do this in order to provide a means to eject floppy disks before
3514          * installing the new fdutils package */
3515         if (cmd == CDROMEJECT || /* CD-ROM eject */
3516             cmd == 0x6470 /* SunOS floppy eject */) {
3517                 DPRINT("obsolete eject ioctl\n");
3518                 DPRINT("please use floppycontrol --eject\n");
3519                 cmd = FDEJECT;
3520         }
3521
3522         /* generic block device ioctls */
3523         switch(cmd) {
3524                 /* the following have been inspired by the corresponding
3525                  * code for other block devices. */
3526                 struct floppy_struct *g;
3527                 case HDIO_GETGEO:
3528                 {
3529                         struct hd_geometry loc;
3530                         ECALL(get_floppy_geometry(drive, type, &g));
3531                         loc.heads = g->head;
3532                         loc.sectors = g->sect;
3533                         loc.cylinders = g->track;
3534                         loc.start = 0;
3535                         return _COPYOUT(loc);
3536                 }
3537         }
3538
3539         /* convert the old style command into a new style command */
3540         if ((cmd & 0xff00) == 0x0200) {
3541                 ECALL(normalize_ioctl(&cmd, &size));
3542         } else
3543                 return -EINVAL;
3544
3545         /* permission checks */
3546         if (((cmd & 0x40) && !FD_IOCTL_ALLOWED) ||
3547             ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))
3548                 return -EPERM;
3549
3550         /* copyin */
3551         CLEARSTRUCT(&inparam);
3552         if (_IOC_DIR(cmd) & _IOC_WRITE)
3553                 ECALL(fd_copyin((void *)param, &inparam, size))
3554
3555         switch (cmd) {
3556                 case FDEJECT:
3557                         if (UDRS->fd_ref != 1)
3558                                 /* somebody else has this drive open */
3559                                 return -EBUSY;
3560                         LOCK_FDC(drive,1);
3561
3562                         /* do the actual eject. Fails on
3563                          * non-Sparc architectures */
3564                         ret=fd_eject(UNIT(drive));
3565
3566                         USETF(FD_DISK_CHANGED);
3567                         USETF(FD_VERIFY);
3568                         process_fd_request();
3569                         return ret;                     
3570                 case FDCLRPRM:
3571                         LOCK_FDC(drive,1);
3572                         current_type[drive] = NULL;
3573                         floppy_sizes[drive] = MAX_DISK_SIZE << 1;
3574                         UDRS->keep_data = 0;
3575                         return invalidate_drive(inode->i_bdev);
3576                 case FDSETPRM:
3577                 case FDDEFPRM:
3578                         return set_geometry(cmd, & inparam.g,
3579                                             drive, type, inode->i_bdev);
3580                 case FDGETPRM:
3581                         ECALL(get_floppy_geometry(drive, type, 
3582                                                   (struct floppy_struct**)
3583                                                   &outparam));
3584                         break;
3585
3586                 case FDMSGON:
3587                         UDP->flags |= FTD_MSG;
3588                         return 0;
3589                 case FDMSGOFF:
3590                         UDP->flags &= ~FTD_MSG;
3591                         return 0;
3592
3593                 case FDFMTBEG:
3594                         LOCK_FDC(drive,1);
3595                         CALL(poll_drive(1, FD_RAW_NEED_DISK));
3596                         ret = UDRS->flags;
3597                         if (ret & FD_VERIFY) {
3598                                 CALL(poll_drive(1, FD_RAW_NEED_DISK));
3599                                 ret = UDRS->flags;
3600                         }
3601
3602                         if (ret & FD_VERIFY) {
3603                                 CALL(poll_drive(1, FD_RAW_NEED_DISK));
3604                                 ret = UDRS->flags;
3605                         }
3606
3607                         if (ret & FD_VERIFY) {
3608                                 CALL(poll_drive(1, FD_RAW_NEED_DISK));
3609                                 ret = UDRS->flags;
3610                         }
3611
3612                         if (ret & FD_VERIFY) {
3613                                 CALL(poll_drive(1, FD_RAW_NEED_DISK));
3614                                 ret = UDRS->flags;
3615                         }
3616
3617                         if(ret & FD_VERIFY){
3618                                 CALL(poll_drive(1, FD_RAW_NEED_DISK));
3619                                 ret = UDRS->flags;
3620                         }
3621                         process_fd_request();
3622                         if (ret & FD_VERIFY)
3623                                 return -ENODEV;
3624                         if (!(ret & FD_DISK_WRITABLE))
3625                                 return -EROFS;
3626                         return 0;
3627                 case FDFMTTRK:
3628                         if (UDRS->fd_ref != 1)
3629                                 return -EBUSY;
3630                         return do_format(drive, &inparam.f);
3631                 case FDFMTEND:
3632                 case FDFLUSH:
3633                         LOCK_FDC(drive,1);
3634                         return invalidate_drive(inode->i_bdev);
3635
3636                 case FDSETEMSGTRESH:
3637                         UDP->max_errors.reporting =
3638                                 (unsigned short) (param & 0x0f);
3639                         return 0;
3640                 OUT(FDGETMAXERRS, &UDP->max_errors);
3641                 IN(FDSETMAXERRS, &UDP->max_errors, max_errors);
3642
3643                 case FDGETDRVTYP:
3644                         outparam = drive_name(type,drive);
3645                         SUPBOUND(size,strlen(outparam)+1);
3646                         break;
3647
3648                 IN(FDSETDRVPRM, UDP, dp);
3649                 OUT(FDGETDRVPRM, UDP);
3650
3651                 case FDPOLLDRVSTAT:
3652                         LOCK_FDC(drive,1);
3653                         CALL(poll_drive(1, FD_RAW_NEED_DISK));
3654                         process_fd_request();
3655                         /* fall through */
3656                 OUT(FDGETDRVSTAT, UDRS);
3657
3658                 case FDRESET:
3659                         return user_reset_fdc(drive, (int)param, 1);
3660
3661                 OUT(FDGETFDCSTAT,UFDCS);
3662
3663                 case FDWERRORCLR:
3664                         CLEARSTRUCT(UDRWE);
3665                         return 0;
3666                 OUT(FDWERRORGET,UDRWE);
3667
3668                 case FDRAWCMD:
3669                         if (type)
3670                                 return -EINVAL;
3671                         LOCK_FDC(drive,1);
3672                         set_floppy(drive);
3673                         CALL(i = raw_cmd_ioctl(cmd,(void *) param));
3674                         process_fd_request();
3675                         return i;
3676
3677                 case FDTWADDLE:
3678                         LOCK_FDC(drive,1);
3679                         twaddle();
3680                         process_fd_request();
3681                         return 0;
3682
3683                 default:
3684                         return -EINVAL;
3685         }
3686
3687         if (_IOC_DIR(cmd) & _IOC_READ)
3688                 return fd_copyout((void *)param, outparam, size);
3689         else
3690                 return 0;
3691 #undef OUT
3692 #undef IN
3693 }
3694
3695 static void __init config_types(void)
3696 {
3697         int first=1;
3698         int drive;
3699         extern struct fd_info {
3700                 unsigned char dummy[4 * 6];
3701                 unsigned char fd_types[8];
3702         } drive_info;
3703
3704         for (drive = 0; drive < 4; drive++)
3705                 UDP->cmos = drive_info.fd_types[drive];
3706
3707         /* XXX */
3708         /* additional physical CMOS drive detection should go here */
3709
3710         for (drive=0; drive < N_DRIVE; drive++){
3711                 unsigned int type = UDP->cmos;
3712                 struct floppy_drive_params *params;
3713                 const char *name = NULL;
3714                 static char temparea[32];
3715
3716                 if (type < NUMBER(default_drive_params)) {
3717                         params = &default_drive_params[type].params;
3718                         if (type) {
3719                                 name = default_drive_params[type].name;
3720                                 allowed_drive_mask |= 1 << drive;
3721                         }
3722                         else
3723                                 allowed_drive_mask &= ~(1 << drive);
3724                 } else {
3725                         params = &default_drive_params[0].params;
3726                         sprintf(temparea, "unknown type %d (usb?)", type);
3727                         name = temparea;
3728                 }
3729                 if (name) {
3730                         const char * prepend = ",";
3731                         if (first) {
3732                                 prepend = KERN_INFO "Floppy drive(s):";
3733                                 first = 0;
3734                         }
3735                         printk("%s fd%d is %s", prepend, drive, name);
3736                         register_devfs_entries (drive);
3737                 }
3738                 *UDP = *params;
3739         }
3740         if (!first)
3741                 printk("\n");
3742 }
3743
3744 static int floppy_release(struct inode * inode, struct file * filp)
3745 {
3746         int drive = (long)inode->i_bdev->bd_disk->private_data;
3747
3748         down(&open_lock);
3749         if (UDRS->fd_ref < 0)
3750                 UDRS->fd_ref=0;
3751         else if (!UDRS->fd_ref--) {
3752                 DPRINT("floppy_release with fd_ref == 0");
3753                 UDRS->fd_ref = 0;
3754         }
3755         if (!UDRS->fd_ref)
3756                 opened_bdev[drive] = NULL;
3757         floppy_release_irq_and_dma();
3758         up(&open_lock);
3759         return 0;
3760 }
3761
3762 /*
3763  * floppy_open check for aliasing (/dev/fd0 can be the same as
3764  * /dev/PS0 etc), and disallows simultaneous access to the same
3765  * drive with different device numbers.
3766  */
3767 #define RETERR(x) do{floppy_release(inode,filp); return -(x);}while(0)
3768
3769 static int floppy_open(struct inode * inode, struct file * filp)
3770 {
3771         int drive = (long)inode->i_bdev->bd_disk->private_data;
3772         int old_dev;
3773         int try;
3774         int res = -EBUSY;
3775         char *tmp;
3776
3777 #ifdef PC9800_DEBUG_FLOPPY
3778         printk("floppy open: start\n");
3779 #endif
3780         filp->private_data = (void*) 0;
3781
3782 #ifdef PC9800_DEBUG_FLOPPY
3783         printk("floppy open: drive=%d, current_drive=%d, UDP->cmos=%d\n"
3784                    "floppy open: FDCS={spec1=%d, spec2=%d, dtr=%d, version=%d, dor=%d, address=%lu}\n",
3785                    drive, current_drive, UDP->cmos, FDCS->spec1, FDCS->spec2,
3786                    FDCS->dtr, FDCS->version, FDCS->dor, FDCS->address);
3787         if (_floppy) {
3788                 printk("floppy open: _floppy={size=%d, sect=%d, head=%d, track=%d, spec1=%d}\n",
3789                            _floppy->size, _floppy->sect, _floppy->head,
3790                            _floppy->track, _floppy->spec1);
3791         } else {
3792                 printk("floppy open: _floppy=NULL\n");
3793         }
3794 #endif /* PC9800_DEBUG_FLOPPY */
3795
3796         down(&open_lock);
3797         old_dev = UDRS->fd_device;
3798         if (opened_bdev[drive] && opened_bdev[drive] != inode->i_bdev)
3799                 goto out2;
3800
3801         if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)){
3802                 USETF(FD_DISK_CHANGED);
3803                 USETF(FD_VERIFY);
3804         }
3805
3806         if (UDRS->fd_ref == -1 ||
3807            (UDRS->fd_ref && (filp->f_flags & O_EXCL)))
3808                 goto out2;
3809
3810         if (floppy_grab_irq_and_dma())
3811                 goto out2;
3812
3813         if (filp->f_flags & O_EXCL)
3814                 UDRS->fd_ref = -1;
3815         else
3816                 UDRS->fd_ref++;
3817
3818         opened_bdev[drive] = inode->i_bdev;
3819
3820         res = -ENXIO;
3821
3822         if (!floppy_track_buffer){
3823                 /* if opening an ED drive, reserve a big buffer,
3824                  * else reserve a small one */
3825                 if ((UDP->cmos == 6) || (UDP->cmos == 5))
3826                         try = 64; /* Only 48 actually useful */
3827                 else
3828                         try = 32; /* Only 24 actually useful */
3829
3830                 tmp=(char *)fd_dma_mem_alloc(1024 * try);
3831                 if (!tmp && !floppy_track_buffer) {
3832                         try >>= 1; /* buffer only one side */
3833                         INFBOUND(try, 16);
3834                         tmp= (char *)fd_dma_mem_alloc(1024*try);
3835                 }
3836                 if (!tmp && !floppy_track_buffer) {
3837                         fallback_on_nodma_alloc(&tmp, 2048 * try);
3838                 }
3839                 if (!tmp && !floppy_track_buffer) {
3840                         DPRINT("Unable to allocate DMA memory\n");
3841                         goto out;
3842                 }
3843                 if (floppy_track_buffer) {
3844                         if (tmp)
3845                                 fd_dma_mem_free((unsigned long)tmp,try*1024);
3846                 } else {
3847                         buffer_min = buffer_max = -1;
3848                         floppy_track_buffer = tmp;
3849                         max_buffer_sectors = try;
3850                 }
3851         }
3852
3853         UDRS->fd_device = iminor(inode);
3854         set_capacity(disks[drive], floppy_sizes[iminor(inode)]);
3855         if (old_dev != -1 && old_dev != iminor(inode)) {
3856                 if (buffer_drive == drive)
3857                         buffer_track = -1;
3858         }
3859
3860 #ifdef PC9800_DEBUG_FLOPPY
3861         printk("floppy open: floppy.c:%d passed\n", __LINE__);
3862 #endif
3863
3864
3865         /* Allow ioctls if we have write-permissions even if read-only open.
3866          * Needed so that programs such as fdrawcmd still can work on write
3867          * protected disks */
3868         if (filp->f_mode & 2 || permission(filp->f_dentry->d_inode,2,NULL) == 0)
3869             filp->private_data = (void*) 8;
3870
3871         if (UFDCS->rawcmd == 1)
3872                 UFDCS->rawcmd = 2;
3873
3874 #ifdef PC9800_DEBUG_FLOPPY
3875         printk("floppy open: floppy.c:%d passed\n", __LINE__);
3876 #endif
3877
3878         if (!(filp->f_flags & O_NDELAY)) {
3879                 if (filp->f_mode & 3) {
3880                         UDRS->last_checked = 0;
3881                         check_disk_change(inode->i_bdev);
3882                         if (UTESTF(FD_DISK_CHANGED))
3883                                 goto out;
3884                 }
3885                 res = -EROFS;
3886                 if ((filp->f_mode & 2) && !(UTESTF(FD_DISK_WRITABLE)))
3887                         goto out;
3888 #ifdef PC9800_DEBUG_FLOPPY
3889                 printk("floppy open: end normally\n");
3890 #endif
3891         }
3892         up(&open_lock);
3893         return 0;
3894 out:
3895         if (UDRS->fd_ref < 0)
3896                 UDRS->fd_ref=0;
3897         else
3898                 UDRS->fd_ref--;
3899         if (!UDRS->fd_ref)
3900                 opened_bdev[drive] = NULL;
3901         floppy_release_irq_and_dma();
3902 out2:
3903         up(&open_lock);
3904         return res;
3905 }
3906
3907 /*
3908  * Check if the disk has been changed or if a change has been faked.
3909  */
3910 static int check_floppy_change(struct gendisk *disk)
3911 {
3912         int drive = (long)disk->private_data;
3913
3914 #ifdef PC9800_DEBUG_FLOPPY
3915         printk("check_floppy_change: MINOR=%d\n", minor(dev));
3916 #endif
3917
3918         if (UTESTF(FD_DISK_CHANGED) || UTESTF(FD_VERIFY))
3919                 return 1;
3920
3921         if (UDP->checkfreq < (int)(jiffies - UDRS->last_checked)) {
3922                 if(floppy_grab_irq_and_dma()) {
3923                         return 1;
3924                 }
3925
3926                 lock_fdc(drive,0);
3927                 poll_drive(0,0);
3928                 process_fd_request();
3929                 floppy_release_irq_and_dma();
3930         }
3931
3932         if (UTESTF(FD_DISK_CHANGED) ||
3933            UTESTF(FD_VERIFY) ||
3934            test_bit(drive, &fake_change) ||
3935            (!ITYPE(UDRS->fd_device) && !current_type[drive]))
3936                 return 1;
3937         return 0;
3938 }
3939
3940 /*
3941  * This implements "read block 0" for floppy_revalidate().
3942  * Needed for format autodetection, checking whether there is
3943  * a disk in the drive, and whether that disk is writable.
3944  */
3945
3946 static int floppy_rb0_complete(struct bio *bio, unsigned int bytes_done, int err)
3947 {
3948         if (bio->bi_size)
3949                 return 1;
3950
3951         complete((struct completion*)bio->bi_private);
3952         return 0;
3953 }
3954
3955 static int __floppy_read_block_0(struct block_device *bdev)
3956 {
3957         struct bio bio;
3958         struct bio_vec bio_vec;
3959         struct completion complete;
3960         struct page *page;
3961         size_t size;
3962
3963         page = alloc_page(GFP_NOIO);
3964         if (!page) {
3965                 process_fd_request();
3966                 return -ENOMEM;
3967         }
3968
3969         size = bdev->bd_block_size;
3970         if (!size)
3971                 size = 1024;
3972
3973         bio_init(&bio);
3974         bio.bi_io_vec = &bio_vec;
3975         bio_vec.bv_page = page;
3976         bio_vec.bv_len = size;
3977         bio_vec.bv_offset = 0;
3978         bio.bi_vcnt = 1;
3979         bio.bi_idx = 0;
3980         bio.bi_size = size;
3981         bio.bi_bdev = bdev;
3982         bio.bi_sector = 0;
3983         init_completion(&complete);
3984         bio.bi_private = &complete;
3985         bio.bi_end_io = floppy_rb0_complete;
3986
3987         submit_bio(READ, &bio);
3988         generic_unplug_device(bdev_get_queue(bdev));
3989         process_fd_request();
3990         wait_for_completion(&complete);
3991
3992         __free_page(page);
3993
3994         return 0;
3995 }
3996
3997 /* revalidate the floppy disk, i.e. trigger format autodetection by reading
3998  * the bootblock (block 0). "Autodetection" is also needed to check whether
3999  * there is a disk in the drive at all... Thus we also do it for fixed
4000  * geometry formats */
4001 static int floppy_revalidate(struct gendisk *disk)
4002 {
4003         int drive=(long)disk->private_data;
4004 #define NO_GEOM (!current_type[drive] && !ITYPE(UDRS->fd_device))
4005         int cf;
4006         int res = 0;
4007
4008         if (UTESTF(FD_DISK_CHANGED) ||
4009             UTESTF(FD_VERIFY) ||
4010             test_bit(drive, &fake_change) ||
4011             NO_GEOM){
4012                 if(usage_count == 0) {
4013                         printk("VFS: revalidate called on non-open device.\n");
4014                         return -EFAULT;
4015                 }
4016                 lock_fdc(drive,0);
4017                 cf = UTESTF(FD_DISK_CHANGED) || UTESTF(FD_VERIFY);
4018                 if (!(cf || test_bit(drive, &fake_change) || NO_GEOM)){
4019                         process_fd_request(); /*already done by another thread*/
4020                         return 0;
4021                 }
4022                 UDRS->maxblock = 0;
4023                 UDRS->maxtrack = 0;
4024                 if (buffer_drive == drive)
4025                         buffer_track = -1;
4026                 clear_bit(drive, &fake_change);
4027                 UCLEARF(FD_DISK_CHANGED);
4028                 if (cf)
4029                         UDRS->generation++;
4030                 if (NO_GEOM){
4031                         /* auto-sensing */
4032                         res = __floppy_read_block_0(opened_bdev[drive]);
4033                 } else {
4034                         if (cf)
4035                                 poll_drive(0, FD_RAW_NEED_DISK);
4036                         process_fd_request();
4037                 }
4038         }
4039         set_capacity(disk, floppy_sizes[UDRS->fd_device]);
4040         return res;
4041 }
4042
4043 static struct block_device_operations floppy_fops = {
4044         .owner          = THIS_MODULE,
4045         .open           = floppy_open,
4046         .release        = floppy_release,
4047         .ioctl          = fd_ioctl,
4048         .media_changed  = check_floppy_change,
4049         .revalidate_disk= floppy_revalidate,
4050 };
4051
4052 static char *table[] =
4053 {"",
4054 #if 0
4055         "d360", 
4056 #else
4057         "h1232",
4058 #endif
4059         "h1200", "u360", "u720", "h360", "h720",
4060         "u1440", "u2880", "CompaQ", "h1440", "u1680", "h410",
4061         "u820", "h1476", "u1722", "h420", "u830", "h1494", "u1743",
4062         "h880", "u1040", "u1120", "h1600", "u1760", "u1920",
4063         "u3200", "u3520", "u3840", "u1840", "u800", "u1600",
4064 NULL
4065 };
4066
4067 static int t360[] = {
4068         1,0
4069 };
4070 static int t1200[] = {
4071         2,5,6,10,12,14,16,18,20,23,0
4072 };
4073 static int t3in[] = {
4074          8, 9,26,27,28, 7,11,15,19,24,25,
4075         29,31, 3, 4,13,17,21,22,30, 0
4076 };
4077
4078 static int *table_sup[] = {
4079         NULL, t360, t1200, t3in+5+8, t3in+5, t3in, t3in
4080 };
4081
4082 static void __init register_devfs_entries (int drive)
4083 {
4084         int base_minor = (drive < 4) ? drive : (124 + drive);
4085
4086         if (UDP->cmos < NUMBER(default_drive_params)) {
4087                 int i = 0;
4088                 do {
4089                         int minor = base_minor + (table_sup[UDP->cmos][i] << 2);
4090
4091                         devfs_mk_bdev(MKDEV(FLOPPY_MAJOR, minor), 
4092                                         S_IFBLK|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
4093                                         "floppy/%d%s",
4094                                         drive, table[table_sup[UDP->cmos][i]]);
4095                 } while (table_sup[UDP->cmos][i++]);
4096         }
4097 }
4098
4099 /*
4100  * Floppy Driver initialization
4101  * =============================
4102  */
4103
4104 static inline char __init get_fdc_version(void)
4105 {
4106         return FDC_8272A;
4107 }
4108
4109 /* lilo configuration */
4110
4111 static void __init floppy_set_flags(int *ints,int param, int param2)
4112 {
4113         int i;
4114
4115         for (i=0; i < ARRAY_SIZE(default_drive_params); i++){
4116                 if (param)
4117                         default_drive_params[i].params.flags |= param2;
4118                 else
4119                         default_drive_params[i].params.flags &= ~param2;
4120         }
4121         DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param);
4122 }
4123
4124 static void __init daring(int *ints,int param, int param2)
4125 {
4126         int i;
4127
4128         for (i=0; i < ARRAY_SIZE(default_drive_params); i++){
4129                 if (param){
4130                         default_drive_params[i].params.select_delay = 0;
4131                         default_drive_params[i].params.flags |= FD_SILENT_DCL_CLEAR;
4132                 } else {
4133                         default_drive_params[i].params.select_delay = 2*HZ/100;
4134                         default_drive_params[i].params.flags &= ~FD_SILENT_DCL_CLEAR;
4135                 }
4136         }
4137         DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken");
4138 }
4139
4140 static void __init set_cmos(int *ints, int dummy, int dummy2)
4141 {
4142         int current_drive=0;
4143
4144         if (ints[0] != 2){
4145                 DPRINT("wrong number of parameters for CMOS\n");
4146                 return;
4147         }
4148         current_drive = ints[1];
4149         if (current_drive < 0 || current_drive >= 8){
4150                 DPRINT("bad drive for set_cmos\n");
4151                 return;
4152         }
4153 #if N_FDC > 1
4154         if (current_drive >= 4 && !FDC2)
4155                 FDC2 = 0x370;
4156 #endif
4157         DP->cmos = ints[2];
4158         DPRINT("setting CMOS code to %d\n", ints[2]);
4159 }
4160
4161 static struct param_table {
4162         const char *name;
4163         void (*fn)(int *ints, int param, int param2);
4164         int *var;
4165         int def_param;
4166         int param2;
4167 } config_params[]={
4168         { "allowed_drive_mask", 0, &allowed_drive_mask, 0xff, 0}, /* obsolete */
4169         { "all_drives", 0, &allowed_drive_mask, 0xff, 0 }, /* obsolete */
4170         { "irq", 0, &FLOPPY_IRQ, DEFAULT_FLOPPY_IRQ, 0 },
4171         { "dma", 0, &FLOPPY_DMA, DEFAULT_FLOPPY_DMA, 0 },
4172
4173         { "daring", daring, 0, 1, 0},
4174 #if N_FDC > 1
4175         { "two_fdc",  0, &FDC2, 0x370, 0 },
4176         { "one_fdc", 0, &FDC2, 0, 0 },
4177 #endif
4178         { "broken_dcl", floppy_set_flags, 0, 1, FD_BROKEN_DCL },
4179         { "messages", floppy_set_flags, 0, 1, FTD_MSG },
4180         { "silent_dcl_clear", floppy_set_flags, 0, 1, FD_SILENT_DCL_CLEAR },
4181         { "debug", floppy_set_flags, 0, 1, FD_DEBUG },
4182
4183         { "nodma", 0, &can_use_virtual_dma, 1, 0 },
4184         { "yesdma", 0, &can_use_virtual_dma, 0, 0 },
4185
4186         { "fifo_depth", 0, &fifo_depth, 0xa, 0 },
4187         { "nofifo", 0, &no_fifo, 0x20, 0 },
4188         { "usefifo", 0, &no_fifo, 0, 0 },
4189
4190         { "cmos", set_cmos, 0, 0, 0 },
4191         { "slow", 0, &slow_floppy, 1, 0 },
4192
4193         { "unexpected_interrupts", 0, &print_unex, 1, 0 },
4194         { "no_unexpected_interrupts", 0, &print_unex, 0, 0 },
4195
4196         EXTRA_FLOPPY_PARAMS
4197 };
4198
4199 static int __init floppy_setup(char *str)
4200 {
4201         int i;
4202         int param;
4203         int ints[11];
4204
4205         str = get_options(str,ARRAY_SIZE(ints),ints);
4206         if (str) {
4207                 for (i=0; i< ARRAY_SIZE(config_params); i++){
4208                         if (strcmp(str,config_params[i].name) == 0){
4209                                 if (ints[0])
4210                                         param = ints[1];
4211                                 else
4212                                         param = config_params[i].def_param;
4213                                 if (config_params[i].fn)
4214                                         config_params[i].
4215                                                 fn(ints,param,
4216                                                    config_params[i].param2);
4217                                 if (config_params[i].var) {
4218                                         DPRINT("%s=%d\n", str, param);
4219                                         *config_params[i].var = param;
4220                                 }
4221                                 return 1;
4222                         }
4223                 }
4224         }
4225         if (str) {
4226                 DPRINT("unknown floppy option [%s]\n", str);
4227                 
4228                 DPRINT("allowed options are:");
4229                 for (i=0; i< ARRAY_SIZE(config_params); i++)
4230                         printk(" %s",config_params[i].name);
4231                 printk("\n");
4232         } else
4233                 DPRINT("botched floppy option\n");
4234         DPRINT("Read linux/Documentation/floppy.txt\n");
4235         return 0;
4236 }
4237
4238 static int have_no_fdc= -ENODEV;
4239
4240 static void floppy_device_release(struct device *dev)
4241 {
4242         complete(&device_release);
4243 }
4244
4245 static struct platform_device floppy_device = {
4246         .name           = "floppy",
4247         .id             = 0,
4248         .dev            = {
4249                         .release = floppy_device_release,
4250         },
4251 };
4252
4253 static struct kobject *floppy_find(dev_t dev, int *part, void *data)
4254 {
4255         int drive = (*part&3) | ((*part&0x80) >> 5);
4256         if (drive >= N_DRIVE ||
4257             !(allowed_drive_mask & (1 << drive)) ||
4258             fdc_state[FDC(drive)].version == FDC_NONE)
4259                 return NULL;
4260         if (((*part>>2) & 0x1f) >= NUMBER(floppy_type))
4261                 return NULL;
4262         *part = 0;
4263         return get_disk(disks[drive]);
4264 }
4265
4266 int __init floppy_init(void)
4267 {
4268         int i,unit,drive;
4269         int err;
4270
4271         raw_cmd = NULL;
4272         FDC1 = 0x90;
4273
4274         for (i=0; i<N_DRIVE; i++) {
4275                 disks[i] = alloc_disk(1);
4276                 if (!disks[i])
4277                         goto Enomem;
4278         }
4279
4280         devfs_mk_dir (NULL, "floppy", NULL);
4281         if ((err = register_blkdev(FLOPPY_MAJOR,"fd")))
4282                 goto out;
4283
4284         for (i=0; i<N_DRIVE; i++) {
4285                 disks[i]->major = FLOPPY_MAJOR;
4286                 disks[i]->first_minor = TOMINOR(i);
4287                 disks[i]->fops = &floppy_fops;
4288                 sprintf(disks[i]->disk_name, "fd%d", i);
4289         }
4290
4291         blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
4292                                 floppy_find, NULL, NULL);
4293
4294         for (i=0; i<256; i++)
4295                 if (ITYPE(i))
4296                         floppy_sizes[i] = floppy_type[ITYPE(i)].size;
4297                 else
4298                         floppy_sizes[i] = MAX_DISK_SIZE << 1;
4299
4300         floppy_queue = blk_init_queue(do_fd_request, &floppy_lock);
4301         if (!floppy_queue)
4302                 goto out_queue;
4303
4304         reschedule_timeout(MAXTIMEOUT, "floppy init", MAXTIMEOUT);
4305         config_types();
4306
4307         for (i = 0; i < N_FDC; i++) {
4308                 fdc = i;
4309                 CLEARSTRUCT(FDCS);
4310                 FDCS->dtr = -1;
4311                 FDCS->dor = 0;
4312         }
4313
4314         if ((fd_inb(FD_MODE_CHANGE) & 1) == 0)
4315                 FDC1 = 0xc8;
4316
4317         use_virtual_dma = can_use_virtual_dma & 1;
4318         fdc_state[0].address = FDC1;
4319         if (fdc_state[0].address == -1) {
4320                 err = -ENODEV;
4321                 goto out1;
4322         }
4323 #if N_FDC > 1
4324         fdc_state[1].address = FDC2;
4325 #endif
4326
4327         fdc = 0; /* reset fdc in case of unexpected interrupt */
4328         if (floppy_grab_irq_and_dma()){
4329                 err = -EBUSY;
4330                 goto out1;
4331         }
4332
4333         /* initialise drive state */
4334         for (drive = 0; drive < N_DRIVE; drive++) {
4335                 CLEARSTRUCT(UDRS);
4336                 CLEARSTRUCT(UDRWE);
4337                 USETF(FD_DISK_NEWCHANGE);
4338                 USETF(FD_DISK_CHANGED);
4339                 USETF(FD_VERIFY);
4340                 UDRS->fd_device = -1;
4341                 floppy_track_buffer = NULL;
4342                 max_buffer_sectors = 0;
4343         }
4344
4345         for (i = 0; i < N_FDC; i++) {
4346                 fdc = i;
4347                 FDCS->driver_version = FD_DRIVER_VERSION;
4348                 for (unit=0; unit<4; unit++)
4349                         FDCS->track[unit] = 0;
4350                 if (FDCS->address == -1)
4351                         continue;
4352                 FDCS->rawcmd = 2;
4353                 user_reset_fdc(-1, FD_RESET_ALWAYS, 0);
4354
4355                 /* Try to determine the floppy controller type */
4356                 FDCS->version = get_fdc_version();
4357                 if (FDCS->version == FDC_NONE){
4358                         /* free ioports reserved by floppy_grab_irq_and_dma() */
4359                         release_region(FDCS->address, 1);
4360                         release_region(FDCS->address + 2, 1);
4361                         release_region(FDCS->address + 4, 1);
4362                         release_region(0xbe, 1);
4363                         release_region(0x4be, 1);
4364                         FDCS->address = -1;
4365                         continue;
4366                 }
4367                 if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)
4368                         can_use_virtual_dma = 0;
4369
4370                 have_no_fdc = 0;
4371                 /* Not all FDCs seem to be able to handle the version command
4372                  * properly, so force a reset for the standard FDC clones,
4373                  * to avoid interrupt garbage.
4374                  */
4375                 user_reset_fdc(-1,FD_RESET_ALWAYS,0);
4376         }
4377         fdc=0;
4378         del_timer(&fd_timeout);
4379         current_drive = 0;
4380         floppy_release_irq_and_dma();
4381 #if 0  /* no message */
4382         initialising=0;
4383 #endif
4384         if (have_no_fdc) {
4385                 DPRINT("no floppy controllers found\n");
4386                 flush_scheduled_work();
4387                 if (usage_count)
4388                         floppy_release_irq_and_dma();
4389                 err = have_no_fdc;
4390                 goto out2;
4391         }
4392         
4393         for (drive = 0; drive < N_DRIVE; drive++) {
4394                 init_timer(&motor_off_timer[drive]);
4395                 motor_off_timer[drive].data = drive;
4396                 motor_off_timer[drive].function = motor_off_callback;
4397                 if (!(allowed_drive_mask & (1 << drive)))
4398                         continue;
4399                 if (fdc_state[FDC(drive)].version == FDC_NONE)
4400                         continue;
4401                 /* to be cleaned up... */
4402                 disks[drive]->private_data = (void*)(long)drive;
4403                 disks[drive]->queue = floppy_queue;
4404                 add_disk(disks[drive]);
4405         }
4406
4407         platform_device_register(&floppy_device);
4408         return 0;
4409
4410 out1:
4411         del_timer_sync(&fd_timeout);
4412 out2:
4413         blk_cleanup_queue(floppy_queue);
4414 out_queue:
4415         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
4416         unregister_blkdev(FLOPPY_MAJOR,"fd");
4417 out:
4418         for (i=0; i<N_DRIVE; i++)
4419                 put_disk(disks[i]);
4420         return err;
4421
4422 Enomem:
4423         while (i--)
4424                 put_disk(disks[i]);
4425         return -ENOMEM;
4426 }
4427
4428 static spinlock_t floppy_usage_lock = SPIN_LOCK_UNLOCKED;
4429
4430 static int floppy_grab_irq_and_dma(void)
4431 {
4432         unsigned long flags;
4433
4434         spin_lock_irqsave(&floppy_usage_lock, flags);
4435         if (usage_count++){
4436                 spin_unlock_irqrestore(&floppy_usage_lock, flags);
4437                 return 0;
4438         }
4439         spin_unlock_irqrestore(&floppy_usage_lock, flags);
4440         if (fd_request_irq()) {
4441                 DPRINT("Unable to grab IRQ%d for the floppy driver\n",
4442                         FLOPPY_IRQ);
4443                 spin_lock_irqsave(&floppy_usage_lock, flags);
4444                 usage_count--;
4445                 spin_unlock_irqrestore(&floppy_usage_lock, flags);
4446                 return -1;
4447         }
4448         if (fd_request_dma()) {
4449                 DPRINT("Unable to grab DMA%d for the floppy driver\n",
4450                         FLOPPY_DMA);
4451                 fd_free_irq();
4452                 spin_lock_irqsave(&floppy_usage_lock, flags);
4453                 usage_count--;
4454                 spin_unlock_irqrestore(&floppy_usage_lock, flags);
4455                 return -1;
4456         }
4457
4458         for (fdc=0; fdc< N_FDC; fdc++){
4459                 if (FDCS->address != -1){
4460                         static char floppy[] = "floppy";
4461                         if (!request_region(FDCS->address, 1, floppy))
4462                                 goto cleanup0;
4463
4464                         if (!request_region(FDCS->address + 2, 1, floppy)) {
4465                                 release_region(FDCS->address, 1);
4466                                 goto cleanup0;
4467                         }
4468
4469                         if (!request_region(FDCS->address + 4, 1, floppy)) {
4470                                 release_region(FDCS->address, 1);
4471                                 release_region(FDCS->address + 2, 1);
4472                                 goto cleanup0;
4473                         }
4474
4475                         if (fdc == 0) {  /* internal FDC */
4476                                 if (request_region(0xbe, 1, "floppy mode change")) {
4477                                         if (request_region(0x4be, 1, "floppy ex. mode change"))
4478                                                 continue;
4479                                         else
4480                                                 DPRINT("Floppy io-port 0x4be in use\n");
4481
4482                                         release_region(0xbe, 1);
4483                                 } else
4484                                         DPRINT("Floppy io-port 0xbe in use\n");
4485
4486                                 release_region(FDCS->address, 1);
4487                                 release_region(FDCS->address + 2, 1);
4488                                 release_region(FDCS->address + 4, 1);
4489                         }
4490
4491                         goto cleanup1;
4492                 }
4493         }
4494         for (fdc=0; fdc< N_FDC; fdc++){
4495                 if (FDCS->address != -1){
4496                         reset_fdc_info(1);
4497                         fd_outb(FDCS->dor, FD_MODE);
4498                 }
4499         }
4500         fdc = 0;
4501         fd_outb((FDCS->dor & 8), FD_MODE);
4502
4503         for (fdc = 0; fdc < N_FDC; fdc++)
4504                 if (FDCS->address != -1)
4505                         fd_outb(FDCS->dor, FD_MODE);
4506         /*
4507          *      The driver will try and free resources and relies on us
4508          *      to know if they were allocated or not.
4509          */
4510         fdc = 0;
4511         irqdma_allocated = 1;
4512         return 0;
4513
4514 cleanup0:
4515         DPRINT("Floppy io-port 0x%04lx in use\n", FDCS->address);
4516 cleanup1:
4517         fd_free_irq();
4518         fd_free_dma();
4519         while(--fdc >= 0) {
4520                 release_region(FDCS->address, 1);
4521                 release_region(FDCS->address + 2, 1);
4522                 release_region(FDCS->address + 4, 1);
4523                 if (fdc == 0) {
4524                         release_region(0x00be, 1);
4525                         release_region(0x04be, 1);
4526                 }
4527         }
4528         spin_lock_irqsave(&floppy_usage_lock, flags);
4529         usage_count--;
4530         spin_unlock_irqrestore(&floppy_usage_lock, flags);
4531         return -1;
4532 }
4533
4534 static void floppy_release_irq_and_dma(void)
4535 {
4536         int old_fdc;
4537 #ifdef FLOPPY_SANITY_CHECK
4538         int drive;
4539 #endif
4540         long tmpsize;
4541         unsigned long tmpaddr;
4542         unsigned long flags;
4543
4544         spin_lock_irqsave(&floppy_usage_lock, flags);
4545         if (--usage_count){
4546                 spin_unlock_irqrestore(&floppy_usage_lock, flags);
4547                 return;
4548         }
4549         spin_unlock_irqrestore(&floppy_usage_lock, flags);
4550         if(irqdma_allocated)
4551         {
4552                 fd_disable_dma();
4553                 fd_free_dma();
4554                 fd_free_irq();
4555                 irqdma_allocated=0;
4556         }
4557         fd_outb(0, FD_MODE);
4558         floppy_enable_hlt();
4559
4560         if (floppy_track_buffer && max_buffer_sectors) {
4561                 tmpsize = max_buffer_sectors*1024;
4562                 tmpaddr = (unsigned long)floppy_track_buffer;
4563                 floppy_track_buffer = NULL;
4564                 max_buffer_sectors = 0;
4565                 buffer_min = buffer_max = -1;
4566                 fd_dma_mem_free(tmpaddr, tmpsize);
4567         }
4568
4569 #ifdef FLOPPY_SANITY_CHECK
4570         for (drive=0; drive < N_FDC * 4; drive++)
4571                 if (timer_pending(motor_off_timer + drive))
4572                         printk("motor off timer %d still active\n", drive);
4573
4574         if (timer_pending(&fd_timeout))
4575                 printk("floppy timer still active:%s\n", timeout_message);
4576         if (timer_pending(&fd_timer))
4577                 printk("auxiliary floppy timer still active\n");
4578         if (floppy_work.pending)
4579                 printk("work still pending\n");
4580 #endif
4581         old_fdc = fdc;
4582         for (fdc = 0; fdc < N_FDC; fdc++)
4583                 if (FDCS->address != -1) {
4584                         release_region(FDCS->address, 1);
4585                         release_region(FDCS->address + 2, 1);
4586                         release_region(FDCS->address + 4, 1);
4587                         if (fdc == 0) {
4588                                 release_region(0xbe, 1);
4589                                 release_region(0x4be, 1);
4590                         }
4591                 }
4592         fdc = old_fdc;
4593 }
4594
4595
4596 #ifdef MODULE
4597
4598 char *floppy;
4599
4600 static void unregister_devfs_entries (int drive)
4601 {
4602     int i;
4603
4604     if (UDP->cmos < NUMBER(default_drive_params)) {
4605         i = 0;
4606         do {
4607             devfs_remove("floppy/%d%s", drive, table[table_sup[UDP->cmos][i]]);
4608         } while (table_sup[UDP->cmos][i++]);
4609     }
4610 }
4611
4612 static void __init parse_floppy_cfg_string(char *cfg)
4613 {
4614         char *ptr;
4615
4616         while(*cfg) {
4617                 for(ptr = cfg;*cfg && *cfg != ' ' && *cfg != '\t'; cfg++);
4618                 if (*cfg) {
4619                         *cfg = '\0';
4620                         cfg++;
4621                 }
4622                 if (*ptr)
4623                         floppy_setup(ptr);
4624         }
4625 }
4626
4627 int init_module(void)
4628 {
4629         printk(KERN_INFO "inserting floppy driver for " UTS_RELEASE "\n");
4630                 
4631         if (floppy)
4632                 parse_floppy_cfg_string(floppy);
4633         return floppy_init();
4634 }
4635
4636 void cleanup_module(void)
4637 {
4638         int drive;
4639                 
4640         init_completion(&device_release);
4641         platform_device_unregister(&floppy_device);
4642         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
4643         unregister_blkdev(FLOPPY_MAJOR, "fd");
4644
4645         for (drive = 0; drive < N_DRIVE; drive++) {
4646                 del_timer_sync(&motor_off_timer[drive]);
4647
4648                 if ((allowed_drive_mask & (1 << drive)) &&
4649                     fdc_state[FDC(drive)].version != FDC_NONE) {
4650                         del_gendisk(disks[drive]);
4651                         unregister_devfs_entries(drive);
4652                 }
4653                 put_disk(disks[drive]);
4654         }
4655         devfs_remove("floppy");
4656
4657         del_timer_sync(&fd_timeout);
4658         del_timer_sync(&fd_timer);
4659         blk_cleanup_queue(floppy_queue);
4660
4661         if (usage_count)
4662                 floppy_release_irq_and_dma();
4663
4664         /* eject disk, if any */
4665         fd_eject(0);
4666
4667         wait_for_completion(&device_release);
4668 }
4669
4670 MODULE_PARM(floppy,"s");
4671 MODULE_PARM(FLOPPY_IRQ,"i");
4672 MODULE_PARM(FLOPPY_DMA,"i");
4673 MODULE_AUTHOR("Osamu Tomita");
4674 MODULE_SUPPORTED_DEVICE("fd");
4675 MODULE_LICENSE("GPL");
4676
4677 #else
4678
4679 __setup ("floppy=", floppy_setup);
4680 module_init(floppy_init)
4681 #endif