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