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