Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  *  drivers/block/ataflop.c
0004  *
0005  *  Copyright (C) 1993  Greg Harp
0006  *  Atari Support by Bjoern Brauel, Roman Hodek
0007  *
0008  *  Big cleanup Sep 11..14 1994 Roman Hodek:
0009  *   - Driver now works interrupt driven
0010  *   - Support for two drives; should work, but I cannot test that :-(
0011  *   - Reading is done in whole tracks and buffered to speed up things
0012  *   - Disk change detection and drive deselecting after motor-off
0013  *     similar to TOS
0014  *   - Autodetection of disk format (DD/HD); untested yet, because I
0015  *     don't have an HD drive :-(
0016  *
0017  *  Fixes Nov 13 1994 Martin Schaller:
0018  *   - Autodetection works now
0019  *   - Support for 5 1/4'' disks
0020  *   - Removed drive type (unknown on atari)
0021  *   - Do seeks with 8 Mhz
0022  *
0023  *  Changes by Andreas Schwab:
0024  *   - After errors in multiple read mode try again reading single sectors
0025  *  (Feb 1995):
0026  *   - Clean up error handling
0027  *   - Set blk_size for proper size checking
0028  *   - Initialize track register when testing presence of floppy
0029  *   - Implement some ioctl's
0030  *
0031  *  Changes by Torsten Lang:
0032  *   - When probing the floppies we should add the FDCCMDADD_H flag since
0033  *     the FDC will otherwise wait forever when no disk is inserted...
0034  *
0035  * ++ Freddi Aschwanden (fa) 20.9.95 fixes for medusa:
0036  *  - MFPDELAY() after each FDC access -> atari 
0037  *  - more/other disk formats
0038  *  - DMA to the block buffer directly if we have a 32bit DMA
0039  *  - for medusa, the step rate is always 3ms
0040  *  - on medusa, use only cache_push()
0041  * Roman:
0042  *  - Make disk format numbering independent from minors
0043  *  - Let user set max. supported drive type (speeds up format
0044  *    detection, saves buffer space)
0045  *
0046  * Roman 10/15/95:
0047  *  - implement some more ioctls
0048  *  - disk formatting
0049  *  
0050  * Andreas 95/12/12:
0051  *  - increase gap size at start of track for HD/ED disks
0052  *
0053  * Michael (MSch) 11/07/96:
0054  *  - implemented FDSETPRM and FDDEFPRM ioctl
0055  *
0056  * Andreas (97/03/19):
0057  *  - implemented missing BLK* ioctls
0058  *
0059  *  Things left to do:
0060  *   - Formatting
0061  *   - Maybe a better strategy for disk change detection (does anyone
0062  *     know one?)
0063  */
0064 
0065 #include <linux/module.h>
0066 
0067 #include <linux/fd.h>
0068 #include <linux/delay.h>
0069 #include <linux/init.h>
0070 #include <linux/blk-mq.h>
0071 #include <linux/major.h>
0072 #include <linux/mutex.h>
0073 #include <linux/completion.h>
0074 #include <linux/wait.h>
0075 
0076 #include <asm/atariints.h>
0077 #include <asm/atari_stdma.h>
0078 #include <asm/atari_stram.h>
0079 
0080 #define FD_MAX_UNITS 2
0081 
0082 #undef DEBUG
0083 
0084 static DEFINE_MUTEX(ataflop_mutex);
0085 static struct request *fd_request;
0086 
0087 /*
0088  * WD1772 stuff
0089  */
0090 
0091 /* register codes */
0092 
0093 #define FDCSELREG_STP   (0x80)   /* command/status register */
0094 #define FDCSELREG_TRA   (0x82)   /* track register */
0095 #define FDCSELREG_SEC   (0x84)   /* sector register */
0096 #define FDCSELREG_DTA   (0x86)   /* data register */
0097 
0098 /* register names for FDC_READ/WRITE macros */
0099 
0100 #define FDCREG_CMD      0
0101 #define FDCREG_STATUS   0
0102 #define FDCREG_TRACK    2
0103 #define FDCREG_SECTOR   4
0104 #define FDCREG_DATA     6
0105 
0106 /* command opcodes */
0107 
0108 #define FDCCMD_RESTORE  (0x00)   /*  -                   */
0109 #define FDCCMD_SEEK     (0x10)   /*   |                  */
0110 #define FDCCMD_STEP     (0x20)   /*   |  TYP 1 Commands  */
0111 #define FDCCMD_STIN     (0x40)   /*   |                  */
0112 #define FDCCMD_STOT     (0x60)   /*  -                   */
0113 #define FDCCMD_RDSEC    (0x80)   /*  -   TYP 2 Commands  */
0114 #define FDCCMD_WRSEC    (0xa0)   /*  -          "        */
0115 #define FDCCMD_RDADR    (0xc0)   /*  -                   */
0116 #define FDCCMD_RDTRA    (0xe0)   /*   |  TYP 3 Commands  */
0117 #define FDCCMD_WRTRA    (0xf0)   /*  -                   */
0118 #define FDCCMD_FORCI    (0xd0)   /*  -   TYP 4 Command   */
0119 
0120 /* command modifier bits */
0121 
0122 #define FDCCMDADD_SR6   (0x00)   /* step rate settings */
0123 #define FDCCMDADD_SR12  (0x01)
0124 #define FDCCMDADD_SR2   (0x02)
0125 #define FDCCMDADD_SR3   (0x03)
0126 #define FDCCMDADD_V     (0x04)   /* verify */
0127 #define FDCCMDADD_H     (0x08)   /* wait for spin-up */
0128 #define FDCCMDADD_U     (0x10)   /* update track register */
0129 #define FDCCMDADD_M     (0x10)   /* multiple sector access */
0130 #define FDCCMDADD_E     (0x04)   /* head settling flag */
0131 #define FDCCMDADD_P     (0x02)   /* precompensation off */
0132 #define FDCCMDADD_A0    (0x01)   /* DAM flag */
0133 
0134 /* status register bits */
0135 
0136 #define FDCSTAT_MOTORON (0x80)   /* motor on */
0137 #define FDCSTAT_WPROT   (0x40)   /* write protected (FDCCMD_WR*) */
0138 #define FDCSTAT_SPINUP  (0x20)   /* motor speed stable (Type I) */
0139 #define FDCSTAT_DELDAM  (0x20)   /* sector has deleted DAM (Type II+III) */
0140 #define FDCSTAT_RECNF   (0x10)   /* record not found */
0141 #define FDCSTAT_CRC     (0x08)   /* CRC error */
0142 #define FDCSTAT_TR00    (0x04)   /* Track 00 flag (Type I) */
0143 #define FDCSTAT_LOST    (0x04)   /* Lost Data (Type II+III) */
0144 #define FDCSTAT_IDX     (0x02)   /* Index status (Type I) */
0145 #define FDCSTAT_DRQ     (0x02)   /* DRQ status (Type II+III) */
0146 #define FDCSTAT_BUSY    (0x01)   /* FDC is busy */
0147 
0148 
0149 /* PSG Port A Bit Nr 0 .. Side Sel .. 0 -> Side 1  1 -> Side 2 */
0150 #define DSKSIDE     (0x01)
0151 
0152 #define DSKDRVNONE  (0x06)
0153 #define DSKDRV0     (0x02)
0154 #define DSKDRV1     (0x04)
0155 
0156 /* step rates */
0157 #define FDCSTEP_6   0x00
0158 #define FDCSTEP_12  0x01
0159 #define FDCSTEP_2   0x02
0160 #define FDCSTEP_3   0x03
0161 
0162 struct atari_format_descr {
0163     int track;      /* to be formatted */
0164     int head;       /*   ""     ""     */
0165     int sect_offset;    /* offset of first sector */
0166 };
0167 
0168 /* Disk types: DD, HD, ED */
0169 static struct atari_disk_type {
0170     const char  *name;
0171     unsigned    spt;        /* sectors per track */
0172     unsigned    blocks;     /* total number of blocks */
0173     unsigned    fdc_speed;  /* fdc_speed setting */
0174     unsigned    stretch;    /* track doubling ? */
0175 } atari_disk_type[] = {
0176     { "d360",  9, 720, 0, 0},   /*  0: 360kB diskette */
0177     { "D360",  9, 720, 0, 1},   /*  1: 360kb in 720k or 1.2MB drive */
0178     { "D720",  9,1440, 0, 0},   /*  2: 720kb in 720k or 1.2MB drive */
0179     { "D820", 10,1640, 0, 0},   /*  3: DD disk with 82 tracks/10 sectors */
0180 /* formats above are probed for type DD */
0181 #define MAX_TYPE_DD 3
0182     { "h1200",15,2400, 3, 0},   /*  4: 1.2MB diskette */
0183     { "H1440",18,2880, 3, 0},   /*  5: 1.4 MB diskette (HD) */
0184     { "H1640",20,3280, 3, 0},   /*  6: 1.64MB diskette (fat HD) 82 tr 20 sec */
0185 /* formats above are probed for types DD and HD */
0186 #define MAX_TYPE_HD 6
0187     { "E2880",36,5760, 3, 0},   /*  7: 2.8 MB diskette (ED) */
0188     { "E3280",40,6560, 3, 0},   /*  8: 3.2 MB diskette (fat ED) 82 tr 40 sec */
0189 /* formats above are probed for types DD, HD and ED */
0190 #define MAX_TYPE_ED 8
0191 /* types below are never autoprobed */
0192     { "H1680",21,3360, 3, 0},   /*  9: 1.68MB diskette (fat HD) 80 tr 21 sec */
0193     { "h410",10,820, 0, 1},     /* 10: 410k diskette 41 tr 10 sec, stretch */
0194     { "h1476",18,2952, 3, 0},   /* 11: 1.48MB diskette 82 tr 18 sec */
0195     { "H1722",21,3444, 3, 0},   /* 12: 1.72MB diskette 82 tr 21 sec */
0196     { "h420",10,840, 0, 1},     /* 13: 420k diskette 42 tr 10 sec, stretch */
0197     { "H830",10,1660, 0, 0},    /* 14: 820k diskette 83 tr 10 sec */
0198     { "h1494",18,2952, 3, 0},   /* 15: 1.49MB diskette 83 tr 18 sec */
0199     { "H1743",21,3486, 3, 0},   /* 16: 1.74MB diskette 83 tr 21 sec */
0200     { "h880",11,1760, 0, 0},    /* 17: 880k diskette 80 tr 11 sec */
0201     { "D1040",13,2080, 0, 0},   /* 18: 1.04MB diskette 80 tr 13 sec */
0202     { "D1120",14,2240, 0, 0},   /* 19: 1.12MB diskette 80 tr 14 sec */
0203     { "h1600",20,3200, 3, 0},   /* 20: 1.60MB diskette 80 tr 20 sec */
0204     { "H1760",22,3520, 3, 0},   /* 21: 1.76MB diskette 80 tr 22 sec */
0205     { "H1920",24,3840, 3, 0},   /* 22: 1.92MB diskette 80 tr 24 sec */
0206     { "E3200",40,6400, 3, 0},   /* 23: 3.2MB diskette 80 tr 40 sec */
0207     { "E3520",44,7040, 3, 0},   /* 24: 3.52MB diskette 80 tr 44 sec */
0208     { "E3840",48,7680, 3, 0},   /* 25: 3.84MB diskette 80 tr 48 sec */
0209     { "H1840",23,3680, 3, 0},   /* 26: 1.84MB diskette 80 tr 23 sec */
0210     { "D800",10,1600, 0, 0},    /* 27: 800k diskette 80 tr 10 sec */
0211 };
0212 
0213 static int StartDiskType[] = {
0214     MAX_TYPE_DD,
0215     MAX_TYPE_HD,
0216     MAX_TYPE_ED
0217 };
0218 
0219 #define TYPE_DD     0
0220 #define TYPE_HD     1
0221 #define TYPE_ED     2
0222 
0223 static int DriveType = TYPE_HD;
0224 
0225 static DEFINE_SPINLOCK(ataflop_lock);
0226 
0227 /* Array for translating minors into disk formats */
0228 static struct {
0229     int      index;
0230     unsigned drive_types;
0231 } minor2disktype[] = {
0232     {  0, TYPE_DD },    /*  1: d360 */
0233     {  4, TYPE_HD },    /*  2: h1200 */
0234     {  1, TYPE_DD },    /*  3: D360 */
0235     {  2, TYPE_DD },    /*  4: D720 */
0236     {  1, TYPE_DD },    /*  5: h360 = D360 */
0237     {  2, TYPE_DD },    /*  6: h720 = D720 */
0238     {  5, TYPE_HD },    /*  7: H1440 */
0239     {  7, TYPE_ED },    /*  8: E2880 */
0240 /* some PC formats :-) */
0241     {  8, TYPE_ED },    /*  9: E3280    <- was "CompaQ" == E2880 for PC */
0242     {  5, TYPE_HD },    /* 10: h1440 = H1440 */
0243     {  9, TYPE_HD },    /* 11: H1680 */
0244     { 10, TYPE_DD },    /* 12: h410  */
0245     {  3, TYPE_DD },    /* 13: H820     <- == D820, 82x10 */
0246     { 11, TYPE_HD },    /* 14: h1476 */
0247     { 12, TYPE_HD },    /* 15: H1722 */
0248     { 13, TYPE_DD },    /* 16: h420  */
0249     { 14, TYPE_DD },    /* 17: H830  */
0250     { 15, TYPE_HD },    /* 18: h1494 */
0251     { 16, TYPE_HD },    /* 19: H1743 */
0252     { 17, TYPE_DD },    /* 20: h880  */
0253     { 18, TYPE_DD },    /* 21: D1040 */
0254     { 19, TYPE_DD },    /* 22: D1120 */
0255     { 20, TYPE_HD },    /* 23: h1600 */
0256     { 21, TYPE_HD },    /* 24: H1760 */
0257     { 22, TYPE_HD },    /* 25: H1920 */
0258     { 23, TYPE_ED },    /* 26: E3200 */
0259     { 24, TYPE_ED },    /* 27: E3520 */
0260     { 25, TYPE_ED },    /* 28: E3840 */
0261     { 26, TYPE_HD },    /* 29: H1840 */
0262     { 27, TYPE_DD },    /* 30: D800  */
0263     {  6, TYPE_HD },    /* 31: H1640    <- was H1600 == h1600 for PC */
0264 };
0265 
0266 #define NUM_DISK_MINORS ARRAY_SIZE(minor2disktype)
0267 
0268 /*
0269  * Maximum disk size (in kilobytes). This default is used whenever the
0270  * current disk size is unknown.
0271  */
0272 #define MAX_DISK_SIZE 3280
0273 
0274 /*
0275  * MSch: User-provided type information. 'drive' points to
0276  * the respective entry of this array. Set by FDSETPRM ioctls.
0277  */
0278 static struct atari_disk_type user_params[FD_MAX_UNITS];
0279 
0280 /*
0281  * User-provided permanent type information. 'drive' points to
0282  * the respective entry of this array.  Set by FDDEFPRM ioctls, 
0283  * restored upon disk change by floppy_revalidate() if valid (as seen by
0284  * default_params[].blocks > 0 - a bit in unit[].flags might be used for this?)
0285  */
0286 static struct atari_disk_type default_params[FD_MAX_UNITS];
0287 
0288 /* current info on each unit */
0289 static struct atari_floppy_struct {
0290     int connected;              /* !=0 : drive is connected */
0291     int autoprobe;              /* !=0 : do autoprobe       */
0292 
0293     struct atari_disk_type  *disktype;  /* current type of disk */
0294 
0295     int track;      /* current head position or -1 if
0296                    unknown */
0297     unsigned int steprate;  /* steprate setting */
0298     unsigned int wpstat;    /* current state of WP signal (for
0299                    disk change detection) */
0300     int flags;      /* flags */
0301     struct gendisk *disk[NUM_DISK_MINORS];
0302     bool registered[NUM_DISK_MINORS];
0303     int ref;
0304     int type;
0305     struct blk_mq_tag_set tag_set;
0306     int error_count;
0307 } unit[FD_MAX_UNITS];
0308 
0309 #define UD  unit[drive]
0310 #define UDT unit[drive].disktype
0311 #define SUD unit[SelectedDrive]
0312 #define SUDT    unit[SelectedDrive].disktype
0313 
0314 
0315 #define FDC_READ(reg) ({            \
0316     /* unsigned long __flags; */        \
0317     unsigned short __val;           \
0318     /* local_irq_save(__flags); */      \
0319     dma_wd.dma_mode_status = 0x80 | (reg);  \
0320     udelay(25);                 \
0321     __val = dma_wd.fdc_acces_seccount;      \
0322     MFPDELAY();                 \
0323     /* local_irq_restore(__flags); */       \
0324     __val & 0xff;               \
0325 })
0326 
0327 #define FDC_WRITE(reg,val)          \
0328     do {                    \
0329     /* unsigned long __flags; */        \
0330     /* local_irq_save(__flags); */      \
0331     dma_wd.dma_mode_status = 0x80 | (reg);  \
0332     udelay(25);             \
0333     dma_wd.fdc_acces_seccount = (val);  \
0334     MFPDELAY();             \
0335         /* local_irq_restore(__flags); */   \
0336     } while(0)
0337 
0338 
0339 /* Buffering variables:
0340  * First, there is a DMA buffer in ST-RAM that is used for floppy DMA
0341  * operations. Second, a track buffer is used to cache a whole track
0342  * of the disk to save read operations. These are two separate buffers
0343  * because that allows write operations without clearing the track buffer.
0344  */
0345 
0346 static int MaxSectors[] = {
0347     11, 22, 44
0348 };
0349 static int BufferSize[] = {
0350     15*512, 30*512, 60*512
0351 };
0352 
0353 #define BUFFER_SIZE (BufferSize[DriveType])
0354 
0355 unsigned char *DMABuffer;             /* buffer for writes */
0356 static unsigned long PhysDMABuffer;   /* physical address */
0357 
0358 static int UseTrackbuffer = -1;       /* Do track buffering? */
0359 module_param(UseTrackbuffer, int, 0);
0360 
0361 unsigned char *TrackBuffer;           /* buffer for reads */
0362 static unsigned long PhysTrackBuffer; /* physical address */
0363 static int BufferDrive, BufferSide, BufferTrack;
0364 static int read_track;      /* non-zero if we are reading whole tracks */
0365 
0366 #define SECTOR_BUFFER(sec)  (TrackBuffer + ((sec)-1)*512)
0367 #define IS_BUFFERED(drive,side,track) \
0368     (BufferDrive == (drive) && BufferSide == (side) && BufferTrack == (track))
0369 
0370 /*
0371  * These are global variables, as that's the easiest way to give
0372  * information to interrupts. They are the data used for the current
0373  * request.
0374  */
0375 static int SelectedDrive = 0;
0376 static int ReqCmd, ReqBlock;
0377 static int ReqSide, ReqTrack, ReqSector, ReqCnt;
0378 static int HeadSettleFlag = 0;
0379 static unsigned char *ReqData, *ReqBuffer;
0380 static int MotorOn = 0, MotorOffTrys;
0381 static int IsFormatting = 0, FormatError;
0382 
0383 static int UserSteprate[FD_MAX_UNITS] = { -1, -1 };
0384 module_param_array(UserSteprate, int, NULL, 0);
0385 
0386 static DECLARE_COMPLETION(format_wait);
0387 
0388 static unsigned long changed_floppies = 0xff, fake_change = 0;
0389 #define CHECK_CHANGE_DELAY  HZ/2
0390 
0391 #define FD_MOTOR_OFF_DELAY  (3*HZ)
0392 #define FD_MOTOR_OFF_MAXTRY (10*20)
0393 
0394 #define FLOPPY_TIMEOUT      (6*HZ)
0395 #define RECALIBRATE_ERRORS  4   /* After this many errors the drive
0396                      * will be recalibrated. */
0397 #define MAX_ERRORS      8   /* After this many errors the driver
0398                      * will give up. */
0399 
0400 
0401 /*
0402  * The driver is trying to determine the correct media format
0403  * while Probing is set. fd_rwsec_done() clears it after a
0404  * successful access.
0405  */
0406 static int Probing = 0;
0407 
0408 /* This flag is set when a dummy seek is necessary to make the WP
0409  * status bit accessible.
0410  */
0411 static int NeedSeek = 0;
0412 
0413 
0414 #ifdef DEBUG
0415 #define DPRINT(a)   printk a
0416 #else
0417 #define DPRINT(a)
0418 #endif
0419 
0420 /***************************** Prototypes *****************************/
0421 
0422 static void fd_select_side( int side );
0423 static void fd_select_drive( int drive );
0424 static void fd_deselect( void );
0425 static void fd_motor_off_timer(struct timer_list *unused);
0426 static void check_change(struct timer_list *unused);
0427 static irqreturn_t floppy_irq (int irq, void *dummy);
0428 static void fd_error( void );
0429 static int do_format(int drive, int type, struct atari_format_descr *desc);
0430 static void do_fd_action( int drive );
0431 static void fd_calibrate( void );
0432 static void fd_calibrate_done( int status );
0433 static void fd_seek( void );
0434 static void fd_seek_done( int status );
0435 static void fd_rwsec( void );
0436 static void fd_readtrack_check(struct timer_list *unused);
0437 static void fd_rwsec_done( int status );
0438 static void fd_rwsec_done1(int status);
0439 static void fd_writetrack( void );
0440 static void fd_writetrack_done( int status );
0441 static void fd_times_out(struct timer_list *unused);
0442 static void finish_fdc( void );
0443 static void finish_fdc_done( int dummy );
0444 static void setup_req_params( int drive );
0445 static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int
0446                      cmd, unsigned long param);
0447 static void fd_probe( int drive );
0448 static int fd_test_drive_present( int drive );
0449 static void config_types( void );
0450 static int floppy_open(struct block_device *bdev, fmode_t mode);
0451 static void floppy_release(struct gendisk *disk, fmode_t mode);
0452 
0453 /************************* End of Prototypes **************************/
0454 
0455 static DEFINE_TIMER(motor_off_timer, fd_motor_off_timer);
0456 static DEFINE_TIMER(readtrack_timer, fd_readtrack_check);
0457 static DEFINE_TIMER(timeout_timer, fd_times_out);
0458 static DEFINE_TIMER(fd_timer, check_change);
0459     
0460 static void fd_end_request_cur(blk_status_t err)
0461 {
0462     DPRINT(("fd_end_request_cur(), bytes %d of %d\n",
0463         blk_rq_cur_bytes(fd_request),
0464         blk_rq_bytes(fd_request)));
0465 
0466     if (!blk_update_request(fd_request, err,
0467                 blk_rq_cur_bytes(fd_request))) {
0468         DPRINT(("calling __blk_mq_end_request()\n"));
0469         __blk_mq_end_request(fd_request, err);
0470         fd_request = NULL;
0471     } else {
0472         /* requeue rest of request */
0473         DPRINT(("calling blk_mq_requeue_request()\n"));
0474         blk_mq_requeue_request(fd_request, true);
0475         fd_request = NULL;
0476     }
0477 }
0478 
0479 static inline void start_motor_off_timer(void)
0480 {
0481     mod_timer(&motor_off_timer, jiffies + FD_MOTOR_OFF_DELAY);
0482     MotorOffTrys = 0;
0483 }
0484 
0485 static inline void start_check_change_timer( void )
0486 {
0487     mod_timer(&fd_timer, jiffies + CHECK_CHANGE_DELAY);
0488 }
0489 
0490 static inline void start_timeout(void)
0491 {
0492     mod_timer(&timeout_timer, jiffies + FLOPPY_TIMEOUT);
0493 }
0494 
0495 static inline void stop_timeout(void)
0496 {
0497     del_timer(&timeout_timer);
0498 }
0499 
0500 /* Select the side to use. */
0501 
0502 static void fd_select_side( int side )
0503 {
0504     unsigned long flags;
0505 
0506     /* protect against various other ints mucking around with the PSG */
0507     local_irq_save(flags);
0508   
0509     sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
0510     sound_ym.wd_data = (side == 0) ? sound_ym.rd_data_reg_sel | 0x01 :
0511                                      sound_ym.rd_data_reg_sel & 0xfe;
0512 
0513     local_irq_restore(flags);
0514 }
0515 
0516 
0517 /* Select a drive, update the FDC's track register and set the correct
0518  * clock speed for this disk's type.
0519  */
0520 
0521 static void fd_select_drive( int drive )
0522 {
0523     unsigned long flags;
0524     unsigned char tmp;
0525   
0526     if (drive == SelectedDrive)
0527       return;
0528 
0529     /* protect against various other ints mucking around with the PSG */
0530     local_irq_save(flags);
0531     sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
0532     tmp = sound_ym.rd_data_reg_sel;
0533     sound_ym.wd_data = (tmp | DSKDRVNONE) & ~(drive == 0 ? DSKDRV0 : DSKDRV1);
0534     atari_dont_touch_floppy_select = 1;
0535     local_irq_restore(flags);
0536 
0537     /* restore track register to saved value */
0538     FDC_WRITE( FDCREG_TRACK, UD.track );
0539     udelay(25);
0540 
0541     /* select 8/16 MHz */
0542     if (UDT)
0543         if (ATARIHW_PRESENT(FDCSPEED))
0544             dma_wd.fdc_speed = UDT->fdc_speed;
0545     
0546     SelectedDrive = drive;
0547 }
0548 
0549 
0550 /* Deselect both drives. */
0551 
0552 static void fd_deselect( void )
0553 {
0554     unsigned long flags;
0555 
0556     /* protect against various other ints mucking around with the PSG */
0557     local_irq_save(flags);
0558     atari_dont_touch_floppy_select = 0;
0559     sound_ym.rd_data_reg_sel=14;    /* Select PSG Port A */
0560     sound_ym.wd_data = (sound_ym.rd_data_reg_sel |
0561                 (MACH_IS_FALCON ? 3 : 7)); /* no drives selected */
0562     /* On Falcon, the drive B select line is used on the printer port, so
0563      * leave it alone... */
0564     SelectedDrive = -1;
0565     local_irq_restore(flags);
0566 }
0567 
0568 
0569 /* This timer function deselects the drives when the FDC switched the
0570  * motor off. The deselection cannot happen earlier because the FDC
0571  * counts the index signals, which arrive only if one drive is selected.
0572  */
0573 
0574 static void fd_motor_off_timer(struct timer_list *unused)
0575 {
0576     unsigned char status;
0577 
0578     if (SelectedDrive < 0)
0579         /* no drive selected, needn't deselect anyone */
0580         return;
0581 
0582     if (stdma_islocked())
0583         goto retry;
0584 
0585     status = FDC_READ( FDCREG_STATUS );
0586 
0587     if (!(status & 0x80)) {
0588         /* motor already turned off by FDC -> deselect drives */
0589         MotorOn = 0;
0590         fd_deselect();
0591         return;
0592     }
0593     /* not yet off, try again */
0594 
0595   retry:
0596     /* Test again later; if tested too often, it seems there is no disk
0597      * in the drive and the FDC will leave the motor on forever (or,
0598      * at least until a disk is inserted). So we'll test only twice
0599      * per second from then on...
0600      */
0601     mod_timer(&motor_off_timer,
0602           jiffies + (MotorOffTrys++ < FD_MOTOR_OFF_MAXTRY ? HZ/20 : HZ/2));
0603 }
0604 
0605 
0606 /* This function is repeatedly called to detect disk changes (as good
0607  * as possible) and keep track of the current state of the write protection.
0608  */
0609 
0610 static void check_change(struct timer_list *unused)
0611 {
0612     static int    drive = 0;
0613 
0614     unsigned long flags;
0615     unsigned char old_porta;
0616     int           stat;
0617 
0618     if (++drive > 1 || !UD.connected)
0619         drive = 0;
0620 
0621     /* protect against various other ints mucking around with the PSG */
0622     local_irq_save(flags);
0623 
0624     if (!stdma_islocked()) {
0625         sound_ym.rd_data_reg_sel = 14;
0626         old_porta = sound_ym.rd_data_reg_sel;
0627         sound_ym.wd_data = (old_porta | DSKDRVNONE) &
0628                            ~(drive == 0 ? DSKDRV0 : DSKDRV1);
0629         stat = !!(FDC_READ( FDCREG_STATUS ) & FDCSTAT_WPROT);
0630         sound_ym.wd_data = old_porta;
0631 
0632         if (stat != UD.wpstat) {
0633             DPRINT(( "wpstat[%d] = %d\n", drive, stat ));
0634             UD.wpstat = stat;
0635             set_bit (drive, &changed_floppies);
0636         }
0637     }
0638     local_irq_restore(flags);
0639 
0640     start_check_change_timer();
0641 }
0642 
0643  
0644 /* Handling of the Head Settling Flag: This flag should be set after each
0645  * seek operation, because we don't use seeks with verify.
0646  */
0647 
0648 static inline void set_head_settle_flag(void)
0649 {
0650     HeadSettleFlag = FDCCMDADD_E;
0651 }
0652 
0653 static inline int get_head_settle_flag(void)
0654 {
0655     int tmp = HeadSettleFlag;
0656     HeadSettleFlag = 0;
0657     return( tmp );
0658 }
0659 
0660 static inline void copy_buffer(void *from, void *to)
0661 {
0662     ulong *p1 = (ulong *)from, *p2 = (ulong *)to;
0663     int cnt;
0664 
0665     for (cnt = 512/4; cnt; cnt--)
0666         *p2++ = *p1++;
0667 }
0668 
0669 /* General Interrupt Handling */
0670 
0671 static void (*FloppyIRQHandler)( int status ) = NULL;
0672 
0673 static irqreturn_t floppy_irq (int irq, void *dummy)
0674 {
0675     unsigned char status;
0676     void (*handler)( int );
0677 
0678     handler = xchg(&FloppyIRQHandler, NULL);
0679 
0680     if (handler) {
0681         nop();
0682         status = FDC_READ( FDCREG_STATUS );
0683         DPRINT(("FDC irq, status = %02x handler = %08lx\n",status,(unsigned long)handler));
0684         handler( status );
0685     }
0686     else {
0687         DPRINT(("FDC irq, no handler\n"));
0688     }
0689     return IRQ_HANDLED;
0690 }
0691 
0692 
0693 /* Error handling: If some error happened, retry some times, then
0694  * recalibrate, then try again, and fail after MAX_ERRORS.
0695  */
0696 
0697 static void fd_error( void )
0698 {
0699     if (IsFormatting) {
0700         IsFormatting = 0;
0701         FormatError = 1;
0702         complete(&format_wait);
0703         return;
0704     }
0705 
0706     if (!fd_request)
0707         return;
0708 
0709     unit[SelectedDrive].error_count++;
0710     if (unit[SelectedDrive].error_count >= MAX_ERRORS) {
0711         printk(KERN_ERR "fd%d: too many errors.\n", SelectedDrive );
0712         fd_end_request_cur(BLK_STS_IOERR);
0713         finish_fdc();
0714         return;
0715     }
0716     else if (unit[SelectedDrive].error_count == RECALIBRATE_ERRORS) {
0717         printk(KERN_WARNING "fd%d: recalibrating\n", SelectedDrive );
0718         if (SelectedDrive != -1)
0719             SUD.track = -1;
0720     }
0721     /* need to re-run request to recalibrate */
0722     atari_disable_irq( IRQ_MFP_FDC );
0723 
0724     setup_req_params( SelectedDrive );
0725     do_fd_action( SelectedDrive );
0726 
0727     atari_enable_irq( IRQ_MFP_FDC );
0728 }
0729 
0730 
0731 
0732 #define SET_IRQ_HANDLER(proc) do { FloppyIRQHandler = (proc); } while(0)
0733 
0734 
0735 /* ---------- Formatting ---------- */
0736 
0737 #define FILL(n,val)     \
0738     do {            \
0739     memset( p, val, n );    \
0740     p += n;         \
0741     } while(0)
0742 
0743 static int do_format(int drive, int type, struct atari_format_descr *desc)
0744 {
0745     struct request_queue *q;
0746     unsigned char   *p;
0747     int sect, nsect;
0748     unsigned long   flags;
0749     int ret;
0750 
0751     if (type) {
0752         type--;
0753         if (type >= NUM_DISK_MINORS ||
0754             minor2disktype[type].drive_types > DriveType) {
0755             finish_fdc();
0756             return -EINVAL;
0757         }
0758     }
0759 
0760     q = unit[drive].disk[type]->queue;
0761     blk_mq_freeze_queue(q);
0762     blk_mq_quiesce_queue(q);
0763 
0764     local_irq_save(flags);
0765     stdma_lock(floppy_irq, NULL);
0766     atari_turnon_irq( IRQ_MFP_FDC ); /* should be already, just to be sure */
0767     local_irq_restore(flags);
0768 
0769     if (type) {
0770         type = minor2disktype[type].index;
0771         UDT = &atari_disk_type[type];
0772     }
0773 
0774     if (!UDT || desc->track >= UDT->blocks/UDT->spt/2 || desc->head >= 2) {
0775         finish_fdc();
0776         ret = -EINVAL;
0777         goto out;
0778     }
0779 
0780     nsect = UDT->spt;
0781     p = TrackBuffer;
0782     /* The track buffer is used for the raw track data, so its
0783        contents become invalid! */
0784     BufferDrive = -1;
0785     /* stop deselect timer */
0786     del_timer( &motor_off_timer );
0787 
0788     FILL( 60 * (nsect / 9), 0x4e );
0789     for( sect = 0; sect < nsect; ++sect ) {
0790         FILL( 12, 0 );
0791         FILL( 3, 0xf5 );
0792         *p++ = 0xfe;
0793         *p++ = desc->track;
0794         *p++ = desc->head;
0795         *p++ = (nsect + sect - desc->sect_offset) % nsect + 1;
0796         *p++ = 2;
0797         *p++ = 0xf7;
0798         FILL( 22, 0x4e );
0799         FILL( 12, 0 );
0800         FILL( 3, 0xf5 );
0801         *p++ = 0xfb;
0802         FILL( 512, 0xe5 );
0803         *p++ = 0xf7;
0804         FILL( 40, 0x4e );
0805     }
0806     FILL( TrackBuffer+BUFFER_SIZE-p, 0x4e );
0807 
0808     IsFormatting = 1;
0809     FormatError = 0;
0810     ReqTrack = desc->track;
0811     ReqSide  = desc->head;
0812     do_fd_action( drive );
0813 
0814     wait_for_completion(&format_wait);
0815 
0816     finish_fdc();
0817     ret = FormatError ? -EIO : 0;
0818 out:
0819     blk_mq_unquiesce_queue(q);
0820     blk_mq_unfreeze_queue(q);
0821     return ret;
0822 }
0823 
0824 
0825 /* do_fd_action() is the general procedure for a fd request: All
0826  * required parameter settings (drive select, side select, track
0827  * position) are checked and set if needed. For each of these
0828  * parameters and the actual reading or writing exist two functions:
0829  * one that starts the setting (or skips it if possible) and one
0830  * callback for the "done" interrupt. Each done func calls the next
0831  * set function to propagate the request down to fd_rwsec_done().
0832  */
0833 
0834 static void do_fd_action( int drive )
0835 {
0836     DPRINT(("do_fd_action\n"));
0837     
0838     if (UseTrackbuffer && !IsFormatting) {
0839     repeat:
0840         if (IS_BUFFERED( drive, ReqSide, ReqTrack )) {
0841         if (ReqCmd == READ) {
0842             copy_buffer( SECTOR_BUFFER(ReqSector), ReqData );
0843             if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
0844             /* read next sector */
0845             setup_req_params( drive );
0846             goto repeat;
0847             }
0848             else {
0849             /* all sectors finished */
0850             fd_end_request_cur(BLK_STS_OK);
0851             finish_fdc();
0852             return;
0853             }
0854         }
0855         else {
0856             /* cmd == WRITE, pay attention to track buffer
0857              * consistency! */
0858             copy_buffer( ReqData, SECTOR_BUFFER(ReqSector) );
0859         }
0860         }
0861     }
0862 
0863     if (SelectedDrive != drive)
0864         fd_select_drive( drive );
0865     
0866     if (UD.track == -1)
0867         fd_calibrate();
0868     else if (UD.track != ReqTrack << UDT->stretch)
0869         fd_seek();
0870     else if (IsFormatting)
0871         fd_writetrack();
0872     else
0873         fd_rwsec();
0874 }
0875 
0876 
0877 /* Seek to track 0 if the current track is unknown */
0878 
0879 static void fd_calibrate( void )
0880 {
0881     if (SUD.track >= 0) {
0882         fd_calibrate_done( 0 );
0883         return;
0884     }
0885 
0886     if (ATARIHW_PRESENT(FDCSPEED))
0887         dma_wd.fdc_speed = 0;   /* always seek with 8 Mhz */
0888     DPRINT(("fd_calibrate\n"));
0889     SET_IRQ_HANDLER( fd_calibrate_done );
0890     /* we can't verify, since the speed may be incorrect */
0891     FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | SUD.steprate );
0892 
0893     NeedSeek = 1;
0894     MotorOn = 1;
0895     start_timeout();
0896     /* wait for IRQ */
0897 }
0898 
0899 
0900 static void fd_calibrate_done( int status )
0901 {
0902     DPRINT(("fd_calibrate_done()\n"));
0903     stop_timeout();
0904     
0905     /* set the correct speed now */
0906     if (ATARIHW_PRESENT(FDCSPEED))
0907         dma_wd.fdc_speed = SUDT->fdc_speed;
0908     if (status & FDCSTAT_RECNF) {
0909         printk(KERN_ERR "fd%d: restore failed\n", SelectedDrive );
0910         fd_error();
0911     }
0912     else {
0913         SUD.track = 0;
0914         fd_seek();
0915     }
0916 }
0917   
0918   
0919 /* Seek the drive to the requested track. The drive must have been
0920  * calibrated at some point before this.
0921  */
0922   
0923 static void fd_seek( void )
0924 {
0925     if (SUD.track == ReqTrack << SUDT->stretch) {
0926         fd_seek_done( 0 );
0927         return;
0928     }
0929 
0930     if (ATARIHW_PRESENT(FDCSPEED)) {
0931         dma_wd.fdc_speed = 0;   /* always seek witch 8 Mhz */
0932         MFPDELAY();
0933     }
0934 
0935     DPRINT(("fd_seek() to track %d\n",ReqTrack));
0936     FDC_WRITE( FDCREG_DATA, ReqTrack << SUDT->stretch);
0937     udelay(25);
0938     SET_IRQ_HANDLER( fd_seek_done );
0939     FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK | SUD.steprate );
0940 
0941     MotorOn = 1;
0942     set_head_settle_flag();
0943     start_timeout();
0944     /* wait for IRQ */
0945 }
0946 
0947 
0948 static void fd_seek_done( int status )
0949 {
0950     DPRINT(("fd_seek_done()\n"));
0951     stop_timeout();
0952     
0953     /* set the correct speed */
0954     if (ATARIHW_PRESENT(FDCSPEED))
0955         dma_wd.fdc_speed = SUDT->fdc_speed;
0956     if (status & FDCSTAT_RECNF) {
0957         printk(KERN_ERR "fd%d: seek error (to track %d)\n",
0958                 SelectedDrive, ReqTrack );
0959         /* we don't know exactly which track we are on now! */
0960         SUD.track = -1;
0961         fd_error();
0962     }
0963     else {
0964         SUD.track = ReqTrack << SUDT->stretch;
0965         NeedSeek = 0;
0966         if (IsFormatting)
0967             fd_writetrack();
0968         else
0969             fd_rwsec();
0970     }
0971 }
0972 
0973 
0974 /* This does the actual reading/writing after positioning the head
0975  * over the correct track.
0976  */
0977 
0978 static int MultReadInProgress = 0;
0979 
0980 
0981 static void fd_rwsec( void )
0982 {
0983     unsigned long paddr, flags;
0984     unsigned int  rwflag, old_motoron;
0985     unsigned int track;
0986     
0987     DPRINT(("fd_rwsec(), Sec=%d, Access=%c\n",ReqSector, ReqCmd == WRITE ? 'w' : 'r' ));
0988     if (ReqCmd == WRITE) {
0989         if (ATARIHW_PRESENT(EXTD_DMA)) {
0990             paddr = virt_to_phys(ReqData);
0991         }
0992         else {
0993             copy_buffer( ReqData, DMABuffer );
0994             paddr = PhysDMABuffer;
0995         }
0996         dma_cache_maintenance( paddr, 512, 1 );
0997         rwflag = 0x100;
0998     }
0999     else {
1000         if (read_track)
1001             paddr = PhysTrackBuffer;
1002         else
1003             paddr = ATARIHW_PRESENT(EXTD_DMA) ? 
1004                 virt_to_phys(ReqData) : PhysDMABuffer;
1005         rwflag = 0;
1006     }
1007 
1008     fd_select_side( ReqSide );
1009   
1010     /* Start sector of this operation */
1011     FDC_WRITE( FDCREG_SECTOR, read_track ? 1 : ReqSector );
1012     MFPDELAY();
1013     /* Cheat for track if stretch != 0 */
1014     if (SUDT->stretch) {
1015         track = FDC_READ( FDCREG_TRACK);
1016         MFPDELAY();
1017         FDC_WRITE( FDCREG_TRACK, track >> SUDT->stretch);
1018     }
1019     udelay(25);
1020   
1021     /* Setup DMA */
1022     local_irq_save(flags);
1023     dma_wd.dma_lo = (unsigned char)paddr;
1024     MFPDELAY();
1025     paddr >>= 8;
1026     dma_wd.dma_md = (unsigned char)paddr;
1027     MFPDELAY();
1028     paddr >>= 8;
1029     if (ATARIHW_PRESENT(EXTD_DMA))
1030         st_dma_ext_dmahi = (unsigned short)paddr;
1031     else
1032         dma_wd.dma_hi = (unsigned char)paddr;
1033     MFPDELAY();
1034     local_irq_restore(flags);
1035   
1036     /* Clear FIFO and switch DMA to correct mode */  
1037     dma_wd.dma_mode_status = 0x90 | rwflag;  
1038     MFPDELAY();
1039     dma_wd.dma_mode_status = 0x90 | (rwflag ^ 0x100);  
1040     MFPDELAY();
1041     dma_wd.dma_mode_status = 0x90 | rwflag;
1042     MFPDELAY();
1043   
1044     /* How many sectors for DMA */
1045     dma_wd.fdc_acces_seccount = read_track ? SUDT->spt : 1;
1046   
1047     udelay(25);  
1048   
1049     /* Start operation */
1050     dma_wd.dma_mode_status = FDCSELREG_STP | rwflag;
1051     udelay(25);
1052     SET_IRQ_HANDLER( fd_rwsec_done );
1053     dma_wd.fdc_acces_seccount =
1054       (get_head_settle_flag() |
1055        (rwflag ? FDCCMD_WRSEC : (FDCCMD_RDSEC | (read_track ? FDCCMDADD_M : 0))));
1056 
1057     old_motoron = MotorOn;
1058     MotorOn = 1;
1059     NeedSeek = 1;
1060     /* wait for interrupt */
1061 
1062     if (read_track) {
1063         /* If reading a whole track, wait about one disk rotation and
1064          * then check if all sectors are read. The FDC will even
1065          * search for the first non-existent sector and need 1 sec to
1066          * recognise that it isn't present :-(
1067          */
1068         MultReadInProgress = 1;
1069         mod_timer(&readtrack_timer,
1070               /* 1 rot. + 5 rot.s if motor was off  */
1071               jiffies + HZ/5 + (old_motoron ? 0 : HZ));
1072     }
1073     start_timeout();
1074 }
1075 
1076     
1077 static void fd_readtrack_check(struct timer_list *unused)
1078 {
1079     unsigned long flags, addr, addr2;
1080 
1081     local_irq_save(flags);
1082 
1083     if (!MultReadInProgress) {
1084         /* This prevents a race condition that could arise if the
1085          * interrupt is triggered while the calling of this timer
1086          * callback function takes place. The IRQ function then has
1087          * already cleared 'MultReadInProgress'  when flow of control
1088          * gets here.
1089          */
1090         local_irq_restore(flags);
1091         return;
1092     }
1093 
1094     /* get the current DMA address */
1095     /* ++ f.a. read twice to avoid being fooled by switcher */
1096     addr = 0;
1097     do {
1098         addr2 = addr;
1099         addr = dma_wd.dma_lo & 0xff;
1100         MFPDELAY();
1101         addr |= (dma_wd.dma_md & 0xff) << 8;
1102         MFPDELAY();
1103         if (ATARIHW_PRESENT( EXTD_DMA ))
1104             addr |= (st_dma_ext_dmahi & 0xffff) << 16;
1105         else
1106             addr |= (dma_wd.dma_hi & 0xff) << 16;
1107         MFPDELAY();
1108     } while(addr != addr2);
1109   
1110     if (addr >= PhysTrackBuffer + SUDT->spt*512) {
1111         /* already read enough data, force an FDC interrupt to stop
1112          * the read operation
1113          */
1114         SET_IRQ_HANDLER( NULL );
1115         MultReadInProgress = 0;
1116         local_irq_restore(flags);
1117         DPRINT(("fd_readtrack_check(): done\n"));
1118         FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1119         udelay(25);
1120 
1121         /* No error until now -- the FDC would have interrupted
1122          * otherwise!
1123          */
1124         fd_rwsec_done1(0);
1125     }
1126     else {
1127         /* not yet finished, wait another tenth rotation */
1128         local_irq_restore(flags);
1129         DPRINT(("fd_readtrack_check(): not yet finished\n"));
1130         mod_timer(&readtrack_timer, jiffies + HZ/5/10);
1131     }
1132 }
1133 
1134 
1135 static void fd_rwsec_done( int status )
1136 {
1137     DPRINT(("fd_rwsec_done()\n"));
1138 
1139     if (read_track) {
1140         del_timer(&readtrack_timer);
1141         if (!MultReadInProgress)
1142             return;
1143         MultReadInProgress = 0;
1144     }
1145     fd_rwsec_done1(status);
1146 }
1147 
1148 static void fd_rwsec_done1(int status)
1149 {
1150     unsigned int track;
1151 
1152     stop_timeout();
1153     
1154     /* Correct the track if stretch != 0 */
1155     if (SUDT->stretch) {
1156         track = FDC_READ( FDCREG_TRACK);
1157         MFPDELAY();
1158         FDC_WRITE( FDCREG_TRACK, track << SUDT->stretch);
1159     }
1160 
1161     if (!UseTrackbuffer) {
1162         dma_wd.dma_mode_status = 0x90;
1163         MFPDELAY();
1164         if (!(dma_wd.dma_mode_status & 0x01)) {
1165             printk(KERN_ERR "fd%d: DMA error\n", SelectedDrive );
1166             goto err_end;
1167         }
1168     }
1169     MFPDELAY();
1170 
1171     if (ReqCmd == WRITE && (status & FDCSTAT_WPROT)) {
1172         printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
1173         goto err_end;
1174     }   
1175     if ((status & FDCSTAT_RECNF) &&
1176         /* RECNF is no error after a multiple read when the FDC
1177            searched for a non-existent sector! */
1178         !(read_track && FDC_READ(FDCREG_SECTOR) > SUDT->spt)) {
1179         if (Probing) {
1180             if (SUDT > atari_disk_type) {
1181                 if (SUDT[-1].blocks > ReqBlock) {
1182                 /* try another disk type */
1183                 SUDT--;
1184                 set_capacity(unit[SelectedDrive].disk[0],
1185                             SUDT->blocks);
1186                 } else
1187                 Probing = 0;
1188             }
1189             else {
1190                 if (SUD.flags & FTD_MSG)
1191                     printk(KERN_INFO "fd%d: Auto-detected floppy type %s\n",
1192                            SelectedDrive, SUDT->name );
1193                 Probing=0;
1194             }
1195         } else {    
1196 /* record not found, but not probing. Maybe stretch wrong ? Restart probing */
1197             if (SUD.autoprobe) {
1198                 SUDT = atari_disk_type + StartDiskType[DriveType];
1199                 set_capacity(unit[SelectedDrive].disk[0],
1200                             SUDT->blocks);
1201                 Probing = 1;
1202             }
1203         }
1204         if (Probing) {
1205             if (ATARIHW_PRESENT(FDCSPEED)) {
1206                 dma_wd.fdc_speed = SUDT->fdc_speed;
1207                 MFPDELAY();
1208             }
1209             setup_req_params( SelectedDrive );
1210             BufferDrive = -1;
1211             do_fd_action( SelectedDrive );
1212             return;
1213         }
1214 
1215         printk(KERN_ERR "fd%d: sector %d not found (side %d, track %d)\n",
1216                SelectedDrive, FDC_READ (FDCREG_SECTOR), ReqSide, ReqTrack );
1217         goto err_end;
1218     }
1219     if (status & FDCSTAT_CRC) {
1220         printk(KERN_ERR "fd%d: CRC error (side %d, track %d, sector %d)\n",
1221                SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
1222         goto err_end;
1223     }
1224     if (status & FDCSTAT_LOST) {
1225         printk(KERN_ERR "fd%d: lost data (side %d, track %d, sector %d)\n",
1226                SelectedDrive, ReqSide, ReqTrack, FDC_READ (FDCREG_SECTOR) );
1227         goto err_end;
1228     }
1229 
1230     Probing = 0;
1231     
1232     if (ReqCmd == READ) {
1233         if (!read_track) {
1234             void *addr;
1235             addr = ATARIHW_PRESENT( EXTD_DMA ) ? ReqData : DMABuffer;
1236             dma_cache_maintenance( virt_to_phys(addr), 512, 0 );
1237             if (!ATARIHW_PRESENT( EXTD_DMA ))
1238                 copy_buffer (addr, ReqData);
1239         } else {
1240             dma_cache_maintenance( PhysTrackBuffer, MaxSectors[DriveType] * 512, 0 );
1241             BufferDrive = SelectedDrive;
1242             BufferSide  = ReqSide;
1243             BufferTrack = ReqTrack;
1244             copy_buffer (SECTOR_BUFFER (ReqSector), ReqData);
1245         }
1246     }
1247   
1248     if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
1249         /* read next sector */
1250         setup_req_params( SelectedDrive );
1251         do_fd_action( SelectedDrive );
1252     }
1253     else {
1254         /* all sectors finished */
1255         fd_end_request_cur(BLK_STS_OK);
1256         finish_fdc();
1257     }
1258     return;
1259   
1260   err_end:
1261     BufferDrive = -1;
1262     fd_error();
1263 }
1264 
1265 
1266 static void fd_writetrack( void )
1267 {
1268     unsigned long paddr, flags;
1269     unsigned int track;
1270     
1271     DPRINT(("fd_writetrack() Tr=%d Si=%d\n", ReqTrack, ReqSide ));
1272 
1273     paddr = PhysTrackBuffer;
1274     dma_cache_maintenance( paddr, BUFFER_SIZE, 1 );
1275 
1276     fd_select_side( ReqSide );
1277   
1278     /* Cheat for track if stretch != 0 */
1279     if (SUDT->stretch) {
1280         track = FDC_READ( FDCREG_TRACK);
1281         MFPDELAY();
1282         FDC_WRITE(FDCREG_TRACK,track >> SUDT->stretch);
1283     }
1284     udelay(40);
1285   
1286     /* Setup DMA */
1287     local_irq_save(flags);
1288     dma_wd.dma_lo = (unsigned char)paddr;
1289     MFPDELAY();
1290     paddr >>= 8;
1291     dma_wd.dma_md = (unsigned char)paddr;
1292     MFPDELAY();
1293     paddr >>= 8;
1294     if (ATARIHW_PRESENT( EXTD_DMA ))
1295         st_dma_ext_dmahi = (unsigned short)paddr;
1296     else
1297         dma_wd.dma_hi = (unsigned char)paddr;
1298     MFPDELAY();
1299     local_irq_restore(flags);
1300   
1301     /* Clear FIFO and switch DMA to correct mode */  
1302     dma_wd.dma_mode_status = 0x190;  
1303     MFPDELAY();
1304     dma_wd.dma_mode_status = 0x90;  
1305     MFPDELAY();
1306     dma_wd.dma_mode_status = 0x190;
1307     MFPDELAY();
1308   
1309     /* How many sectors for DMA */
1310     dma_wd.fdc_acces_seccount = BUFFER_SIZE/512;
1311     udelay(40);  
1312   
1313     /* Start operation */
1314     dma_wd.dma_mode_status = FDCSELREG_STP | 0x100;
1315     udelay(40);
1316     SET_IRQ_HANDLER( fd_writetrack_done );
1317     dma_wd.fdc_acces_seccount = FDCCMD_WRTRA | get_head_settle_flag(); 
1318 
1319     MotorOn = 1;
1320     start_timeout();
1321     /* wait for interrupt */
1322 }
1323 
1324 
1325 static void fd_writetrack_done( int status )
1326 {
1327     DPRINT(("fd_writetrack_done()\n"));
1328 
1329     stop_timeout();
1330 
1331     if (status & FDCSTAT_WPROT) {
1332         printk(KERN_NOTICE "fd%d: is write protected\n", SelectedDrive );
1333         goto err_end;
1334     }   
1335     if (status & FDCSTAT_LOST) {
1336         printk(KERN_ERR "fd%d: lost data (side %d, track %d)\n",
1337                 SelectedDrive, ReqSide, ReqTrack );
1338         goto err_end;
1339     }
1340 
1341     complete(&format_wait);
1342     return;
1343 
1344   err_end:
1345     fd_error();
1346 }
1347 
1348 static void fd_times_out(struct timer_list *unused)
1349 {
1350     atari_disable_irq( IRQ_MFP_FDC );
1351     if (!FloppyIRQHandler) goto end; /* int occurred after timer was fired, but
1352                       * before we came here... */
1353 
1354     SET_IRQ_HANDLER( NULL );
1355     /* If the timeout occurred while the readtrack_check timer was
1356      * active, we need to cancel it, else bad things will happen */
1357     if (UseTrackbuffer)
1358         del_timer( &readtrack_timer );
1359     FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1360     udelay( 25 );
1361     
1362     printk(KERN_ERR "floppy timeout\n" );
1363     fd_error();
1364   end:
1365     atari_enable_irq( IRQ_MFP_FDC );
1366 }
1367 
1368 
1369 /* The (noop) seek operation here is needed to make the WP bit in the
1370  * FDC status register accessible for check_change. If the last disk
1371  * operation would have been a RDSEC, this bit would always read as 0
1372  * no matter what :-( To save time, the seek goes to the track we're
1373  * already on.
1374  */
1375 
1376 static void finish_fdc( void )
1377 {
1378     if (!NeedSeek || !stdma_is_locked_by(floppy_irq)) {
1379         finish_fdc_done( 0 );
1380     }
1381     else {
1382         DPRINT(("finish_fdc: dummy seek started\n"));
1383         FDC_WRITE (FDCREG_DATA, SUD.track);
1384         SET_IRQ_HANDLER( finish_fdc_done );
1385         FDC_WRITE (FDCREG_CMD, FDCCMD_SEEK);
1386         MotorOn = 1;
1387         start_timeout();
1388         /* we must wait for the IRQ here, because the ST-DMA
1389            is released immediately afterwards and the interrupt
1390            may be delivered to the wrong driver. */
1391       }
1392 }
1393 
1394 
1395 static void finish_fdc_done( int dummy )
1396 {
1397     unsigned long flags;
1398 
1399     DPRINT(("finish_fdc_done entered\n"));
1400     stop_timeout();
1401     NeedSeek = 0;
1402 
1403     if (timer_pending(&fd_timer) && time_before(fd_timer.expires, jiffies + 5))
1404         /* If the check for a disk change is done too early after this
1405          * last seek command, the WP bit still reads wrong :-((
1406          */
1407         mod_timer(&fd_timer, jiffies + 5);
1408     else
1409         start_check_change_timer();
1410     start_motor_off_timer();
1411 
1412     local_irq_save(flags);
1413     if (stdma_is_locked_by(floppy_irq))
1414         stdma_release();
1415     local_irq_restore(flags);
1416 
1417     DPRINT(("finish_fdc() finished\n"));
1418 }
1419 
1420 /* The detection of disk changes is a dark chapter in Atari history :-(
1421  * Because the "Drive ready" signal isn't present in the Atari
1422  * hardware, one has to rely on the "Write Protect". This works fine,
1423  * as long as no write protected disks are used. TOS solves this
1424  * problem by introducing tri-state logic ("maybe changed") and
1425  * looking at the serial number in block 0. This isn't possible for
1426  * Linux, since the floppy driver can't make assumptions about the
1427  * filesystem used on the disk and thus the contents of block 0. I've
1428  * chosen the method to always say "The disk was changed" if it is
1429  * unsure whether it was. This implies that every open or mount
1430  * invalidates the disk buffers if you work with write protected
1431  * disks. But at least this is better than working with incorrect data
1432  * due to unrecognised disk changes.
1433  */
1434 
1435 static unsigned int floppy_check_events(struct gendisk *disk,
1436                     unsigned int clearing)
1437 {
1438     struct atari_floppy_struct *p = disk->private_data;
1439     unsigned int drive = p - unit;
1440     if (test_bit (drive, &fake_change)) {
1441         /* simulated change (e.g. after formatting) */
1442         return DISK_EVENT_MEDIA_CHANGE;
1443     }
1444     if (test_bit (drive, &changed_floppies)) {
1445         /* surely changed (the WP signal changed at least once) */
1446         return DISK_EVENT_MEDIA_CHANGE;
1447     }
1448     if (UD.wpstat) {
1449         /* WP is on -> could be changed: to be sure, buffers should be
1450          * invalidated...
1451          */
1452         return DISK_EVENT_MEDIA_CHANGE;
1453     }
1454 
1455     return 0;
1456 }
1457 
1458 static int floppy_revalidate(struct gendisk *disk)
1459 {
1460     struct atari_floppy_struct *p = disk->private_data;
1461     unsigned int drive = p - unit;
1462 
1463     if (test_bit(drive, &changed_floppies) ||
1464         test_bit(drive, &fake_change) || !p->disktype) {
1465         if (UD.flags & FTD_MSG)
1466             printk(KERN_ERR "floppy: clear format %p!\n", UDT);
1467         BufferDrive = -1;
1468         clear_bit(drive, &fake_change);
1469         clear_bit(drive, &changed_floppies);
1470         /* MSch: clearing geometry makes sense only for autoprobe
1471            formats, for 'permanent user-defined' parameter:
1472            restore default_params[] here if flagged valid! */
1473         if (default_params[drive].blocks == 0)
1474             UDT = NULL;
1475         else
1476             UDT = &default_params[drive];
1477     }
1478     return 0;
1479 }
1480 
1481 
1482 /* This sets up the global variables describing the current request. */
1483 
1484 static void setup_req_params( int drive )
1485 {
1486     int block = ReqBlock + ReqCnt;
1487 
1488     ReqTrack = block / UDT->spt;
1489     ReqSector = block - ReqTrack * UDT->spt + 1;
1490     ReqSide = ReqTrack & 1;
1491     ReqTrack >>= 1;
1492     ReqData = ReqBuffer + 512 * ReqCnt;
1493 
1494     if (UseTrackbuffer)
1495         read_track = (ReqCmd == READ && unit[drive].error_count == 0);
1496     else
1497         read_track = 0;
1498 
1499     DPRINT(("Request params: Si=%d Tr=%d Se=%d Data=%08lx\n",ReqSide,
1500             ReqTrack, ReqSector, (unsigned long)ReqData ));
1501 }
1502 
1503 static blk_status_t ataflop_queue_rq(struct blk_mq_hw_ctx *hctx,
1504                      const struct blk_mq_queue_data *bd)
1505 {
1506     struct atari_floppy_struct *floppy = bd->rq->q->disk->private_data;
1507     int drive = floppy - unit;
1508     int type = floppy->type;
1509 
1510     DPRINT(("Queue request: drive %d type %d sectors %d of %d last %d\n",
1511         drive, type, blk_rq_cur_sectors(bd->rq),
1512         blk_rq_sectors(bd->rq), bd->last));
1513 
1514     spin_lock_irq(&ataflop_lock);
1515     if (fd_request) {
1516         spin_unlock_irq(&ataflop_lock);
1517         return BLK_STS_DEV_RESOURCE;
1518     }
1519     if (!stdma_try_lock(floppy_irq, NULL))  {
1520         spin_unlock_irq(&ataflop_lock);
1521         return BLK_STS_RESOURCE;
1522     }
1523     fd_request = bd->rq;
1524     unit[drive].error_count = 0;
1525     blk_mq_start_request(fd_request);
1526 
1527     atari_disable_irq( IRQ_MFP_FDC );
1528 
1529     IsFormatting = 0;
1530 
1531     if (!UD.connected) {
1532         /* drive not connected */
1533         printk(KERN_ERR "Unknown Device: fd%d\n", drive );
1534         fd_end_request_cur(BLK_STS_IOERR);
1535         stdma_release();
1536         goto out;
1537     }
1538         
1539     if (type == 0) {
1540         if (!UDT) {
1541             Probing = 1;
1542             UDT = atari_disk_type + StartDiskType[DriveType];
1543             set_capacity(bd->rq->q->disk, UDT->blocks);
1544             UD.autoprobe = 1;
1545         }
1546     } 
1547     else {
1548         /* user supplied disk type */
1549         if (--type >= NUM_DISK_MINORS) {
1550             printk(KERN_WARNING "fd%d: invalid disk format", drive );
1551             fd_end_request_cur(BLK_STS_IOERR);
1552             stdma_release();
1553             goto out;
1554         }
1555         if (minor2disktype[type].drive_types > DriveType)  {
1556             printk(KERN_WARNING "fd%d: unsupported disk format", drive );
1557             fd_end_request_cur(BLK_STS_IOERR);
1558             stdma_release();
1559             goto out;
1560         }
1561         type = minor2disktype[type].index;
1562         UDT = &atari_disk_type[type];
1563         set_capacity(bd->rq->q->disk, UDT->blocks);
1564         UD.autoprobe = 0;
1565     }
1566 
1567     /* stop deselect timer */
1568     del_timer( &motor_off_timer );
1569         
1570     ReqCnt = 0;
1571     ReqCmd = rq_data_dir(fd_request);
1572     ReqBlock = blk_rq_pos(fd_request);
1573     ReqBuffer = bio_data(fd_request->bio);
1574     setup_req_params( drive );
1575     do_fd_action( drive );
1576 
1577     atari_enable_irq( IRQ_MFP_FDC );
1578 
1579 out:
1580     spin_unlock_irq(&ataflop_lock);
1581     return BLK_STS_OK;
1582 }
1583 
1584 static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode,
1585             unsigned int cmd, unsigned long param)
1586 {
1587     struct gendisk *disk = bdev->bd_disk;
1588     struct atari_floppy_struct *floppy = disk->private_data;
1589     int drive = floppy - unit;
1590     int type = floppy->type;
1591     struct atari_format_descr fmt_desc;
1592     struct atari_disk_type *dtp;
1593     struct floppy_struct getprm;
1594     int settype;
1595     struct floppy_struct setprm;
1596     void __user *argp = (void __user *)param;
1597 
1598     switch (cmd) {
1599     case FDGETPRM:
1600         if (type) {
1601             if (--type >= NUM_DISK_MINORS)
1602                 return -ENODEV;
1603             if (minor2disktype[type].drive_types > DriveType)
1604                 return -ENODEV;
1605             type = minor2disktype[type].index;
1606             dtp = &atari_disk_type[type];
1607             if (UD.flags & FTD_MSG)
1608                 printk (KERN_ERR "floppy%d: found dtp %p name %s!\n",
1609                     drive, dtp, dtp->name);
1610         }
1611         else {
1612             if (!UDT)
1613                 return -ENXIO;
1614             else
1615                 dtp = UDT;
1616         }
1617         memset((void *)&getprm, 0, sizeof(getprm));
1618         getprm.size = dtp->blocks;
1619         getprm.sect = dtp->spt;
1620         getprm.head = 2;
1621         getprm.track = dtp->blocks/dtp->spt/2;
1622         getprm.stretch = dtp->stretch;
1623         if (copy_to_user(argp, &getprm, sizeof(getprm)))
1624             return -EFAULT;
1625         return 0;
1626     }
1627     switch (cmd) {
1628     case FDSETPRM:
1629     case FDDEFPRM:
1630             /* 
1631          * MSch 7/96: simple 'set geometry' case: just set the
1632          * 'default' device params (minor == 0).
1633          * Currently, the drive geometry is cleared after each
1634          * disk change and subsequent revalidate()! simple
1635          * implementation of FDDEFPRM: save geometry from a
1636          * FDDEFPRM call and restore it in floppy_revalidate() !
1637          */
1638 
1639         /* get the parameters from user space */
1640         if (floppy->ref != 1 && floppy->ref != -1)
1641             return -EBUSY;
1642         if (copy_from_user(&setprm, argp, sizeof(setprm)))
1643             return -EFAULT;
1644         /* 
1645          * first of all: check for floppy change and revalidate, 
1646          * or the next access will revalidate - and clear UDT :-(
1647          */
1648 
1649         if (floppy_check_events(disk, 0))
1650                 floppy_revalidate(disk);
1651 
1652         if (UD.flags & FTD_MSG)
1653             printk (KERN_INFO "floppy%d: setting size %d spt %d str %d!\n",
1654             drive, setprm.size, setprm.sect, setprm.stretch);
1655 
1656         /* what if type > 0 here? Overwrite specified entry ? */
1657         if (type) {
1658                 /* refuse to re-set a predefined type for now */
1659             finish_fdc();
1660             return -EINVAL;
1661         }
1662 
1663         /* 
1664          * type == 0: first look for a matching entry in the type list,
1665          * and set the UD.disktype field to use the perdefined entry.
1666          * TODO: add user-defined format to head of autoprobe list ? 
1667          * Useful to include the user-type for future autodetection!
1668          */
1669 
1670         for (settype = 0; settype < NUM_DISK_MINORS; settype++) {
1671             int setidx = 0;
1672             if (minor2disktype[settype].drive_types > DriveType) {
1673                 /* skip this one, invalid for drive ... */
1674                 continue;
1675             }
1676             setidx = minor2disktype[settype].index;
1677             dtp = &atari_disk_type[setidx];
1678 
1679             /* found matching entry ?? */
1680             if (   dtp->blocks  == setprm.size 
1681                 && dtp->spt     == setprm.sect
1682                 && dtp->stretch == setprm.stretch ) {
1683                 if (UD.flags & FTD_MSG)
1684                     printk (KERN_INFO "floppy%d: setting %s %p!\n",
1685                         drive, dtp->name, dtp);
1686                 UDT = dtp;
1687                 set_capacity(disk, UDT->blocks);
1688 
1689                 if (cmd == FDDEFPRM) {
1690                   /* save settings as permanent default type */
1691                   default_params[drive].name    = dtp->name;
1692                   default_params[drive].spt     = dtp->spt;
1693                   default_params[drive].blocks  = dtp->blocks;
1694                   default_params[drive].fdc_speed = dtp->fdc_speed;
1695                   default_params[drive].stretch = dtp->stretch;
1696                 }
1697                 
1698                 return 0;
1699             }
1700 
1701         }
1702 
1703         /* no matching disk type found above - setting user_params */
1704 
1705             if (cmd == FDDEFPRM) {
1706             /* set permanent type */
1707             dtp = &default_params[drive];
1708         } else
1709             /* set user type (reset by disk change!) */
1710             dtp = &user_params[drive];
1711 
1712         dtp->name   = "user format";
1713         dtp->blocks = setprm.size;
1714         dtp->spt    = setprm.sect;
1715         if (setprm.sect > 14) 
1716             dtp->fdc_speed = 3;
1717         else
1718             dtp->fdc_speed = 0;
1719         dtp->stretch = setprm.stretch;
1720 
1721         if (UD.flags & FTD_MSG)
1722             printk (KERN_INFO "floppy%d: blk %d spt %d str %d!\n",
1723                 drive, dtp->blocks, dtp->spt, dtp->stretch);
1724 
1725         /* sanity check */
1726         if (setprm.track != dtp->blocks/dtp->spt/2 ||
1727             setprm.head != 2) {
1728             finish_fdc();
1729             return -EINVAL;
1730         }
1731 
1732         UDT = dtp;
1733         set_capacity(disk, UDT->blocks);
1734 
1735         return 0;
1736     case FDMSGON:
1737         UD.flags |= FTD_MSG;
1738         return 0;
1739     case FDMSGOFF:
1740         UD.flags &= ~FTD_MSG;
1741         return 0;
1742     case FDSETEMSGTRESH:
1743         return -EINVAL;
1744     case FDFMTBEG:
1745         return 0;
1746     case FDFMTTRK:
1747         if (floppy->ref != 1 && floppy->ref != -1)
1748             return -EBUSY;
1749         if (copy_from_user(&fmt_desc, argp, sizeof(fmt_desc)))
1750             return -EFAULT;
1751         return do_format(drive, type, &fmt_desc);
1752     case FDCLRPRM:
1753         UDT = NULL;
1754         /* MSch: invalidate default_params */
1755         default_params[drive].blocks  = 0;
1756         set_capacity(disk, MAX_DISK_SIZE * 2);
1757         fallthrough;
1758     case FDFMTEND:
1759     case FDFLUSH:
1760         /* invalidate the buffer track to force a reread */
1761         BufferDrive = -1;
1762         set_bit(drive, &fake_change);
1763         if (bdev_check_media_change(bdev))
1764             floppy_revalidate(bdev->bd_disk);
1765         return 0;
1766     default:
1767         return -EINVAL;
1768     }
1769 }
1770 
1771 static int fd_ioctl(struct block_device *bdev, fmode_t mode,
1772                  unsigned int cmd, unsigned long arg)
1773 {
1774     int ret;
1775 
1776     mutex_lock(&ataflop_mutex);
1777     ret = fd_locked_ioctl(bdev, mode, cmd, arg);
1778     mutex_unlock(&ataflop_mutex);
1779 
1780     return ret;
1781 }
1782 
1783 /* Initialize the 'unit' variable for drive 'drive' */
1784 
1785 static void __init fd_probe( int drive )
1786 {
1787     UD.connected = 0;
1788     UDT  = NULL;
1789 
1790     if (!fd_test_drive_present( drive ))
1791         return;
1792 
1793     UD.connected = 1;
1794     UD.track     = 0;
1795     switch( UserSteprate[drive] ) {
1796     case 2:
1797         UD.steprate = FDCSTEP_2;
1798         break;
1799     case 3:
1800         UD.steprate = FDCSTEP_3;
1801         break;
1802     case 6:
1803         UD.steprate = FDCSTEP_6;
1804         break;
1805     case 12:
1806         UD.steprate = FDCSTEP_12;
1807         break;
1808     default: /* should be -1 for "not set by user" */
1809         if (ATARIHW_PRESENT( FDCSPEED ) || MACH_IS_MEDUSA)
1810             UD.steprate = FDCSTEP_3;
1811         else
1812             UD.steprate = FDCSTEP_6;
1813         break;
1814     }
1815     MotorOn = 1;    /* from probe restore operation! */
1816 }
1817 
1818 
1819 /* This function tests the physical presence of a floppy drive (not
1820  * whether a disk is inserted). This is done by issuing a restore
1821  * command, waiting max. 2 seconds (that should be enough to move the
1822  * head across the whole disk) and looking at the state of the "TR00"
1823  * signal. This should now be raised if there is a drive connected
1824  * (and there is no hardware failure :-) Otherwise, the drive is
1825  * declared absent.
1826  */
1827 
1828 static int __init fd_test_drive_present( int drive )
1829 {
1830     unsigned long timeout;
1831     unsigned char status;
1832     int ok;
1833     
1834     if (drive >= (MACH_IS_FALCON ? 1 : 2)) return( 0 );
1835     fd_select_drive( drive );
1836 
1837     /* disable interrupt temporarily */
1838     atari_turnoff_irq( IRQ_MFP_FDC );
1839     FDC_WRITE (FDCREG_TRACK, 0xff00);
1840     FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | FDCCMDADD_H | FDCSTEP_6 );
1841 
1842     timeout = jiffies + 2*HZ+HZ/2;
1843     while (time_before(jiffies, timeout))
1844         if (!(st_mfp.par_dt_reg & 0x20))
1845             break;
1846 
1847     status = FDC_READ( FDCREG_STATUS );
1848     ok = (status & FDCSTAT_TR00) != 0;
1849 
1850     /* force interrupt to abort restore operation (FDC would try
1851      * about 50 seconds!) */
1852     FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1853     udelay(500);
1854     status = FDC_READ( FDCREG_STATUS );
1855     udelay(20);
1856 
1857     if (ok) {
1858         /* dummy seek command to make WP bit accessible */
1859         FDC_WRITE( FDCREG_DATA, 0 );
1860         FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK );
1861         while( st_mfp.par_dt_reg & 0x20 )
1862             ;
1863         status = FDC_READ( FDCREG_STATUS );
1864     }
1865 
1866     atari_turnon_irq( IRQ_MFP_FDC );
1867     return( ok );
1868 }
1869 
1870 
1871 /* Look how many and which kind of drives are connected. If there are
1872  * floppies, additionally start the disk-change and motor-off timers.
1873  */
1874 
1875 static void __init config_types( void )
1876 {
1877     int drive, cnt = 0;
1878 
1879     /* for probing drives, set the FDC speed to 8 MHz */
1880     if (ATARIHW_PRESENT(FDCSPEED))
1881         dma_wd.fdc_speed = 0;
1882 
1883     printk(KERN_INFO "Probing floppy drive(s):\n");
1884     for( drive = 0; drive < FD_MAX_UNITS; drive++ ) {
1885         fd_probe( drive );
1886         if (UD.connected) {
1887             printk(KERN_INFO "fd%d\n", drive);
1888             ++cnt;
1889         }
1890     }
1891 
1892     if (FDC_READ( FDCREG_STATUS ) & FDCSTAT_BUSY) {
1893         /* If FDC is still busy from probing, give it another FORCI
1894          * command to abort the operation. If this isn't done, the FDC
1895          * will interrupt later and its IRQ line stays low, because
1896          * the status register isn't read. And this will block any
1897          * interrupts on this IRQ line :-(
1898          */
1899         FDC_WRITE( FDCREG_CMD, FDCCMD_FORCI );
1900         udelay(500);
1901         FDC_READ( FDCREG_STATUS );
1902         udelay(20);
1903     }
1904     
1905     if (cnt > 0) {
1906         start_motor_off_timer();
1907         if (cnt == 1) fd_select_drive( 0 );
1908         start_check_change_timer();
1909     }
1910 }
1911 
1912 /*
1913  * floppy_open check for aliasing (/dev/fd0 can be the same as
1914  * /dev/PS0 etc), and disallows simultaneous access to the same
1915  * drive with different device numbers.
1916  */
1917 
1918 static int floppy_open(struct block_device *bdev, fmode_t mode)
1919 {
1920     struct atari_floppy_struct *p = bdev->bd_disk->private_data;
1921     int type  = MINOR(bdev->bd_dev) >> 2;
1922 
1923     DPRINT(("fd_open: type=%d\n",type));
1924     if (p->ref && p->type != type)
1925         return -EBUSY;
1926 
1927     if (p->ref == -1 || (p->ref && mode & FMODE_EXCL))
1928         return -EBUSY;
1929 
1930     if (mode & FMODE_EXCL)
1931         p->ref = -1;
1932     else
1933         p->ref++;
1934 
1935     p->type = type;
1936 
1937     if (mode & FMODE_NDELAY)
1938         return 0;
1939 
1940     if (mode & (FMODE_READ|FMODE_WRITE)) {
1941         if (bdev_check_media_change(bdev))
1942             floppy_revalidate(bdev->bd_disk);
1943         if (mode & FMODE_WRITE) {
1944             if (p->wpstat) {
1945                 if (p->ref < 0)
1946                     p->ref = 0;
1947                 else
1948                     p->ref--;
1949                 return -EROFS;
1950             }
1951         }
1952     }
1953     return 0;
1954 }
1955 
1956 static int floppy_unlocked_open(struct block_device *bdev, fmode_t mode)
1957 {
1958     int ret;
1959 
1960     mutex_lock(&ataflop_mutex);
1961     ret = floppy_open(bdev, mode);
1962     mutex_unlock(&ataflop_mutex);
1963 
1964     return ret;
1965 }
1966 
1967 static void floppy_release(struct gendisk *disk, fmode_t mode)
1968 {
1969     struct atari_floppy_struct *p = disk->private_data;
1970     mutex_lock(&ataflop_mutex);
1971     if (p->ref < 0)
1972         p->ref = 0;
1973     else if (!p->ref--) {
1974         printk(KERN_ERR "floppy_release with fd_ref == 0");
1975         p->ref = 0;
1976     }
1977     mutex_unlock(&ataflop_mutex);
1978 }
1979 
1980 static const struct block_device_operations floppy_fops = {
1981     .owner      = THIS_MODULE,
1982     .open       = floppy_unlocked_open,
1983     .release    = floppy_release,
1984     .ioctl      = fd_ioctl,
1985     .check_events   = floppy_check_events,
1986 };
1987 
1988 static const struct blk_mq_ops ataflop_mq_ops = {
1989     .queue_rq = ataflop_queue_rq,
1990 };
1991 
1992 static int ataflop_alloc_disk(unsigned int drive, unsigned int type)
1993 {
1994     struct gendisk *disk;
1995 
1996     disk = blk_mq_alloc_disk(&unit[drive].tag_set, NULL);
1997     if (IS_ERR(disk))
1998         return PTR_ERR(disk);
1999 
2000     disk->major = FLOPPY_MAJOR;
2001     disk->first_minor = drive + (type << 2);
2002     disk->minors = 1;
2003     sprintf(disk->disk_name, "fd%d", drive);
2004     disk->fops = &floppy_fops;
2005     disk->flags |= GENHD_FL_NO_PART;
2006     disk->events = DISK_EVENT_MEDIA_CHANGE;
2007     disk->private_data = &unit[drive];
2008     set_capacity(disk, MAX_DISK_SIZE * 2);
2009 
2010     unit[drive].disk[type] = disk;
2011     return 0;
2012 }
2013 
2014 static void ataflop_probe(dev_t dev)
2015 {
2016     int drive = MINOR(dev) & 3;
2017     int type  = MINOR(dev) >> 2;
2018 
2019     if (type)
2020         type--;
2021 
2022     if (drive >= FD_MAX_UNITS || type >= NUM_DISK_MINORS)
2023         return;
2024     if (unit[drive].disk[type])
2025         return;
2026     if (ataflop_alloc_disk(drive, type))
2027         return;
2028     if (add_disk(unit[drive].disk[type]))
2029         goto cleanup_disk;
2030     unit[drive].registered[type] = true;
2031     return;
2032 
2033 cleanup_disk:
2034     put_disk(unit[drive].disk[type]);
2035     unit[drive].disk[type] = NULL;
2036 }
2037 
2038 static void atari_floppy_cleanup(void)
2039 {
2040     int i;
2041     int type;
2042 
2043     for (i = 0; i < FD_MAX_UNITS; i++) {
2044         for (type = 0; type < NUM_DISK_MINORS; type++) {
2045             if (!unit[i].disk[type])
2046                 continue;
2047             del_gendisk(unit[i].disk[type]);
2048             put_disk(unit[i].disk[type]);
2049         }
2050         blk_mq_free_tag_set(&unit[i].tag_set);
2051     }
2052 
2053     del_timer_sync(&fd_timer);
2054     atari_stram_free(DMABuffer);
2055 }
2056 
2057 static void atari_cleanup_floppy_disk(struct atari_floppy_struct *fs)
2058 {
2059     int type;
2060 
2061     for (type = 0; type < NUM_DISK_MINORS; type++) {
2062         if (!fs->disk[type])
2063             continue;
2064         if (fs->registered[type])
2065             del_gendisk(fs->disk[type]);
2066         put_disk(fs->disk[type]);
2067     }
2068     blk_mq_free_tag_set(&fs->tag_set);
2069 }
2070 
2071 static int __init atari_floppy_init (void)
2072 {
2073     int i;
2074     int ret;
2075 
2076     if (!MACH_IS_ATARI)
2077         /* Amiga, Mac, ... don't have Atari-compatible floppy :-) */
2078         return -ENODEV;
2079 
2080     for (i = 0; i < FD_MAX_UNITS; i++) {
2081         memset(&unit[i].tag_set, 0, sizeof(unit[i].tag_set));
2082         unit[i].tag_set.ops = &ataflop_mq_ops;
2083         unit[i].tag_set.nr_hw_queues = 1;
2084         unit[i].tag_set.nr_maps = 1;
2085         unit[i].tag_set.queue_depth = 2;
2086         unit[i].tag_set.numa_node = NUMA_NO_NODE;
2087         unit[i].tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2088         ret = blk_mq_alloc_tag_set(&unit[i].tag_set);
2089         if (ret)
2090             goto err;
2091 
2092         ret = ataflop_alloc_disk(i, 0);
2093         if (ret) {
2094             blk_mq_free_tag_set(&unit[i].tag_set);
2095             goto err;
2096         }
2097     }
2098 
2099     if (UseTrackbuffer < 0)
2100         /* not set by user -> use default: for now, we turn
2101            track buffering off for all Medusas, though it
2102            could be used with ones that have a counter
2103            card. But the test is too hard :-( */
2104         UseTrackbuffer = !MACH_IS_MEDUSA;
2105 
2106     /* initialize variables */
2107     SelectedDrive = -1;
2108     BufferDrive = -1;
2109 
2110     DMABuffer = atari_stram_alloc(BUFFER_SIZE+512, "ataflop");
2111     if (!DMABuffer) {
2112         printk(KERN_ERR "atari_floppy_init: cannot get dma buffer\n");
2113         ret = -ENOMEM;
2114         goto err;
2115     }
2116     TrackBuffer = DMABuffer + 512;
2117     PhysDMABuffer = atari_stram_to_phys(DMABuffer);
2118     PhysTrackBuffer = virt_to_phys(TrackBuffer);
2119     BufferDrive = BufferSide = BufferTrack = -1;
2120 
2121     for (i = 0; i < FD_MAX_UNITS; i++) {
2122         unit[i].track = -1;
2123         unit[i].flags = 0;
2124         ret = add_disk(unit[i].disk[0]);
2125         if (ret)
2126             goto err_out_dma;
2127         unit[i].registered[0] = true;
2128     }
2129 
2130     printk(KERN_INFO "Atari floppy driver: max. %cD, %strack buffering\n",
2131            DriveType == 0 ? 'D' : DriveType == 1 ? 'H' : 'E',
2132            UseTrackbuffer ? "" : "no ");
2133     config_types();
2134 
2135     ret = __register_blkdev(FLOPPY_MAJOR, "fd", ataflop_probe);
2136     if (ret) {
2137         printk(KERN_ERR "atari_floppy_init: cannot register block device\n");
2138         atari_floppy_cleanup();
2139     }
2140     return ret;
2141 
2142 err_out_dma:
2143     atari_stram_free(DMABuffer);
2144 err:
2145     while (--i >= 0)
2146         atari_cleanup_floppy_disk(&unit[i]);
2147 
2148     return ret;
2149 }
2150 
2151 #ifndef MODULE
2152 static int __init atari_floppy_setup(char *str)
2153 {
2154     int ints[3 + FD_MAX_UNITS];
2155     int i;
2156 
2157     if (!MACH_IS_ATARI)
2158         return 0;
2159 
2160     str = get_options(str, 3 + FD_MAX_UNITS, ints);
2161     
2162     if (ints[0] < 1) {
2163         printk(KERN_ERR "ataflop_setup: no arguments!\n" );
2164         return 0;
2165     }
2166     else if (ints[0] > 2+FD_MAX_UNITS) {
2167         printk(KERN_ERR "ataflop_setup: too many arguments\n" );
2168     }
2169 
2170     if (ints[1] < 0 || ints[1] > 2)
2171         printk(KERN_ERR "ataflop_setup: bad drive type\n" );
2172     else
2173         DriveType = ints[1];
2174 
2175     if (ints[0] >= 2)
2176         UseTrackbuffer = (ints[2] > 0);
2177 
2178     for( i = 3; i <= ints[0] && i-3 < FD_MAX_UNITS; ++i ) {
2179         if (ints[i] != 2 && ints[i] != 3 && ints[i] != 6 && ints[i] != 12)
2180             printk(KERN_ERR "ataflop_setup: bad steprate\n" );
2181         else
2182             UserSteprate[i-3] = ints[i];
2183     }
2184     return 1;
2185 }
2186 
2187 __setup("floppy=", atari_floppy_setup);
2188 #endif
2189 
2190 static void __exit atari_floppy_exit(void)
2191 {
2192     unregister_blkdev(FLOPPY_MAJOR, "fd");
2193     atari_floppy_cleanup();
2194 }
2195 
2196 module_init(atari_floppy_init)
2197 module_exit(atari_floppy_exit)
2198 
2199 MODULE_LICENSE("GPL");