GNU Linux-libre 5.4.241-gnu1
[releases.git] / drivers / block / ataflop.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  drivers/block/ataflop.c
4  *
5  *  Copyright (C) 1993  Greg Harp
6  *  Atari Support by Bjoern Brauel, Roman Hodek
7  *
8  *  Big cleanup Sep 11..14 1994 Roman Hodek:
9  *   - Driver now works interrupt driven
10  *   - Support for two drives; should work, but I cannot test that :-(
11  *   - Reading is done in whole tracks and buffered to speed up things
12  *   - Disk change detection and drive deselecting after motor-off
13  *     similar to TOS
14  *   - Autodetection of disk format (DD/HD); untested yet, because I
15  *     don't have an HD drive :-(
16  *
17  *  Fixes Nov 13 1994 Martin Schaller:
18  *   - Autodetection works now
19  *   - Support for 5 1/4'' disks
20  *   - Removed drive type (unknown on atari)
21  *   - Do seeks with 8 Mhz
22  *
23  *  Changes by Andreas Schwab:
24  *   - After errors in multiple read mode try again reading single sectors
25  *  (Feb 1995):
26  *   - Clean up error handling
27  *   - Set blk_size for proper size checking
28  *   - Initialize track register when testing presence of floppy
29  *   - Implement some ioctl's
30  *
31  *  Changes by Torsten Lang:
32  *   - When probing the floppies we should add the FDCCMDADD_H flag since
33  *     the FDC will otherwise wait forever when no disk is inserted...
34  *
35  * ++ Freddi Aschwanden (fa) 20.9.95 fixes for medusa:
36  *  - MFPDELAY() after each FDC access -> atari 
37  *  - more/other disk formats
38  *  - DMA to the block buffer directly if we have a 32bit DMA
39  *  - for medusa, the step rate is always 3ms
40  *  - on medusa, use only cache_push()
41  * Roman:
42  *  - Make disk format numbering independent from minors
43  *  - Let user set max. supported drive type (speeds up format
44  *    detection, saves buffer space)
45  *
46  * Roman 10/15/95:
47  *  - implement some more ioctls
48  *  - disk formatting
49  *  
50  * Andreas 95/12/12:
51  *  - increase gap size at start of track for HD/ED disks
52  *
53  * Michael (MSch) 11/07/96:
54  *  - implemented FDSETPRM and FDDEFPRM ioctl
55  *
56  * Andreas (97/03/19):
57  *  - implemented missing BLK* ioctls
58  *
59  *  Things left to do:
60  *   - Formatting
61  *   - Maybe a better strategy for disk change detection (does anyone
62  *     know one?)
63  */
64
65 #include <linux/module.h>
66
67 #include <linux/fd.h>
68 #include <linux/delay.h>
69 #include <linux/init.h>
70 #include <linux/blk-mq.h>
71 #include <linux/mutex.h>
72 #include <linux/completion.h>
73 #include <linux/wait.h>
74
75 #include <asm/atariints.h>
76 #include <asm/atari_stdma.h>
77 #include <asm/atari_stram.h>
78
79 #define FD_MAX_UNITS 2
80
81 #undef DEBUG
82
83 static DEFINE_MUTEX(ataflop_mutex);
84 static struct request *fd_request;
85
86 /*
87  * WD1772 stuff
88  */
89
90 /* register codes */
91
92 #define FDCSELREG_STP   (0x80)   /* command/status register */
93 #define FDCSELREG_TRA   (0x82)   /* track register */
94 #define FDCSELREG_SEC   (0x84)   /* sector register */
95 #define FDCSELREG_DTA   (0x86)   /* data register */
96
97 /* register names for FDC_READ/WRITE macros */
98
99 #define FDCREG_CMD              0
100 #define FDCREG_STATUS   0
101 #define FDCREG_TRACK    2
102 #define FDCREG_SECTOR   4
103 #define FDCREG_DATA             6
104
105 /* command opcodes */
106
107 #define FDCCMD_RESTORE  (0x00)   /*  -                   */
108 #define FDCCMD_SEEK     (0x10)   /*   |                  */
109 #define FDCCMD_STEP     (0x20)   /*   |  TYP 1 Commands  */
110 #define FDCCMD_STIN     (0x40)   /*   |                  */
111 #define FDCCMD_STOT     (0x60)   /*  -                   */
112 #define FDCCMD_RDSEC    (0x80)   /*  -   TYP 2 Commands  */
113 #define FDCCMD_WRSEC    (0xa0)   /*  -          "        */
114 #define FDCCMD_RDADR    (0xc0)   /*  -                   */
115 #define FDCCMD_RDTRA    (0xe0)   /*   |  TYP 3 Commands  */
116 #define FDCCMD_WRTRA    (0xf0)   /*  -                   */
117 #define FDCCMD_FORCI    (0xd0)   /*  -   TYP 4 Command   */
118
119 /* command modifier bits */
120
121 #define FDCCMDADD_SR6   (0x00)   /* step rate settings */
122 #define FDCCMDADD_SR12  (0x01)
123 #define FDCCMDADD_SR2   (0x02)
124 #define FDCCMDADD_SR3   (0x03)
125 #define FDCCMDADD_V     (0x04)   /* verify */
126 #define FDCCMDADD_H     (0x08)   /* wait for spin-up */
127 #define FDCCMDADD_U     (0x10)   /* update track register */
128 #define FDCCMDADD_M     (0x10)   /* multiple sector access */
129 #define FDCCMDADD_E     (0x04)   /* head settling flag */
130 #define FDCCMDADD_P     (0x02)   /* precompensation off */
131 #define FDCCMDADD_A0    (0x01)   /* DAM flag */
132
133 /* status register bits */
134
135 #define FDCSTAT_MOTORON (0x80)   /* motor on */
136 #define FDCSTAT_WPROT   (0x40)   /* write protected (FDCCMD_WR*) */
137 #define FDCSTAT_SPINUP  (0x20)   /* motor speed stable (Type I) */
138 #define FDCSTAT_DELDAM  (0x20)   /* sector has deleted DAM (Type II+III) */
139 #define FDCSTAT_RECNF   (0x10)   /* record not found */
140 #define FDCSTAT_CRC             (0x08)   /* CRC error */
141 #define FDCSTAT_TR00    (0x04)   /* Track 00 flag (Type I) */
142 #define FDCSTAT_LOST    (0x04)   /* Lost Data (Type II+III) */
143 #define FDCSTAT_IDX             (0x02)   /* Index status (Type I) */
144 #define FDCSTAT_DRQ             (0x02)   /* DRQ status (Type II+III) */
145 #define FDCSTAT_BUSY    (0x01)   /* FDC is busy */
146
147
148 /* PSG Port A Bit Nr 0 .. Side Sel .. 0 -> Side 1  1 -> Side 2 */
149 #define DSKSIDE     (0x01)
150
151 #define DSKDRVNONE  (0x06)
152 #define DSKDRV0     (0x02)
153 #define DSKDRV1     (0x04)
154
155 /* step rates */
156 #define FDCSTEP_6       0x00
157 #define FDCSTEP_12      0x01
158 #define FDCSTEP_2       0x02
159 #define FDCSTEP_3       0x03
160
161 struct atari_format_descr {
162         int track;              /* to be formatted */
163         int head;               /*   ""     ""     */
164         int sect_offset;        /* offset of first sector */
165 };
166
167 /* Disk types: DD, HD, ED */
168 static struct atari_disk_type {
169         const char      *name;
170         unsigned        spt;            /* sectors per track */
171         unsigned        blocks;         /* total number of blocks */
172         unsigned        fdc_speed;      /* fdc_speed setting */
173         unsigned        stretch;        /* track doubling ? */
174 } atari_disk_type[] = {
175         { "d360",  9, 720, 0, 0},       /*  0: 360kB diskette */
176         { "D360",  9, 720, 0, 1},       /*  1: 360kb in 720k or 1.2MB drive */
177         { "D720",  9,1440, 0, 0},       /*  2: 720kb in 720k or 1.2MB drive */
178         { "D820", 10,1640, 0, 0},       /*  3: DD disk with 82 tracks/10 sectors */
179 /* formats above are probed for type DD */
180 #define MAX_TYPE_DD 3
181         { "h1200",15,2400, 3, 0},       /*  4: 1.2MB diskette */
182         { "H1440",18,2880, 3, 0},       /*  5: 1.4 MB diskette (HD) */
183         { "H1640",20,3280, 3, 0},       /*  6: 1.64MB diskette (fat HD) 82 tr 20 sec */
184 /* formats above are probed for types DD and HD */
185 #define MAX_TYPE_HD 6
186         { "E2880",36,5760, 3, 0},       /*  7: 2.8 MB diskette (ED) */
187         { "E3280",40,6560, 3, 0},       /*  8: 3.2 MB diskette (fat ED) 82 tr 40 sec */
188 /* formats above are probed for types DD, HD and ED */
189 #define MAX_TYPE_ED 8
190 /* types below are never autoprobed */
191         { "H1680",21,3360, 3, 0},       /*  9: 1.68MB diskette (fat HD) 80 tr 21 sec */
192         { "h410",10,820, 0, 1},         /* 10: 410k diskette 41 tr 10 sec, stretch */
193         { "h1476",18,2952, 3, 0},       /* 11: 1.48MB diskette 82 tr 18 sec */
194         { "H1722",21,3444, 3, 0},       /* 12: 1.72MB diskette 82 tr 21 sec */
195         { "h420",10,840, 0, 1},         /* 13: 420k diskette 42 tr 10 sec, stretch */
196         { "H830",10,1660, 0, 0},        /* 14: 820k diskette 83 tr 10 sec */
197         { "h1494",18,2952, 3, 0},       /* 15: 1.49MB diskette 83 tr 18 sec */
198         { "H1743",21,3486, 3, 0},       /* 16: 1.74MB diskette 83 tr 21 sec */
199         { "h880",11,1760, 0, 0},        /* 17: 880k diskette 80 tr 11 sec */
200         { "D1040",13,2080, 0, 0},       /* 18: 1.04MB diskette 80 tr 13 sec */
201         { "D1120",14,2240, 0, 0},       /* 19: 1.12MB diskette 80 tr 14 sec */
202         { "h1600",20,3200, 3, 0},       /* 20: 1.60MB diskette 80 tr 20 sec */
203         { "H1760",22,3520, 3, 0},       /* 21: 1.76MB diskette 80 tr 22 sec */
204         { "H1920",24,3840, 3, 0},       /* 22: 1.92MB diskette 80 tr 24 sec */
205         { "E3200",40,6400, 3, 0},       /* 23: 3.2MB diskette 80 tr 40 sec */
206         { "E3520",44,7040, 3, 0},       /* 24: 3.52MB diskette 80 tr 44 sec */
207         { "E3840",48,7680, 3, 0},       /* 25: 3.84MB diskette 80 tr 48 sec */
208         { "H1840",23,3680, 3, 0},       /* 26: 1.84MB diskette 80 tr 23 sec */
209         { "D800",10,1600, 0, 0},        /* 27: 800k diskette 80 tr 10 sec */
210 };
211
212 static int StartDiskType[] = {
213         MAX_TYPE_DD,
214         MAX_TYPE_HD,
215         MAX_TYPE_ED
216 };
217
218 #define TYPE_DD         0
219 #define TYPE_HD         1
220 #define TYPE_ED         2
221
222 static int DriveType = TYPE_HD;
223
224 static DEFINE_SPINLOCK(ataflop_lock);
225
226 /* Array for translating minors into disk formats */
227 static struct {
228         int      index;
229         unsigned drive_types;
230 } minor2disktype[] = {
231         {  0, TYPE_DD },        /*  1: d360 */
232         {  4, TYPE_HD },        /*  2: h1200 */
233         {  1, TYPE_DD },        /*  3: D360 */
234         {  2, TYPE_DD },        /*  4: D720 */
235         {  1, TYPE_DD },        /*  5: h360 = D360 */
236         {  2, TYPE_DD },        /*  6: h720 = D720 */
237         {  5, TYPE_HD },        /*  7: H1440 */
238         {  7, TYPE_ED },        /*  8: E2880 */
239 /* some PC formats :-) */
240         {  8, TYPE_ED },        /*  9: E3280    <- was "CompaQ" == E2880 for PC */
241         {  5, TYPE_HD },        /* 10: h1440 = H1440 */
242         {  9, TYPE_HD },        /* 11: H1680 */
243         { 10, TYPE_DD },        /* 12: h410  */
244         {  3, TYPE_DD },        /* 13: H820     <- == D820, 82x10 */
245         { 11, TYPE_HD },        /* 14: h1476 */
246         { 12, TYPE_HD },        /* 15: H1722 */
247         { 13, TYPE_DD },        /* 16: h420  */
248         { 14, TYPE_DD },        /* 17: H830  */
249         { 15, TYPE_HD },        /* 18: h1494 */
250         { 16, TYPE_HD },        /* 19: H1743 */
251         { 17, TYPE_DD },        /* 20: h880  */
252         { 18, TYPE_DD },        /* 21: D1040 */
253         { 19, TYPE_DD },        /* 22: D1120 */
254         { 20, TYPE_HD },        /* 23: h1600 */
255         { 21, TYPE_HD },        /* 24: H1760 */
256         { 22, TYPE_HD },        /* 25: H1920 */
257         { 23, TYPE_ED },        /* 26: E3200 */
258         { 24, TYPE_ED },        /* 27: E3520 */
259         { 25, TYPE_ED },        /* 28: E3840 */
260         { 26, TYPE_HD },        /* 29: H1840 */
261         { 27, TYPE_DD },        /* 30: D800  */
262         {  6, TYPE_HD },        /* 31: H1640    <- was H1600 == h1600 for PC */
263 };
264
265 #define NUM_DISK_MINORS ARRAY_SIZE(minor2disktype)
266
267 /*
268  * Maximum disk size (in kilobytes). This default is used whenever the
269  * current disk size is unknown.
270  */
271 #define MAX_DISK_SIZE 3280
272
273 /*
274  * MSch: User-provided type information. 'drive' points to
275  * the respective entry of this array. Set by FDSETPRM ioctls.
276  */
277 static struct atari_disk_type user_params[FD_MAX_UNITS];
278
279 /*
280  * User-provided permanent type information. 'drive' points to
281  * the respective entry of this array.  Set by FDDEFPRM ioctls, 
282  * restored upon disk change by floppy_revalidate() if valid (as seen by
283  * default_params[].blocks > 0 - a bit in unit[].flags might be used for this?)
284  */
285 static struct atari_disk_type default_params[FD_MAX_UNITS];
286
287 /* current info on each unit */
288 static struct atari_floppy_struct {
289         int connected;                          /* !=0 : drive is connected */
290         int autoprobe;                          /* !=0 : do autoprobe       */
291
292         struct atari_disk_type  *disktype;      /* current type of disk */
293
294         int track;              /* current head position or -1 if
295                                    unknown */
296         unsigned int steprate;  /* steprate setting */
297         unsigned int wpstat;    /* current state of WP signal (for
298                                    disk change detection) */
299         int flags;              /* flags */
300         struct gendisk *disk;
301         int ref;
302         int type;
303         struct blk_mq_tag_set tag_set;
304 } unit[FD_MAX_UNITS];
305
306 #define UD      unit[drive]
307 #define UDT     unit[drive].disktype
308 #define SUD     unit[SelectedDrive]
309 #define SUDT    unit[SelectedDrive].disktype
310
311
312 #define FDC_READ(reg) ({                        \
313     /* unsigned long __flags; */                \
314     unsigned short __val;                       \
315     /* local_irq_save(__flags); */              \
316     dma_wd.dma_mode_status = 0x80 | (reg);      \
317     udelay(25);                                 \
318     __val = dma_wd.fdc_acces_seccount;          \
319     MFPDELAY();                                 \
320     /* local_irq_restore(__flags); */           \
321     __val & 0xff;                               \
322 })
323
324 #define FDC_WRITE(reg,val)                      \
325     do {                                        \
326         /* unsigned long __flags; */            \
327         /* local_irq_save(__flags); */          \
328         dma_wd.dma_mode_status = 0x80 | (reg);  \
329         udelay(25);                             \
330         dma_wd.fdc_acces_seccount = (val);      \
331         MFPDELAY();                             \
332         /* local_irq_restore(__flags); */       \
333     } while(0)
334
335
336 /* Buffering variables:
337  * First, there is a DMA buffer in ST-RAM that is used for floppy DMA
338  * operations. Second, a track buffer is used to cache a whole track
339  * of the disk to save read operations. These are two separate buffers
340  * because that allows write operations without clearing the track buffer.
341  */
342
343 static int MaxSectors[] = {
344         11, 22, 44
345 };
346 static int BufferSize[] = {
347         15*512, 30*512, 60*512
348 };
349
350 #define BUFFER_SIZE     (BufferSize[DriveType])
351
352 unsigned char *DMABuffer;                         /* buffer for writes */
353 static unsigned long PhysDMABuffer;   /* physical address */
354
355 static int UseTrackbuffer = -1;           /* Do track buffering? */
356 module_param(UseTrackbuffer, int, 0);
357
358 unsigned char *TrackBuffer;                       /* buffer for reads */
359 static unsigned long PhysTrackBuffer; /* physical address */
360 static int BufferDrive, BufferSide, BufferTrack;
361 static int read_track;          /* non-zero if we are reading whole tracks */
362
363 #define SECTOR_BUFFER(sec)      (TrackBuffer + ((sec)-1)*512)
364 #define IS_BUFFERED(drive,side,track) \
365     (BufferDrive == (drive) && BufferSide == (side) && BufferTrack == (track))
366
367 /*
368  * These are global variables, as that's the easiest way to give
369  * information to interrupts. They are the data used for the current
370  * request.
371  */
372 static int SelectedDrive = 0;
373 static int ReqCmd, ReqBlock;
374 static int ReqSide, ReqTrack, ReqSector, ReqCnt;
375 static int HeadSettleFlag = 0;
376 static unsigned char *ReqData, *ReqBuffer;
377 static int MotorOn = 0, MotorOffTrys;
378 static int IsFormatting = 0, FormatError;
379
380 static int UserSteprate[FD_MAX_UNITS] = { -1, -1 };
381 module_param_array(UserSteprate, int, NULL, 0);
382
383 static DECLARE_COMPLETION(format_wait);
384
385 static unsigned long changed_floppies = 0xff, fake_change = 0;
386 #define CHECK_CHANGE_DELAY      HZ/2
387
388 #define FD_MOTOR_OFF_DELAY      (3*HZ)
389 #define FD_MOTOR_OFF_MAXTRY     (10*20)
390
391 #define FLOPPY_TIMEOUT          (6*HZ)
392 #define RECALIBRATE_ERRORS      4       /* After this many errors the drive
393                                          * will be recalibrated. */
394 #define MAX_ERRORS              8       /* After this many errors the driver
395                                          * will give up. */
396
397
398 /*
399  * The driver is trying to determine the correct media format
400  * while Probing is set. fd_rwsec_done() clears it after a
401  * successful access.
402  */
403 static int Probing = 0;
404
405 /* This flag is set when a dummy seek is necessary to make the WP
406  * status bit accessible.
407  */
408 static int NeedSeek = 0;
409
410
411 #ifdef DEBUG
412 #define DPRINT(a)       printk a
413 #else
414 #define DPRINT(a)
415 #endif
416
417 /***************************** Prototypes *****************************/
418
419 static void fd_select_side( int side );
420 static void fd_select_drive( int drive );
421 static void fd_deselect( void );
422 static void fd_motor_off_timer(struct timer_list *unused);
423 static void check_change(struct timer_list *unused);
424 static irqreturn_t floppy_irq (int irq, void *dummy);
425 static void fd_error( void );
426 static int do_format(int drive, int type, struct atari_format_descr *desc);
427 static void do_fd_action( int drive );
428 static void fd_calibrate( void );
429 static void fd_calibrate_done( int status );
430 static void fd_seek( void );
431 static void fd_seek_done( int status );
432 static void fd_rwsec( void );
433 static void fd_readtrack_check(struct timer_list *unused);
434 static void fd_rwsec_done( int status );
435 static void fd_rwsec_done1(int status);
436 static void fd_writetrack( void );
437 static void fd_writetrack_done( int status );
438 static void fd_times_out(struct timer_list *unused);
439 static void finish_fdc( void );
440 static void finish_fdc_done( int dummy );
441 static void setup_req_params( int drive );
442 static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int
443                      cmd, unsigned long param);
444 static void fd_probe( int drive );
445 static int fd_test_drive_present( int drive );
446 static void config_types( void );
447 static int floppy_open(struct block_device *bdev, fmode_t mode);
448 static void floppy_release(struct gendisk *disk, fmode_t mode);
449
450 /************************* End of Prototypes **************************/
451
452 static DEFINE_TIMER(motor_off_timer, fd_motor_off_timer);
453 static DEFINE_TIMER(readtrack_timer, fd_readtrack_check);
454 static DEFINE_TIMER(timeout_timer, fd_times_out);
455 static DEFINE_TIMER(fd_timer, check_change);
456         
457 static void fd_end_request_cur(blk_status_t err)
458 {
459         if (!blk_update_request(fd_request, err,
460                                 blk_rq_cur_bytes(fd_request))) {
461                 __blk_mq_end_request(fd_request, err);
462                 fd_request = NULL;
463         }
464 }
465
466 static inline void start_motor_off_timer(void)
467 {
468         mod_timer(&motor_off_timer, jiffies + FD_MOTOR_OFF_DELAY);
469         MotorOffTrys = 0;
470 }
471
472 static inline void start_check_change_timer( void )
473 {
474         mod_timer(&fd_timer, jiffies + CHECK_CHANGE_DELAY);
475 }
476
477 static inline void start_timeout(void)
478 {
479         mod_timer(&timeout_timer, jiffies + FLOPPY_TIMEOUT);
480 }
481
482 static inline void stop_timeout(void)
483 {
484         del_timer(&timeout_timer);
485 }
486
487 /* Select the side to use. */
488
489 static void fd_select_side( int side )
490 {
491         unsigned long flags;
492
493         /* protect against various other ints mucking around with the PSG */
494         local_irq_save(flags);
495   
496         sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
497         sound_ym.wd_data = (side == 0) ? sound_ym.rd_data_reg_sel | 0x01 :
498                                          sound_ym.rd_data_reg_sel & 0xfe;
499
500         local_irq_restore(flags);
501 }
502
503
504 /* Select a drive, update the FDC's track register and set the correct
505  * clock speed for this disk's type.
506  */
507
508 static void fd_select_drive( int drive )
509 {
510         unsigned long flags;
511         unsigned char tmp;
512   
513         if (drive == SelectedDrive)
514           return;
515
516         /* protect against various other ints mucking around with the PSG */
517         local_irq_save(flags);
518         sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
519         tmp = sound_ym.rd_data_reg_sel;
520         sound_ym.wd_data = (tmp | DSKDRVNONE) & ~(drive == 0 ? DSKDRV0 : DSKDRV1);
521         atari_dont_touch_floppy_select = 1;
522         local_irq_restore(flags);
523
524         /* restore track register to saved value */
525         FDC_WRITE( FDCREG_TRACK, UD.track );
526         udelay(25);
527
528         /* select 8/16 MHz */
529         if (UDT)
530                 if (ATARIHW_PRESENT(FDCSPEED))
531                         dma_wd.fdc_speed = UDT->fdc_speed;
532         
533         SelectedDrive = drive;
534 }
535
536
537 /* Deselect both drives. */
538
539 static void fd_deselect( void )
540 {
541         unsigned long flags;
542
543         /* protect against various other ints mucking around with the PSG */
544         local_irq_save(flags);
545         atari_dont_touch_floppy_select = 0;
546         sound_ym.rd_data_reg_sel=14;    /* Select PSG Port A */
547         sound_ym.wd_data = (sound_ym.rd_data_reg_sel |
548                             (MACH_IS_FALCON ? 3 : 7)); /* no drives selected */
549         /* On Falcon, the drive B select line is used on the printer port, so
550          * leave it alone... */
551         SelectedDrive = -1;
552         local_irq_restore(flags);
553 }
554
555
556 /* This timer function deselects the drives when the FDC switched the
557  * motor off. The deselection cannot happen earlier because the FDC
558  * counts the index signals, which arrive only if one drive is selected.
559  */
560
561 static void fd_motor_off_timer(struct timer_list *unused)
562 {
563         unsigned char status;
564
565         if (SelectedDrive < 0)
566                 /* no drive selected, needn't deselect anyone */
567                 return;
568
569         if (stdma_islocked())
570                 goto retry;
571
572         status = FDC_READ( FDCREG_STATUS );
573
574         if (!(status & 0x80)) {
575                 /* motor already turned off by FDC -> deselect drives */
576                 MotorOn = 0;
577                 fd_deselect();
578                 return;
579         }
580         /* not yet off, try again */
581
582   retry:
583         /* Test again later; if tested too often, it seems there is no disk
584          * in the drive and the FDC will leave the motor on forever (or,
585          * at least until a disk is inserted). So we'll test only twice
586          * per second from then on...
587          */
588         mod_timer(&motor_off_timer,
589                   jiffies + (MotorOffTrys++ < FD_MOTOR_OFF_MAXTRY ? HZ/20 : HZ/2));
590 }
591
592
593 /* This function is repeatedly called to detect disk changes (as good
594  * as possible) and keep track of the current state of the write protection.
595  */
596
597 static void check_change(struct timer_list *unused)
598 {
599         static int    drive = 0;
600
601         unsigned long flags;
602         unsigned char old_porta;
603         int                       stat;
604
605         if (++drive > 1 || !UD.connected)
606                 drive = 0;
607
608         /* protect against various other ints mucking around with the PSG */
609         local_irq_save(flags);
610
611         if (!stdma_islocked()) {
612                 sound_ym.rd_data_reg_sel = 14;
613                 old_porta = sound_ym.rd_data_reg_sel;
614                 sound_ym.wd_data = (old_porta | DSKDRVNONE) &
615                                        ~(drive == 0 ? DSKDRV0 : DSKDRV1);
616                 stat = !!(FDC_READ( FDCREG_STATUS ) & FDCSTAT_WPROT);
617                 sound_ym.wd_data = old_porta;
618
619                 if (stat != UD.wpstat) {
620                         DPRINT(( "wpstat[%d] = %d\n", drive, stat ));
621                         UD.wpstat = stat;
622                         set_bit (drive, &changed_floppies);
623                 }
624         }
625         local_irq_restore(flags);
626
627         start_check_change_timer();
628 }
629
630  
631 /* Handling of the Head Settling Flag: This flag should be set after each
632  * seek operation, because we don't use seeks with verify.
633  */
634
635 static inline void set_head_settle_flag(void)
636 {
637         HeadSettleFlag = FDCCMDADD_E;
638 }
639
640 static inline int get_head_settle_flag(void)
641 {
642         int     tmp = HeadSettleFlag;
643         HeadSettleFlag = 0;
644         return( tmp );
645 }
646
647 static inline void copy_buffer(void *from, void *to)
648 {
649         ulong *p1 = (ulong *)from, *p2 = (ulong *)to;
650         int cnt;
651
652         for (cnt = 512/4; cnt; cnt--)
653                 *p2++ = *p1++;
654 }
655
656 /* General Interrupt Handling */
657
658 static void (*FloppyIRQHandler)( int status ) = NULL;
659
660 static irqreturn_t floppy_irq (int irq, void *dummy)
661 {
662         unsigned char status;
663         void (*handler)( int );
664
665         handler = xchg(&FloppyIRQHandler, NULL);
666
667         if (handler) {
668                 nop();
669                 status = FDC_READ( FDCREG_STATUS );
670                 DPRINT(("FDC irq, status = %02x handler = %08lx\n",status,(unsigned long)handler));
671                 handler( status );
672         }
673         else {
674                 DPRINT(("FDC irq, no handler\n"));
675         }
676         return IRQ_HANDLED;
677 }
678
679
680 /* Error handling: If some error happened, retry some times, then
681  * recalibrate, then try again, and fail after MAX_ERRORS.
682  */
683
684 static void fd_error( void )
685 {
686         if (IsFormatting) {
687                 IsFormatting = 0;
688                 FormatError = 1;
689                 complete(&format_wait);
690                 return;
691         }
692
693         if (!fd_request)
694                 return;
695
696         fd_request->error_count++;
697         if (fd_request->error_count >= MAX_ERRORS) {
698                 printk(KERN_ERR "fd%d: too many errors.\n", SelectedDrive );
699                 fd_end_request_cur(BLK_STS_IOERR);
700         }
701         else if (fd_request->error_count == RECALIBRATE_ERRORS) {
702                 printk(KERN_WARNING "fd%d: recalibrating\n", SelectedDrive );
703                 if (SelectedDrive != -1)
704                         SUD.track = -1;
705         }
706 }
707
708
709
710 #define SET_IRQ_HANDLER(proc) do { FloppyIRQHandler = (proc); } while(0)
711
712
713 /* ---------- Formatting ---------- */
714
715 #define FILL(n,val)             \
716     do {                        \
717         memset( p, val, n );    \
718         p += n;                 \
719     } while(0)
720
721 static int do_format(int drive, int type, struct atari_format_descr *desc)
722 {
723         struct request_queue *q = unit[drive].disk->queue;
724         unsigned char   *p;
725         int sect, nsect;
726         unsigned long   flags;
727         int ret;
728
729         blk_mq_freeze_queue(q);
730         blk_mq_quiesce_queue(q);
731
732         local_irq_save(flags);
733         stdma_lock(floppy_irq, NULL);
734         atari_turnon_irq( IRQ_MFP_FDC ); /* should be already, just to be sure */
735         local_irq_restore(flags);
736
737         if (type) {
738                 if (--type >= NUM_DISK_MINORS ||
739                     minor2disktype[type].drive_types > DriveType) {
740                         ret = -EINVAL;
741                         goto out;
742                 }
743                 type = minor2disktype[type].index;
744                 UDT = &atari_disk_type[type];
745         }
746
747         if (!UDT || desc->track >= UDT->blocks/UDT->spt/2 || desc->head >= 2) {
748                 ret = -EINVAL;
749                 goto out;
750         }
751
752         nsect = UDT->spt;
753         p = TrackBuffer;
754         /* The track buffer is used for the raw track data, so its
755            contents become invalid! */
756         BufferDrive = -1;
757         /* stop deselect timer */
758         del_timer( &motor_off_timer );
759
760         FILL( 60 * (nsect / 9), 0x4e );
761         for( sect = 0; sect < nsect; ++sect ) {
762                 FILL( 12, 0 );
763                 FILL( 3, 0xf5 );
764                 *p++ = 0xfe;
765                 *p++ = desc->track;
766                 *p++ = desc->head;
767                 *p++ = (nsect + sect - desc->sect_offset) % nsect + 1;
768                 *p++ = 2;
769                 *p++ = 0xf7;
770                 FILL( 22, 0x4e );
771                 FILL( 12, 0 );
772                 FILL( 3, 0xf5 );
773                 *p++ = 0xfb;
774                 FILL( 512, 0xe5 );
775                 *p++ = 0xf7;
776                 FILL( 40, 0x4e );
777         }
778         FILL( TrackBuffer+BUFFER_SIZE-p, 0x4e );
779
780         IsFormatting = 1;
781         FormatError = 0;
782         ReqTrack = desc->track;
783         ReqSide  = desc->head;
784         do_fd_action( drive );
785
786         wait_for_completion(&format_wait);
787
788         ret = FormatError ? -EIO : 0;
789 out:
790         blk_mq_unquiesce_queue(q);
791         blk_mq_unfreeze_queue(q);
792         return ret;
793 }
794
795
796 /* do_fd_action() is the general procedure for a fd request: All
797  * required parameter settings (drive select, side select, track
798  * position) are checked and set if needed. For each of these
799  * parameters and the actual reading or writing exist two functions:
800  * one that starts the setting (or skips it if possible) and one
801  * callback for the "done" interrupt. Each done func calls the next
802  * set function to propagate the request down to fd_rwsec_done().
803  */
804
805 static void do_fd_action( int drive )
806 {
807         DPRINT(("do_fd_action\n"));
808         
809         if (UseTrackbuffer && !IsFormatting) {
810         repeat:
811             if (IS_BUFFERED( drive, ReqSide, ReqTrack )) {
812                 if (ReqCmd == READ) {
813                     copy_buffer( SECTOR_BUFFER(ReqSector), ReqData );
814                     if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
815                         /* read next sector */
816                         setup_req_params( drive );
817                         goto repeat;
818                     }
819                     else {
820                         /* all sectors finished */
821                         fd_end_request_cur(BLK_STS_OK);
822                         return;
823                     }
824                 }
825                 else {
826                     /* cmd == WRITE, pay attention to track buffer
827                      * consistency! */
828                     copy_buffer( ReqData, SECTOR_BUFFER(ReqSector) );
829                 }
830             }
831         }
832
833         if (SelectedDrive != drive)
834                 fd_select_drive( drive );
835     
836         if (UD.track == -1)
837                 fd_calibrate();
838         else if (UD.track != ReqTrack << UDT->stretch)
839                 fd_seek();
840         else if (IsFormatting)
841                 fd_writetrack();
842         else
843                 fd_rwsec();
844 }
845
846
847 /* Seek to track 0 if the current track is unknown */
848
849 static void fd_calibrate( void )
850 {
851         if (SUD.track >= 0) {
852                 fd_calibrate_done( 0 );
853                 return;
854         }
855
856         if (ATARIHW_PRESENT(FDCSPEED))
857                 dma_wd.fdc_speed = 0;   /* always seek with 8 Mhz */;
858         DPRINT(("fd_calibrate\n"));
859         SET_IRQ_HANDLER( fd_calibrate_done );
860         /* we can't verify, since the speed may be incorrect */
861         FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | SUD.steprate );
862
863         NeedSeek = 1;
864         MotorOn = 1;
865         start_timeout();
866         /* wait for IRQ */
867 }
868
869
870 static void fd_calibrate_done( int status )
871 {
872         DPRINT(("fd_calibrate_done()\n"));
873         stop_timeout();
874     
875         /* set the correct speed now */
876         if (ATARIHW_PRESENT(FDCSPEED))
877                 dma_wd.fdc_speed = SUDT->fdc_speed;
878         if (status & FDCSTAT_RECNF) {
879                 printk(KERN_ERR "fd%d: restore failed\n", SelectedDrive );
880                 fd_error();
881         }
882         else {
883                 SUD.track = 0;
884                 fd_seek();
885         }
886 }
887   
888   
889 /* Seek the drive to the requested track. The drive must have been
890  * calibrated at some point before this.
891  */
892   
893 static void fd_seek( void )
894 {
895         if (SUD.track == ReqTrack << SUDT->stretch) {
896                 fd_seek_done( 0 );
897                 return;
898         }
899
900         if (ATARIHW_PRESENT(FDCSPEED)) {
901                 dma_wd.fdc_speed = 0;   /* always seek witch 8 Mhz */
902                 MFPDELAY();
903         }
904
905         DPRINT(("fd_seek() to track %d\n",ReqTrack));
906         FDC_WRITE( FDCREG_DATA, ReqTrack << SUDT->stretch);
907         udelay(25);
908         SET_IRQ_HANDLER( fd_seek_done );
909         FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK | SUD.steprate );
910
911         MotorOn = 1;
912         set_head_settle_flag();
913         start_timeout();
914         /* wait for IRQ */
915 }
916
917
918 static void fd_seek_done( int status )
919 {
920         DPRINT(("fd_seek_done()\n"));
921         stop_timeout();
922         
923         /* set the correct speed */
924         if (ATARIHW_PRESENT(FDCSPEED))
925                 dma_wd.fdc_speed = SUDT->fdc_speed;
926         if (status & FDCSTAT_RECNF) {
927                 printk(KERN_ERR "fd%d: seek error (to track %d)\n",
928                                 SelectedDrive, ReqTrack );
929                 /* we don't know exactly which track we are on now! */
930                 SUD.track = -1;
931                 fd_error();
932         }
933         else {
934                 SUD.track = ReqTrack << SUDT->stretch;
935                 NeedSeek = 0;
936                 if (IsFormatting)
937                         fd_writetrack();
938                 else
939                         fd_rwsec();
940         }
941 }
942
943
944 /* This does the actual reading/writing after positioning the head
945  * over the correct track.
946  */
947
948 static int MultReadInProgress = 0;
949
950
951 static void fd_rwsec( void )
952 {
953         unsigned long paddr, flags;
954         unsigned int  rwflag, old_motoron;
955         unsigned int track;
956         
957         DPRINT(("fd_rwsec(), Sec=%d, Access=%c\n",ReqSector, ReqCmd == WRITE ? 'w' : 'r' ));
958         if (ReqCmd == WRITE) {
959                 if (ATARIHW_PRESENT(EXTD_DMA)) {
960                         paddr = virt_to_phys(ReqData);
961                 }
962                 else {
963                         copy_buffer( ReqData, DMABuffer );
964                         paddr = PhysDMABuffer;
965                 }
966                 dma_cache_maintenance( paddr, 512, 1 );
967                 rwflag = 0x100;
968         }
969         else {
970                 if (read_track)
971                         paddr = PhysTrackBuffer;
972                 else
973                         paddr = ATARIHW_PRESENT(EXTD_DMA) ? 
974                                 virt_to_phys(ReqData) : PhysDMABuffer;
975                 rwflag = 0;
976         }
977
978         fd_select_side( ReqSide );
979   
980         /* Start sector of this operation */
981         FDC_WRITE( FDCREG_SECTOR, read_track ? 1 : ReqSector );
982         MFPDELAY();
983         /* Cheat for track if stretch != 0 */
984         if (SUDT->stretch) {
985                 track = FDC_READ( FDCREG_TRACK);
986                 MFPDELAY();
987                 FDC_WRITE( FDCREG_TRACK, track >> SUDT->stretch);
988         }
989         udelay(25);
990   
991         /* Setup DMA */
992         local_irq_save(flags);
993         dma_wd.dma_lo = (unsigned char)paddr;
994         MFPDELAY();
995         paddr >>= 8;
996         dma_wd.dma_md = (unsigned char)paddr;
997         MFPDELAY();
998         paddr >>= 8;
999         if (ATARIHW_PRESENT(EXTD_DMA))
1000                 st_dma_ext_dmahi = (unsigned short)paddr;
1001         else
1002                 dma_wd.dma_hi = (unsigned char)paddr;
1003         MFPDELAY();
1004         local_irq_restore(flags);
1005   
1006         /* Clear FIFO and switch DMA to correct mode */  
1007         dma_wd.dma_mode_status = 0x90 | rwflag;  
1008         MFPDELAY();
1009         dma_wd.dma_mode_status = 0x90 | (rwflag ^ 0x100);  
1010         MFPDELAY();
1011         dma_wd.dma_mode_status = 0x90 | rwflag;
1012         MFPDELAY();
1013   
1014         /* How many sectors for DMA */
1015         dma_wd.fdc_acces_seccount = read_track ? SUDT->spt : 1;
1016   
1017         udelay(25);  
1018   
1019         /* Start operation */
1020         dma_wd.dma_mode_status = FDCSELREG_STP | rwflag;
1021         udelay(25);
1022         SET_IRQ_HANDLER( fd_rwsec_done );
1023         dma_wd.fdc_acces_seccount =
1024           (get_head_settle_flag() |
1025            (rwflag ? FDCCMD_WRSEC : (FDCCMD_RDSEC | (read_track ? FDCCMDADD_M : 0))));
1026
1027         old_motoron = MotorOn;
1028         MotorOn = 1;
1029         NeedSeek = 1;
1030         /* wait for interrupt */
1031
1032         if (read_track) {
1033                 /* If reading a whole track, wait about one disk rotation and
1034                  * then check if all sectors are read. The FDC will even
1035                  * search for the first non-existent sector and need 1 sec to
1036                  * recognise that it isn't present :-(
1037                  */
1038                 MultReadInProgress = 1;
1039                 mod_timer(&readtrack_timer,
1040                           /* 1 rot. + 5 rot.s if motor was off  */
1041                           jiffies + HZ/5 + (old_motoron ? 0 : HZ));
1042         }
1043         start_timeout();
1044 }
1045
1046     
1047 static void fd_readtrack_check(struct timer_list *unused)
1048 {
1049         unsigned long flags, addr, addr2;
1050
1051         local_irq_save(flags);
1052
1053         if (!MultReadInProgress) {
1054                 /* This prevents a race condition that could arise if the
1055                  * interrupt is triggered while the calling of this timer
1056                  * callback function takes place. The IRQ function then has
1057                  * already cleared 'MultReadInProgress'  when flow of control
1058                  * gets here.
1059                  */
1060                 local_irq_restore(flags);
1061                 return;
1062         }
1063
1064         /* get the current DMA address */
1065         /* ++ f.a. read twice to avoid being fooled by switcher */
1066         addr = 0;
1067         do {
1068                 addr2 = addr;
1069                 addr = dma_wd.dma_lo & 0xff;
1070                 MFPDELAY();
1071                 addr |= (dma_wd.dma_md & 0xff) << 8;
1072                 MFPDELAY();
1073                 if (ATARIHW_PRESENT( EXTD_DMA ))
1074                         addr |= (st_dma_ext_dmahi & 0xffff) << 16;
1075                 else
1076                         addr |= (dma_wd.dma_hi & 0xff) << 16;
1077                 MFPDELAY();
1078         } while(addr != addr2);
1079   
1080         if (addr >= PhysTrackBuffer + SUDT->spt*512) {
1081                 /* already read enough data, force an FDC interrupt to stop
1082                  * the read operation
1083                  */
1084                 SET_IRQ_HANDLER( NULL );
1085                 MultReadInProgress = 0;
1086                 local_irq_restore(flags);
1087                 DPRINT(("fd_readtrack_check(): done\n"));
1088                 FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1089                 udelay(25);
1090
1091                 /* No error until now -- the FDC would have interrupted
1092                  * otherwise!
1093                  */
1094                 fd_rwsec_done1(0);
1095         }
1096         else {
1097                 /* not yet finished, wait another tenth rotation */
1098                 local_irq_restore(flags);
1099                 DPRINT(("fd_readtrack_check(): not yet finished\n"));
1100                 mod_timer(&readtrack_timer, jiffies + HZ/5/10);
1101         }
1102 }
1103
1104
1105 static void fd_rwsec_done( int status )
1106 {
1107         DPRINT(("fd_rwsec_done()\n"));
1108
1109         if (read_track) {
1110                 del_timer(&readtrack_timer);
1111                 if (!MultReadInProgress)
1112                         return;
1113                 MultReadInProgress = 0;
1114         }
1115         fd_rwsec_done1(status);
1116 }
1117
1118 static void fd_rwsec_done1(int status)
1119 {
1120         unsigned int track;
1121
1122         stop_timeout();
1123         
1124         /* Correct the track if stretch != 0 */
1125         if (SUDT->stretch) {
1126                 track = FDC_READ( FDCREG_TRACK);
1127                 MFPDELAY();
1128                 FDC_WRITE( FDCREG_TRACK, track << SUDT->stretch);
1129         }
1130
1131         if (!UseTrackbuffer) {
1132                 dma_wd.dma_mode_status = 0x90;
1133                 MFPDELAY();
1134                 if (!(dma_wd.dma_mode_status & 0x01)) {
1135                         printk(KERN_ERR "fd%d: DMA error\n", SelectedDrive );
1136                         goto err_end;
1137                 }
1138         }
1139         MFPDELAY();
1140
1141         if (ReqCmd == WRITE && (status & FDCSTAT_WPROT)) {
1142                 printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
1143                 goto err_end;
1144         }       
1145         if ((status & FDCSTAT_RECNF) &&
1146             /* RECNF is no error after a multiple read when the FDC
1147                searched for a non-existent sector! */
1148             !(read_track && FDC_READ(FDCREG_SECTOR) > SUDT->spt)) {
1149                 if (Probing) {
1150                         if (SUDT > atari_disk_type) {
1151                             if (SUDT[-1].blocks > ReqBlock) {
1152                                 /* try another disk type */
1153                                 SUDT--;
1154                                 set_capacity(unit[SelectedDrive].disk,
1155                                                         SUDT->blocks);
1156                             } else
1157                                 Probing = 0;
1158                         }
1159                         else {
1160                                 if (SUD.flags & FTD_MSG)
1161                                         printk(KERN_INFO "fd%d: Auto-detected floppy type %s\n",
1162                                                SelectedDrive, SUDT->name );
1163                                 Probing=0;
1164                         }
1165                 } else {        
1166 /* record not found, but not probing. Maybe stretch wrong ? Restart probing */
1167                         if (SUD.autoprobe) {
1168                                 SUDT = atari_disk_type + StartDiskType[DriveType];
1169                                 set_capacity(unit[SelectedDrive].disk,
1170                                                         SUDT->blocks);
1171                                 Probing = 1;
1172                         }
1173                 }
1174                 if (Probing) {
1175                         if (ATARIHW_PRESENT(FDCSPEED)) {
1176                                 dma_wd.fdc_speed = SUDT->fdc_speed;
1177                                 MFPDELAY();
1178                         }
1179                         setup_req_params( SelectedDrive );
1180                         BufferDrive = -1;
1181                         do_fd_action( SelectedDrive );
1182                         return;
1183                 }
1184
1185                 printk(KERN_ERR "fd%d: sector %d not found (side %d, track %d)\n",
1186                        SelectedDrive, FDC_READ (FDCREG_SECTOR), ReqSide, ReqTrack );
1187                 goto err_end;
1188         }
1189         if (status & FDCSTAT_CRC) {
1190                 printk(KERN_ERR "fd%d: CRC error (side %d, track %d, sector %d)\n",
1191                        SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
1192                 goto err_end;
1193         }
1194         if (status & FDCSTAT_LOST) {
1195                 printk(KERN_ERR "fd%d: lost data (side %d, track %d, sector %d)\n",
1196                        SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
1197                 goto err_end;
1198         }
1199
1200         Probing = 0;
1201         
1202         if (ReqCmd == READ) {
1203                 if (!read_track) {
1204                         void *addr;
1205                         addr = ATARIHW_PRESENT( EXTD_DMA ) ? ReqData : DMABuffer;
1206                         dma_cache_maintenance( virt_to_phys(addr), 512, 0 );
1207                         if (!ATARIHW_PRESENT( EXTD_DMA ))
1208                                 copy_buffer (addr, ReqData);
1209                 } else {
1210                         dma_cache_maintenance( PhysTrackBuffer, MaxSectors[DriveType] * 512, 0 );
1211                         BufferDrive = SelectedDrive;
1212                         BufferSide  = ReqSide;
1213                         BufferTrack = ReqTrack;
1214                         copy_buffer (SECTOR_BUFFER (ReqSector), ReqData);
1215                 }
1216         }
1217   
1218         if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
1219                 /* read next sector */
1220                 setup_req_params( SelectedDrive );
1221                 do_fd_action( SelectedDrive );
1222         }
1223         else {
1224                 /* all sectors finished */
1225                 finish_fdc();
1226                 fd_end_request_cur(BLK_STS_OK);
1227         }
1228         return;
1229   
1230   err_end:
1231         BufferDrive = -1;
1232         fd_error();
1233 }
1234
1235
1236 static void fd_writetrack( void )
1237 {
1238         unsigned long paddr, flags;
1239         unsigned int track;
1240         
1241         DPRINT(("fd_writetrack() Tr=%d Si=%d\n", ReqTrack, ReqSide ));
1242
1243         paddr = PhysTrackBuffer;
1244         dma_cache_maintenance( paddr, BUFFER_SIZE, 1 );
1245
1246         fd_select_side( ReqSide );
1247   
1248         /* Cheat for track if stretch != 0 */
1249         if (SUDT->stretch) {
1250                 track = FDC_READ( FDCREG_TRACK);
1251                 MFPDELAY();
1252                 FDC_WRITE(FDCREG_TRACK,track >> SUDT->stretch);
1253         }
1254         udelay(40);
1255   
1256         /* Setup DMA */
1257         local_irq_save(flags);
1258         dma_wd.dma_lo = (unsigned char)paddr;
1259         MFPDELAY();
1260         paddr >>= 8;
1261         dma_wd.dma_md = (unsigned char)paddr;
1262         MFPDELAY();
1263         paddr >>= 8;
1264         if (ATARIHW_PRESENT( EXTD_DMA ))
1265                 st_dma_ext_dmahi = (unsigned short)paddr;
1266         else
1267                 dma_wd.dma_hi = (unsigned char)paddr;
1268         MFPDELAY();
1269         local_irq_restore(flags);
1270   
1271         /* Clear FIFO and switch DMA to correct mode */  
1272         dma_wd.dma_mode_status = 0x190;  
1273         MFPDELAY();
1274         dma_wd.dma_mode_status = 0x90;  
1275         MFPDELAY();
1276         dma_wd.dma_mode_status = 0x190;
1277         MFPDELAY();
1278   
1279         /* How many sectors for DMA */
1280         dma_wd.fdc_acces_seccount = BUFFER_SIZE/512;
1281         udelay(40);  
1282   
1283         /* Start operation */
1284         dma_wd.dma_mode_status = FDCSELREG_STP | 0x100;
1285         udelay(40);
1286         SET_IRQ_HANDLER( fd_writetrack_done );
1287         dma_wd.fdc_acces_seccount = FDCCMD_WRTRA | get_head_settle_flag(); 
1288
1289         MotorOn = 1;
1290         start_timeout();
1291         /* wait for interrupt */
1292 }
1293
1294
1295 static void fd_writetrack_done( int status )
1296 {
1297         DPRINT(("fd_writetrack_done()\n"));
1298
1299         stop_timeout();
1300
1301         if (status & FDCSTAT_WPROT) {
1302                 printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
1303                 goto err_end;
1304         }       
1305         if (status & FDCSTAT_LOST) {
1306                 printk(KERN_ERR "fd%d: lost data (side %d, track %d)\n",
1307                                 SelectedDrive, ReqSide, ReqTrack );
1308                 goto err_end;
1309         }
1310
1311         complete(&format_wait);
1312         return;
1313
1314   err_end:
1315         fd_error();
1316 }
1317
1318 static void fd_times_out(struct timer_list *unused)
1319 {
1320         atari_disable_irq( IRQ_MFP_FDC );
1321         if (!FloppyIRQHandler) goto end; /* int occurred after timer was fired, but
1322                                           * before we came here... */
1323
1324         SET_IRQ_HANDLER( NULL );
1325         /* If the timeout occurred while the readtrack_check timer was
1326          * active, we need to cancel it, else bad things will happen */
1327         if (UseTrackbuffer)
1328                 del_timer( &readtrack_timer );
1329         FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1330         udelay( 25 );
1331         
1332         printk(KERN_ERR "floppy timeout\n" );
1333         fd_error();
1334   end:
1335         atari_enable_irq( IRQ_MFP_FDC );
1336 }
1337
1338
1339 /* The (noop) seek operation here is needed to make the WP bit in the
1340  * FDC status register accessible for check_change. If the last disk
1341  * operation would have been a RDSEC, this bit would always read as 0
1342  * no matter what :-( To save time, the seek goes to the track we're
1343  * already on.
1344  */
1345
1346 static void finish_fdc( void )
1347 {
1348         if (!NeedSeek) {
1349                 finish_fdc_done( 0 );
1350         }
1351         else {
1352                 DPRINT(("finish_fdc: dummy seek started\n"));
1353                 FDC_WRITE (FDCREG_DATA, SUD.track);
1354                 SET_IRQ_HANDLER( finish_fdc_done );
1355                 FDC_WRITE (FDCREG_CMD, FDCCMD_SEEK);
1356                 MotorOn = 1;
1357                 start_timeout();
1358                 /* we must wait for the IRQ here, because the ST-DMA
1359                    is released immediately afterwards and the interrupt
1360                    may be delivered to the wrong driver. */
1361           }
1362 }
1363
1364
1365 static void finish_fdc_done( int dummy )
1366 {
1367         unsigned long flags;
1368
1369         DPRINT(("finish_fdc_done entered\n"));
1370         stop_timeout();
1371         NeedSeek = 0;
1372
1373         if (timer_pending(&fd_timer) && time_before(fd_timer.expires, jiffies + 5))
1374                 /* If the check for a disk change is done too early after this
1375                  * last seek command, the WP bit still reads wrong :-((
1376                  */
1377                 mod_timer(&fd_timer, jiffies + 5);
1378         else
1379                 start_check_change_timer();
1380         start_motor_off_timer();
1381
1382         local_irq_save(flags);
1383         stdma_release();
1384         local_irq_restore(flags);
1385
1386         DPRINT(("finish_fdc() finished\n"));
1387 }
1388
1389 /* The detection of disk changes is a dark chapter in Atari history :-(
1390  * Because the "Drive ready" signal isn't present in the Atari
1391  * hardware, one has to rely on the "Write Protect". This works fine,
1392  * as long as no write protected disks are used. TOS solves this
1393  * problem by introducing tri-state logic ("maybe changed") and
1394  * looking at the serial number in block 0. This isn't possible for
1395  * Linux, since the floppy driver can't make assumptions about the
1396  * filesystem used on the disk and thus the contents of block 0. I've
1397  * chosen the method to always say "The disk was changed" if it is
1398  * unsure whether it was. This implies that every open or mount
1399  * invalidates the disk buffers if you work with write protected
1400  * disks. But at least this is better than working with incorrect data
1401  * due to unrecognised disk changes.
1402  */
1403
1404 static unsigned int floppy_check_events(struct gendisk *disk,
1405                                         unsigned int clearing)
1406 {
1407         struct atari_floppy_struct *p = disk->private_data;
1408         unsigned int drive = p - unit;
1409         if (test_bit (drive, &fake_change)) {
1410                 /* simulated change (e.g. after formatting) */
1411                 return DISK_EVENT_MEDIA_CHANGE;
1412         }
1413         if (test_bit (drive, &changed_floppies)) {
1414                 /* surely changed (the WP signal changed at least once) */
1415                 return DISK_EVENT_MEDIA_CHANGE;
1416         }
1417         if (UD.wpstat) {
1418                 /* WP is on -> could be changed: to be sure, buffers should be
1419                  * invalidated...
1420                  */
1421                 return DISK_EVENT_MEDIA_CHANGE;
1422         }
1423
1424         return 0;
1425 }
1426
1427 static int floppy_revalidate(struct gendisk *disk)
1428 {
1429         struct atari_floppy_struct *p = disk->private_data;
1430         unsigned int drive = p - unit;
1431
1432         if (test_bit(drive, &changed_floppies) ||
1433             test_bit(drive, &fake_change) ||
1434             p->disktype == 0) {
1435                 if (UD.flags & FTD_MSG)
1436                         printk(KERN_ERR "floppy: clear format %p!\n", UDT);
1437                 BufferDrive = -1;
1438                 clear_bit(drive, &fake_change);
1439                 clear_bit(drive, &changed_floppies);
1440                 /* MSch: clearing geometry makes sense only for autoprobe
1441                    formats, for 'permanent user-defined' parameter:
1442                    restore default_params[] here if flagged valid! */
1443                 if (default_params[drive].blocks == 0)
1444                         UDT = NULL;
1445                 else
1446                         UDT = &default_params[drive];
1447         }
1448         return 0;
1449 }
1450
1451
1452 /* This sets up the global variables describing the current request. */
1453
1454 static void setup_req_params( int drive )
1455 {
1456         int block = ReqBlock + ReqCnt;
1457
1458         ReqTrack = block / UDT->spt;
1459         ReqSector = block - ReqTrack * UDT->spt + 1;
1460         ReqSide = ReqTrack & 1;
1461         ReqTrack >>= 1;
1462         ReqData = ReqBuffer + 512 * ReqCnt;
1463
1464         if (UseTrackbuffer)
1465                 read_track = (ReqCmd == READ && fd_request->error_count == 0);
1466         else
1467                 read_track = 0;
1468
1469         DPRINT(("Request params: Si=%d Tr=%d Se=%d Data=%08lx\n",ReqSide,
1470                         ReqTrack, ReqSector, (unsigned long)ReqData ));
1471 }
1472
1473 static blk_status_t ataflop_queue_rq(struct blk_mq_hw_ctx *hctx,
1474                                      const struct blk_mq_queue_data *bd)
1475 {
1476         struct atari_floppy_struct *floppy = bd->rq->rq_disk->private_data;
1477         int drive = floppy - unit;
1478         int type = floppy->type;
1479
1480         DPRINT(("Queue request: drive %d type %d last %d\n", drive, type, bd->last));
1481
1482         spin_lock_irq(&ataflop_lock);
1483         if (fd_request) {
1484                 spin_unlock_irq(&ataflop_lock);
1485                 return BLK_STS_DEV_RESOURCE;
1486         }
1487         if (!stdma_try_lock(floppy_irq, NULL))  {
1488                 spin_unlock_irq(&ataflop_lock);
1489                 return BLK_STS_RESOURCE;
1490         }
1491         fd_request = bd->rq;
1492         blk_mq_start_request(fd_request);
1493
1494         atari_disable_irq( IRQ_MFP_FDC );
1495
1496         IsFormatting = 0;
1497
1498         if (!UD.connected) {
1499                 /* drive not connected */
1500                 printk(KERN_ERR "Unknown Device: fd%d\n", drive );
1501                 fd_end_request_cur(BLK_STS_IOERR);
1502                 goto out;
1503         }
1504                 
1505         if (type == 0) {
1506                 if (!UDT) {
1507                         Probing = 1;
1508                         UDT = atari_disk_type + StartDiskType[DriveType];
1509                         set_capacity(floppy->disk, UDT->blocks);
1510                         UD.autoprobe = 1;
1511                 }
1512         } 
1513         else {
1514                 /* user supplied disk type */
1515                 if (--type >= NUM_DISK_MINORS) {
1516                         printk(KERN_WARNING "fd%d: invalid disk format", drive );
1517                         fd_end_request_cur(BLK_STS_IOERR);
1518                         goto out;
1519                 }
1520                 if (minor2disktype[type].drive_types > DriveType)  {
1521                         printk(KERN_WARNING "fd%d: unsupported disk format", drive );
1522                         fd_end_request_cur(BLK_STS_IOERR);
1523                         goto out;
1524                 }
1525                 type = minor2disktype[type].index;
1526                 UDT = &atari_disk_type[type];
1527                 set_capacity(floppy->disk, UDT->blocks);
1528                 UD.autoprobe = 0;
1529         }
1530
1531         /* stop deselect timer */
1532         del_timer( &motor_off_timer );
1533                 
1534         ReqCnt = 0;
1535         ReqCmd = rq_data_dir(fd_request);
1536         ReqBlock = blk_rq_pos(fd_request);
1537         ReqBuffer = bio_data(fd_request->bio);
1538         setup_req_params( drive );
1539         do_fd_action( drive );
1540
1541         atari_enable_irq( IRQ_MFP_FDC );
1542
1543 out:
1544         spin_unlock_irq(&ataflop_lock);
1545         return BLK_STS_OK;
1546 }
1547
1548 static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode,
1549                     unsigned int cmd, unsigned long param)
1550 {
1551         struct gendisk *disk = bdev->bd_disk;
1552         struct atari_floppy_struct *floppy = disk->private_data;
1553         int drive = floppy - unit;
1554         int type = floppy->type;
1555         struct atari_format_descr fmt_desc;
1556         struct atari_disk_type *dtp;
1557         struct floppy_struct getprm;
1558         int settype;
1559         struct floppy_struct setprm;
1560         void __user *argp = (void __user *)param;
1561
1562         switch (cmd) {
1563         case FDGETPRM:
1564                 if (type) {
1565                         if (--type >= NUM_DISK_MINORS)
1566                                 return -ENODEV;
1567                         if (minor2disktype[type].drive_types > DriveType)
1568                                 return -ENODEV;
1569                         type = minor2disktype[type].index;
1570                         dtp = &atari_disk_type[type];
1571                         if (UD.flags & FTD_MSG)
1572                             printk (KERN_ERR "floppy%d: found dtp %p name %s!\n",
1573                                 drive, dtp, dtp->name);
1574                 }
1575                 else {
1576                         if (!UDT)
1577                                 return -ENXIO;
1578                         else
1579                                 dtp = UDT;
1580                 }
1581                 memset((void *)&getprm, 0, sizeof(getprm));
1582                 getprm.size = dtp->blocks;
1583                 getprm.sect = dtp->spt;
1584                 getprm.head = 2;
1585                 getprm.track = dtp->blocks/dtp->spt/2;
1586                 getprm.stretch = dtp->stretch;
1587                 if (copy_to_user(argp, &getprm, sizeof(getprm)))
1588                         return -EFAULT;
1589                 return 0;
1590         }
1591         switch (cmd) {
1592         case FDSETPRM:
1593         case FDDEFPRM:
1594                 /* 
1595                  * MSch 7/96: simple 'set geometry' case: just set the
1596                  * 'default' device params (minor == 0).
1597                  * Currently, the drive geometry is cleared after each
1598                  * disk change and subsequent revalidate()! simple
1599                  * implementation of FDDEFPRM: save geometry from a
1600                  * FDDEFPRM call and restore it in floppy_revalidate() !
1601                  */
1602
1603                 /* get the parameters from user space */
1604                 if (floppy->ref != 1 && floppy->ref != -1)
1605                         return -EBUSY;
1606                 if (copy_from_user(&setprm, argp, sizeof(setprm)))
1607                         return -EFAULT;
1608                 /* 
1609                  * first of all: check for floppy change and revalidate, 
1610                  * or the next access will revalidate - and clear UDT :-(
1611                  */
1612
1613                 if (floppy_check_events(disk, 0))
1614                         floppy_revalidate(disk);
1615
1616                 if (UD.flags & FTD_MSG)
1617                     printk (KERN_INFO "floppy%d: setting size %d spt %d str %d!\n",
1618                         drive, setprm.size, setprm.sect, setprm.stretch);
1619
1620                 /* what if type > 0 here? Overwrite specified entry ? */
1621                 if (type) {
1622                         /* refuse to re-set a predefined type for now */
1623                         return -EINVAL;
1624                 }
1625
1626                 /* 
1627                  * type == 0: first look for a matching entry in the type list,
1628                  * and set the UD.disktype field to use the perdefined entry.
1629                  * TODO: add user-defined format to head of autoprobe list ? 
1630                  * Useful to include the user-type for future autodetection!
1631                  */
1632
1633                 for (settype = 0; settype < NUM_DISK_MINORS; settype++) {
1634                         int setidx = 0;
1635                         if (minor2disktype[settype].drive_types > DriveType) {
1636                                 /* skip this one, invalid for drive ... */
1637                                 continue;
1638                         }
1639                         setidx = minor2disktype[settype].index;
1640                         dtp = &atari_disk_type[setidx];
1641
1642                         /* found matching entry ?? */
1643                         if (   dtp->blocks  == setprm.size 
1644                             && dtp->spt     == setprm.sect
1645                             && dtp->stretch == setprm.stretch ) {
1646                                 if (UD.flags & FTD_MSG)
1647                                     printk (KERN_INFO "floppy%d: setting %s %p!\n",
1648                                         drive, dtp->name, dtp);
1649                                 UDT = dtp;
1650                                 set_capacity(floppy->disk, UDT->blocks);
1651
1652                                 if (cmd == FDDEFPRM) {
1653                                   /* save settings as permanent default type */
1654                                   default_params[drive].name    = dtp->name;
1655                                   default_params[drive].spt     = dtp->spt;
1656                                   default_params[drive].blocks  = dtp->blocks;
1657                                   default_params[drive].fdc_speed = dtp->fdc_speed;
1658                                   default_params[drive].stretch = dtp->stretch;
1659                                 }
1660                                 
1661                                 return 0;
1662                         }
1663
1664                 }
1665
1666                 /* no matching disk type found above - setting user_params */
1667
1668                 if (cmd == FDDEFPRM) {
1669                         /* set permanent type */
1670                         dtp = &default_params[drive];
1671                 } else
1672                         /* set user type (reset by disk change!) */
1673                         dtp = &user_params[drive];
1674
1675                 dtp->name   = "user format";
1676                 dtp->blocks = setprm.size;
1677                 dtp->spt    = setprm.sect;
1678                 if (setprm.sect > 14) 
1679                         dtp->fdc_speed = 3;
1680                 else
1681                         dtp->fdc_speed = 0;
1682                 dtp->stretch = setprm.stretch;
1683
1684                 if (UD.flags & FTD_MSG)
1685                         printk (KERN_INFO "floppy%d: blk %d spt %d str %d!\n",
1686                                 drive, dtp->blocks, dtp->spt, dtp->stretch);
1687
1688                 /* sanity check */
1689                 if (setprm.track != dtp->blocks/dtp->spt/2 ||
1690                     setprm.head != 2)
1691                         return -EINVAL;
1692
1693                 UDT = dtp;
1694                 set_capacity(floppy->disk, UDT->blocks);
1695
1696                 return 0;
1697         case FDMSGON:
1698                 UD.flags |= FTD_MSG;
1699                 return 0;
1700         case FDMSGOFF:
1701                 UD.flags &= ~FTD_MSG;
1702                 return 0;
1703         case FDSETEMSGTRESH:
1704                 return -EINVAL;
1705         case FDFMTBEG:
1706                 return 0;
1707         case FDFMTTRK:
1708                 if (floppy->ref != 1 && floppy->ref != -1)
1709                         return -EBUSY;
1710                 if (copy_from_user(&fmt_desc, argp, sizeof(fmt_desc)))
1711                         return -EFAULT;
1712                 return do_format(drive, type, &fmt_desc);
1713         case FDCLRPRM:
1714                 UDT = NULL;
1715                 /* MSch: invalidate default_params */
1716                 default_params[drive].blocks  = 0;
1717                 set_capacity(floppy->disk, MAX_DISK_SIZE * 2);
1718                 /* Fall through */
1719         case FDFMTEND:
1720         case FDFLUSH:
1721                 /* invalidate the buffer track to force a reread */
1722                 BufferDrive = -1;
1723                 set_bit(drive, &fake_change);
1724                 check_disk_change(bdev);
1725                 return 0;
1726         default:
1727                 return -EINVAL;
1728         }
1729 }
1730
1731 static int fd_ioctl(struct block_device *bdev, fmode_t mode,
1732                              unsigned int cmd, unsigned long arg)
1733 {
1734         int ret;
1735
1736         mutex_lock(&ataflop_mutex);
1737         ret = fd_locked_ioctl(bdev, mode, cmd, arg);
1738         mutex_unlock(&ataflop_mutex);
1739
1740         return ret;
1741 }
1742
1743 /* Initialize the 'unit' variable for drive 'drive' */
1744
1745 static void __init fd_probe( int drive )
1746 {
1747         UD.connected = 0;
1748         UDT  = NULL;
1749
1750         if (!fd_test_drive_present( drive ))
1751                 return;
1752
1753         UD.connected = 1;
1754         UD.track     = 0;
1755         switch( UserSteprate[drive] ) {
1756         case 2:
1757                 UD.steprate = FDCSTEP_2;
1758                 break;
1759         case 3:
1760                 UD.steprate = FDCSTEP_3;
1761                 break;
1762         case 6:
1763                 UD.steprate = FDCSTEP_6;
1764                 break;
1765         case 12:
1766                 UD.steprate = FDCSTEP_12;
1767                 break;
1768         default: /* should be -1 for "not set by user" */
1769                 if (ATARIHW_PRESENT( FDCSPEED ) || MACH_IS_MEDUSA)
1770                         UD.steprate = FDCSTEP_3;
1771                 else
1772                         UD.steprate = FDCSTEP_6;
1773                 break;
1774         }
1775         MotorOn = 1;    /* from probe restore operation! */
1776 }
1777
1778
1779 /* This function tests the physical presence of a floppy drive (not
1780  * whether a disk is inserted). This is done by issuing a restore
1781  * command, waiting max. 2 seconds (that should be enough to move the
1782  * head across the whole disk) and looking at the state of the "TR00"
1783  * signal. This should now be raised if there is a drive connected
1784  * (and there is no hardware failure :-) Otherwise, the drive is
1785  * declared absent.
1786  */
1787
1788 static int __init fd_test_drive_present( int drive )
1789 {
1790         unsigned long timeout;
1791         unsigned char status;
1792         int ok;
1793         
1794         if (drive >= (MACH_IS_FALCON ? 1 : 2)) return( 0 );
1795         fd_select_drive( drive );
1796
1797         /* disable interrupt temporarily */
1798         atari_turnoff_irq( IRQ_MFP_FDC );
1799         FDC_WRITE (FDCREG_TRACK, 0xff00);
1800         FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | FDCCMDADD_H | FDCSTEP_6 );
1801
1802         timeout = jiffies + 2*HZ+HZ/2;
1803         while (time_before(jiffies, timeout))
1804                 if (!(st_mfp.par_dt_reg & 0x20))
1805                         break;
1806
1807         status = FDC_READ( FDCREG_STATUS );
1808         ok = (status & FDCSTAT_TR00) != 0;
1809
1810         /* force interrupt to abort restore operation (FDC would try
1811          * about 50 seconds!) */
1812         FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1813         udelay(500);
1814         status = FDC_READ( FDCREG_STATUS );
1815         udelay(20);
1816
1817         if (ok) {
1818                 /* dummy seek command to make WP bit accessible */
1819                 FDC_WRITE( FDCREG_DATA, 0 );
1820                 FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK );
1821                 while( st_mfp.par_dt_reg & 0x20 )
1822                         ;
1823                 status = FDC_READ( FDCREG_STATUS );
1824         }
1825
1826         atari_turnon_irq( IRQ_MFP_FDC );
1827         return( ok );
1828 }
1829
1830
1831 /* Look how many and which kind of drives are connected. If there are
1832  * floppies, additionally start the disk-change and motor-off timers.
1833  */
1834
1835 static void __init config_types( void )
1836 {
1837         int drive, cnt = 0;
1838
1839         /* for probing drives, set the FDC speed to 8 MHz */
1840         if (ATARIHW_PRESENT(FDCSPEED))
1841                 dma_wd.fdc_speed = 0;
1842
1843         printk(KERN_INFO "Probing floppy drive(s):\n");
1844         for( drive = 0; drive < FD_MAX_UNITS; drive++ ) {
1845                 fd_probe( drive );
1846                 if (UD.connected) {
1847                         printk(KERN_INFO "fd%d\n", drive);
1848                         ++cnt;
1849                 }
1850         }
1851
1852         if (FDC_READ( FDCREG_STATUS ) & FDCSTAT_BUSY) {
1853                 /* If FDC is still busy from probing, give it another FORCI
1854                  * command to abort the operation. If this isn't done, the FDC
1855                  * will interrupt later and its IRQ line stays low, because
1856                  * the status register isn't read. And this will block any
1857                  * interrupts on this IRQ line :-(
1858                  */
1859                 FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1860                 udelay(500);
1861                 FDC_READ( FDCREG_STATUS );
1862                 udelay(20);
1863         }
1864         
1865         if (cnt > 0) {
1866                 start_motor_off_timer();
1867                 if (cnt == 1) fd_select_drive( 0 );
1868                 start_check_change_timer();
1869         }
1870 }
1871
1872 /*
1873  * floppy_open check for aliasing (/dev/fd0 can be the same as
1874  * /dev/PS0 etc), and disallows simultaneous access to the same
1875  * drive with different device numbers.
1876  */
1877
1878 static int floppy_open(struct block_device *bdev, fmode_t mode)
1879 {
1880         struct atari_floppy_struct *p = bdev->bd_disk->private_data;
1881         int type  = MINOR(bdev->bd_dev) >> 2;
1882
1883         DPRINT(("fd_open: type=%d\n",type));
1884         if (p->ref && p->type != type)
1885                 return -EBUSY;
1886
1887         if (p->ref == -1 || (p->ref && mode & FMODE_EXCL))
1888                 return -EBUSY;
1889
1890         if (mode & FMODE_EXCL)
1891                 p->ref = -1;
1892         else
1893                 p->ref++;
1894
1895         p->type = type;
1896
1897         if (mode & FMODE_NDELAY)
1898                 return 0;
1899
1900         if (mode & (FMODE_READ|FMODE_WRITE)) {
1901                 check_disk_change(bdev);
1902                 if (mode & FMODE_WRITE) {
1903                         if (p->wpstat) {
1904                                 if (p->ref < 0)
1905                                         p->ref = 0;
1906                                 else
1907                                         p->ref--;
1908                                 return -EROFS;
1909                         }
1910                 }
1911         }
1912         return 0;
1913 }
1914
1915 static int floppy_unlocked_open(struct block_device *bdev, fmode_t mode)
1916 {
1917         int ret;
1918
1919         mutex_lock(&ataflop_mutex);
1920         ret = floppy_open(bdev, mode);
1921         mutex_unlock(&ataflop_mutex);
1922
1923         return ret;
1924 }
1925
1926 static void floppy_release(struct gendisk *disk, fmode_t mode)
1927 {
1928         struct atari_floppy_struct *p = disk->private_data;
1929         mutex_lock(&ataflop_mutex);
1930         if (p->ref < 0)
1931                 p->ref = 0;
1932         else if (!p->ref--) {
1933                 printk(KERN_ERR "floppy_release with fd_ref == 0");
1934                 p->ref = 0;
1935         }
1936         mutex_unlock(&ataflop_mutex);
1937 }
1938
1939 static const struct block_device_operations floppy_fops = {
1940         .owner          = THIS_MODULE,
1941         .open           = floppy_unlocked_open,
1942         .release        = floppy_release,
1943         .ioctl          = fd_ioctl,
1944         .check_events   = floppy_check_events,
1945         .revalidate_disk= floppy_revalidate,
1946 };
1947
1948 static const struct blk_mq_ops ataflop_mq_ops = {
1949         .queue_rq = ataflop_queue_rq,
1950 };
1951
1952 static struct kobject *floppy_find(dev_t dev, int *part, void *data)
1953 {
1954         int drive = *part & 3;
1955         int type  = *part >> 2;
1956         if (drive >= FD_MAX_UNITS || type > NUM_DISK_MINORS)
1957                 return NULL;
1958         *part = 0;
1959         return get_disk_and_module(unit[drive].disk);
1960 }
1961
1962 static int __init atari_floppy_init (void)
1963 {
1964         int i;
1965         int ret;
1966
1967         if (!MACH_IS_ATARI)
1968                 /* Amiga, Mac, ... don't have Atari-compatible floppy :-) */
1969                 return -ENODEV;
1970
1971         if (register_blkdev(FLOPPY_MAJOR,"fd"))
1972                 return -EBUSY;
1973
1974         for (i = 0; i < FD_MAX_UNITS; i++) {
1975                 unit[i].disk = alloc_disk(1);
1976                 if (!unit[i].disk) {
1977                         ret = -ENOMEM;
1978                         goto err;
1979                 }
1980
1981                 unit[i].disk->queue = blk_mq_init_sq_queue(&unit[i].tag_set,
1982                                                            &ataflop_mq_ops, 2,
1983                                                            BLK_MQ_F_SHOULD_MERGE);
1984                 if (IS_ERR(unit[i].disk->queue)) {
1985                         put_disk(unit[i].disk);
1986                         ret = PTR_ERR(unit[i].disk->queue);
1987                         unit[i].disk->queue = NULL;
1988                         goto err;
1989                 }
1990         }
1991
1992         if (UseTrackbuffer < 0)
1993                 /* not set by user -> use default: for now, we turn
1994                    track buffering off for all Medusas, though it
1995                    could be used with ones that have a counter
1996                    card. But the test is too hard :-( */
1997                 UseTrackbuffer = !MACH_IS_MEDUSA;
1998
1999         /* initialize variables */
2000         SelectedDrive = -1;
2001         BufferDrive = -1;
2002
2003         DMABuffer = atari_stram_alloc(BUFFER_SIZE+512, "ataflop");
2004         if (!DMABuffer) {
2005                 printk(KERN_ERR "atari_floppy_init: cannot get dma buffer\n");
2006                 ret = -ENOMEM;
2007                 goto err;
2008         }
2009         TrackBuffer = DMABuffer + 512;
2010         PhysDMABuffer = atari_stram_to_phys(DMABuffer);
2011         PhysTrackBuffer = virt_to_phys(TrackBuffer);
2012         BufferDrive = BufferSide = BufferTrack = -1;
2013
2014         for (i = 0; i < FD_MAX_UNITS; i++) {
2015                 unit[i].track = -1;
2016                 unit[i].flags = 0;
2017                 unit[i].disk->major = FLOPPY_MAJOR;
2018                 unit[i].disk->first_minor = i;
2019                 sprintf(unit[i].disk->disk_name, "fd%d", i);
2020                 unit[i].disk->fops = &floppy_fops;
2021                 unit[i].disk->events = DISK_EVENT_MEDIA_CHANGE;
2022                 unit[i].disk->private_data = &unit[i];
2023                 set_capacity(unit[i].disk, MAX_DISK_SIZE * 2);
2024                 add_disk(unit[i].disk);
2025         }
2026
2027         blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
2028                                 floppy_find, NULL, NULL);
2029
2030         printk(KERN_INFO "Atari floppy driver: max. %cD, %strack buffering\n",
2031                DriveType == 0 ? 'D' : DriveType == 1 ? 'H' : 'E',
2032                UseTrackbuffer ? "" : "no ");
2033         config_types();
2034
2035         return 0;
2036
2037 err:
2038         while (--i >= 0) {
2039                 struct gendisk *disk = unit[i].disk;
2040
2041                 blk_cleanup_queue(disk->queue);
2042                 blk_mq_free_tag_set(&unit[i].tag_set);
2043                 put_disk(unit[i].disk);
2044         }
2045
2046         unregister_blkdev(FLOPPY_MAJOR, "fd");
2047         return ret;
2048 }
2049
2050 #ifndef MODULE
2051 static int __init atari_floppy_setup(char *str)
2052 {
2053         int ints[3 + FD_MAX_UNITS];
2054         int i;
2055
2056         if (!MACH_IS_ATARI)
2057                 return 0;
2058
2059         str = get_options(str, 3 + FD_MAX_UNITS, ints);
2060         
2061         if (ints[0] < 1) {
2062                 printk(KERN_ERR "ataflop_setup: no arguments!\n" );
2063                 return 0;
2064         }
2065         else if (ints[0] > 2+FD_MAX_UNITS) {
2066                 printk(KERN_ERR "ataflop_setup: too many arguments\n" );
2067         }
2068
2069         if (ints[1] < 0 || ints[1] > 2)
2070                 printk(KERN_ERR "ataflop_setup: bad drive type\n" );
2071         else
2072                 DriveType = ints[1];
2073
2074         if (ints[0] >= 2)
2075                 UseTrackbuffer = (ints[2] > 0);
2076
2077         for( i = 3; i <= ints[0] && i-3 < FD_MAX_UNITS; ++i ) {
2078                 if (ints[i] != 2 && ints[i] != 3 && ints[i] != 6 && ints[i] != 12)
2079                         printk(KERN_ERR "ataflop_setup: bad steprate\n" );
2080                 else
2081                         UserSteprate[i-3] = ints[i];
2082         }
2083         return 1;
2084 }
2085
2086 __setup("floppy=", atari_floppy_setup);
2087 #endif
2088
2089 static void __exit atari_floppy_exit(void)
2090 {
2091         int i;
2092         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
2093         for (i = 0; i < FD_MAX_UNITS; i++) {
2094                 del_gendisk(unit[i].disk);
2095                 blk_cleanup_queue(unit[i].disk->queue);
2096                 blk_mq_free_tag_set(&unit[i].tag_set);
2097                 put_disk(unit[i].disk);
2098         }
2099         unregister_blkdev(FLOPPY_MAJOR, "fd");
2100
2101         del_timer_sync(&fd_timer);
2102         atari_stram_free( DMABuffer );
2103 }
2104
2105 module_init(atari_floppy_init)
2106 module_exit(atari_floppy_exit)
2107
2108 MODULE_LICENSE("GPL");