76a08236430a0f1d2e6ca02ad347433115d7145e
[firefly-linux-kernel-4.4.55.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/string.h>
182 #include <linux/jiffies.h>
183 #include <linux/fcntl.h>
184 #include <linux/delay.h>
185 #include <linux/mc146818rtc.h>  /* CMOS defines */
186 #include <linux/ioport.h>
187 #include <linux/interrupt.h>
188 #include <linux/init.h>
189 #include <linux/platform_device.h>
190 #include <linux/mod_devicetable.h>
191 #include <linux/mutex.h>
192 #include <linux/io.h>
193 #include <linux/uaccess.h>
194
195 /*
196  * PS/2 floppies have much slower step rates than regular floppies.
197  * It's been recommended that take about 1/4 of the default speed
198  * in some more extreme cases.
199  */
200 static DEFINE_MUTEX(floppy_mutex);
201 static int slow_floppy;
202
203 #include <asm/dma.h>
204 #include <asm/irq.h>
205
206 static int FLOPPY_IRQ = 6;
207 static int FLOPPY_DMA = 2;
208 static int can_use_virtual_dma = 2;
209 /* =======
210  * can use virtual DMA:
211  * 0 = use of virtual DMA disallowed by config
212  * 1 = use of virtual DMA prescribed by config
213  * 2 = no virtual DMA preference configured.  By default try hard DMA,
214  * but fall back on virtual DMA when not enough memory available
215  */
216
217 static int use_virtual_dma;
218 /* =======
219  * use virtual DMA
220  * 0 using hard DMA
221  * 1 using virtual DMA
222  * This variable is set to virtual when a DMA mem problem arises, and
223  * reset back in floppy_grab_irq_and_dma.
224  * It is not safe to reset it in other circumstances, because the floppy
225  * driver may have several buffers in use at once, and we do currently not
226  * record each buffers capabilities
227  */
228
229 static DEFINE_SPINLOCK(floppy_lock);
230
231 static unsigned short virtual_dma_port = 0x3f0;
232 irqreturn_t floppy_interrupt(int irq, void *dev_id);
233 static int set_dor(int fdc, char mask, char data);
234
235 #define K_64    0x10000         /* 64KB */
236
237 /* the following is the mask of allowed drives. By default units 2 and
238  * 3 of both floppy controllers are disabled, because switching on the
239  * motor of these drives causes system hangs on some PCI computers. drive
240  * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if
241  * a drive is allowed.
242  *
243  * NOTE: This must come before we include the arch floppy header because
244  *       some ports reference this variable from there. -DaveM
245  */
246
247 static int allowed_drive_mask = 0x33;
248
249 #include <asm/floppy.h>
250
251 static int irqdma_allocated;
252
253 #include <linux/blkdev.h>
254 #include <linux/blkpg.h>
255 #include <linux/cdrom.h>        /* for the compatibility eject ioctl */
256 #include <linux/completion.h>
257
258 static struct request *current_req;
259 static void do_fd_request(struct request_queue *q);
260 static int set_next_request(void);
261
262 #ifndef fd_get_dma_residue
263 #define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)
264 #endif
265
266 /* Dma Memory related stuff */
267
268 #ifndef fd_dma_mem_free
269 #define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))
270 #endif
271
272 #ifndef fd_dma_mem_alloc
273 #define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size))
274 #endif
275
276 static inline void fallback_on_nodma_alloc(char **addr, size_t l)
277 {
278 #ifdef FLOPPY_CAN_FALLBACK_ON_NODMA
279         if (*addr)
280                 return;         /* we have the memory */
281         if (can_use_virtual_dma != 2)
282                 return;         /* no fallback allowed */
283         pr_info("DMA memory shortage. Temporarily falling back on virtual DMA\n");
284         *addr = (char *)nodma_mem_alloc(l);
285 #else
286         return;
287 #endif
288 }
289
290 /* End dma memory related stuff */
291
292 static unsigned long fake_change;
293 static bool initialized;
294
295 #define ITYPE(x)        (((x) >> 2) & 0x1f)
296 #define TOMINOR(x)      ((x & 3) | ((x & 4) << 5))
297 #define UNIT(x)         ((x) & 0x03)            /* drive on fdc */
298 #define FDC(x)          (((x) & 0x04) >> 2)     /* fdc of drive */
299         /* reverse mapping from unit and fdc to drive */
300 #define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))
301
302 #define DP      (&drive_params[current_drive])
303 #define DRS     (&drive_state[current_drive])
304 #define DRWE    (&write_errors[current_drive])
305 #define FDCS    (&fdc_state[fdc])
306
307 #define UDP     (&drive_params[drive])
308 #define UDRS    (&drive_state[drive])
309 #define UDRWE   (&write_errors[drive])
310 #define UFDCS   (&fdc_state[FDC(drive)])
311
312 #define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2)
313 #define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH)
314
315 /* read/write */
316 #define COMMAND         (raw_cmd->cmd[0])
317 #define DR_SELECT       (raw_cmd->cmd[1])
318 #define TRACK           (raw_cmd->cmd[2])
319 #define HEAD            (raw_cmd->cmd[3])
320 #define SECTOR          (raw_cmd->cmd[4])
321 #define SIZECODE        (raw_cmd->cmd[5])
322 #define SECT_PER_TRACK  (raw_cmd->cmd[6])
323 #define GAP             (raw_cmd->cmd[7])
324 #define SIZECODE2       (raw_cmd->cmd[8])
325 #define NR_RW 9
326
327 /* format */
328 #define F_SIZECODE      (raw_cmd->cmd[2])
329 #define F_SECT_PER_TRACK (raw_cmd->cmd[3])
330 #define F_GAP           (raw_cmd->cmd[4])
331 #define F_FILL          (raw_cmd->cmd[5])
332 #define NR_F 6
333
334 /*
335  * Maximum disk size (in kilobytes).
336  * This default is used whenever the current disk size is unknown.
337  * [Now it is rather a minimum]
338  */
339 #define MAX_DISK_SIZE 4         /* 3984 */
340
341 /*
342  * globals used by 'result()'
343  */
344 #define MAX_REPLIES 16
345 static unsigned char reply_buffer[MAX_REPLIES];
346 static int inr;         /* size of reply buffer, when called from interrupt */
347 #define ST0             (reply_buffer[0])
348 #define ST1             (reply_buffer[1])
349 #define ST2             (reply_buffer[2])
350 #define ST3             (reply_buffer[0])       /* result of GETSTATUS */
351 #define R_TRACK         (reply_buffer[3])
352 #define R_HEAD          (reply_buffer[4])
353 #define R_SECTOR        (reply_buffer[5])
354 #define R_SIZECODE      (reply_buffer[6])
355
356 #define SEL_DLY         (2 * HZ / 100)
357
358 /*
359  * this struct defines the different floppy drive types.
360  */
361 static struct {
362         struct floppy_drive_params params;
363         const char *name;       /* name printed while booting */
364 } default_drive_params[] = {
365 /* NOTE: the time values in jiffies should be in msec!
366  CMOS drive type
367   |     Maximum data rate supported by drive type
368   |     |   Head load time, msec
369   |     |   |   Head unload time, msec (not used)
370   |     |   |   |     Step rate interval, usec
371   |     |   |   |     |       Time needed for spinup time (jiffies)
372   |     |   |   |     |       |      Timeout for spinning down (jiffies)
373   |     |   |   |     |       |      |   Spindown offset (where disk stops)
374   |     |   |   |     |       |      |   |     Select delay
375   |     |   |   |     |       |      |   |     |     RPS
376   |     |   |   |     |       |      |   |     |     |    Max number of tracks
377   |     |   |   |     |       |      |   |     |     |    |     Interrupt timeout
378   |     |   |   |     |       |      |   |     |     |    |     |   Max nonintlv. sectors
379   |     |   |   |     |       |      |   |     |     |    |     |   | -Max Errors- flags */
380 {{0,  500, 16, 16, 8000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  80, 3*HZ, 20, {3,1,2,0,2}, 0,
381       0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" },
382
383 {{1,  300, 16, 16, 8000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  40, 3*HZ, 17, {3,1,2,0,2}, 0,
384       0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/
385
386 {{2,  500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6,  83, 3*HZ, 17, {3,1,2,0,2}, 0,
387       0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/
388
389 {{3,  250, 16, 16, 3000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  83, 3*HZ, 20, {3,1,2,0,2}, 0,
390       0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/
391
392 {{4,  500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 20, {3,1,2,0,2}, 0,
393       0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/
394
395 {{5, 1000, 15,  8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 40, {3,1,2,0,2}, 0,
396       0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/
397
398 {{6, 1000, 15,  8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 40, {3,1,2,0,2}, 0,
399       0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/
400 /*    |  --autodetected formats---    |      |      |
401  *    read_track                      |      |    Name printed when booting
402  *                                    |     Native format
403  *                  Frequency of disk change checks */
404 };
405
406 static struct floppy_drive_params drive_params[N_DRIVE];
407 static struct floppy_drive_struct drive_state[N_DRIVE];
408 static struct floppy_write_errors write_errors[N_DRIVE];
409 static struct timer_list motor_off_timer[N_DRIVE];
410 static struct gendisk *disks[N_DRIVE];
411 static struct block_device *opened_bdev[N_DRIVE];
412 static DEFINE_MUTEX(open_lock);
413 static struct floppy_raw_cmd *raw_cmd, default_raw_cmd;
414 static int fdc_queue;
415
416 /*
417  * This struct defines the different floppy types.
418  *
419  * Bit 0 of 'stretch' tells if the tracks need to be doubled for some
420  * types (e.g. 360kB diskette in 1.2MB drive, etc.).  Bit 1 of 'stretch'
421  * tells if the disk is in Commodore 1581 format, which means side 0 sectors
422  * are located on side 1 of the disk but with a side 0 ID, and vice-versa.
423  * This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the
424  * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical
425  * side 0 is on physical side 0 (but with the misnamed sector IDs).
426  * 'stretch' should probably be renamed to something more general, like
427  * 'options'.
428  *
429  * Bits 2 through 9 of 'stretch' tell the number of the first sector.
430  * The LSB (bit 2) is flipped. For most disks, the first sector
431  * is 1 (represented by 0x00<<2).  For some CP/M and music sampler
432  * disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2).
433  * For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2).
434  *
435  * Other parameters should be self-explanatory (see also setfdprm(8)).
436  */
437 /*
438             Size
439              |  Sectors per track
440              |  | Head
441              |  | |  Tracks
442              |  | |  | Stretch
443              |  | |  | |  Gap 1 size
444              |  | |  | |    |  Data rate, | 0x40 for perp
445              |  | |  | |    |    |  Spec1 (stepping rate, head unload
446              |  | |  | |    |    |    |    /fmt gap (gap2) */
447 static struct floppy_struct floppy_type[32] = {
448         {    0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL    }, /*  0 no testing    */
449         {  720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360"  }, /*  1 360KB PC      */
450         { 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /*  2 1.2MB AT      */
451         {  720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360"  }, /*  3 360KB SS 3.5" */
452         { 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720"  }, /*  4 720KB 3.5"    */
453         {  720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360"  }, /*  5 360KB AT      */
454         { 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720"  }, /*  6 720KB AT      */
455         { 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /*  7 1.44MB 3.5"   */
456         { 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /*  8 2.88MB 3.5"   */
457         { 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /*  9 3.12MB 3.5"   */
458
459         { 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25"  */
460         { 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5"   */
461         {  820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410"  }, /* 12 410KB 5.25"   */
462         { 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820"  }, /* 13 820KB 3.5"    */
463         { 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25"  */
464         { 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5"   */
465         {  840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420"  }, /* 16 420KB 5.25"   */
466         { 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830"  }, /* 17 830KB 3.5"    */
467         { 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25"  */
468         { 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5"  */
469
470         { 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880"  }, /* 20 880KB 5.25"   */
471         { 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5"   */
472         { 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5"   */
473         { 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25"   */
474         { 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5"   */
475         { 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5"   */
476         { 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5"   */
477         { 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5"   */
478         { 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5"   */
479         { 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5"   */
480
481         { 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800"  }, /* 30 800KB 3.5"    */
482         { 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5"    */
483 };
484
485 #define SECTSIZE (_FD_SECTSIZE(*floppy))
486
487 /* Auto-detection: Disk type used until the next media change occurs. */
488 static struct floppy_struct *current_type[N_DRIVE];
489
490 /*
491  * User-provided type information. current_type points to
492  * the respective entry of this array.
493  */
494 static struct floppy_struct user_params[N_DRIVE];
495
496 static sector_t floppy_sizes[256];
497
498 static char floppy_device_name[] = "floppy";
499
500 /*
501  * The driver is trying to determine the correct media format
502  * while probing is set. rw_interrupt() clears it after a
503  * successful access.
504  */
505 static int probing;
506
507 /* Synchronization of FDC access. */
508 #define FD_COMMAND_NONE         -1
509 #define FD_COMMAND_ERROR        2
510 #define FD_COMMAND_OKAY         3
511
512 static volatile int command_status = FD_COMMAND_NONE;
513 static unsigned long fdc_busy;
514 static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
515 static DECLARE_WAIT_QUEUE_HEAD(command_done);
516
517 /* Errors during formatting are counted here. */
518 static int format_errors;
519
520 /* Format request descriptor. */
521 static struct format_descr format_req;
522
523 /*
524  * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps
525  * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),
526  * H is head unload time (1=16ms, 2=32ms, etc)
527  */
528
529 /*
530  * Track buffer
531  * Because these are written to by the DMA controller, they must
532  * not contain a 64k byte boundary crossing, or data will be
533  * corrupted/lost.
534  */
535 static char *floppy_track_buffer;
536 static int max_buffer_sectors;
537
538 static int *errors;
539 typedef void (*done_f)(int);
540 static const struct cont_t {
541         void (*interrupt)(void);
542                                 /* this is called after the interrupt of the
543                                  * main command */
544         void (*redo)(void);     /* this is called to retry the operation */
545         void (*error)(void);    /* this is called to tally an error */
546         done_f done;            /* this is called to say if the operation has
547                                  * succeeded/failed */
548 } *cont;
549
550 static void floppy_ready(void);
551 static void floppy_start(void);
552 static void process_fd_request(void);
553 static void recalibrate_floppy(void);
554 static void floppy_shutdown(unsigned long);
555
556 static int floppy_request_regions(int);
557 static void floppy_release_regions(int);
558 static int floppy_grab_irq_and_dma(void);
559 static void floppy_release_irq_and_dma(void);
560
561 /*
562  * The "reset" variable should be tested whenever an interrupt is scheduled,
563  * after the commands have been sent. This is to ensure that the driver doesn't
564  * get wedged when the interrupt doesn't come because of a failed command.
565  * reset doesn't need to be tested before sending commands, because
566  * output_byte is automatically disabled when reset is set.
567  */
568 static void reset_fdc(void);
569
570 /*
571  * These are global variables, as that's the easiest way to give
572  * information to interrupts. They are the data used for the current
573  * request.
574  */
575 #define NO_TRACK        -1
576 #define NEED_1_RECAL    -2
577 #define NEED_2_RECAL    -3
578
579 static atomic_t usage_count = ATOMIC_INIT(0);
580
581 /* buffer related variables */
582 static int buffer_track = -1;
583 static int buffer_drive = -1;
584 static int buffer_min = -1;
585 static int buffer_max = -1;
586
587 /* fdc related variables, should end up in a struct */
588 static struct floppy_fdc_state fdc_state[N_FDC];
589 static int fdc;                 /* current fdc */
590
591 static struct floppy_struct *_floppy = floppy_type;
592 static unsigned char current_drive;
593 static long current_count_sectors;
594 static unsigned char fsector_t; /* sector in track */
595 static unsigned char in_sector_offset;  /* offset within physical sector,
596                                          * expressed in units of 512 bytes */
597
598 static inline bool drive_no_geom(int drive)
599 {
600         return !current_type[drive] && !ITYPE(UDRS->fd_device);
601 }
602
603 #ifndef fd_eject
604 static inline int fd_eject(int drive)
605 {
606         return -EINVAL;
607 }
608 #endif
609
610 /*
611  * Debugging
612  * =========
613  */
614 #ifdef DEBUGT
615 static long unsigned debugtimer;
616
617 static inline void set_debugt(void)
618 {
619         debugtimer = jiffies;
620 }
621
622 static inline void debugt(const char *func, const char *msg)
623 {
624         if (DP->flags & DEBUGT)
625                 pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer);
626 }
627 #else
628 static inline void set_debugt(void) { }
629 static inline void debugt(const char *func, const char *msg) { }
630 #endif /* DEBUGT */
631
632 typedef void (*timeout_fn)(unsigned long);
633 static DEFINE_TIMER(fd_timeout, floppy_shutdown, 0, 0);
634
635 static const char *timeout_message;
636
637 static void is_alive(const char *func, const char *message)
638 {
639         /* this routine checks whether the floppy driver is "alive" */
640         if (test_bit(0, &fdc_busy) && command_status < 2 &&
641             !timer_pending(&fd_timeout)) {
642                 DPRINT("%s: timeout handler died.  %s\n", func, message);
643         }
644 }
645
646 static void (*do_floppy)(void) = NULL;
647
648 #define OLOGSIZE 20
649
650 static void (*lasthandler)(void);
651 static unsigned long interruptjiffies;
652 static unsigned long resultjiffies;
653 static int resultsize;
654 static unsigned long lastredo;
655
656 static struct output_log {
657         unsigned char data;
658         unsigned char status;
659         unsigned long jiffies;
660 } output_log[OLOGSIZE];
661
662 static int output_log_pos;
663
664 #define current_reqD -1
665 #define MAXTIMEOUT -2
666
667 static void __reschedule_timeout(int drive, const char *message)
668 {
669         if (drive == current_reqD)
670                 drive = current_drive;
671         del_timer(&fd_timeout);
672         if (drive < 0 || drive >= N_DRIVE) {
673                 fd_timeout.expires = jiffies + 20UL * HZ;
674                 drive = 0;
675         } else
676                 fd_timeout.expires = jiffies + UDP->timeout;
677         add_timer(&fd_timeout);
678         if (UDP->flags & FD_DEBUG)
679                 DPRINT("reschedule timeout %s\n", message);
680         timeout_message = message;
681 }
682
683 static void reschedule_timeout(int drive, const char *message)
684 {
685         unsigned long flags;
686
687         spin_lock_irqsave(&floppy_lock, flags);
688         __reschedule_timeout(drive, message);
689         spin_unlock_irqrestore(&floppy_lock, flags);
690 }
691
692 #define INFBOUND(a, b) (a) = max_t(int, a, b)
693 #define SUPBOUND(a, b) (a) = min_t(int, a, b)
694
695 /*
696  * Bottom half floppy driver.
697  * ==========================
698  *
699  * This part of the file contains the code talking directly to the hardware,
700  * and also the main service loop (seek-configure-spinup-command)
701  */
702
703 /*
704  * disk change.
705  * This routine is responsible for maintaining the FD_DISK_CHANGE flag,
706  * and the last_checked date.
707  *
708  * last_checked is the date of the last check which showed 'no disk change'
709  * FD_DISK_CHANGE is set under two conditions:
710  * 1. The floppy has been changed after some i/o to that floppy already
711  *    took place.
712  * 2. No floppy disk is in the drive. This is done in order to ensure that
713  *    requests are quickly flushed in case there is no disk in the drive. It
714  *    follows that FD_DISK_CHANGE can only be cleared if there is a disk in
715  *    the drive.
716  *
717  * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.
718  * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on
719  *  each seek. If a disk is present, the disk change line should also be
720  *  cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk
721  *  change line is set, this means either that no disk is in the drive, or
722  *  that it has been removed since the last seek.
723  *
724  * This means that we really have a third possibility too:
725  *  The floppy has been changed after the last seek.
726  */
727
728 static int disk_change(int drive)
729 {
730         int fdc = FDC(drive);
731
732         if (time_before(jiffies, UDRS->select_date + UDP->select_delay))
733                 DPRINT("WARNING disk change called early\n");
734         if (!(FDCS->dor & (0x10 << UNIT(drive))) ||
735             (FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) {
736                 DPRINT("probing disk change on unselected drive\n");
737                 DPRINT("drive=%d fdc=%d dor=%x\n", drive, FDC(drive),
738                        (unsigned int)FDCS->dor);
739         }
740
741         debug_dcl(UDP->flags,
742                   "checking disk change line for drive %d\n", drive);
743         debug_dcl(UDP->flags, "jiffies=%lu\n", jiffies);
744         debug_dcl(UDP->flags, "disk change line=%x\n", fd_inb(FD_DIR) & 0x80);
745         debug_dcl(UDP->flags, "flags=%lx\n", UDRS->flags);
746
747         if (UDP->flags & FD_BROKEN_DCL)
748                 return test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
749         if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) {
750                 set_bit(FD_VERIFY_BIT, &UDRS->flags);
751                                         /* verify write protection */
752
753                 if (UDRS->maxblock)     /* mark it changed */
754                         set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
755
756                 /* invalidate its geometry */
757                 if (UDRS->keep_data >= 0) {
758                         if ((UDP->flags & FTD_MSG) &&
759                             current_type[drive] != NULL)
760                                 DPRINT("Disk type is undefined after disk change\n");
761                         current_type[drive] = NULL;
762                         floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1;
763                 }
764
765                 return 1;
766         } else {
767                 UDRS->last_checked = jiffies;
768                 clear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);
769         }
770         return 0;
771 }
772
773 static inline int is_selected(int dor, int unit)
774 {
775         return ((dor & (0x10 << unit)) && (dor & 3) == unit);
776 }
777
778 static bool is_ready_state(int status)
779 {
780         int state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA);
781         return state == STATUS_READY;
782 }
783
784 static int set_dor(int fdc, char mask, char data)
785 {
786         unsigned char unit;
787         unsigned char drive;
788         unsigned char newdor;
789         unsigned char olddor;
790
791         if (FDCS->address == -1)
792                 return -1;
793
794         olddor = FDCS->dor;
795         newdor = (olddor & mask) | data;
796         if (newdor != olddor) {
797                 unit = olddor & 0x3;
798                 if (is_selected(olddor, unit) && !is_selected(newdor, unit)) {
799                         drive = REVDRIVE(fdc, unit);
800                         debug_dcl(UDP->flags,
801                                   "calling disk change from set_dor\n");
802                         disk_change(drive);
803                 }
804                 FDCS->dor = newdor;
805                 fd_outb(newdor, FD_DOR);
806
807                 unit = newdor & 0x3;
808                 if (!is_selected(olddor, unit) && is_selected(newdor, unit)) {
809                         drive = REVDRIVE(fdc, unit);
810                         UDRS->select_date = jiffies;
811                 }
812         }
813         return olddor;
814 }
815
816 static void twaddle(void)
817 {
818         if (DP->select_delay)
819                 return;
820         fd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR);
821         fd_outb(FDCS->dor, FD_DOR);
822         DRS->select_date = jiffies;
823 }
824
825 /*
826  * Reset all driver information about the current fdc.
827  * This is needed after a reset, and after a raw command.
828  */
829 static void reset_fdc_info(int mode)
830 {
831         int drive;
832
833         FDCS->spec1 = FDCS->spec2 = -1;
834         FDCS->need_configure = 1;
835         FDCS->perp_mode = 1;
836         FDCS->rawcmd = 0;
837         for (drive = 0; drive < N_DRIVE; drive++)
838                 if (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL))
839                         UDRS->track = NEED_2_RECAL;
840 }
841
842 /* selects the fdc and drive, and enables the fdc's input/dma. */
843 static void set_fdc(int drive)
844 {
845         if (drive >= 0 && drive < N_DRIVE) {
846                 fdc = FDC(drive);
847                 current_drive = drive;
848         }
849         if (fdc != 1 && fdc != 0) {
850                 pr_info("bad fdc value\n");
851                 return;
852         }
853         set_dor(fdc, ~0, 8);
854 #if N_FDC > 1
855         set_dor(1 - fdc, ~8, 0);
856 #endif
857         if (FDCS->rawcmd == 2)
858                 reset_fdc_info(1);
859         if (fd_inb(FD_STATUS) != STATUS_READY)
860                 FDCS->reset = 1;
861 }
862
863 /* locks the driver */
864 static int lock_fdc(int drive, bool interruptible)
865 {
866         if (WARN(atomic_read(&usage_count) == 0,
867                  "Trying to lock fdc while usage count=0\n"))
868                 return -1;
869
870         if (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy)))
871                 return -EINTR;
872
873         command_status = FD_COMMAND_NONE;
874
875         __reschedule_timeout(drive, "lock fdc");
876         set_fdc(drive);
877         return 0;
878 }
879
880 /* unlocks the driver */
881 static void unlock_fdc(void)
882 {
883         unsigned long flags;
884
885         raw_cmd = NULL;
886         if (!test_bit(0, &fdc_busy))
887                 DPRINT("FDC access conflict!\n");
888
889         if (do_floppy)
890                 DPRINT("device interrupt still active at FDC release: %pf!\n",
891                        do_floppy);
892         command_status = FD_COMMAND_NONE;
893         spin_lock_irqsave(&floppy_lock, flags);
894         del_timer(&fd_timeout);
895         cont = NULL;
896         clear_bit(0, &fdc_busy);
897         if (current_req || set_next_request())
898                 do_fd_request(current_req->q);
899         spin_unlock_irqrestore(&floppy_lock, flags);
900         wake_up(&fdc_wait);
901 }
902
903 /* switches the motor off after a given timeout */
904 static void motor_off_callback(unsigned long nr)
905 {
906         unsigned char mask = ~(0x10 << UNIT(nr));
907
908         set_dor(FDC(nr), mask, 0);
909 }
910
911 /* schedules motor off */
912 static void floppy_off(unsigned int drive)
913 {
914         unsigned long volatile delta;
915         int fdc = FDC(drive);
916
917         if (!(FDCS->dor & (0x10 << UNIT(drive))))
918                 return;
919
920         del_timer(motor_off_timer + drive);
921
922         /* make spindle stop in a position which minimizes spinup time
923          * next time */
924         if (UDP->rps) {
925                 delta = jiffies - UDRS->first_read_date + HZ -
926                     UDP->spindown_offset;
927                 delta = ((delta * UDP->rps) % HZ) / UDP->rps;
928                 motor_off_timer[drive].expires =
929                     jiffies + UDP->spindown - delta;
930         }
931         add_timer(motor_off_timer + drive);
932 }
933
934 /*
935  * cycle through all N_DRIVE floppy drives, for disk change testing.
936  * stopping at current drive. This is done before any long operation, to
937  * be sure to have up to date disk change information.
938  */
939 static void scandrives(void)
940 {
941         int i;
942         int drive;
943         int saved_drive;
944
945         if (DP->select_delay)
946                 return;
947
948         saved_drive = current_drive;
949         for (i = 0; i < N_DRIVE; i++) {
950                 drive = (saved_drive + i + 1) % N_DRIVE;
951                 if (UDRS->fd_ref == 0 || UDP->select_delay != 0)
952                         continue;       /* skip closed drives */
953                 set_fdc(drive);
954                 if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) &
955                       (0x10 << UNIT(drive))))
956                         /* switch the motor off again, if it was off to
957                          * begin with */
958                         set_dor(fdc, ~(0x10 << UNIT(drive)), 0);
959         }
960         set_fdc(saved_drive);
961 }
962
963 static void empty(void)
964 {
965 }
966
967 static DECLARE_WORK(floppy_work, NULL);
968
969 static void schedule_bh(void (*handler)(void))
970 {
971         PREPARE_WORK(&floppy_work, (work_func_t)handler);
972         schedule_work(&floppy_work);
973 }
974
975 static DEFINE_TIMER(fd_timer, NULL, 0, 0);
976
977 static void cancel_activity(void)
978 {
979         unsigned long flags;
980
981         spin_lock_irqsave(&floppy_lock, flags);
982         do_floppy = NULL;
983         PREPARE_WORK(&floppy_work, (work_func_t)empty);
984         del_timer(&fd_timer);
985         spin_unlock_irqrestore(&floppy_lock, flags);
986 }
987
988 /* this function makes sure that the disk stays in the drive during the
989  * transfer */
990 static void fd_watchdog(void)
991 {
992         debug_dcl(DP->flags, "calling disk change from watchdog\n");
993
994         if (disk_change(current_drive)) {
995                 DPRINT("disk removed during i/o\n");
996                 cancel_activity();
997                 cont->done(0);
998                 reset_fdc();
999         } else {
1000                 del_timer(&fd_timer);
1001                 fd_timer.function = (timeout_fn)fd_watchdog;
1002                 fd_timer.expires = jiffies + HZ / 10;
1003                 add_timer(&fd_timer);
1004         }
1005 }
1006
1007 static void main_command_interrupt(void)
1008 {
1009         del_timer(&fd_timer);
1010         cont->interrupt();
1011 }
1012
1013 /* waits for a delay (spinup or select) to pass */
1014 static int fd_wait_for_completion(unsigned long delay, timeout_fn function)
1015 {
1016         if (FDCS->reset) {
1017                 reset_fdc();    /* do the reset during sleep to win time
1018                                  * if we don't need to sleep, it's a good
1019                                  * occasion anyways */
1020                 return 1;
1021         }
1022
1023         if (time_before(jiffies, delay)) {
1024                 del_timer(&fd_timer);
1025                 fd_timer.function = function;
1026                 fd_timer.expires = delay;
1027                 add_timer(&fd_timer);
1028                 return 1;
1029         }
1030         return 0;
1031 }
1032
1033 static DEFINE_SPINLOCK(floppy_hlt_lock);
1034 static int hlt_disabled;
1035 static void floppy_disable_hlt(void)
1036 {
1037         unsigned long flags;
1038
1039         WARN_ONCE(1, "floppy_disable_hlt() scheduled for removal in 2012");
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 *req = current_req;
2252         struct request_queue *q;
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         q = req->q;
2267
2268         if (uptodate) {
2269                 /* maintain values for invalidation on geometry
2270                  * change */
2271                 block = current_count_sectors + blk_rq_pos(req);
2272                 INFBOUND(DRS->maxblock, block);
2273                 if (block > _floppy->sect)
2274                         DRS->maxtrack = 1;
2275
2276                 /* unlock chained buffers */
2277                 spin_lock_irqsave(q->queue_lock, flags);
2278                 floppy_end_request(req, 0);
2279                 spin_unlock_irqrestore(q->queue_lock, flags);
2280         } else {
2281                 if (rq_data_dir(req) == WRITE) {
2282                         /* record write error information */
2283                         DRWE->write_errors++;
2284                         if (DRWE->write_errors == 1) {
2285                                 DRWE->first_error_sector = blk_rq_pos(req);
2286                                 DRWE->first_error_generation = DRS->generation;
2287                         }
2288                         DRWE->last_error_sector = blk_rq_pos(req);
2289                         DRWE->last_error_generation = DRS->generation;
2290                 }
2291                 spin_lock_irqsave(q->queue_lock, flags);
2292                 floppy_end_request(req, -EIO);
2293                 spin_unlock_irqrestore(q->queue_lock, flags);
2294         }
2295 }
2296
2297 /* Interrupt handler evaluating the result of the r/w operation */
2298 static void rw_interrupt(void)
2299 {
2300         int eoc;
2301         int ssize;
2302         int heads;
2303         int nr_sectors;
2304
2305         if (R_HEAD >= 2) {
2306                 /* some Toshiba floppy controllers occasionnally seem to
2307                  * return bogus interrupts after read/write operations, which
2308                  * can be recognized by a bad head number (>= 2) */
2309                 return;
2310         }
2311
2312         if (!DRS->first_read_date)
2313                 DRS->first_read_date = jiffies;
2314
2315         nr_sectors = 0;
2316         ssize = DIV_ROUND_UP(1 << SIZECODE, 4);
2317
2318         if (ST1 & ST1_EOC)
2319                 eoc = 1;
2320         else
2321                 eoc = 0;
2322
2323         if (COMMAND & 0x80)
2324                 heads = 2;
2325         else
2326                 heads = 1;
2327
2328         nr_sectors = (((R_TRACK - TRACK) * heads +
2329                        R_HEAD - HEAD) * SECT_PER_TRACK +
2330                       R_SECTOR - SECTOR + eoc) << SIZECODE >> 2;
2331
2332         if (nr_sectors / ssize >
2333             DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) {
2334                 DPRINT("long rw: %x instead of %lx\n",
2335                        nr_sectors, current_count_sectors);
2336                 pr_info("rs=%d s=%d\n", R_SECTOR, SECTOR);
2337                 pr_info("rh=%d h=%d\n", R_HEAD, HEAD);
2338                 pr_info("rt=%d t=%d\n", R_TRACK, TRACK);
2339                 pr_info("heads=%d eoc=%d\n", heads, eoc);
2340                 pr_info("spt=%d st=%d ss=%d\n",
2341                         SECT_PER_TRACK, fsector_t, ssize);
2342                 pr_info("in_sector_offset=%d\n", in_sector_offset);
2343         }
2344
2345         nr_sectors -= in_sector_offset;
2346         INFBOUND(nr_sectors, 0);
2347         SUPBOUND(current_count_sectors, nr_sectors);
2348
2349         switch (interpret_errors()) {
2350         case 2:
2351                 cont->redo();
2352                 return;
2353         case 1:
2354                 if (!current_count_sectors) {
2355                         cont->error();
2356                         cont->redo();
2357                         return;
2358                 }
2359                 break;
2360         case 0:
2361                 if (!current_count_sectors) {
2362                         cont->redo();
2363                         return;
2364                 }
2365                 current_type[current_drive] = _floppy;
2366                 floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
2367                 break;
2368         }
2369
2370         if (probing) {
2371                 if (DP->flags & FTD_MSG)
2372                         DPRINT("Auto-detected floppy type %s in fd%d\n",
2373                                _floppy->name, current_drive);
2374                 current_type[current_drive] = _floppy;
2375                 floppy_sizes[TOMINOR(current_drive)] = _floppy->size;
2376                 probing = 0;
2377         }
2378
2379         if (CT(COMMAND) != FD_READ ||
2380             raw_cmd->kernel_data == current_req->buffer) {
2381                 /* transfer directly from buffer */
2382                 cont->done(1);
2383         } else if (CT(COMMAND) == FD_READ) {
2384                 buffer_track = raw_cmd->track;
2385                 buffer_drive = current_drive;
2386                 INFBOUND(buffer_max, nr_sectors + fsector_t);
2387         }
2388         cont->redo();
2389 }
2390
2391 /* Compute maximal contiguous buffer size. */
2392 static int buffer_chain_size(void)
2393 {
2394         struct bio_vec *bv;
2395         int size;
2396         struct req_iterator iter;
2397         char *base;
2398
2399         base = bio_data(current_req->bio);
2400         size = 0;
2401
2402         rq_for_each_segment(bv, current_req, iter) {
2403                 if (page_address(bv->bv_page) + bv->bv_offset != base + size)
2404                         break;
2405
2406                 size += bv->bv_len;
2407         }
2408
2409         return size >> 9;
2410 }
2411
2412 /* Compute the maximal transfer size */
2413 static int transfer_size(int ssize, int max_sector, int max_size)
2414 {
2415         SUPBOUND(max_sector, fsector_t + max_size);
2416
2417         /* alignment */
2418         max_sector -= (max_sector % _floppy->sect) % ssize;
2419
2420         /* transfer size, beginning not aligned */
2421         current_count_sectors = max_sector - fsector_t;
2422
2423         return max_sector;
2424 }
2425
2426 /*
2427  * Move data from/to the track buffer to/from the buffer cache.
2428  */
2429 static void copy_buffer(int ssize, int max_sector, int max_sector_2)
2430 {
2431         int remaining;          /* number of transferred 512-byte sectors */
2432         struct bio_vec *bv;
2433         char *buffer;
2434         char *dma_buffer;
2435         int size;
2436         struct req_iterator iter;
2437
2438         max_sector = transfer_size(ssize,
2439                                    min(max_sector, max_sector_2),
2440                                    blk_rq_sectors(current_req));
2441
2442         if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&
2443             buffer_max > fsector_t + blk_rq_sectors(current_req))
2444                 current_count_sectors = min_t(int, buffer_max - fsector_t,
2445                                               blk_rq_sectors(current_req));
2446
2447         remaining = current_count_sectors << 9;
2448         if (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) {
2449                 DPRINT("in copy buffer\n");
2450                 pr_info("current_count_sectors=%ld\n", current_count_sectors);
2451                 pr_info("remaining=%d\n", remaining >> 9);
2452                 pr_info("current_req->nr_sectors=%u\n",
2453                         blk_rq_sectors(current_req));
2454                 pr_info("current_req->current_nr_sectors=%u\n",
2455                         blk_rq_cur_sectors(current_req));
2456                 pr_info("max_sector=%d\n", max_sector);
2457                 pr_info("ssize=%d\n", ssize);
2458         }
2459
2460         buffer_max = max(max_sector, buffer_max);
2461
2462         dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9);
2463
2464         size = blk_rq_cur_bytes(current_req);
2465
2466         rq_for_each_segment(bv, current_req, iter) {
2467                 if (!remaining)
2468                         break;
2469
2470                 size = bv->bv_len;
2471                 SUPBOUND(size, remaining);
2472
2473                 buffer = page_address(bv->bv_page) + bv->bv_offset;
2474                 if (dma_buffer + size >
2475                     floppy_track_buffer + (max_buffer_sectors << 10) ||
2476                     dma_buffer < floppy_track_buffer) {
2477                         DPRINT("buffer overrun in copy buffer %d\n",
2478                                (int)((floppy_track_buffer - dma_buffer) >> 9));
2479                         pr_info("fsector_t=%d buffer_min=%d\n",
2480                                 fsector_t, buffer_min);
2481                         pr_info("current_count_sectors=%ld\n",
2482                                 current_count_sectors);
2483                         if (CT(COMMAND) == FD_READ)
2484                                 pr_info("read\n");
2485                         if (CT(COMMAND) == FD_WRITE)
2486                                 pr_info("write\n");
2487                         break;
2488                 }
2489                 if (((unsigned long)buffer) % 512)
2490                         DPRINT("%p buffer not aligned\n", buffer);
2491
2492                 if (CT(COMMAND) == FD_READ)
2493                         memcpy(buffer, dma_buffer, size);
2494                 else
2495                         memcpy(dma_buffer, buffer, size);
2496
2497                 remaining -= size;
2498                 dma_buffer += size;
2499         }
2500         if (remaining) {
2501                 if (remaining > 0)
2502                         max_sector -= remaining >> 9;
2503                 DPRINT("weirdness: remaining %d\n", remaining >> 9);
2504         }
2505 }
2506
2507 /* work around a bug in pseudo DMA
2508  * (on some FDCs) pseudo DMA does not stop when the CPU stops
2509  * sending data.  Hence we need a different way to signal the
2510  * transfer length:  We use SECT_PER_TRACK.  Unfortunately, this
2511  * does not work with MT, hence we can only transfer one head at
2512  * a time
2513  */
2514 static void virtualdmabug_workaround(void)
2515 {
2516         int hard_sectors;
2517         int end_sector;
2518
2519         if (CT(COMMAND) == FD_WRITE) {
2520                 COMMAND &= ~0x80;       /* switch off multiple track mode */
2521
2522                 hard_sectors = raw_cmd->length >> (7 + SIZECODE);
2523                 end_sector = SECTOR + hard_sectors - 1;
2524                 if (end_sector > SECT_PER_TRACK) {
2525                         pr_info("too many sectors %d > %d\n",
2526                                 end_sector, SECT_PER_TRACK);
2527                         return;
2528                 }
2529                 SECT_PER_TRACK = end_sector;
2530                                         /* make sure SECT_PER_TRACK
2531                                          * points to end of transfer */
2532         }
2533 }
2534
2535 /*
2536  * Formulate a read/write request.
2537  * this routine decides where to load the data (directly to buffer, or to
2538  * tmp floppy area), how much data to load (the size of the buffer, the whole
2539  * track, or a single sector)
2540  * All floppy_track_buffer handling goes in here. If we ever add track buffer
2541  * allocation on the fly, it should be done here. No other part should need
2542  * modification.
2543  */
2544
2545 static int make_raw_rw_request(void)
2546 {
2547         int aligned_sector_t;
2548         int max_sector;
2549         int max_size;
2550         int tracksize;
2551         int ssize;
2552
2553         if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n"))
2554                 return 0;
2555
2556         set_fdc((long)current_req->rq_disk->private_data);
2557
2558         raw_cmd = &default_raw_cmd;
2559         raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_DISK |
2560             FD_RAW_NEED_SEEK;
2561         raw_cmd->cmd_count = NR_RW;
2562         if (rq_data_dir(current_req) == READ) {
2563                 raw_cmd->flags |= FD_RAW_READ;
2564                 COMMAND = FM_MODE(_floppy, FD_READ);
2565         } else if (rq_data_dir(current_req) == WRITE) {
2566                 raw_cmd->flags |= FD_RAW_WRITE;
2567                 COMMAND = FM_MODE(_floppy, FD_WRITE);
2568         } else {
2569                 DPRINT("%s: unknown command\n", __func__);
2570                 return 0;
2571         }
2572
2573         max_sector = _floppy->sect * _floppy->head;
2574
2575         TRACK = (int)blk_rq_pos(current_req) / max_sector;
2576         fsector_t = (int)blk_rq_pos(current_req) % max_sector;
2577         if (_floppy->track && TRACK >= _floppy->track) {
2578                 if (blk_rq_cur_sectors(current_req) & 1) {
2579                         current_count_sectors = 1;
2580                         return 1;
2581                 } else
2582                         return 0;
2583         }
2584         HEAD = fsector_t / _floppy->sect;
2585
2586         if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) ||
2587              test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) &&
2588             fsector_t < _floppy->sect)
2589                 max_sector = _floppy->sect;
2590
2591         /* 2M disks have phantom sectors on the first track */
2592         if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) {
2593                 max_sector = 2 * _floppy->sect / 3;
2594                 if (fsector_t >= max_sector) {
2595                         current_count_sectors =
2596                             min_t(int, _floppy->sect - fsector_t,
2597                                   blk_rq_sectors(current_req));
2598                         return 1;
2599                 }
2600                 SIZECODE = 2;
2601         } else
2602                 SIZECODE = FD_SIZECODE(_floppy);
2603         raw_cmd->rate = _floppy->rate & 0x43;
2604         if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2)
2605                 raw_cmd->rate = 1;
2606
2607         if (SIZECODE)
2608                 SIZECODE2 = 0xff;
2609         else
2610                 SIZECODE2 = 0x80;
2611         raw_cmd->track = TRACK << STRETCH(_floppy);
2612         DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD);
2613         GAP = _floppy->gap;
2614         ssize = DIV_ROUND_UP(1 << SIZECODE, 4);
2615         SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;
2616         SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) +
2617             FD_SECTBASE(_floppy);
2618
2619         /* tracksize describes the size which can be filled up with sectors
2620          * of size ssize.
2621          */
2622         tracksize = _floppy->sect - _floppy->sect % ssize;
2623         if (tracksize < _floppy->sect) {
2624                 SECT_PER_TRACK++;
2625                 if (tracksize <= fsector_t % _floppy->sect)
2626                         SECTOR--;
2627
2628                 /* if we are beyond tracksize, fill up using smaller sectors */
2629                 while (tracksize <= fsector_t % _floppy->sect) {
2630                         while (tracksize + ssize > _floppy->sect) {
2631                                 SIZECODE--;
2632                                 ssize >>= 1;
2633                         }
2634                         SECTOR++;
2635                         SECT_PER_TRACK++;
2636                         tracksize += ssize;
2637                 }
2638                 max_sector = HEAD * _floppy->sect + tracksize;
2639         } else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {
2640                 max_sector = _floppy->sect;
2641         } else if (!HEAD && CT(COMMAND) == FD_WRITE) {
2642                 /* for virtual DMA bug workaround */
2643                 max_sector = _floppy->sect;
2644         }
2645
2646         in_sector_offset = (fsector_t % _floppy->sect) % ssize;
2647         aligned_sector_t = fsector_t - in_sector_offset;
2648         max_size = blk_rq_sectors(current_req);
2649         if ((raw_cmd->track == buffer_track) &&
2650             (current_drive == buffer_drive) &&
2651             (fsector_t >= buffer_min) && (fsector_t < buffer_max)) {
2652                 /* data already in track buffer */
2653                 if (CT(COMMAND) == FD_READ) {
2654                         copy_buffer(1, max_sector, buffer_max);
2655                         return 1;
2656                 }
2657         } else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) {
2658                 if (CT(COMMAND) == FD_WRITE) {
2659                         unsigned int sectors;
2660
2661                         sectors = fsector_t + blk_rq_sectors(current_req);
2662                         if (sectors > ssize && sectors < ssize + ssize)
2663                                 max_size = ssize + ssize;
2664                         else
2665                                 max_size = ssize;
2666                 }
2667                 raw_cmd->flags &= ~FD_RAW_WRITE;
2668                 raw_cmd->flags |= FD_RAW_READ;
2669                 COMMAND = FM_MODE(_floppy, FD_READ);
2670         } else if ((unsigned long)current_req->buffer < MAX_DMA_ADDRESS) {
2671                 unsigned long dma_limit;
2672                 int direct, indirect;
2673
2674                 indirect =
2675                     transfer_size(ssize, max_sector,
2676                                   max_buffer_sectors * 2) - fsector_t;
2677
2678                 /*
2679                  * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide
2680                  * on a 64 bit machine!
2681                  */
2682                 max_size = buffer_chain_size();
2683                 dma_limit = (MAX_DMA_ADDRESS -
2684                              ((unsigned long)current_req->buffer)) >> 9;
2685                 if ((unsigned long)max_size > dma_limit)
2686                         max_size = dma_limit;
2687                 /* 64 kb boundaries */
2688                 if (CROSS_64KB(current_req->buffer, max_size << 9))
2689                         max_size = (K_64 -
2690                                     ((unsigned long)current_req->buffer) %
2691                                     K_64) >> 9;
2692                 direct = transfer_size(ssize, max_sector, max_size) - fsector_t;
2693                 /*
2694                  * We try to read tracks, but if we get too many errors, we
2695                  * go back to reading just one sector at a time.
2696                  *
2697                  * This means we should be able to read a sector even if there
2698                  * are other bad sectors on this track.
2699                  */
2700                 if (!direct ||
2701                     (indirect * 2 > direct * 3 &&
2702                      *errors < DP->max_errors.read_track &&
2703                      ((!probing ||
2704                        (DP->read_track & (1 << DRS->probed_format)))))) {
2705                         max_size = blk_rq_sectors(current_req);
2706                 } else {
2707                         raw_cmd->kernel_data = current_req->buffer;
2708                         raw_cmd->length = current_count_sectors << 9;
2709                         if (raw_cmd->length == 0) {
2710                                 DPRINT("%s: zero dma transfer attempted\n", __func__);
2711                                 DPRINT("indirect=%d direct=%d fsector_t=%d\n",
2712                                        indirect, direct, fsector_t);
2713                                 return 0;
2714                         }
2715                         virtualdmabug_workaround();
2716                         return 2;
2717                 }
2718         }
2719
2720         if (CT(COMMAND) == FD_READ)
2721                 max_size = max_sector;  /* unbounded */
2722
2723         /* claim buffer track if needed */
2724         if (buffer_track != raw_cmd->track ||   /* bad track */
2725             buffer_drive != current_drive ||    /* bad drive */
2726             fsector_t > buffer_max ||
2727             fsector_t < buffer_min ||
2728             ((CT(COMMAND) == FD_READ ||
2729               (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) &&
2730              max_sector > 2 * max_buffer_sectors + buffer_min &&
2731              max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) {
2732                 /* not enough space */
2733                 buffer_track = -1;
2734                 buffer_drive = current_drive;
2735                 buffer_max = buffer_min = aligned_sector_t;
2736         }
2737         raw_cmd->kernel_data = floppy_track_buffer +
2738                 ((aligned_sector_t - buffer_min) << 9);
2739
2740         if (CT(COMMAND) == FD_WRITE) {
2741                 /* copy write buffer to track buffer.
2742                  * if we get here, we know that the write
2743                  * is either aligned or the data already in the buffer
2744                  * (buffer will be overwritten) */
2745                 if (in_sector_offset && buffer_track == -1)
2746                         DPRINT("internal error offset !=0 on write\n");
2747                 buffer_track = raw_cmd->track;
2748                 buffer_drive = current_drive;
2749                 copy_buffer(ssize, max_sector,
2750                             2 * max_buffer_sectors + buffer_min);
2751         } else
2752                 transfer_size(ssize, max_sector,
2753                               2 * max_buffer_sectors + buffer_min -
2754                               aligned_sector_t);
2755
2756         /* round up current_count_sectors to get dma xfer size */
2757         raw_cmd->length = in_sector_offset + current_count_sectors;
2758         raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1;
2759         raw_cmd->length <<= 9;
2760         if ((raw_cmd->length < current_count_sectors << 9) ||
2761             (raw_cmd->kernel_data != current_req->buffer &&
2762              CT(COMMAND) == FD_WRITE &&
2763              (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||
2764               aligned_sector_t < buffer_min)) ||
2765             raw_cmd->length % (128 << SIZECODE) ||
2766             raw_cmd->length <= 0 || current_count_sectors <= 0) {
2767                 DPRINT("fractionary current count b=%lx s=%lx\n",
2768                        raw_cmd->length, current_count_sectors);
2769                 if (raw_cmd->kernel_data != current_req->buffer)
2770                         pr_info("addr=%d, length=%ld\n",
2771                                 (int)((raw_cmd->kernel_data -
2772                                        floppy_track_buffer) >> 9),
2773                                 current_count_sectors);
2774                 pr_info("st=%d ast=%d mse=%d msi=%d\n",
2775                         fsector_t, aligned_sector_t, max_sector, max_size);
2776                 pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE);
2777                 pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n",
2778                         COMMAND, SECTOR, HEAD, TRACK);
2779                 pr_info("buffer drive=%d\n", buffer_drive);
2780                 pr_info("buffer track=%d\n", buffer_track);
2781                 pr_info("buffer_min=%d\n", buffer_min);
2782                 pr_info("buffer_max=%d\n", buffer_max);
2783                 return 0;
2784         }
2785
2786         if (raw_cmd->kernel_data != current_req->buffer) {
2787                 if (raw_cmd->kernel_data < floppy_track_buffer ||
2788                     current_count_sectors < 0 ||
2789                     raw_cmd->length < 0 ||
2790                     raw_cmd->kernel_data + raw_cmd->length >
2791                     floppy_track_buffer + (max_buffer_sectors << 10)) {
2792                         DPRINT("buffer overrun in schedule dma\n");
2793                         pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n",
2794                                 fsector_t, buffer_min, raw_cmd->length >> 9);
2795                         pr_info("current_count_sectors=%ld\n",
2796                                 current_count_sectors);
2797                         if (CT(COMMAND) == FD_READ)
2798                                 pr_info("read\n");
2799                         if (CT(COMMAND) == FD_WRITE)
2800                                 pr_info("write\n");
2801                         return 0;
2802                 }
2803         } else if (raw_cmd->length > blk_rq_bytes(current_req) ||
2804                    current_count_sectors > blk_rq_sectors(current_req)) {
2805                 DPRINT("buffer overrun in direct transfer\n");
2806                 return 0;
2807         } else if (raw_cmd->length < current_count_sectors << 9) {
2808                 DPRINT("more sectors than bytes\n");
2809                 pr_info("bytes=%ld\n", raw_cmd->length >> 9);
2810                 pr_info("sectors=%ld\n", current_count_sectors);
2811         }
2812         if (raw_cmd->length == 0) {
2813                 DPRINT("zero dma transfer attempted from make_raw_request\n");
2814                 return 0;
2815         }
2816
2817         virtualdmabug_workaround();
2818         return 2;
2819 }
2820
2821 /*
2822  * Round-robin between our available drives, doing one request from each
2823  */
2824 static int set_next_request(void)
2825 {
2826         struct request_queue *q;
2827         int old_pos = fdc_queue;
2828
2829         do {
2830                 q = disks[fdc_queue]->queue;
2831                 if (++fdc_queue == N_DRIVE)
2832                         fdc_queue = 0;
2833                 if (q) {
2834                         current_req = blk_fetch_request(q);
2835                         if (current_req)
2836                                 break;
2837                 }
2838         } while (fdc_queue != old_pos);
2839
2840         return current_req != NULL;
2841 }
2842
2843 static void redo_fd_request(void)
2844 {
2845         int drive;
2846         int tmp;
2847
2848         lastredo = jiffies;
2849         if (current_drive < N_DRIVE)
2850                 floppy_off(current_drive);
2851
2852 do_request:
2853         if (!current_req) {
2854                 int pending;
2855
2856                 spin_lock_irq(&floppy_lock);
2857                 pending = set_next_request();
2858                 spin_unlock_irq(&floppy_lock);
2859
2860                 if (!pending) {
2861                         do_floppy = NULL;
2862                         unlock_fdc();
2863                         return;
2864                 }
2865         }
2866         drive = (long)current_req->rq_disk->private_data;
2867         set_fdc(drive);
2868         reschedule_timeout(current_reqD, "redo fd request");
2869
2870         set_floppy(drive);
2871         raw_cmd = &default_raw_cmd;
2872         raw_cmd->flags = 0;
2873         if (start_motor(redo_fd_request))
2874                 return;
2875
2876         disk_change(current_drive);
2877         if (test_bit(current_drive, &fake_change) ||
2878             test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) {
2879                 DPRINT("disk absent or changed during operation\n");
2880                 request_done(0);
2881                 goto do_request;
2882         }
2883         if (!_floppy) { /* Autodetection */
2884                 if (!probing) {
2885                         DRS->probed_format = 0;
2886                         if (next_valid_format()) {
2887                                 DPRINT("no autodetectable formats\n");
2888                                 _floppy = NULL;
2889                                 request_done(0);
2890                                 goto do_request;
2891                         }
2892                 }
2893                 probing = 1;
2894                 _floppy = floppy_type + DP->autodetect[DRS->probed_format];
2895         } else
2896                 probing = 0;
2897         errors = &(current_req->errors);
2898         tmp = make_raw_rw_request();
2899         if (tmp < 2) {
2900                 request_done(tmp);
2901                 goto do_request;
2902         }
2903
2904         if (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags))
2905                 twaddle();
2906         schedule_bh(floppy_start);
2907         debugt(__func__, "queue fd request");
2908         return;
2909 }
2910
2911 static const struct cont_t rw_cont = {
2912         .interrupt      = rw_interrupt,
2913         .redo           = redo_fd_request,
2914         .error          = bad_flp_intr,
2915         .done           = request_done
2916 };
2917
2918 static void process_fd_request(void)
2919 {
2920         cont = &rw_cont;
2921         schedule_bh(redo_fd_request);
2922 }
2923
2924 static void do_fd_request(struct request_queue *q)
2925 {
2926         if (WARN(max_buffer_sectors == 0,
2927                  "VFS: %s called on non-open device\n", __func__))
2928                 return;
2929
2930         if (WARN(atomic_read(&usage_count) == 0,
2931                  "warning: usage count=0, current_req=%p sect=%ld type=%x flags=%x\n",
2932                  current_req, (long)blk_rq_pos(current_req), current_req->cmd_type,
2933                  current_req->cmd_flags))
2934                 return;
2935
2936         if (test_bit(0, &fdc_busy)) {
2937                 /* fdc busy, this new request will be treated when the
2938                    current one is done */
2939                 is_alive(__func__, "old request running");
2940                 return;
2941         }
2942         lock_fdc(MAXTIMEOUT, false);
2943         process_fd_request();
2944         is_alive(__func__, "");
2945 }
2946
2947 static const struct cont_t poll_cont = {
2948         .interrupt      = success_and_wakeup,
2949         .redo           = floppy_ready,
2950         .error          = generic_failure,
2951         .done           = generic_done
2952 };
2953
2954 static int poll_drive(bool interruptible, int flag)
2955 {
2956         /* no auto-sense, just clear dcl */
2957         raw_cmd = &default_raw_cmd;
2958         raw_cmd->flags = flag;
2959         raw_cmd->track = 0;
2960         raw_cmd->cmd_count = 0;
2961         cont = &poll_cont;
2962         debug_dcl(DP->flags, "setting NEWCHANGE in poll_drive\n");
2963         set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags);
2964
2965         return wait_til_done(floppy_ready, interruptible);
2966 }
2967
2968 /*
2969  * User triggered reset
2970  * ====================
2971  */
2972
2973 static void reset_intr(void)
2974 {
2975         pr_info("weird, reset interrupt called\n");
2976 }
2977
2978 static const struct cont_t reset_cont = {
2979         .interrupt      = reset_intr,
2980         .redo           = success_and_wakeup,
2981         .error          = generic_failure,
2982         .done           = generic_done
2983 };
2984
2985 static int user_reset_fdc(int drive, int arg, bool interruptible)
2986 {
2987         int ret;
2988
2989         if (lock_fdc(drive, interruptible))
2990                 return -EINTR;
2991
2992         if (arg == FD_RESET_ALWAYS)
2993                 FDCS->reset = 1;
2994         if (FDCS->reset) {
2995                 cont = &reset_cont;
2996                 ret = wait_til_done(reset_fdc, interruptible);
2997                 if (ret == -EINTR)
2998                         return -EINTR;
2999         }
3000         process_fd_request();
3001         return 0;
3002 }
3003
3004 /*
3005  * Misc Ioctl's and support
3006  * ========================
3007  */
3008 static inline int fd_copyout(void __user *param, const void *address,
3009                              unsigned long size)
3010 {
3011         return copy_to_user(param, address, size) ? -EFAULT : 0;
3012 }
3013
3014 static inline int fd_copyin(void __user *param, void *address,
3015                             unsigned long size)
3016 {
3017         return copy_from_user(address, param, size) ? -EFAULT : 0;
3018 }
3019
3020 static const char *drive_name(int type, int drive)
3021 {
3022         struct floppy_struct *floppy;
3023
3024         if (type)
3025                 floppy = floppy_type + type;
3026         else {
3027                 if (UDP->native_format)
3028                         floppy = floppy_type + UDP->native_format;
3029                 else
3030                         return "(null)";
3031         }
3032         if (floppy->name)
3033                 return floppy->name;
3034         else
3035                 return "(null)";
3036 }
3037
3038 /* raw commands */
3039 static void raw_cmd_done(int flag)
3040 {
3041         int i;
3042
3043         if (!flag) {
3044                 raw_cmd->flags |= FD_RAW_FAILURE;
3045                 raw_cmd->flags |= FD_RAW_HARDFAILURE;
3046         } else {
3047                 raw_cmd->reply_count = inr;
3048                 if (raw_cmd->reply_count > MAX_REPLIES)
3049                         raw_cmd->reply_count = 0;
3050                 for (i = 0; i < raw_cmd->reply_count; i++)
3051                         raw_cmd->reply[i] = reply_buffer[i];
3052
3053                 if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
3054                         unsigned long flags;
3055                         flags = claim_dma_lock();
3056                         raw_cmd->length = fd_get_dma_residue();
3057                         release_dma_lock(flags);
3058                 }
3059
3060                 if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&
3061                     (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))
3062                         raw_cmd->flags |= FD_RAW_FAILURE;
3063
3064                 if (disk_change(current_drive))
3065                         raw_cmd->flags |= FD_RAW_DISK_CHANGE;
3066                 else
3067                         raw_cmd->flags &= ~FD_RAW_DISK_CHANGE;
3068                 if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)
3069                         motor_off_callback(current_drive);
3070
3071                 if (raw_cmd->next &&
3072                     (!(raw_cmd->flags & FD_RAW_FAILURE) ||
3073                      !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&
3074                     ((raw_cmd->flags & FD_RAW_FAILURE) ||
3075                      !(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) {
3076                         raw_cmd = raw_cmd->next;
3077                         return;
3078                 }
3079         }
3080         generic_done(flag);
3081 }
3082
3083 static const struct cont_t raw_cmd_cont = {
3084         .interrupt      = success_and_wakeup,
3085         .redo           = floppy_start,
3086         .error          = generic_failure,
3087         .done           = raw_cmd_done
3088 };
3089
3090 static int raw_cmd_copyout(int cmd, void __user *param,
3091                                   struct floppy_raw_cmd *ptr)
3092 {
3093         int ret;
3094
3095         while (ptr) {
3096                 ret = copy_to_user(param, ptr, sizeof(*ptr));
3097                 if (ret)
3098                         return -EFAULT;
3099                 param += sizeof(struct floppy_raw_cmd);
3100                 if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) {
3101                         if (ptr->length >= 0 &&
3102                             ptr->length <= ptr->buffer_length) {
3103                                 long length = ptr->buffer_length - ptr->length;
3104                                 ret = fd_copyout(ptr->data, ptr->kernel_data,
3105                                                  length);
3106                                 if (ret)
3107                                         return ret;
3108                         }
3109                 }
3110                 ptr = ptr->next;
3111         }
3112
3113         return 0;
3114 }
3115
3116 static void raw_cmd_free(struct floppy_raw_cmd **ptr)
3117 {
3118         struct floppy_raw_cmd *next;
3119         struct floppy_raw_cmd *this;
3120
3121         this = *ptr;
3122         *ptr = NULL;
3123         while (this) {
3124                 if (this->buffer_length) {
3125                         fd_dma_mem_free((unsigned long)this->kernel_data,
3126                                         this->buffer_length);
3127                         this->buffer_length = 0;
3128                 }
3129                 next = this->next;
3130                 kfree(this);
3131                 this = next;
3132         }
3133 }
3134
3135 static int raw_cmd_copyin(int cmd, void __user *param,
3136                                  struct floppy_raw_cmd **rcmd)
3137 {
3138         struct floppy_raw_cmd *ptr;
3139         int ret;
3140         int i;
3141
3142         *rcmd = NULL;
3143
3144 loop:
3145         ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);
3146         if (!ptr)
3147                 return -ENOMEM;
3148         *rcmd = ptr;
3149         ret = copy_from_user(ptr, param, sizeof(*ptr));
3150         if (ret)
3151                 return -EFAULT;
3152         ptr->next = NULL;
3153         ptr->buffer_length = 0;
3154         param += sizeof(struct floppy_raw_cmd);
3155         if (ptr->cmd_count > 33)
3156                         /* the command may now also take up the space
3157                          * initially intended for the reply & the
3158                          * reply count. Needed for long 82078 commands
3159                          * such as RESTORE, which takes ... 17 command
3160                          * bytes. Murphy's law #137: When you reserve
3161                          * 16 bytes for a structure, you'll one day
3162                          * discover that you really need 17...
3163                          */
3164                 return -EINVAL;
3165
3166         for (i = 0; i < 16; i++)
3167                 ptr->reply[i] = 0;
3168         ptr->resultcode = 0;
3169         ptr->kernel_data = NULL;
3170
3171         if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
3172                 if (ptr->length <= 0)
3173                         return -EINVAL;
3174                 ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length);
3175                 fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length);
3176                 if (!ptr->kernel_data)
3177                         return -ENOMEM;
3178                 ptr->buffer_length = ptr->length;
3179         }
3180         if (ptr->flags & FD_RAW_WRITE) {
3181                 ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length);
3182                 if (ret)
3183                         return ret;
3184         }
3185
3186         if (ptr->flags & FD_RAW_MORE) {
3187                 rcmd = &(ptr->next);
3188                 ptr->rate &= 0x43;
3189                 goto loop;
3190         }
3191
3192         return 0;
3193 }
3194
3195 static int raw_cmd_ioctl(int cmd, void __user *param)
3196 {
3197         struct floppy_raw_cmd *my_raw_cmd;
3198         int drive;
3199         int ret2;
3200         int ret;
3201
3202         if (FDCS->rawcmd <= 1)
3203                 FDCS->rawcmd = 1;
3204         for (drive = 0; drive < N_DRIVE; drive++) {
3205                 if (FDC(drive) != fdc)
3206                         continue;
3207                 if (drive == current_drive) {
3208                         if (UDRS->fd_ref > 1) {
3209                                 FDCS->rawcmd = 2;
3210                                 break;
3211                         }
3212                 } else if (UDRS->fd_ref) {
3213                         FDCS->rawcmd = 2;
3214                         break;
3215                 }
3216         }
3217
3218         if (FDCS->reset)
3219                 return -EIO;
3220
3221         ret = raw_cmd_copyin(cmd, param, &my_raw_cmd);
3222         if (ret) {
3223                 raw_cmd_free(&my_raw_cmd);
3224                 return ret;
3225         }
3226
3227         raw_cmd = my_raw_cmd;
3228         cont = &raw_cmd_cont;
3229         ret = wait_til_done(floppy_start, true);
3230         debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n");
3231
3232         if (ret != -EINTR && FDCS->reset)
3233                 ret = -EIO;
3234
3235         DRS->track = NO_TRACK;
3236
3237         ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);
3238         if (!ret)
3239                 ret = ret2;
3240         raw_cmd_free(&my_raw_cmd);
3241         return ret;
3242 }
3243
3244 static int invalidate_drive(struct block_device *bdev)
3245 {
3246         /* invalidate the buffer track to force a reread */
3247         set_bit((long)bdev->bd_disk->private_data, &fake_change);
3248         process_fd_request();
3249         check_disk_change(bdev);
3250         return 0;
3251 }
3252
3253 static int set_geometry(unsigned int cmd, struct floppy_struct *g,
3254                                int drive, int type, struct block_device *bdev)
3255 {
3256         int cnt;
3257
3258         /* sanity checking for parameters. */
3259         if (g->sect <= 0 ||
3260             g->head <= 0 ||
3261             g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
3262             /* check if reserved bits are set */
3263             (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
3264                 return -EINVAL;
3265         if (type) {
3266                 if (!capable(CAP_SYS_ADMIN))
3267                         return -EPERM;
3268                 mutex_lock(&open_lock);
3269                 if (lock_fdc(drive, true)) {
3270                         mutex_unlock(&open_lock);
3271                         return -EINTR;
3272                 }
3273                 floppy_type[type] = *g;
3274                 floppy_type[type].name = "user format";
3275                 for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
3276                         floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
3277                             floppy_type[type].size + 1;
3278                 process_fd_request();
3279                 for (cnt = 0; cnt < N_DRIVE; cnt++) {
3280                         struct block_device *bdev = opened_bdev[cnt];
3281                         if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
3282                                 continue;
3283                         __invalidate_device(bdev, true);
3284                 }
3285                 mutex_unlock(&open_lock);
3286         } else {
3287                 int oldStretch;
3288
3289                 if (lock_fdc(drive, true))
3290                         return -EINTR;
3291                 if (cmd != FDDEFPRM) {
3292                         /* notice a disk change immediately, else
3293                          * we lose our settings immediately*/
3294                         if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
3295                                 return -EINTR;
3296                 }
3297                 oldStretch = g->stretch;
3298                 user_params[drive] = *g;
3299                 if (buffer_drive == drive)
3300                         SUPBOUND(buffer_max, user_params[drive].sect);
3301                 current_type[drive] = &user_params[drive];
3302                 floppy_sizes[drive] = user_params[drive].size;
3303                 if (cmd == FDDEFPRM)
3304                         DRS->keep_data = -1;
3305                 else
3306                         DRS->keep_data = 1;
3307                 /* invalidation. Invalidate only when needed, i.e.
3308                  * when there are already sectors in the buffer cache
3309                  * whose number will change. This is useful, because
3310                  * mtools often changes the geometry of the disk after
3311                  * looking at the boot block */
3312                 if (DRS->maxblock > user_params[drive].sect ||
3313                     DRS->maxtrack ||
3314                     ((user_params[drive].sect ^ oldStretch) &
3315                      (FD_SWAPSIDES | FD_SECTBASEMASK)))
3316                         invalidate_drive(bdev);
3317                 else
3318                         process_fd_request();
3319         }
3320         return 0;
3321 }
3322
3323 /* handle obsolete ioctl's */
3324 static unsigned int ioctl_table[] = {
3325         FDCLRPRM,
3326         FDSETPRM,
3327         FDDEFPRM,
3328         FDGETPRM,
3329         FDMSGON,
3330         FDMSGOFF,
3331         FDFMTBEG,
3332         FDFMTTRK,
3333         FDFMTEND,
3334         FDSETEMSGTRESH,
3335         FDFLUSH,
3336         FDSETMAXERRS,
3337         FDGETMAXERRS,
3338         FDGETDRVTYP,
3339         FDSETDRVPRM,
3340         FDGETDRVPRM,
3341         FDGETDRVSTAT,
3342         FDPOLLDRVSTAT,
3343         FDRESET,
3344         FDGETFDCSTAT,
3345         FDWERRORCLR,
3346         FDWERRORGET,
3347         FDRAWCMD,
3348         FDEJECT,
3349         FDTWADDLE
3350 };
3351
3352 static int normalize_ioctl(unsigned int *cmd, int *size)
3353 {
3354         int i;
3355
3356         for (i = 0; i < ARRAY_SIZE(ioctl_table); i++) {
3357                 if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) {
3358                         *size = _IOC_SIZE(*cmd);
3359                         *cmd = ioctl_table[i];
3360                         if (*size > _IOC_SIZE(*cmd)) {
3361                                 pr_info("ioctl not yet supported\n");
3362                                 return -EFAULT;
3363                         }
3364                         return 0;
3365                 }
3366         }
3367         return -EINVAL;
3368 }
3369
3370 static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)
3371 {
3372         if (type)
3373                 *g = &floppy_type[type];
3374         else {
3375                 if (lock_fdc(drive, false))
3376                         return -EINTR;
3377                 if (poll_drive(false, 0) == -EINTR)
3378                         return -EINTR;
3379                 process_fd_request();
3380                 *g = current_type[drive];
3381         }
3382         if (!*g)
3383                 return -ENODEV;
3384         return 0;
3385 }
3386
3387 static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
3388 {
3389         int drive = (long)bdev->bd_disk->private_data;
3390         int type = ITYPE(drive_state[drive].fd_device);
3391         struct floppy_struct *g;
3392         int ret;
3393
3394         ret = get_floppy_geometry(drive, type, &g);
3395         if (ret)
3396                 return ret;
3397
3398         geo->heads = g->head;
3399         geo->sectors = g->sect;
3400         geo->cylinders = g->track;
3401         return 0;
3402 }
3403
3404 static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
3405                     unsigned long param)
3406 {
3407         int drive = (long)bdev->bd_disk->private_data;
3408         int type = ITYPE(UDRS->fd_device);
3409         int i;
3410         int ret;
3411         int size;
3412         union inparam {
3413                 struct floppy_struct g; /* geometry */
3414                 struct format_descr f;
3415                 struct floppy_max_errors max_errors;
3416                 struct floppy_drive_params dp;
3417         } inparam;              /* parameters coming from user space */
3418         const void *outparam;   /* parameters passed back to user space */
3419
3420         /* convert compatibility eject ioctls into floppy eject ioctl.
3421          * We do this in order to provide a means to eject floppy disks before
3422          * installing the new fdutils package */
3423         if (cmd == CDROMEJECT ||        /* CD-ROM eject */
3424             cmd == 0x6470) {            /* SunOS floppy eject */
3425                 DPRINT("obsolete eject ioctl\n");
3426                 DPRINT("please use floppycontrol --eject\n");
3427                 cmd = FDEJECT;
3428         }
3429
3430         if (!((cmd & 0xff00) == 0x0200))
3431                 return -EINVAL;
3432
3433         /* convert the old style command into a new style command */
3434         ret = normalize_ioctl(&cmd, &size);
3435         if (ret)
3436                 return ret;
3437
3438         /* permission checks */
3439         if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) ||
3440             ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))
3441                 return -EPERM;
3442
3443         if (WARN_ON(size < 0 || size > sizeof(inparam)))
3444                 return -EINVAL;
3445
3446         /* copyin */
3447         memset(&inparam, 0, sizeof(inparam));
3448         if (_IOC_DIR(cmd) & _IOC_WRITE) {
3449                 ret = fd_copyin((void __user *)param, &inparam, size);
3450                 if (ret)
3451                         return ret;
3452         }
3453
3454         switch (cmd) {
3455         case FDEJECT:
3456                 if (UDRS->fd_ref != 1)
3457                         /* somebody else has this drive open */
3458                         return -EBUSY;
3459                 if (lock_fdc(drive, true))
3460                         return -EINTR;
3461
3462                 /* do the actual eject. Fails on
3463                  * non-Sparc architectures */
3464                 ret = fd_eject(UNIT(drive));
3465
3466                 set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
3467                 set_bit(FD_VERIFY_BIT, &UDRS->flags);
3468                 process_fd_request();
3469                 return ret;
3470         case FDCLRPRM:
3471                 if (lock_fdc(drive, true))
3472                         return -EINTR;
3473                 current_type[drive] = NULL;
3474                 floppy_sizes[drive] = MAX_DISK_SIZE << 1;
3475                 UDRS->keep_data = 0;
3476                 return invalidate_drive(bdev);
3477         case FDSETPRM:
3478         case FDDEFPRM:
3479                 return set_geometry(cmd, &inparam.g, drive, type, bdev);
3480         case FDGETPRM:
3481                 ret = get_floppy_geometry(drive, type,
3482                                           (struct floppy_struct **)&outparam);
3483                 if (ret)
3484                         return ret;
3485                 break;
3486         case FDMSGON:
3487                 UDP->flags |= FTD_MSG;
3488                 return 0;
3489         case FDMSGOFF:
3490                 UDP->flags &= ~FTD_MSG;
3491                 return 0;
3492         case FDFMTBEG:
3493                 if (lock_fdc(drive, true))
3494                         return -EINTR;
3495                 if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
3496                         return -EINTR;
3497                 ret = UDRS->flags;
3498                 process_fd_request();
3499                 if (ret & FD_VERIFY)
3500                         return -ENODEV;
3501                 if (!(ret & FD_DISK_WRITABLE))
3502                         return -EROFS;
3503                 return 0;
3504         case FDFMTTRK:
3505                 if (UDRS->fd_ref != 1)
3506                         return -EBUSY;
3507                 return do_format(drive, &inparam.f);
3508         case FDFMTEND:
3509         case FDFLUSH:
3510                 if (lock_fdc(drive, true))
3511                         return -EINTR;
3512                 return invalidate_drive(bdev);
3513         case FDSETEMSGTRESH:
3514                 UDP->max_errors.reporting = (unsigned short)(param & 0x0f);
3515                 return 0;
3516         case FDGETMAXERRS:
3517                 outparam = &UDP->max_errors;
3518                 break;
3519         case FDSETMAXERRS:
3520                 UDP->max_errors = inparam.max_errors;
3521                 break;
3522         case FDGETDRVTYP:
3523                 outparam = drive_name(type, drive);
3524                 SUPBOUND(size, strlen((const char *)outparam) + 1);
3525                 break;
3526         case FDSETDRVPRM:
3527                 *UDP = inparam.dp;
3528                 break;
3529         case FDGETDRVPRM:
3530                 outparam = UDP;
3531                 break;
3532         case FDPOLLDRVSTAT:
3533                 if (lock_fdc(drive, true))
3534                         return -EINTR;
3535                 if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
3536                         return -EINTR;
3537                 process_fd_request();
3538                 /* fall through */
3539         case FDGETDRVSTAT:
3540                 outparam = UDRS;
3541                 break;
3542         case FDRESET:
3543                 return user_reset_fdc(drive, (int)param, true);
3544         case FDGETFDCSTAT:
3545                 outparam = UFDCS;
3546                 break;
3547         case FDWERRORCLR:
3548                 memset(UDRWE, 0, sizeof(*UDRWE));
3549                 return 0;
3550         case FDWERRORGET:
3551                 outparam = UDRWE;
3552                 break;
3553         case FDRAWCMD:
3554                 if (type)
3555                         return -EINVAL;
3556                 if (lock_fdc(drive, true))
3557                         return -EINTR;
3558                 set_floppy(drive);
3559                 i = raw_cmd_ioctl(cmd, (void __user *)param);
3560                 if (i == -EINTR)
3561                         return -EINTR;
3562                 process_fd_request();
3563                 return i;
3564         case FDTWADDLE:
3565                 if (lock_fdc(drive, true))
3566                         return -EINTR;
3567                 twaddle();
3568                 process_fd_request();
3569                 return 0;
3570         default:
3571                 return -EINVAL;
3572         }
3573
3574         if (_IOC_DIR(cmd) & _IOC_READ)
3575                 return fd_copyout((void __user *)param, outparam, size);
3576
3577         return 0;
3578 }
3579
3580 static int fd_ioctl(struct block_device *bdev, fmode_t mode,
3581                              unsigned int cmd, unsigned long param)
3582 {
3583         int ret;
3584
3585         mutex_lock(&floppy_mutex);
3586         ret = fd_locked_ioctl(bdev, mode, cmd, param);
3587         mutex_unlock(&floppy_mutex);
3588
3589         return ret;
3590 }
3591
3592 static void __init config_types(void)
3593 {
3594         bool has_drive = false;
3595         int drive;
3596
3597         /* read drive info out of physical CMOS */
3598         drive = 0;
3599         if (!UDP->cmos)
3600                 UDP->cmos = FLOPPY0_TYPE;
3601         drive = 1;
3602         if (!UDP->cmos && FLOPPY1_TYPE)
3603                 UDP->cmos = FLOPPY1_TYPE;
3604
3605         /* FIXME: additional physical CMOS drive detection should go here */
3606
3607         for (drive = 0; drive < N_DRIVE; drive++) {
3608                 unsigned int type = UDP->cmos;
3609                 struct floppy_drive_params *params;
3610                 const char *name = NULL;
3611                 static char temparea[32];
3612
3613                 if (type < ARRAY_SIZE(default_drive_params)) {
3614                         params = &default_drive_params[type].params;
3615                         if (type) {
3616                                 name = default_drive_params[type].name;
3617                                 allowed_drive_mask |= 1 << drive;
3618                         } else
3619                                 allowed_drive_mask &= ~(1 << drive);
3620                 } else {
3621                         params = &default_drive_params[0].params;
3622                         sprintf(temparea, "unknown type %d (usb?)", type);
3623                         name = temparea;
3624                 }
3625                 if (name) {
3626                         const char *prepend;
3627                         if (!has_drive) {
3628                                 prepend = "";
3629                                 has_drive = true;
3630                                 pr_info("Floppy drive(s):");
3631                         } else {
3632                                 prepend = ",";
3633                         }
3634
3635                         pr_cont("%s fd%d is %s", prepend, drive, name);
3636                 }
3637                 *UDP = *params;
3638         }
3639
3640         if (has_drive)
3641                 pr_cont("\n");
3642 }
3643
3644 static int floppy_release(struct gendisk *disk, fmode_t mode)
3645 {
3646         int drive = (long)disk->private_data;
3647
3648         mutex_lock(&floppy_mutex);
3649         mutex_lock(&open_lock);
3650         if (UDRS->fd_ref < 0)
3651                 UDRS->fd_ref = 0;
3652         else if (!UDRS->fd_ref--) {
3653                 DPRINT("floppy_release with fd_ref == 0");
3654                 UDRS->fd_ref = 0;
3655         }
3656         if (!UDRS->fd_ref)
3657                 opened_bdev[drive] = NULL;
3658         mutex_unlock(&open_lock);
3659         mutex_unlock(&floppy_mutex);
3660
3661         return 0;
3662 }
3663
3664 /*
3665  * floppy_open check for aliasing (/dev/fd0 can be the same as
3666  * /dev/PS0 etc), and disallows simultaneous access to the same
3667  * drive with different device numbers.
3668  */
3669 static int floppy_open(struct block_device *bdev, fmode_t mode)
3670 {
3671         int drive = (long)bdev->bd_disk->private_data;
3672         int old_dev, new_dev;
3673         int try;
3674         int res = -EBUSY;
3675         char *tmp;
3676
3677         mutex_lock(&floppy_mutex);
3678         mutex_lock(&open_lock);
3679         old_dev = UDRS->fd_device;
3680         if (opened_bdev[drive] && opened_bdev[drive] != bdev)
3681                 goto out2;
3682
3683         if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) {
3684                 set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
3685                 set_bit(FD_VERIFY_BIT, &UDRS->flags);
3686         }
3687
3688         if (UDRS->fd_ref == -1 || (UDRS->fd_ref && (mode & FMODE_EXCL)))
3689                 goto out2;
3690
3691         if (mode & FMODE_EXCL)
3692                 UDRS->fd_ref = -1;
3693         else
3694                 UDRS->fd_ref++;
3695
3696         opened_bdev[drive] = bdev;
3697
3698         res = -ENXIO;
3699
3700         if (!floppy_track_buffer) {
3701                 /* if opening an ED drive, reserve a big buffer,
3702                  * else reserve a small one */
3703                 if ((UDP->cmos == 6) || (UDP->cmos == 5))
3704                         try = 64;       /* Only 48 actually useful */
3705                 else
3706                         try = 32;       /* Only 24 actually useful */
3707
3708                 tmp = (char *)fd_dma_mem_alloc(1024 * try);
3709                 if (!tmp && !floppy_track_buffer) {
3710                         try >>= 1;      /* buffer only one side */
3711                         INFBOUND(try, 16);
3712                         tmp = (char *)fd_dma_mem_alloc(1024 * try);
3713                 }
3714                 if (!tmp && !floppy_track_buffer)
3715                         fallback_on_nodma_alloc(&tmp, 2048 * try);
3716                 if (!tmp && !floppy_track_buffer) {
3717                         DPRINT("Unable to allocate DMA memory\n");
3718                         goto out;
3719                 }
3720                 if (floppy_track_buffer) {
3721                         if (tmp)
3722                                 fd_dma_mem_free((unsigned long)tmp, try * 1024);
3723                 } else {
3724                         buffer_min = buffer_max = -1;
3725                         floppy_track_buffer = tmp;
3726                         max_buffer_sectors = try;
3727                 }
3728         }
3729
3730         new_dev = MINOR(bdev->bd_dev);
3731         UDRS->fd_device = new_dev;
3732         set_capacity(disks[drive], floppy_sizes[new_dev]);
3733         if (old_dev != -1 && old_dev != new_dev) {
3734                 if (buffer_drive == drive)
3735                         buffer_track = -1;
3736         }
3737
3738         if (UFDCS->rawcmd == 1)
3739                 UFDCS->rawcmd = 2;
3740
3741         if (!(mode & FMODE_NDELAY)) {
3742                 if (mode & (FMODE_READ|FMODE_WRITE)) {
3743                         UDRS->last_checked = 0;
3744                         check_disk_change(bdev);
3745                         if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags))
3746                                 goto out;
3747                 }
3748                 res = -EROFS;
3749                 if ((mode & FMODE_WRITE) &&
3750                     !test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags))
3751                         goto out;
3752         }
3753         mutex_unlock(&open_lock);
3754         mutex_unlock(&floppy_mutex);
3755         return 0;
3756 out:
3757         if (UDRS->fd_ref < 0)
3758                 UDRS->fd_ref = 0;
3759         else
3760                 UDRS->fd_ref--;
3761         if (!UDRS->fd_ref)
3762                 opened_bdev[drive] = NULL;
3763 out2:
3764         mutex_unlock(&open_lock);
3765         mutex_unlock(&floppy_mutex);
3766         return res;
3767 }
3768
3769 /*
3770  * Check if the disk has been changed or if a change has been faked.
3771  */
3772 static unsigned int floppy_check_events(struct gendisk *disk,
3773                                         unsigned int clearing)
3774 {
3775         int drive = (long)disk->private_data;
3776
3777         if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
3778             test_bit(FD_VERIFY_BIT, &UDRS->flags))
3779                 return DISK_EVENT_MEDIA_CHANGE;
3780
3781         if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) {
3782                 lock_fdc(drive, false);
3783                 poll_drive(false, 0);
3784                 process_fd_request();
3785         }
3786
3787         if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
3788             test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
3789             test_bit(drive, &fake_change) ||
3790             drive_no_geom(drive))
3791                 return DISK_EVENT_MEDIA_CHANGE;
3792         return 0;
3793 }
3794
3795 /*
3796  * This implements "read block 0" for floppy_revalidate().
3797  * Needed for format autodetection, checking whether there is
3798  * a disk in the drive, and whether that disk is writable.
3799  */
3800
3801 static void floppy_rb0_complete(struct bio *bio, int err)
3802 {
3803         complete((struct completion *)bio->bi_private);
3804 }
3805
3806 static int __floppy_read_block_0(struct block_device *bdev)
3807 {
3808         struct bio bio;
3809         struct bio_vec bio_vec;
3810         struct completion complete;
3811         struct page *page;
3812         size_t size;
3813
3814         page = alloc_page(GFP_NOIO);
3815         if (!page) {
3816                 process_fd_request();
3817                 return -ENOMEM;
3818         }
3819
3820         size = bdev->bd_block_size;
3821         if (!size)
3822                 size = 1024;
3823
3824         bio_init(&bio);
3825         bio.bi_io_vec = &bio_vec;
3826         bio_vec.bv_page = page;
3827         bio_vec.bv_len = size;
3828         bio_vec.bv_offset = 0;
3829         bio.bi_vcnt = 1;
3830         bio.bi_idx = 0;
3831         bio.bi_size = size;
3832         bio.bi_bdev = bdev;
3833         bio.bi_sector = 0;
3834         bio.bi_flags = (1 << BIO_QUIET);
3835         init_completion(&complete);
3836         bio.bi_private = &complete;
3837         bio.bi_end_io = floppy_rb0_complete;
3838
3839         submit_bio(READ, &bio);
3840         process_fd_request();
3841         wait_for_completion(&complete);
3842
3843         __free_page(page);
3844
3845         return 0;
3846 }
3847
3848 /* revalidate the floppy disk, i.e. trigger format autodetection by reading
3849  * the bootblock (block 0). "Autodetection" is also needed to check whether
3850  * there is a disk in the drive at all... Thus we also do it for fixed
3851  * geometry formats */
3852 static int floppy_revalidate(struct gendisk *disk)
3853 {
3854         int drive = (long)disk->private_data;
3855         int cf;
3856         int res = 0;
3857
3858         if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
3859             test_bit(FD_VERIFY_BIT, &UDRS->flags) ||
3860             test_bit(drive, &fake_change) ||
3861             drive_no_geom(drive)) {
3862                 if (WARN(atomic_read(&usage_count) == 0,
3863                          "VFS: revalidate called on non-open device.\n"))
3864                         return -EFAULT;
3865
3866                 lock_fdc(drive, false);
3867                 cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) ||
3868                       test_bit(FD_VERIFY_BIT, &UDRS->flags));
3869                 if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) {
3870                         process_fd_request();   /*already done by another thread */
3871                         return 0;
3872                 }
3873                 UDRS->maxblock = 0;
3874                 UDRS->maxtrack = 0;
3875                 if (buffer_drive == drive)
3876                         buffer_track = -1;
3877                 clear_bit(drive, &fake_change);
3878                 clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
3879                 if (cf)
3880                         UDRS->generation++;
3881                 if (drive_no_geom(drive)) {
3882                         /* auto-sensing */
3883                         res = __floppy_read_block_0(opened_bdev[drive]);
3884                 } else {
3885                         if (cf)
3886                                 poll_drive(false, FD_RAW_NEED_DISK);
3887                         process_fd_request();
3888                 }
3889         }
3890         set_capacity(disk, floppy_sizes[UDRS->fd_device]);
3891         return res;
3892 }
3893
3894 static const struct block_device_operations floppy_fops = {
3895         .owner                  = THIS_MODULE,
3896         .open                   = floppy_open,
3897         .release                = floppy_release,
3898         .ioctl                  = fd_ioctl,
3899         .getgeo                 = fd_getgeo,
3900         .check_events           = floppy_check_events,
3901         .revalidate_disk        = floppy_revalidate,
3902 };
3903
3904 /*
3905  * Floppy Driver initialization
3906  * =============================
3907  */
3908
3909 /* Determine the floppy disk controller type */
3910 /* This routine was written by David C. Niemi */
3911 static char __init get_fdc_version(void)
3912 {
3913         int r;
3914
3915         output_byte(FD_DUMPREGS);       /* 82072 and better know DUMPREGS */
3916         if (FDCS->reset)
3917                 return FDC_NONE;
3918         r = result();
3919         if (r <= 0x00)
3920                 return FDC_NONE;        /* No FDC present ??? */
3921         if ((r == 1) && (reply_buffer[0] == 0x80)) {
3922                 pr_info("FDC %d is an 8272A\n", fdc);
3923                 return FDC_8272A;       /* 8272a/765 don't know DUMPREGS */
3924         }
3925         if (r != 10) {
3926                 pr_info("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n",
3927                         fdc, r);
3928                 return FDC_UNKNOWN;
3929         }
3930
3931         if (!fdc_configure()) {
3932                 pr_info("FDC %d is an 82072\n", fdc);
3933                 return FDC_82072;       /* 82072 doesn't know CONFIGURE */
3934         }
3935
3936         output_byte(FD_PERPENDICULAR);
3937         if (need_more_output() == MORE_OUTPUT) {
3938                 output_byte(0);
3939         } else {
3940                 pr_info("FDC %d is an 82072A\n", fdc);
3941                 return FDC_82072A;      /* 82072A as found on Sparcs. */
3942         }
3943
3944         output_byte(FD_UNLOCK);
3945         r = result();
3946         if ((r == 1) && (reply_buffer[0] == 0x80)) {
3947                 pr_info("FDC %d is a pre-1991 82077\n", fdc);
3948                 return FDC_82077_ORIG;  /* Pre-1991 82077, doesn't know
3949                                          * LOCK/UNLOCK */
3950         }
3951         if ((r != 1) || (reply_buffer[0] != 0x00)) {
3952                 pr_info("FDC %d init: UNLOCK: unexpected return of %d bytes.\n",
3953                         fdc, r);
3954                 return FDC_UNKNOWN;
3955         }
3956         output_byte(FD_PARTID);
3957         r = result();
3958         if (r != 1) {
3959                 pr_info("FDC %d init: PARTID: unexpected return of %d bytes.\n",
3960                         fdc, r);
3961                 return FDC_UNKNOWN;
3962         }
3963         if (reply_buffer[0] == 0x80) {
3964                 pr_info("FDC %d is a post-1991 82077\n", fdc);
3965                 return FDC_82077;       /* Revised 82077AA passes all the tests */
3966         }
3967         switch (reply_buffer[0] >> 5) {
3968         case 0x0:
3969                 /* Either a 82078-1 or a 82078SL running at 5Volt */
3970                 pr_info("FDC %d is an 82078.\n", fdc);
3971                 return FDC_82078;
3972         case 0x1:
3973                 pr_info("FDC %d is a 44pin 82078\n", fdc);
3974                 return FDC_82078;
3975         case 0x2:
3976                 pr_info("FDC %d is a S82078B\n", fdc);
3977                 return FDC_S82078B;
3978         case 0x3:
3979                 pr_info("FDC %d is a National Semiconductor PC87306\n", fdc);
3980                 return FDC_87306;
3981         default:
3982                 pr_info("FDC %d init: 82078 variant with unknown PARTID=%d.\n",
3983                         fdc, reply_buffer[0] >> 5);
3984                 return FDC_82078_UNKN;
3985         }
3986 }                               /* get_fdc_version */
3987
3988 /* lilo configuration */
3989
3990 static void __init floppy_set_flags(int *ints, int param, int param2)
3991 {
3992         int i;
3993
3994         for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {
3995                 if (param)
3996                         default_drive_params[i].params.flags |= param2;
3997                 else
3998                         default_drive_params[i].params.flags &= ~param2;
3999         }
4000         DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param);
4001 }
4002
4003 static void __init daring(int *ints, int param, int param2)
4004 {
4005         int i;
4006
4007         for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) {
4008                 if (param) {
4009                         default_drive_params[i].params.select_delay = 0;
4010                         default_drive_params[i].params.flags |=
4011                             FD_SILENT_DCL_CLEAR;
4012                 } else {
4013                         default_drive_params[i].params.select_delay =
4014                             2 * HZ / 100;
4015                         default_drive_params[i].params.flags &=
4016                             ~FD_SILENT_DCL_CLEAR;
4017                 }
4018         }
4019         DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken");
4020 }
4021
4022 static void __init set_cmos(int *ints, int dummy, int dummy2)
4023 {
4024         int current_drive = 0;
4025
4026         if (ints[0] != 2) {
4027                 DPRINT("wrong number of parameters for CMOS\n");
4028                 return;
4029         }
4030         current_drive = ints[1];
4031         if (current_drive < 0 || current_drive >= 8) {
4032                 DPRINT("bad drive for set_cmos\n");
4033                 return;
4034         }
4035 #if N_FDC > 1
4036         if (current_drive >= 4 && !FDC2)
4037                 FDC2 = 0x370;
4038 #endif
4039         DP->cmos = ints[2];
4040         DPRINT("setting CMOS code to %d\n", ints[2]);
4041 }
4042
4043 static struct param_table {
4044         const char *name;
4045         void (*fn) (int *ints, int param, int param2);
4046         int *var;
4047         int def_param;
4048         int param2;
4049 } config_params[] __initdata = {
4050         {"allowed_drive_mask", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */
4051         {"all_drives", NULL, &allowed_drive_mask, 0xff, 0},     /* obsolete */
4052         {"asus_pci", NULL, &allowed_drive_mask, 0x33, 0},
4053         {"irq", NULL, &FLOPPY_IRQ, 6, 0},
4054         {"dma", NULL, &FLOPPY_DMA, 2, 0},
4055         {"daring", daring, NULL, 1, 0},
4056 #if N_FDC > 1
4057         {"two_fdc", NULL, &FDC2, 0x370, 0},
4058         {"one_fdc", NULL, &FDC2, 0, 0},
4059 #endif
4060         {"thinkpad", floppy_set_flags, NULL, 1, FD_INVERTED_DCL},
4061         {"broken_dcl", floppy_set_flags, NULL, 1, FD_BROKEN_DCL},
4062         {"messages", floppy_set_flags, NULL, 1, FTD_MSG},
4063         {"silent_dcl_clear", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR},
4064         {"debug", floppy_set_flags, NULL, 1, FD_DEBUG},
4065         {"nodma", NULL, &can_use_virtual_dma, 1, 0},
4066         {"omnibook", NULL, &can_use_virtual_dma, 1, 0},
4067         {"yesdma", NULL, &can_use_virtual_dma, 0, 0},
4068         {"fifo_depth", NULL, &fifo_depth, 0xa, 0},
4069         {"nofifo", NULL, &no_fifo, 0x20, 0},
4070         {"usefifo", NULL, &no_fifo, 0, 0},
4071         {"cmos", set_cmos, NULL, 0, 0},
4072         {"slow", NULL, &slow_floppy, 1, 0},
4073         {"unexpected_interrupts", NULL, &print_unex, 1, 0},
4074         {"no_unexpected_interrupts", NULL, &print_unex, 0, 0},
4075         {"L40SX", NULL, &print_unex, 0, 0}
4076
4077         EXTRA_FLOPPY_PARAMS
4078 };
4079
4080 static int __init floppy_setup(char *str)
4081 {
4082         int i;
4083         int param;
4084         int ints[11];
4085
4086         str = get_options(str, ARRAY_SIZE(ints), ints);
4087         if (str) {
4088                 for (i = 0; i < ARRAY_SIZE(config_params); i++) {
4089                         if (strcmp(str, config_params[i].name) == 0) {
4090                                 if (ints[0])
4091                                         param = ints[1];
4092                                 else
4093                                         param = config_params[i].def_param;
4094                                 if (config_params[i].fn)
4095                                         config_params[i].fn(ints, param,
4096                                                             config_params[i].
4097                                                             param2);
4098                                 if (config_params[i].var) {
4099                                         DPRINT("%s=%d\n", str, param);
4100                                         *config_params[i].var = param;
4101                                 }
4102                                 return 1;
4103                         }
4104                 }
4105         }
4106         if (str) {
4107                 DPRINT("unknown floppy option [%s]\n", str);
4108
4109                 DPRINT("allowed options are:");
4110                 for (i = 0; i < ARRAY_SIZE(config_params); i++)
4111                         pr_cont(" %s", config_params[i].name);
4112                 pr_cont("\n");
4113         } else
4114                 DPRINT("botched floppy option\n");
4115         DPRINT("Read Documentation/blockdev/floppy.txt\n");
4116         return 0;
4117 }
4118
4119 static int have_no_fdc = -ENODEV;
4120
4121 static ssize_t floppy_cmos_show(struct device *dev,
4122                                 struct device_attribute *attr, char *buf)
4123 {
4124         struct platform_device *p = to_platform_device(dev);
4125         int drive;
4126
4127         drive = p->id;
4128         return sprintf(buf, "%X\n", UDP->cmos);
4129 }
4130
4131 static DEVICE_ATTR(cmos, S_IRUGO, floppy_cmos_show, NULL);
4132
4133 static void floppy_device_release(struct device *dev)
4134 {
4135 }
4136
4137 static int floppy_resume(struct device *dev)
4138 {
4139         int fdc;
4140
4141         for (fdc = 0; fdc < N_FDC; fdc++)
4142                 if (FDCS->address != -1)
4143                         user_reset_fdc(-1, FD_RESET_ALWAYS, false);
4144
4145         return 0;
4146 }
4147
4148 static const struct dev_pm_ops floppy_pm_ops = {
4149         .resume = floppy_resume,
4150         .restore = floppy_resume,
4151 };
4152
4153 static struct platform_driver floppy_driver = {
4154         .driver = {
4155                    .name = "floppy",
4156                    .pm = &floppy_pm_ops,
4157         },
4158 };
4159
4160 static struct platform_device floppy_device[N_DRIVE];
4161
4162 static struct kobject *floppy_find(dev_t dev, int *part, void *data)
4163 {
4164         int drive = (*part & 3) | ((*part & 0x80) >> 5);
4165         if (drive >= N_DRIVE ||
4166             !(allowed_drive_mask & (1 << drive)) ||
4167             fdc_state[FDC(drive)].version == FDC_NONE)
4168                 return NULL;
4169         if (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type))
4170                 return NULL;
4171         *part = 0;
4172         return get_disk(disks[drive]);
4173 }
4174
4175 static int __init floppy_init(void)
4176 {
4177         int i, unit, drive;
4178         int err, dr;
4179
4180         set_debugt();
4181         interruptjiffies = resultjiffies = jiffies;
4182
4183 #if defined(CONFIG_PPC)
4184         if (check_legacy_ioport(FDC1))
4185                 return -ENODEV;
4186 #endif
4187
4188         raw_cmd = NULL;
4189
4190         for (dr = 0; dr < N_DRIVE; dr++) {
4191                 disks[dr] = alloc_disk(1);
4192                 if (!disks[dr]) {
4193                         err = -ENOMEM;
4194                         goto out_put_disk;
4195                 }
4196
4197                 disks[dr]->queue = blk_init_queue(do_fd_request, &floppy_lock);
4198                 if (!disks[dr]->queue) {
4199                         err = -ENOMEM;
4200                         goto out_put_disk;
4201                 }
4202
4203                 blk_queue_max_hw_sectors(disks[dr]->queue, 64);
4204                 disks[dr]->major = FLOPPY_MAJOR;
4205                 disks[dr]->first_minor = TOMINOR(dr);
4206                 disks[dr]->fops = &floppy_fops;
4207                 sprintf(disks[dr]->disk_name, "fd%d", dr);
4208
4209                 init_timer(&motor_off_timer[dr]);
4210                 motor_off_timer[dr].data = dr;
4211                 motor_off_timer[dr].function = motor_off_callback;
4212         }
4213
4214         err = register_blkdev(FLOPPY_MAJOR, "fd");
4215         if (err)
4216                 goto out_put_disk;
4217
4218         err = platform_driver_register(&floppy_driver);
4219         if (err)
4220                 goto out_unreg_blkdev;
4221
4222         blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
4223                             floppy_find, NULL, NULL);
4224
4225         for (i = 0; i < 256; i++)
4226                 if (ITYPE(i))
4227                         floppy_sizes[i] = floppy_type[ITYPE(i)].size;
4228                 else
4229                         floppy_sizes[i] = MAX_DISK_SIZE << 1;
4230
4231         reschedule_timeout(MAXTIMEOUT, "floppy init");
4232         config_types();
4233
4234         for (i = 0; i < N_FDC; i++) {
4235                 fdc = i;
4236                 memset(FDCS, 0, sizeof(*FDCS));
4237                 FDCS->dtr = -1;
4238                 FDCS->dor = 0x4;
4239 #if defined(__sparc__) || defined(__mc68000__)
4240         /*sparcs/sun3x don't have a DOR reset which we can fall back on to */
4241 #ifdef __mc68000__
4242                 if (MACH_IS_SUN3X)
4243 #endif
4244                         FDCS->version = FDC_82072A;
4245 #endif
4246         }
4247
4248         use_virtual_dma = can_use_virtual_dma & 1;
4249         fdc_state[0].address = FDC1;
4250         if (fdc_state[0].address == -1) {
4251                 del_timer_sync(&fd_timeout);
4252                 err = -ENODEV;
4253                 goto out_unreg_region;
4254         }
4255 #if N_FDC > 1
4256         fdc_state[1].address = FDC2;
4257 #endif
4258
4259         fdc = 0;                /* reset fdc in case of unexpected interrupt */
4260         err = floppy_grab_irq_and_dma();
4261         if (err) {
4262                 del_timer_sync(&fd_timeout);
4263                 err = -EBUSY;
4264                 goto out_unreg_region;
4265         }
4266
4267         /* initialise drive state */
4268         for (drive = 0; drive < N_DRIVE; drive++) {
4269                 memset(UDRS, 0, sizeof(*UDRS));
4270                 memset(UDRWE, 0, sizeof(*UDRWE));
4271                 set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags);
4272                 set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags);
4273                 set_bit(FD_VERIFY_BIT, &UDRS->flags);
4274                 UDRS->fd_device = -1;
4275                 floppy_track_buffer = NULL;
4276                 max_buffer_sectors = 0;
4277         }
4278         /*
4279          * Small 10 msec delay to let through any interrupt that
4280          * initialization might have triggered, to not
4281          * confuse detection:
4282          */
4283         msleep(10);
4284
4285         for (i = 0; i < N_FDC; i++) {
4286                 fdc = i;
4287                 FDCS->driver_version = FD_DRIVER_VERSION;
4288                 for (unit = 0; unit < 4; unit++)
4289                         FDCS->track[unit] = 0;
4290                 if (FDCS->address == -1)
4291                         continue;
4292                 FDCS->rawcmd = 2;
4293                 if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) {
4294                         /* free ioports reserved by floppy_grab_irq_and_dma() */
4295                         floppy_release_regions(fdc);
4296                         FDCS->address = -1;
4297                         FDCS->version = FDC_NONE;
4298                         continue;
4299                 }
4300                 /* Try to determine the floppy controller type */
4301                 FDCS->version = get_fdc_version();
4302                 if (FDCS->version == FDC_NONE) {
4303                         /* free ioports reserved by floppy_grab_irq_and_dma() */
4304                         floppy_release_regions(fdc);
4305                         FDCS->address = -1;
4306                         continue;
4307                 }
4308                 if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)
4309                         can_use_virtual_dma = 0;
4310
4311                 have_no_fdc = 0;
4312                 /* Not all FDCs seem to be able to handle the version command
4313                  * properly, so force a reset for the standard FDC clones,
4314                  * to avoid interrupt garbage.
4315                  */
4316                 user_reset_fdc(-1, FD_RESET_ALWAYS, false);
4317         }
4318         fdc = 0;
4319         del_timer_sync(&fd_timeout);
4320         current_drive = 0;
4321         initialized = true;
4322         if (have_no_fdc) {
4323                 DPRINT("no floppy controllers found\n");
4324                 err = have_no_fdc;
4325                 goto out_flush_work;
4326         }
4327
4328         for (drive = 0; drive < N_DRIVE; drive++) {
4329                 if (!(allowed_drive_mask & (1 << drive)))
4330                         continue;
4331                 if (fdc_state[FDC(drive)].version == FDC_NONE)
4332                         continue;
4333
4334                 floppy_device[drive].name = floppy_device_name;
4335                 floppy_device[drive].id = drive;
4336                 floppy_device[drive].dev.release = floppy_device_release;
4337
4338                 err = platform_device_register(&floppy_device[drive]);
4339                 if (err)
4340                         goto out_flush_work;
4341
4342                 err = device_create_file(&floppy_device[drive].dev,
4343                                          &dev_attr_cmos);
4344                 if (err)
4345                         goto out_unreg_platform_dev;
4346
4347                 /* to be cleaned up... */
4348                 disks[drive]->private_data = (void *)(long)drive;
4349                 disks[drive]->flags |= GENHD_FL_REMOVABLE;
4350                 disks[drive]->driverfs_dev = &floppy_device[drive].dev;
4351                 add_disk(disks[drive]);
4352         }
4353
4354         return 0;
4355
4356 out_unreg_platform_dev:
4357         platform_device_unregister(&floppy_device[drive]);
4358 out_flush_work:
4359         flush_work_sync(&floppy_work);
4360         if (atomic_read(&usage_count))
4361                 floppy_release_irq_and_dma();
4362 out_unreg_region:
4363         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
4364         platform_driver_unregister(&floppy_driver);
4365 out_unreg_blkdev:
4366         unregister_blkdev(FLOPPY_MAJOR, "fd");
4367 out_put_disk:
4368         while (dr--) {
4369                 del_timer_sync(&motor_off_timer[dr]);
4370                 if (disks[dr]->queue) {
4371                         blk_cleanup_queue(disks[dr]->queue);
4372                         /*
4373                          * put_disk() is not paired with add_disk() and
4374                          * will put queue reference one extra time. fix it.
4375                          */
4376                         disks[dr]->queue = NULL;
4377                 }
4378                 put_disk(disks[dr]);
4379         }
4380         return err;
4381 }
4382
4383 static const struct io_region {
4384         int offset;
4385         int size;
4386 } io_regions[] = {
4387         { 2, 1 },
4388         /* address + 3 is sometimes reserved by pnp bios for motherboard */
4389         { 4, 2 },
4390         /* address + 6 is reserved, and may be taken by IDE.
4391          * Unfortunately, Adaptec doesn't know this :-(, */
4392         { 7, 1 },
4393 };
4394
4395 static void floppy_release_allocated_regions(int fdc, const struct io_region *p)
4396 {
4397         while (p != io_regions) {
4398                 p--;
4399                 release_region(FDCS->address + p->offset, p->size);
4400         }
4401 }
4402
4403 #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)]))
4404
4405 static int floppy_request_regions(int fdc)
4406 {
4407         const struct io_region *p;
4408
4409         for (p = io_regions; p < ARRAY_END(io_regions); p++) {
4410                 if (!request_region(FDCS->address + p->offset,
4411                                     p->size, "floppy")) {
4412                         DPRINT("Floppy io-port 0x%04lx in use\n",
4413                                FDCS->address + p->offset);
4414                         floppy_release_allocated_regions(fdc, p);
4415                         return -EBUSY;
4416                 }
4417         }
4418         return 0;
4419 }
4420
4421 static void floppy_release_regions(int fdc)
4422 {
4423         floppy_release_allocated_regions(fdc, ARRAY_END(io_regions));
4424 }
4425
4426 static int floppy_grab_irq_and_dma(void)
4427 {
4428         if (atomic_inc_return(&usage_count) > 1)
4429                 return 0;
4430
4431         /*
4432          * We might have scheduled a free_irq(), wait it to
4433          * drain first:
4434          */
4435         flush_work_sync(&floppy_work);
4436
4437         if (fd_request_irq()) {
4438                 DPRINT("Unable to grab IRQ%d for the floppy driver\n",
4439                        FLOPPY_IRQ);
4440                 atomic_dec(&usage_count);
4441                 return -1;
4442         }
4443         if (fd_request_dma()) {
4444                 DPRINT("Unable to grab DMA%d for the floppy driver\n",
4445                        FLOPPY_DMA);
4446                 if (can_use_virtual_dma & 2)
4447                         use_virtual_dma = can_use_virtual_dma = 1;
4448                 if (!(can_use_virtual_dma & 1)) {
4449                         fd_free_irq();
4450                         atomic_dec(&usage_count);
4451                         return -1;
4452                 }
4453         }
4454
4455         for (fdc = 0; fdc < N_FDC; fdc++) {
4456                 if (FDCS->address != -1) {
4457                         if (floppy_request_regions(fdc))
4458                                 goto cleanup;
4459                 }
4460         }
4461         for (fdc = 0; fdc < N_FDC; fdc++) {
4462                 if (FDCS->address != -1) {
4463                         reset_fdc_info(1);
4464                         fd_outb(FDCS->dor, FD_DOR);
4465                 }
4466         }
4467         fdc = 0;
4468         set_dor(0, ~0, 8);      /* avoid immediate interrupt */
4469
4470         for (fdc = 0; fdc < N_FDC; fdc++)
4471                 if (FDCS->address != -1)
4472                         fd_outb(FDCS->dor, FD_DOR);
4473         /*
4474          * The driver will try and free resources and relies on us
4475          * to know if they were allocated or not.
4476          */
4477         fdc = 0;
4478         irqdma_allocated = 1;
4479         return 0;
4480 cleanup:
4481         fd_free_irq();
4482         fd_free_dma();
4483         while (--fdc >= 0)
4484                 floppy_release_regions(fdc);
4485         atomic_dec(&usage_count);
4486         return -1;
4487 }
4488
4489 static void floppy_release_irq_and_dma(void)
4490 {
4491         int old_fdc;
4492 #ifndef __sparc__
4493         int drive;
4494 #endif
4495         long tmpsize;
4496         unsigned long tmpaddr;
4497
4498         if (!atomic_dec_and_test(&usage_count))
4499                 return;
4500
4501         if (irqdma_allocated) {
4502                 fd_disable_dma();
4503                 fd_free_dma();
4504                 fd_free_irq();
4505                 irqdma_allocated = 0;
4506         }
4507         set_dor(0, ~0, 8);
4508 #if N_FDC > 1
4509         set_dor(1, ~8, 0);
4510 #endif
4511         floppy_enable_hlt();
4512
4513         if (floppy_track_buffer && max_buffer_sectors) {
4514                 tmpsize = max_buffer_sectors * 1024;
4515                 tmpaddr = (unsigned long)floppy_track_buffer;
4516                 floppy_track_buffer = NULL;
4517                 max_buffer_sectors = 0;
4518                 buffer_min = buffer_max = -1;
4519                 fd_dma_mem_free(tmpaddr, tmpsize);
4520         }
4521 #ifndef __sparc__
4522         for (drive = 0; drive < N_FDC * 4; drive++)
4523                 if (timer_pending(motor_off_timer + drive))
4524                         pr_info("motor off timer %d still active\n", drive);
4525 #endif
4526
4527         if (timer_pending(&fd_timeout))
4528                 pr_info("floppy timer still active:%s\n", timeout_message);
4529         if (timer_pending(&fd_timer))
4530                 pr_info("auxiliary floppy timer still active\n");
4531         if (work_pending(&floppy_work))
4532                 pr_info("work still pending\n");
4533         old_fdc = fdc;
4534         for (fdc = 0; fdc < N_FDC; fdc++)
4535                 if (FDCS->address != -1)
4536                         floppy_release_regions(fdc);
4537         fdc = old_fdc;
4538 }
4539
4540 #ifdef MODULE
4541
4542 static char *floppy;
4543
4544 static void __init parse_floppy_cfg_string(char *cfg)
4545 {
4546         char *ptr;
4547
4548         while (*cfg) {
4549                 ptr = cfg;
4550                 while (*cfg && *cfg != ' ' && *cfg != '\t')
4551                         cfg++;
4552                 if (*cfg) {
4553                         *cfg = '\0';
4554                         cfg++;
4555                 }
4556                 if (*ptr)
4557                         floppy_setup(ptr);
4558         }
4559 }
4560
4561 static int __init floppy_module_init(void)
4562 {
4563         if (floppy)
4564                 parse_floppy_cfg_string(floppy);
4565         return floppy_init();
4566 }
4567 module_init(floppy_module_init);
4568
4569 static void __exit floppy_module_exit(void)
4570 {
4571         int drive;
4572
4573         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
4574         unregister_blkdev(FLOPPY_MAJOR, "fd");
4575         platform_driver_unregister(&floppy_driver);
4576
4577         for (drive = 0; drive < N_DRIVE; drive++) {
4578                 del_timer_sync(&motor_off_timer[drive]);
4579
4580                 if ((allowed_drive_mask & (1 << drive)) &&
4581                     fdc_state[FDC(drive)].version != FDC_NONE) {
4582                         del_gendisk(disks[drive]);
4583                         device_remove_file(&floppy_device[drive].dev, &dev_attr_cmos);
4584                         platform_device_unregister(&floppy_device[drive]);
4585                 }
4586                 blk_cleanup_queue(disks[drive]->queue);
4587
4588                 /*
4589                  * These disks have not called add_disk().  Don't put down
4590                  * queue reference in put_disk().
4591                  */
4592                 if (!(allowed_drive_mask & (1 << drive)) ||
4593                     fdc_state[FDC(drive)].version == FDC_NONE)
4594                         disks[drive]->queue = NULL;
4595
4596                 put_disk(disks[drive]);
4597         }
4598
4599         del_timer_sync(&fd_timeout);
4600         del_timer_sync(&fd_timer);
4601
4602         if (atomic_read(&usage_count))
4603                 floppy_release_irq_and_dma();
4604
4605         /* eject disk, if any */
4606         fd_eject(0);
4607 }
4608
4609 module_exit(floppy_module_exit);
4610
4611 module_param(floppy, charp, 0);
4612 module_param(FLOPPY_IRQ, int, 0);
4613 module_param(FLOPPY_DMA, int, 0);
4614 MODULE_AUTHOR("Alain L. Knaff");
4615 MODULE_SUPPORTED_DEVICE("fd");
4616 MODULE_LICENSE("GPL");
4617
4618 /* This doesn't actually get used other than for module information */
4619 static const struct pnp_device_id floppy_pnpids[] = {
4620         {"PNP0700", 0},
4621         {}
4622 };
4623
4624 MODULE_DEVICE_TABLE(pnp, floppy_pnpids);
4625
4626 #else
4627
4628 __setup("floppy=", floppy_setup);
4629 module_init(floppy_init)
4630 #endif
4631
4632 MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);