GNU Linux-libre 5.10.215-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         DPRINT(("fd_end_request_cur(), bytes %d of %d\n",
460                 blk_rq_cur_bytes(fd_request),
461                 blk_rq_bytes(fd_request)));
462
463         if (!blk_update_request(fd_request, err,
464                                 blk_rq_cur_bytes(fd_request))) {
465                 DPRINT(("calling __blk_mq_end_request()\n"));
466                 __blk_mq_end_request(fd_request, err);
467                 fd_request = NULL;
468         } else {
469                 /* requeue rest of request */
470                 DPRINT(("calling blk_mq_requeue_request()\n"));
471                 blk_mq_requeue_request(fd_request, true);
472                 fd_request = NULL;
473         }
474 }
475
476 static inline void start_motor_off_timer(void)
477 {
478         mod_timer(&motor_off_timer, jiffies + FD_MOTOR_OFF_DELAY);
479         MotorOffTrys = 0;
480 }
481
482 static inline void start_check_change_timer( void )
483 {
484         mod_timer(&fd_timer, jiffies + CHECK_CHANGE_DELAY);
485 }
486
487 static inline void start_timeout(void)
488 {
489         mod_timer(&timeout_timer, jiffies + FLOPPY_TIMEOUT);
490 }
491
492 static inline void stop_timeout(void)
493 {
494         del_timer(&timeout_timer);
495 }
496
497 /* Select the side to use. */
498
499 static void fd_select_side( int side )
500 {
501         unsigned long flags;
502
503         /* protect against various other ints mucking around with the PSG */
504         local_irq_save(flags);
505   
506         sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
507         sound_ym.wd_data = (side == 0) ? sound_ym.rd_data_reg_sel | 0x01 :
508                                          sound_ym.rd_data_reg_sel & 0xfe;
509
510         local_irq_restore(flags);
511 }
512
513
514 /* Select a drive, update the FDC's track register and set the correct
515  * clock speed for this disk's type.
516  */
517
518 static void fd_select_drive( int drive )
519 {
520         unsigned long flags;
521         unsigned char tmp;
522   
523         if (drive == SelectedDrive)
524           return;
525
526         /* protect against various other ints mucking around with the PSG */
527         local_irq_save(flags);
528         sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
529         tmp = sound_ym.rd_data_reg_sel;
530         sound_ym.wd_data = (tmp | DSKDRVNONE) & ~(drive == 0 ? DSKDRV0 : DSKDRV1);
531         atari_dont_touch_floppy_select = 1;
532         local_irq_restore(flags);
533
534         /* restore track register to saved value */
535         FDC_WRITE( FDCREG_TRACK, UD.track );
536         udelay(25);
537
538         /* select 8/16 MHz */
539         if (UDT)
540                 if (ATARIHW_PRESENT(FDCSPEED))
541                         dma_wd.fdc_speed = UDT->fdc_speed;
542         
543         SelectedDrive = drive;
544 }
545
546
547 /* Deselect both drives. */
548
549 static void fd_deselect( void )
550 {
551         unsigned long flags;
552
553         /* protect against various other ints mucking around with the PSG */
554         local_irq_save(flags);
555         atari_dont_touch_floppy_select = 0;
556         sound_ym.rd_data_reg_sel=14;    /* Select PSG Port A */
557         sound_ym.wd_data = (sound_ym.rd_data_reg_sel |
558                             (MACH_IS_FALCON ? 3 : 7)); /* no drives selected */
559         /* On Falcon, the drive B select line is used on the printer port, so
560          * leave it alone... */
561         SelectedDrive = -1;
562         local_irq_restore(flags);
563 }
564
565
566 /* This timer function deselects the drives when the FDC switched the
567  * motor off. The deselection cannot happen earlier because the FDC
568  * counts the index signals, which arrive only if one drive is selected.
569  */
570
571 static void fd_motor_off_timer(struct timer_list *unused)
572 {
573         unsigned char status;
574
575         if (SelectedDrive < 0)
576                 /* no drive selected, needn't deselect anyone */
577                 return;
578
579         if (stdma_islocked())
580                 goto retry;
581
582         status = FDC_READ( FDCREG_STATUS );
583
584         if (!(status & 0x80)) {
585                 /* motor already turned off by FDC -> deselect drives */
586                 MotorOn = 0;
587                 fd_deselect();
588                 return;
589         }
590         /* not yet off, try again */
591
592   retry:
593         /* Test again later; if tested too often, it seems there is no disk
594          * in the drive and the FDC will leave the motor on forever (or,
595          * at least until a disk is inserted). So we'll test only twice
596          * per second from then on...
597          */
598         mod_timer(&motor_off_timer,
599                   jiffies + (MotorOffTrys++ < FD_MOTOR_OFF_MAXTRY ? HZ/20 : HZ/2));
600 }
601
602
603 /* This function is repeatedly called to detect disk changes (as good
604  * as possible) and keep track of the current state of the write protection.
605  */
606
607 static void check_change(struct timer_list *unused)
608 {
609         static int    drive = 0;
610
611         unsigned long flags;
612         unsigned char old_porta;
613         int                       stat;
614
615         if (++drive > 1 || !UD.connected)
616                 drive = 0;
617
618         /* protect against various other ints mucking around with the PSG */
619         local_irq_save(flags);
620
621         if (!stdma_islocked()) {
622                 sound_ym.rd_data_reg_sel = 14;
623                 old_porta = sound_ym.rd_data_reg_sel;
624                 sound_ym.wd_data = (old_porta | DSKDRVNONE) &
625                                        ~(drive == 0 ? DSKDRV0 : DSKDRV1);
626                 stat = !!(FDC_READ( FDCREG_STATUS ) & FDCSTAT_WPROT);
627                 sound_ym.wd_data = old_porta;
628
629                 if (stat != UD.wpstat) {
630                         DPRINT(( "wpstat[%d] = %d\n", drive, stat ));
631                         UD.wpstat = stat;
632                         set_bit (drive, &changed_floppies);
633                 }
634         }
635         local_irq_restore(flags);
636
637         start_check_change_timer();
638 }
639
640  
641 /* Handling of the Head Settling Flag: This flag should be set after each
642  * seek operation, because we don't use seeks with verify.
643  */
644
645 static inline void set_head_settle_flag(void)
646 {
647         HeadSettleFlag = FDCCMDADD_E;
648 }
649
650 static inline int get_head_settle_flag(void)
651 {
652         int     tmp = HeadSettleFlag;
653         HeadSettleFlag = 0;
654         return( tmp );
655 }
656
657 static inline void copy_buffer(void *from, void *to)
658 {
659         ulong *p1 = (ulong *)from, *p2 = (ulong *)to;
660         int cnt;
661
662         for (cnt = 512/4; cnt; cnt--)
663                 *p2++ = *p1++;
664 }
665
666 /* General Interrupt Handling */
667
668 static void (*FloppyIRQHandler)( int status ) = NULL;
669
670 static irqreturn_t floppy_irq (int irq, void *dummy)
671 {
672         unsigned char status;
673         void (*handler)( int );
674
675         handler = xchg(&FloppyIRQHandler, NULL);
676
677         if (handler) {
678                 nop();
679                 status = FDC_READ( FDCREG_STATUS );
680                 DPRINT(("FDC irq, status = %02x handler = %08lx\n",status,(unsigned long)handler));
681                 handler( status );
682         }
683         else {
684                 DPRINT(("FDC irq, no handler\n"));
685         }
686         return IRQ_HANDLED;
687 }
688
689
690 /* Error handling: If some error happened, retry some times, then
691  * recalibrate, then try again, and fail after MAX_ERRORS.
692  */
693
694 static void fd_error( void )
695 {
696         if (IsFormatting) {
697                 IsFormatting = 0;
698                 FormatError = 1;
699                 complete(&format_wait);
700                 return;
701         }
702
703         if (!fd_request)
704                 return;
705
706         fd_request->error_count++;
707         if (fd_request->error_count >= MAX_ERRORS) {
708                 printk(KERN_ERR "fd%d: too many errors.\n", SelectedDrive );
709                 fd_end_request_cur(BLK_STS_IOERR);
710                 finish_fdc();
711                 return;
712         }
713         else if (fd_request->error_count == RECALIBRATE_ERRORS) {
714                 printk(KERN_WARNING "fd%d: recalibrating\n", SelectedDrive );
715                 if (SelectedDrive != -1)
716                         SUD.track = -1;
717         }
718         /* need to re-run request to recalibrate */
719         atari_disable_irq( IRQ_MFP_FDC );
720
721         setup_req_params( SelectedDrive );
722         do_fd_action( SelectedDrive );
723
724         atari_enable_irq( IRQ_MFP_FDC );
725 }
726
727
728
729 #define SET_IRQ_HANDLER(proc) do { FloppyIRQHandler = (proc); } while(0)
730
731
732 /* ---------- Formatting ---------- */
733
734 #define FILL(n,val)             \
735     do {                        \
736         memset( p, val, n );    \
737         p += n;                 \
738     } while(0)
739
740 static int do_format(int drive, int type, struct atari_format_descr *desc)
741 {
742         struct request_queue *q = unit[drive].disk->queue;
743         unsigned char   *p;
744         int sect, nsect;
745         unsigned long   flags;
746         int ret;
747
748         blk_mq_freeze_queue(q);
749         blk_mq_quiesce_queue(q);
750
751         local_irq_save(flags);
752         stdma_lock(floppy_irq, NULL);
753         atari_turnon_irq( IRQ_MFP_FDC ); /* should be already, just to be sure */
754         local_irq_restore(flags);
755
756         if (type) {
757                 if (--type >= NUM_DISK_MINORS ||
758                     minor2disktype[type].drive_types > DriveType) {
759                         finish_fdc();
760                         ret = -EINVAL;
761                         goto out;
762                 }
763                 type = minor2disktype[type].index;
764                 UDT = &atari_disk_type[type];
765         }
766
767         if (!UDT || desc->track >= UDT->blocks/UDT->spt/2 || desc->head >= 2) {
768                 finish_fdc();
769                 ret = -EINVAL;
770                 goto out;
771         }
772
773         nsect = UDT->spt;
774         p = TrackBuffer;
775         /* The track buffer is used for the raw track data, so its
776            contents become invalid! */
777         BufferDrive = -1;
778         /* stop deselect timer */
779         del_timer( &motor_off_timer );
780
781         FILL( 60 * (nsect / 9), 0x4e );
782         for( sect = 0; sect < nsect; ++sect ) {
783                 FILL( 12, 0 );
784                 FILL( 3, 0xf5 );
785                 *p++ = 0xfe;
786                 *p++ = desc->track;
787                 *p++ = desc->head;
788                 *p++ = (nsect + sect - desc->sect_offset) % nsect + 1;
789                 *p++ = 2;
790                 *p++ = 0xf7;
791                 FILL( 22, 0x4e );
792                 FILL( 12, 0 );
793                 FILL( 3, 0xf5 );
794                 *p++ = 0xfb;
795                 FILL( 512, 0xe5 );
796                 *p++ = 0xf7;
797                 FILL( 40, 0x4e );
798         }
799         FILL( TrackBuffer+BUFFER_SIZE-p, 0x4e );
800
801         IsFormatting = 1;
802         FormatError = 0;
803         ReqTrack = desc->track;
804         ReqSide  = desc->head;
805         do_fd_action( drive );
806
807         wait_for_completion(&format_wait);
808
809         finish_fdc();
810         ret = FormatError ? -EIO : 0;
811 out:
812         blk_mq_unquiesce_queue(q);
813         blk_mq_unfreeze_queue(q);
814         return ret;
815 }
816
817
818 /* do_fd_action() is the general procedure for a fd request: All
819  * required parameter settings (drive select, side select, track
820  * position) are checked and set if needed. For each of these
821  * parameters and the actual reading or writing exist two functions:
822  * one that starts the setting (or skips it if possible) and one
823  * callback for the "done" interrupt. Each done func calls the next
824  * set function to propagate the request down to fd_rwsec_done().
825  */
826
827 static void do_fd_action( int drive )
828 {
829         DPRINT(("do_fd_action\n"));
830         
831         if (UseTrackbuffer && !IsFormatting) {
832         repeat:
833             if (IS_BUFFERED( drive, ReqSide, ReqTrack )) {
834                 if (ReqCmd == READ) {
835                     copy_buffer( SECTOR_BUFFER(ReqSector), ReqData );
836                     if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
837                         /* read next sector */
838                         setup_req_params( drive );
839                         goto repeat;
840                     }
841                     else {
842                         /* all sectors finished */
843                         fd_end_request_cur(BLK_STS_OK);
844                         finish_fdc();
845                         return;
846                     }
847                 }
848                 else {
849                     /* cmd == WRITE, pay attention to track buffer
850                      * consistency! */
851                     copy_buffer( ReqData, SECTOR_BUFFER(ReqSector) );
852                 }
853             }
854         }
855
856         if (SelectedDrive != drive)
857                 fd_select_drive( drive );
858     
859         if (UD.track == -1)
860                 fd_calibrate();
861         else if (UD.track != ReqTrack << UDT->stretch)
862                 fd_seek();
863         else if (IsFormatting)
864                 fd_writetrack();
865         else
866                 fd_rwsec();
867 }
868
869
870 /* Seek to track 0 if the current track is unknown */
871
872 static void fd_calibrate( void )
873 {
874         if (SUD.track >= 0) {
875                 fd_calibrate_done( 0 );
876                 return;
877         }
878
879         if (ATARIHW_PRESENT(FDCSPEED))
880                 dma_wd.fdc_speed = 0;   /* always seek with 8 Mhz */
881         DPRINT(("fd_calibrate\n"));
882         SET_IRQ_HANDLER( fd_calibrate_done );
883         /* we can't verify, since the speed may be incorrect */
884         FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | SUD.steprate );
885
886         NeedSeek = 1;
887         MotorOn = 1;
888         start_timeout();
889         /* wait for IRQ */
890 }
891
892
893 static void fd_calibrate_done( int status )
894 {
895         DPRINT(("fd_calibrate_done()\n"));
896         stop_timeout();
897     
898         /* set the correct speed now */
899         if (ATARIHW_PRESENT(FDCSPEED))
900                 dma_wd.fdc_speed = SUDT->fdc_speed;
901         if (status & FDCSTAT_RECNF) {
902                 printk(KERN_ERR "fd%d: restore failed\n", SelectedDrive );
903                 fd_error();
904         }
905         else {
906                 SUD.track = 0;
907                 fd_seek();
908         }
909 }
910   
911   
912 /* Seek the drive to the requested track. The drive must have been
913  * calibrated at some point before this.
914  */
915   
916 static void fd_seek( void )
917 {
918         if (SUD.track == ReqTrack << SUDT->stretch) {
919                 fd_seek_done( 0 );
920                 return;
921         }
922
923         if (ATARIHW_PRESENT(FDCSPEED)) {
924                 dma_wd.fdc_speed = 0;   /* always seek witch 8 Mhz */
925                 MFPDELAY();
926         }
927
928         DPRINT(("fd_seek() to track %d\n",ReqTrack));
929         FDC_WRITE( FDCREG_DATA, ReqTrack << SUDT->stretch);
930         udelay(25);
931         SET_IRQ_HANDLER( fd_seek_done );
932         FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK | SUD.steprate );
933
934         MotorOn = 1;
935         set_head_settle_flag();
936         start_timeout();
937         /* wait for IRQ */
938 }
939
940
941 static void fd_seek_done( int status )
942 {
943         DPRINT(("fd_seek_done()\n"));
944         stop_timeout();
945         
946         /* set the correct speed */
947         if (ATARIHW_PRESENT(FDCSPEED))
948                 dma_wd.fdc_speed = SUDT->fdc_speed;
949         if (status & FDCSTAT_RECNF) {
950                 printk(KERN_ERR "fd%d: seek error (to track %d)\n",
951                                 SelectedDrive, ReqTrack );
952                 /* we don't know exactly which track we are on now! */
953                 SUD.track = -1;
954                 fd_error();
955         }
956         else {
957                 SUD.track = ReqTrack << SUDT->stretch;
958                 NeedSeek = 0;
959                 if (IsFormatting)
960                         fd_writetrack();
961                 else
962                         fd_rwsec();
963         }
964 }
965
966
967 /* This does the actual reading/writing after positioning the head
968  * over the correct track.
969  */
970
971 static int MultReadInProgress = 0;
972
973
974 static void fd_rwsec( void )
975 {
976         unsigned long paddr, flags;
977         unsigned int  rwflag, old_motoron;
978         unsigned int track;
979         
980         DPRINT(("fd_rwsec(), Sec=%d, Access=%c\n",ReqSector, ReqCmd == WRITE ? 'w' : 'r' ));
981         if (ReqCmd == WRITE) {
982                 if (ATARIHW_PRESENT(EXTD_DMA)) {
983                         paddr = virt_to_phys(ReqData);
984                 }
985                 else {
986                         copy_buffer( ReqData, DMABuffer );
987                         paddr = PhysDMABuffer;
988                 }
989                 dma_cache_maintenance( paddr, 512, 1 );
990                 rwflag = 0x100;
991         }
992         else {
993                 if (read_track)
994                         paddr = PhysTrackBuffer;
995                 else
996                         paddr = ATARIHW_PRESENT(EXTD_DMA) ? 
997                                 virt_to_phys(ReqData) : PhysDMABuffer;
998                 rwflag = 0;
999         }
1000
1001         fd_select_side( ReqSide );
1002   
1003         /* Start sector of this operation */
1004         FDC_WRITE( FDCREG_SECTOR, read_track ? 1 : ReqSector );
1005         MFPDELAY();
1006         /* Cheat for track if stretch != 0 */
1007         if (SUDT->stretch) {
1008                 track = FDC_READ( FDCREG_TRACK);
1009                 MFPDELAY();
1010                 FDC_WRITE( FDCREG_TRACK, track >> SUDT->stretch);
1011         }
1012         udelay(25);
1013   
1014         /* Setup DMA */
1015         local_irq_save(flags);
1016         dma_wd.dma_lo = (unsigned char)paddr;
1017         MFPDELAY();
1018         paddr >>= 8;
1019         dma_wd.dma_md = (unsigned char)paddr;
1020         MFPDELAY();
1021         paddr >>= 8;
1022         if (ATARIHW_PRESENT(EXTD_DMA))
1023                 st_dma_ext_dmahi = (unsigned short)paddr;
1024         else
1025                 dma_wd.dma_hi = (unsigned char)paddr;
1026         MFPDELAY();
1027         local_irq_restore(flags);
1028   
1029         /* Clear FIFO and switch DMA to correct mode */  
1030         dma_wd.dma_mode_status = 0x90 | rwflag;  
1031         MFPDELAY();
1032         dma_wd.dma_mode_status = 0x90 | (rwflag ^ 0x100);  
1033         MFPDELAY();
1034         dma_wd.dma_mode_status = 0x90 | rwflag;
1035         MFPDELAY();
1036   
1037         /* How many sectors for DMA */
1038         dma_wd.fdc_acces_seccount = read_track ? SUDT->spt : 1;
1039   
1040         udelay(25);  
1041   
1042         /* Start operation */
1043         dma_wd.dma_mode_status = FDCSELREG_STP | rwflag;
1044         udelay(25);
1045         SET_IRQ_HANDLER( fd_rwsec_done );
1046         dma_wd.fdc_acces_seccount =
1047           (get_head_settle_flag() |
1048            (rwflag ? FDCCMD_WRSEC : (FDCCMD_RDSEC | (read_track ? FDCCMDADD_M : 0))));
1049
1050         old_motoron = MotorOn;
1051         MotorOn = 1;
1052         NeedSeek = 1;
1053         /* wait for interrupt */
1054
1055         if (read_track) {
1056                 /* If reading a whole track, wait about one disk rotation and
1057                  * then check if all sectors are read. The FDC will even
1058                  * search for the first non-existent sector and need 1 sec to
1059                  * recognise that it isn't present :-(
1060                  */
1061                 MultReadInProgress = 1;
1062                 mod_timer(&readtrack_timer,
1063                           /* 1 rot. + 5 rot.s if motor was off  */
1064                           jiffies + HZ/5 + (old_motoron ? 0 : HZ));
1065         }
1066         start_timeout();
1067 }
1068
1069     
1070 static void fd_readtrack_check(struct timer_list *unused)
1071 {
1072         unsigned long flags, addr, addr2;
1073
1074         local_irq_save(flags);
1075
1076         if (!MultReadInProgress) {
1077                 /* This prevents a race condition that could arise if the
1078                  * interrupt is triggered while the calling of this timer
1079                  * callback function takes place. The IRQ function then has
1080                  * already cleared 'MultReadInProgress'  when flow of control
1081                  * gets here.
1082                  */
1083                 local_irq_restore(flags);
1084                 return;
1085         }
1086
1087         /* get the current DMA address */
1088         /* ++ f.a. read twice to avoid being fooled by switcher */
1089         addr = 0;
1090         do {
1091                 addr2 = addr;
1092                 addr = dma_wd.dma_lo & 0xff;
1093                 MFPDELAY();
1094                 addr |= (dma_wd.dma_md & 0xff) << 8;
1095                 MFPDELAY();
1096                 if (ATARIHW_PRESENT( EXTD_DMA ))
1097                         addr |= (st_dma_ext_dmahi & 0xffff) << 16;
1098                 else
1099                         addr |= (dma_wd.dma_hi & 0xff) << 16;
1100                 MFPDELAY();
1101         } while(addr != addr2);
1102   
1103         if (addr >= PhysTrackBuffer + SUDT->spt*512) {
1104                 /* already read enough data, force an FDC interrupt to stop
1105                  * the read operation
1106                  */
1107                 SET_IRQ_HANDLER( NULL );
1108                 MultReadInProgress = 0;
1109                 local_irq_restore(flags);
1110                 DPRINT(("fd_readtrack_check(): done\n"));
1111                 FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1112                 udelay(25);
1113
1114                 /* No error until now -- the FDC would have interrupted
1115                  * otherwise!
1116                  */
1117                 fd_rwsec_done1(0);
1118         }
1119         else {
1120                 /* not yet finished, wait another tenth rotation */
1121                 local_irq_restore(flags);
1122                 DPRINT(("fd_readtrack_check(): not yet finished\n"));
1123                 mod_timer(&readtrack_timer, jiffies + HZ/5/10);
1124         }
1125 }
1126
1127
1128 static void fd_rwsec_done( int status )
1129 {
1130         DPRINT(("fd_rwsec_done()\n"));
1131
1132         if (read_track) {
1133                 del_timer(&readtrack_timer);
1134                 if (!MultReadInProgress)
1135                         return;
1136                 MultReadInProgress = 0;
1137         }
1138         fd_rwsec_done1(status);
1139 }
1140
1141 static void fd_rwsec_done1(int status)
1142 {
1143         unsigned int track;
1144
1145         stop_timeout();
1146         
1147         /* Correct the track if stretch != 0 */
1148         if (SUDT->stretch) {
1149                 track = FDC_READ( FDCREG_TRACK);
1150                 MFPDELAY();
1151                 FDC_WRITE( FDCREG_TRACK, track << SUDT->stretch);
1152         }
1153
1154         if (!UseTrackbuffer) {
1155                 dma_wd.dma_mode_status = 0x90;
1156                 MFPDELAY();
1157                 if (!(dma_wd.dma_mode_status & 0x01)) {
1158                         printk(KERN_ERR "fd%d: DMA error\n", SelectedDrive );
1159                         goto err_end;
1160                 }
1161         }
1162         MFPDELAY();
1163
1164         if (ReqCmd == WRITE && (status & FDCSTAT_WPROT)) {
1165                 printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
1166                 goto err_end;
1167         }       
1168         if ((status & FDCSTAT_RECNF) &&
1169             /* RECNF is no error after a multiple read when the FDC
1170                searched for a non-existent sector! */
1171             !(read_track && FDC_READ(FDCREG_SECTOR) > SUDT->spt)) {
1172                 if (Probing) {
1173                         if (SUDT > atari_disk_type) {
1174                             if (SUDT[-1].blocks > ReqBlock) {
1175                                 /* try another disk type */
1176                                 SUDT--;
1177                                 set_capacity(unit[SelectedDrive].disk,
1178                                                         SUDT->blocks);
1179                             } else
1180                                 Probing = 0;
1181                         }
1182                         else {
1183                                 if (SUD.flags & FTD_MSG)
1184                                         printk(KERN_INFO "fd%d: Auto-detected floppy type %s\n",
1185                                                SelectedDrive, SUDT->name );
1186                                 Probing=0;
1187                         }
1188                 } else {        
1189 /* record not found, but not probing. Maybe stretch wrong ? Restart probing */
1190                         if (SUD.autoprobe) {
1191                                 SUDT = atari_disk_type + StartDiskType[DriveType];
1192                                 set_capacity(unit[SelectedDrive].disk,
1193                                                         SUDT->blocks);
1194                                 Probing = 1;
1195                         }
1196                 }
1197                 if (Probing) {
1198                         if (ATARIHW_PRESENT(FDCSPEED)) {
1199                                 dma_wd.fdc_speed = SUDT->fdc_speed;
1200                                 MFPDELAY();
1201                         }
1202                         setup_req_params( SelectedDrive );
1203                         BufferDrive = -1;
1204                         do_fd_action( SelectedDrive );
1205                         return;
1206                 }
1207
1208                 printk(KERN_ERR "fd%d: sector %d not found (side %d, track %d)\n",
1209                        SelectedDrive, FDC_READ (FDCREG_SECTOR), ReqSide, ReqTrack );
1210                 goto err_end;
1211         }
1212         if (status & FDCSTAT_CRC) {
1213                 printk(KERN_ERR "fd%d: CRC error (side %d, track %d, sector %d)\n",
1214                        SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
1215                 goto err_end;
1216         }
1217         if (status & FDCSTAT_LOST) {
1218                 printk(KERN_ERR "fd%d: lost data (side %d, track %d, sector %d)\n",
1219                        SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
1220                 goto err_end;
1221         }
1222
1223         Probing = 0;
1224         
1225         if (ReqCmd == READ) {
1226                 if (!read_track) {
1227                         void *addr;
1228                         addr = ATARIHW_PRESENT( EXTD_DMA ) ? ReqData : DMABuffer;
1229                         dma_cache_maintenance( virt_to_phys(addr), 512, 0 );
1230                         if (!ATARIHW_PRESENT( EXTD_DMA ))
1231                                 copy_buffer (addr, ReqData);
1232                 } else {
1233                         dma_cache_maintenance( PhysTrackBuffer, MaxSectors[DriveType] * 512, 0 );
1234                         BufferDrive = SelectedDrive;
1235                         BufferSide  = ReqSide;
1236                         BufferTrack = ReqTrack;
1237                         copy_buffer (SECTOR_BUFFER (ReqSector), ReqData);
1238                 }
1239         }
1240   
1241         if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
1242                 /* read next sector */
1243                 setup_req_params( SelectedDrive );
1244                 do_fd_action( SelectedDrive );
1245         }
1246         else {
1247                 /* all sectors finished */
1248                 fd_end_request_cur(BLK_STS_OK);
1249                 finish_fdc();
1250         }
1251         return;
1252   
1253   err_end:
1254         BufferDrive = -1;
1255         fd_error();
1256 }
1257
1258
1259 static void fd_writetrack( void )
1260 {
1261         unsigned long paddr, flags;
1262         unsigned int track;
1263         
1264         DPRINT(("fd_writetrack() Tr=%d Si=%d\n", ReqTrack, ReqSide ));
1265
1266         paddr = PhysTrackBuffer;
1267         dma_cache_maintenance( paddr, BUFFER_SIZE, 1 );
1268
1269         fd_select_side( ReqSide );
1270   
1271         /* Cheat for track if stretch != 0 */
1272         if (SUDT->stretch) {
1273                 track = FDC_READ( FDCREG_TRACK);
1274                 MFPDELAY();
1275                 FDC_WRITE(FDCREG_TRACK,track >> SUDT->stretch);
1276         }
1277         udelay(40);
1278   
1279         /* Setup DMA */
1280         local_irq_save(flags);
1281         dma_wd.dma_lo = (unsigned char)paddr;
1282         MFPDELAY();
1283         paddr >>= 8;
1284         dma_wd.dma_md = (unsigned char)paddr;
1285         MFPDELAY();
1286         paddr >>= 8;
1287         if (ATARIHW_PRESENT( EXTD_DMA ))
1288                 st_dma_ext_dmahi = (unsigned short)paddr;
1289         else
1290                 dma_wd.dma_hi = (unsigned char)paddr;
1291         MFPDELAY();
1292         local_irq_restore(flags);
1293   
1294         /* Clear FIFO and switch DMA to correct mode */  
1295         dma_wd.dma_mode_status = 0x190;  
1296         MFPDELAY();
1297         dma_wd.dma_mode_status = 0x90;  
1298         MFPDELAY();
1299         dma_wd.dma_mode_status = 0x190;
1300         MFPDELAY();
1301   
1302         /* How many sectors for DMA */
1303         dma_wd.fdc_acces_seccount = BUFFER_SIZE/512;
1304         udelay(40);  
1305   
1306         /* Start operation */
1307         dma_wd.dma_mode_status = FDCSELREG_STP | 0x100;
1308         udelay(40);
1309         SET_IRQ_HANDLER( fd_writetrack_done );
1310         dma_wd.fdc_acces_seccount = FDCCMD_WRTRA | get_head_settle_flag(); 
1311
1312         MotorOn = 1;
1313         start_timeout();
1314         /* wait for interrupt */
1315 }
1316
1317
1318 static void fd_writetrack_done( int status )
1319 {
1320         DPRINT(("fd_writetrack_done()\n"));
1321
1322         stop_timeout();
1323
1324         if (status & FDCSTAT_WPROT) {
1325                 printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
1326                 goto err_end;
1327         }       
1328         if (status & FDCSTAT_LOST) {
1329                 printk(KERN_ERR "fd%d: lost data (side %d, track %d)\n",
1330                                 SelectedDrive, ReqSide, ReqTrack );
1331                 goto err_end;
1332         }
1333
1334         complete(&format_wait);
1335         return;
1336
1337   err_end:
1338         fd_error();
1339 }
1340
1341 static void fd_times_out(struct timer_list *unused)
1342 {
1343         atari_disable_irq( IRQ_MFP_FDC );
1344         if (!FloppyIRQHandler) goto end; /* int occurred after timer was fired, but
1345                                           * before we came here... */
1346
1347         SET_IRQ_HANDLER( NULL );
1348         /* If the timeout occurred while the readtrack_check timer was
1349          * active, we need to cancel it, else bad things will happen */
1350         if (UseTrackbuffer)
1351                 del_timer( &readtrack_timer );
1352         FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1353         udelay( 25 );
1354         
1355         printk(KERN_ERR "floppy timeout\n" );
1356         fd_error();
1357   end:
1358         atari_enable_irq( IRQ_MFP_FDC );
1359 }
1360
1361
1362 /* The (noop) seek operation here is needed to make the WP bit in the
1363  * FDC status register accessible for check_change. If the last disk
1364  * operation would have been a RDSEC, this bit would always read as 0
1365  * no matter what :-( To save time, the seek goes to the track we're
1366  * already on.
1367  */
1368
1369 static void finish_fdc( void )
1370 {
1371         if (!NeedSeek || !stdma_is_locked_by(floppy_irq)) {
1372                 finish_fdc_done( 0 );
1373         }
1374         else {
1375                 DPRINT(("finish_fdc: dummy seek started\n"));
1376                 FDC_WRITE (FDCREG_DATA, SUD.track);
1377                 SET_IRQ_HANDLER( finish_fdc_done );
1378                 FDC_WRITE (FDCREG_CMD, FDCCMD_SEEK);
1379                 MotorOn = 1;
1380                 start_timeout();
1381                 /* we must wait for the IRQ here, because the ST-DMA
1382                    is released immediately afterwards and the interrupt
1383                    may be delivered to the wrong driver. */
1384           }
1385 }
1386
1387
1388 static void finish_fdc_done( int dummy )
1389 {
1390         unsigned long flags;
1391
1392         DPRINT(("finish_fdc_done entered\n"));
1393         stop_timeout();
1394         NeedSeek = 0;
1395
1396         if (timer_pending(&fd_timer) && time_before(fd_timer.expires, jiffies + 5))
1397                 /* If the check for a disk change is done too early after this
1398                  * last seek command, the WP bit still reads wrong :-((
1399                  */
1400                 mod_timer(&fd_timer, jiffies + 5);
1401         else
1402                 start_check_change_timer();
1403         start_motor_off_timer();
1404
1405         local_irq_save(flags);
1406         if (stdma_is_locked_by(floppy_irq))
1407                 stdma_release();
1408         local_irq_restore(flags);
1409
1410         DPRINT(("finish_fdc() finished\n"));
1411 }
1412
1413 /* The detection of disk changes is a dark chapter in Atari history :-(
1414  * Because the "Drive ready" signal isn't present in the Atari
1415  * hardware, one has to rely on the "Write Protect". This works fine,
1416  * as long as no write protected disks are used. TOS solves this
1417  * problem by introducing tri-state logic ("maybe changed") and
1418  * looking at the serial number in block 0. This isn't possible for
1419  * Linux, since the floppy driver can't make assumptions about the
1420  * filesystem used on the disk and thus the contents of block 0. I've
1421  * chosen the method to always say "The disk was changed" if it is
1422  * unsure whether it was. This implies that every open or mount
1423  * invalidates the disk buffers if you work with write protected
1424  * disks. But at least this is better than working with incorrect data
1425  * due to unrecognised disk changes.
1426  */
1427
1428 static unsigned int floppy_check_events(struct gendisk *disk,
1429                                         unsigned int clearing)
1430 {
1431         struct atari_floppy_struct *p = disk->private_data;
1432         unsigned int drive = p - unit;
1433         if (test_bit (drive, &fake_change)) {
1434                 /* simulated change (e.g. after formatting) */
1435                 return DISK_EVENT_MEDIA_CHANGE;
1436         }
1437         if (test_bit (drive, &changed_floppies)) {
1438                 /* surely changed (the WP signal changed at least once) */
1439                 return DISK_EVENT_MEDIA_CHANGE;
1440         }
1441         if (UD.wpstat) {
1442                 /* WP is on -> could be changed: to be sure, buffers should be
1443                  * invalidated...
1444                  */
1445                 return DISK_EVENT_MEDIA_CHANGE;
1446         }
1447
1448         return 0;
1449 }
1450
1451 static int floppy_revalidate(struct gendisk *disk)
1452 {
1453         struct atari_floppy_struct *p = disk->private_data;
1454         unsigned int drive = p - unit;
1455
1456         if (test_bit(drive, &changed_floppies) ||
1457             test_bit(drive, &fake_change) ||
1458             p->disktype == 0) {
1459                 if (UD.flags & FTD_MSG)
1460                         printk(KERN_ERR "floppy: clear format %p!\n", UDT);
1461                 BufferDrive = -1;
1462                 clear_bit(drive, &fake_change);
1463                 clear_bit(drive, &changed_floppies);
1464                 /* MSch: clearing geometry makes sense only for autoprobe
1465                    formats, for 'permanent user-defined' parameter:
1466                    restore default_params[] here if flagged valid! */
1467                 if (default_params[drive].blocks == 0)
1468                         UDT = NULL;
1469                 else
1470                         UDT = &default_params[drive];
1471         }
1472         return 0;
1473 }
1474
1475
1476 /* This sets up the global variables describing the current request. */
1477
1478 static void setup_req_params( int drive )
1479 {
1480         int block = ReqBlock + ReqCnt;
1481
1482         ReqTrack = block / UDT->spt;
1483         ReqSector = block - ReqTrack * UDT->spt + 1;
1484         ReqSide = ReqTrack & 1;
1485         ReqTrack >>= 1;
1486         ReqData = ReqBuffer + 512 * ReqCnt;
1487
1488         if (UseTrackbuffer)
1489                 read_track = (ReqCmd == READ && fd_request->error_count == 0);
1490         else
1491                 read_track = 0;
1492
1493         DPRINT(("Request params: Si=%d Tr=%d Se=%d Data=%08lx\n",ReqSide,
1494                         ReqTrack, ReqSector, (unsigned long)ReqData ));
1495 }
1496
1497 static blk_status_t ataflop_queue_rq(struct blk_mq_hw_ctx *hctx,
1498                                      const struct blk_mq_queue_data *bd)
1499 {
1500         struct atari_floppy_struct *floppy = bd->rq->rq_disk->private_data;
1501         int drive = floppy - unit;
1502         int type = floppy->type;
1503
1504         DPRINT(("Queue request: drive %d type %d sectors %d of %d last %d\n",
1505                 drive, type, blk_rq_cur_sectors(bd->rq),
1506                 blk_rq_sectors(bd->rq), bd->last));
1507
1508         spin_lock_irq(&ataflop_lock);
1509         if (fd_request) {
1510                 spin_unlock_irq(&ataflop_lock);
1511                 return BLK_STS_DEV_RESOURCE;
1512         }
1513         if (!stdma_try_lock(floppy_irq, NULL))  {
1514                 spin_unlock_irq(&ataflop_lock);
1515                 return BLK_STS_RESOURCE;
1516         }
1517         fd_request = bd->rq;
1518         blk_mq_start_request(fd_request);
1519
1520         atari_disable_irq( IRQ_MFP_FDC );
1521
1522         IsFormatting = 0;
1523
1524         if (!UD.connected) {
1525                 /* drive not connected */
1526                 printk(KERN_ERR "Unknown Device: fd%d\n", drive );
1527                 fd_end_request_cur(BLK_STS_IOERR);
1528                 stdma_release();
1529                 goto out;
1530         }
1531                 
1532         if (type == 0) {
1533                 if (!UDT) {
1534                         Probing = 1;
1535                         UDT = atari_disk_type + StartDiskType[DriveType];
1536                         set_capacity(floppy->disk, UDT->blocks);
1537                         UD.autoprobe = 1;
1538                 }
1539         } 
1540         else {
1541                 /* user supplied disk type */
1542                 if (--type >= NUM_DISK_MINORS) {
1543                         printk(KERN_WARNING "fd%d: invalid disk format", drive );
1544                         fd_end_request_cur(BLK_STS_IOERR);
1545                         stdma_release();
1546                         goto out;
1547                 }
1548                 if (minor2disktype[type].drive_types > DriveType)  {
1549                         printk(KERN_WARNING "fd%d: unsupported disk format", drive );
1550                         fd_end_request_cur(BLK_STS_IOERR);
1551                         stdma_release();
1552                         goto out;
1553                 }
1554                 type = minor2disktype[type].index;
1555                 UDT = &atari_disk_type[type];
1556                 set_capacity(floppy->disk, UDT->blocks);
1557                 UD.autoprobe = 0;
1558         }
1559
1560         /* stop deselect timer */
1561         del_timer( &motor_off_timer );
1562                 
1563         ReqCnt = 0;
1564         ReqCmd = rq_data_dir(fd_request);
1565         ReqBlock = blk_rq_pos(fd_request);
1566         ReqBuffer = bio_data(fd_request->bio);
1567         setup_req_params( drive );
1568         do_fd_action( drive );
1569
1570         atari_enable_irq( IRQ_MFP_FDC );
1571
1572 out:
1573         spin_unlock_irq(&ataflop_lock);
1574         return BLK_STS_OK;
1575 }
1576
1577 static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode,
1578                     unsigned int cmd, unsigned long param)
1579 {
1580         struct gendisk *disk = bdev->bd_disk;
1581         struct atari_floppy_struct *floppy = disk->private_data;
1582         int drive = floppy - unit;
1583         int type = floppy->type;
1584         struct atari_format_descr fmt_desc;
1585         struct atari_disk_type *dtp;
1586         struct floppy_struct getprm;
1587         int settype;
1588         struct floppy_struct setprm;
1589         void __user *argp = (void __user *)param;
1590
1591         switch (cmd) {
1592         case FDGETPRM:
1593                 if (type) {
1594                         if (--type >= NUM_DISK_MINORS)
1595                                 return -ENODEV;
1596                         if (minor2disktype[type].drive_types > DriveType)
1597                                 return -ENODEV;
1598                         type = minor2disktype[type].index;
1599                         dtp = &atari_disk_type[type];
1600                         if (UD.flags & FTD_MSG)
1601                             printk (KERN_ERR "floppy%d: found dtp %p name %s!\n",
1602                                 drive, dtp, dtp->name);
1603                 }
1604                 else {
1605                         if (!UDT)
1606                                 return -ENXIO;
1607                         else
1608                                 dtp = UDT;
1609                 }
1610                 memset((void *)&getprm, 0, sizeof(getprm));
1611                 getprm.size = dtp->blocks;
1612                 getprm.sect = dtp->spt;
1613                 getprm.head = 2;
1614                 getprm.track = dtp->blocks/dtp->spt/2;
1615                 getprm.stretch = dtp->stretch;
1616                 if (copy_to_user(argp, &getprm, sizeof(getprm)))
1617                         return -EFAULT;
1618                 return 0;
1619         }
1620         switch (cmd) {
1621         case FDSETPRM:
1622         case FDDEFPRM:
1623                 /* 
1624                  * MSch 7/96: simple 'set geometry' case: just set the
1625                  * 'default' device params (minor == 0).
1626                  * Currently, the drive geometry is cleared after each
1627                  * disk change and subsequent revalidate()! simple
1628                  * implementation of FDDEFPRM: save geometry from a
1629                  * FDDEFPRM call and restore it in floppy_revalidate() !
1630                  */
1631
1632                 /* get the parameters from user space */
1633                 if (floppy->ref != 1 && floppy->ref != -1)
1634                         return -EBUSY;
1635                 if (copy_from_user(&setprm, argp, sizeof(setprm)))
1636                         return -EFAULT;
1637                 /* 
1638                  * first of all: check for floppy change and revalidate, 
1639                  * or the next access will revalidate - and clear UDT :-(
1640                  */
1641
1642                 if (floppy_check_events(disk, 0))
1643                         floppy_revalidate(disk);
1644
1645                 if (UD.flags & FTD_MSG)
1646                     printk (KERN_INFO "floppy%d: setting size %d spt %d str %d!\n",
1647                         drive, setprm.size, setprm.sect, setprm.stretch);
1648
1649                 /* what if type > 0 here? Overwrite specified entry ? */
1650                 if (type) {
1651                         /* refuse to re-set a predefined type for now */
1652                         finish_fdc();
1653                         return -EINVAL;
1654                 }
1655
1656                 /* 
1657                  * type == 0: first look for a matching entry in the type list,
1658                  * and set the UD.disktype field to use the perdefined entry.
1659                  * TODO: add user-defined format to head of autoprobe list ? 
1660                  * Useful to include the user-type for future autodetection!
1661                  */
1662
1663                 for (settype = 0; settype < NUM_DISK_MINORS; settype++) {
1664                         int setidx = 0;
1665                         if (minor2disktype[settype].drive_types > DriveType) {
1666                                 /* skip this one, invalid for drive ... */
1667                                 continue;
1668                         }
1669                         setidx = minor2disktype[settype].index;
1670                         dtp = &atari_disk_type[setidx];
1671
1672                         /* found matching entry ?? */
1673                         if (   dtp->blocks  == setprm.size 
1674                             && dtp->spt     == setprm.sect
1675                             && dtp->stretch == setprm.stretch ) {
1676                                 if (UD.flags & FTD_MSG)
1677                                     printk (KERN_INFO "floppy%d: setting %s %p!\n",
1678                                         drive, dtp->name, dtp);
1679                                 UDT = dtp;
1680                                 set_capacity(floppy->disk, UDT->blocks);
1681
1682                                 if (cmd == FDDEFPRM) {
1683                                   /* save settings as permanent default type */
1684                                   default_params[drive].name    = dtp->name;
1685                                   default_params[drive].spt     = dtp->spt;
1686                                   default_params[drive].blocks  = dtp->blocks;
1687                                   default_params[drive].fdc_speed = dtp->fdc_speed;
1688                                   default_params[drive].stretch = dtp->stretch;
1689                                 }
1690                                 
1691                                 return 0;
1692                         }
1693
1694                 }
1695
1696                 /* no matching disk type found above - setting user_params */
1697
1698                 if (cmd == FDDEFPRM) {
1699                         /* set permanent type */
1700                         dtp = &default_params[drive];
1701                 } else
1702                         /* set user type (reset by disk change!) */
1703                         dtp = &user_params[drive];
1704
1705                 dtp->name   = "user format";
1706                 dtp->blocks = setprm.size;
1707                 dtp->spt    = setprm.sect;
1708                 if (setprm.sect > 14) 
1709                         dtp->fdc_speed = 3;
1710                 else
1711                         dtp->fdc_speed = 0;
1712                 dtp->stretch = setprm.stretch;
1713
1714                 if (UD.flags & FTD_MSG)
1715                         printk (KERN_INFO "floppy%d: blk %d spt %d str %d!\n",
1716                                 drive, dtp->blocks, dtp->spt, dtp->stretch);
1717
1718                 /* sanity check */
1719                 if (setprm.track != dtp->blocks/dtp->spt/2 ||
1720                     setprm.head != 2) {
1721                         finish_fdc();
1722                         return -EINVAL;
1723                 }
1724
1725                 UDT = dtp;
1726                 set_capacity(floppy->disk, UDT->blocks);
1727
1728                 return 0;
1729         case FDMSGON:
1730                 UD.flags |= FTD_MSG;
1731                 return 0;
1732         case FDMSGOFF:
1733                 UD.flags &= ~FTD_MSG;
1734                 return 0;
1735         case FDSETEMSGTRESH:
1736                 return -EINVAL;
1737         case FDFMTBEG:
1738                 return 0;
1739         case FDFMTTRK:
1740                 if (floppy->ref != 1 && floppy->ref != -1)
1741                         return -EBUSY;
1742                 if (copy_from_user(&fmt_desc, argp, sizeof(fmt_desc)))
1743                         return -EFAULT;
1744                 return do_format(drive, type, &fmt_desc);
1745         case FDCLRPRM:
1746                 UDT = NULL;
1747                 /* MSch: invalidate default_params */
1748                 default_params[drive].blocks  = 0;
1749                 set_capacity(floppy->disk, MAX_DISK_SIZE * 2);
1750                 fallthrough;
1751         case FDFMTEND:
1752         case FDFLUSH:
1753                 /* invalidate the buffer track to force a reread */
1754                 BufferDrive = -1;
1755                 set_bit(drive, &fake_change);
1756                 if (bdev_check_media_change(bdev))
1757                         floppy_revalidate(bdev->bd_disk);
1758                 return 0;
1759         default:
1760                 return -EINVAL;
1761         }
1762 }
1763
1764 static int fd_ioctl(struct block_device *bdev, fmode_t mode,
1765                              unsigned int cmd, unsigned long arg)
1766 {
1767         int ret;
1768
1769         mutex_lock(&ataflop_mutex);
1770         ret = fd_locked_ioctl(bdev, mode, cmd, arg);
1771         mutex_unlock(&ataflop_mutex);
1772
1773         return ret;
1774 }
1775
1776 /* Initialize the 'unit' variable for drive 'drive' */
1777
1778 static void __init fd_probe( int drive )
1779 {
1780         UD.connected = 0;
1781         UDT  = NULL;
1782
1783         if (!fd_test_drive_present( drive ))
1784                 return;
1785
1786         UD.connected = 1;
1787         UD.track     = 0;
1788         switch( UserSteprate[drive] ) {
1789         case 2:
1790                 UD.steprate = FDCSTEP_2;
1791                 break;
1792         case 3:
1793                 UD.steprate = FDCSTEP_3;
1794                 break;
1795         case 6:
1796                 UD.steprate = FDCSTEP_6;
1797                 break;
1798         case 12:
1799                 UD.steprate = FDCSTEP_12;
1800                 break;
1801         default: /* should be -1 for "not set by user" */
1802                 if (ATARIHW_PRESENT( FDCSPEED ) || MACH_IS_MEDUSA)
1803                         UD.steprate = FDCSTEP_3;
1804                 else
1805                         UD.steprate = FDCSTEP_6;
1806                 break;
1807         }
1808         MotorOn = 1;    /* from probe restore operation! */
1809 }
1810
1811
1812 /* This function tests the physical presence of a floppy drive (not
1813  * whether a disk is inserted). This is done by issuing a restore
1814  * command, waiting max. 2 seconds (that should be enough to move the
1815  * head across the whole disk) and looking at the state of the "TR00"
1816  * signal. This should now be raised if there is a drive connected
1817  * (and there is no hardware failure :-) Otherwise, the drive is
1818  * declared absent.
1819  */
1820
1821 static int __init fd_test_drive_present( int drive )
1822 {
1823         unsigned long timeout;
1824         unsigned char status;
1825         int ok;
1826         
1827         if (drive >= (MACH_IS_FALCON ? 1 : 2)) return( 0 );
1828         fd_select_drive( drive );
1829
1830         /* disable interrupt temporarily */
1831         atari_turnoff_irq( IRQ_MFP_FDC );
1832         FDC_WRITE (FDCREG_TRACK, 0xff00);
1833         FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | FDCCMDADD_H | FDCSTEP_6 );
1834
1835         timeout = jiffies + 2*HZ+HZ/2;
1836         while (time_before(jiffies, timeout))
1837                 if (!(st_mfp.par_dt_reg & 0x20))
1838                         break;
1839
1840         status = FDC_READ( FDCREG_STATUS );
1841         ok = (status & FDCSTAT_TR00) != 0;
1842
1843         /* force interrupt to abort restore operation (FDC would try
1844          * about 50 seconds!) */
1845         FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1846         udelay(500);
1847         status = FDC_READ( FDCREG_STATUS );
1848         udelay(20);
1849
1850         if (ok) {
1851                 /* dummy seek command to make WP bit accessible */
1852                 FDC_WRITE( FDCREG_DATA, 0 );
1853                 FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK );
1854                 while( st_mfp.par_dt_reg & 0x20 )
1855                         ;
1856                 status = FDC_READ( FDCREG_STATUS );
1857         }
1858
1859         atari_turnon_irq( IRQ_MFP_FDC );
1860         return( ok );
1861 }
1862
1863
1864 /* Look how many and which kind of drives are connected. If there are
1865  * floppies, additionally start the disk-change and motor-off timers.
1866  */
1867
1868 static void __init config_types( void )
1869 {
1870         int drive, cnt = 0;
1871
1872         /* for probing drives, set the FDC speed to 8 MHz */
1873         if (ATARIHW_PRESENT(FDCSPEED))
1874                 dma_wd.fdc_speed = 0;
1875
1876         printk(KERN_INFO "Probing floppy drive(s):\n");
1877         for( drive = 0; drive < FD_MAX_UNITS; drive++ ) {
1878                 fd_probe( drive );
1879                 if (UD.connected) {
1880                         printk(KERN_INFO "fd%d\n", drive);
1881                         ++cnt;
1882                 }
1883         }
1884
1885         if (FDC_READ( FDCREG_STATUS ) & FDCSTAT_BUSY) {
1886                 /* If FDC is still busy from probing, give it another FORCI
1887                  * command to abort the operation. If this isn't done, the FDC
1888                  * will interrupt later and its IRQ line stays low, because
1889                  * the status register isn't read. And this will block any
1890                  * interrupts on this IRQ line :-(
1891                  */
1892                 FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1893                 udelay(500);
1894                 FDC_READ( FDCREG_STATUS );
1895                 udelay(20);
1896         }
1897         
1898         if (cnt > 0) {
1899                 start_motor_off_timer();
1900                 if (cnt == 1) fd_select_drive( 0 );
1901                 start_check_change_timer();
1902         }
1903 }
1904
1905 /*
1906  * floppy_open check for aliasing (/dev/fd0 can be the same as
1907  * /dev/PS0 etc), and disallows simultaneous access to the same
1908  * drive with different device numbers.
1909  */
1910
1911 static int floppy_open(struct block_device *bdev, fmode_t mode)
1912 {
1913         struct atari_floppy_struct *p = bdev->bd_disk->private_data;
1914         int type  = MINOR(bdev->bd_dev) >> 2;
1915
1916         DPRINT(("fd_open: type=%d\n",type));
1917         if (p->ref && p->type != type)
1918                 return -EBUSY;
1919
1920         if (p->ref == -1 || (p->ref && mode & FMODE_EXCL))
1921                 return -EBUSY;
1922
1923         if (mode & FMODE_EXCL)
1924                 p->ref = -1;
1925         else
1926                 p->ref++;
1927
1928         p->type = type;
1929
1930         if (mode & FMODE_NDELAY)
1931                 return 0;
1932
1933         if (mode & (FMODE_READ|FMODE_WRITE)) {
1934                 if (bdev_check_media_change(bdev))
1935                         floppy_revalidate(bdev->bd_disk);
1936                 if (mode & FMODE_WRITE) {
1937                         if (p->wpstat) {
1938                                 if (p->ref < 0)
1939                                         p->ref = 0;
1940                                 else
1941                                         p->ref--;
1942                                 return -EROFS;
1943                         }
1944                 }
1945         }
1946         return 0;
1947 }
1948
1949 static int floppy_unlocked_open(struct block_device *bdev, fmode_t mode)
1950 {
1951         int ret;
1952
1953         mutex_lock(&ataflop_mutex);
1954         ret = floppy_open(bdev, mode);
1955         mutex_unlock(&ataflop_mutex);
1956
1957         return ret;
1958 }
1959
1960 static void floppy_release(struct gendisk *disk, fmode_t mode)
1961 {
1962         struct atari_floppy_struct *p = disk->private_data;
1963         mutex_lock(&ataflop_mutex);
1964         if (p->ref < 0)
1965                 p->ref = 0;
1966         else if (!p->ref--) {
1967                 printk(KERN_ERR "floppy_release with fd_ref == 0");
1968                 p->ref = 0;
1969         }
1970         mutex_unlock(&ataflop_mutex);
1971 }
1972
1973 static const struct block_device_operations floppy_fops = {
1974         .owner          = THIS_MODULE,
1975         .open           = floppy_unlocked_open,
1976         .release        = floppy_release,
1977         .ioctl          = fd_ioctl,
1978         .check_events   = floppy_check_events,
1979 };
1980
1981 static const struct blk_mq_ops ataflop_mq_ops = {
1982         .queue_rq = ataflop_queue_rq,
1983 };
1984
1985 static struct kobject *floppy_find(dev_t dev, int *part, void *data)
1986 {
1987         int drive = *part & 3;
1988         int type  = *part >> 2;
1989         if (drive >= FD_MAX_UNITS || type > NUM_DISK_MINORS)
1990                 return NULL;
1991         *part = 0;
1992         return get_disk_and_module(unit[drive].disk);
1993 }
1994
1995 static int __init atari_floppy_init (void)
1996 {
1997         int i;
1998         int ret;
1999
2000         if (!MACH_IS_ATARI)
2001                 /* Amiga, Mac, ... don't have Atari-compatible floppy :-) */
2002                 return -ENODEV;
2003
2004         if (register_blkdev(FLOPPY_MAJOR,"fd"))
2005                 return -EBUSY;
2006
2007         for (i = 0; i < FD_MAX_UNITS; i++) {
2008                 unit[i].disk = alloc_disk(1);
2009                 if (!unit[i].disk) {
2010                         ret = -ENOMEM;
2011                         goto err;
2012                 }
2013
2014                 unit[i].disk->queue = blk_mq_init_sq_queue(&unit[i].tag_set,
2015                                                            &ataflop_mq_ops, 2,
2016                                                            BLK_MQ_F_SHOULD_MERGE);
2017                 if (IS_ERR(unit[i].disk->queue)) {
2018                         put_disk(unit[i].disk);
2019                         ret = PTR_ERR(unit[i].disk->queue);
2020                         unit[i].disk->queue = NULL;
2021                         goto err;
2022                 }
2023         }
2024
2025         if (UseTrackbuffer < 0)
2026                 /* not set by user -> use default: for now, we turn
2027                    track buffering off for all Medusas, though it
2028                    could be used with ones that have a counter
2029                    card. But the test is too hard :-( */
2030                 UseTrackbuffer = !MACH_IS_MEDUSA;
2031
2032         /* initialize variables */
2033         SelectedDrive = -1;
2034         BufferDrive = -1;
2035
2036         DMABuffer = atari_stram_alloc(BUFFER_SIZE+512, "ataflop");
2037         if (!DMABuffer) {
2038                 printk(KERN_ERR "atari_floppy_init: cannot get dma buffer\n");
2039                 ret = -ENOMEM;
2040                 goto err;
2041         }
2042         TrackBuffer = DMABuffer + 512;
2043         PhysDMABuffer = atari_stram_to_phys(DMABuffer);
2044         PhysTrackBuffer = virt_to_phys(TrackBuffer);
2045         BufferDrive = BufferSide = BufferTrack = -1;
2046
2047         for (i = 0; i < FD_MAX_UNITS; i++) {
2048                 unit[i].track = -1;
2049                 unit[i].flags = 0;
2050                 unit[i].disk->major = FLOPPY_MAJOR;
2051                 unit[i].disk->first_minor = i;
2052                 sprintf(unit[i].disk->disk_name, "fd%d", i);
2053                 unit[i].disk->fops = &floppy_fops;
2054                 unit[i].disk->events = DISK_EVENT_MEDIA_CHANGE;
2055                 unit[i].disk->private_data = &unit[i];
2056                 set_capacity(unit[i].disk, MAX_DISK_SIZE * 2);
2057                 add_disk(unit[i].disk);
2058         }
2059
2060         blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
2061                                 floppy_find, NULL, NULL);
2062
2063         printk(KERN_INFO "Atari floppy driver: max. %cD, %strack buffering\n",
2064                DriveType == 0 ? 'D' : DriveType == 1 ? 'H' : 'E',
2065                UseTrackbuffer ? "" : "no ");
2066         config_types();
2067
2068         return 0;
2069
2070 err:
2071         while (--i >= 0) {
2072                 struct gendisk *disk = unit[i].disk;
2073
2074                 blk_cleanup_queue(disk->queue);
2075                 blk_mq_free_tag_set(&unit[i].tag_set);
2076                 put_disk(unit[i].disk);
2077         }
2078
2079         unregister_blkdev(FLOPPY_MAJOR, "fd");
2080         return ret;
2081 }
2082
2083 #ifndef MODULE
2084 static int __init atari_floppy_setup(char *str)
2085 {
2086         int ints[3 + FD_MAX_UNITS];
2087         int i;
2088
2089         if (!MACH_IS_ATARI)
2090                 return 0;
2091
2092         str = get_options(str, 3 + FD_MAX_UNITS, ints);
2093         
2094         if (ints[0] < 1) {
2095                 printk(KERN_ERR "ataflop_setup: no arguments!\n" );
2096                 return 0;
2097         }
2098         else if (ints[0] > 2+FD_MAX_UNITS) {
2099                 printk(KERN_ERR "ataflop_setup: too many arguments\n" );
2100         }
2101
2102         if (ints[1] < 0 || ints[1] > 2)
2103                 printk(KERN_ERR "ataflop_setup: bad drive type\n" );
2104         else
2105                 DriveType = ints[1];
2106
2107         if (ints[0] >= 2)
2108                 UseTrackbuffer = (ints[2] > 0);
2109
2110         for( i = 3; i <= ints[0] && i-3 < FD_MAX_UNITS; ++i ) {
2111                 if (ints[i] != 2 && ints[i] != 3 && ints[i] != 6 && ints[i] != 12)
2112                         printk(KERN_ERR "ataflop_setup: bad steprate\n" );
2113                 else
2114                         UserSteprate[i-3] = ints[i];
2115         }
2116         return 1;
2117 }
2118
2119 __setup("floppy=", atari_floppy_setup);
2120 #endif
2121
2122 static void __exit atari_floppy_exit(void)
2123 {
2124         int i;
2125         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
2126         for (i = 0; i < FD_MAX_UNITS; i++) {
2127                 del_gendisk(unit[i].disk);
2128                 blk_cleanup_queue(unit[i].disk->queue);
2129                 blk_mq_free_tag_set(&unit[i].tag_set);
2130                 put_disk(unit[i].disk);
2131         }
2132         unregister_blkdev(FLOPPY_MAJOR, "fd");
2133
2134         del_timer_sync(&fd_timer);
2135         atari_stram_free( DMABuffer );
2136 }
2137
2138 module_init(atari_floppy_init)
2139 module_exit(atari_floppy_exit)
2140
2141 MODULE_LICENSE("GPL");