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