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