xref: /openbmc/linux/drivers/block/ataflop.c (revision 05bdb996)
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/major.h>
72 #include <linux/mutex.h>
73 #include <linux/completion.h>
74 #include <linux/wait.h>
75 
76 #include <asm/atariints.h>
77 #include <asm/atari_stdma.h>
78 #include <asm/atari_stram.h>
79 
80 #define	FD_MAX_UNITS 2
81 
82 #undef DEBUG
83 
84 static DEFINE_MUTEX(ataflop_mutex);
85 static struct request *fd_request;
86 
87 /*
88  * WD1772 stuff
89  */
90 
91 /* register codes */
92 
93 #define FDCSELREG_STP   (0x80)   /* command/status register */
94 #define FDCSELREG_TRA   (0x82)   /* track register */
95 #define FDCSELREG_SEC   (0x84)   /* sector register */
96 #define FDCSELREG_DTA   (0x86)   /* data register */
97 
98 /* register names for FDC_READ/WRITE macros */
99 
100 #define FDCREG_CMD		0
101 #define FDCREG_STATUS	0
102 #define FDCREG_TRACK	2
103 #define FDCREG_SECTOR	4
104 #define FDCREG_DATA		6
105 
106 /* command opcodes */
107 
108 #define FDCCMD_RESTORE  (0x00)   /*  -                   */
109 #define FDCCMD_SEEK     (0x10)   /*   |                  */
110 #define FDCCMD_STEP     (0x20)   /*   |  TYP 1 Commands  */
111 #define FDCCMD_STIN     (0x40)   /*   |                  */
112 #define FDCCMD_STOT     (0x60)   /*  -                   */
113 #define FDCCMD_RDSEC    (0x80)   /*  -   TYP 2 Commands  */
114 #define FDCCMD_WRSEC    (0xa0)   /*  -          "        */
115 #define FDCCMD_RDADR    (0xc0)   /*  -                   */
116 #define FDCCMD_RDTRA    (0xe0)   /*   |  TYP 3 Commands  */
117 #define FDCCMD_WRTRA    (0xf0)   /*  -                   */
118 #define FDCCMD_FORCI    (0xd0)   /*  -   TYP 4 Command   */
119 
120 /* command modifier bits */
121 
122 #define FDCCMDADD_SR6   (0x00)   /* step rate settings */
123 #define FDCCMDADD_SR12  (0x01)
124 #define FDCCMDADD_SR2   (0x02)
125 #define FDCCMDADD_SR3   (0x03)
126 #define FDCCMDADD_V     (0x04)   /* verify */
127 #define FDCCMDADD_H     (0x08)   /* wait for spin-up */
128 #define FDCCMDADD_U     (0x10)   /* update track register */
129 #define FDCCMDADD_M     (0x10)   /* multiple sector access */
130 #define FDCCMDADD_E     (0x04)   /* head settling flag */
131 #define FDCCMDADD_P     (0x02)   /* precompensation off */
132 #define FDCCMDADD_A0    (0x01)   /* DAM flag */
133 
134 /* status register bits */
135 
136 #define	FDCSTAT_MOTORON	(0x80)   /* motor on */
137 #define	FDCSTAT_WPROT	(0x40)   /* write protected (FDCCMD_WR*) */
138 #define	FDCSTAT_SPINUP	(0x20)   /* motor speed stable (Type I) */
139 #define	FDCSTAT_DELDAM	(0x20)   /* sector has deleted DAM (Type II+III) */
140 #define	FDCSTAT_RECNF	(0x10)   /* record not found */
141 #define	FDCSTAT_CRC		(0x08)   /* CRC error */
142 #define	FDCSTAT_TR00	(0x04)   /* Track 00 flag (Type I) */
143 #define	FDCSTAT_LOST	(0x04)   /* Lost Data (Type II+III) */
144 #define	FDCSTAT_IDX		(0x02)   /* Index status (Type I) */
145 #define	FDCSTAT_DRQ		(0x02)   /* DRQ status (Type II+III) */
146 #define	FDCSTAT_BUSY	(0x01)   /* FDC is busy */
147 
148 
149 /* PSG Port A Bit Nr 0 .. Side Sel .. 0 -> Side 1  1 -> Side 2 */
150 #define DSKSIDE     (0x01)
151 
152 #define DSKDRVNONE  (0x06)
153 #define DSKDRV0     (0x02)
154 #define DSKDRV1     (0x04)
155 
156 /* step rates */
157 #define	FDCSTEP_6	0x00
158 #define	FDCSTEP_12	0x01
159 #define	FDCSTEP_2	0x02
160 #define	FDCSTEP_3	0x03
161 
162 struct atari_format_descr {
163 	int track;		/* to be formatted */
164 	int head;		/*   ""     ""     */
165 	int sect_offset;	/* offset of first sector */
166 };
167 
168 /* Disk types: DD, HD, ED */
169 static struct atari_disk_type {
170 	const char	*name;
171 	unsigned	spt;		/* sectors per track */
172 	unsigned	blocks;		/* total number of blocks */
173 	unsigned	fdc_speed;	/* fdc_speed setting */
174 	unsigned 	stretch;	/* track doubling ? */
175 } atari_disk_type[] = {
176 	{ "d360",  9, 720, 0, 0},	/*  0: 360kB diskette */
177 	{ "D360",  9, 720, 0, 1},	/*  1: 360kb in 720k or 1.2MB drive */
178 	{ "D720",  9,1440, 0, 0},	/*  2: 720kb in 720k or 1.2MB drive */
179 	{ "D820", 10,1640, 0, 0},	/*  3: DD disk with 82 tracks/10 sectors */
180 /* formats above are probed for type DD */
181 #define	MAX_TYPE_DD 3
182 	{ "h1200",15,2400, 3, 0},	/*  4: 1.2MB diskette */
183 	{ "H1440",18,2880, 3, 0},	/*  5: 1.4 MB diskette (HD) */
184 	{ "H1640",20,3280, 3, 0},	/*  6: 1.64MB diskette (fat HD) 82 tr 20 sec */
185 /* formats above are probed for types DD and HD */
186 #define	MAX_TYPE_HD 6
187 	{ "E2880",36,5760, 3, 0},	/*  7: 2.8 MB diskette (ED) */
188 	{ "E3280",40,6560, 3, 0},	/*  8: 3.2 MB diskette (fat ED) 82 tr 40 sec */
189 /* formats above are probed for types DD, HD and ED */
190 #define	MAX_TYPE_ED 8
191 /* types below are never autoprobed */
192 	{ "H1680",21,3360, 3, 0},	/*  9: 1.68MB diskette (fat HD) 80 tr 21 sec */
193 	{ "h410",10,820, 0, 1},		/* 10: 410k diskette 41 tr 10 sec, stretch */
194 	{ "h1476",18,2952, 3, 0},	/* 11: 1.48MB diskette 82 tr 18 sec */
195 	{ "H1722",21,3444, 3, 0},	/* 12: 1.72MB diskette 82 tr 21 sec */
196 	{ "h420",10,840, 0, 1},		/* 13: 420k diskette 42 tr 10 sec, stretch */
197 	{ "H830",10,1660, 0, 0},	/* 14: 820k diskette 83 tr 10 sec */
198 	{ "h1494",18,2952, 3, 0},	/* 15: 1.49MB diskette 83 tr 18 sec */
199 	{ "H1743",21,3486, 3, 0},	/* 16: 1.74MB diskette 83 tr 21 sec */
200 	{ "h880",11,1760, 0, 0},	/* 17: 880k diskette 80 tr 11 sec */
201 	{ "D1040",13,2080, 0, 0},	/* 18: 1.04MB diskette 80 tr 13 sec */
202 	{ "D1120",14,2240, 0, 0},	/* 19: 1.12MB diskette 80 tr 14 sec */
203 	{ "h1600",20,3200, 3, 0},	/* 20: 1.60MB diskette 80 tr 20 sec */
204 	{ "H1760",22,3520, 3, 0},	/* 21: 1.76MB diskette 80 tr 22 sec */
205 	{ "H1920",24,3840, 3, 0},	/* 22: 1.92MB diskette 80 tr 24 sec */
206 	{ "E3200",40,6400, 3, 0},	/* 23: 3.2MB diskette 80 tr 40 sec */
207 	{ "E3520",44,7040, 3, 0},	/* 24: 3.52MB diskette 80 tr 44 sec */
208 	{ "E3840",48,7680, 3, 0},	/* 25: 3.84MB diskette 80 tr 48 sec */
209 	{ "H1840",23,3680, 3, 0},	/* 26: 1.84MB diskette 80 tr 23 sec */
210 	{ "D800",10,1600, 0, 0},	/* 27: 800k diskette 80 tr 10 sec */
211 };
212 
213 static int StartDiskType[] = {
214 	MAX_TYPE_DD,
215 	MAX_TYPE_HD,
216 	MAX_TYPE_ED
217 };
218 
219 #define	TYPE_DD		0
220 #define	TYPE_HD		1
221 #define	TYPE_ED		2
222 
223 static int DriveType = TYPE_HD;
224 
225 static DEFINE_SPINLOCK(ataflop_lock);
226 
227 /* Array for translating minors into disk formats */
228 static struct {
229 	int 	 index;
230 	unsigned drive_types;
231 } minor2disktype[] = {
232 	{  0, TYPE_DD },	/*  1: d360 */
233 	{  4, TYPE_HD },	/*  2: h1200 */
234 	{  1, TYPE_DD },	/*  3: D360 */
235 	{  2, TYPE_DD },	/*  4: D720 */
236 	{  1, TYPE_DD },	/*  5: h360 = D360 */
237 	{  2, TYPE_DD },	/*  6: h720 = D720 */
238 	{  5, TYPE_HD },	/*  7: H1440 */
239 	{  7, TYPE_ED },	/*  8: E2880 */
240 /* some PC formats :-) */
241 	{  8, TYPE_ED },	/*  9: E3280    <- was "CompaQ" == E2880 for PC */
242 	{  5, TYPE_HD },	/* 10: h1440 = H1440 */
243 	{  9, TYPE_HD },	/* 11: H1680 */
244 	{ 10, TYPE_DD },	/* 12: h410  */
245 	{  3, TYPE_DD },	/* 13: H820     <- == D820, 82x10 */
246 	{ 11, TYPE_HD },	/* 14: h1476 */
247 	{ 12, TYPE_HD },	/* 15: H1722 */
248 	{ 13, TYPE_DD },	/* 16: h420  */
249 	{ 14, TYPE_DD },	/* 17: H830  */
250 	{ 15, TYPE_HD },	/* 18: h1494 */
251 	{ 16, TYPE_HD },	/* 19: H1743 */
252 	{ 17, TYPE_DD },	/* 20: h880  */
253 	{ 18, TYPE_DD },	/* 21: D1040 */
254 	{ 19, TYPE_DD },	/* 22: D1120 */
255 	{ 20, TYPE_HD },	/* 23: h1600 */
256 	{ 21, TYPE_HD },	/* 24: H1760 */
257 	{ 22, TYPE_HD },	/* 25: H1920 */
258 	{ 23, TYPE_ED },	/* 26: E3200 */
259 	{ 24, TYPE_ED },	/* 27: E3520 */
260 	{ 25, TYPE_ED },	/* 28: E3840 */
261 	{ 26, TYPE_HD },	/* 29: H1840 */
262 	{ 27, TYPE_DD },	/* 30: D800  */
263 	{  6, TYPE_HD },	/* 31: H1640    <- was H1600 == h1600 for PC */
264 };
265 
266 #define NUM_DISK_MINORS ARRAY_SIZE(minor2disktype)
267 
268 /*
269  * Maximum disk size (in kilobytes). This default is used whenever the
270  * current disk size is unknown.
271  */
272 #define MAX_DISK_SIZE 3280
273 
274 /*
275  * MSch: User-provided type information. 'drive' points to
276  * the respective entry of this array. Set by FDSETPRM ioctls.
277  */
278 static struct atari_disk_type user_params[FD_MAX_UNITS];
279 
280 /*
281  * User-provided permanent type information. 'drive' points to
282  * the respective entry of this array.  Set by FDDEFPRM ioctls,
283  * restored upon disk change by floppy_revalidate() if valid (as seen by
284  * default_params[].blocks > 0 - a bit in unit[].flags might be used for this?)
285  */
286 static struct atari_disk_type default_params[FD_MAX_UNITS];
287 
288 /* current info on each unit */
289 static struct atari_floppy_struct {
290 	int connected;				/* !=0 : drive is connected */
291 	int autoprobe;				/* !=0 : do autoprobe	    */
292 
293 	struct atari_disk_type	*disktype;	/* current type of disk */
294 
295 	int track;		/* current head position or -1 if
296 				   unknown */
297 	unsigned int steprate;	/* steprate setting */
298 	unsigned int wpstat;	/* current state of WP signal (for
299 				   disk change detection) */
300 	int flags;		/* flags */
301 	struct gendisk *disk[NUM_DISK_MINORS];
302 	bool registered[NUM_DISK_MINORS];
303 	int ref;
304 	int type;
305 	struct blk_mq_tag_set tag_set;
306 	int error_count;
307 } unit[FD_MAX_UNITS];
308 
309 #define	UD	unit[drive]
310 #define	UDT	unit[drive].disktype
311 #define	SUD	unit[SelectedDrive]
312 #define	SUDT	unit[SelectedDrive].disktype
313 
314 
315 #define FDC_READ(reg) ({			\
316     /* unsigned long __flags; */		\
317     unsigned short __val;			\
318     /* local_irq_save(__flags); */		\
319     dma_wd.dma_mode_status = 0x80 | (reg);	\
320     udelay(25);					\
321     __val = dma_wd.fdc_acces_seccount;		\
322     MFPDELAY();					\
323     /* local_irq_restore(__flags); */		\
324     __val & 0xff;				\
325 })
326 
327 #define FDC_WRITE(reg,val)			\
328     do {					\
329 	/* unsigned long __flags; */		\
330 	/* local_irq_save(__flags); */		\
331 	dma_wd.dma_mode_status = 0x80 | (reg);	\
332 	udelay(25);				\
333 	dma_wd.fdc_acces_seccount = (val);	\
334 	MFPDELAY();				\
335         /* local_irq_restore(__flags); */	\
336     } while(0)
337 
338 
339 /* Buffering variables:
340  * First, there is a DMA buffer in ST-RAM that is used for floppy DMA
341  * operations. Second, a track buffer is used to cache a whole track
342  * of the disk to save read operations. These are two separate buffers
343  * because that allows write operations without clearing the track buffer.
344  */
345 
346 static int MaxSectors[] = {
347 	11, 22, 44
348 };
349 static int BufferSize[] = {
350 	15*512, 30*512, 60*512
351 };
352 
353 #define	BUFFER_SIZE	(BufferSize[DriveType])
354 
355 unsigned char *DMABuffer;			  /* buffer for writes */
356 static unsigned long PhysDMABuffer;   /* physical address */
357 
358 static int UseTrackbuffer = -1;		  /* Do track buffering? */
359 module_param(UseTrackbuffer, int, 0);
360 
361 unsigned char *TrackBuffer;			  /* buffer for reads */
362 static unsigned long PhysTrackBuffer; /* physical address */
363 static int BufferDrive, BufferSide, BufferTrack;
364 static int read_track;		/* non-zero if we are reading whole tracks */
365 
366 #define	SECTOR_BUFFER(sec)	(TrackBuffer + ((sec)-1)*512)
367 #define	IS_BUFFERED(drive,side,track) \
368     (BufferDrive == (drive) && BufferSide == (side) && BufferTrack == (track))
369 
370 /*
371  * These are global variables, as that's the easiest way to give
372  * information to interrupts. They are the data used for the current
373  * request.
374  */
375 static int SelectedDrive = 0;
376 static int ReqCmd, ReqBlock;
377 static int ReqSide, ReqTrack, ReqSector, ReqCnt;
378 static int HeadSettleFlag = 0;
379 static unsigned char *ReqData, *ReqBuffer;
380 static int MotorOn = 0, MotorOffTrys;
381 static int IsFormatting = 0, FormatError;
382 
383 static int UserSteprate[FD_MAX_UNITS] = { -1, -1 };
384 module_param_array(UserSteprate, int, NULL, 0);
385 
386 static DECLARE_COMPLETION(format_wait);
387 
388 static unsigned long changed_floppies = 0xff, fake_change = 0;
389 #define	CHECK_CHANGE_DELAY	HZ/2
390 
391 #define	FD_MOTOR_OFF_DELAY	(3*HZ)
392 #define	FD_MOTOR_OFF_MAXTRY	(10*20)
393 
394 #define FLOPPY_TIMEOUT		(6*HZ)
395 #define RECALIBRATE_ERRORS	4	/* After this many errors the drive
396 					 * will be recalibrated. */
397 #define MAX_ERRORS		8	/* After this many errors the driver
398 					 * will give up. */
399 
400 
401 /*
402  * The driver is trying to determine the correct media format
403  * while Probing is set. fd_rwsec_done() clears it after a
404  * successful access.
405  */
406 static int Probing = 0;
407 
408 /* This flag is set when a dummy seek is necessary to make the WP
409  * status bit accessible.
410  */
411 static int NeedSeek = 0;
412 
413 
414 #ifdef DEBUG
415 #define DPRINT(a)	printk a
416 #else
417 #define DPRINT(a)
418 #endif
419 
420 /***************************** Prototypes *****************************/
421 
422 static void fd_select_side( int side );
423 static void fd_select_drive( int drive );
424 static void fd_deselect( void );
425 static void fd_motor_off_timer(struct timer_list *unused);
426 static void check_change(struct timer_list *unused);
427 static irqreturn_t floppy_irq (int irq, void *dummy);
428 static void fd_error( void );
429 static int do_format(int drive, int type, struct atari_format_descr *desc);
430 static void do_fd_action( int drive );
431 static void fd_calibrate( void );
432 static void fd_calibrate_done( int status );
433 static void fd_seek( void );
434 static void fd_seek_done( int status );
435 static void fd_rwsec( void );
436 static void fd_readtrack_check(struct timer_list *unused);
437 static void fd_rwsec_done( int status );
438 static void fd_rwsec_done1(int status);
439 static void fd_writetrack( void );
440 static void fd_writetrack_done( int status );
441 static void fd_times_out(struct timer_list *unused);
442 static void finish_fdc( void );
443 static void finish_fdc_done( int dummy );
444 static void setup_req_params( int drive );
445 static int fd_locked_ioctl(struct block_device *bdev, blk_mode_t mode,
446 		unsigned int cmd, unsigned long param);
447 static void fd_probe( int drive );
448 static int fd_test_drive_present( int drive );
449 static void config_types( void );
450 static int floppy_open(struct gendisk *disk, blk_mode_t mode);
451 static void floppy_release(struct gendisk *disk);
452 
453 /************************* End of Prototypes **************************/
454 
455 static DEFINE_TIMER(motor_off_timer, fd_motor_off_timer);
456 static DEFINE_TIMER(readtrack_timer, fd_readtrack_check);
457 static DEFINE_TIMER(timeout_timer, fd_times_out);
458 static DEFINE_TIMER(fd_timer, check_change);
459 
fd_end_request_cur(blk_status_t err)460 static void fd_end_request_cur(blk_status_t err)
461 {
462 	DPRINT(("fd_end_request_cur(), bytes %d of %d\n",
463 		blk_rq_cur_bytes(fd_request),
464 		blk_rq_bytes(fd_request)));
465 
466 	if (!blk_update_request(fd_request, err,
467 				blk_rq_cur_bytes(fd_request))) {
468 		DPRINT(("calling __blk_mq_end_request()\n"));
469 		__blk_mq_end_request(fd_request, err);
470 		fd_request = NULL;
471 	} else {
472 		/* requeue rest of request */
473 		DPRINT(("calling blk_mq_requeue_request()\n"));
474 		blk_mq_requeue_request(fd_request, true);
475 		fd_request = NULL;
476 	}
477 }
478 
start_motor_off_timer(void)479 static inline void start_motor_off_timer(void)
480 {
481 	mod_timer(&motor_off_timer, jiffies + FD_MOTOR_OFF_DELAY);
482 	MotorOffTrys = 0;
483 }
484 
start_check_change_timer(void)485 static inline void start_check_change_timer( void )
486 {
487 	mod_timer(&fd_timer, jiffies + CHECK_CHANGE_DELAY);
488 }
489 
start_timeout(void)490 static inline void start_timeout(void)
491 {
492 	mod_timer(&timeout_timer, jiffies + FLOPPY_TIMEOUT);
493 }
494 
stop_timeout(void)495 static inline void stop_timeout(void)
496 {
497 	del_timer(&timeout_timer);
498 }
499 
500 /* Select the side to use. */
501 
fd_select_side(int side)502 static void fd_select_side( int side )
503 {
504 	unsigned long flags;
505 
506 	/* protect against various other ints mucking around with the PSG */
507 	local_irq_save(flags);
508 
509 	sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
510 	sound_ym.wd_data = (side == 0) ? sound_ym.rd_data_reg_sel | 0x01 :
511 	                                 sound_ym.rd_data_reg_sel & 0xfe;
512 
513 	local_irq_restore(flags);
514 }
515 
516 
517 /* Select a drive, update the FDC's track register and set the correct
518  * clock speed for this disk's type.
519  */
520 
fd_select_drive(int drive)521 static void fd_select_drive( int drive )
522 {
523 	unsigned long flags;
524 	unsigned char tmp;
525 
526 	if (drive == SelectedDrive)
527 	  return;
528 
529 	/* protect against various other ints mucking around with the PSG */
530 	local_irq_save(flags);
531 	sound_ym.rd_data_reg_sel = 14; /* Select PSG Port A */
532 	tmp = sound_ym.rd_data_reg_sel;
533 	sound_ym.wd_data = (tmp | DSKDRVNONE) & ~(drive == 0 ? DSKDRV0 : DSKDRV1);
534 	atari_dont_touch_floppy_select = 1;
535 	local_irq_restore(flags);
536 
537 	/* restore track register to saved value */
538 	FDC_WRITE( FDCREG_TRACK, UD.track );
539 	udelay(25);
540 
541 	/* select 8/16 MHz */
542 	if (UDT)
543 		if (ATARIHW_PRESENT(FDCSPEED))
544 			dma_wd.fdc_speed = UDT->fdc_speed;
545 
546 	SelectedDrive = drive;
547 }
548 
549 
550 /* Deselect both drives. */
551 
fd_deselect(void)552 static void fd_deselect( void )
553 {
554 	unsigned long flags;
555 
556 	/* protect against various other ints mucking around with the PSG */
557 	local_irq_save(flags);
558 	atari_dont_touch_floppy_select = 0;
559 	sound_ym.rd_data_reg_sel=14;	/* Select PSG Port A */
560 	sound_ym.wd_data = (sound_ym.rd_data_reg_sel |
561 			    (MACH_IS_FALCON ? 3 : 7)); /* no drives selected */
562 	/* On Falcon, the drive B select line is used on the printer port, so
563 	 * leave it alone... */
564 	SelectedDrive = -1;
565 	local_irq_restore(flags);
566 }
567 
568 
569 /* This timer function deselects the drives when the FDC switched the
570  * motor off. The deselection cannot happen earlier because the FDC
571  * counts the index signals, which arrive only if one drive is selected.
572  */
573 
fd_motor_off_timer(struct timer_list * unused)574 static void fd_motor_off_timer(struct timer_list *unused)
575 {
576 	unsigned char status;
577 
578 	if (SelectedDrive < 0)
579 		/* no drive selected, needn't deselect anyone */
580 		return;
581 
582 	if (stdma_islocked())
583 		goto retry;
584 
585 	status = FDC_READ( FDCREG_STATUS );
586 
587 	if (!(status & 0x80)) {
588 		/* motor already turned off by FDC -> deselect drives */
589 		MotorOn = 0;
590 		fd_deselect();
591 		return;
592 	}
593 	/* not yet off, try again */
594 
595   retry:
596 	/* Test again later; if tested too often, it seems there is no disk
597 	 * in the drive and the FDC will leave the motor on forever (or,
598 	 * at least until a disk is inserted). So we'll test only twice
599 	 * per second from then on...
600 	 */
601 	mod_timer(&motor_off_timer,
602 		  jiffies + (MotorOffTrys++ < FD_MOTOR_OFF_MAXTRY ? HZ/20 : HZ/2));
603 }
604 
605 
606 /* This function is repeatedly called to detect disk changes (as good
607  * as possible) and keep track of the current state of the write protection.
608  */
609 
check_change(struct timer_list * unused)610 static void check_change(struct timer_list *unused)
611 {
612 	static int    drive = 0;
613 
614 	unsigned long flags;
615 	unsigned char old_porta;
616 	int			  stat;
617 
618 	if (++drive > 1 || !UD.connected)
619 		drive = 0;
620 
621 	/* protect against various other ints mucking around with the PSG */
622 	local_irq_save(flags);
623 
624 	if (!stdma_islocked()) {
625 		sound_ym.rd_data_reg_sel = 14;
626 		old_porta = sound_ym.rd_data_reg_sel;
627 		sound_ym.wd_data = (old_porta | DSKDRVNONE) &
628 			               ~(drive == 0 ? DSKDRV0 : DSKDRV1);
629 		stat = !!(FDC_READ( FDCREG_STATUS ) & FDCSTAT_WPROT);
630 		sound_ym.wd_data = old_porta;
631 
632 		if (stat != UD.wpstat) {
633 			DPRINT(( "wpstat[%d] = %d\n", drive, stat ));
634 			UD.wpstat = stat;
635 			set_bit (drive, &changed_floppies);
636 		}
637 	}
638 	local_irq_restore(flags);
639 
640 	start_check_change_timer();
641 }
642 
643 
644 /* Handling of the Head Settling Flag: This flag should be set after each
645  * seek operation, because we don't use seeks with verify.
646  */
647 
set_head_settle_flag(void)648 static inline void set_head_settle_flag(void)
649 {
650 	HeadSettleFlag = FDCCMDADD_E;
651 }
652 
get_head_settle_flag(void)653 static inline int get_head_settle_flag(void)
654 {
655 	int	tmp = HeadSettleFlag;
656 	HeadSettleFlag = 0;
657 	return( tmp );
658 }
659 
copy_buffer(void * from,void * to)660 static inline void copy_buffer(void *from, void *to)
661 {
662 	ulong *p1 = (ulong *)from, *p2 = (ulong *)to;
663 	int cnt;
664 
665 	for (cnt = 512/4; cnt; cnt--)
666 		*p2++ = *p1++;
667 }
668 
669 /* General Interrupt Handling */
670 
671 static void (*FloppyIRQHandler)( int status ) = NULL;
672 
floppy_irq(int irq,void * dummy)673 static irqreturn_t floppy_irq (int irq, void *dummy)
674 {
675 	unsigned char status;
676 	void (*handler)( int );
677 
678 	handler = xchg(&FloppyIRQHandler, NULL);
679 
680 	if (handler) {
681 		nop();
682 		status = FDC_READ( FDCREG_STATUS );
683 		DPRINT(("FDC irq, status = %02x handler = %08lx\n",status,(unsigned long)handler));
684 		handler( status );
685 	}
686 	else {
687 		DPRINT(("FDC irq, no handler\n"));
688 	}
689 	return IRQ_HANDLED;
690 }
691 
692 
693 /* Error handling: If some error happened, retry some times, then
694  * recalibrate, then try again, and fail after MAX_ERRORS.
695  */
696 
fd_error(void)697 static void fd_error( void )
698 {
699 	if (IsFormatting) {
700 		IsFormatting = 0;
701 		FormatError = 1;
702 		complete(&format_wait);
703 		return;
704 	}
705 
706 	if (!fd_request)
707 		return;
708 
709 	unit[SelectedDrive].error_count++;
710 	if (unit[SelectedDrive].error_count >= MAX_ERRORS) {
711 		printk(KERN_ERR "fd%d: too many errors.\n", SelectedDrive );
712 		fd_end_request_cur(BLK_STS_IOERR);
713 		finish_fdc();
714 		return;
715 	}
716 	else if (unit[SelectedDrive].error_count == RECALIBRATE_ERRORS) {
717 		printk(KERN_WARNING "fd%d: recalibrating\n", SelectedDrive );
718 		if (SelectedDrive != -1)
719 			SUD.track = -1;
720 	}
721 	/* need to re-run request to recalibrate */
722 	atari_disable_irq( IRQ_MFP_FDC );
723 
724 	setup_req_params( SelectedDrive );
725 	do_fd_action( SelectedDrive );
726 
727 	atari_enable_irq( IRQ_MFP_FDC );
728 }
729 
730 
731 
732 #define	SET_IRQ_HANDLER(proc) do { FloppyIRQHandler = (proc); } while(0)
733 
734 
735 /* ---------- Formatting ---------- */
736 
737 #define FILL(n,val)		\
738     do {			\
739 	memset( p, val, n );	\
740 	p += n;			\
741     } while(0)
742 
do_format(int drive,int type,struct atari_format_descr * desc)743 static int do_format(int drive, int type, struct atari_format_descr *desc)
744 {
745 	struct request_queue *q;
746 	unsigned char	*p;
747 	int sect, nsect;
748 	unsigned long	flags;
749 	int ret;
750 
751 	if (type) {
752 		type--;
753 		if (type >= NUM_DISK_MINORS ||
754 		    minor2disktype[type].drive_types > DriveType) {
755 			finish_fdc();
756 			return -EINVAL;
757 		}
758 	}
759 
760 	q = unit[drive].disk[type]->queue;
761 	blk_mq_freeze_queue(q);
762 	blk_mq_quiesce_queue(q);
763 
764 	local_irq_save(flags);
765 	stdma_lock(floppy_irq, NULL);
766 	atari_turnon_irq( IRQ_MFP_FDC ); /* should be already, just to be sure */
767 	local_irq_restore(flags);
768 
769 	if (type) {
770 		type = minor2disktype[type].index;
771 		UDT = &atari_disk_type[type];
772 	}
773 
774 	if (!UDT || desc->track >= UDT->blocks/UDT->spt/2 || desc->head >= 2) {
775 		finish_fdc();
776 		ret = -EINVAL;
777 		goto out;
778 	}
779 
780 	nsect = UDT->spt;
781 	p = TrackBuffer;
782 	/* The track buffer is used for the raw track data, so its
783 	   contents become invalid! */
784 	BufferDrive = -1;
785 	/* stop deselect timer */
786 	del_timer( &motor_off_timer );
787 
788 	FILL( 60 * (nsect / 9), 0x4e );
789 	for( sect = 0; sect < nsect; ++sect ) {
790 		FILL( 12, 0 );
791 		FILL( 3, 0xf5 );
792 		*p++ = 0xfe;
793 		*p++ = desc->track;
794 		*p++ = desc->head;
795 		*p++ = (nsect + sect - desc->sect_offset) % nsect + 1;
796 		*p++ = 2;
797 		*p++ = 0xf7;
798 		FILL( 22, 0x4e );
799 		FILL( 12, 0 );
800 		FILL( 3, 0xf5 );
801 		*p++ = 0xfb;
802 		FILL( 512, 0xe5 );
803 		*p++ = 0xf7;
804 		FILL( 40, 0x4e );
805 	}
806 	FILL( TrackBuffer+BUFFER_SIZE-p, 0x4e );
807 
808 	IsFormatting = 1;
809 	FormatError = 0;
810 	ReqTrack = desc->track;
811 	ReqSide  = desc->head;
812 	do_fd_action( drive );
813 
814 	wait_for_completion(&format_wait);
815 
816 	finish_fdc();
817 	ret = FormatError ? -EIO : 0;
818 out:
819 	blk_mq_unquiesce_queue(q);
820 	blk_mq_unfreeze_queue(q);
821 	return ret;
822 }
823 
824 
825 /* do_fd_action() is the general procedure for a fd request: All
826  * required parameter settings (drive select, side select, track
827  * position) are checked and set if needed. For each of these
828  * parameters and the actual reading or writing exist two functions:
829  * one that starts the setting (or skips it if possible) and one
830  * callback for the "done" interrupt. Each done func calls the next
831  * set function to propagate the request down to fd_rwsec_done().
832  */
833 
do_fd_action(int drive)834 static void do_fd_action( int drive )
835 {
836 	DPRINT(("do_fd_action\n"));
837 
838 	if (UseTrackbuffer && !IsFormatting) {
839 	repeat:
840 	    if (IS_BUFFERED( drive, ReqSide, ReqTrack )) {
841 		if (ReqCmd == READ) {
842 		    copy_buffer( SECTOR_BUFFER(ReqSector), ReqData );
843 		    if (++ReqCnt < blk_rq_cur_sectors(fd_request)) {
844 			/* read next sector */
845 			setup_req_params( drive );
846 			goto repeat;
847 		    }
848 		    else {
849 			/* all sectors finished */
850 			fd_end_request_cur(BLK_STS_OK);
851 			finish_fdc();
852 			return;
853 		    }
854 		}
855 		else {
856 		    /* cmd == WRITE, pay attention to track buffer
857 		     * consistency! */
858 		    copy_buffer( ReqData, SECTOR_BUFFER(ReqSector) );
859 		}
860 	    }
861 	}
862 
863 	if (SelectedDrive != drive)
864 		fd_select_drive( drive );
865 
866 	if (UD.track == -1)
867 		fd_calibrate();
868 	else if (UD.track != ReqTrack << UDT->stretch)
869 		fd_seek();
870 	else if (IsFormatting)
871 		fd_writetrack();
872 	else
873 		fd_rwsec();
874 }
875 
876 
877 /* Seek to track 0 if the current track is unknown */
878 
fd_calibrate(void)879 static void fd_calibrate( void )
880 {
881 	if (SUD.track >= 0) {
882 		fd_calibrate_done( 0 );
883 		return;
884 	}
885 
886 	if (ATARIHW_PRESENT(FDCSPEED))
887 		dma_wd.fdc_speed = 0;   /* always seek with 8 Mhz */
888 	DPRINT(("fd_calibrate\n"));
889 	SET_IRQ_HANDLER( fd_calibrate_done );
890 	/* we can't verify, since the speed may be incorrect */
891 	FDC_WRITE( FDCREG_CMD, FDCCMD_RESTORE | SUD.steprate );
892 
893 	NeedSeek = 1;
894 	MotorOn = 1;
895 	start_timeout();
896 	/* wait for IRQ */
897 }
898 
899 
fd_calibrate_done(int status)900 static void fd_calibrate_done( int status )
901 {
902 	DPRINT(("fd_calibrate_done()\n"));
903 	stop_timeout();
904 
905 	/* set the correct speed now */
906 	if (ATARIHW_PRESENT(FDCSPEED))
907 		dma_wd.fdc_speed = SUDT->fdc_speed;
908 	if (status & FDCSTAT_RECNF) {
909 		printk(KERN_ERR "fd%d: restore failed\n", SelectedDrive );
910 		fd_error();
911 	}
912 	else {
913 		SUD.track = 0;
914 		fd_seek();
915 	}
916 }
917 
918 
919 /* Seek the drive to the requested track. The drive must have been
920  * calibrated at some point before this.
921  */
922 
fd_seek(void)923 static void fd_seek( void )
924 {
925 	if (SUD.track == ReqTrack << SUDT->stretch) {
926 		fd_seek_done( 0 );
927 		return;
928 	}
929 
930 	if (ATARIHW_PRESENT(FDCSPEED)) {
931 		dma_wd.fdc_speed = 0;	/* always seek witch 8 Mhz */
932 		MFPDELAY();
933 	}
934 
935 	DPRINT(("fd_seek() to track %d\n",ReqTrack));
936 	FDC_WRITE( FDCREG_DATA, ReqTrack << SUDT->stretch);
937 	udelay(25);
938 	SET_IRQ_HANDLER( fd_seek_done );
939 	FDC_WRITE( FDCREG_CMD, FDCCMD_SEEK | SUD.steprate );
940 
941 	MotorOn = 1;
942 	set_head_settle_flag();
943 	start_timeout();
944 	/* wait for IRQ */
945 }
946 
947 
fd_seek_done(int status)948 static void fd_seek_done( int status )
949 {
950 	DPRINT(("fd_seek_done()\n"));
951 	stop_timeout();
952 
953 	/* set the correct speed */
954 	if (ATARIHW_PRESENT(FDCSPEED))
955 		dma_wd.fdc_speed = SUDT->fdc_speed;
956 	if (status & FDCSTAT_RECNF) {
957 		printk(KERN_ERR "fd%d: seek error (to track %d)\n",
958 				SelectedDrive, ReqTrack );
959 		/* we don't know exactly which track we are on now! */
960 		SUD.track = -1;
961 		fd_error();
962 	}
963 	else {
964 		SUD.track = ReqTrack << SUDT->stretch;
965 		NeedSeek = 0;
966 		if (IsFormatting)
967 			fd_writetrack();
968 		else
969 			fd_rwsec();
970 	}
971 }
972 
973 
974 /* This does the actual reading/writing after positioning the head
975  * over the correct track.
976  */
977 
978 static int MultReadInProgress = 0;
979 
980 
fd_rwsec(void)981 static void fd_rwsec( void )
982 {
983 	unsigned long paddr, flags;
984 	unsigned int  rwflag, old_motoron;
985 	unsigned int track;
986 
987 	DPRINT(("fd_rwsec(), Sec=%d, Access=%c\n",ReqSector, ReqCmd == WRITE ? 'w' : 'r' ));
988 	if (ReqCmd == WRITE) {
989 		if (ATARIHW_PRESENT(EXTD_DMA)) {
990 			paddr = virt_to_phys(ReqData);
991 		}
992 		else {
993 			copy_buffer( ReqData, DMABuffer );
994 			paddr = PhysDMABuffer;
995 		}
996 		dma_cache_maintenance( paddr, 512, 1 );
997 		rwflag = 0x100;
998 	}
999 	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 
fd_readtrack_check(struct timer_list * unused)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 
fd_rwsec_done(int status)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 
fd_rwsec_done1(int status)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 
fd_writetrack(void)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 
fd_writetrack_done(int status)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 
fd_times_out(struct timer_list * unused)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 
finish_fdc(void)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 
finish_fdc_done(int dummy)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 
floppy_check_events(struct gendisk * disk,unsigned int clearing)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 
floppy_revalidate(struct gendisk * disk)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 
setup_req_params(int drive)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 
ataflop_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)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 
fd_locked_ioctl(struct block_device * bdev,blk_mode_t mode,unsigned int cmd,unsigned long param)1584 static int fd_locked_ioctl(struct block_device *bdev, blk_mode_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 (disk_check_media_change(disk))
1764 			floppy_revalidate(disk);
1765 		return 0;
1766 	default:
1767 		return -EINVAL;
1768 	}
1769 }
1770 
fd_ioctl(struct block_device * bdev,blk_mode_t mode,unsigned int cmd,unsigned long arg)1771 static int fd_ioctl(struct block_device *bdev, blk_mode_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 
fd_probe(int drive)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 
fd_test_drive_present(int drive)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 
config_types(void)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 
floppy_open(struct gendisk * disk,blk_mode_t mode)1918 static int floppy_open(struct gendisk *disk, blk_mode_t mode)
1919 {
1920 	struct atari_floppy_struct *p = disk->private_data;
1921 	int type = disk->first_minor >> 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 & BLK_OPEN_EXCL))
1928 		return -EBUSY;
1929 	if (mode & BLK_OPEN_EXCL)
1930 		p->ref = -1;
1931 	else
1932 		p->ref++;
1933 
1934 	p->type = type;
1935 
1936 	if (mode & BLK_OPEN_NDELAY)
1937 		return 0;
1938 
1939 	if (mode & (BLK_OPEN_READ | BLK_OPEN_WRITE)) {
1940 		if (disk_check_media_change(disk))
1941 			floppy_revalidate(disk);
1942 		if (mode & BLK_OPEN_WRITE) {
1943 			if (p->wpstat) {
1944 				if (p->ref < 0)
1945 					p->ref = 0;
1946 				else
1947 					p->ref--;
1948 				return -EROFS;
1949 			}
1950 		}
1951 	}
1952 	return 0;
1953 }
1954 
floppy_unlocked_open(struct gendisk * disk,blk_mode_t mode)1955 static int floppy_unlocked_open(struct gendisk *disk, blk_mode_t mode)
1956 {
1957 	int ret;
1958 
1959 	mutex_lock(&ataflop_mutex);
1960 	ret = floppy_open(disk, mode);
1961 	mutex_unlock(&ataflop_mutex);
1962 
1963 	return ret;
1964 }
1965 
floppy_release(struct gendisk * disk)1966 static void floppy_release(struct gendisk *disk)
1967 {
1968 	struct atari_floppy_struct *p = disk->private_data;
1969 	mutex_lock(&ataflop_mutex);
1970 	if (p->ref < 0)
1971 		p->ref = 0;
1972 	else if (!p->ref--) {
1973 		printk(KERN_ERR "floppy_release with fd_ref == 0");
1974 		p->ref = 0;
1975 	}
1976 	mutex_unlock(&ataflop_mutex);
1977 }
1978 
1979 static const struct block_device_operations floppy_fops = {
1980 	.owner		= THIS_MODULE,
1981 	.open		= floppy_unlocked_open,
1982 	.release	= floppy_release,
1983 	.ioctl		= fd_ioctl,
1984 	.check_events	= floppy_check_events,
1985 };
1986 
1987 static const struct blk_mq_ops ataflop_mq_ops = {
1988 	.queue_rq = ataflop_queue_rq,
1989 };
1990 
ataflop_alloc_disk(unsigned int drive,unsigned int type)1991 static int ataflop_alloc_disk(unsigned int drive, unsigned int type)
1992 {
1993 	struct gendisk *disk;
1994 
1995 	disk = blk_mq_alloc_disk(&unit[drive].tag_set, NULL);
1996 	if (IS_ERR(disk))
1997 		return PTR_ERR(disk);
1998 
1999 	disk->major = FLOPPY_MAJOR;
2000 	disk->first_minor = drive + (type << 2);
2001 	disk->minors = 1;
2002 	sprintf(disk->disk_name, "fd%d", drive);
2003 	disk->fops = &floppy_fops;
2004 	disk->flags |= GENHD_FL_NO_PART;
2005 	disk->events = DISK_EVENT_MEDIA_CHANGE;
2006 	disk->private_data = &unit[drive];
2007 	set_capacity(disk, MAX_DISK_SIZE * 2);
2008 
2009 	unit[drive].disk[type] = disk;
2010 	return 0;
2011 }
2012 
ataflop_probe(dev_t dev)2013 static void ataflop_probe(dev_t dev)
2014 {
2015 	int drive = MINOR(dev) & 3;
2016 	int type  = MINOR(dev) >> 2;
2017 
2018 	if (type)
2019 		type--;
2020 
2021 	if (drive >= FD_MAX_UNITS || type >= NUM_DISK_MINORS)
2022 		return;
2023 	if (unit[drive].disk[type])
2024 		return;
2025 	if (ataflop_alloc_disk(drive, type))
2026 		return;
2027 	if (add_disk(unit[drive].disk[type]))
2028 		goto cleanup_disk;
2029 	unit[drive].registered[type] = true;
2030 	return;
2031 
2032 cleanup_disk:
2033 	put_disk(unit[drive].disk[type]);
2034 	unit[drive].disk[type] = NULL;
2035 }
2036 
atari_floppy_cleanup(void)2037 static void atari_floppy_cleanup(void)
2038 {
2039 	int i;
2040 	int type;
2041 
2042 	for (i = 0; i < FD_MAX_UNITS; i++) {
2043 		for (type = 0; type < NUM_DISK_MINORS; type++) {
2044 			if (!unit[i].disk[type])
2045 				continue;
2046 			del_gendisk(unit[i].disk[type]);
2047 			put_disk(unit[i].disk[type]);
2048 		}
2049 		blk_mq_free_tag_set(&unit[i].tag_set);
2050 	}
2051 
2052 	del_timer_sync(&fd_timer);
2053 	atari_stram_free(DMABuffer);
2054 }
2055 
atari_cleanup_floppy_disk(struct atari_floppy_struct * fs)2056 static void atari_cleanup_floppy_disk(struct atari_floppy_struct *fs)
2057 {
2058 	int type;
2059 
2060 	for (type = 0; type < NUM_DISK_MINORS; type++) {
2061 		if (!fs->disk[type])
2062 			continue;
2063 		if (fs->registered[type])
2064 			del_gendisk(fs->disk[type]);
2065 		put_disk(fs->disk[type]);
2066 	}
2067 	blk_mq_free_tag_set(&fs->tag_set);
2068 }
2069 
atari_floppy_init(void)2070 static int __init atari_floppy_init (void)
2071 {
2072 	int i;
2073 	int ret;
2074 
2075 	if (!MACH_IS_ATARI)
2076 		/* Amiga, Mac, ... don't have Atari-compatible floppy :-) */
2077 		return -ENODEV;
2078 
2079 	for (i = 0; i < FD_MAX_UNITS; i++) {
2080 		memset(&unit[i].tag_set, 0, sizeof(unit[i].tag_set));
2081 		unit[i].tag_set.ops = &ataflop_mq_ops;
2082 		unit[i].tag_set.nr_hw_queues = 1;
2083 		unit[i].tag_set.nr_maps = 1;
2084 		unit[i].tag_set.queue_depth = 2;
2085 		unit[i].tag_set.numa_node = NUMA_NO_NODE;
2086 		unit[i].tag_set.flags = BLK_MQ_F_SHOULD_MERGE;
2087 		ret = blk_mq_alloc_tag_set(&unit[i].tag_set);
2088 		if (ret)
2089 			goto err;
2090 
2091 		ret = ataflop_alloc_disk(i, 0);
2092 		if (ret) {
2093 			blk_mq_free_tag_set(&unit[i].tag_set);
2094 			goto err;
2095 		}
2096 	}
2097 
2098 	if (UseTrackbuffer < 0)
2099 		/* not set by user -> use default: for now, we turn
2100 		   track buffering off for all Medusas, though it
2101 		   could be used with ones that have a counter
2102 		   card. But the test is too hard :-( */
2103 		UseTrackbuffer = !MACH_IS_MEDUSA;
2104 
2105 	/* initialize variables */
2106 	SelectedDrive = -1;
2107 	BufferDrive = -1;
2108 
2109 	DMABuffer = atari_stram_alloc(BUFFER_SIZE+512, "ataflop");
2110 	if (!DMABuffer) {
2111 		printk(KERN_ERR "atari_floppy_init: cannot get dma buffer\n");
2112 		ret = -ENOMEM;
2113 		goto err;
2114 	}
2115 	TrackBuffer = DMABuffer + 512;
2116 	PhysDMABuffer = atari_stram_to_phys(DMABuffer);
2117 	PhysTrackBuffer = virt_to_phys(TrackBuffer);
2118 	BufferDrive = BufferSide = BufferTrack = -1;
2119 
2120 	for (i = 0; i < FD_MAX_UNITS; i++) {
2121 		unit[i].track = -1;
2122 		unit[i].flags = 0;
2123 		ret = add_disk(unit[i].disk[0]);
2124 		if (ret)
2125 			goto err_out_dma;
2126 		unit[i].registered[0] = true;
2127 	}
2128 
2129 	printk(KERN_INFO "Atari floppy driver: max. %cD, %strack buffering\n",
2130 	       DriveType == 0 ? 'D' : DriveType == 1 ? 'H' : 'E',
2131 	       UseTrackbuffer ? "" : "no ");
2132 	config_types();
2133 
2134 	ret = __register_blkdev(FLOPPY_MAJOR, "fd", ataflop_probe);
2135 	if (ret) {
2136 		printk(KERN_ERR "atari_floppy_init: cannot register block device\n");
2137 		atari_floppy_cleanup();
2138 	}
2139 	return ret;
2140 
2141 err_out_dma:
2142 	atari_stram_free(DMABuffer);
2143 err:
2144 	while (--i >= 0)
2145 		atari_cleanup_floppy_disk(&unit[i]);
2146 
2147 	return ret;
2148 }
2149 
2150 #ifndef MODULE
atari_floppy_setup(char * str)2151 static int __init atari_floppy_setup(char *str)
2152 {
2153 	int ints[3 + FD_MAX_UNITS];
2154 	int i;
2155 
2156 	if (!MACH_IS_ATARI)
2157 		return 0;
2158 
2159 	str = get_options(str, 3 + FD_MAX_UNITS, ints);
2160 
2161 	if (ints[0] < 1) {
2162 		printk(KERN_ERR "ataflop_setup: no arguments!\n" );
2163 		return 0;
2164 	}
2165 	else if (ints[0] > 2+FD_MAX_UNITS) {
2166 		printk(KERN_ERR "ataflop_setup: too many arguments\n" );
2167 	}
2168 
2169 	if (ints[1] < 0 || ints[1] > 2)
2170 		printk(KERN_ERR "ataflop_setup: bad drive type\n" );
2171 	else
2172 		DriveType = ints[1];
2173 
2174 	if (ints[0] >= 2)
2175 		UseTrackbuffer = (ints[2] > 0);
2176 
2177 	for( i = 3; i <= ints[0] && i-3 < FD_MAX_UNITS; ++i ) {
2178 		if (ints[i] != 2 && ints[i] != 3 && ints[i] != 6 && ints[i] != 12)
2179 			printk(KERN_ERR "ataflop_setup: bad steprate\n" );
2180 		else
2181 			UserSteprate[i-3] = ints[i];
2182 	}
2183 	return 1;
2184 }
2185 
2186 __setup("floppy=", atari_floppy_setup);
2187 #endif
2188 
atari_floppy_exit(void)2189 static void __exit atari_floppy_exit(void)
2190 {
2191 	unregister_blkdev(FLOPPY_MAJOR, "fd");
2192 	atari_floppy_cleanup();
2193 }
2194 
2195 module_init(atari_floppy_init)
2196 module_exit(atari_floppy_exit)
2197 
2198 MODULE_LICENSE("GPL");
2199