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