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