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