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